Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Brains that serve several people refuse reads from unbound connections after a 14-day grace (GST-363)
garrytande65c59d96c5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 927b2836bc..28eab72e36 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,32 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++### A brain that serves several people refuses reads from connections bound to nobody++**On a brain that serves several people, a token, OAuth client or stdio server bound to no member can no longer read every unmarked page for whoever is asking.** After a 14-day grace for connections that already existed, such a read is refused with `requester_scope_required` and nothing is read. A brain serves several people when two or more members are enabled, or when config `access.serves` is `several`. A brain pinned `access.serves one` never refuses, however many members it has, and a credential bound to a member, the owner's included, reads exactly what it read before. Everything is database state, so repo-less and keyless brains get the same refusal and the same grace with no new config.++| Connection | Before | Now, on a brain that serves several people |+|---|---|---|+| Bound to a member (`--member`, the owner included), naming an audience per call (`--may-act-for`), or attested | reads as that person | unchanged |+| Bound to nobody, existed when the brain started serving several people | read every page no rule restricts | reads for 14 more days, each answer carrying `_meta.access.requester_scope` with the date and the fix; then refused |+| Bound to nobody, created later | read every page no rule restricts | refused at once (`requester_scope_required`, reason `created_after`) |+| Marked `--reads-unscoped --yes` by the operator | (no such mark) | reads as before, on purpose, audited |+| Any connection on a one-person brain, or the local CLI | unchanged | unchanged |++### Itemized changes++- `src/core/access/requester-scope.ts` (new): the gate, run in `dispatchToolCall` after access resolves and in every agent job tool call. Every read op and every read-scope op (`think` included) is gated unless it reads no page: `whoami`, `get_brain_identity`, `get_status_snapshot`, `search_modes`, `get_health`, the caller's own `join_brain` / `leave_brain` / `sync_brain_skills` / `request_tools`, and a non-admin credential's own `get_job` / `wait_job`. When the serves policy cannot be read it is read once more, and a second failure refuses retryably (`requester_scope_unknown`) rather than reading as one person; a bound credential is never refused that way.+- Migration v308 (number assigned at the merge slot): `reads_unscoped` on `access_tokens` and `oauth_clients`, and a trigger that keeps config `access.serves_derived` and sets `access.serves_since` once, the first time the brain serves several people, so a request reads both from its config snapshot. Disabling and re-enabling a member does not restart the grace. Nothing else is rewritten.+- `gbrain auth create`, `gbrain auth register-client` and the admin dashboard's key mint refuse an unbound credential on such a brain (`credential_scope_required`). `gbrain auth rescope ... --reads-unscoped --yes` (`none` removes it) is the explicit opt-out, written to the `access-reads-unscoped` audit file; `gbrain access check` reports it.+- The fix every refusal, notice, `whoami` note and `gbrain access owner` hint gives for stdio is the per-harness binding, `gbrain setup claude-code|codex --stdio-member <id>`, on PGLite and Postgres alike, or a per-person key over `gbrain serve --http` for a harness several people talk to. Nothing suggests `config set mcp.stdio_member`, and no upgrade, doctor or setup path writes it.+- Doctor: `unscoped_shared_reads` fails per unbound credential with its state, grace end and bind command (warns while `access.requester_scope_enforce` is false); `shared_stdio_binding` fails when `mcp.stdio_member` is set on a host where OpenClaw or Hermes is installed, with `gbrain config unset mcp.stdio_member` as its ask-first fix. `gbrain post-upgrade` lists the unbound credentials.+- `src/commands/setup-serves.ts`: a `hermes` on PATH counts as the Hermes agent only when it is a script, so React Native's compiled `hermes` engine no longer makes setup refuse `--stdio-member` or doctor fail `shared_stdio_binding`.+- Hosted brains keep `access.requester_scope_enforce false` until their control plane binds each connection; every unbound read then answers with the notice and nothing is refused.+- Docs: `docs/guides/write-refusals.md` (the three codes), `docs/guides/setup.md`, `docs/guides/multi-source-brains.md`, `docs/tutorials/company-brain.md`, `docs/architecture/key-files/access.md`; a behaviour-change notice row explains the change on upgrade.+- Tests: `test/requester-scope.test.ts` (PGLite and Postgres, repo-less and a repo brain: the refusal, the grace, the pinned one-person brain and the owner-bound key unchanged, every gated op refused before its handler, the hosted switch, agent jobs, the CLI), `test/shared-stdio-binding.test.ts`.+## [0.60.699.0] - 2026-11-12### The Ubicloud gate VMs run a current gitdiff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.mdindex 1c7cb22888..714e4729cc 100644--- a/docs/architecture/key-files/access.md+++ b/docs/architecture/key-files/access.md@@ -5,7 +5,9 @@ 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). 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`). A 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`. 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`) is `person`, and handlers read the mode with `currentReadMode`. `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/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 2+ enabled members) 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).+- `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 v308'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).- `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 v308'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/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; fix `gbrain config unset mcp.stdio_member`. 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`). 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` 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` (CLI subprocesses, both engines, repo-less and git), `test/enforced-member-classes.test.ts` (every command and operation classified once).diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.mdindex 9012232caa..e349989455 100644--- a/docs/architecture/key-files/core-minions-2.md+++ b/docs/architecture/key-files/core-minions-2.md@@ -30,7 +30,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/sync-queue-wake.ts` — GBRA-133 2a.4: wakes an idle `gbrain jobs work` claim loop when a `sync` job turns `waiting` in its queue. `chooseSyncQueueWake(engine, env)` picks `listen` only on a detected direct session (the engine's dual-pool direct route, or a pool whose `prepare` is not off, read through `consumerConnectionRoute` in persistence/consumer-lane.ts), `poll` behind a transaction pooler or an unknown pooler mode, `off` on PGLite or with `GBRAIN_WORKER_SYNC_WAKE=0`. `startSyncQueueWake` LISTENs on the `minion_jobs` channel (the schema's `notify_minion_job_change` trigger) and requires a probe NOTIFY to arrive within 3 s, else it polls; the poll reads one `minion_jobs` row every `GBRAIN_WORKER_SYNC_WAKE_POLL_MS` (default 1 s, 250 ms-5 s) only while the worker is idle. It logs one line naming the mode and never throws; the worker's own poll stays the backstop. Tests: `test/pathological/s-sync-queue-wake.test.ts` + `test/e2e/s-sync-queue-wake-postgres.test.ts` (listed in `scripts/e2e-backend-matrix.txt`, so it also runs through PgBouncer).- `src/core/minions/tool-write-identity.ts` — Binds a journal mutation to the persisted subagent execution coordinates with a deterministic UUIDv8 before dispatch. Legacy, gateway and oneshot replay preserve the same logical request across process restart; explicit caller IDs remain authoritative. `awaitCommittedToolWrite(job, toolName, dispatch)` wraps every subagent tool dispatch (legacy loop and resume, gateway execute and resume reconciliation, oneshot write loop and recovery): while the write is admitted but still pending it replays the same request ID through `replayWhilePending` (no model call, nothing new admitted) until the write is terminal, the job's signal aborts (the pause ends and the last pending error, receipt included, is rethrown), or the job deadline is closer than `WIRE_WRITE_WAIT_MAX_MS` plus `WRITE_ADMISSION_HEADROOM_MS` (45 s); a job without a deadline replays for the `MaintenanceWriteWait` base (30 s). Only then does the write leave the handler as `write_pending`, so a write that never commits holds the job (and a serial dream drain behind it) until that point. A terminal `failed` receipt and non-mutation tools are never replayed. Pending receipts leave tool ledgers pending for retry and never count as written pages. Pinned by `test/subagent-handler.test.ts`, `test/minions/subagent-pending-write-runners.test.ts`, `test/minions/subagent-oneshot.test.ts` and `test/e2e/subagent-gateway-resume-reconciliation.test.ts`.-- `src/core/minions/tools/brain-allowlist.ts` — derives the subagent tool registry from `src/core/operations.ts` (13-name allow-list in the handler-free `brain-tool-allowlist.ts`, which `src/mcp/surface.ts` reads, size pinned by `test/brain-allowlist.test.ts`). Attachment tools `file_list` and `file_url` are excluded. Registry construction and execution reject every `localOnly` operation; `selectAllowedTools` rejects malformed bindings and preserves explicit empty lists as no tools. Includes `add_timeline_entry` (the canonical timeline write), fenced server-side by the same `enforceSubagentSlugFence` policy as `put_page`. By default `put_page` schema is namespace-wrapped per subagent (`^wiki/agents/<subagentId>/.+`). When `BuildBrainToolsOpts.allowedSlugPrefixes` is set, the put_page schema describes the prefix list to the model and the OperationContext is threaded with `allowedSlugPrefixes` — trusted local jobs receive these from the submitter; remote-owned jobs receive the grant intersection plus `delegatedAuth`. Their per-call operation contexts carry the verified OAuth owner principal and current operation/source grant intersection into durable requests, and retain remote visibility policy, without requiring direct read/write scopes for independently bound delegated tools. `BuildBrainToolsOpts.deferEmbeds` (server-side-only, set by the oneshot runner for its programmatic writes; never hydrated from any wire payload) threads `OperationContext.deferEmbeds` so put_page defers chunk embeddings for the phase-end backfill. Allow-list includes `get_recent_salience` + `find_anomalies` but deliberately NOT `get_recent_transcripts` (all subagent calls run `ctx.remote === true` and the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase calls `discoverTranscripts` directly instead). `paramsToInputSchema()` consumes `paramDefToSchema` from `src/mcp/tool-defs.ts`; required-aggregation at the tool-def level stays here (the shared helper is per-param). `execute()` runs the same `validateParams` the MCP dispatchers use before the op handler, so a call that omits a required parameter (or sends the wrong type / an unknown enum value) fails with `<tool>: Missing required parameter: <name>` the model can act on, instead of a handler crash. `putPageRejection` classifies legacy rejected import envelopes for subagent accounting; actual persistence errors keep the typed receipt contract. Scoped model-authored type normalization is performed by `persistence/page-input.ts` only after durable existing-request lookup, so registry execution never rewrites a replay using a newer schema pack. #6297: a subagent `get_page` with `include_content: true` is forced to `content_only: true`, so the body arrives once (as `content`) instead of also as parsed `compiled_truth`/`timeline`. `BuildBrainToolsOpts.readBudgetBytes` (from trusted `SubagentHandlerData.read_budget_bytes`) routes `get_page` results through `read-budget.ts`. #6779: a subagent `put_page` refused `revision_required` names the page's current revision (`rethrowWithCurrentRevision` in `put-page-result.ts`); MCP and CLI callers keep the bare refusal.+- `src/core/minions/tools/brain-allowlist.ts` — derives the subagent tool registry from `src/core/operations.ts` (13-name allow-list in the handler-free `brain-tool-allowlist.ts`, which `src/mcp/surface.ts` reads, size pinned by `test/brain-allowlist.test.ts`). Attachment tools `file_list` and `file_url` are excluded. Registry construction and execution reject every `localOnly` operation; `selectAllowedTools` rejects malformed bindings and preserves explicit empty lists as no tools. Includes `add_timeline_entry` (the canonical timeline write), fenced server-side by the same `enforceSubagentSlugFence` policy as `put_page`. By default `put_page` schema is namespace-wrapped per subagent (`^wiki/agents/<subagentId>/.+`). When `BuildBrainToolsOpts.allowedSlugPrefixes` is set, the put_page schema describes the prefix list to the model and the OperationContext is threaded with `allowedSlugPrefixes` — trusted local jobs receive these from the submitter; remote-owned jobs receive the grant intersection plus `delegatedAuth`. Their per-call operation contexts carry the verified OAuth owner principal and current operation/source grant intersection into durable requests, and retain remote visibility policy, without requiring direct read/write scopes for independently bound delegated tools. `BuildBrainToolsOpts.deferEmbeds` (server-side-only, set by the oneshot runner for its programmatic writes; never hydrated from any wire payload) threads `OperationContext.deferEmbeds` so put_page defers chunk embeddings for the phase-end backfill. Allow-list includes `get_recent_salience` + `find_anomalies` but deliberately NOT `get_recent_transcripts` (all subagent calls run `ctx.remote === true` and the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase calls `discoverTranscripts` directly instead). `paramsToInputSchema()` consumes `paramDefToSchema` from `src/mcp/tool-defs.ts`; required-aggregation at the tool-def level stays here (the shared helper is per-param). `execute()` runs the same `validateParams` the MCP dispatchers use before the op handler, so a call that omits a required parameter (or sends the wrong type / an unknown enum value) fails with `<tool>: Missing required parameter: <name>` the model can act on, instead of a handler crash. `putPageRejection` classifies legacy rejected import envelopes for subagent accounting; actual persistence errors keep the typed receipt contract. Scoped model-authored type normalization is performed by `persistence/page-input.ts` only after durable existing-request lookup, so registry execution never rewrites a replay using a newer schema pack. #6297: a subagent `get_page` with `include_content: true` is forced to `content_only: true`, so the body arrives once (as `content`) instead of also as parsed `compiled_truth`/`timeline`. `BuildBrainToolsOpts.readBudgetBytes` (from trusted `SubagentHandlerData.read_budget_bytes`) routes `get_page` results through `read-budget.ts`. #6779: a subagent `put_page` refused `revision_required` names the page's current revision (`rethrowWithCurrentRevision` in `put-page-result.ts`); MCP and CLI callers keep the bare refusal. A remote-owned job tool call runs the same requester-scope gate as dispatch (`scopedJobAccess`), read live per call.- `src/core/minions/tools/read-budget.ts` — #6297 per-job `get_page` byte budget: `budgetedPageRead` counts bytes already returned from the job's `subagent_tool_executions` rows (`brain_get_page`, `complete`), so a replayed job keeps its spend, and past the budget returns a summary (`truncated: true`, `code: read_budget_exhausted`, slug/title/type, the `revision` (#6779, so a child can still append or skip), a bounded prefix of the result's rendered `content`/`text` of at most `READ_BUDGET_EXCERPT_BYTES`; sizes are result bytes, never a body read, so segmented pages need no body string) instead of the page.- `src/core/minions/transcript.ts` — renders `subagent_messages` + `subagent_tool_executions` to markdown. Tool rows splice under their owning assistant `tool_use` by `(message_idx, tool_use_id)` — raw provider tool ids may repeat across turns, so `tool_use_id` alone is not an identity; echoed `tool_result` blocks check ownership against the nearest preceding assistant turn's key. UTF-8-safe truncation; unknown block types fall through to fenced JSON.diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.mdindex c1bbc313c2..9f10be08d6 100644--- a/docs/architecture/key-files/mcp.md+++ b/docs/architecture/key-files/mcp.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)` (a read op (`mutating === false`) runs inside `withRequestConfigSnapshot`, a write op under `withoutRequestConfigSnapshot`; `src/core/config-snapshot.ts`), `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts`; for a read op on a live engine it runs beside the handler instead of after it (GBRA-156), and reads its withdrawal watermark and trust generation in one round trip — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash + eligibility + the `sessionOnly` scope (a session with no facts of its own falls back to the source's newest 24h facts unless the caller passes `sessionOnly`, which the IPC handlers do when `context.hot_memory.session_only` is on; MCP callers never pass it), so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served, the key folds the effective read eligibility and each hit revalidates the trust policy generation (`src/core/eligibility/generation.ts`, migration v230: deferred triggers bump `trust_policy_state` on tier changes, quarantine transitions, read floor and `trust.%` config changes, purges and `needs_rederive`), read before the rows; an unreadable generation delivers nothing; facts read through the `hot_memory` proactive eligibility and `partitionForActivation`, carry `trust_tier` and `origin`, and the payload's `suppressed` counts what activation control withheld), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` marks a saved fact that carries `corrected_by` with "corrected by a newer saved fact above" in its bracket and caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope. `sessionSafetyNotices` adds the one-time `behavior_changes` disclosure (stdio: once per brain; HTTP: once per authenticated client, remote view) and, on stdio only, the queued `chat_fallback_hop` notice, on success and failure results alike. `requestMetaSessionId(request.params)` is the one reader of the request-level `_meta.session_id` (beside `arguments`); stdio (`server.ts`) and HTTP (`serve-http-mcp.ts`) both pass it as `opts.sessionId`, which wins over an arguments-level `_meta` and is clamped to `SESSION_ID_MAX_CHARS` (256). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`). Large pages: after a read's result is assembled (notices and `_meta` included), `frameOverCap` measures the final encoded frame against the connection's cap and replaces an oversized read with `result_too_large` (writes are never replaced); `DispatchOpts.thinClient` (from `X-Gbrain-Client` on both HTTP transports) reaches `OperationContext.thinClient`, a default-body-mode hint, never authority. GBRA-156: `hotMemoryOffIn(params)` reads `_meta.hot_memory: "off"`. Both transports pass the request-level value as `opts.hotMemoryOff`, and dispatch also reads it from the arguments' `_meta`. Either one skips the `metaHook` for that call, so the response carries no `brain_hot_memory` (`test/mcp-hot-memory-opt-out.test.ts`). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`). Large pages: after a read's result is assembled (notices and `_meta` included), `frameOverCap` measures the final encoded frame against the connection's cap and replaces an oversized read with `result_too_large` (writes are never replaced); `DispatchOpts.thinClient` (from `X-Gbrain-Client` on both HTTP transports) reaches `OperationContext.thinClient`, a default-body-mode hint, never authority. GBRA-156: a remote non-mutating op runs inside `withPrivateReadableSources(auth.privatePages.sources)`; writes, local calls and `context_pack` / `delta` (`WORLD_ONLY_PACK_OPS`) run with an empty set. GST-359 C1: `opts.actor` carries the `x-qm-actor` header from both HTTP transports (stdio never attests); `resolveAttestedActor` (`src/core/access/actor.ts`) decides before any work, and `actorRefusal` returns its refusals with `structuredContent.error` beside the JSON text block, the one seam where layer D's `memory_recall` will answer `actor_unlinked` as empty content plus `structuredContent {facts: [], truncated: false, code: 'actor_unlinked'}`. Every MCP server's `serverInfo.description` is `MCP_SERVER_DESCRIPTION` (`instructions.ts`, at most 120 characters); `instructions` are unchanged. `asAgentToolError(e, op, ctx, allowedOps)` renders a failed read as the error text an HTTP read-scope MCP caller gets for the same call (code, message, suggestion, `fix` limited to `allowedOps`) for SkillOpt's tool loops, which throw it with `code` kept; an AI invocation policy stop passes through unchanged.+- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)` (a read op (`mutating === false`) runs inside `withRequestConfigSnapshot`, a write op under `withoutRequestConfigSnapshot`; `src/core/config-snapshot.ts`), `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts`; for a read op on a live engine it runs beside the handler instead of after it (GBRA-156), and reads its withdrawal watermark and trust generation in one round trip — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash + eligibility + the `sessionOnly` scope (a session with no facts of its own falls back to the source's newest 24h facts unless the caller passes `sessionOnly`, which the IPC handlers do when `context.hot_memory.session_only` is on; MCP callers never pass it), so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served, the key folds the effective read eligibility and each hit revalidates the trust policy generation (`src/core/eligibility/generation.ts`, migration v230: deferred triggers bump `trust_policy_state` on tier changes, quarantine transitions, read floor and `trust.%` config changes, purges and `needs_rederive`), read before the rows; an unreadable generation delivers nothing; facts read through the `hot_memory` proactive eligibility and `partitionForActivation`, carry `trust_tier` and `origin`, and the payload's `suppressed` counts what activation control withheld), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` marks a saved fact that carries `corrected_by` with "corrected by a newer saved fact above" in its bracket and caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope. `sessionSafetyNotices` adds the one-time `behavior_changes` disclosure (stdio: once per brain; HTTP: once per authenticated client, remote view) and, on stdio only, the queued `chat_fallback_hop` notice, on success and failure results alike. `requestMetaSessionId(request.params)` is the one reader of the request-level `_meta.session_id` (beside `arguments`); stdio (`server.ts`) and HTTP (`serve-http-mcp.ts`) both pass it as `opts.sessionId`, which wins over an arguments-level `_meta` and is clamped to `SESSION_ID_MAX_CHARS` (256). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`). Large pages: after a read's result is assembled (notices and `_meta` included), `frameOverCap` measures the final encoded frame against the connection's cap and replaces an oversized read with `result_too_large` (writes are never replaced); `DispatchOpts.thinClient` (from `X-Gbrain-Client` on both HTTP transports) reaches `OperationContext.thinClient`, a default-body-mode hint, never authority. GBRA-156: `hotMemoryOffIn(params)` reads `_meta.hot_memory: "off"`. Both transports pass the request-level value as `opts.hotMemoryOff`, and dispatch also reads it from the arguments' `_meta`. Either one skips the `metaHook` for that call, so the response carries no `brain_hot_memory` (`test/mcp-hot-memory-opt-out.test.ts`). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`). Large pages: after a read's result is assembled (notices and `_meta` included), `frameOverCap` measures the final encoded frame against the connection's cap and replaces an oversized read with `result_too_large` (writes are never replaced); `DispatchOpts.thinClient` (from `X-Gbrain-Client` on both HTTP transports) reaches `OperationContext.thinClient`, a default-body-mode hint, never authority. GBRA-156: a remote non-mutating op runs inside `withPrivateReadableSources(auth.privatePages.sources)`; writes, local calls and `context_pack` / `delta` (`WORLD_ONLY_PACK_OPS`) run with an empty set. GST-359 C1: `opts.actor` carries the `x-qm-actor` header from both HTTP transports (stdio never attests); `resolveAttestedActor` (`src/core/access/actor.ts`) decides before any work, and `actorRefusal` returns its refusals with `structuredContent.error` beside the JSON text block, the one seam where layer D's `memory_recall` will answer `actor_unlinked` as empty content plus `structuredContent {facts: [], truncated: false, code: 'actor_unlinked'}`. Every MCP server's `serverInfo.description` is `MCP_SERVER_DESCRIPTION` (`instructions.ts`, at most 120 characters); `instructions` are unchanged. `asAgentToolError(e, op, ctx, allowedOps)` renders a failed read as the error text an HTTP read-scope MCP caller gets for the same call (code, message, suggestion, `fix` limited to `allowedOps`) for SkillOpt's tool loops, which throw it with `code` kept; an AI invocation policy stop passes through unchanged. On a remote read it runs the requester-scope gate (`src/core/access/requester-scope.ts`) right after access resolves: refusals come back structured with `structuredContent.error`, grace notices in `_meta.access.requester_scope`.- `src/core/egress-budget.ts` — the per-connection result cap: `resultByteCap` (Infinity for the trusted local CLI; else `mcp.max_result_bytes_stdio` 4 MiB / `mcp.max_result_bytes_http` 1 MiB, DB plane then file plane, clamped to 256 KiB–9 MiB), `encodedFrameBytes` (the complete JSON-RPC frame plus a framing reserve), and the dispatcher backstop pair `frameOverCap` / `resultTooLargeError`.- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract, compile-time source text (no runtime filesystem dependency) shared by the stdio SDK server, the OAuth HTTP SDK server and the legacy raw HTTP initialize path. `buildMcpInstructions({writeback?, tools?})` GENERATES the contract from the caller's callable set (`tools.callable`, the tools/list predicate): a clause naming a tool (search/query/get_page, skills catalog, put_page, whoami, join/sync skills, put/delete skill, the memory loop's `context_pack`/`volunteer_context`/`remember`/`forget`) appears only when that tool is listed, so every tool named is in that surface's tools/list (`test/mcp-initialize-instructions.test.ts`). When callable tools are left out of the listed set (`hiddenCallable`) and `request_tools` is callable, the hidden-tool sentence leads the contract, inside the 2,048 characters capped harnesses read (D1). It always carries the error protocol (follow `fix.next`, then `fix.verify`) and the notice prefix, then the optional status-only line (F4), the opt-in ambient-writeback section (`src/core/facts/writeback-instructions.ts`) and the readiness tail (top two `missing`/`degraded` gaps among embeddings, chat_llm, migrations, worker — never a by-choice state). With no `tools` and no writeback it equals `GBRAIN_MCP_INSTRUCTIONS` (the every-tool rendering bootstrap writes to GBRAIN-INSTRUCTIONS.md). `resolveMcpInstructions(config, env?, opts)` appends the operator-set deployment identity LAST under `Deployment identity:` (`GBRAIN_MCP_INSTRUCTIONS` env when non-blank, else file-plane `mcp.instructions`). `installInstructionsResolver(server, compute)` swaps the SDK Server's initialize handler so the stdio and OAuth servers compute the contract (callable set + readiness tail via `src/mcp/initialize-context.ts`) when the client initializes; the constructor value stays the fallback on a throw. The legacy bearer transport builds it inline per initialize. Transport tests compare against the contract for that connection's own tools/list (`test/helpers/instructions-parity.ts`): `test/serve-stdio-roundtrip.test.ts`, `test/http-transport.test.ts`, `test/connect-bearer.test.ts`, `test/mcp-instructions-writeback.test.ts`; identity composition in `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`. #6170: `contractClauses(c, writeback)` puts the short `Ambient writeback is ON (<mode>)` line (with `visibility "private"` under a private posture) in the memory clause when writeback is on, follows the data-not-instructions clause with the shortened error protocol and moves the forget caveat after the scope clause, so the writeback line, `Follow \`fix.next\``, `[gbrain notice`, `context_pack`, `put_page REPLACES` and `Writing:` end inside the first 2,048 characters on every surface (pinned per surface × mode × extract_facts × visibility in `test/mcp-initialize-instructions.test.ts`); the full writeback section stays appended last. Cat 40's measured "Answering from the brain" clause is verbatim; the change needs the D12 Cat 40 smoke before merge. The brief clause puts the `referenced_by` walk on the single-name `entity` card and names only the fields compact `names` rows carry on the brain (`references: {namesRow, records}`, read at every per-initialize call site by `readInstructionContent` from `src/core/entity-references-config.ts`; the static contract is the defaults rendering; `test/mcp-instructions-references.test.ts`). Instruction 7's governing rule (`mcp.instructions_governing_rule`: `in_effect` default, `newest` the earlier recency sentence) leads the answering clause so it ends inside the first 2,048 characters (`test/mcp-instructions-governing-rule.test.ts` records its offset per surface).diff --git a/docs/architecture/thin-client.md b/docs/architecture/thin-client.mdindex 61685d538b..36cf550085 100644--- a/docs/architecture/thin-client.md+++ b/docs/architecture/thin-client.md@@ -17,6 +17,18 @@ to host authorization. Local PGLite launchers retain their host/source binding.The generic `gbrain call` dispatcher is host-only and refuses before opening alocal engine; use the named CLI command or an authorized MCP tool instead.+**Requester scope:** on a host brain that serves several people (two or more+enabled members, or `access.serves = several`), every remote read op except the+identity and health calls (`src/core/access/requester-scope.ts`) must come from a+connection bound to a member, naming an audience, or attested; a thin client's+unbound OAuth client is refused `requester_scope_required` with a host-side fix+(`gbrain auth rescope --client <id> --member <id>`), after a 14-day grace for+clients older than the brain's `access.serves_since`. The gate runs in+`dispatchToolCall` after access resolves and inside agent jobs; it reads only the+request's config snapshot and the verifier's AuthInfo (`readsUnscoped`,+`createdAt`). `access.requester_scope_enforce false` (hosted) turns it into the+`_meta.access.requester_scope` notice.+**Surface posture:** thin CLI clients use the full MCP surface for remotecommand compatibility. Bootstrap pins `--surface starter --advertise verbs`; managed thin CLI grantsfor OpenClaw, Grok Bot, and Muse also select `full`. Surface visibility does notdiff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 8d6a62a3d7..f9b8d425aa 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1248,6 +1248,16 @@ Reasons: `not_covered`, `restore`.More: [docs/guides/repair.md#coverage-gap](../../docs/guides/repair.md#coverage-gap)+### credential_scope_required++<a id="credential_scope_required"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| gbrain auth create or gbrain auth register-client was asked for a credential bound to no member on a brain that serves several people, so nothing was created. | A credential bound to nobody on such a brain is refused on every read (requester_scope_required); creating one would hand out a key that cannot work, or one that reads everyone's unmarked notes. | Bind it to the person it serves: gbrain auth create <name> --member <id> (gbrain access member list names the members). A shared agent passes --may-act-for <members> instead; --reads-unscoped --yes creates one that reads every page no rule restricts for any asker, on purpose. Run: gbrain access member list --json | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/write-refusals.md#credential_scope_required](../../docs/guides/write-refusals.md#credential_scope_required)+### cursor_incarnation_retired<a id="cursor_incarnation_retired"></a>@@ -4266,6 +4276,28 @@ More: [docs/guides/troubleshooting.md#repair-preview-timeout](../../docs/guides/|---|---|---|---|---|---|---|| The request exceeds a configured capacity; narrow it. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### requester_scope_required++<a id="requester_scope_required"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A remote read came from a connection bound to no member (an access token, an OAuth client or a local stdio server) on a brain that serves several people (two or more enabled members, or config access.serves = several), so it was refused before any work and nothing was read. | On a brain that serves several people a connection bound to nobody reads every page no rule restricts, for whoever is asking; gbrain refuses rather than guess whose notes a read is for. A connection that existed when the brain started serving several people gets 14 days of in-band notices first (reason grace_ended); one created after that is refused at once (created_after). | On the brain host, bind the connection to the person it serves: gbrain auth rescope --token <name>\|--client <id> --member <id> (preview with gbrain access check --token <name>), or for a stdio server, when only one person uses that harness, gbrain setup claude-code\|codex --stdio-member <id>, which binds that one harness entry on that machine (refused where OpenClaw or Hermes is installed); for a harness several people talk to, give each person a key over HTTP instead (gbrain serve --http with gbrain auth create <name> --member <id> keys). A shared agent lists whom it may act for (--may-act-for) and names the person on each call. Last resort: --reads-unscoped --yes lets that one credential read every page no rule restricts for any asker. | user | `gbrain doctor --json` | 1 | no |++Reasons: `grace_ended`, `created_after`, `since_unknown`.++More: [docs/guides/write-refusals.md#requester_scope_required](../../docs/guides/write-refusals.md#requester_scope_required)++### requester_scope_unknown++<a id="requester_scope_unknown"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A remote read came from a connection bound to no member, and whether the brain serves one person or several could not be read (the config read failed, and so did one re-read), so it was refused before any work and nothing was read. | A statement timeout, a lock wait or a dropped pooled connection can fail one config read while the next read succeeds. Reading that as a one-person brain would let a connection bound to nobody read every page no rule restricts on a brain that may serve several people, so gbrain refuses until it can tell. | Retry the same call in a few seconds. If it keeps failing, the brain host's operator checks the database with gbrain doctor --json. A connection bound to a member is never refused this way. | provider | `repeat the read that failed` | 1 | yes |++More: [docs/guides/write-refusals.md#requester_scope_unknown](../../docs/guides/write-refusals.md#requester_scope_unknown)+### requirements_changed<a id="requirements_changed"></a>diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex 0fc053529e..cd09c63441 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -405,6 +405,14 @@ Read [brains and sources](../architecture/brains-and-sources.md#what-confines-rebefore choosing a sharing topology. Tests cover specific boundaries, not auniversal security guarantee.+A brain that serves several people (two or more enabled members, or config+`access.serves = several`) refuses remote reads from a connection bound to no+member (`requester_scope_required`, after a 14-day grace for connections that+already existed), so a shared bot cannot read everyone's unmarked notes for+whoever is asking. That covers reads only: writes keep their own rules, and a+page that names no readers is still read by every member.+[The refusal and its fix](write-refusals.md#requester_scope_required).+<a id="fence-markers-in-code"></a>**Fence markers quoted in code.** Since 0.60.97.0 the readers (the fenceparser, projections, repair) ignore a takes or facts fence marker that sits indiff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.mdindex 528c2b7022..fc12f464c0 100644--- a/docs/guides/multi-source-brains.md+++ b/docs/guides/multi-source-brains.md@@ -214,12 +214,22 @@ member's token. This is the supported production setup today: onenever learns who is asking from the request itself.```bash-gbrain auth create bot-alice-example+gbrain auth create bot-alice-example --member alice-examplegbrain auth rescope --token bot-alice-example --sources source-a# OAuth client instead of a bearer token:-gbrain auth rescope --client <client_id> --sources source-a+gbrain auth rescope --client <client_id> --sources source-a --member alice-example```+Once the brain has two or more enabled members (or config `access.serves` is+`several`), a remote read through a token, OAuth client or stdio server bound to+no member is refused with+[`requester_scope_required`](write-refusals.md#requester_scope_required), and+`gbrain auth create` refuses an unbound token. A connection that existed when the+brain started serving several people reads for 14 more days, with a notice on+every answer (`_meta.access.requester_scope`) naming the date and the command that+binds it. Bind every member's token with `--member`. A brain for one person sees+no change, however many sources it holds.+The token's grant is the security boundary: the server scopes every call tothe grant of the token that made it, whatever the call's arguments say.`source_ids` is a convenience inside that boundary. A bot holding one tokendiff --git a/docs/guides/setup.md b/docs/guides/setup.mdindex af28cf2891..d07f264026 100644--- a/docs/guides/setup.md+++ b/docs/guides/setup.md@@ -208,6 +208,34 @@ a brain setup cannot read refuses (`setup_serves_unreadable`).`gbrain access serves several --members ...` does the labelling alone (preview, then`--yes`).+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+any work, and `gbrain auth create` / `register-client` refuse to create one+(`credential_scope_required`). A connection that existed when the brain started+serving several people (config `access.serves_since`, or the upgrade that added+the refusal) keeps reading for 14 days, with `_meta.access.requester_scope` on+every answer naming the date and the fix; `gbrain doctor` fails+`unscoped_shared_reads` and `gbrain post-upgrade` lists each one with its+command. Bind each connection to its person+(`gbrain auth rescope --token <name> --member <id>`). A stdio harness only one+person uses is bound with `gbrain setup claude-code|codex --stdio-member <id>`,+which writes the member into that one harness entry on that machine, on PGLite+or Postgres. For a harness several people talk to, give each person a key over+HTTP instead (`gbrain serve --http` with `gbrain auth create <name> --member <id>`+keys). A brain pinned `access.serves one` never refuses, however many members+it has.+Nothing binds stdio on its own: upgrade, post-upgrade and doctor never write+`mcp.stdio_member`, and `gbrain doctor` fails `shared_stdio_binding` when it is+set on a host where OpenClaw or Hermes is installed (its fix is+`gbrain config unset mcp.stdio_member`). A team that shares everything may+mark one credential `gbrain auth rescope --token <name> --reads-unscoped --yes`+(`--reads-unscoped none` takes it back); every change is recorded in the+`access-reads-unscoped` audit file. Hosted brains keep+`access.requester_scope_enforce false` until their control plane binds each+connection to a member, so they see the notice and no refusal. Writes are not+affected, and a one-person brain sees no change.+## Brain-first instructionsRegistering MCP makes the tools available; it does not make agents use them.diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 32a3c75147..7020648107 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -1064,6 +1064,28 @@ live in the database, so they are the same on a repo-less brain.| <a id="on_behalf_of_not_permitted"></a>`on_behalf_of_not_permitted` | The credential's `may_act_for` (for a stdio server, config `mcp.stdio_may_act_for`) does not list every audience entry. The message names the credential and the entries it may not act for. Nothing was read. | The brain operator decides: `fix` carries `gbrain auth rescope --token <name> --may-act-for <list>` (or `--client <id>`, or `gbrain config set mcp.stdio_may_act_for <list>`) with the full list to approve. The agent never runs it; until then, call without the audience. || <a id="on_behalf_of_in_arguments"></a>`on_behalf_of_in_arguments` | A tool call carried `on_behalf_of` in its arguments (top level or an arguments-level `_meta`), where conversation text could set it. Nothing was read. | Remove it from the arguments. Harness code sends the audience as the header or request-level `_meta.on_behalf_of`; a stdio client that cannot set request-level `_meta` uses a credential bound to one member or config `mcp.stdio_member`. |+## Unscoped reads on a brain that serves several people++A brain serves several people when two or more members are enabled, or when config `access.serves` is `several`+(`gbrain access serves` says which and why; an explicit `one` wins over the member count). On such a brain every+remote read must say whom it reads for: a credential bound to a member (`--member`, the owner included), a shared+agent naming its audience per call (`--may-act-for` plus `X-Gbrain-On-Behalf-Of`), or an attested person. A brain+for one person, with any number of sources, sees no change. Writes are not affected. Everything is database state, so a+repo-less or keyless brain behaves the same.++A connection that existed when the brain started serving several people (config `access.serves_since`, or the+upgrade that added it, whichever is later) keeps reading for 14 days; each answer then carries+`_meta.access.requester_scope` with `state: "grace"`, `refuses_at`, the connection and `fix`. A local stdio+server and a credential with no recorded creation time count as existing. Hosted brains set+`access.requester_scope_enforce false` until their control plane binds each connection to a member: the notice then+reads `state: "not_enforced"` and nothing is refused.++| Code | What happened | What to do |+|---|---|---|+| <a id="requester_scope_required"></a>`requester_scope_required` | A remote read came from a connection bound to nobody. `reason` says which: `grace_ended` (the connection is older than the brain's several-people date and its 14 days ran out), `created_after` (it was created after that date, so it had to be scoped at creation) or `since_unknown` (the date could not be read; fail closed). The message names the connection and the operation. Nothing was read; the code is also in `structuredContent.error.code` and the audit trail (`access-audience`). Read-only identity and health calls (`whoami`, `get_brain_identity`, `get_status_snapshot`, `search_modes`, `get_health`, and a non-admin credential's own `get_job` / `wait_job`) still answer. | The brain operator runs `fix` on the brain host: `gbrain auth rescope --token <name> --member <id>` (or `--client <id>`; preview with `gbrain access check --token <name>`), or for a stdio server, when only one person uses that harness, `gbrain setup claude-code|codex --stdio-member <id>`, which binds that one harness entry on that machine, on PGLite or Postgres (setup refuses it where OpenClaw or Hermes is installed); for a harness several people talk to, give each person a key over HTTP instead (`gbrain serve --http` with `gbrain auth create <name> --member <id>` keys). `gbrain doctor` fails `shared_stdio_binding` when `mcp.stdio_member` is set on a host where OpenClaw or Hermes is installed. A shared agent instead lists whom it may act for (`--may-act-for`) and names the person on each call. Last resort, for a team that shares everything: `gbrain auth rescope --token <name> --reads-unscoped --yes` lets that one credential read every page no rule restricts for whoever is asking (`--reads-unscoped none` takes it back). |+| <a id="requester_scope_unknown"></a>`requester_scope_unknown` | A remote read came from a connection bound to nobody, and gbrain could not tell whether the brain serves one person or several: its config read failed (a statement timeout, a lock wait or a dropped pooled connection) and so did one re-read of the serves keys. Nothing was read. The message does not claim the brain serves several people, because that is what could not be read. A connection bound to a member is never refused this way. | Retry the same call after `retry_after_ms` (`fix.next` is `wait`). If it keeps failing, the brain host's operator checks the database with `gbrain doctor --json`. |+| <a id="credential_scope_required"></a>`credential_scope_required` | `gbrain auth create` or `gbrain auth register-client` was asked for a credential bound to no member on a brain that serves several people. Nothing was created. | Pass `--member <id>` (`gbrain access member list`), or `--may-act-for <members>` for a shared agent. `--reads-unscoped --yes` creates one that reads unscoped on purpose. |+## Attested-actor refusalsA trusted system (QM) names the person a call serves in the `x-qm-actor` header, as an opaque canonical id that thediff --git a/docs/tutorials/company-brain.md b/docs/tutorials/company-brain.mdindex bee47ff1ba..058f82c525 100644--- a/docs/tutorials/company-brain.md+++ b/docs/tutorials/company-brain.md@@ -134,6 +134,8 @@ A credential bound with `--member` whose write source is `default` (a token withA remote caller whose credential is bound to a listed member (directly or through a group) reads the page on every read path; every other remote caller, including an unbound token, an unbound stdio server, a bot with `--private-pages granted-sources` and an operator escape hatch (`GBRAIN_REMOTE_PRIVATE_PAGES=1`, `search.remote_private_pages=visible`), gets the same `not_found` as for a page that does not exist. `readable_by` only narrows: a `visibility: private` page stays private to a listed member unless the member's credential also has `--private-pages granted-sources`. What every designation means for each kind of caller is in [access designations](../guides/access-designations.md). A malformed `readable_by` reads as nobody. A page derived from a restricted page (an extracted atom, a synthesized concept, a chronicle event) is readable by no remote caller. The local CLI is unchanged; `--as <member>` previews one member's view. Pages that already carried `readable_by` before you upgraded read as nobody until `gbrain repair access` (preview, then `--apply`) derives their readers. This works the same on a repo-less brain: members, groups and bindings live in the database.+On a brain with two or more enabled members, Model C is required, not optional: a remote read from a token or OAuth client bound to no member is refused with [`requester_scope_required`](../guides/write-refusals.md#requester_scope_required) (connections that already existed get 14 days of notices first), and `gbrain auth create` refuses an unbound token. Bind each teammate's credential with `--member`; a bot serving a channel names its audience per call (`--may-act-for`); `--reads-unscoped --yes` opts one credential out on purpose.+**Folder rules: keep a whole folder to some members.** Instead of tagging every page, give a prefix its readers. On a repo-less brain (the default install) the rules live in the database:```bashdiff --git a/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md b/plugin-variants/gbrain-coding/skills/conventions/brain-routing.mdindex f056816e2b..bc59a3b877 100644--- a/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md+++ b/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md@@ -28,7 +28,7 @@ reason.A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludesthis credential or the audience it acts for: check `whoami` (`access.applied`) before telling the user there are no notes.-On a brain that serves several people (`gbrain access serves`), a connection bound to a member (`whoami` names it) already reads as the person asking; an unbound one still needs the scoping above.+On a brain that serves several people (`gbrain access serves`), a connection bound to a member (`whoami` names it) already reads as the person asking; an unbound one is refused `requester_scope_required` (after a 14-day grace noticed in `_meta.access.requester_scope`): relay its fix to the user.## When to switch braindiff --git a/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md b/plugin-variants/gbrain-daily/skills/conventions/brain-routing.mdindex f056816e2b..bc59a3b877 100644--- a/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md+++ b/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md@@ -28,7 +28,7 @@ reason.A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludesthis credential or the audience it acts for: check `whoami` (`access.applied`) before telling the user there are no notes.-On a brain that serves several people (`gbrain access serves`), a connection bound to a member (`whoami` names it) already reads as the person asking; an unbound one still needs the scoping above.+On a brain that serves several people (`gbrain access serves`), a connection bound to a member (`whoami` names it) already reads as the person asking; an unbound one is refused `requester_scope_required` (after a 14-day grace noticed in `_meta.access.requester_scope`): relay its fix to the user.## When to switch braindiff --git a/plugin/skills/conventions/brain-routing.md b/plugin/skills/conventions/brain-routing.mdindex f056816e2b..bc59a3b877 100644--- a/plugin/skills/conventions/brain-routing.md+++ b/plugin/skills/conventions/brain-routing.md@@ -28,7 +28,7 @@ reason.A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludesthis credential or the audience it acts for: check `whoami` (`access.applied`) before telling the user there are no notes.-On a brain that serves several people (`gbrain access serves`), a connection bound to a member (`whoami` names it) already reads as the person asking; an unbound one still needs the scoping above.+On a brain that serves several people (`gbrain access serves`), a connection bound to a member (`whoami` names it) already reads as the person asking; an unbound one is refused `requester_scope_required` (after a 14-day grace noticed in `_meta.access.requester_scope`): relay its fix to the user.## When to switch braindiff --git a/plugin/skills/remote-mcp/SKILL.md b/plugin/skills/remote-mcp/SKILL.mdindex e1fd0955f2..5465892a21 100644--- a/plugin/skills/remote-mcp/SKILL.md+++ b/plugin/skills/remote-mcp/SKILL.md@@ -84,7 +84,7 @@ This skill guarantees:| Your own devices: Claude Desktop, Claude Code / Codex / opencode on another laptop, phone apps joined to the tailnet | tailnet-only HTTPS (default) | `gbrain mcp expose --dry-run` (preview; the run itself is Phase 2, after consent) || Cloud agents running in a vendor's cloud: Grok Bot, Muse, ChatGPT connector, Claude.ai / Cowork, Perplexity Computer | public HTTPS on the same `*.ts.net` name | `gbrain mcp expose --funnel --dry-run` (preview; Phase 2 after consent) || Cloud agent whose runtime you can join to your tailnet (userspace `tailscaled`, ephemeral auth key) | tailnet-only | Advanced, unverified, not automated — see the [remote MCP guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/remote-mcp.md) |-| Local agents on the same machine (Claude Code, Codex, opencode) | loopback — no Tailscale needed | Postgres: `gbrain bootstrap harness --yes --port 3131`. PGLite: mint the token BEFORE the service runs (`gbrain auth create local-agents --scopes read,write` — before `gbrain mcp expose`, or while the service is briefly stopped) and pass `gbrain bootstrap harness --yes --port 3131 --token <value>`; OR use the scoped path `gbrain mcp grant <name> --harness <id> --profile memory-writer --source default --url http://127.0.0.1:3131/mcp --admin-token-file ~/.gbrain/serve/admin-token --credentials-out /private/<name>.json` then `gbrain connect http://127.0.0.1:3131/mcp --harness <id> --credentials-file /private/<name>.json --install` (MCP wiring only, no per-turn hooks) |+| Local agents on the same machine (Claude Code, Codex, opencode) | loopback — no Tailscale needed | Postgres: `gbrain bootstrap harness --yes --port 3131`. PGLite: mint the token BEFORE the service runs (`gbrain auth create local-agents --scopes read,write`, plus `--member <id>` on a brain that serves several people — before `gbrain mcp expose`, or while the service is briefly stopped) and pass `gbrain bootstrap harness --yes --port 3131 --token <value>`; OR use the scoped path `gbrain mcp grant <name> --harness <id> --profile memory-writer --source default --url http://127.0.0.1:3131/mcp --admin-token-file ~/.gbrain/serve/admin-token --credentials-out /private/<name>.json` then `gbrain connect http://127.0.0.1:3131/mcp --harness <id> --credentials-file /private/<name>.json --install` (MCP wiring only, no per-turn hooks) || Thin client only (this machine has no brain) | — | Stop: run this skill on the brain host |Grok Bot and Muse users with no always-on machine keep the in-agent local@@ -276,7 +276,7 @@ gbrain mcp grant agent-example --harness grok-bot --profile memory-writer \| Grok Bot using the private machine path | Inside the Bot: `gbrain connect https://your-machine.your-tailnet.ts.net/mcp --harness grok-bot --credentials-file /private/agent-example.json --install --root /workspace/gbrain`; enable the generated instruction as a native skill (a visible, separate step) || Muse using the private machine path | Same `gbrain connect … --harness muse … --install --root <verified durable root>`; establish the durable user-files location first — never `/tmp`, never an invented path || Claude Code / Codex / opencode using managed private configuration on another machine | `gbrain connect https://your-machine.your-tailnet.ts.net/mcp --harness codex --credentials-file /private/agent-example.json --install`; select the actual adapter |-| Local agents on the brain host | Postgres: `gbrain bootstrap harness --yes --port 3131`. PGLite: `bootstrap harness` refuses under the live serve unless `--token` is passed — mint BEFORE the service runs (`gbrain auth create local-agents --scopes read,write`, run before `gbrain mcp expose` or while the service is briefly stopped) and pass `gbrain bootstrap harness --yes --port 3131 --token <value>`; or skip hooks and use the scoped `gbrain mcp grant … --url http://127.0.0.1:3131/mcp --admin-token-file ~/.gbrain/serve/admin-token --credentials-out /private/<name>.json` + `gbrain connect http://127.0.0.1:3131/mcp --harness <id> --credentials-file /private/<name>.json --install` path (MCP wiring only) |+| Local agents on the brain host | Postgres: `gbrain bootstrap harness --yes --port 3131`. PGLite: `bootstrap harness` refuses under the live serve unless `--token` is passed — mint BEFORE the service runs (`gbrain auth create local-agents --scopes read,write`, plus `--member <id>` on a brain that serves several people, run before `gbrain mcp expose` or while the service is briefly stopped) and pass `gbrain bootstrap harness --yes --port 3131 --token <value>`; or skip hooks and use the scoped `gbrain mcp grant … --url http://127.0.0.1:3131/mcp --admin-token-file ~/.gbrain/serve/admin-token --credentials-out /private/<name>.json` + `gbrain connect http://127.0.0.1:3131/mcp --harness <id> --credentials-file /private/<name>.json --install` path (MCP wiring only) || ChatGPT / Perplexity / other cloud OAuth clients | Requires explicit `--funnel` when the runtime is outside the tailnet; follow the native OAuth path and per-client page under `docs/mcp/` with the published URL |Tailnet-only endpoints are reachable only from devices signed in to the samediff --git a/plugin/skills/setup/SKILL.md b/plugin/skills/setup/SKILL.mdindex 1a4fdd8cb7..038194855e 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. Fix a `setup_serves_several` 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. Relay key file paths, never keys. 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.tsvindex b1efc2ba87..0f348a0835 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -49,6 +49,6 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)src/commands/config.ts 1530 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +4 GBRA-377 PR B: skills.resolver.* file-plane routing (doc line, the one-line router and its two dispatch lines; logic in core/setup/skill-resolver-config.ts)src/commands/mcp-expose.ts 1519 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)-src/core/behavior-change-notice.ts 1761 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+src/core/behavior-change-notice.ts 1762 ratchet +1 GST-363 requester_scope_gst363 row (since TBD until the merge slot); +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 + 3src/core/git/commit-push.ts 1658 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 + 31src/commands/auth.ts 1503 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 movediff --git a/skills/conventions/brain-routing.md b/skills/conventions/brain-routing.mdindex f056816e2b..bc59a3b877 100644--- a/skills/conventions/brain-routing.md+++ b/skills/conventions/brain-routing.md@@ -28,7 +28,7 @@ reason.A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludesthis credential or the audience it acts for: check `whoami` (`access.applied`) before telling the user there are no notes.-On a brain that serves several people (`gbrain access serves`), a connection bound to a member (`whoami` names it) already reads as the person asking; an unbound one still needs the scoping above.+On a brain that serves several people (`gbrain access serves`), a connection bound to a member (`whoami` names it) already reads as the person asking; an unbound one is refused `requester_scope_required` (after a 14-day grace noticed in `_meta.access.requester_scope`): relay its fix to the user.## When to switch braindiff --git a/skills/remote-mcp/SKILL.md b/skills/remote-mcp/SKILL.mdindex 4aee2616c2..62716a345f 100644--- a/skills/remote-mcp/SKILL.md+++ b/skills/remote-mcp/SKILL.md@@ -83,7 +83,7 @@ This skill guarantees:| Your own devices: Claude Desktop, Claude Code / Codex / opencode on another laptop, phone apps joined to the tailnet | tailnet-only HTTPS (default) | `gbrain mcp expose --dry-run` (preview; the run itself is Phase 2, after consent) || Cloud agents running in a vendor's cloud: Grok Bot, Muse, ChatGPT connector, Claude.ai / Cowork, Perplexity Computer | public HTTPS on the same `*.ts.net` name | `gbrain mcp expose --funnel --dry-run` (preview; Phase 2 after consent) || Cloud agent whose runtime you can join to your tailnet (userspace `tailscaled`, ephemeral auth key) | tailnet-only | Advanced, unverified, not automated — see the [remote MCP guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/remote-mcp.md) |-| Local agents on the same machine (Claude Code, Codex, opencode) | loopback — no Tailscale needed | Postgres: `gbrain bootstrap harness --yes --port 3131`. PGLite: mint the token BEFORE the service runs (`gbrain auth create local-agents --scopes read,write` — before `gbrain mcp expose`, or while the service is briefly stopped) and pass `gbrain bootstrap harness --yes --port 3131 --token <value>`; OR use the scoped path `gbrain mcp grant <name> --harness <id> --profile memory-writer --source default --url http://127.0.0.1:3131/mcp --admin-token-file ~/.gbrain/serve/admin-token --credentials-out /private/<name>.json` then `gbrain connect http://127.0.0.1:3131/mcp --harness <id> --credentials-file /private/<name>.json --install` (MCP wiring only, no per-turn hooks) |+| Local agents on the same machine (Claude Code, Codex, opencode) | loopback — no Tailscale needed | Postgres: `gbrain bootstrap harness --yes --port 3131`. PGLite: mint the token BEFORE the service runs (`gbrain auth create local-agents --scopes read,write`, plus `--member <id>` on a brain that serves several people — before `gbrain mcp expose`, or while the service is briefly stopped) and pass `gbrain bootstrap harness --yes --port 3131 --token <value>`; OR use the scoped path `gbrain mcp grant <name> --harness <id> --profile memory-writer --source default --url http://127.0.0.1:3131/mcp --admin-token-file ~/.gbrain/serve/admin-token --credentials-out /private/<name>.json` then `gbrain connect http://127.0.0.1:3131/mcp --harness <id> --credentials-file /private/<name>.json --install` (MCP wiring only, no per-turn hooks) || Thin client only (this machine has no brain) | — | Stop: run this skill on the brain host |Grok Bot and Muse users with no always-on machine keep the in-agent local@@ -275,7 +275,7 @@ gbrain mcp grant agent-example --harness grok-bot --profile memory-writer \| Grok Bot using the private machine path | Inside the Bot: `gbrain connect https://your-machine.your-tailnet.ts.net/mcp --harness grok-bot --credentials-file /private/agent-example.json --install --root /workspace/gbrain`; enable the generated instruction as a native skill (a visible, separate step) || Muse using the private machine path | Same `gbrain connect … --harness muse … --install --root <verified durable root>`; establish the durable user-files location first — never `/tmp`, never an invented path || Claude Code / Codex / opencode using managed private configuration on another machine | `gbrain connect https://your-machine.your-tailnet.ts.net/mcp --harness codex --credentials-file /private/agent-example.json --install`; select the actual adapter |-| Local agents on the brain host | Postgres: `gbrain bootstrap harness --yes --port 3131`. PGLite: `bootstrap harness` refuses under the live serve unless `--token` is passed — mint BEFORE the service runs (`gbrain auth create local-agents --scopes read,write`, run before `gbrain mcp expose` or while the service is briefly stopped) and pass `gbrain bootstrap harness --yes --port 3131 --token <value>`; or skip hooks and use the scoped `gbrain mcp grant … --url http://127.0.0.1:3131/mcp --admin-token-file ~/.gbrain/serve/admin-token --credentials-out /private/<name>.json` + `gbrain connect http://127.0.0.1:3131/mcp --harness <id> --credentials-file /private/<name>.json --install` path (MCP wiring only) |+| Local agents on the brain host | Postgres: `gbrain bootstrap harness --yes --port 3131`. PGLite: `bootstrap harness` refuses under the live serve unless `--token` is passed — mint BEFORE the service runs (`gbrain auth create local-agents --scopes read,write`, plus `--member <id>` on a brain that serves several people, run before `gbrain mcp expose` or while the service is briefly stopped) and pass `gbrain bootstrap harness --yes --port 3131 --token <value>`; or skip hooks and use the scoped `gbrain mcp grant … --url http://127.0.0.1:3131/mcp --admin-token-file ~/.gbrain/serve/admin-token --credentials-out /private/<name>.json` + `gbrain connect http://127.0.0.1:3131/mcp --harness <id> --credentials-file /private/<name>.json --install` path (MCP wiring only) || ChatGPT / Perplexity / other cloud OAuth clients | Requires explicit `--funnel` when the runtime is outside the tailnet; follow the native OAuth path and per-client page under `docs/mcp/` with the published URL |Tailnet-only endpoints are reachable only from devices signed in to the samediff --git a/skills/setup/SKILL.md b/skills/setup/SKILL.mdindex 8d30d98975..6e7803b0a2 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. Fix a `setup_serves_several` 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. Relay key file paths, never keys. 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.json b/skills/skills.lock.jsonindex e39d2a62bf..968e3a8ce1 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -46,7 +46,7 @@"context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab","conventions/agent-operator-protocol.md": "12c7b876994b96babdffa903326f7e23253d54ad9023248820337f56f8770512","conventions/brain-first.md": "f84f03b9619a1c9302a231bd43957c6987d55084f56eee351434b85ec2646a5c",- "conventions/brain-routing.md": "753703b94fcb10d42cb52fb0c85d7a8c9769df84b0df622dd04ae0d943bb84b1",+ "conventions/brain-routing.md": "c325dacde22e6df12b8c90decd92b5cb1845f2c9b9e211ea8ee0ac5ee1c9f390","conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198","conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933","conventions/cross-modal.yaml": "c012c3d72614a87b1ee698173dce2a0fb0d057a54df7aab87993c4b07fff6280",@@ -201,7 +201,7 @@"publish/SKILL.md": "271bd9ba87279429cd934509071dd032b859d59264038c38829c9af46f15c13b","query/SKILL.md": "81f1f4d8d18a364bc5d90c65cc731f73e77be6c28dc86797aaebfad7430e552d","query/routing-eval.jsonl": "74f5a91e52fabc54e0e9403fa17db87ee26bb7ebb8ae8005148c51142abc62fe",- "remote-mcp/SKILL.md": "753d4df2c6b8c837d00a9c0593028220bdceb1a83b08b29a1d9b973242b789c5",+ "remote-mcp/SKILL.md": "ef7b60b6424405ffaaed0edbdbbf8bbec42e30333ad363a3a28f114a10af3b32","remote-mcp/routing-eval.jsonl": "7287693135c9fe2d6495d81d22746ddf41b116254db4b6e683dbdee251e08f8e","repo-architecture/SKILL.md": "c57c629d31676ef02f4f42f6dd55dd432e02e0d3a6397aacbbd1037138493763","reports/SKILL.md": "3d3ad45a4ebe82251244f74c98c29f633c1b4b98745ad88fdbc01bd6e43b6dec",@@ -212,7 +212,7 @@"resolve-before-asking/routing-eval.jsonl": "bac1bcf30337f5255ef4ce1a2a8a2b38d58ebcd576503c483190c79ec6e69489","schema-author/SKILL.md": "38efb8b48399a2dc526d7084579aa265b2ab232882605bc2f86f6ba2869619f5","schema-unify/SKILL.md": "36259f1510fd693253535bd203e32db1bfa24aaae7278c7a2e8b7d6859022708",- "setup/SKILL.md": "1cfb85220ef53a8575a54137ab45296a36e5d00652d1e71e8f569315b425b027",+ "setup/SKILL.md": "987ed3621d335ea8aef704e24e2f2eb4d9558802aff2c8216a230d3ac82aaddd","signal-detector/SKILL.md": "426a8a3b01a007dd25638e61adef510c18c3d9ce6f1c18ba3d77fdfcd3281d60","skill-autobench/SKILL.md": "29f5760dcfd823c5f7d4fb50a3cf4e36601b1b8125e57d6bf83645a41f97f613","skill-autobench/routing-eval.jsonl": "8d961ed6403b7e2f690948e4c18529d40f26f6f21064befc56d465966b1a9ec0",diff --git a/src/commands/access.ts b/src/commands/access.tsindex 5565aa8b24..095b9724d7 100644--- a/src/commands/access.ts+++ b/src/commands/access.ts@@ -30,6 +30,7 @@ import { mayActForCovers, singleMemberAudience, type AudiencePrincipal } from '.import { linkMember, linkMemberByEmail, listMemberLinks, unlinkMember } from '../core/access/actor.ts';import { bindMemberSource, listMemberSources, unbindMemberSource } from '../core/access/member-sources.ts';import { clearOwner, ownerMemberId, ownerReadsRestrictedOn, ownerView, setOwner, setOwnerReadsRestricted, type OwnerView } from '../core/access/owner.ts';+import { stdioBindRoute } from '../core/access/stdio-bind-route.ts';import {addGroup, addMember, assertAccessId, disableMember, enableMember, getMember, legacyTokenByName, listGroups, listMembers,parseIdList, previewRemoveGroup, previewRemoveMember, removeGroup, removeGroupMembers, removeMember, setMemberEmail, setMemberKind, type MemberRecord,@@ -215,6 +216,8 @@ export interface AccessCheckResult {identity: string[];may_act_for: string[] | null;verdict: 'reads_as_member' | 'unbound' | 'refused';+ /** GST-363: marked with auth rescope --reads-unscoped --yes, so it reads unscoped on purpose on a brain that serves several people. */+ reads_unscoped: boolean;/** GST-2059: the credential reads as the brain owner (config access.owner_member). */owner: boolean;/** GST-2490: access.owner_reads_restricted is on, so the owner's credentials read past readers lists and rules. */@@ -239,7 +242,7 @@ export async function accessCheck(engine: BrainEngine, target: { token?: string;} else {const client = await readClientGrant(engine, target.client!);if (client.revoked) throw opError('client_not_found', `OAuth client "${target.client}" is revoked.`, 'List the clients with gbrain auth clients --json.');- [row] = await engine.executeRaw<Record<string, unknown>>('SELECT member_id, may_act_for FROM oauth_clients WHERE client_id = $1', [client.clientId]) as [Record<string, unknown>];+ [row] = await engine.executeRaw<Record<string, unknown>>('SELECT member_id, may_act_for, reads_unscoped FROM oauth_clients WHERE client_id = $1', [client.clientId]) as [Record<string, unknown>];grant = grantFromClient(client);credential = { kind: 'client', id: client.clientId, name: client.clientName };}@@ -250,11 +253,13 @@ export async function accessCheck(engine: BrainEngine, target: { token?: string;const identity = live ? identityFor(member!.id, member!.groups) : [];const mayActFor = Array.isArray(row.may_act_for) ? (row.may_act_for as string[]) : null;const verdict: AccessCheckResult['verdict'] = !member ? 'unbound' : live ? 'reads_as_member' : 'refused';+ const readsUnscoped = row.reads_unscoped != null;const ownerId = await ownerMemberId(engine);const owner = live && member!.id === ownerId;const ownerReadsRestricted = !!ownerId && await ownerReadsRestrictedOn(engine);const memberLineage = await membersReadLineageOn(engine);const explanation = verdict === 'unbound' ? 'Bound to no member: reads every page its grant allows except pages that name readers (readable_by).'+ + (readsUnscoped ? ' Marked --reads-unscoped: on a brain that serves several people it reads every page no rule restricts, for any asker (gbrain auth rescope --reads-unscoped none removes the mark).' : ''): verdict === 'refused' ? `Bound to member "${member!.id}", which is ${member!.status}: the credential is refused at verification (access_member_disabled).`: `Reads as member "${member!.id}"${member!.groups.length ? ` (groups: ${member!.groups.join(', ')})` : ''}: pages naming readers are visible when they list the member or one of its groups, within the grant below.`+ (owner ? ' It is the brain owner: it also reads visibility: private pages, privacy-alias pages, derived and pinned-question pages and private facts in every source the grant reads.' : '')@@ -268,7 +273,7 @@ export async function accessCheck(engine: BrainEngine, target: { token?: string;credential,grant: { scopes: grant.scopes, sources: grant.sources, takes_holders: grant.takesHolders, private_pages: grant.privatePages,operations: grant.allowedOperations ?? 'unrestricted', revision: grant.revision },- member, identity, may_act_for: mayActFor, verdict, owner, owner_reads_restricted: ownerReadsRestricted, members_read_lineage: memberLineage, explanation,+ member, identity, may_act_for: mayActFor, verdict, reads_unscoped: readsUnscoped, owner, owner_reads_restricted: ownerReadsRestricted, members_read_lineage: memberLineage, explanation,};if (target.as !== undefined) {const audience: NonNullable<AccessCheckResult['audience']> = [];@@ -407,7 +412,7 @@ async function memberSourceCmd(engine: BrainEngine, args: string[], json: boolea}}-function ownerLines(v: OwnerView): string[] {+export function ownerLines(v: OwnerView): string[] {if (!v.owner) return v.inactive ? [`Owner: none in effect. access.owner_member names "${v.inactive.value}": ${v.inactive.reason}`, 'Fix it with gbrain access owner set <member> or gbrain access owner clear.']: ['Owner: none. Every remote caller reads under the ordinary policy (no visibility: private page without a grant).', 'Name one: gbrain access owner set <member>'];return [`Owner: ${v.owner}`,@@ -415,7 +420,7 @@ function ownerLines(v: OwnerView): string[] {v.reads_restricted? ' Owner reads member-restricted pages: on (access.owner_reads_restricted). Its credentials read pages that readers lists and folder or page rules keep to other members, and their derived pages and facts; never another member\'s own member page. Turn off: gbrain access owner reads-restricted off': ' Owner reads member-restricted pages: off. It reads a page that names readers or sits under a rule only when listed. Turn on: gbrain access owner reads-restricted on',- ` Bind one: gbrain auth rescope --token <name> --member ${v.owner} (a stdio server: gbrain config set mcp.stdio_member ${v.owner})`];+ ` Bind one: gbrain auth rescope --token <name> --member ${v.owner}. Stdio: ${stdioBindRoute(v.owner).text}`];}async function ownerCmd(engine: BrainEngine, sub: string | undefined, args: string[], json: boolean): Promise<void> {diff --git a/src/commands/auth-binding.ts b/src/commands/auth-binding.tsindex 4e40381d74..61c210c171 100644--- a/src/commands/auth-binding.ts+++ b/src/commands/auth-binding.ts@@ -51,8 +51,18 @@ export function takeBindingFlags(args: string[]): { args: string[]; patch: Bindiconst out: string[] = [];const patch: BindingPatch = {};let seen = false;+ let yes = false;for (let i = 0; i < args.length; i++) {const a = args[i]!;+ if (a === '--yes') { yes = true; continue; }+ // GST-363: --reads-unscoped (with --yes) lets one credential read unscoped on a brain that serves several people; none removes it.+ if (a === '--reads-unscoped' || a.startsWith('--reads-unscoped=')) {+ const value = a.includes('=') ? a.slice(a.indexOf('=') + 1) : args[i + 1] === 'none' ? args[++i] : undefined;+ if (value !== undefined && value !== 'none') throw usageError(`--reads-unscoped takes no value, or none (got ${value}).`, 'Pass --reads-unscoped --yes to let this credential read unscoped on purpose, or --reads-unscoped none to remove it.');+ patch.readsUnscoped = value === undefined;+ seen = true;+ continue;+ }const flag = FLAGS.find(f => a === f || a.startsWith(`${f}=`));if (!flag) { out.push(a); continue; }const value = a.includes('=') ? a.slice(a.indexOf('=') + 1) : args[++i];@@ -65,6 +75,11 @@ export function takeBindingFlags(args: string[]): { args: string[]; patch: Bindielse patch.attestSources = parseAttestSources(value);seen = true;}+ if (patch.readsUnscoped === true && !yes) {+ throw usageError('--reads-unscoped needs --yes: on a brain that serves several people this credential then reads every page no rule restricts, for whoever is asking.',+ 'Bind it to the person it serves instead (--member <id>), or confirm with --reads-unscoped --yes.');+ }+ if (yes && patch.readsUnscoped === undefined) out.push('--yes');return { args: out, patch: seen ? patch : null };}@@ -75,5 +90,6 @@ export async function checkBindingTarget(engine: BrainEngine, patch: BindingPatcexport function bindingLine(b: BindingResult, dryRun = false): string {const attest = b.attest_actor ? `; attests actor: ${b.attest_actor} for ${(b.attest_ops ?? DEFAULT_ATTEST_OPS).join(', ')}; named sources read as: ${b.attest_read ?? 'scope (default)'}${b.attest_sources?.length ? `; scope sources: ${b.attest_sources.join(', ')}` : ''}` : '';- return ` Member: ${b.member ?? 'none'}; may act for: ${b.may_act_for?.join(', ') ?? 'none'}${attest}${b.changed ? (dryRun ? ' (preview, not written)' : ' (updated)') : ''}`;+ const unscoped = b.reads_unscoped === undefined ? '' : `; reads unscoped: ${b.reads_unscoped ? 'yes (every page no rule restricts, for any asker)' : 'no'}`;+ return ` Member: ${b.member ?? 'none'}; may act for: ${b.may_act_for?.join(', ') ?? 'none'}${attest}${unscoped}${b.changed ? (dryRun ? ' (preview, not written)' : ' (updated)') : ''}`;}diff --git a/src/commands/auth.ts b/src/commands/auth.tsindex 966cd18faa..f7f3bee7f3 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -39,6 +39,7 @@ import { migrateLegacyTokens, parseRescopeTokenArgs, renderLegacyGrantAxis, rescimport { bindCredential, type BindingPatch, type BindingResult } from '../core/access/members.ts';import { bindingLine, checkBindingTarget, takeBindingFlags } from './auth-binding.ts';import { mintToken } from './auth-mint.ts';+import { assertCredentialScoped, logReadsUnscopedChange } from '../core/access/requester-scope.ts';import { exitCliError } from '../cli/cli-error.ts';import { OperationError } from '../core/ops/contract.ts';@@ -76,7 +77,7 @@ async function withConfiguredSql<T>(}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>]'); process.exit(1); }+ 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// treats a filtered-empty scopes array as DENY, so a typo must fail loudly// here, never silently brick (or widen) the token.@@ -91,7 +92,9 @@ async function create(name: string, opts: { takesHolders?: string[]; scopes?: st}try {await withConfiguredSql(async (_sql, engine) => {+ await assertCredentialScoped(engine, opts.binding ?? null, 'token', name);const { token, takesHolders, bound } = await mintToken(engine, name, opts);+ if (bound) auditReadsUnscoped(bound, `token ${name}`, false);const scopeLine = opts.scopes !== undefined? `scopes=${JSON.stringify(opts.scopes)}`: 'scopes=full access (grandfathered — pass --scopes read,write to narrow)';@@ -753,7 +756,7 @@ export function formatRegisterClientOutput(name: string, r: RegisteredClient, paasync function registerClient(name: string, args: string[]) {if (!name) {- console.error('Usage: auth register-client <name> [--grant-types G] [--scopes S] [--source SOURCE] [--federated-read SRC1,SRC2,...] [--redirect-uri URI ...] [--token-endpoint-auth-method client_secret_post|client_secret_basic|none] [--bound-tools T1,T2] [--bound-source SOURCE] [--bound-brain BRAIN] [--bound-slug-prefixes P1,P2] [--bound-max-concurrent N] [--budget-usd-per-day USD] [--token-ttl SECONDS]');+ console.error('Usage: auth register-client <name> [--grant-types G] [--scopes S] [--source SOURCE] [--federated-read SRC1,SRC2,...] [--redirect-uri URI ...] [--token-endpoint-auth-method client_secret_post|client_secret_basic|none] [--bound-tools T1,T2] [--bound-source SOURCE] [--bound-brain BRAIN] [--bound-slug-prefixes P1,P2] [--bound-max-concurrent N] [--budget-usd-per-day USD] [--token-ttl SECONDS] [--member <id>] [--reads-unscoped --yes]');process.exit(1);}let parsed: RegisterClientArgs;@@ -763,18 +766,20 @@ async function registerClient(name: string, args: string[]) {parsed = parseRegisterClientArgs(binding.args);} catch (e: any) {console.error(`Error: ${e.message}`);- console.error('Usage: auth register-client <name> [--grant-types G] [--scopes S] [--source SOURCE] [--federated-read SRC1,SRC2,...] [--redirect-uri URI ...] [--token-endpoint-auth-method client_secret_post|client_secret_basic|none] [--bound-tools T1,T2] [--bound-source SOURCE] [--bound-brain BRAIN] [--bound-slug-prefixes P1,P2] [--bound-max-concurrent N] [--budget-usd-per-day USD] [--token-ttl SECONDS]');+ console.error('Usage: auth register-client <name> [--grant-types G] [--scopes S] [--source SOURCE] [--federated-read SRC1,SRC2,...] [--redirect-uri URI ...] [--token-endpoint-auth-method client_secret_post|client_secret_basic|none] [--bound-tools T1,T2] [--bound-source SOURCE] [--bound-brain BRAIN] [--bound-slug-prefixes P1,P2] [--bound-max-concurrent N] [--budget-usd-per-day USD] [--token-ttl SECONDS] [--member <id>] [--reads-unscoped --yes]');process.exit(1);}try {await withConfiguredSql(async (sql, engine) => {await checkBindingTarget(engine, binding.patch);+ await assertCredentialScoped(engine, binding.patch, 'client', name);const columns = parsed.tokenTtlSeconds !== undefined? await preflightOauthClientColumns(sql): undefined;const registered = await registerScopedClient(sql, name, parsed, { columns, transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });const bound = binding.patch ? await bindCredential(engine, { kind: 'client', id: registered.clientId }, binding.patch) : null;+ if (bound) auditReadsUnscoped(bound, `OAuth client ${registered.clientId}`, false);if (registered.skipped?.tokenTtl) {console.error('Note: this brain predates the token_ttl column; run `gbrain apply-migrations --yes`, then rescope. The server default TTL applies.');}@@ -848,13 +853,18 @@ async function runRescope(rawArgs: string[], clientParser?: (args: string[]) =>if (target.kind === 'client') {const clientId = target.clientId;const parsedClient = clientParser ? clientParser(command.args) : parseClientRescopeArgs(clientId, command.args);- const bindLater = async () => bindCredential(engine, { kind: 'client', id: clientId }, binding.patch!, { dryRun });+ const bindLater = async () => {+ const bound = await bindCredential(engine, { kind: 'client', id: clientId }, binding.patch!, { dryRun });+ auditReadsUnscoped(bound, `OAuth client ${clientId}`, dryRun);+ return bound;+ };return rescopeClientWith(engine, clientId, parsedClient, bindLater);}const tokenArgv = command.kind === 'bare' ? [command.name, ...command.args] : command.args;const parsed = parseRescopeTokenArgs(tokenArgv);const result = await rescopeLegacyToken(engine, parsed);const bound = await bindCredential(engine, { kind: 'token', id: result.id }, binding.patch, { dryRun });+ auditReadsUnscoped(bound, `token ${result.name}`, dryRun);printTokenRescope(result, parsed.json, bound);});} catch (error) {@@ -871,6 +881,11 @@ async function runRescope(rawArgs: string[], clientParser?: (args: string[]) =>}}+/** GST-363: every grant or removal of --reads-unscoped lands in the access-reads-unscoped audit trail. */+function auditReadsUnscoped(b: BindingResult, credential: string, dryRun: boolean): void {+ if (b.reads_unscoped !== undefined && b.changed && !dryRun) logReadsUnscopedChange({ credential, reads_unscoped: b.reads_unscoped, by: 'gbrain auth' });+}+const CLIENT_NOT_FOUND_FIX = {argv: ['gbrain', 'auth', 'clients', '--json'], consent: [], actor: 'agent' as const, requires_exclusive: false,why: 'Read-only: lists the OAuth clients registered on this brain so the call can be retried with an existing client id. No grants or tokens changed.',@@ -1295,7 +1310,7 @@ Admin dashboard login (running HTTP server):This does not create an MCP bearer token. See docs/mcp/DEPLOY.md.Usage:- gbrain auth create <name> [--takes-holders world,garry,brain] [--scopes read,write] [--min-trust <tier>] [--member <id>]+ gbrain auth create <name> [--takes-holders world,garry,brain] [--scopes read,write] [--min-trust <tier>] [--member <id>] [--reads-unscoped --yes]Create a legacy bearer token. v0.28: --takes-holderssets the per-token allow-list for the takes.holderfield (default: ["world"]). MCP-bound calls to@@ -1307,6 +1322,9 @@ Usage:return rows below that trust tier (${TRUST_TIERS.join(', ')});memory_confirm in --scopes lets the token confirmmemory as you (local CLI only; never via admin API)+ On a brain that serves several people a new token needs+ --member <id>, or --reads-unscoped --yes to read every+ page no rule restricts on purpose (credential_scope_required)gbrain auth set-min-trust <client|token> <tier|none> Set or clear the read floor of an OAuth client (id)or legacy token (id or name). Local CLI only.gbrain auth list [--json] List all tokens (id, scopes, usage, private pages)@@ -1370,6 +1388,8 @@ Usage:--token-endpoint-auth-method <method> (v0.41.3+; client_secret_post | client_secret_basic | none;'none' = public PKCE-only client, no secret minted)--member <id> / --may-act-for <list> Bind the client to a member (see auth rescope)+ --reads-unscoped --yes Read unscoped on a brain that serves several people+ (without it or --member, refused: see auth create)--bound-tools <tool1,tool2> Bind submit_agent to an allow-list of tools--bound-source <id> Bind submit_agent jobs to a source id--bound-brain <id> Bind submit_agent jobs to a brain iddiff --git a/src/commands/doctor/checks/shared-stdio-binding.ts b/src/commands/doctor/checks/shared-stdio-binding.tsnew file mode 100644index 0000000000..0b7b7a6803--- /dev/null+++ b/src/commands/doctor/checks/shared-stdio-binding.ts@@ -0,0 +1,43 @@+/**+ * GST-363 (PR 2): shared_stdio_binding. config mcp.stdio_member binds every stdio session on this host to one member,+ * so a harness several people talk to (OpenClaw or Hermes, found by sharedStdioHarness) then reads as that member,+ * private pages included, for whoever is asking it. Fails when the key is set and such a harness is installed, with the+ * unset command as the fix; ok when the key is set and no shared harness is installed; not applicable while it is unset.+ */+import type { Check } from '../../doctor.ts';+import { agentFix, checkError, infoCheck } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { stdioMemberId } from '../../../core/access/caller.ts';+import { sharedStdioHarness } from '../../setup-serves.ts';++const NAME = 'shared_stdio_binding';++async function runSharedStdioBinding(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ try {+ const member = await stdioMemberId(connectedEngine(ctx));+ if (!member) {+ checks.push(infoCheck(NAME, 'Not applicable: config mcp.stdio_member is unset, so no stdio session on this host reads as a member.', 'not_applicable'));+ return checks;+ }+ const harness = sharedStdioHarness();+ if (!harness) {+ checks.push({ name: 'shared_stdio_binding', status: 'ok', details: { stdio_member: member, shared_harness: null },+ message: `Every stdio session on this host reads as ${member} (config mcp.stdio_member), and no harness several people talk to (OpenClaw, Hermes) is installed here.` });+ return checks;+ }+ checks.push({ name: 'shared_stdio_binding', status: 'fail', details: { stdio_member: member, shared_harness: harness },+ message: `config mcp.stdio_member binds every stdio session on this host to ${member}, and ${harness} is installed here, so ${harness} reads as ${member}, private pages included, for whoever is asking it.`,+ fix: agentFix(['gbrain', 'config', 'unset', 'mcp.stdio_member'], `Unbinds stdio on this host, so ${harness} stops reading as ${member}. Ask the user first: a harness only ${member} uses then reads unbound until it gets its own key.`, NAME,+ { ask_user: true, docs: 'docs/guides/setup.md#a-brain-that-serves-several-people' }) });+ } catch (error) {+ checks.push(checkError(NAME, `run ${NAME}`, error));+ }+ return checks;+}++export const sharedStdioBindingEntry: DoctorEntry = {+ name: 'shared_stdio_binding',+ emits: ['shared_stdio_binding'],+ run: runSharedStdioBinding,+};diff --git a/src/commands/doctor/checks/unscoped-shared-reads.ts b/src/commands/doctor/checks/unscoped-shared-reads.tsnew file mode 100644index 0000000000..d8200d6801--- /dev/null+++ b/src/commands/doctor/checks/unscoped-shared-reads.ts@@ -0,0 +1,52 @@+/**+ * GST-363 (PR 2): unscoped_shared_reads. On a brain that serves several people (config access.serves, else two or+ * more enabled members), every remote read through a credential bound to nobody is refused (requester_scope_required)+ * once its 14-day grace ends, or at once for a credential created after the brain started serving several people.+ * Fails while any live credential is bound to nobody, naming each with its state, its grace end and the command that+ * binds it; a credential the operator let read unscoped on purpose (--reads-unscoped) is listed as info. Warns+ * instead of failing while access.requester_scope_enforce is false (hosted). Not applicable on a one-person brain.+ */+import type { Check } from '../../doctor.ts';+import { agentFix, checkError, infoCheck } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { unscopedConnections } from '../../../core/access/requester-scope.ts';++const NAME = 'unscoped_shared_reads';++async function runUnscopedSharedReads(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const checks: Check[] = [];+ try {+ const found = await unscopedConnections(engine);+ if (!found) {+ checks.push(infoCheck(NAME, 'Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).', 'not_applicable'));+ return checks;+ }+ const optedOut = found.connections.filter(c => c.state === 'reads_unscoped');+ const pending = found.connections.filter(c => c.state !== 'reads_unscoped');+ const optedLine = optedOut.length ? ` Reading unscoped on purpose (--reads-unscoped): ${optedOut.map(c => c.connection).join(', ')}.` : '';+ if (!pending.length) {+ checks.push({ name: 'unscoped_shared_reads', status: 'ok', details: { connections: found.connections, enforce: found.serves.enforce, since: found.serves.since },+ message: `This brain serves several people, and every live credential is bound to a member or an audience.${optedLine}` });+ return checks;+ }+ const first = pending[0]!;+ checks.push({ name: 'unscoped_shared_reads', status: found.serves.enforce ? 'fail' : 'warn',+ details: { connections: found.connections, enforce: found.serves.enforce, since: found.serves.since },+ message: `This brain serves several people, but ${pending.length} credential(s) are bound to nobody: `+ + `${pending.map(c => `${c.connection} (${c.state}${c.refuses_at ? ` until ${c.refuses_at}` : ''})`).join(', ')}. `+ + (found.serves.enforce ? 'Their reads are refused with requester_scope_required once the grace ends.' : 'Enforcement is off (access.requester_scope_enforce false), so they read every page no rule restricts, for whoever is asking.')+ + optedLine,+ fix: agentFix(first.argv, `Binds ${first.connection} to the person it serves. Ask the user which member it is (gbrain access member list); a team that shares everything may use --reads-unscoped --yes instead.`, NAME,+ { ask_user: true, docs: 'docs/guides/write-refusals.md#requester_scope_required' }) });+ } catch (error) {+ checks.push(checkError(NAME, `run ${NAME}`, error));+ }+ return checks;+}++export const unscopedSharedReadsEntry: DoctorEntry = {+ name: 'unscoped_shared_reads',+ emits: ['unscoped_shared_reads'],+ run: runUnscopedSharedReads,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex caa61be819..ab06360871 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -143,6 +143,8 @@ import { ghostPagesEntry } from './checks/ghost-pages.ts';import { memberAccessEntry } from './checks/member-access.ts';import { folderAccessEntry } from './checks/folder-access.ts';import { unlabeledPeopleFoldersEntry } from './checks/unlabeled-people-folders.ts';+import { unscopedSharedReadsEntry } from './checks/unscoped-shared-reads.ts';+import { sharedStdioBindingEntry } from './checks/shared-stdio-binding.ts';import { sharedAgentAccessEntry } from './checks/shared-agent-access.ts';import { ownerReadsRestrictedEntry } from './checks/owner-reads-restricted.ts';import { accessLineageEntry } from './checks/access-lineage.ts';@@ -231,6 +233,8 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [memberAccessEntry,folderAccessEntry,unlabeledPeopleFoldersEntry,+ unscopedSharedReadsEntry,+ sharedStdioBindingEntry,sharedAgentAccessEntry,ownerReadsRestrictedEntry,accessLineageEntry,diff --git a/src/commands/serve-http-api-keys.ts b/src/commands/serve-http-api-keys.tsindex 2892224a18..422de56799 100644--- a/src/commands/serve-http-api-keys.ts+++ b/src/commands/serve-http-api-keys.ts@@ -20,6 +20,7 @@ import { ALLOWED_SCOPES_LIST, isScope, localCliOnlyScopeViolation } from '../corimport { isValidSourceId } from '../core/source-id.ts';import { isValidHolder } from '../core/takes-fence.ts';import { mintLegacyToken, revokeLegacyTokenById, TOKEN_ID_RE } from '../core/token-mint.ts';+import { assertCredentialScoped } from '../core/access/requester-scope.ts';export const API_KEY_NAME_MAX = 128;export const API_KEY_DEFAULT_SCOPES: readonly string[] = ['read', 'write'];@@ -142,6 +143,7 @@ export function mountAdminApiKeys(app: Express, requireAdmin: RequestHandler, enlet request: ApiKeyMintRequest;try {request = await parseApiKeyMintRequest(engine, req.body);+ await assertCredentialScoped(engine, null, 'token', request.name);} catch (e) {sendError(res, 400, e);return;diff --git a/src/commands/setup-serves.ts b/src/commands/setup-serves.tsindex 37bdd1d777..28e76604ff 100644--- a/src/commands/setup-serves.ts+++ b/src/commands/setup-serves.ts@@ -14,7 +14,7 @@* 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.*/-import { existsSync } from 'node:fs';+import { closeSync, existsSync, openSync, readSync } from 'node:fs';import { homedir } from 'node:os';import { join } from 'node:path';import { openclawStateDir } from '../core/setup/brain-first.ts';@@ -27,14 +27,26 @@ export interface ServesFlags { serves?: 'one' | 'several'; members?: string; mem/** 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 }-/** A harness installed on this host whose stdio sessions serve several conversations (OpenClaw, Hermes), or null. */+/**+ * A harness installed on this host whose stdio sessions serve several conversations (OpenClaw, Hermes), or null.+ * A `hermes` on PATH counts only as a script (the Hermes agent's launcher): React Native ships a compiled JavaScript+ * engine under the same name.+ */export function sharedStdioHarness(): string | null {- const onPath = (bin: string) => { try { return !!Bun.which(bin, { PATH: process.env.PATH ?? '' }); } catch { return false; } };- if (onPath('openclaw') || existsSync(openclawStateDir())) return 'OpenClaw';- if (onPath('hermes') || existsSync(process.env.HERMES_HOME?.trim() || join(homedir(), '.hermes'))) return 'Hermes';+ const which = (bin: string) => { try { return Bun.which(bin, { PATH: process.env.PATH ?? '' }); } catch { return null; } };+ if (which('openclaw') || existsSync(openclawStateDir())) return 'OpenClaw';+ if (isScript(which('hermes')) || existsSync(process.env.HERMES_HOME?.trim() || join(homedir(), '.hermes'))) return 'Hermes';return null;}+function isScript(path: string | null): boolean {+ if (!path) return false;+ try {+ const fd = openSync(path, 'r');+ try { const head = Buffer.alloc(2); return readSync(fd, head, 0, 2, 0) === 2 && head.toString('latin1') === '#!'; } finally { closeSync(fd); }+ } catch { return false; }+}+export interface ProofLine { member: string; own: number; leaked: string[] }export interface ServesOutcome {mode: 'one' | 'several';@@ -158,7 +170,7 @@ export function servesApply(flags: ServesFlags, launcher: string, harness: strinconst 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, owner: null, stdio_member: status?.stdio_member ?? null } : status;+ 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 } : {}),diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex 4cf5f4e4d2..c0d56fb624 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -959,6 +959,7 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {await (await import('../core/temporal-edges-upgrade-notice.ts')).printTemporalEdgesUpgradeNotice(engine);// #5575 memory trust: [AGENT] ask_user while unclaimed sources hold legacy rows; never claims or scans (best-effort).await (await import('../core/trust/claim-notice.ts')).printTrustClaimUpgradeNotice(engine);+ await (await import('../core/access/requester-scope.ts')).printUnscopedReadsUpgradeNotice(engine); // GST-363: credentials bound to nobody on a several-people brain// Ambient-writeback consent ask (WP8): one-shot for EXISTING installs// upgrading into the feature. Personal brains only; double-gated ondiff --git a/src/core/access/audience.ts b/src/core/access/audience.tsindex 66df6c3b78..90d115f4c8 100644--- a/src/core/access/audience.ts+++ b/src/core/access/audience.ts@@ -104,7 +104,11 @@ export interface AudienceAuditEvent {op: string;audience: string[];outcome: 'accepted' | 'on_behalf_of_invalid_audience' | 'on_behalf_of_not_permitted' | 'on_behalf_of_unknown_member' | 'on_behalf_of_in_arguments'- | 'actor_not_attested' | 'actor_unlinked';+ | 'actor_not_attested' | 'actor_unlinked'+ /** GST-363: a read from a connection bound to nobody on a brain that serves several people, refused before any work. */+ | 'requester_scope_required'+ /** GST-363: the same read when whom the brain serves could not be read (even after one re-read): refused as retryable. */+ | 'requester_scope_unknown';/** GST-359 C1: an attested actor's system, the id it named (only when well-formed) and a refusal's reason. */actor?: { system: string; external_id?: string; reason?: string };}diff --git a/src/core/access/caller.ts b/src/core/access/caller.tsindex 2034fde5ab..dfb3423de4 100644--- a/src/core/access/caller.ts+++ b/src/core/access/caller.ts@@ -23,6 +23,7 @@ import { currentCallerAccess } from '../search/private-visibility.ts';import { edgeTrimSql } from '../edge-whitespace.ts';import { GUEST, STDIO_MAY_ACT_FOR_KEY, mayActForCovers, singleMemberAudience, type AudiencePrincipal } from './audience.ts';import { audienceMemberIds, parseMayActFor } from './members.ts';+import { stdioBindRoute } from './stdio-bind-route.ts';/** Config key binding a local stdio MCP server to one member. */export const STDIO_MEMBER_KEY = 'mcp.stdio_member';@@ -345,5 +346,5 @@ export async function stdioAccessView(engine: BrainEngine, registered?: string):if (identity.length) return accessView(identity, 'stdio_config');return accessView([], 'none', null, configured? `mcp.stdio_member names "${configured}", which is not an enabled member, so this server reads no page that names readers.`- : `${UNBOUND_NOTE} Bind it with gbrain config set ${STDIO_MEMBER_KEY} <member>.`);+ : `${UNBOUND_NOTE} ${stdioBindRoute().text}`);}diff --git a/src/core/access/members.ts b/src/core/access/members.tsindex 1c87d2277b..53b3f808e0 100644--- a/src/core/access/members.ts+++ b/src/core/access/members.ts@@ -408,8 +408,9 @@ export function parseMemberFlag(raw: string): string | null {/** GST-359 C1: attestActor names the system whose actor header this credential may send (null clears it, attestOps and attestRead). *//** GST-1113: attestSources lists the scope sources an attested memory_write may name (null clears it; access/attest-sources.ts). */-export interface BindingPatch { member?: string | null; mayActFor?: string[] | null; attestActor?: string | null; attestOps?: string[] | null; attestSources?: string[] | null; attestRead?: 'person' | 'scope' | null }-export interface BindingResult { member: string | null; may_act_for: string[] | null; attest_actor?: string; attest_ops?: string[] | null; attest_sources?: string[] | null; attest_read?: 'person' | 'scope' | null; changed: boolean }+/** GST-363: readsUnscoped true sets reads_unscoped (kept when already set), false clears it; undefined leaves it. */+export interface BindingPatch { member?: string | null; mayActFor?: string[] | null; attestActor?: string | null; attestOps?: string[] | null; attestSources?: string[] | null; attestRead?: 'person' | 'scope' | null; readsUnscoped?: boolean }+export interface BindingResult { member: string | null; may_act_for: string[] | null; attest_actor?: string; attest_ops?: string[] | null; attest_sources?: string[] | null; attest_read?: 'person' | 'scope' | null; reads_unscoped?: boolean; changed: boolean }function attestRefused(message: string, suggestion: string): OperationError {return opError('invalid_params', message, suggestion, { why: 'Only a credential bound to no member that authenticates as itself (a client-credentials client with a secret, or a legacy token) may name the people a trusted system serves.' });@@ -427,8 +428,9 @@ export async function bindCredential(engine: BrainEngine, target: { kind: 'token// GST-1113: lock the credential row first and read it under the lock (grant rescopes lock it first too), so a// concurrent rescope commits before or after this change, never between its checks and its write.return engine.transaction(async tx => {- const [before] = await tx.executeRaw<{ member_id: string | null; may_act_for: string[] | null; attest_actor: string | null; attest_ops: string[] | null; attest_sources: string[] | null; attest_read: 'person' | 'scope' | null; grant_types?: string[] | null; confidential?: boolean }>(- `SELECT member_id, may_act_for, attest_actor, attest_ops, attest_sources, attest_read${target.kind === 'client' ? ', grant_types, client_secret_hash IS NOT NULL AS confidential' : ''} FROM ${table} WHERE ${key} = $1 FOR UPDATE`, [target.id]);+ const unscopedPatch = patch.readsUnscoped !== undefined;+ const [before] = await tx.executeRaw<{ member_id: string | null; may_act_for: string[] | null; attest_actor: string | null; attest_ops: string[] | null; attest_sources: string[] | null; attest_read: 'person' | 'scope' | null; grant_types?: string[] | null; confidential?: boolean; reads_unscoped?: unknown }>(+ `SELECT member_id, may_act_for, attest_actor, attest_ops, attest_sources, attest_read${target.kind === 'client' ? ', grant_types, client_secret_hash IS NOT NULL AS confidential' : ''}${unscopedPatch ? ', reads_unscoped' : ''} FROM ${table} WHERE ${key} = $1 FOR UPDATE`, [target.id]);if (!before) {throw opError('invalid_params', `No ${target.kind === 'token' ? 'token' : 'OAuth client'} "${target.id}" exists.`,target.kind === 'token' ? 'List tokens with gbrain auth list.' : 'List clients with gbrain auth clients --json.');@@ -469,7 +471,14 @@ export async function bindCredential(engine: BrainEngine, target: { kind: 'token[target.id, member, mayActFor, attestActor, attestOps, attestSources, attestRead ?? null]);}}- return { member, may_act_for: mayActFor ?? null, ...(attestActor ? { attest_actor: attestActor, attest_ops: attestOps ?? null, attest_sources: attestSources ?? null, attest_read: attestRead ?? null } : {}), changed };+ // GST-363: the opt-out records when it was granted; restating it keeps that time.+ const readsUnscoped = unscopedPatch ? patch.readsUnscoped! : undefined;+ if (unscopedPatch && readsUnscoped !== (before.reads_unscoped != null)) {+ changed = true;+ if (!opts.dryRun) await tx.executeRaw(`UPDATE ${table} SET reads_unscoped = CASE WHEN $2::boolean THEN now() ELSE NULL END WHERE ${key} = $1`, [target.id, readsUnscoped]);+ }+ return { member, may_act_for: mayActFor ?? null, ...(attestActor ? { attest_actor: attestActor, attest_ops: attestOps ?? null, attest_sources: attestSources ?? null, attest_read: attestRead ?? null } : {}),+ ...(readsUnscoped !== undefined ? { reads_unscoped: readsUnscoped } : {}), changed };});}diff --git a/src/core/access/requester-scope.ts b/src/core/access/requester-scope.tsnew file mode 100644index 0000000000..7a234a0a93--- /dev/null+++ b/src/core/access/requester-scope.ts@@ -0,0 +1,295 @@+/**+ * GST-363: on a brain that serves several people (two or more enabled members, or config access.serves = several;+ * ServesPolicy), a remote read must say whom it reads for. A connection does when it is bound to a member (the owner+ * included), when a shared agent names its audience on the call (may_act_for), or when a trusted system attests the+ * person (exempt in dispatch); the brain operator may also let one credential read unscoped on purpose+ * (reads_unscoped). Every other remote read is refused with requester_scope_required before any work.+ *+ * Deny by default: every operation not marked mutating: true, and every read-scope one (think), is covered except the+ * short list below, which reads no+ * page (the caller's own identity and the brain's health) or, for a token fenced to its own jobs, only its own jobs.+ * test/requester-scope.test.ts fails when a new read operation is neither refused nor listed here.+ *+ * Grace: a connection that existed when the brain started serving several people (config access.serves_since, set+ * once by the v308 trigger, or the upgrade that added it) keeps reading for 14 days with an in-band notice+ * (_meta.access.requester_scope); a stdio server and a credential with no creation time count as such. A credential+ * created after that point is refused at once. Hosted brains set access.requester_scope_enforce = false until their+ * control plane binds each connection to a member: every unscoped read then carries the notice and nothing is refused.+ * Writes are out of scope. Everything is database state, so a repo-less or keyless brain behaves the same.+ */+import type { BrainEngine } from '../engine.ts';+import { opError, type AuthInfo, type Operation, type OperationError } from '../ops/contract.ts';+import type { Action } from '../agent-output.ts';+import { agentBlock } from '../agent-markers.ts';+import { readServesPolicy, type CallerAccess, type ServesPolicy } from '../search/private-visibility.ts';+import type { BindingPatch } from './members.ts';+import { hostFix, hostOnlyError } from '../ops/op-fix.ts';+import { hasScope } from '../scope.ts';+import { createAuditWriter } from '../audit/audit-writer.ts';+import { credentialScopeFields } from './token-binding.ts';+import { stdioBindRoute } from './stdio-bind-route.ts';++/**+ * Read operations that read no page: the caller's own identity, the brain's identity and health, search mode names,+ * and the read-scope operations that only manage the caller's own shared-skills enrollment and tool catalog.+ */+export const REQUESTER_SCOPE_EXEMPT: ReadonlySet<string> = new Set(['whoami', 'get_brain_identity', 'get_status_snapshot', 'search_modes', 'get_health',+ 'join_brain', 'leave_brain', 'sync_brain_skills', 'request_tools']);+/** Exempt only for a credential without admin scope, which sees only the jobs it owns (ops/jobs.ts agentOwnerFence). */+export const OWN_JOB_OPS: ReadonlySet<string> = new Set(['get_job', 'wait_job']);+export const REQUESTER_SCOPE_GRACE_DAYS = 14;+const GRACE_SECONDS = REQUESTER_SCOPE_GRACE_DAYS * 24 * 3600;+/** Whether `op` needs a scoped requester on a brain that serves several people. */+export function requiresRequesterScope(op: Pick<Operation, 'name' | 'mutating' | 'scope'> | undefined, auth?: Pick<AuthInfo, 'scopes'>): boolean {+ if (!op || (op.mutating === true && (op.scope ?? 'read') !== 'read') || REQUESTER_SCOPE_EXEMPT.has(op.name)) return false;+ return !(OWN_JOB_OPS.has(op.name) && auth && !hasScope(auth.scopes ?? [], 'admin'));+}++/** The in-band notice an unscoped read carries while it is still answered. */+export interface RequesterScopeNotice {+ state: 'grace' | 'not_enforced';+ connection: string;+ refuses_at: string | null;+ message: string;+ fix: Action;+}++type ScopeAuth = Pick<AuthInfo, 'clientName' | 'readsUnscoped' | 'createdAt' | 'scopes'> & { principal?: { kind: string; id: string } };++type Inputs = NonNullable<Action['inputs']>;++const MEMBER_INPUTS: Inputs = [{ name: 'MEMBER', how: 'The member this connection serves; gbrain access member list on the brain host names them. Ask the user which person it is.' }];++interface Connection { handle: string; argv: string[]; inputs: Inputs; check?: string[]; optOut?: string[]; route?: string }++function connectionOf(auth: Pick<ScopeAuth, 'clientName' | 'principal'> | undefined): Connection {+ const principal = auth?.principal;+ if (principal?.kind === 'legacy_token') {+ const target = auth?.clientName ? ['--token', auth.clientName] : ['--id', principal.id];+ return { handle: `token ${auth?.clientName ?? principal.id}`, argv: ['gbrain', 'auth', 'rescope', ...target, '--member', '<MEMBER>'], inputs: MEMBER_INPUTS,+ check: ['gbrain', 'access', 'check', ...target], optOut: ['gbrain', 'auth', 'rescope', ...target, '--reads-unscoped', '--yes'] };+ }+ if (principal?.kind === 'oauth_client') {+ return { handle: `OAuth client ${principal.id}`, argv: ['gbrain', 'auth', 'rescope', '--client', principal.id, '--member', '<MEMBER>'], inputs: MEMBER_INPUTS,+ check: ['gbrain', 'access', 'check', '--client', principal.id], optOut: ['gbrain', 'auth', 'rescope', '--client', principal.id, '--reads-unscoped', '--yes'] };+ }+ const route = stdioBindRoute();+ return { handle: 'this stdio server', argv: route.argv, inputs: [...route.inputs, ...MEMBER_INPUTS], route: route.text };+}++type Transport = 'stdio' | 'http' | undefined;++function why(policy: ServesPolicy): string {+ return policy?.from === 'config' ? 'config access.serves is several' : 'it has two or more enabled members';+}++function alternatives(c: Connection): string {+ if (!c.optOut) return `On the brain host (gbrain access member list names the members): ${c.route}`;+ return `On the brain host, see what the connection reads with ${c.check!.join(' ')}, then bind it to the person it serves: ${c.argv.join(' ')} (gbrain access member list names the members). `+ + `A shared agent instead lists whom it may act for (--may-act-for <members>) and names the person on each call (X-Gbrain-On-Behalf-Of). `+ + `Last resort, for a team that shares everything: ${c.optOut.join(' ')} lets it read every page no rule restricts for whoever is asking.`;+}++function fixFor(c: Connection, transport: Transport): Action {+ return { ...hostFix({ remote: true, transport }, c.argv, 'Binds this connection to one member, so it reads only what that person may read.'),+ inputs: c.inputs,+ ...(c.check ? { verify: { argv: c.check } } : {}) };+}++/**+ * The requester-scope decision for one remote read, after access resolved: null when it runs as before, a notice when+ * it runs with one (grace, or enforcement off), and a thrown requester_scope_required otherwise. Attested calls never+ * reach it. `auth` carries readsUnscoped and createdAt from the verifier (credentialScopeFor fills them otherwise).+ */+export function requesterScopeGate(op: Pick<Operation, 'name' | 'mutating'> | undefined, access: Partial<CallerAccess>, auth: ScopeAuth | undefined,+ via: string | undefined, nowMs = Date.now()): RequesterScopeNotice | null {+ if (!requiresRequesterScope(op, auth)) return null;+ const serves = access.remotePolicy?.serves;+ const unknown = access.remotePolicy?.servesUnknown === true;+ if (!serves?.several && !unknown) return null;+ const transport: Transport = via === 'http' ? 'http' : 'stdio';+ if (boundToSomeone(access)) return null;+ if (auth?.readsUnscoped) return null;+ const c = connectionOf(auth);+ if (unknown || !serves) throw requesterScopeUnknown(op!.name, c);+ const created = auth?.createdAt ?? null;+ const since = serves.since;+ const refusesAt = since === null ? null : since + GRACE_SECONDS;+ const now = Math.floor(nowMs / 1000);+ if (!serves.enforce) {+ return { state: 'not_enforced', connection: c.handle, refuses_at: null, fix: fixFor(c, transport),+ message: `This brain serves several people (${why(serves)}) and ${c.handle} is bound to nobody, so it reads every page no rule restricts for whoever is asking. ${alternatives(c)}` };+ }+ const old = since !== null && (created === null || created <= since);+ if (old && refusesAt !== null && now < refusesAt) {+ const date = new Date(refusesAt * 1000).toISOString();+ return { state: 'grace', connection: c.handle, refuses_at: date, fix: fixFor(c, transport),+ message: `This brain serves several people (${why(serves)}) and ${c.handle} is bound to nobody. From ${date} its reads are refused (requester_scope_required). ${alternatives(c)}` };+ }+ throw requesterScopeRequired(op!.name, c, serves, transport, old ? 'grace_ended' : since === null ? 'since_unknown' : 'created_after');+}++function boundToSomeone(access: Partial<CallerAccess>): boolean {+ return !!access.audience?.length || !!access.actor || (access.identity ?? []).some(p => p.startsWith('member:'));+}++/**+ * The access a requester-scope decision reads: unchanged unless whom the brain serves could not be read (servesUnknown)+ * and the call is from a connection bound to nobody, which gets one targeted re-read of the serves keys. A second+ * failure leaves it unknown, and requesterScopeGate refuses (requester_scope_unknown) rather than read it as one person.+ */+export async function withServesReread<T extends Partial<CallerAccess>>(engine: Pick<BrainEngine, 'executeRaw'>, access: T, auth: Pick<ScopeAuth, 'readsUnscoped'> | undefined): Promise<T> {+ const policy = access.remotePolicy;+ if (!policy?.servesUnknown || boundToSomeone(access) || auth?.readsUnscoped) return access;+ try {+ return { ...access, remotePolicy: { ...policy, serves: await readServesPolicy(engine), servesUnknown: false } };+ } catch {+ return access;+ }+}++function requesterScopeUnknown(op: string, c: Connection): OperationError {+ return opError('requester_scope_unknown',+ `Whether this brain serves one person or several could not be read (its config read failed twice), so ${op} from ${c.handle}, which is bound to no member, was refused and nothing was read.`,+ 'Retry the same call in a few seconds. If it keeps failing, the brain host\'s operator checks the database with gbrain doctor --json.',+ { retryable: true, detail: 'retry_after_ms=2000',+ fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'provider', requires_exclusive: false,+ why: 'Nothing was read. Repeat the same call after about 2 s (retry_after_ms=2000); this read-only command shows whether the database is answering.' } });+}++function requesterScopeRequired(op: string, c: Connection, serves: ServesPolicy, transport: Transport, reason: string): OperationError {+ const e = hostOnlyError({ remote: true, transport }, 'requester_scope_required',+ `This brain serves several people (${why(serves)}) and ${c.handle} is bound to nobody, so ${op} was refused and nothing was read.`,+ c.argv, 'Binds this connection to one member, so it reads only what that person may read.',+ { suggestion: `The fix runs on the brain host. ${alternatives(c)}`, reason });+ e.fix = fixFor(c, transport);+ return e;+}++/**+ * readsUnscoped and createdAt for `auth`: the verifier's values when it set them (no query), else a live lookup from+ * the stored principal (an agent job's delegated credential). Unreadable or unknown: not opted out, creation unknown.+ */+export async function credentialScopeFor<T extends ScopeAuth>(engine: Pick<BrainEngine, 'executeRaw'>, auth: T): Promise<T> {+ if (auth.readsUnscoped !== undefined) return auth;+ const principal = auth.principal;+ try {+ if (principal?.kind === 'legacy_token') {+ const [row] = await engine.executeRaw<{ reads_unscoped: unknown; created_at: unknown }>('SELECT reads_unscoped, created_at FROM access_tokens WHERE id::text = $1 AND revoked_at IS NULL', [principal.id]);+ return { ...auth, ...credentialScopeFields(row?.reads_unscoped, row?.created_at) };+ }+ if (principal?.kind === 'oauth_client') {+ const [row] = await engine.executeRaw<{ reads_unscoped: unknown; client_id_issued_at: unknown }>('SELECT reads_unscoped, client_id_issued_at FROM oauth_clients WHERE client_id = $1 AND deleted_at IS NULL', [principal.id]);+ return { ...auth, ...credentialScopeFields(row?.reads_unscoped, row?.client_id_issued_at) };+ }+ } catch { /* unreadable: not opted out, creation unknown */ }+ return { ...auth, readsUnscoped: false, createdAt: null };+}++/**+ * GST-363: creating a credential bound to nobody on a brain that serves several people is refused+ * (credential_scope_required): it names a member, a may_act_for audience, the attest right, or --reads-unscoped.+ * Off while enforcement is off (hosted), like the read refusal.+ */+export async function assertCredentialScoped(engine: Pick<BrainEngine, 'executeRaw'>, patch: BindingPatch | null, kind: 'token' | 'client', name: string): Promise<void> {+ if (patch?.member || patch?.mayActFor?.length || patch?.attestActor || patch?.readsUnscoped) return;+ const serves = await readServesPolicy(engine);+ if (!serves.several || !serves.enforce) return;+ const create = kind === 'token' ? ['gbrain', 'auth', 'create', name] : ['gbrain', 'auth', 'register-client', name];+ throw opError('credential_scope_required',+ `This brain serves several people (${why(serves)}), so the ${kind === 'token' ? 'token' : 'OAuth client'} ${name} was not created bound to nobody; nothing was created.`,+ `Bind it to the person it serves: ${create.join(' ')} --member followed by that member's id (gbrain access member list names the members). A shared agent passes --may-act-for <members>; --reads-unscoped --yes creates one that reads every page no rule restricts for any asker.`,+ { fix: { argv: [...create, '--member', '<MEMBER>'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Creates the credential bound to one member, so it reads only what that person may read.',+ inputs: [{ name: 'MEMBER', how: 'The member it serves; gbrain access member list names them. Ask the user which person it is.' }],+ verify: { argv: ['gbrain', 'access', 'member', 'list', '--json'] } } });+}++/**+ * whoami's view of the requester-scope gate for the calling connection (whoami itself is exempt, so an unbound+ * connection can learn why its reads are refused): not_required on a one-person brain, scoped, reads_unscoped, unknown+ * when whom the brain serves could not be read (even after one re-read), or the+ * state a read would get, with the command that binds the connection.+ */+export async function requesterScopeView(engine: Pick<BrainEngine, 'executeRaw'>, access: Partial<CallerAccess>, auth: ScopeAuth | undefined, transport: string | undefined): Promise<{ state: string; refuses_at?: string | null; reason?: string; argv?: string[] }> {+ const policy = access.remotePolicy;+ if (!policy?.serves?.several && !policy?.servesUnknown) return { state: 'not_required' };+ if (boundToSomeone(access)) return { state: 'scoped' };+ const scoped = auth ? await credentialScopeFor(engine, auth) : undefined;+ if (scoped?.readsUnscoped) return { state: 'reads_unscoped' };+ const resolved = await withServesReread(engine, access, scoped);+ if (!resolved.remotePolicy?.servesUnknown && !resolved.remotePolicy?.serves?.several) return { state: 'not_required' };+ try {+ const notice = requesterScopeGate({ name: 'search', mutating: false }, resolved, scoped, transport);+ return { state: notice!.state, refuses_at: notice!.refuses_at, argv: notice!.fix.argv };+ } catch (e) {+ const err = e as OperationError;+ if (err.code === 'requester_scope_unknown') return { state: 'unknown' };+ return { state: 'refused', reason: err.reason, argv: err.fix?.argv };+ }+}++/** One credential bound to nobody on a brain that serves several people, as doctor and post-upgrade list it. */+export interface UnscopedConnection {+ connection: string;+ /** grace: still reads until refuses_at; refused: every read is refused; not_enforced: hosted, reads with a notice; reads_unscoped: opted out on purpose. */+ state: 'grace' | 'refused' | 'not_enforced' | 'reads_unscoped';+ refuses_at: string | null;+ argv: string[];+}++/**+ * GST-363: whom the brain serves and every live credential bound to nobody (no member, no may_act_for audience, no+ * attest right), each with the state the requester-scope gate gives its reads and the one command that binds it.+ * Null when the brain serves one person.+ */+export async function unscopedConnections(engine: Pick<BrainEngine, 'executeRaw'>, nowMs = Date.now()): Promise<{ serves: ServesPolicy; connections: UnscopedConnection[] } | null> {+ const serves = await readServesPolicy(engine);+ if (!serves.several) return null;+ const unbound = 'member_id IS NULL AND COALESCE(cardinality(may_act_for), 0) = 0 AND attest_actor IS NULL';+ const [tokens, clients] = await Promise.all([+ engine.executeRaw<{ id: string; name: string; created: unknown; reads_unscoped: unknown }>(`SELECT id::text AS id, name, created_at AS created, reads_unscoped FROM access_tokens WHERE revoked_at IS NULL AND ${unbound} ORDER BY name, id`),+ engine.executeRaw<{ id: string; name: string; created: unknown; reads_unscoped: unknown }>(`SELECT client_id AS id, client_name AS name, client_id_issued_at AS created, reads_unscoped FROM oauth_clients WHERE deleted_at IS NULL AND ${unbound} ORDER BY client_id`),+ ]);+ const refusesAt = serves.since === null ? null : serves.since + GRACE_SECONDS;+ const now = Math.floor(nowMs / 1000);+ const entry = (c: Connection, row: { created: unknown; reads_unscoped: unknown }): UnscopedConnection => {+ const { readsUnscoped, createdAt } = credentialScopeFields(row.reads_unscoped, row.created);+ const old = serves.since !== null && (createdAt === null || createdAt <= serves.since);+ const state = readsUnscoped ? 'reads_unscoped' : !serves.enforce ? 'not_enforced' : old && refusesAt !== null && now < refusesAt ? 'grace' : 'refused';+ return { connection: c.handle, state, refuses_at: state === 'grace' ? new Date(refusesAt! * 1000).toISOString() : null, argv: c.argv };+ };+ return { serves, connections: [+ ...tokens.map(t => entry(connectionOf({ principal: { kind: 'legacy_token', id: t.id }, clientName: t.name }), t)),+ ...clients.map(c => entry(connectionOf({ principal: { kind: 'oauth_client', id: c.id } }), c)),+ ] };+}++/** `gbrain post-upgrade`: each credential whose reads are (or will be) refused, with its one command. Best effort. */+export async function printUnscopedReadsUpgradeNotice(engine: Pick<BrainEngine, 'executeRaw'>): Promise<void> {+ try {+ const found = await unscopedConnections(engine);+ const pending = found?.connections.filter(c => c.state !== 'reads_unscoped') ?? [];+ if (!found || !pending.length) return;+ console.log('');+ console.log(agentBlock({+ why: `This brain serves several people (${why(found.serves)}), and ${pending.length} connection(s) are bound to nobody. Their reads are refused (requester_scope_required) ${found.serves.enforce ? 'after the grace shown' : 'once access.requester_scope_enforce is on'}.`,+ actor: 'user',+ next: 'Relay the list below to the user. Each command runs on the brain host; MEMBER is the person the connection serves (gbrain access member list names them). A team that shares everything may mark one connection with --reads-unscoped --yes on gbrain auth rescope instead.',+ verify: 'gbrain doctor --only unscoped_shared_reads --json',+ }).trimEnd());+ for (const c of pending) console.log(` ${c.connection}: ${c.state}${c.refuses_at ? ` until ${c.refuses_at}` : ''}. Fix: ${c.argv.join(' ')}`);+ } catch { /* cosmetic; never blocks the upgrade */ }+}++/** One change to a credential's reads_unscoped, as ~/.gbrain/audit/access-reads-unscoped-YYYY-Www.jsonl records it. */+export interface ReadsUnscopedAuditEvent { ts: string; credential: string; reads_unscoped: boolean; by: string }++const audit = createAuditWriter<ReadsUnscopedAuditEvent>({ featureName: 'access-reads-unscoped', errorLabel: 'access-reads-unscoped-audit', errorTrailer: '; continuing' });++export function logReadsUnscopedChange(event: Omit<ReadsUnscopedAuditEvent, 'ts'>): void {+ audit.log({ ts: new Date().toISOString(), ...event });+}++export function readReadsUnscopedChanges(): ReadsUnscopedAuditEvent[] {+ return audit.readRecent();+}diff --git a/src/core/access/serves.ts b/src/core/access/serves.tsindex fa17daea7b..a8d326155c 100644--- a/src/core/access/serves.ts+++ b/src/core/access/serves.ts@@ -2,28 +2,35 @@* GST-363: whether a brain serves several people. A brain does when config* access.serves says `several`, or when it is unset and the brain has two or* more enabled members; an explicit `one` or `several` wins over the member- * count. `gbrain setup <harness> --serves several` writes the explicit value;- * the doctor check unlabeled_people_folders and setup's refusal read it here.- * Everything lives in the database, so a repo-less brain gets it unchanged.+ * count. The member count is the flag a trigger on access_members keeps in+ * config access.serves_derived (migration v308), which a remote request reads+ * from its config snapshot (servesPolicyFrom); `since` is when the brain first+ * served several people, which starts the unscoped-read grace.+ * `gbrain setup <harness> --serves several` writes the explicit value; the+ * doctor checks and setup's refusal read it here. Everything lives in the+ * database, so a repo-less brain gets it unchanged.*/import type { BrainEngine } from '../engine.ts';import { appliedRules } from './policy.ts';+import { SERVES_DERIVED_KEY, SERVES_KEY, SERVES_SINCE_KEY, servesPolicyFrom } from '../search/private-visibility.ts';-export const SERVES_KEY = 'access.serves';+export { SERVES_KEY };export interface ServesView {serves: 'one' | 'several';/** `config` when access.serves decided it, `members` when the enabled-member count did. */from: 'config' | 'members';enabled_members: string[];+ /** When the brain first served several people (config access.serves_since), or null. */+ since: string | null;}export async function brainServes(engine: Pick<BrainEngine, 'getConfig' | 'executeRaw'>): Promise<ServesView> {const members = (await engine.executeRaw<{ id: string }>('SELECT id FROM access_members WHERE disabled_at IS NULL AND tombstoned_at IS NULL ORDER BY id')).map(r => r.id);- const explicit = (await engine.getConfig(SERVES_KEY))?.trim();- if (explicit === 'one' || explicit === 'several') return { serves: explicit, from: 'config', enabled_members: members };- return { serves: members.length >= 2 ? 'several' : 'one', from: 'members', enabled_members: members };+ const [explicit, derived, since] = await Promise.all([SERVES_KEY, SERVES_DERIVED_KEY, SERVES_SINCE_KEY].map(k => engine.getConfig(k)));+ const policy = servesPolicyFrom({ [SERVES_KEY]: explicit ?? undefined, [SERVES_DERIVED_KEY]: derived ?? undefined });+ return { serves: policy.several ? 'several' : 'one', from: policy.from, enabled_members: members, since: since?.trim() || null };}export interface PeopleFolder { source: string; prefix: string; pages: number }diff --git a/src/core/access/stdio-bind-route.ts b/src/core/access/stdio-bind-route.tsnew file mode 100644index 0000000000..31dfbeb319--- /dev/null+++ b/src/core/access/stdio-bind-route.ts@@ -0,0 +1,19 @@+/**+ * GST-363: how to bind a stdio connection that is bound to nobody. Since per-harness binding (serve --stdio-member),+ * a harness only one person uses binds with `gbrain setup claude-code|codex --stdio-member <member>`, which writes+ * the member into that one harness entry, on PGLite and Postgres alike; setup refuses it where OpenClaw or Hermes is+ * installed. A harness several people talk to gets one member key per person over `serve --http` instead. The+ * refusal, the grace notice, the access owner hint and whoami's unbound note all read the route here.+ */+import type { Action } from '../agent-output.ts';++export interface StdioBindRoute { argv: string[]; inputs: NonNullable<Action['inputs']>; text: string }++export function stdioBindRoute(member = '<id>'): StdioBindRoute {+ return {+ argv: ['gbrain', 'setup', '<HARNESS>', '--stdio-member', '<MEMBER>'],+ inputs: [{ name: 'HARNESS', how: 'claude-code or codex, the harness only this one person uses. Never a harness several people talk to.' }],+ text: `For a harness only one person uses: gbrain setup claude-code|codex --stdio-member ${member}, which binds that one harness entry on this machine (refused where OpenClaw or Hermes is installed). `+ + `For a harness several people talk to, give each person a key over HTTP instead: gbrain serve --http with one gbrain auth create <name> --member <id> key per person.`,+ };+}diff --git a/src/core/access/token-binding.ts b/src/core/access/token-binding.tsindex 15b75c52db..e288540002 100644--- a/src/core/access/token-binding.ts+++ b/src/core/access/token-binding.ts@@ -3,15 +3,35 @@* unbound) and its stored may_act_for list. A binding to a disabled, removed* or missing member, or one that cannot be read, refuses the credential* (InvalidTokenError carrying access_member_disabled).+ * GST-363: the verifiers also carry whether the credential reads unscoped on+ * purpose and when it was created (credentialScopeFields), so the+ * requester-scope gate adds no query.*/import { InvalidTokenError } from '@modelcontextprotocol/sdk/server/auth/errors.js';import type { SqlQuery } from '../sql-query.ts';import { MemberBindingRefused, storedMayActFor, verifiedMember } from './members.ts';-export async function tokenMemberBinding(sql: SqlQuery, memberId: unknown, mayActFor: unknown): Promise<{ member: { id: string; groups: string[] } | null; mayActFor: string[] | null }> {+export async function tokenMemberBinding(sql: SqlQuery, row: { member_id?: unknown; may_act_for?: unknown; reads_unscoped?: unknown }, created: unknown):+ Promise<{ member: { id: string; groups: string[] } | null; mayActFor: string[] | null; readsUnscoped: boolean; createdAt: number | null }> {try {- return { member: await verifiedMember(sql, memberId), mayActFor: storedMayActFor(mayActFor) };+ return { member: await verifiedMember(sql, row.member_id), mayActFor: storedMayActFor(row.may_act_for), ...credentialScopeFields(row.reads_unscoped, created) };} catch (e) {throw new InvalidTokenError(e instanceof MemberBindingRefused ? e.message : 'access_member_disabled: the member binding of this credential could not be verified.');}}++/** A stored creation time as epoch seconds: a Date or timestamp string (created_at), or seconds (client_id_issued_at); null when absent or unreadable. */+export function epochSeconds(value: unknown): number | null {+ if (value == null) return null;+ if (typeof value === 'number' || typeof value === 'bigint') return Number.isFinite(Number(value)) ? Math.floor(Number(value)) : null;+ if (value instanceof Date) return Number.isFinite(value.getTime()) ? Math.floor(value.getTime() / 1000) : null;+ if (typeof value !== 'string') return null;+ if (/^\d+$/.test(value.trim())) return Number(value.trim());+ const ms = Date.parse(value);+ return Number.isFinite(ms) ? Math.floor(ms / 1000) : null;+}++/** GST-363: the AuthInfo fields the requester-scope gate reads, from a credential row's reads_unscoped and creation time. */+export function credentialScopeFields(readsUnscoped: unknown, created: unknown): { readsUnscoped: boolean; createdAt: number | null } {+ return { readsUnscoped: readsUnscoped != null, createdAt: epochSeconds(created) };+}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 590ab065e6..1b29e64e77 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1563,6 +1563,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.693.0', id: 'member_save_withdrawn_scope_gst2346', text: 'A remote `remember` onto a member\'s own page (`memory/members/<id>`) is refused `fact_withdrawn` only when that member could read what was withdrawn: a fact on its own page, its own copy withdrawn by the brain host, or for the brain owner a fact it reads. A claim withdrawn by the brain host or the owner that the member never read no longer refuses its save: the fact saves as the member\'s own active row with the same reply as a new claim. A schema migration makes the database insert guards mark a row on a member page only by that page\'s own withdrawals; a withdrawal still expires matching rows on member pages when it is made, and strikes them in the page\'s file, so an import of a member page\'s file no longer marks a row withdrawn by a withdrawal of another subject. The same holds for each item of a `remember` batch (`items`), a replay with the same `request_id`, a `replaces` and the write receipt (`get_write_request`). Trusted local saves keep the check they had.' },{ since: '0.60.694.0', id: 'owner_labels_guarded_gst2521', text: 'Labels the owner sets with `gbrain repair visibility` (or its `--readers` setter, or `gbrain repair private-labels`) now raise the page\'s label guard to operator_curated, so a later local agent write at the page\'s own tier that drops or widens them is held like a write over an owner page, with a `lower_page` item. A local write below operator_curated whose `readable_by` would leave the brain owner out of a page the owner reads now publishes with the owner kept in the readers (the rest of the narrowing applies), and its item records the requested readers. Accepting such an item (`gbrain trust confirm tp<id>`) on a page whose own tier is an agent\'s writes only the labels and keeps the agent\'s tier; on an owner page it still endorses the edit at the owner\'s tier. The guard is stored in the database (`page_label_guards`) and set only by label repairs run after the upgrade, so labels set earlier, and a managed Git brain rebuilt from a clone, start unguarded; re-running `gbrain repair visibility --slug` or `--readers` on a page that already has those labels raises the guard without changing them. The owner\'s own label writes, synced owner edits, agent narrowing that keeps the owner, and brains with `access.owner_reads_restricted` on are unchanged.' },{ since: '0.60.694.0', id: 'page_label_widening_held_gst2518', text: 'A local agent write (`put_page`, `capture`, `edit_page`, `append_page`, `revert_version`, `restore_page`) less trusted than a page that drops or widens its `visibility`, `access`, `confidentiality` or `readable_by` now publishes with the page\'s earlier labels kept, in the database and in the committed file, and its receipt lists them under `privacy_labels_kept`; so does a maintenance job\'s derived page publication, and a page whose tier is still `unknown` counts as the owner\'s. A soft delete no longer lowers the page\'s tier. Before, the page became readable to remote callers and other members at once, and only a `lower_page` item waited for the owner. That item now records the requested labels: `gbrain trust confirm tp<id>` applies them if the page has not changed since, `gbrain trust drop tp<id>` keeps the earlier ones, and undoing a confirm restores them while the page is unchanged since. Narrowing writes, label-neutral writes, writers at or above the page\'s tier, synced owner edits and `gbrain repair visibility` are unchanged.' },+ { since: 'TBD', id: 'requester_scope_gst363', text: 'On a brain that serves several people (two or more enabled members, or config `access.serves = several`; a brain pinned `access.serves one` never does), a remote read through a connection bound to no member (an access token, an OAuth client, or a stdio server started without `--stdio-member` and with no `mcp.stdio_member`) is now refused with `requester_scope_required` before any work; `whoami`, `get_brain_identity`, `get_status_snapshot`, `search_modes`, `get_health` and a non-admin key\'s own `get_job` / `wait_job` still answer. A connection that existed when the brain started serving several people (config `access.serves_since`, set once, or this upgrade) reads for 14 more days with `_meta.access.requester_scope` naming the date and the fix; one created later is refused at once. Bind each connection to the person it serves: `gbrain auth rescope --token <name>|--client <id> --member <id>`; a stdio harness only one person uses, `gbrain setup claude-code|codex --stdio-member <id>` (that one harness entry, PGLite or Postgres); a harness several people talk to, one `--member` key per person over `gbrain serve --http`. A shared agent names the person per call (`--may-act-for`), and `--reads-unscoped --yes` marks one credential to read unscoped on purpose. `gbrain auth create` and `gbrain auth register-client` refuse an unbound credential on such a brain (`credential_scope_required`); `gbrain doctor` fails `unscoped_shared_reads` per unbound credential and `gbrain post-upgrade` lists them. `gbrain doctor` also fails `shared_stdio_binding` when `mcp.stdio_member` is set on a host where OpenClaw or Hermes is installed (fix: `gbrain config unset mcp.stdio_member`); a `hermes` on PATH now counts as Hermes only when it is a script, so React Native\'s compiled `hermes` no longer blocks `--stdio-member`. Hosted brains set `access.requester_scope_enforce false`, which turns every refusal into the notice. Member-bound credentials (the owner\'s included), attested calls, a one-person brain with any number of sources and the local CLI see no change; writes are not affected.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex cca0fb7231..546c379d19 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -14,13 +14,13 @@// (help-text mentions count): accepting an ignored flag is the pre-#2185// status quo; missing a real one breaks working invocations.export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {- 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--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', '--limit', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--name', '--operation', '--operations', '--prefix', '--private-pages', '--qm', '--raw-only', '--readers', '--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', '--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', '--limit', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--name', '--operation', '--operations', '--prefix', '--private-pages', '--qm', '--raw-only', '--readers', '--reads-unscoped', '--refresh-operations', '--reset-default', '--revision', '--scopes', '--slug', '--source', '--sources', '--stdio-member', '--takes-holders', '--to', '--token', '--tools-json', '--yes'],'advisor': ['--apply', '--brain', '--help', '--json', '--skills-dir', '--source', '--workspace', '--yes'],'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],'anomalies': ['--all', '--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--request-id', '--sigma', '--since', '--source'],'append': ['--brain', '--expect-tail', '--expected-revision', '--file', '--force', '--help', '--json', '--region', '--request-id', '--separator', '--source'],'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--install', '--json', '--legacy-lock', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--only', '--path', '--prefer-postgres', '--probe', '--repo', '--require-db', '--skip-verify', '--source', '--statement-timeout', '--uninstall', '--url', '--yes'],- 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--allowed-operations', '--apply', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--email', '--enable', '--enable-dcr-insecure', '--expect', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--may-act-for', '--member', '--members', '--migrate-legacy', '--min-trust', '--no-pull', '--operation', '--operations', '--origin', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--private-pages', '--probe', '--profile', '--qm', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retire', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--unsettle', '--usage', '--wait', '--warn-only', '--yes'],+ 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--allowed-operations', '--apply', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--email', '--enable', '--enable-dcr-insecure', '--expect', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--may-act-for', '--member', '--members', '--migrate-legacy', '--min-trust', '--no-pull', '--only', '--operation', '--operations', '--origin', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--private-pages', '--probe', '--profile', '--qm', '--read-sources', '--reads-unscoped', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retire', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--unsettle', '--usage', '--wait', '--warn-only', '--yes'],'autopilot': ['--apply', '--batch', '--brain', '--channel', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--pause', '--phase', '--quiet', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--restart-only', '--resume', '--retry-global', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],'backup': ['--accept-pending', '--as', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--purge-mirror', '--quiet', '--restore-only', '--source', '--timeout', '--timings', '--wait'],@@ -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', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--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', '--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', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--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', '--aliases', '--all', '--all-drifted', '--all-from', '--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', '--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', '--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', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--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', '--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', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--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', '--hold-state', '--holds', '--home', '--http', '--id', '--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', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--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-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--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', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--reader-mode', '--readers', '--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', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--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', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--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', '--aliases', '--all', '--all-drifted', '--all-from', '--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', '--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', '--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', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--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', '--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', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--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', '--hold-state', '--holds', '--home', '--http', '--id', '--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', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--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-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--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', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--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', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--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', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--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', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--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', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -78,14 +78,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--catalog', '--count', '--diff-filter', '--dir', '--enable', '--end-of-options', '--env', '--force-with-lease', '--gbrain-bin', '--get', '--harness', '--heads', '--help', '--instructions', '--instructions-only', '--is-ancestor', '--jq', '--json', '--limit', '--name-only', '--no-follow-tags', '--no-instructions', '--no-tags', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--recurse-submodules', '--remove', '--scope', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--verify', '--workspace', '--yes'],'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers', '--yes'],- 'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--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', '--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', '--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'],+ 'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--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', '--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', '--reads-unscoped', '--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', '--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', '--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', '--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', '--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', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filter', '--filters', '--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', '--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', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--readers', '--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', '--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', '--target', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--untrack', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--agent', '--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', '--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', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filter', '--filters', '--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', '--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', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--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', '--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', '--target', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--untrack', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--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', '--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'],- 'maintain': ['--absolute-git-dir', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--attest-read', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--no-walk', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefix', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scan-secrets', '--scope', '--scopes', '--serves', '--session', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--untracked-files', '--url-env', '--verbose', '--verify', '--version', '--where', '--window', '--workers', '--workspace', '--yes'],+ 'maintain': ['--absolute-git-dir', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--attest-read', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--no-walk', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefix', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--reader-mode', '--readers', '--reads-unscoped', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scan-secrets', '--scope', '--scopes', '--serves', '--session', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--untracked-files', '--url-env', '--verbose', '--verify', '--version', '--where', '--window', '--workers', '--workspace', '--yes'],'mcp': ['--admin-token-file', '--advertise', '--agent', '--all', '--arg', '--attest-actor', '--attest-ops', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--cursor', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--email', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--groups', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--member', '--name', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--qm', '--queue', '--reason', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'memory-proposals': ['--all', '--brain', '--dry-run', '--help', '--json', '--limit', '--reason', '--replace', '--source'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--as', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],@@ -97,7 +97,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'orphans': ['--accept-pending', '--all', '--as', '--background', '--brain', '--count', '--cursor', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--limit', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--literal-pathspecs', '--name-only', '--older-than', '--quiet', '--retry-parked', '--show-toplevel', '--source', '--source-id', '--state', '--verify', '--yes'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],- 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--check-only', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--check-only', '--client', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--id', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--may-act-for', '--member', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reads-unscoped', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--token', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],'projections': ['--advertise', '--brain', '--dry-run', '--enable-dcr', '--help', '--http', '--images', '--install', '--json', '--limit', '--now', '--only', '--port', '--public-url', '--remove', '--source', '--stale', '--status', '--surface', '--user'],'protocol': ['--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--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', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],@@ -116,14 +116,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--allow-without-owner', '--apply', '--as', '--auto-additive', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--cursor', '--cwd', '--day', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--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', '--prefer', '--principal', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--readers', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--rules', '--run', '--scopes', '--seat', '--session', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--stale', '--state', '--timeout', '--timings', '--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', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--approval-out', '--approved', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--force-with-lease', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--heads', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--list-out', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-follow-tags', '--no-harden', '--no-lanes', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--readers', '--rebase', '--recurse-submodules', '--redirect-uri', '--refresh-operations', '--remote', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--stat', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--approval-out', '--approved', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--force-with-lease', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--heads', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--list-out', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-follow-tags', '--no-harden', '--no-lanes', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--readers', '--reads-unscoped', '--rebase', '--recurse-submodules', '--redirect-uri', '--refresh-operations', '--remote', '--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', '--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', '--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', '--limit', '--log-full-params', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--min-trust', '--no-embedding', '--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', '--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'],+ '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', '--limit', '--log-full-params', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--min-trust', '--no-embedding', '--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', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--credentials-file', '--dry-run', '--env', '--force', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--limit', '--link', '--live-fraction', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--no-stdio-member', '--oauth-client-id', '--oauth-client-secret', '--only', '--owner-sender', '--path', '--pglite', '--pins-route', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--scope', '--serves', '--skill-loading', '--skills-index-only', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--surface', '--token', '--url', '--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', '--harness', '--help', '--input-json', '--input-type', '--json', '--line', '--link', '--load-hint', '--min-match', '--names-only', '--only', '--out', '--previous', '--reset-session', '--routing', '--runtime', '--scope', '--session', '--shadow', '--shadow-log', '--skill-loading', '--source', '--text', '--top-k'],'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],@@ -131,16 +131,16 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],'skillpack-check': ['--accept-pending', '--as', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--timings', '--wait', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--approval-out', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--channels', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-with-lease', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--heads', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--list-out', '--local', '--local-env-vars', '--lookback-days', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--max-requests', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-follow-tags', '--no-harden', '--no-lanes', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--progress-interval', '--progress-json', '--provider', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--readers', '--rebase', '--record', '--recurse-submodules', '--redirect-uri', '--refresh-operations', '--remote', '--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', '--skip', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--stat', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--sync-interval-min', '--takes-holders', '--timeout', '--timezone', '--timings', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--transcript', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--visibility', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--approval-out', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--channels', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-with-lease', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--heads', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--list-out', '--local', '--local-env-vars', '--lookback-days', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--max-requests', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-follow-tags', '--no-harden', '--no-lanes', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--prefix', '--preview', '--private-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-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', '--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': ['--brain', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--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', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],- 'sync': ['--abbrev-ref', '--absolute-git-dir', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--attest-read', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--check-only', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filter', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--get-regexp', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--raw-only', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scan-secrets', '--scope', '--scopes', '--self-transfer', '--serial', '--serves', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--untracked-files', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'sync': ['--abbrev-ref', '--absolute-git-dir', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--attest-read', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--check-only', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filter', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--get-regexp', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--raw-only', '--reader-mode', '--readers', '--reads-unscoped', '--reauth', '--rebase', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scan-secrets', '--scope', '--scopes', '--self-transfer', '--serial', '--serves', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--untracked-files', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--images', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--stale', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--as', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],'trust': ['--accept-all', '--accept-pending', '--all', '--as', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--expect', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--label-lowerings', '--legacy-lock', '--no-accept-pending', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--relower', '--remove', '--repair-unknown-markers', '--resume', '--since', '--slug', '--source', '--source-id', '--timeout', '--timings', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],- 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--check-downgrade', '--check-only', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--check-downgrade', '--check-only', '--client', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--id', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--may-act-for', '--member', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reads-unscoped', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--token', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'waiting': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'wakeshift': ['--apply', '--brain', '--expect', '--help', '--json', '--key-stdin', '--max-cost', '--max-usd', '--non-interactive', '--source', '--trust', '--url', '--yes'],'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],diff --git a/src/core/config-runtime-keys.ts b/src/core/config-runtime-keys.tsindex e30d890f5e..433dd2830c 100644--- a/src/core/config-runtime-keys.ts+++ b/src/core/config-runtime-keys.ts@@ -28,6 +28,7 @@ export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = ['access.owner_reads_restricted', // access/owner.ts (GST-2490): '1' lets owner-bound credentials read past readers lists and rules (gbrain access owner reads-restricted on)'access.members_read_lineage', // access/lineage.ts (GBRA-108 design 3): '1' lets a member read derived pages and facts of origins it reads (gbrain access members-read-lineage on)'access.serves', // access/serves.ts (GST-363): one or several; explicit wins over the enabled-member count (gbrain setup --serves several writes it)+ 'access.requester_scope_enforce', // access/requester-scope.ts (GST-363): false turns the unscoped-read refusal on a brain that serves several people into a notice (hosted, until connections are bound); default on'mcp.stdio_may_act_for', // access/audience.ts (GBRA-231): whom a local stdio server may act for (_meta.on_behalf_of); unset, stdio refuses every audience'proposals.ttl_hours', 'proposals.max_pending_per_actor', 'proposals.max_pending_per_credential', // persistence/memory-proposals.ts: held QM proposal TTL (168 h) and pending caps (10 per person, 50 per credential)'proposals.retention_days', 'proposals.max_payload_chars', 'proposals.max_reason_chars', // persistence/memory-proposals.ts: closed-row retention (30 d), payload (1,000) and deny-reason (500) character capsdiff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 4013a71284..8e5d7a4bce 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -102,6 +102,10 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['access_policy_store_mismatch',// GST-363: a brain that serves several people keeps each people/<name>/ folder to its readers (doctor/checks/unlabeled-people-folders.ts).'unlabeled_people_folders',+ // GST-363: credentials bound to nobody on a brain that serves several people (doctor/checks/unscoped-shared-reads.ts).+ 'unscoped_shared_reads',+ // GST-363: config mcp.stdio_member set on a host where OpenClaw or Hermes is installed (doctor/checks/shared-stdio-binding.ts).+ 'shared_stdio_binding',// GBRA-231: shared agents (doctor/checks/shared-agent-access.ts).'access_may_act_for_wildcard',// GST-2490: the owner opt-in (doctor/checks/owner-reads-restricted.ts).diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 5a35211363..735c1225d1 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -41,6 +41,10 @@ export const ERROR_CATALOGUE = {on_behalf_of_unknown_member: { code: 'on_behalf_of_unknown_member', docs: 'docs/guides/write-refusals.md#on_behalf_of_unknown_member' },on_behalf_of_not_permitted: { code: 'on_behalf_of_not_permitted', docs: 'docs/guides/write-refusals.md#on_behalf_of_not_permitted' },on_behalf_of_in_arguments: { code: 'on_behalf_of_in_arguments', docs: 'docs/guides/write-refusals.md#on_behalf_of_in_arguments' },+ // GST-363: a brain that serves several people knows who is asking (remote reads, credential creation).+ requester_scope_required: { code: 'requester_scope_required', docs: 'docs/guides/write-refusals.md#requester_scope_required' },+ credential_scope_required: { code: 'credential_scope_required', docs: 'docs/guides/write-refusals.md#credential_scope_required' },+ requester_scope_unknown: { code: 'requester_scope_unknown', docs: 'docs/guides/write-refusals.md#requester_scope_unknown' },// GST-359 C1 attested actor: the person a trusted system names (x-qm-actor) on a credential holding the attest right.actor_not_attested: { code: 'actor_not_attested', docs: 'docs/guides/write-refusals.md#actor_not_attested' },actor_unlinked: { code: 'actor_unlinked', docs: 'docs/guides/write-refusals.md#actor_unlinked' },diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 5de3c80547..2618a11403 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -76,6 +76,9 @@ export const CODES = {access_policy_widening_held: { class: 'consent', actor: 'user', summary: "A change to a source's folder rules widens who may read (a rule removed, readers added, the old folder of a moved prefix), so it is recorded but held: the previous rules stay in force until an operator previews it with gbrain access apply --source <id> and approves the printed plan with --yes --expect <plan_hash> on the brain host.", why: 'Write access to the policy (a git commit or a rule edit) must not be enough to open a folder; widening needs a host-side preview and an explicit approval.', suggestion: 'Ask the user whether to approve the widening; the brain host previews it with gbrain access apply --source <id>.', fix: { argv: ['gbrain', 'access', 'apply', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews the held widening (pages and members gaining access) and prints the plan hash an approval binds; changes nothing.' } },access_policy_store_mismatch: { class: 'host_only', actor: 'user', summary: "A source's persisted folder-rule store (sources.config.access_store) disagrees with what this host sees (a git store with no visible work tree, or a database store whose root became a repository), so the persisted store and its applied rules stay in force and nothing switches on its own.", why: 'Inferring the store per host would let a missing checkout or a stray git init change which rules apply; only gbrain access rule migrate moves them, and neither direction widens.', suggestion: 'On the brain host, preview the move with gbrain access rule migrate --source <id>, then apply it by adding --yes.', fix: { argv: ['gbrain', 'access', 'rule', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the persisted store and the applied rules; changes nothing.' } },access_rule_invalid: { class: 'caller', docs: 'docs/guides/write-refusals.md#access_rule_invalid', summary: 'A folder rule given to gbrain access rule add is invalid (its prefix is not a literal lower-case folder ending in /, holds .. or *, its readers are not member ids or group:<id>, or another rule already covers the prefix), so nothing was written.', why: 'Prefixes are matched literally against slugs; a pattern or a typo would silently restrict the wrong pages or none.', suggestion: 'Write the prefix as a slug folder ending in / (partners/alice-example/) and the readers as member ids or group:<id>.' },+ requester_scope_required: { class: 'host_only', actor: 'user', reasons: ['grace_ended', 'created_after', 'since_unknown'], docs: 'docs/guides/write-refusals.md#requester_scope_required', summary: 'A remote read came from a connection bound to no member (an access token, an OAuth client or a local stdio server) on a brain that serves several people (two or more enabled members, or config access.serves = several), so it was refused before any work and nothing was read.', why: 'On a brain that serves several people a connection bound to nobody reads every page no rule restricts, for whoever is asking; gbrain refuses rather than guess whose notes a read is for. A connection that existed when the brain started serving several people gets 14 days of in-band notices first (reason grace_ended); one created after that is refused at once (created_after).', suggestion: 'On the brain host, bind the connection to the person it serves: gbrain auth rescope --token <name>|--client <id> --member <id> (preview with gbrain access check --token <name>), or for a stdio server, when only one person uses that harness, gbrain setup claude-code|codex --stdio-member <id>, which binds that one harness entry on that machine (refused where OpenClaw or Hermes is installed); for a harness several people talk to, give each person a key over HTTP instead (gbrain serve --http with gbrain auth create <name> --member <id> keys). A shared agent lists whom it may act for (--may-act-for) and names the person on each call. Last resort: --reads-unscoped --yes lets that one credential read every page no rule restricts for any asker.' },+ requester_scope_unknown: { class: 'retryable', retryable: true, actor: 'provider', docs: 'docs/guides/write-refusals.md#requester_scope_unknown', summary: 'A remote read came from a connection bound to no member, and whether the brain serves one person or several could not be read (the config read failed, and so did one re-read), so it was refused before any work and nothing was read.', why: 'A statement timeout, a lock wait or a dropped pooled connection can fail one config read while the next read succeeds. Reading that as a one-person brain would let a connection bound to nobody read every page no rule restricts on a brain that may serve several people, so gbrain refuses until it can tell.', suggestion: 'Retry the same call in a few seconds. If it keeps failing, the brain host\'s operator checks the database with gbrain doctor --json. A connection bound to a member is never refused this way.' },+ credential_scope_required: { class: 'caller', docs: 'docs/guides/write-refusals.md#credential_scope_required', summary: 'gbrain auth create or gbrain auth register-client was asked for a credential bound to no member on a brain that serves several people, so nothing was created.', why: 'A credential bound to nobody on such a brain is refused on every read (requester_scope_required); creating one would hand out a key that cannot work, or one that reads everyone\'s unmarked notes.', suggestion: 'Bind it to the person it serves: gbrain auth create <name> --member <id> (gbrain access member list names the members). A shared agent passes --may-act-for <members> instead; --reads-unscoped --yes creates one that reads every page no rule restricts for any asker, on purpose.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists the members a credential can be bound to.' } },access_serves_roster_empty: { class: 'caller', summary: 'gbrain setup --serves several or gbrain access serves several was given no people (no --members, an empty --members-file), so nothing was written.', why: 'Each person gets a member, a folder only they read and a key bound to them; the installer never guesses who they are.', suggestion: 'Name every person: --members alice-example,bob-example, or --members-file <file> with one id per line.' },access_serves_key_dir_in_git: { class: 'caller', summary: 'The directory the per-member keys would be written to is inside a git work tree, so no key, member or rule was written.', why: 'Key files hold live credentials; a file inside a checkout can be committed and pushed.', suggestion: 'Point GBRAIN_HOME at a directory outside any git checkout (the default is your home directory) and run the command again.' },access_member_id_retired: { class: 'caller', summary: "The member id was removed earlier and member ids are never reused, so nothing was created or enabled.", why: 'Pages and audit history may still name a removed id; reusing it would hand that history to a different person.', docs: 'docs/guides/write-refusals.md#access_member_id_retired', suggestion: 'Choose a new member id.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists every member id on this brain with its status, removed ones included.', verify: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'] } } },diff --git a/src/core/minions/tools/brain-allowlist.ts b/src/core/minions/tools/brain-allowlist.tsindex c813e863f2..e4e149b5cd 100644--- a/src/core/minions/tools/brain-allowlist.ts+++ b/src/core/minions/tools/brain-allowlist.ts@@ -36,6 +36,7 @@ import { BRAIN_TOOL_ALLOWLIST } from './brain-tool-allowlist.ts';import { stagePutPage } from './staged-put-page.ts';import { withCallerAccess } from '../../search/private-visibility.ts';import { folderAccessFor, remoteCallerAccess } from '../../access/caller.ts';+import { credentialScopeFor, requesterScopeGate, requiresRequesterScope, withServesReread } from '../../access/requester-scope.ts';import { attestedCallerAccess, attestRightOf, storedActorIdentity } from '../../access/actor.ts';import { attestedReadMode, SCOPE_READ_ACCESS, withReadMode } from '../../access/scope-read.ts';import { attestedReadScope } from '../../access/member-sources.ts';@@ -331,7 +332,7 @@ function brainTool(op: Operation, opts: BuildBrainToolsOpts): ToolDef {return withCallerAccess(access, () => withReadMode(readMode, async () => run(await attestedReadScope(ctx.engine, opCtx, actor.member, readMode === 'scope'))));})(): opCtx.auth- ? await withCallerAccess(await remoteCallerAccess(ctx.engine, opCtx.auth, [], undefined, actingFor, undefined, op.mutating === false), run)+ ? await withCallerAccess(await scopedJobAccess(ctx.engine, op, opCtx.auth, actingFor), run): await run();const rejection = op.name === 'put_page' ? putPageRejection(output) : null;if (rejection) throw new Error(rejection);@@ -341,6 +342,20 @@ function brainTool(op: Operation, opts: BuildBrainToolsOpts): ToolDef {};}+/**+ * The caller access of a remote-owned job's tool call. GST-363: the same requester-scope gate as dispatch, read live+ * on every call: on a brain that serves several people, a read by a job whose credential is bound to nobody (and that+ * names no audience) is refused with requester_scope_required once the grace ends; during it the call runs.+ */+async function scopedJobAccess(engine: BrainEngine, op: Operation, auth: NonNullable<OperationContext['auth']>, actingFor: AudiencePrincipal[] | undefined) {+ const access = await remoteCallerAccess(engine, auth, [], undefined, actingFor, undefined, op.mutating === false);+ if (!requiresRequesterScope(op, auth)) return access;+ const credential = await credentialScopeFor(engine, auth);+ const resolved = await withServesReread(engine, access, credential);+ requesterScopeGate(op, resolved, credential, 'http');+ return resolved;+}+/*** Apply the caller's `allowed_tools` subset to a registry. Unknown tool* names throw a clear error at load time (NOT silently ignored) sodiff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.tsindex 8e4735b213..cec39d10a8 100644--- a/src/core/oauth-provider.ts+++ b/src/core/oauth-provider.ts@@ -887,7 +887,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {token,clientId: row.client_id as string,principal: { kind: 'oauth_client', id: row.client_id as string },- ...withAttestRight(await tokenMemberBinding(this.sql, currentGrant.member_id, currentGrant.may_act_for), currentGrant, row.token_grant),+ ...withAttestRight(await tokenMemberBinding(this.sql, currentGrant, currentGrant.client_id_issued_at), currentGrant, row.token_grant),clientName: (row.client_name as string | null) ?? undefined,scopes: effectiveScopes,issuedScopes,@@ -959,7 +959,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {token,clientId: name,principal: { kind: 'legacy_token', id: String(legacyRows[0].id) },- ...withAttestRight(await tokenMemberBinding(this.sql, legacyRows[0].member_id, legacyRows[0].may_act_for), legacyRows[0], 'legacy'),+ ...withAttestRight(await tokenMemberBinding(this.sql, legacyRows[0], legacyRows[0].created_at), legacyRows[0], 'legacy'),clientName: name,scopes: grant.scopes,...(grant.allowedOperations === null ? {} : { allowedOperations: grant.allowedOperations }),diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 4f648d99dd..a147673405 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -304,6 +304,13 @@ export interface AuthInfo {member?: { id: string; groups: string[] } | null;/** GBRA-218: the stored `may_act_for` audience list (shared agents, PR B); stored and reported only. */mayActFor?: string[] | null;+ /**+ * GST-363: the brain operator let this credential read unscoped on purpose (`reads_unscoped` is set, gbrain auth+ * rescope --reads-unscoped --yes). Undefined when no verifier read it; access/requester-scope.ts then looks it up.+ */+ readsUnscoped?: boolean;+ /** GST-363: when the credential was created, epoch seconds (access_tokens.created_at, oauth_clients.client_id_issued_at); null = unknown, which counts as old. */+ createdAt?: number | null;/*** GST-359 C1: the live right to name the person a call serves (x-qm-actor), joined by the verifier: the system and* the operations an attested call may run, and (GST-1158 F3) how it reads named sources. Null when the credential holds none, is bound to a member, or (an OAuthdiff --git a/src/core/ops/sources.ts b/src/core/ops/sources.tsindex 5ab5ac4135..65d70d8c48 100644--- a/src/core/ops/sources.ts+++ b/src/core/ops/sources.ts@@ -55,7 +55,9 @@ const whoami: Operation = {// while access.members_read_lineage is on, that members read the derived pages of pages listed to them.const withApplied = async <T extends object>(view: T) => ({ ...view, applied: await appliedAccessSummary(ctx.engine, ctx.auth, [ctx.sourceId, ...(ctx.localFederatedSourceIds ?? [])]),...await (await import('../access/owner.ts')).ownerReadsRestrictedNotice(ctx.engine),- ...await (await import('../access/lineage.ts')).membersReadLineageNotice(ctx.engine) });+ ...await (await import('../access/lineage.ts')).membersReadLineageNotice(ctx.engine),+ // GST-363: and, remotely, what the requester-scope gate does with this connection's reads.+ requester_scope: await (await import('../access/requester-scope.ts')).requesterScopeView(ctx.engine, (await import('../search/private-visibility.ts')).currentCallerAccess(), ctx.auth, ctx.transport) });if (ctx.remote === false) {// GBRA-218: a local --as <member> preview reports the member it reads as; the plain local CLI reads every page.const access = ctx.applyRemoteReadPolicy && ctx.accessIdentity?.length ? accessView(ctx.accessIdentity, 'as')diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 66e025f253..1a22223036 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 307;+export const LATEST_SCHEMA_VERSION = 308;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 154782fc2d..a9e5599656 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -308,6 +308,7 @@ import { v304 } from './v304-access-owner-origin.ts';import { v305 } from './v305-access-lineage-designs.ts';import { v306 } from './v306-member-page-withdrawal-scope.ts';import { v307 } from './v307-page-label-guards.ts';+import { v308 } from './v308-requester-scope.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -614,4 +615,5 @@ export const MIGRATIONS: Migration[] = [v305,v306,v307,+ v308,];diff --git a/src/core/schema-migrations/v308-requester-scope.ts b/src/core/schema-migrations/v308-requester-scope.tsnew file mode 100644index 0000000000..b03cc47da6--- /dev/null+++ b/src/core/schema-migrations/v308-requester-scope.ts@@ -0,0 +1,63 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// GST-363: a brain that serves several people refuses remote reads from a+// connection bound to nobody (src/core/access/requester-scope.ts). The request+// reads whom the brain serves from config, never by counting members:+// gbrain_access_refresh_serves() keeps config access.serves_derived (`several`+// while two or more members are enabled, `one` otherwise) and, the first time+// the brain serves several people (that, or an explicit access.serves =+// several), sets access.serves_since once; nothing ever clears it, so disabling+// and re-enabling a member does not restart the grace. Triggers on+// access_members and on config access.serves call it. The one call below+// derives both keys for an existing brain (a brain that already serves several+// people starts its 14-day grace at this upgrade). reads_unscoped records when+// the brain operator let one credential read unscoped on purpose (gbrain auth+// rescope --reads-unscoped --yes); NULL, with no backfill. Nothing else is+// rewritten. No schema.sql mirror: like v282, these exist only through+// migrations. The number is a placeholder restamped at the merge slot.+export const v308: Migration = {+ version: 308,+ name: 'requester_scope',+ idempotent: true,+ sql: `+ALTER TABLE access_tokens ADD COLUMN IF NOT EXISTS reads_unscoped TIMESTAMPTZ;+ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS reads_unscoped TIMESTAMPTZ;+CREATE OR REPLACE FUNCTION gbrain_access_refresh_serves() RETURNS void+ LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$+DECLARE+ derived TEXT;+ explicit TEXT;+BEGIN+ SELECT CASE WHEN count(*) >= 2 THEN 'several' ELSE 'one' END INTO derived+ FROM access_members WHERE disabled_at IS NULL AND tombstoned_at IS NULL;+ INSERT INTO config (key, value) VALUES ('access.serves_derived', derived)+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value WHERE config.value IS DISTINCT FROM EXCLUDED.value;+ SELECT btrim(value) INTO explicit FROM config WHERE key = 'access.serves';+ IF (CASE WHEN explicit IN ('one', 'several') THEN explicit ELSE derived END) = 'several' THEN+ INSERT INTO config (key, value) VALUES ('access.serves_since', to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"'))+ ON CONFLICT (key) DO NOTHING;+ END IF;+END+$fn$;+CREATE OR REPLACE FUNCTION gbrain_access_refresh_serves_trigger() RETURNS trigger+ LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$+BEGIN+ PERFORM gbrain_access_refresh_serves();+ RETURN NULL;+END+$fn$;+DROP TRIGGER IF EXISTS access_members_refresh_serves ON access_members;+CREATE TRIGGER access_members_refresh_serves AFTER INSERT OR DELETE OR TRUNCATE OR UPDATE OF disabled_at, tombstoned_at ON access_members+ FOR EACH STATEMENT EXECUTE FUNCTION gbrain_access_refresh_serves_trigger();+DROP TRIGGER IF EXISTS config_serves_refresh ON config;+CREATE TRIGGER config_serves_refresh AFTER INSERT OR UPDATE ON config+ FOR EACH ROW WHEN (NEW.key = 'access.serves') EXECUTE FUNCTION gbrain_access_refresh_serves_trigger();+DROP TRIGGER IF EXISTS config_serves_refresh_delete ON config;+CREATE TRIGGER config_serves_refresh_delete AFTER DELETE ON config+ FOR EACH ROW WHEN (OLD.key = 'access.serves') EXECUTE FUNCTION gbrain_access_refresh_serves_trigger();+SELECT gbrain_access_refresh_serves();+`,+};diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex 9c07b9af11..229c7f1a8b 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -940,6 +940,19 @@ const strictEngines = new Set<BrainEngine>();/** GBRA-218: set once a page names readers or a member exists (sticky; a trigger and `gbrain access` write it). */export const ACCESS_RESTRICTIONS_KEY = 'access.restrictions_present';+/**+ * GST-363: whom the brain serves. SERVES_KEY is the explicit `one` or `several` (`gbrain setup --serves several`+ * writes it, and it wins); SERVES_DERIVED_KEY is `several` while two or more members are enabled, `one` otherwise;+ * SERVES_SINCE_KEY is when the brain first served several people, set once and never cleared. A trigger on+ * access_members and on config access.serves keeps the last two (migration v308), so a request reads them from its+ * config snapshot with no query. REQUESTER_SCOPE_ENFORCE_KEY `false` turns the unscoped-read refusal into a notice+ * (hosted, until its control plane binds each connection to a member).+ */+export const SERVES_KEY = 'access.serves';+export const SERVES_DERIVED_KEY = 'access.serves_derived';+export const SERVES_SINCE_KEY = 'access.serves_since';+export const REQUESTER_SCOPE_ENFORCE_KEY = 'access.requester_scope_enforce';+/** @internal exported for tests: engines the process-wide policy sets hold. */export function __aliasPolicyEngineCountForTests(): number {return honorAliasEngines.size + aliasOptOutEngines.size + exposeEngines.size + strictEngines.size;@@ -998,24 +1011,52 @@ export async function remotePrivacyRelaxed(engine: BrainEngine): Promise<booleanreturn expose;}-export interface RemotePolicy { privacyRelaxed: boolean; restricted: boolean; ownerMember?: string | null; ownerReadsRestricted?: boolean; membersReadLineage?: boolean }+/** GST-363: whom the brain serves, as a remote request reads it from config (no query). `since` is epoch seconds. */+export interface ServesPolicy { several: boolean; from: 'config' | 'members'; since: number | null; enforce: boolean }++/** `servesUnknown`: the config read failed, so whom the brain serves is not known (never read as one person, GST-363). */+export interface RemotePolicy { privacyRelaxed: boolean; restricted: boolean; ownerMember?: string | null; ownerReadsRestricted?: boolean; membersReadLineage?: boolean; serves?: ServesPolicy; servesUnknown?: boolean }++/** GST-363: an explicit access.serves wins over the trigger-kept member count; enforcement is on unless set to false. */+export function servesPolicyFrom(config: Record<string, string | undefined>): ServesPolicy {+ const explicit = config[SERVES_KEY]?.trim();+ const fromConfig = explicit === 'one' || explicit === 'several';+ const since = Date.parse(config[SERVES_SINCE_KEY]?.trim() ?? '');+ return {+ several: (fromConfig ? explicit : config[SERVES_DERIVED_KEY]?.trim()) === 'several',+ from: fromConfig ? 'config' : 'members',+ since: Number.isFinite(since) ? Math.floor(since / 1000) : null,+ enforce: !['false', '0', 'off', 'no'].includes(config[REQUESTER_SCOPE_ENFORCE_KEY]?.trim().toLowerCase() ?? ''),+ };+}/*** The remote read policy read fresh, for publication: whether an operator* relaxed privacy (the env hatch or the config opt-out, uncached) and whether* the brain holds member-access restrictions. Takes any executeRaw engine (a* transaction included). An unreadable config counts as not opted out and- * restricted (fail closed); the env hatch needs no read.+ * restricted (fail closed); the env hatch needs no read. Whom the brain serves+ * is then unknown (servesUnknown, GST-363): the requester-scope gate reads the+ * serves keys once more (readServesPolicy) and refuses an unbound read when that+ * fails too, because a timeout or a dropped pooled connection can fail this one+ * statement while the next read succeeds.*/export async function readRemotePolicyNow(engine: Pick<BrainEngine, 'executeRaw'>): Promise<RemotePolicy> {try {- const rows = await engine.executeRaw<{ key: string; value: string }>('SELECT key, value FROM config WHERE key = ANY($1::text[])', [[REMOTE_PRIVATE_PAGES_KEY, ACCESS_RESTRICTIONS_KEY, OWNER_MEMBER_KEY, OWNER_READS_RESTRICTED_KEY, MEMBERS_READ_LINEAGE_KEY]]);+ const rows = await engine.executeRaw<{ key: string; value: string }>('SELECT key, value FROM config WHERE key = ANY($1::text[])', [[REMOTE_PRIVATE_PAGES_KEY, ACCESS_RESTRICTIONS_KEY, OWNER_MEMBER_KEY, OWNER_READS_RESTRICTED_KEY, MEMBERS_READ_LINEAGE_KEY,+ SERVES_KEY, SERVES_DERIVED_KEY, SERVES_SINCE_KEY, REQUESTER_SCOPE_ENFORCE_KEY]]);return remotePolicyFrom(Object.fromEntries(rows.map(r => [r.key, r.value])));} catch {- return { privacyRelaxed: process.env.GBRAIN_REMOTE_PRIVATE_PAGES === '1', restricted: true, ownerMember: null, ownerReadsRestricted: false, membersReadLineage: false };+ return { privacyRelaxed: process.env.GBRAIN_REMOTE_PRIVATE_PAGES === '1', restricted: true, ownerMember: null, ownerReadsRestricted: false, membersReadLineage: false, servesUnknown: true };}}+/** GST-363: whom the brain serves, read on its own (the requester-scope gate's re-read after an unreadable policy read). Throws when unreadable. */+export async function readServesPolicy(engine: Pick<BrainEngine, 'executeRaw'>): Promise<ServesPolicy> {+ const rows = await engine.executeRaw<{ key: string; value: string }>('SELECT key, value FROM config WHERE key = ANY($1::text[])', [[SERVES_KEY, SERVES_DERIVED_KEY, SERVES_SINCE_KEY, REQUESTER_SCOPE_ENFORCE_KEY]]);+ return servesPolicyFrom(Object.fromEntries(rows.map(r => [r.key, r.value])));+}+/*** The remote read policy a request starts under: answered from the read request's config snapshot when one is open* (taken when the request started, so no staler than readRemotePolicyNow there, and no extra round trip, #6721);@@ -1031,7 +1072,7 @@ function remotePolicyFrom(config: Record<string, string>): RemotePolicy {const owner = config[OWNER_MEMBER_KEY]?.trim();return { privacyRelaxed: hatch || ['visible', 'true', '1'].includes(config[REMOTE_PRIVATE_PAGES_KEY] ?? ''), restricted: config[ACCESS_RESTRICTIONS_KEY] === '1',ownerMember: owner && ACCESS_ID_RE.test(owner) ? owner : null, ownerReadsRestricted: config[OWNER_READS_RESTRICTED_KEY]?.trim() === '1',- membersReadLineage: config[MEMBERS_READ_LINEAGE_KEY]?.trim() === '1' };+ membersReadLineage: config[MEMBERS_READ_LINEAGE_KEY]?.trim() === '1', serves: servesPolicyFrom(config) };}/** GBRA-218: does this brain hold member-access restrictions? Read live (the request snapshot answers it inside a read); unreadable counts as yes. */diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 4b8fea3137..ea50192985 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -16,6 +16,7 @@ import { loadConfig } from '../core/config.ts';import { withRequestConfigSnapshot, withoutRequestConfigSnapshot } from '../core/config-snapshot.ts';import { withCallerAccess } from '../core/search/private-visibility.ts';import { appliedAccessSummary, folderAccessFor, remoteCallerAccess } from '../core/access/caller.ts';+import { credentialScopeFor, requesterScopeGate, requiresRequesterScope, withServesReread, type RequesterScopeNotice } from '../core/access/requester-scope.ts';import { audienceInArguments, audienceInArgumentsError, logAudienceAssertion, parseAudience, type AudienceAuditEvent, type AudienceChannels, type AudiencePrincipal } from '../core/access/audience.ts';import { ACTOR_ARGUMENT, actorNotAttested, EXTERNAL_ID_RE, resolveAttestedActor, type ActorChannels } from '../core/access/actor.ts';import { attestedReadMode, SCOPE_READ_ACCESS, withReadMode, type ReadMode } from '../core/access/scope-read.ts';@@ -24,7 +25,7 @@ import { QM_PERSONAL_OPS, qmMemoryToolResult, recallArguments, unlinkedRecallResimport { resolveBrainId } from '../core/brain-resolver.ts';import { getCliOptions } from '../core/cli-options.ts';import { VERB_NAMES, MEMORY_VERBS_VERSION } from '../core/verbs.ts';-import { cliRenderContext, orderNotices, redactForTransport, renderNotice, toAgentError, toolErrorResult, toolResultWithNotices, type Notice, type RenderContext } from '../core/agent-output.ts';+import { cliRenderContext, orderNotices, redactForTransport, renderAction, renderNotice, toAgentError, toolErrorResult, toolResultWithNotices, type Notice, type RenderContext } from '../core/agent-output.ts';import { cliOnlyRefusal, isCallable } from '../core/ops/callable.ts';import { hostFix, scopeDeniedError } from '../core/ops/op-fix.ts';import { mutedNoticeCodes, processNoticeLedger, __resetProcessNoticeLedgerForTests, type NoticeLedger, type NoticeAudience } from '../core/notice-ledger.ts';@@ -1015,6 +1016,7 @@ export async function dispatchToolCall(let access: Awaited<ReturnType<typeof remoteCallerAccess>>;let readMode: ReadMode | null = null;let scoped = resolved;+ let scopeNotice: RequesterScopeNotice | null = null;const header = opts.actor?.header ?? undefined;const actorNamed = header !== undefined || opts.actor?.audience != null || (!!args && Object.prototype.hasOwnProperty.call(args, ACTOR_ARGUMENT));const assertion = (outcome: AudienceAuditEvent['outcome'], reason?: string) => logAudienceAssertion({ outcome, op: name,@@ -1032,14 +1034,23 @@ export async function dispatchToolCall(// GBRA-284: an attested call reads its grant minus other members' personal sources, a scope read minus every personal source (access/member-sources.ts).if (attested?.actor) scoped = await attestedReadScope(engine, resolved, attested.actor.member, readMode === 'scope');if (opts.enforcedMember) access = { ...access, hidePrivate: true, owner: false, privateReadableSources: [] };+ // GST-363: on a brain that serves several people, a read from a connection bound to nobody is refused (or, in its grace, noticed) before any work.+ // An op this connection cannot reach (hidden by its surface, or localOnly off stdio) keeps the unknown-tool envelope instead.+ const reachable = !!op && (!opts.allowedOps || opts.allowedOps.has(name)) && (!op.localOnly || opts.transport === 'stdio');+ if (!attested?.actor && reachable && requiresRequesterScope(op, opts.auth)) {+ const credential = opts.auth ? await credentialScopeFor(engine, opts.auth) : undefined;+ access = await withServesReread(engine, access, credential);+ scopeNotice = requesterScopeGate(op, access, credential, opts.transport);+ }} catch (e) {// GST-359: a call that names a person gets every failure here (a lock timeout reading its link included) in the// envelope QM reads, never a thrown call; anything else keeps the caller's own error path.- if (!(e instanceof OperationError) || !/^(on_behalf_of_|actor_)/.test(String(e.code))) {+ if (!(e instanceof OperationError) || !/^(on_behalf_of_|actor_|requester_scope_(required|unknown)$)/.test(String(e.code))) {if (!actorNamed) throw e;return withStructuredError(errorResult(e, opts, { op: name }));}assertion(e.code as AudienceAuditEvent['outcome'], e.reason);+ if (e.code === 'requester_scope_required' || e.code === 'requester_scope_unknown') return qmMemoryToolResult(name, withStructuredError(errorResult(e, opts, { op: name })));return qmMemoryToolResult(name, actorNamed ? actorRefusal(e, opts, name, header, args) : errorResult(e, opts, { op: name }));}if (audience || attested?.actor) assertion('accepted');@@ -1048,6 +1059,10 @@ export async function dispatchToolCall(const out = await withRequestIdentityMemo(() => withReadMode(readMode, () => dispatchResolvedCall(engine, name, callParams, scoped)));// _meta.access (MCP_META_CHANNELS.md): the view this call was answered under, for the harness; own producer, isolated.try { out._meta = { ...(out._meta ?? {}), access: await appliedAccessSummary(engine, scoped.auth, [scoped.sourceId, ...(scoped.localFederatedSourceIds ?? [])]) }; } catch { /* the key is absent */ }+ if (scopeNotice) {+ const applied = (out._meta?.access ?? {}) as Record<string, unknown>;+ out._meta = { ...(out._meta ?? {}), access: { ...applied, requester_scope: { ...scopeNotice, fix: renderAction(scopeNotice.fix, dispatchRenderContext(opts)) } } };+ }const personal = !!attested?.actor;const shaped = qmMemoryToolResult(name, out, personal);// GST-1158 F2: a personal read's structuredContent repeats its JSON, so the final frame is measured again.diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.tsindex 2670265374..1b56cb1c34 100644--- a/src/mcp/http-transport.ts+++ b/src/mcp/http-transport.ts@@ -306,7 +306,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {// on the legacy shape is converted on this read. Takes holders fail safe// to ['world']; #1336 honors the stored source grant.const grant = await resolveTokenGrant(sql, row);- const binding = await tokenMemberBinding(sql, row.member_id, row.may_act_for).catch(() => null); // GBRA-218 verify join+ const binding = await tokenMemberBinding(sql, row, row.created_at).catch(() => null); // GBRA-218 verify joinif (!binding) return { ok: false, code: 'access_member_disabled' };const allowList = grant.takesHolders ?? ['world'];const { sourceId, allowedSources, hasSourceGrant } = authSourcesFromGrant(grant);diff --git a/test/access-binding.serial.test.ts b/test/access-binding.serial.test.tsindex 0ec83b02b8..61c6d1ce36 100644--- a/test/access-binding.serial.test.ts+++ b/test/access-binding.serial.test.ts@@ -91,7 +91,7 @@ describe('access and auth binding CLI (repo-less PGLite)', () => {}, 120_000);test('auth rescope --member rebinds, --dry-run writes nothing, --member none unbinds, --may-act-for is stored normalized', async () => {- expect((await cli(['auth', 'create', 'shared-bot', '--scopes', 'read'])).exitCode).toBe(0);+ expect((await cli(['auth', 'create', 'shared-bot', '--scopes', 'read', '--reads-unscoped', '--yes'])).exitCode).toBe(0);const preview = await cli(['auth', 'rescope', '--token', 'shared-bot', '--member', 'bob-example', '--dry-run']);expect(preview.exitCode).toBe(0);expect(preview.stdout).toContain('preview, not written');diff --git a/test/access-binding.test.ts b/test/access-binding.test.tsindex dd92e1ad76..56fbe1edd2 100644--- a/test/access-binding.test.ts+++ b/test/access-binding.test.ts@@ -38,6 +38,7 @@ import { watchPrincipal } from '../src/core/ops/wakeshift.ts';import { principalLive, STDIO_REGISTRATION_PRINCIPAL } from '../src/core/wakeshift/drain.ts';import { testBackends } from './helpers/test-backends.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';const DIMS = 1536;const SRC = 'source-a';@@ -74,6 +75,7 @@ for (const kind of testBackends()) {await bindCredential(engine, { kind: 'token', id: tokens.alice!.id }, { member: 'alice-example', mayActFor: ['member:bob-example'] });await bindCredential(engine, { kind: 'token', id: tokens.bob!.id }, { member: 'bob-example' });await engine.executeRaw("UPDATE access_tokens SET member_id = 'nobody-example' WHERE id = $1::uuid", [tokens.ghost!.id]);+ await readsUnscopedOnPurpose(engine, tokens.unbound!.id);}, 120_000);afterAll(async () => {@@ -226,10 +228,10 @@ for (const kind of testBackends()) {const out = await dispatchToolCall(engine, 'whoami', {}, { remote: true, transport: 'http', auth, sourceId: SRC });const body = JSON.parse(out.content[0]!.text);expect(body.access).toEqual({ member: 'alice-example', groups: ['team-a'], may_act_for: ['member:bob-example'], bound_by: 'credential',- applied: { member: 'alice-example', groups: ['team-a'], audience: null, policy_rev: {}, relaxation: 'none' } });+ applied: { member: 'alice-example', groups: ['team-a'], audience: null, policy_rev: {}, relaxation: 'none' }, requester_scope: { state: 'scoped' } });expect(body.grant_diagnosis).toMatchObject({ member: 'alice-example', groups: ['team-a'], may_act_for: ['member:bob-example'] });const unbound = JSON.parse((await dispatchToolCall(engine, 'whoami', {}, { remote: true, transport: 'http', auth: await verify(tokens.unbound!.token), sourceId: SRC })).content[0]!.text);- expect(unbound.access).toMatchObject({ member: null, groups: [], bound_by: 'none' });+ expect(unbound.access).toMatchObject({ member: null, groups: [], bound_by: 'none', requester_scope: { state: 'reads_unscoped' } });expect(unbound.grant_diagnosis).toMatchObject({ member: null, may_act_for: null });const local = JSON.parse((await dispatchToolCall(engine, 'whoami', {}, { remote: false, sourceId: SRC })).content[0]!.text);expect(local.access).toMatchObject({ member: null, bound_by: 'none' });diff --git a/test/access-federated-member-writes.test.ts b/test/access-federated-member-writes.test.tsindex 81c9f2077e..ad92a865bb 100644--- a/test/access-federated-member-writes.test.ts+++ b/test/access-federated-member-writes.test.ts@@ -33,6 +33,7 @@ import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/privatimport type { AuthInfo } from '../src/core/ops/contract.ts';import { testBackends } from './helpers/test-backends.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';const MiB = 1024 ** 2;const PART_CHARS = 3_900_000;@@ -94,6 +95,7 @@ for (const kind of testBackends()) {tokens[name] = minted.token;tokenIds[name] = minted.id;if (member) await engine.executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id = $1::uuid', [minted.id, member]);+ else await readsUnscopedOnPurpose(engine, minted.id);}}, 240_000);afterAll(async () => { await close?.(); }, 60_000);diff --git a/test/access-folder-rules.test.ts b/test/access-folder-rules.test.tsindex 79315e3714..0ca749f330 100644--- a/test/access-folder-rules.test.ts+++ b/test/access-folder-rules.test.ts@@ -40,6 +40,7 @@ import { runAccessRules } from '../src/commands/access-rules.ts';import { testBackends } from './helpers/test-backends.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';const DIMS = 1536;function vectorFor(text: string): number[] {@@ -185,6 +186,7 @@ for (const kind of testBackends()) {const minted = await mintLegacyToken(engine, { name, scopes: ['read', 'write'], takesHolders: ['world'], sourceGrant: [SRC, SRC2] });tokens[name] = minted.token;if (member) await engine.executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id = $1::uuid', [minted.id, member]);+ else await readsUnscopedOnPurpose(engine, minted.id);};await mint('alice', 'alice-example');await mint('bob', 'bob-example');diff --git a/test/access-member-facts.test.ts b/test/access-member-facts.test.tsindex eb7adc0cdb..ed415d51f5 100644--- a/test/access-member-facts.test.ts+++ b/test/access-member-facts.test.ts@@ -40,6 +40,7 @@ import type { AuthInfo } from '../src/core/ops/contract.ts';import { testBackends } from './helpers/test-backends.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';const DIMS = 1536;function vectorFor(text: string): number[] {@@ -109,6 +110,7 @@ for (const kind of testBackends()) {const bob = await register('bob');await bindCredential(engine, { kind: 'client', id: bob.id }, { member: 'bob-example' });const plain = await register('plain');+ for (const c of [qm, plain]) await readsUnscopedOnPurpose(engine, c.id, 'client');for (const [name, c] of [['qm', qm], ['bob', bob], ['plain', plain]] as const) tokens[name] = (await provider().exchangeClientCredentials(c.id, c.secret)).access_token;await linkMember(engine, 'alice-example', 'qm', ALICE_ID);await linkMember(engine, 'bob-example', 'qm', BOB_ID);@@ -341,6 +343,7 @@ for (const kind of testBackends()) {const reg = await provider().registerClientManual('c2-agent-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], SRC);await engine.executeRaw("UPDATE oauth_clients SET scope = 'read write agent', bound_tools = $2, bound_source_id = source_id, federated_read = ARRAY[source_id], delegated_namespace = 'job', delegated_slug_prefixes = NULL, bound_max_concurrent = 5 WHERE client_id = $1", [reg.clientId, ['get_page', 'search']]);await bindCredential(engine, { kind: 'client', id: reg.clientId }, { attestActor: 'qm', attestOps: ['get_agent_job', 'get_page', 'submit_agent'] });+ await readsUnscopedOnPurpose(engine, reg.clientId, 'client');tokens.agent = (await provider().exchangeClientCredentials(reg.clientId, reg.clientSecret!)).access_token;const as = { alice: { token: 'agent', actor: ALICE_ID }, bob: { token: 'agent', actor: BOB_ID }, bare: { token: 'agent' } };const prompt = 'Summarize the harbor ledger notes';diff --git a/test/access-on-behalf-of.test.ts b/test/access-on-behalf-of.test.tsindex 61022c7285..7cb6a32031 100644--- a/test/access-on-behalf-of.test.ts+++ b/test/access-on-behalf-of.test.ts@@ -49,6 +49,7 @@ import type { DoctorContext } from '../src/commands/doctor/context.ts';import { testBackends } from './helpers/test-backends.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';const DIMS = 1536;function vectorFor(text: string): number[] {@@ -159,6 +160,7 @@ for (const kind of testBackends()) {const minted = await mintLegacyToken(engine, { name, scopes, takesHolders: ['world'], sourceGrant: [SRC] });tokens[name] = { id: minted.id, token: minted.token };if (binding.member || binding.mayActFor) await bindCredential(engine, { kind: 'token', id: minted.id }, binding);+ if (!binding.member) await readsUnscopedOnPurpose(engine, minted.id);};await mint('bot', { mayActFor: ['member:alice-example', 'member:bob-example', 'group:team-a', 'guest'] });await mint('bot-dan', { member: 'dan-example', mayActFor: ['guest', 'member:alice-example', 'member:bob-example'] }, ['read', 'write']);diff --git a/test/access-owner-reads.test.ts b/test/access-owner-reads.test.tsindex 9b5422d4ce..7e253df222 100644--- a/test/access-owner-reads.test.ts+++ b/test/access-owner-reads.test.ts@@ -30,6 +30,7 @@ import type { AuthInfo } from '../src/core/ops/contract.ts';import { getBrainHotMemoryMeta, __resetHotMemoryCacheForTests } from '../src/core/facts/meta-hook.ts';import { testBackends } from './helpers/test-backends.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';const DIMS = 1536;function vectorFor(text: string): number[] {@@ -136,6 +137,7 @@ for (const kind of testBackends()) {const minted = await mintLegacyToken(engine, { name, scopes: ['read'], takesHolders: ['world'], sourceGrant: [SRC] });tokens[name] = minted.token;if (member) await bindCredential(engine, { kind: 'token', id: minted.id }, { member, ...(mayActFor ? { mayActFor } : {}) });+ else await readsUnscopedOnPurpose(engine, minted.id);};await mint('owner', OWNER, [`member:${OWNER}`, 'member:bob-example']);await mint('delegate', OWNER);diff --git a/test/access-qm-actor.test.ts b/test/access-qm-actor.test.tsindex c188218461..5fed1a2ec3 100644--- a/test/access-qm-actor.test.ts+++ b/test/access-qm-actor.test.ts@@ -124,7 +124,8 @@ for (const kind of testBackends()) {clients[name] = { id: c.clientId, secret: c.clientSecret ?? '', token: '' };return c.clientId;};- await bindCredential(engine, { kind: 'client', id: await register('qm') }, { attestActor: 'qm', attestOps: ATTEST_OPS });+ // GST-363: these attest credentials' calls without x-qm-actor read unscoped on purpose on this several-member brain.+ await bindCredential(engine, { kind: 'client', id: await register('qm') }, { attestActor: 'qm', attestOps: ATTEST_OPS, readsUnscoped: true });await register('plain');await bindCredential(engine, { kind: 'client', id: await register('defaults') }, { attestActor: 'qm' });await register('code', ['authorization_code']);@@ -137,7 +138,7 @@ for (const kind of testBackends()) {await engine.executeRaw("UPDATE oauth_clients SET private_pages = 'granted_sources' WHERE client_id = $1", [clients.qm!.id]);const minted = await mintLegacyToken(engine, { name: 'qm-legacy', scopes: ['read', 'write'], takesHolders: ['world'], sourceGrant: [SRC] });tokens.legacy = { id: minted.id, token: minted.token };- await bindCredential(engine, { kind: 'token', id: minted.id }, { attestActor: 'qm', attestOps: ATTEST_OPS });+ await bindCredential(engine, { kind: 'token', id: minted.id }, { attestActor: 'qm', attestOps: ATTEST_OPS, readsUnscoped: true });await rescopeLegacyToken(engine, parseRescopeTokenArgs(['qm-legacy', '--private-pages', 'granted-sources']));await linkMember(engine, 'alice-example', 'qm', ALICE_ID);await linkMember(engine, 'alice-example', 'qm', OIDC_ID);diff --git a/test/access-ungranted-member-writes.test.ts b/test/access-ungranted-member-writes.test.tsindex 53db50678d..b3f5cc7902 100644--- a/test/access-ungranted-member-writes.test.ts+++ b/test/access-ungranted-member-writes.test.ts@@ -39,6 +39,7 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { withEnv } from './helpers/with-env.ts';+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';const PRIVATE_SRC = 'private-alice-example';const SHARED_PAGE = 'notes/team-shared';@@ -100,6 +101,7 @@ for (const kind of testBackends()) {const minted = await mintLegacyToken(engine, { name, scopes: ['read', 'write'], takesHolders: ['world'], ...(sourceGrant ? { sourceGrant: [...sourceGrant] } : {}) });tokens[name] = minted.token;if (member) await engine.executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id = $1::uuid', [minted.id, member]);+ else await readsUnscopedOnPurpose(engine, minted.id);}}, 240_000);afterAll(async () => { await close?.(); }, 60_000);diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex d4953b0ebc..5196e5c29e 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -609,6 +609,8 @@"gbrain_access_origin_restricted(p_id integer, p_source_id text, p_type text, fm jsonb)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=506a29c639348746278d0c472b43a013bf2e39a8e83de4cd3641424116160c6d","gbrain_access_pending_covers(p_source text, p_slug text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=57448e941169ad1e65fbdab4bbe4572cc7b6f164ef19fd61a3666640e85f253c","gbrain_access_readers(fm jsonb)": "RETURNS text[] kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=18348cb56089106aaec6470076ee652d7ed3bfbcb20e950a24abd52a21e7a380",+ "gbrain_access_refresh_serves()": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d4fe6a3a2fdd179f677cf2778223a6e084b99414dcfbcd37b7268ecdd68cfac2",+ "gbrain_access_refresh_serves_trigger()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cfc246e282936cd9beb99ac87c59f8121412adf0d7bca856ee70cd939039e764","gbrain_access_stamp_folder_rules()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7fb49ce62f4f6153ef0c844a1816f5f5bb7d765b8610ff66fec137283469fc09","gbrain_access_state_unreadable()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fa6c6edac062270a2fcf9ff3e9c29f16242156e817a3710c273d8da9f5203943","gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2a431195dc4c4150e3428251d0dec0a685cdc2992525c1b4b54dff103d5d99c9",@@ -1908,7 +1910,8 @@"19 attest_actor text/text NULL","20 attest_ops ARRAY/_text NULL","21 attest_sources ARRAY/_text NULL",- "22 attest_read text/text NULL"+ "22 attest_read text/text NULL",+ "23 reads_unscoped timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -3184,7 +3187,8 @@"36 attest_actor text/text NULL","37 attest_ops ARRAY/_text NULL","38 attest_sources ARRAY/_text NULL",- "39 attest_read text/text NULL"+ "39 attest_read text/text NULL",+ "40 reads_unscoped timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -4684,9 +4688,12 @@},"triggers": {"access_members.access_members_mark_restricted": "CREATE TRIGGER access_members_mark_restricted AFTER INSERT ON public.access_members FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()",+ "access_members.access_members_refresh_serves": "CREATE TRIGGER access_members_refresh_serves AFTER INSERT OR DELETE OR UPDATE OF disabled_at, tombstoned_at OR TRUNCATE ON public.access_members FOR EACH STATEMENT EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()","access_pending_coverage.access_pending_coverage_mark_restricted": "CREATE TRIGGER access_pending_coverage_mark_restricted AFTER INSERT ON public.access_pending_coverage FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()","access_rules.access_rules_mark_restricted": "CREATE TRIGGER access_rules_mark_restricted AFTER INSERT ON public.access_rules FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()","access_tokens.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.access_tokens DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()",+ "config.config_serves_refresh": "CREATE TRIGGER config_serves_refresh AFTER INSERT OR UPDATE ON public.config FOR EACH ROW WHEN ((new.key = 'access.serves'::text)) EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()",+ "config.config_serves_refresh_delete": "CREATE TRIGGER config_serves_refresh_delete AFTER DELETE ON public.config FOR EACH ROW WHEN ((old.key = 'access.serves'::text)) EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()","config.trust_generation_delete": "CREATE CONSTRAINT TRIGGER trust_generation_delete AFTER DELETE ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.key ~~ 'trust.%'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","config.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((new.key ~~ 'trust.%'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","config.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((((old.key ~~ 'trust.%'::text) OR (new.key ~~ 'trust.%'::text)) AND ((old.key IS DISTINCT FROM new.key) OR (old.value IS DISTINCT FROM new.value)))) EXECUTE FUNCTION gbrain_bump_trust_generation()",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex c95efbda38..8316d4b921 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -609,6 +609,8 @@"gbrain_access_origin_restricted(p_id integer, p_source_id text, p_type text, fm jsonb)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=506a29c639348746278d0c472b43a013bf2e39a8e83de4cd3641424116160c6d","gbrain_access_pending_covers(p_source text, p_slug text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=57448e941169ad1e65fbdab4bbe4572cc7b6f164ef19fd61a3666640e85f253c","gbrain_access_readers(fm jsonb)": "RETURNS text[] kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=18348cb56089106aaec6470076ee652d7ed3bfbcb20e950a24abd52a21e7a380",+ "gbrain_access_refresh_serves()": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d4fe6a3a2fdd179f677cf2778223a6e084b99414dcfbcd37b7268ecdd68cfac2",+ "gbrain_access_refresh_serves_trigger()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cfc246e282936cd9beb99ac87c59f8121412adf0d7bca856ee70cd939039e764","gbrain_access_stamp_folder_rules()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7fb49ce62f4f6153ef0c844a1816f5f5bb7d765b8610ff66fec137283469fc09","gbrain_access_state_unreadable()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fa6c6edac062270a2fcf9ff3e9c29f16242156e817a3710c273d8da9f5203943","gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2a431195dc4c4150e3428251d0dec0a685cdc2992525c1b4b54dff103d5d99c9",@@ -1908,7 +1910,8 @@"19 attest_actor text/text NULL","20 attest_ops ARRAY/_text NULL","21 attest_sources ARRAY/_text NULL",- "22 attest_read text/text NULL"+ "22 attest_read text/text NULL",+ "23 reads_unscoped timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -3184,7 +3187,8 @@"36 attest_actor text/text NULL","37 attest_ops ARRAY/_text NULL","38 attest_sources ARRAY/_text NULL",- "39 attest_read text/text NULL"+ "39 attest_read text/text NULL",+ "40 reads_unscoped timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -4684,9 +4688,12 @@},"triggers": {"access_members.access_members_mark_restricted": "CREATE TRIGGER access_members_mark_restricted AFTER INSERT ON public.access_members FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()",+ "access_members.access_members_refresh_serves": "CREATE TRIGGER access_members_refresh_serves AFTER INSERT OR DELETE OR UPDATE OF disabled_at, tombstoned_at OR TRUNCATE ON public.access_members FOR EACH STATEMENT EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()","access_pending_coverage.access_pending_coverage_mark_restricted": "CREATE TRIGGER access_pending_coverage_mark_restricted AFTER INSERT ON public.access_pending_coverage FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()","access_rules.access_rules_mark_restricted": "CREATE TRIGGER access_rules_mark_restricted AFTER INSERT ON public.access_rules FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()","access_tokens.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.access_tokens DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()",+ "config.config_serves_refresh": "CREATE TRIGGER config_serves_refresh AFTER INSERT OR UPDATE ON public.config FOR EACH ROW WHEN ((new.key = 'access.serves'::text)) EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()",+ "config.config_serves_refresh_delete": "CREATE TRIGGER config_serves_refresh_delete AFTER DELETE ON public.config FOR EACH ROW WHEN ((old.key = 'access.serves'::text)) EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()","config.trust_generation_delete": "CREATE CONSTRAINT TRIGGER trust_generation_delete AFTER DELETE ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.key ~~ 'trust.%'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","config.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((new.key ~~ 'trust.%'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","config.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((((old.key ~~ 'trust.%'::text) OR (new.key ~~ 'trust.%'::text)) AND ((old.key IS DISTINCT FROM new.key) OR (old.value IS DISTINCT FROM new.value)))) EXECUTE FUNCTION gbrain_bump_trust_generation()",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex e5dcfae3e2..f752fff869 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -609,6 +609,8 @@"gbrain_access_origin_restricted(p_id integer, p_source_id text, p_type text, fm jsonb)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=506a29c639348746278d0c472b43a013bf2e39a8e83de4cd3641424116160c6d","gbrain_access_pending_covers(p_source text, p_slug text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=57448e941169ad1e65fbdab4bbe4572cc7b6f164ef19fd61a3666640e85f253c","gbrain_access_readers(fm jsonb)": "RETURNS text[] kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=18348cb56089106aaec6470076ee652d7ed3bfbcb20e950a24abd52a21e7a380",+ "gbrain_access_refresh_serves()": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d4fe6a3a2fdd179f677cf2778223a6e084b99414dcfbcd37b7268ecdd68cfac2",+ "gbrain_access_refresh_serves_trigger()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cfc246e282936cd9beb99ac87c59f8121412adf0d7bca856ee70cd939039e764","gbrain_access_stamp_folder_rules()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7fb49ce62f4f6153ef0c844a1816f5f5bb7d765b8610ff66fec137283469fc09","gbrain_access_state_unreadable()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fa6c6edac062270a2fcf9ff3e9c29f16242156e817a3710c273d8da9f5203943","gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2a431195dc4c4150e3428251d0dec0a685cdc2992525c1b4b54dff103d5d99c9",@@ -1904,7 +1906,8 @@"19 attest_actor text/text NULL","20 attest_ops ARRAY/_text NULL","21 attest_sources ARRAY/_text NULL",- "22 attest_read text/text NULL"+ "22 attest_read text/text NULL",+ "23 reads_unscoped timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -3180,7 +3183,8 @@"36 attest_actor text/text NULL","37 attest_ops ARRAY/_text NULL","38 attest_sources ARRAY/_text NULL",- "39 attest_read text/text NULL"+ "39 attest_read text/text NULL",+ "40 reads_unscoped timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -4680,9 +4684,12 @@},"triggers": {"access_members.access_members_mark_restricted": "CREATE TRIGGER access_members_mark_restricted AFTER INSERT ON public.access_members FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()",+ "access_members.access_members_refresh_serves": "CREATE TRIGGER access_members_refresh_serves AFTER INSERT OR DELETE OR UPDATE OF disabled_at, tombstoned_at OR TRUNCATE ON public.access_members FOR EACH STATEMENT EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()","access_pending_coverage.access_pending_coverage_mark_restricted": "CREATE TRIGGER access_pending_coverage_mark_restricted AFTER INSERT ON public.access_pending_coverage FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()","access_rules.access_rules_mark_restricted": "CREATE TRIGGER access_rules_mark_restricted AFTER INSERT ON public.access_rules FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()","access_tokens.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.access_tokens DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()",+ "config.config_serves_refresh": "CREATE TRIGGER config_serves_refresh AFTER INSERT OR UPDATE ON public.config FOR EACH ROW WHEN ((new.key = 'access.serves'::text)) EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()",+ "config.config_serves_refresh_delete": "CREATE TRIGGER config_serves_refresh_delete AFTER DELETE ON public.config FOR EACH ROW WHEN ((old.key = 'access.serves'::text)) EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()","config.trust_generation_delete": "CREATE CONSTRAINT TRIGGER trust_generation_delete AFTER DELETE ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.key ~~ 'trust.%'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","config.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((new.key ~~ 'trust.%'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","config.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((((old.key ~~ 'trust.%'::text) OR (new.key ~~ 'trust.%'::text)) AND ((old.key IS DISTINCT FROM new.key) OR (old.value IS DISTINCT FROM new.value)))) EXECUTE FUNCTION gbrain_bump_trust_generation()",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 3f5ed40c8a..755a0e9da2 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -613,6 +613,8 @@"gbrain_access_origin_restricted(p_id integer, p_source_id text, p_type text, fm jsonb)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=506a29c639348746278d0c472b43a013bf2e39a8e83de4cd3641424116160c6d","gbrain_access_pending_covers(p_source text, p_slug text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=57448e941169ad1e65fbdab4bbe4572cc7b6f164ef19fd61a3666640e85f253c","gbrain_access_readers(fm jsonb)": "RETURNS text[] kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=18348cb56089106aaec6470076ee652d7ed3bfbcb20e950a24abd52a21e7a380",+ "gbrain_access_refresh_serves()": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d4fe6a3a2fdd179f677cf2778223a6e084b99414dcfbcd37b7268ecdd68cfac2",+ "gbrain_access_refresh_serves_trigger()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cfc246e282936cd9beb99ac87c59f8121412adf0d7bca856ee70cd939039e764","gbrain_access_stamp_folder_rules()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7fb49ce62f4f6153ef0c844a1816f5f5bb7d765b8610ff66fec137283469fc09","gbrain_access_state_unreadable()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fa6c6edac062270a2fcf9ff3e9c29f16242156e817a3710c273d8da9f5203943","gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2a431195dc4c4150e3428251d0dec0a685cdc2992525c1b4b54dff103d5d99c9",@@ -1909,7 +1911,8 @@"19 attest_actor text/text NULL","20 attest_ops ARRAY/_text NULL","21 attest_sources ARRAY/_text NULL",- "22 attest_read text/text NULL"+ "22 attest_read text/text NULL",+ "23 reads_unscoped timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -3196,7 +3199,8 @@"36 attest_actor text/text NULL","37 attest_ops ARRAY/_text NULL","38 attest_sources ARRAY/_text NULL",- "39 attest_read text/text NULL"+ "39 attest_read text/text NULL",+ "40 reads_unscoped timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -4679,9 +4683,12 @@},"triggers": {"access_members.access_members_mark_restricted": "CREATE TRIGGER access_members_mark_restricted AFTER INSERT ON public.access_members FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()",+ "access_members.access_members_refresh_serves": "CREATE TRIGGER access_members_refresh_serves AFTER INSERT OR DELETE OR UPDATE OF disabled_at, tombstoned_at OR TRUNCATE ON public.access_members FOR EACH STATEMENT EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()","access_pending_coverage.access_pending_coverage_mark_restricted": "CREATE TRIGGER access_pending_coverage_mark_restricted AFTER INSERT ON public.access_pending_coverage FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()","access_rules.access_rules_mark_restricted": "CREATE TRIGGER access_rules_mark_restricted AFTER INSERT ON public.access_rules FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()","access_tokens.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.access_tokens DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()",+ "config.config_serves_refresh": "CREATE TRIGGER config_serves_refresh AFTER INSERT OR UPDATE ON public.config FOR EACH ROW WHEN ((new.key = 'access.serves'::text)) EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()",+ "config.config_serves_refresh_delete": "CREATE TRIGGER config_serves_refresh_delete AFTER DELETE ON public.config FOR EACH ROW WHEN ((old.key = 'access.serves'::text)) EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()","config.trust_generation_delete": "CREATE CONSTRAINT TRIGGER trust_generation_delete AFTER DELETE ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.key ~~ 'trust.%'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","config.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((new.key ~~ 'trust.%'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","config.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((((old.key ~~ 'trust.%'::text) OR (new.key ~~ 'trust.%'::text)) AND ((old.key IS DISTINCT FROM new.key) OR (old.value IS DISTINCT FROM new.value)))) EXECUTE FUNCTION gbrain_bump_trust_generation()",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 1069576faa..4a62b855ee 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -613,6 +613,8 @@"gbrain_access_origin_restricted(p_id integer, p_source_id text, p_type text, fm jsonb)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=506a29c639348746278d0c472b43a013bf2e39a8e83de4cd3641424116160c6d","gbrain_access_pending_covers(p_source text, p_slug text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=57448e941169ad1e65fbdab4bbe4572cc7b6f164ef19fd61a3666640e85f253c","gbrain_access_readers(fm jsonb)": "RETURNS text[] kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=18348cb56089106aaec6470076ee652d7ed3bfbcb20e950a24abd52a21e7a380",+ "gbrain_access_refresh_serves()": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d4fe6a3a2fdd179f677cf2778223a6e084b99414dcfbcd37b7268ecdd68cfac2",+ "gbrain_access_refresh_serves_trigger()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cfc246e282936cd9beb99ac87c59f8121412adf0d7bca856ee70cd939039e764","gbrain_access_stamp_folder_rules()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7fb49ce62f4f6153ef0c844a1816f5f5bb7d765b8610ff66fec137283469fc09","gbrain_access_state_unreadable()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fa6c6edac062270a2fcf9ff3e9c29f16242156e817a3710c273d8da9f5203943","gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2a431195dc4c4150e3428251d0dec0a685cdc2992525c1b4b54dff103d5d99c9",@@ -1909,7 +1911,8 @@"19 attest_actor text/text NULL","20 attest_ops ARRAY/_text NULL","21 attest_sources ARRAY/_text NULL",- "22 attest_read text/text NULL"+ "22 attest_read text/text NULL",+ "23 reads_unscoped timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -3196,7 +3199,8 @@"36 attest_actor text/text NULL","37 attest_ops ARRAY/_text NULL","38 attest_sources ARRAY/_text NULL",- "39 attest_read text/text NULL"+ "39 attest_read text/text NULL",+ "40 reads_unscoped timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -4679,9 +4683,12 @@},"triggers": {"access_members.access_members_mark_restricted": "CREATE TRIGGER access_members_mark_restricted AFTER INSERT ON public.access_members FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()",+ "access_members.access_members_refresh_serves": "CREATE TRIGGER access_members_refresh_serves AFTER INSERT OR DELETE OR UPDATE OF disabled_at, tombstoned_at OR TRUNCATE ON public.access_members FOR EACH STATEMENT EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()","access_pending_coverage.access_pending_coverage_mark_restricted": "CREATE TRIGGER access_pending_coverage_mark_restricted AFTER INSERT ON public.access_pending_coverage FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()","access_rules.access_rules_mark_restricted": "CREATE TRIGGER access_rules_mark_restricted AFTER INSERT ON public.access_rules FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()","access_tokens.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.access_tokens DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()",+ "config.config_serves_refresh": "CREATE TRIGGER config_serves_refresh AFTER INSERT OR UPDATE ON public.config FOR EACH ROW WHEN ((new.key = 'access.serves'::text)) EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()",+ "config.config_serves_refresh_delete": "CREATE TRIGGER config_serves_refresh_delete AFTER DELETE ON public.config FOR EACH ROW WHEN ((old.key = 'access.serves'::text)) EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()","config.trust_generation_delete": "CREATE CONSTRAINT TRIGGER trust_generation_delete AFTER DELETE ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.key ~~ 'trust.%'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","config.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((new.key ~~ 'trust.%'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","config.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((((old.key ~~ 'trust.%'::text) OR (new.key ~~ 'trust.%'::text)) AND ((old.key IS DISTINCT FROM new.key) OR (old.value IS DISTINCT FROM new.value)))) EXECUTE FUNCTION gbrain_bump_trust_generation()",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex 626ac9a4d5..70228bddb6 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -613,6 +613,8 @@"gbrain_access_origin_restricted(p_id integer, p_source_id text, p_type text, fm jsonb)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=506a29c639348746278d0c472b43a013bf2e39a8e83de4cd3641424116160c6d","gbrain_access_pending_covers(p_source text, p_slug text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=57448e941169ad1e65fbdab4bbe4572cc7b6f164ef19fd61a3666640e85f253c","gbrain_access_readers(fm jsonb)": "RETURNS text[] kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=18348cb56089106aaec6470076ee652d7ed3bfbcb20e950a24abd52a21e7a380",+ "gbrain_access_refresh_serves()": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=d4fe6a3a2fdd179f677cf2778223a6e084b99414dcfbcd37b7268ecdd68cfac2",+ "gbrain_access_refresh_serves_trigger()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cfc246e282936cd9beb99ac87c59f8121412adf0d7bca856ee70cd939039e764","gbrain_access_stamp_folder_rules()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7fb49ce62f4f6153ef0c844a1816f5f5bb7d765b8610ff66fec137283469fc09","gbrain_access_state_unreadable()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=fa6c6edac062270a2fcf9ff3e9c29f16242156e817a3710c273d8da9f5203943","gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2a431195dc4c4150e3428251d0dec0a685cdc2992525c1b4b54dff103d5d99c9",@@ -1905,7 +1907,8 @@"19 attest_actor text/text NULL","20 attest_ops ARRAY/_text NULL","21 attest_sources ARRAY/_text NULL",- "22 attest_read text/text NULL"+ "22 attest_read text/text NULL",+ "23 reads_unscoped timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -3192,7 +3195,8 @@"36 attest_actor text/text NULL","37 attest_ops ARRAY/_text NULL","38 attest_sources ARRAY/_text NULL",- "39 attest_read text/text NULL"+ "39 attest_read text/text NULL",+ "40 reads_unscoped timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -4675,9 +4679,12 @@},"triggers": {"access_members.access_members_mark_restricted": "CREATE TRIGGER access_members_mark_restricted AFTER INSERT ON public.access_members FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()",+ "access_members.access_members_refresh_serves": "CREATE TRIGGER access_members_refresh_serves AFTER INSERT OR DELETE OR UPDATE OF disabled_at, tombstoned_at OR TRUNCATE ON public.access_members FOR EACH STATEMENT EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()","access_pending_coverage.access_pending_coverage_mark_restricted": "CREATE TRIGGER access_pending_coverage_mark_restricted AFTER INSERT ON public.access_pending_coverage FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()","access_rules.access_rules_mark_restricted": "CREATE TRIGGER access_rules_mark_restricted AFTER INSERT ON public.access_rules FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted()","access_tokens.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.access_tokens DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()",+ "config.config_serves_refresh": "CREATE TRIGGER config_serves_refresh AFTER INSERT OR UPDATE ON public.config FOR EACH ROW WHEN ((new.key = 'access.serves'::text)) EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()",+ "config.config_serves_refresh_delete": "CREATE TRIGGER config_serves_refresh_delete AFTER DELETE ON public.config FOR EACH ROW WHEN ((old.key = 'access.serves'::text)) EXECUTE FUNCTION gbrain_access_refresh_serves_trigger()","config.trust_generation_delete": "CREATE CONSTRAINT TRIGGER trust_generation_delete AFTER DELETE ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.key ~~ 'trust.%'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","config.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((new.key ~~ 'trust.%'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","config.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.config DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((((old.key ~~ 'trust.%'::text) OR (new.key ~~ 'trust.%'::text)) AND ((old.key IS DISTINCT FROM new.key) OR (old.value IS DISTINCT FROM new.value)))) EXECUTE FUNCTION gbrain_bump_trust_generation()",diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex 3b272ef293..17c7d95f62 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -87,6 +87,8 @@" [INFO] access_policy_invalid: Not applicable: no source has a folder rule."," [INFO] access_policy_store_mismatch: Not applicable: no source has a folder rule."," [INFO] unlabeled_people_folders: Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).",+ " [INFO] unscoped_shared_reads: Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).",+ " [INFO] shared_stdio_binding: Not applicable: config mcp.stdio_member is unset, so no stdio session on this host reads as a member."," [INFO] access_may_act_for_wildcard: Not applicable: no page names readers and no member exists."," [INFO] access_owner_reads_restricted: Not applicable: the owner opt-in (access.owner_reads_restricted) is off; the owner reads a page that names readers or sits under a rule only when listed."," [INFO] access_raw_only_rules: Not applicable: every folder and page rule also keeps the pages and facts derived from its pages to its readers (no rule has covers_derived: false).",@@ -271,7 +273,7 @@" [OK] fence_integrity: No malformed facts or takes fence is held, stored or waiting in a checkout (2 source(s) scanned)."," [OK] search_mode: Mode: conservative (no per-key overrides — mode bundle is canonical)."," [OK] hidden_by_search_policy: No pages hidden by search-exclude policy.",- " [OK] eval_drift: No retrieval-affecting files changed in working tree.",+ " [OK] eval_drift: 1 retrieval-affecting file(s) changed since HEAD: src/core/search/private-visibility.ts. Re-run `gbrain eval run-all` after committing these changes."," [OK] reranker_health: Reranker disabled — no failures expected"," [OK] batch_retry_health: No exhausted batch retries in last 24h."," [OK] wedged_queue: PGLite — no queue to check",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 7b9a5d1f5d..246a1587b3 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -1057,6 +1057,24 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).",+ "name": "unscoped_shared_reads",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: config mcp.stdio_member is unset, so no stdio session on this host reads as a member.",+ "name": "shared_stdio_binding",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",@@ -4082,7 +4100,7 @@{"category": "brain","elapsed_ms": "<volatile>",- "message": "No retrieval-affecting files changed in working tree.",+ "message": "1 retrieval-affecting file(s) changed since HEAD: src/core/search/private-visibility.ts. Re-run `gbrain eval run-all` after committing these changes.","name": "eval_drift","status": "ok"},diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex 1a48759622..8d95b38581 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -1128,6 +1128,24 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).",+ "name": "unscoped_shared_reads",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: config mcp.stdio_member is unset, so no stdio session on this host reads as a member.",+ "name": "shared_stdio_binding",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",@@ -4514,7 +4532,7 @@{"category": "brain","elapsed_ms": "<volatile>",- "message": "No retrieval-affecting files changed in working tree.",+ "message": "1 retrieval-affecting file(s) changed since HEAD: src/core/search/private-visibility.ts. Re-run `gbrain eval run-all` after committing these changes.","name": "eval_drift","status": "ok"},@@ -6251,6 +6269,24 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).",+ "name": "unscoped_shared_reads",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: config mcp.stdio_member is unset, so no stdio session on this host reads as a member.",+ "name": "shared_stdio_binding",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",@@ -9649,7 +9685,7 @@{"category": "brain","elapsed_ms": "<volatile>",- "message": "No retrieval-affecting files changed in working tree.",+ "message": "1 retrieval-affecting file(s) changed since HEAD: src/core/search/private-visibility.ts. Re-run `gbrain eval run-all` after committing these changes.","name": "eval_drift","status": "ok"},diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex ffab954553..1be1647440 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -1124,6 +1124,24 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).",+ "name": "unscoped_shared_reads",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: config mcp.stdio_member is unset, so no stdio session on this host reads as a member.",+ "name": "shared_stdio_binding",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",@@ -4524,7 +4542,7 @@{"category": "brain","elapsed_ms": "<volatile>",- "message": "No retrieval-affecting files changed in working tree.",+ "message": "1 retrieval-affecting file(s) changed since HEAD: src/core/search/private-visibility.ts. Re-run `gbrain eval run-all` after committing these changes.","name": "eval_drift","status": "ok"},@@ -6255,6 +6273,24 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).",+ "name": "unscoped_shared_reads",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: config mcp.stdio_member is unset, so no stdio session on this host reads as a member.",+ "name": "shared_stdio_binding",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",@@ -9667,7 +9703,7 @@{"category": "brain","elapsed_ms": "<volatile>",- "message": "No retrieval-affecting files changed in working tree.",+ "message": "1 retrieval-affecting file(s) changed since HEAD: src/core/search/private-visibility.ts. Re-run `gbrain eval run-all` after committing these changes.","name": "eval_drift","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 33216de7b1..b4e425cef3 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -970,6 +970,24 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).",+ "name": "unscoped_shared_reads",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: config mcp.stdio_member is unset, so no stdio session on this host reads as a member.",+ "name": "shared_stdio_binding",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 932946be75..b0877a0519 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1017,6 +1017,24 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).",+ "name": "unscoped_shared_reads",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: config mcp.stdio_member is unset, so no stdio session on this host reads as a member.",+ "name": "shared_stdio_binding",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 038abf31ee..c8f399c4ae 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1013,6 +1013,24 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).",+ "name": "unscoped_shared_reads",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: config mcp.stdio_member is unset, so no stdio session on this host reads as a member.",+ "name": "shared_stdio_binding",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "brain","elapsed_ms": "<volatile>",@@ -3715,7 +3733,7 @@{"category": "brain","elapsed_ms": "<volatile>",- "message": "No retrieval-affecting files changed in working tree.",+ "message": "1 retrieval-affecting file(s) changed since HEAD: src/core/search/private-visibility.ts. Re-run `gbrain eval run-all` after committing these changes.","name": "eval_drift","status": "ok"},diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex e159fdc11e..bd1762df01 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -393,6 +393,14 @@"category": "brain","name": "unlabeled_people_folders"},+ {+ "category": "brain",+ "name": "unscoped_shared_reads"+ },+ {+ "category": "brain",+ "name": "shared_stdio_binding"+ },{"category": "brain","name": "access_may_act_for_wildcard"diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 698e329aa7..e193670e21 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6719,6 +6719,7 @@"budgetUsdPerDay?: string | null | undefined","clientId: string","clientName?: string | undefined",+ "createdAt?: number | null | undefined","delegatedNamespace?: \"prefixes\" | \"job\" | undefined","delegatedSlugPrefixes?: string[] | null | undefined","effectiveSurface?: \"verbs\" | \"starter\" | \"full\" | undefined",@@ -6735,6 +6736,7 @@"minTrust?: \"user_confirmed\" | \"operator_curated\" | \"tool_observed\" | \"agent_written\" | \"unknown\" | \"external_untrusted\" | undefined","principal?: { kind: \"oauth_client\" | \"legacy_token\"; id: string; } | undefined","privatePages?: { mode: \"granted_sources\"; sources: string[]; } | undefined",+ "readsUnscoped?: boolean | undefined","scopes: string[]","sourceActive?: boolean | undefined","sourceId?: string | undefined",@@ -6857,7 +6859,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_member_disabled\" | \"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_store_mismatch\" | \"access_rule_invalid\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"access_member_id_retired\" | \"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_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_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_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\" | \"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_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\" | \"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\" | \"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\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"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\" | \"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_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\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_retire_superseded\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"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\" | \"target_escape\" | \"timeline_comment_markup\" | \"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_member_disabled\" | \"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_store_mismatch\" | \"access_rule_invalid\" | \"requester_scope_required\" | \"requester_scope_unknown\" | \"credential_scope_required\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"access_member_id_retired\" | \"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_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_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_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\" | \"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_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\" | \"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\" | \"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\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"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\" | \"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_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\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_retire_superseded\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"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\" | \"target_escape\" | \"timeline_comment_markup\" | \"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/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 50a0c623f6..d86d524fab 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 302,+ "count": 303,"gaps": [17,18,@@ -103,7 +103,7 @@"widenIdentityIndex": "86a6176bd7637d964dbc1d3cd3b1bdfa3ca0161e1ee248c37d7380a1471282e6","withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59"},- "latest": 307,+ "latest": 308,"records": [{"handler": {@@ -5002,6 +5002,19 @@"transaction": "absent","verify": "absent","version": 307+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "requester_scope",+ "sql": {+ "length": 2072,+ "sha256": "b631dbd4ceca33ed40b55c2e9aaea7b1cebcb624158c9193037a0bb0d04728f8"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 308}],"versions": [@@ -5306,7 +5319,8 @@304,305,306,- 307+ 307,+ 308]},"normalizer": "migrations-record-v1"diff --git a/test/helpers/access-lineage-fixture.ts b/test/helpers/access-lineage-fixture.tsindex 5d09a8d441..08d821a3d4 100644--- a/test/helpers/access-lineage-fixture.ts+++ b/test/helpers/access-lineage-fixture.ts@@ -22,6 +22,7 @@ import { dispatchToolCall } from '../../src/mcp/dispatch.ts';import { __resetPrivateVisibilityCacheForTests } from '../../src/core/search/private-visibility.ts';import { setOwner } from '../../src/core/access/owner.ts';import { bindCredential } from '../../src/core/access/members.ts';+import { readsUnscopedOnPurpose } from './reads-unscoped.ts';import { applyApproved, getRevision, previewApply, proposeRevision, type ProposalResult } from '../../src/core/access/policy.ts';import { POLICY_FILE, syncGitPolicy, writeApprovedFile, writeGitRules } from '../../src/core/access/policy-git.ts';import { serializePolicyYaml, type FolderRule } from '../../src/core/access/folder-rules.ts';@@ -174,6 +175,7 @@ export async function buildLineageBrain(spec: LineageSpec): Promise<LineageBraintokenIds[c.name] = minted.id;if (c.member || c.mayActFor) await bindCredential(engine, { kind: 'token', id: minted.id }, { ...(c.member ? { member: c.member } : {}), ...(c.mayActFor ? { mayActFor: c.mayActFor } : {}) });if (c.grantedSources) await rescopeLegacyToken(engine, parseRescopeTokenArgs([c.name, '--private-pages', 'granted-sources']));+ if (!c.member && !c.audience?.length) await readsUnscopedOnPurpose(engine, minted.id);}if (spec.owner) await setOwner(engine, spec.owner);const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });diff --git a/test/helpers/config-reader-registry.ts b/test/helpers/config-reader-registry.tsindex 51f60d2165..3535f1b6f4 100644--- a/test/helpers/config-reader-registry.ts+++ b/test/helpers/config-reader-registry.ts@@ -25,6 +25,8 @@ export interface InternalConfigState {export const INTERNAL_CONFIG_STATE: readonly InternalConfigState[] = [{ key: 'version', reason: 'schema version stamp written by migrate.ts' },+ { key: 'access.serves_derived', reason: 'whether two or more members are enabled, kept by the v308 trigger on access_members (search/private-visibility.ts servesPolicyFrom); a hand edit would lie about whom the brain serves' },+ { key: 'access.serves_since', reason: 'when the brain first served several people, set once by the v308 trigger and never cleared; it starts the unscoped-read grace (access/requester-scope.ts)' },{ key: 'access.restrictions_present', reason: 'sticky member-access marker a v282 trigger sets once a page names readers or a member exists (search/private-visibility.ts); clearing it would send remote reads down the unrestricted fast path' },{ key: '_internal.link_extraction_generation', reason: 'link-extraction watermark generation (link-extraction-watermark.ts)' },{ key: 'code.cluster_generation', reason: 'code-intel traversal cache generation counter' },diff --git a/test/helpers/reads-unscoped.ts b/test/helpers/reads-unscoped.tsnew file mode 100644index 0000000000..b579da7e7b--- /dev/null+++ b/test/helpers/reads-unscoped.ts@@ -0,0 +1,12 @@+/**+ * GST-363: on a brain with two or more enabled members, a remote read from a credential bound to no member is refused+ * (requester_scope_required) unless the operator marked it reads_unscoped. Suites written before that refusal pin what+ * an unbound credential reads (nothing restricted, every world page); their fixtures mark those credentials with this,+ * the same state `gbrain auth rescope --reads-unscoped --yes` writes, so the behaviour they pin is unchanged and does+ * not depend on whether the credential was minted in the same second as the brain's second member.+ */+import type { BrainEngine } from '../../src/core/engine.ts';++export async function readsUnscopedOnPurpose(engine: Pick<BrainEngine, 'executeRaw'>, id: string, kind: 'token' | 'client' = 'token'): Promise<void> {+ await engine.executeRaw(kind === 'token' ? 'UPDATE access_tokens SET reads_unscoped = now() WHERE id::text = $1' : 'UPDATE oauth_clients SET reads_unscoped = now() WHERE client_id = $1', [id]);+}diff --git a/test/member-read-access.test.ts b/test/member-read-access.test.tsindex c8a5d269e2..4ff8944aba 100644--- a/test/member-read-access.test.ts+++ b/test/member-read-access.test.ts@@ -35,6 +35,7 @@ import type { WriteAuthority } from '../src/core/persistence/model.ts';import { testBackends } from './helpers/test-backends.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';const DIMS = 1536;function vectorFor(text: string): number[] {@@ -180,6 +181,7 @@ for (const kind of testBackends()) {tokens[name] = minted.token;tokenIds[name] = minted.id;if (member) await engine.executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id = $1::uuid', [minted.id, member]);+ else await readsUnscopedOnPurpose(engine, minted.id);};await mint('alice', 'alice-example');await mint('bob', 'bob-example');diff --git a/test/owner-reads-restricted.test.ts b/test/owner-reads-restricted.test.tsindex 9efa1b4019..1b916fe60d 100644--- a/test/owner-reads-restricted.test.ts+++ b/test/owner-reads-restricted.test.ts@@ -28,6 +28,7 @@ import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';import { sqlQueryForEngine } from '../src/core/sql-query.ts';import { mintLegacyToken } from '../src/core/token-mint.ts';+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';import { noGrantFederatedScope } from '../src/core/source-resolver.ts';import { dispatchToolCall } from '../src/mcp/dispatch.ts';import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';@@ -225,6 +226,7 @@ for (const kind of testBackends()) {tokens[name] = minted.token;tokenIds[name] = minted.id;if (member) await bindCredential(engine, { kind: 'token', id: minted.id }, { member });+ else await readsUnscopedOnPurpose(engine, minted.id);}await setOwner(engine, OWNER);}, 300_000);diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 8844966e9f..9a4d945427 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -557,6 +557,7 @@ test/repair-rename-identity-6729.test.tstest/repair-secret-spans.test.tstest/repair-unwithdrawn-facts-8819.test.tstest/request-tools-combined-gbra449.test.ts+test/requester-scope.test.tstest/retrieval-coverage-notices.test.tstest/schema-missing-tables.test.tstest/schema-replay-deadlock-6143.test.tsdiff --git a/test/qm-memory-tools.test.ts b/test/qm-memory-tools.test.tsindex dd436edd18..ec96d965c3 100644--- a/test/qm-memory-tools.test.ts+++ b/test/qm-memory-tools.test.ts@@ -42,6 +42,7 @@ import { withTrustPromotion } from '../src/core/persistence/context.ts';import type { AuthInfo } from '../src/core/ops/contract.ts';import { testBackends } from './helpers/test-backends.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';const DIMS = 1536;const TICKS = String.fromCharCode(96).repeat(3);@@ -215,6 +216,8 @@ for (const kind of testBackends()) {const legacyRead = await mintLegacyToken(engine, { name: 'qm-mem-legacy-ro-' + randomUUID().slice(0, 8), scopes: ['read'], takesHolders: ['world'], sourceGrant: [SRC] });await bindCredential(engine, { kind: 'token', id: legacyRead.id }, { attestActor: 'qm', attestOps: ATTEST_OPS });tokens.legacyRead = legacyRead.token;+ for (const c of [qm, plain, qmDefault]) await readsUnscopedOnPurpose(engine, c.id, 'client');+ for (const t of [legacy, legacyRead]) await readsUnscopedOnPurpose(engine, t.id);await linkMember(engine, 'alice-example', 'qm', ALICE_ID);await linkMember(engine, 'bob-example', 'qm', BOB_ID);await linkMember(engine, 'carol-example', 'qm', CAROL_ID);diff --git a/test/requester-scope.test.ts b/test/requester-scope.test.tsnew file mode 100644index 0000000000..7f77d099a8--- /dev/null+++ b/test/requester-scope.test.ts@@ -0,0 +1,591 @@+/**+ * GST-363 (PR 2): a brain that serves several people refuses remote reads from a connection bound to nobody.+ *+ * 1. Protects: on a brain with two or more enabled members (or config access.serves = several), every remote read op+ * from a credential or stdio server bound to no member is refused with requester_scope_required before its handler+ * runs; a connection that existed when the brain started serving several people reads for 14 days with an in-band+ * notice (_meta.access.requester_scope) first; member-bound, audience-naming and attested calls, and credentials+ * the operator marked --reads-unscoped, read as before; a one-person brain with several sources sees nothing new;+ * hosted brains (access.requester_scope_enforce = false) get the notice and no refusal; agent jobs get the same+ * gate; creating an unbound credential on such a brain is refused with credential_scope_required.+ * 2. Fails when: a read op answers an unbound key after the grace, a new read op is neither refused nor exempted, the+ * grace notice or the refusal loses its fix or date, a bound key or an attested call is refused, the one-person+ * brain gets a notice, the hosted switch still refuses a DCR client, or the trigger restarts the grace.+ * 3. Existing coverage: setup-serves-several.test.ts (labelling, brainServes), access-qm-actor.test.ts (attested+ * calls), access-on-behalf-of.test.ts (audiences), member-read-access.test.ts (bound reads).+ * 4. Real seams: legacy tokens through the serve --http legacy transport over a real socket (startHttpTransport) and+ * the OAuth verifier; dispatchToolCall remote=true over stdio; the v308 trigger on PGLite (repo-less and a repo+ * brain) and Postgres when DATABASE_URL is set; `bun src/cli.ts auth` spawned against a temp GBRAIN_HOME.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+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 { 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 { mintLegacyToken } from '../src/core/token-mint.ts';+import { operations } from '../src/core/operations.ts';+import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';+import { startHttpTransport } from '../src/mcp/http-transport.ts';+import { RateLimiter } from '../src/mcp/rate-limit.ts';+import { addMember, bindCredential, disableMember, enableMember } from '../src/core/access/members.ts';+import { linkMember } from '../src/core/access/actor.ts';+import { readAudienceAssertions } from '../src/core/access/audience.ts';+import { brainServes } from '../src/core/access/serves.ts';+import { assertCredentialScoped, OWN_JOB_OPS, printUnscopedReadsUpgradeNotice, REQUESTER_SCOPE_EXEMPT, requiresRequesterScope, readReadsUnscopedChanges } from '../src/core/access/requester-scope.ts';+import { unscopedSharedReadsEntry } from '../src/commands/doctor/checks/unscoped-shared-reads.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import { takeBindingFlags } from '../src/commands/auth-binding.ts';+import { ownerLines } from '../src/commands/access.ts';+import { buildBrainTools } from '../src/core/minions/tools/brain-allowlist.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { runCli } from './helpers/cli-spawn.ts';+import { withEnv } from './helpers/with-env.ts';++const DAY = 24 * 3600 * 1000;+const iso = (ms: number) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z');+const PAGES: Record<string, string> = { 'notes/harbor-alpha': 'canaryalpha', 'notes/harbor-beta': 'canarybeta' };+const pageText = (slug: string, canary: string) => `---\ntype: note\ntitle: ${slug}\n---\n# ${slug}\n\nHarbor ledger notes ${canary}.\n`;+const roots: string[] = [];+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });++/**+ * Every read operation's requester-scope class, reviewed by hand: a new read op fails this list until someone decides+ * whether an unbound connection on a several-people brain may call it (add it to REQUESTER_SCOPE_EXEMPT) or not.+ */+const REVIEWED_EXEMPT = ['get_brain_identity', 'get_health', 'get_status_snapshot', 'join_brain', 'leave_brain', 'request_tools', 'search_modes', 'sync_brain_skills', 'whoami'];++type Call = { isError: boolean; text: string; json: Record<string, any>; meta: Record<string, any> | undefined; structured: Record<string, any> | undefined };+function shape(out: ToolResult): Call {+ 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, meta: out._meta as Record<string, any> | undefined, structured: out.structuredContent as Record<string, any> | undefined };+}++describe('requiresRequesterScope: every read op is classified (deny by default)', () => {+ test('every remote op declares mutating, and the exempt list is exactly the reviewed one', () => {+ expect(operations.filter(op => op.mutating === undefined).map(op => op.name)).toEqual([]);+ expect([...REQUESTER_SCOPE_EXEMPT].sort()).toEqual(REVIEWED_EXEMPT);+ expect([...OWN_JOB_OPS].sort()).toEqual(['get_job', 'wait_job']);+ for (const op of operations) {+ const expected = (op.mutating === false || (op.scope ?? 'read') === 'read') && !REVIEWED_EXEMPT.includes(op.name);+ expect({ op: op.name, gated: requiresRequesterScope(op, { scopes: ['read', 'write', 'admin'] }) }).toEqual({ op: op.name, gated: expected });+ }+ expect(requiresRequesterScope({ name: 'brand_new_read', mutating: undefined })).toBe(true);+ expect(requiresRequesterScope(operations.find(op => op.name === 'think'))).toBe(true);+ expect(requiresRequesterScope({ name: 'brand_new_read_scope_write', mutating: true, scope: 'read' })).toBe(true);+ expect(requiresRequesterScope({ name: 'brand_new_mutating_no_scope', mutating: true })).toBe(true);+ expect(requiresRequesterScope({ name: 'get_job', mutating: false }, { scopes: ['read'] })).toBe(false);+ expect(requiresRequesterScope({ name: 'get_job', mutating: false }, { scopes: ['admin'] })).toBe(true);+ expect(requiresRequesterScope({ name: 'get_job', mutating: false })).toBe(true);+ });+});++for (const kind of testBackends()) {+ describe(`refusing unscoped reads (${kind}, repo-less)`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let server: Awaited<ReturnType<typeof startHttpTransport>>;+ const provider = (dcr = false) => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))), ...(dcr ? { allowClientCredentialsDcr: true } : {}) });+ const keys: Record<string, { id: string; token: string }> = {};+ const mint = async (name: string, member?: string) => {+ const m = await mintLegacyToken(engine, { name, scopes: ['read', 'write'], takesHolders: ['world'] });+ if (member) await bindCredential(engine, { kind: 'token', id: m.id }, { member });+ keys[name] = { id: m.id, token: m.token };+ };+ const backdate = (name: string, daysAgo: number) => engine.executeRaw('UPDATE access_tokens SET created_at = $2::timestamptz WHERE id::text = $1', [keys[name]!.id, iso(Date.now() - daysAgo * DAY)]);+ const setSince = (daysAgo: number) => engine.setConfig('access.serves_since', iso(Date.now() - daysAgo * DAY));++ /** One tools/call over a real socket to the serve --http legacy transport. */+ async function http(name: string, tool: string, args: Record<string, unknown>): Promise<Call> {+ const res = await fetch(`http://127.0.0.1:${server.port}/mcp`, {+ method: 'POST', headers: { authorization: `Bearer ${keys[name]!.token}`, 'content-type': 'application/json', accept: 'application/json, text/event-stream' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args } }),+ });+ return shape((await res.json() as { result: ToolResult }).result);+ }+ const search = (name: string) => http(name, 'search', { query: 'harbor ledger notes', match: 'keyword', limit: 10 });+ const stdio = async (tool: string, args: Record<string, unknown>) => shape(await dispatchToolCall(engine, tool, args, { remote: true, transport: 'stdio', sourceId: 'default', takesHoldersAllowList: ['world'] }));+ const oauthCall = async (bearer: string, tool: string, args: Record<string, unknown>, extra: Record<string, unknown> = {}) => {+ const auth = await provider().verifyAccessToken(bearer) as unknown as AuthInfo;+ return shape(await dispatchToolCall(engine, tool, args, { remote: true, transport: 'http', auth, sourceId: 'default', takesHoldersAllowList: ['world'], ...extra }));+ };+ function refused(out: Call, reason: string) {+ expect({ isError: out.isError, code: out.json.code, reason: out.json.reason }).toEqual({ isError: true, code: 'requester_scope_required', reason });+ expect(out.structured?.error).toMatchObject({ code: 'requester_scope_required', reason });+ expect(out.structured?.error.fix).toMatchObject({ next: expect.any(String), argv: expect.arrayContaining(['--member', '<MEMBER>']) });+ for (const canary of Object.values(PAGES)) expect(out.text).not.toContain(canary);+ }++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else {+ const pglite = new PGLiteEngine();+ await pglite.connect({ engine: 'pglite' } as never);+ await pglite.initSchema();+ engine = pglite;+ close = () => pglite.disconnect();+ }+ __resetPrivateVisibilityCacheForTests();+ for (const [slug, canary] of Object.entries(PAGES)) await importFromContent(engine, slug, pageText(slug, canary), { sourceId: 'default', noEmbed: true });+ await addMember(engine, 'alice-example');+ await mint('old-unbound');+ await mint('alice-key', 'alice-example');+ server = await startHttpTransport({ port: 0, engine, surface: 'full', limiters: {+ ip: new RateLimiter({ limit: 10_000, windowMs: 60_000, lruCap: 100 }),+ token: new RateLimiter({ limit: 10_000, windowMs: 60_000, lruCap: 100 }),+ } });+ }, 240_000);+ afterAll(async () => { await server?.stop?.(true); await close?.(); }, 60_000);++ test('one member: nothing changes, no notice, and the brain has no several-people date', async () => {+ const out = await search('old-unbound');+ expect(out.isError).toBe(false);+ expect(out.text).toContain('canaryalpha');+ expect(out.meta?.access?.requester_scope).toBeUndefined();+ expect(await engine.getConfig('access.serves_derived')).toBe('one');+ expect(await engine.getConfig('access.serves_since')).toBeNull();+ }, 60_000);++ test('the second member sets the flag and the date once; disabling and re-enabling keeps the date', async () => {+ await addMember(engine, 'bob-example');+ expect(await engine.getConfig('access.serves_derived')).toBe('several');+ const since = await engine.getConfig('access.serves_since');+ expect(since).toMatch(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/);+ expect((await brainServes(engine))).toMatchObject({ serves: 'several', from: 'members', since });+ await disableMember(engine, 'bob-example');+ expect(await engine.getConfig('access.serves_derived')).toBe('one');+ await enableMember(engine, 'bob-example');+ expect(await engine.getConfig('access.serves_derived')).toBe('several');+ expect(await engine.getConfig('access.serves_since')).toBe(since);+ await engine.setConfig('access.serves', 'one');+ expect((await brainServes(engine)).serves).toBe('one');+ expect((await search('old-unbound')).meta?.access?.requester_scope).toBeUndefined();+ await engine.unsetConfig('access.serves');+ }, 60_000);++ test('over HTTP, an old unbound key inside the grace reads with a notice naming the fix and the date', async () => {+ await setSince(1);+ await backdate('old-unbound', 2);+ const out = await search('old-unbound');+ expect(out.isError).toBe(false);+ expect(out.text).toContain('canaryalpha');+ const notice = out.meta?.access?.requester_scope;+ expect(notice).toMatchObject({ state: 'grace', connection: 'token old-unbound' });+ expect(Date.parse(notice.refuses_at)).toBe(Date.parse(await engine.getConfig('access.serves_since') as string) + 14 * DAY);+ expect(notice.fix).toMatchObject({ argv: ['gbrain', 'auth', 'rescope', '--token', 'old-unbound', '--member', '<MEMBER>'], next: expect.any(String), verify: { argv: ['gbrain', 'access', 'check', '--token', 'old-unbound'] } });+ expect(notice.message).toContain('--reads-unscoped --yes');+ }, 60_000);++ /**+ * The request's config reads fail (a statement timeout under load): the whole-table snapshot and the policy read that+ * names the serves keys. With `reread` the gate's one re-read of the serves keys fails too.+ */+ async function withConfigReadsFailing<T>(reread: boolean, fn: () => Promise<T>): Promise<T> {+ const target = engine as unknown as Record<string, unknown>;+ const own = { executeRaw: Object.getOwnPropertyDescriptor(engine, 'executeRaw'), getAllConfig: Object.getOwnPropertyDescriptor(engine, 'getAllConfig') };+ const realRaw = engine.executeRaw.bind(engine);+ const timeout = () => Promise.reject(new Error('canceling statement due to statement timeout'));+ target.getAllConfig = timeout;+ target.executeRaw = (sql: string, params?: unknown[]) => {+ const keys = params?.[0];+ const servesRead = /FROM config WHERE key/.test(sql) && Array.isArray(keys) && keys.includes('access.serves');+ if (servesRead && (reread || keys.includes('search.remote_private_pages'))) return timeout();+ return realRaw(sql, params as never);+ };+ try { return await fn(); } finally {+ for (const [k, d] of Object.entries(own)) if (d) Object.defineProperty(engine, k, d); else delete target[k];+ }+ }++ test('an unreadable serves policy is read again: an unbound key in its grace still gets the notice', async () => {+ await engine.setConfig('access.serves', 'several');+ await setSince(1);+ await backdate('old-unbound', 2);+ try {+ const out = await withConfigReadsFailing(false, () => search('old-unbound'));+ expect(out.isError).toBe(false);+ expect(out.meta?.access?.requester_scope).toMatchObject({ state: 'grace', connection: 'token old-unbound' });+ } finally { await engine.unsetConfig('access.serves'); }+ }, 60_000);++ test('when the re-read fails too, the unbound read is refused as retryable and nothing is read', async () => {+ await engine.setConfig('access.serves', 'several');+ try {+ const out = await withConfigReadsFailing(true, () => search('old-unbound'));+ expect({ isError: out.isError, code: out.json.code }).toEqual({ isError: true, code: 'requester_scope_unknown' });+ expect(out.structured?.error).toMatchObject({ code: 'requester_scope_unknown', fix: { next: 'wait' } });+ expect(out.json.message).not.toContain('serves several');+ for (const canary of Object.values(PAGES)) expect(out.text).not.toContain(canary);+ expect((await withConfigReadsFailing(true, () => search('alice-key'))).isError).toBe(false);+ } finally { await engine.unsetConfig('access.serves'); }+ }, 60_000);++ test('on a one-person brain, a failed first read and a good re-read run the call with no notice', async () => {+ await engine.setConfig('access.serves', 'one');+ try {+ const out = await withConfigReadsFailing(false, () => search('old-unbound'));+ expect(out.isError).toBe(false);+ expect(out.text).toContain('canaryalpha');+ expect(out.meta?.access?.requester_scope).toBeUndefined();+ } finally { await engine.unsetConfig('access.serves'); }+ }, 60_000);++ test('over HTTP, the same key after the grace is refused with the structured code, and the audit line records it', async () => {+ await setSince(15);+ await backdate('old-unbound', 16);+ const out = await search('old-unbound');+ refused(out, 'grace_ended');+ expect(out.json.message).toContain('token old-unbound');+ expect(out.json.message).toContain('two or more enabled members');+ const audit = readAudienceAssertions().filter(e => e.outcome === 'requester_scope_required' && e.op === 'search');+ expect(audit.length).toBeGreaterThan(0);+ expect(JSON.stringify(audit)).not.toContain(keys['old-unbound']!.token);+ }, 60_000);++ test('over HTTP, a member-bound key is unaffected', async () => {+ const out = await search('alice-key');+ expect(out.isError).toBe(false);+ expect(out.text).toContain('canarybeta');+ expect(out.meta?.access).toMatchObject({ member: 'alice-example' });+ expect(out.meta?.access?.requester_scope).toBeUndefined();+ }, 60_000);++ test('a key created after the brain started serving several people is refused at once; whoami still answers', async () => {+ await setSince(1);+ await mint('fresh-unbound');+ refused(await search('fresh-unbound'), 'created_after');+ const who = await http('fresh-unbound', 'whoami', {});+ expect(who.isError).toBe(false);+ expect(who.json.access.requester_scope).toEqual({ state: 'refused', reason: 'created_after', argv: ['gbrain', 'auth', 'rescope', '--token', 'fresh-unbound', '--member', '<MEMBER>'] });+ expect((await http('alice-key', 'whoami', {})).json.access.requester_scope).toEqual({ state: 'scoped' });+ }, 60_000);++ test('enumeration: every gated read op is refused for an unbound key before its handler runs', async () => {+ await setSince(15);+ const auth = await provider().verifyAccessToken(keys['fresh-unbound']!.token) as unknown as AuthInfo;+ const ran: string[] = [];+ const saved = new Map(operations.map(op => [op.name, op.handler]));+ for (const op of operations) op.handler = (async () => { ran.push(op.name); return {}; }) as typeof op.handler;+ const answered: string[] = [];+ try {+ for (const op of operations.filter(o => (o.mutating === false || o.scope === 'read') && !o.localOnly)) {+ const out = shape(await dispatchToolCall(engine, op.name, {}, { remote: true, transport: 'http', auth, sourceId: 'default', takesHoldersAllowList: ['world'] }));+ if (requiresRequesterScope(op, auth)) {+ expect({ op: op.name, code: out.structured?.error?.code }).toEqual({ op: op.name, code: 'requester_scope_required' });+ } else answered.push(op.name);+ }+ } finally {+ for (const op of operations) op.handler = saved.get(op.name)!;+ }+ expect(ran.filter(n => !answered.includes(n))).toEqual([]);+ expect(answered.sort()).toEqual([...REVIEWED_EXEMPT, ...OWN_JOB_OPS].sort());+ expect(ran).not.toContain('think');+ }, 120_000);++ test('the opt-out: --reads-unscoped lets one key read with no notice, and removing it refuses again', async () => {+ expect(() => takeBindingFlags(['--reads-unscoped'])).toThrow(/--yes/);+ expect(takeBindingFlags(['--reads-unscoped', '--yes']).patch).toEqual({ readsUnscoped: true });+ expect(takeBindingFlags(['--reads-unscoped', 'none']).patch).toEqual({ readsUnscoped: false });+ const set = await bindCredential(engine, { kind: 'token', id: keys['fresh-unbound']!.id }, { readsUnscoped: true });+ expect(set).toMatchObject({ reads_unscoped: true, changed: true });+ const out = await search('fresh-unbound');+ expect(out.isError).toBe(false);+ expect(out.meta?.access?.requester_scope).toBeUndefined();+ expect((await bindCredential(engine, { kind: 'token', id: keys['fresh-unbound']!.id }, { readsUnscoped: true })).changed).toBe(false);+ await bindCredential(engine, { kind: 'token', id: keys['fresh-unbound']!.id }, { readsUnscoped: false });+ refused(await search('fresh-unbound'), 'created_after');+ }, 60_000);++ test('stdio: unbound reads world pages with a notice in the grace (never a member-restricted page) and is refused after it; the fix is the per-harness --stdio-member binding or a per-person HTTP key, on either engine, never config set; a server started with --stdio-member reads plainly', async () => {+ const setupFix = ['gbrain', 'setup', '<HARNESS>', '--stdio-member', '<MEMBER>'];+ const route = (text: string) => {+ expect(text).toContain('gbrain setup claude-code|codex --stdio-member');+ expect(text).toContain('gbrain serve --http');+ expect(text).not.toContain('PGLite');+ };+ await importFromContent(engine, 'notes/alice-only', '---\ntype: note\ntitle: alice only\nreadable_by: [alice-example]\n---\n# alice only\n\nHarbor ledger notes canaryalice.\n', { sourceId: 'default', noEmbed: true });+ await setSince(1);+ const inGrace = await stdio('get_page', { slug: 'notes/harbor-alpha' });+ expect(inGrace.isError).toBe(false);+ expect(inGrace.text).toContain('canaryalpha');+ expect(inGrace.meta?.access?.requester_scope).toMatchObject({ state: 'grace', connection: 'this stdio server', fix: { argv: expect.arrayContaining(setupFix), next: 'tell_user_to_run' } });+ route(inGrace.meta?.access?.requester_scope.message);+ expect((await stdio('get_page', { slug: 'notes/alice-only' })).text).not.toContain('canaryalice');+ await setSince(15);+ const after = await stdio('get_page', { slug: 'notes/harbor-alpha' });+ expect(after.structured?.error).toMatchObject({ code: 'requester_scope_required', reason: 'grace_ended', fix: { argv: expect.arrayContaining(setupFix) } });+ expect(after.text).not.toContain('canaryalpha');+ route(after.text);+ for (const out of [inGrace, after]) expect(JSON.stringify([out.meta, out.structured, out.text])).not.toContain('config set mcp.stdio_member');+ const who = await stdio('whoami', {});+ route(who.json.access.note);+ expect(who.json.access.requester_scope.argv).toEqual(setupFix);+ expect(JSON.stringify(who.json)).not.toContain('config set mcp.stdio_member');+ const registered = shape(await dispatchToolCall(engine, 'get_page', { slug: 'notes/alice-only' }, { remote: true, transport: 'stdio', sourceId: 'default', takesHoldersAllowList: ['world'], stdioMember: 'alice-example' }));+ expect(registered.isError).toBe(false);+ expect(registered.text).toContain('canaryalice');+ expect(registered.meta?.access?.requester_scope).toBeUndefined();+ await engine.setConfig('mcp.stdio_member', 'alice-example');+ const bound = await stdio('get_page', { slug: 'notes/harbor-alpha' });+ expect(bound.isError).toBe(false);+ expect(bound.meta?.access?.requester_scope).toBeUndefined();+ await engine.unsetConfig('mcp.stdio_member');+ }, 60_000);++ test('R94: on a brain pinned access.serves one, unbound reads (old, new, HTTP, stdio) answer with no notice after any grace; the owner-bound key reads the same private pages here as on a several-people brain', async () => {+ await importFromContent(engine, 'notes/owner-private', '---\ntype: note\ntitle: owner private\nvisibility: private\n---\n# owner private\n\nHarbor ledger notes canaryowner.\n', { sourceId: 'default', noEmbed: true });+ await engine.setConfig('access.owner_member', 'alice-example');+ __resetPrivateVisibilityCacheForTests();+ await setSince(30);+ await mint('pinned-fresh');+ const ownerRead = async () => (await http('alice-key', 'get_page', { slug: 'notes/owner-private' })).json;+ const several = await ownerRead();+ expect(several.compiled_truth).toContain('canaryowner');+ await engine.setConfig('access.serves', 'one');+ try {+ expect(await ownerRead()).toEqual(several);+ for (const name of ['old-unbound', 'pinned-fresh']) {+ const out = await search(name);+ expect({ name, isError: out.isError }).toEqual({ name, isError: false });+ expect(out.text).toContain('canaryalpha');+ expect(out.meta?.access?.requester_scope).toBeUndefined();+ }+ const viaStdio = await stdio('get_page', { slug: 'notes/harbor-alpha' });+ expect(viaStdio.isError).toBe(false);+ expect(viaStdio.meta?.access?.requester_scope).toBeUndefined();+ expect((await http('pinned-fresh', 'whoami', {})).json.access.requester_scope).toEqual({ state: 'not_required' });+ await expect(assertCredentialScoped(engine, null, 'token', 'pinned-new')).resolves.toBeUndefined();+ } finally {+ await engine.unsetConfig('access.serves');+ await engine.unsetConfig('access.owner_member');+ __resetPrivateVisibilityCacheForTests();+ }+ }, 60_000);++ test('a shared agent naming its audience reads; the same credential with no audience is refused', async () => {+ const c = await provider().registerClientManual('agent-' + kind, ['client_credentials'], 'read write', [], 'default');+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { mayActFor: ['member:alice-example', 'member:bob-example'] });+ const bearer = (await provider().exchangeClientCredentials(c.clientId, c.clientSecret!)).access_token;+ const named = await oauthCall(bearer, 'get_page', { slug: 'notes/harbor-alpha' }, { onBehalfOf: { header: 'alice-example' } });+ expect(named.isError).toBe(false);+ expect(named.meta?.access?.requester_scope).toBeUndefined();+ const bare = await oauthCall(bearer, 'get_page', { slug: 'notes/harbor-alpha' });+ expect(bare.structured?.error).toMatchObject({ code: 'requester_scope_required', fix: { argv: ['gbrain', 'auth', 'rescope', '--client', c.clientId, '--member', '<MEMBER>'] } });+ }, 60_000);++ test('an attested call is exempt', async () => {+ const c = await provider().registerClientManual('qm-' + kind, ['client_credentials'], 'read write', [], 'default');+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { attestActor: 'qm', attestOps: ['get_page', 'search'] });+ await linkMember(engine, 'alice-example', 'qm', 'U0ALICE');+ const bearer = (await provider().exchangeClientCredentials(c.clientId, c.clientSecret!)).access_token;+ const out = await oauthCall(bearer, 'get_page', { slug: 'notes/harbor-alpha' }, { actor: { header: 'U0ALICE' } });+ expect(out.isError).toBe(false);+ expect(out.text).toContain('canaryalpha');+ expect(out.meta?.access).toMatchObject({ member: 'alice-example', actor: { system: 'qm' } });+ expect(out.meta?.access?.requester_scope).toBeUndefined();+ }, 60_000);++ test('hosted switch off: an unbound DCR client registered after the date reads with the notice, and is refused once the switch is on', async () => {+ const dcr = await provider(true).clientsStore.registerClient!({ client_name: 'dcr-' + kind, grant_types: ['client_credentials'], scope: 'read', redirect_uris: [], token_endpoint_auth_method: 'client_secret_post' } as never);+ const bearer = (await provider().exchangeClientCredentials(dcr.client_id, dcr.client_secret!)).access_token;+ await engine.setConfig('access.requester_scope_enforce', 'false');+ const off = await oauthCall(bearer, 'get_page', { slug: 'notes/harbor-alpha' });+ expect(off.isError).toBe(false);+ expect(off.text).toContain('canaryalpha');+ expect(off.meta?.access?.requester_scope).toMatchObject({ state: 'not_enforced', refuses_at: null, connection: `OAuth client ${dcr.client_id}` });+ await expect(assertCredentialScoped(engine, null, 'token', 'any-name')).resolves.toBeUndefined();+ await engine.unsetConfig('access.requester_scope_enforce');+ const on = await oauthCall(bearer, 'get_page', { slug: 'notes/harbor-alpha' });+ expect(on.structured?.error).toMatchObject({ code: 'requester_scope_required', reason: 'created_after' });+ }, 60_000);++ test('an agent job from an unbound credential is refused at its first tool call, structured; in the grace it runs', async () => {+ const c = await provider().registerClientManual('job-' + kind, ['client_credentials'], 'read write', [], 'default');+ const tools = buildBrainTools({ subagentId: 7, engine, config: { engine: 'pglite' } as never, sourceId: 'default',+ delegatedAuth: { clientId: c.clientId, scopes: ['read', 'agent'], sourceId: 'default', allowedSources: ['default'] } });+ const getPage = tools.find(t => t.name === 'brain_get_page')!;+ const ctx = { engine, jobId: 1, signal: new AbortController().signal } as never;+ const err = await getPage.execute({ slug: 'notes/harbor-alpha' }, ctx).then(() => null, e => e);+ expect(err).toMatchObject({ code: 'requester_scope_required', reason: 'created_after' });+ expect(err.fix).toMatchObject({ argv: ['gbrain', 'auth', 'rescope', '--client', c.clientId, '--member', '<MEMBER>'] });+ await engine.executeRaw('UPDATE oauth_clients SET client_id_issued_at = $2 WHERE client_id = $1', [c.clientId, Math.floor((Date.now() - 2 * DAY) / 1000)]);+ await setSince(1);+ const ran = await getPage.execute({ slug: 'notes/harbor-alpha' }, ctx);+ expect(JSON.stringify(ran)).toContain('canaryalpha');+ }, 60_000);++ test('creating an unbound credential on this brain is refused with credential_scope_required and the fix', async () => {+ const err = await assertCredentialScoped(engine, null, 'token', 'new-bot').then(() => null, e => e);+ expect(err).toMatchObject({ code: 'credential_scope_required' });+ expect(err.fix).toMatchObject({ argv: ['gbrain', 'auth', 'create', 'new-bot', '--member', '<MEMBER>'] });+ for (const patch of [{ member: 'alice-example' }, { mayActFor: ['member:alice-example'] }, { readsUnscoped: true }, { attestActor: 'qm' }]) {+ await expect(assertCredentialScoped(engine, patch, 'client', 'new-bot')).resolves.toBeUndefined();+ }+ }, 60_000);+ });+}++describe('the access owner hint names the per-harness binding', () => {+ const view = { owner: 'alice-example', bound_credentials: [], inactive: null } as unknown as Parameters<typeof ownerLines>[0];+ test('it names --stdio-member for one harness and the per-person HTTP key, never a bare config set', () => {+ const text = ownerLines(view).join('\n');+ expect(text).toContain('gbrain setup claude-code|codex --stdio-member alice-example');+ expect(text).toContain('gbrain serve --http');+ expect(text).toContain('--member alice-example');+ expect(text).not.toContain('config set mcp.stdio_member');+ });+});++describe('doctor unscoped_shared_reads and the post-upgrade list (pglite, repo-less)', () => {+ let engine: BrainEngine;+ const doctor = async () => (await unscopedSharedReadsEntry.run({ engine } as unknown as DoctorContext) as Array<Record<string, any>>)[0]!;+ beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema();+ }, 120_000);+ afterAll(async () => { await engine?.disconnect(); }, 60_000);++ test('not applicable for one person; fails per unbound credential with its grace end and command; opt-outs are info; hosted warns', async () => {+ const old = await mintLegacyToken(engine, { name: 'old-bot', scopes: ['read'], takesHolders: ['world'] });+ expect(await doctor()).toMatchObject({ name: 'unscoped_shared_reads', status: 'ok', readiness_state: 'not_applicable' });+ for (const id of ['alice-example', 'bob-example']) await addMember(engine, id);+ await engine.executeRaw('UPDATE access_tokens SET created_at = $2::timestamptz WHERE id::text = $1', [old.id, iso(Date.now() - 2 * DAY)]);+ await engine.setConfig('access.serves_since', iso(Date.now() - DAY));+ const fresh = await mintLegacyToken(engine, { name: 'fresh-bot', scopes: ['read'], takesHolders: ['world'] });+ const optOut = await mintLegacyToken(engine, { name: 'team-bot', scopes: ['read'], takesHolders: ['world'] });+ await bindCredential(engine, { kind: 'token', id: optOut.id }, { readsUnscoped: true });+ const bound = await mintLegacyToken(engine, { name: 'alice-bot', scopes: ['read'], takesHolders: ['world'] });+ await bindCredential(engine, { kind: 'token', id: bound.id }, { member: 'alice-example' });+ const c = await doctor();+ expect(c.status).toBe('fail');+ expect(c.details.connections).toEqual([+ { connection: 'token fresh-bot', state: 'refused', refuses_at: null, argv: ['gbrain', 'auth', 'rescope', '--token', 'fresh-bot', '--member', '<MEMBER>'] },+ { connection: 'token old-bot', state: 'grace', refuses_at: new Date(Date.parse(await engine.getConfig('access.serves_since') as string) + 14 * DAY).toISOString(), argv: ['gbrain', 'auth', 'rescope', '--token', 'old-bot', '--member', '<MEMBER>'] },+ { connection: 'token team-bot', state: 'reads_unscoped', refuses_at: null, argv: ['gbrain', 'auth', 'rescope', '--token', 'team-bot', '--member', '<MEMBER>'] },+ ]);+ expect(c.message).toContain('Reading unscoped on purpose (--reads-unscoped): token team-bot');+ expect(c.fix).toMatchObject({ argv: ['gbrain', 'auth', 'rescope', '--token', 'fresh-bot', '--member', '<MEMBER>'], ask_user: true });+ const lines: string[] = [];+ const log = console.log;+ console.log = (...a: unknown[]) => { lines.push(a.join(' ')); };+ try { await printUnscopedReadsUpgradeNotice(engine); } finally { console.log = log; }+ expect(lines.join('\n')).toContain('token old-bot: grace until');+ expect(lines.join('\n')).toContain('Fix: gbrain auth rescope --token fresh-bot --member <MEMBER>');+ expect(lines.join('\n')).not.toContain('team-bot');+ await engine.setConfig('access.requester_scope_enforce', 'false');+ expect((await doctor()).status).toBe('warn');+ await engine.unsetConfig('access.requester_scope_enforce');+ for (const t of [old, fresh]) await bindCredential(engine, { kind: 'token', id: t.id }, { member: 'bob-example' });+ expect(await doctor()).toMatchObject({ status: 'ok' });+ }, 60_000);+});++describe('a one-person brain with several sources sees no refusal and no notice (pglite, repo-less)', () => {+ let engine: BrainEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema();+ for (const src of ['source-a', 'source-b', 'source-c']) await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [src]);+ for (const src of ['source-a', 'source-b', 'source-c']) await importFromContent(engine, `notes/${src}`, pageText(`notes/${src}`, `canary${src.replace('-', '')}`), { sourceId: src, noEmbed: true });+ await addMember(engine, 'alice-example');+ await engine.setConfig('access.owner_member', 'alice-example');+ }, 120_000);+ afterAll(async () => { await engine?.disconnect(); }, 60_000);++ test('an unbound key created today and an unbound stdio server read every source with nothing new in _meta', async () => {+ const m = await mintLegacyToken(engine, { name: 'one-person-bot', scopes: ['read'], takesHolders: ['world'], sourceGrant: ['source-a', 'source-b', 'source-c'] });+ const auth = await new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine) } as never).verifyAccessToken(m.token) as unknown as AuthInfo;+ for (const transport of ['http', 'stdio'] as const) {+ const out = shape(await dispatchToolCall(engine, 'search', { query: 'harbor ledger notes', match: 'keyword', limit: 10, source_ids: ['source-a', 'source-b', 'source-c'] },+ { remote: true, transport, ...(transport === 'http' ? { auth } : { localFederatedSourceIds: ['source-b', 'source-c'] }), sourceId: 'source-a', takesHoldersAllowList: ['world'] }));+ expect({ transport, isError: out.isError, text: out.isError ? out.text : '' }).toEqual({ transport, isError: false, text: '' });+ for (const src of ['sourcea', 'sourceb', 'sourcec']) expect(out.text).toContain(`canary${src}`);+ expect(out.meta?.access).not.toHaveProperty('requester_scope');+ }+ await expect(assertCredentialScoped(engine, null, 'token', 'x')).resolves.toBeUndefined();+ expect(await engine.getConfig('access.serves_since')).toBeNull();+ }, 60_000);+});++describe('a repo brain behaves the same (pglite, source with a git checkout)', () => {+ let engine: BrainEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema();+ const repo = mkdtempSync(join(tmpdir(), 'gbrain-scope-repo-')); roots.push(repo);+ execFileSync('git', ['init', '-q', repo]);+ await engine.executeRaw('INSERT INTO sources (id, name, local_path) VALUES ($1, $1, $2) ON CONFLICT (id) DO NOTHING', ['repo-src', repo]);+ await importFromContent(engine, 'notes/repo-page', pageText('notes/repo-page', 'canaryrepo'), { sourceId: 'repo-src', noEmbed: true });+ for (const id of ['alice-example', 'bob-example']) await addMember(engine, id);+ }, 120_000);+ afterAll(async () => { await engine?.disconnect(); }, 60_000);++ test('unbound stdio in the grace gets the notice, after it the refusal', async () => {+ const call = async () => shape(await dispatchToolCall(engine, 'get_page', { slug: 'notes/repo-page' }, { remote: true, transport: 'stdio', sourceId: 'repo-src', takesHoldersAllowList: ['world'] }));+ expect((await call()).meta?.access?.requester_scope).toMatchObject({ state: 'grace' });+ await engine.setConfig('access.serves_since', iso(Date.now() - 15 * DAY));+ expect((await call()).structured?.error).toMatchObject({ code: 'requester_scope_required', reason: 'grace_ended' });+ }, 60_000);+});++describe('the CLI refuses an unbound credential and records the opt-out (pglite, spawned)', () => {+ test('auth create refuses credential_scope_required; --reads-unscoped needs --yes and lands in the audit trail', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-scope-cli-')); roots.push(home);+ const env = { GBRAIN_HOME: home, HOME: home, GBRAIN_AUDIT_DIR: join(home, 'audit') };+ const run = (args: string[]) => runCli(args, { env, timeoutMs: 120_000 });+ expect((await run(['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ for (const id of ['alice-example', 'bob-example']) expect((await run(['access', 'member', 'add', id])).exitCode).toBe(0);+ const refused = await run(['auth', 'create', 'shared-bot']);+ expect(refused.exitCode).not.toBe(0);+ expect(refused.stdout + refused.stderr).toContain('credential_scope_required');+ expect(refused.stdout + refused.stderr).not.toMatch(/gbrain_[A-Za-z0-9]{20,}/);+ const noYes = await run(['auth', 'create', 'shared-bot', '--reads-unscoped']);+ expect(noYes.exitCode).not.toBe(0);+ expect(noYes.stdout + noYes.stderr).toContain('--yes');+ const optOut = await run(['auth', 'create', 'shared-bot', '--reads-unscoped', '--yes']);+ expect(optOut.exitCode).toBe(0);+ expect(optOut.stdout).toContain('reads unscoped: yes');+ const bound = await run(['auth', 'create', 'alice-bot', '--member', 'alice-example']);+ expect(bound.exitCode).toBe(0);+ const marked = await run(['access', 'check', '--token', 'shared-bot', '--json']);+ expect(JSON.parse(marked.stdout)).toMatchObject({ verdict: 'unbound', reads_unscoped: true });+ expect(JSON.parse(marked.stdout).explanation).toContain('--reads-unscoped');+ expect(JSON.parse((await run(['access', 'check', '--token', 'alice-bot', '--json'])).stdout)).toMatchObject({ verdict: 'reads_as_member', reads_unscoped: false });+ await withEnv({ GBRAIN_AUDIT_DIR: join(home, 'audit') }, () => {+ expect(readReadsUnscopedChanges()).toEqual([expect.objectContaining({ credential: 'token shared-bot', reads_unscoped: true, by: 'gbrain auth' })]);+ });+ }, 180_000);++ test('the upgrade path never binds stdio: post-upgrade and apply-migrations on a brain with an owner and two members leave mcp.stdio_member unset', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-scope-upgrade-')); roots.push(home);+ const env = { GBRAIN_HOME: home, HOME: home, GBRAIN_AUDIT_DIR: join(home, 'audit') };+ const run = (args: string[]) => runCli(args, { env, timeoutMs: 180_000 });+ expect((await run(['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ expect((await run(['access', 'member', 'add', 'alice-example'])).exitCode).toBe(0);+ expect((await run(['auth', 'create', 'old-bot'])).exitCode).toBe(0);+ expect((await run(['access', 'member', 'add', 'bob-example'])).exitCode).toBe(0);+ const owner = await run(['access', 'owner', 'set', 'alice-example']);+ expect(owner.exitCode).toBe(0);+ expect(owner.stdout).toContain('--stdio-member alice-example');+ expect(owner.stdout).not.toContain('config set mcp.stdio_member');+ const stdioMember = async () => (await run(['config', 'get', 'mcp.stdio_member'])).stdout.trim();+ const before = await stdioMember();+ const post = await run(['post-upgrade']);+ expect(post.stdout + post.stderr).toContain('token old-bot');+ expect(post.stdout + post.stderr).not.toContain('config set mcp.stdio_member');+ await run(['apply-migrations', '--yes', '--non-interactive']);+ expect({ before, after: await stdioMember() }).toEqual({ before: '', after: '' });+ }, 600_000);+ test('auth --help names --reads-unscoped --yes on auth create and register-client, the flags the credential_scope_required refusal asks for', async () => {+ const help = await runCli(['auth', '--help'], { timeoutMs: 60_000 });+ const text = help.stdout + help.stderr;+ expect(text).toMatch(/gbrain auth create <name> [^\n]*\[--reads-unscoped --yes\]/);+ expect(text).toMatch(/gbrain auth register-client <name>[\s\S]*--reads-unscoped --yes/);+ }, 120_000);+});diff --git a/test/serve-http-api-keys.test.ts b/test/serve-http-api-keys.test.tsindex ae407c72a9..a6e0efb28c 100644--- a/test/serve-http-api-keys.test.ts+++ b/test/serve-http-api-keys.test.ts@@ -164,3 +164,22 @@ describe('doctor legacy_token_null_scope', () => {expect(after.details?.null_scope_count).toBe(0);});});++describe('a brain that serves several people (GST-363)', () => {+ test('the dashboard refuses to mint a key bound to nobody, like auth create: credential_scope_required, nothing created', async () => {+ const { addMember, disableMember } = await import('../src/core/access/members.ts');+ const ids = ['alice-example', 'bob-example'];+ for (const id of ids) await addMember(engine, id);+ try {+ const before = (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM access_tokens'))[0]!.n;+ const { status, body } = await post('/admin/api/api-keys', { name: 'dash-unbound' });+ expect(status).toBe(400);+ expect(JSON.stringify(body)).toContain('credential_scope_required');+ expect(body.token).toBeUndefined();+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM access_tokens'))[0]!.n).toBe(before);+ } finally {+ for (const id of ids) await disableMember(engine, id);+ }+ expect((await post('/admin/api/api-keys', { name: 'dash-after-members' })).status).toBe(200);+ });+});diff --git a/test/shared-stdio-binding.test.ts b/test/shared-stdio-binding.test.tsnew file mode 100644index 0000000000..f2754df774--- /dev/null+++ b/test/shared-stdio-binding.test.ts@@ -0,0 +1,68 @@+/**+ * GST-363 (PR 2): doctor shared_stdio_binding. config mcp.stdio_member binds every stdio session on the host to one+ * member, so on a host where a harness several people talk to (OpenClaw, Hermes; sharedStdioHarness) is installed,+ * that harness reads as that member, private pages included. The check fails there with the unset command as its+ * fix, passes when no shared harness is installed, and is not applicable while the key is unset. Repo-less PGLite.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { sharedStdioBindingEntry } from '../src/commands/doctor/checks/shared-stdio-binding.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import { withEnv } from './helpers/with-env.ts';++describe('doctor shared_stdio_binding (pglite, repo-less)', () => {+ let engine: BrainEngine;+ let home: string;+ const doctor = (env: Record<string, string | undefined> = {}) => withEnv({ HOME: home, GBRAIN_HOME: home, PATH: '', OPENCLAW_STATE_DIR: undefined, OPENCLAW_PROFILE: undefined, HERMES_HOME: undefined, ...env },+ async () => (await sharedStdioBindingEntry.run({ engine } as unknown as DoctorContext) as Array<Record<string, any>>)[0]!);+ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-shared-stdio-'));+ engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema();+ }, 120_000);+ afterAll(async () => { await engine?.disconnect(); rmSync(home, { recursive: true, force: true }); }, 60_000);++ test('not applicable while mcp.stdio_member is unset, even with a shared harness installed', async () => {+ const hermes = join(home, 'hermes-unset'); mkdirSync(hermes);+ expect(await doctor({ HERMES_HOME: hermes })).toMatchObject({ name: 'shared_stdio_binding', status: 'ok', readiness_state: 'not_applicable' });+ });++ test('set with no shared harness on the host: ok', async () => {+ await engine.setConfig('mcp.stdio_member', 'alice-example');+ const c = await doctor();+ expect(c).toMatchObject({ name: 'shared_stdio_binding', status: 'ok' });+ expect(c.fix).toBeUndefined();+ await engine.unsetConfig('mcp.stdio_member');+ });++ test('set with Hermes or OpenClaw installed: fails, naming the harness and the member, with the unset command as the fix', async () => {+ await engine.setConfig('mcp.stdio_member', 'alice-example');+ const hermes = join(home, 'hermes'); mkdirSync(hermes);+ const viaHermes = await doctor({ HERMES_HOME: hermes });+ expect(viaHermes).toMatchObject({ name: 'shared_stdio_binding', status: 'fail', fix: { argv: ['gbrain', 'config', 'unset', 'mcp.stdio_member'], ask_user: true } });+ expect(viaHermes.message).toContain('Hermes');+ expect(viaHermes.message).toContain('alice-example');+ const openclaw = join(home, 'openclaw-state'); mkdirSync(openclaw);+ const viaOpenClaw = await doctor({ OPENCLAW_STATE_DIR: openclaw });+ expect(viaOpenClaw).toMatchObject({ status: 'fail', fix: { argv: ['gbrain', 'config', 'unset', 'mcp.stdio_member'] } });+ expect(viaOpenClaw.message).toContain('OpenClaw');+ expect(JSON.stringify([viaHermes, viaOpenClaw])).not.toContain('config set mcp.stdio_member');+ await engine.unsetConfig('mcp.stdio_member');+ });++ test('a compiled hermes on PATH (React Native\'s JavaScript engine) is not the Hermes agent; the agent\'s script launcher is', async () => {+ await engine.setConfig('mcp.stdio_member', 'alice-example');+ const engineBin = join(home, 'rn-bin'); mkdirSync(engineBin);+ writeFileSync(join(engineBin, 'hermes'), Buffer.from([0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00])); chmodSync(join(engineBin, 'hermes'), 0o755);+ expect(await doctor({ PATH: engineBin })).toMatchObject({ name: 'shared_stdio_binding', status: 'ok' });+ const agentBin = join(home, 'agent-bin'); mkdirSync(agentBin);+ writeFileSync(join(agentBin, 'hermes'), '#!/usr/bin/env python3\nprint("hermes")\n'); chmodSync(join(agentBin, 'hermes'), 0o755);+ const agent = await doctor({ PATH: agentBin });+ expect(agent).toMatchObject({ status: 'fail' });+ expect(agent.message).toContain('Hermes');+ await engine.unsetConfig('mcp.stdio_member');+ });+});