Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(access): shared agents read as the audience their harness names (on_behalf_of)
garrytan942a2ea5bc07
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8cd67bd3f1..3ef5c722d9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -27,6 +27,7 @@ identifiers and attribution are available in the pre-removal Git revision| Folder rules | | `gbrain access rule add\|rm\|list\|status\|history\|revert\|export\|import\|migrate`, `gbrain access apply` and `gbrain access resume` keep whole folders of a source to named members; a page under a rule is read remotely only by a member listed on every rule covering it and on its own `readable_by`. Rules live in the database on a repo-less source and in `.gbrain/access.yml` on a git-backed one || Changing folder rules | | narrowing applies at once; widening is held until `gbrain access apply --source <id>` previews it and `--yes --expect <plan_hash>` approves it; an unfinished apply reads as nobody remotely until `gbrain access resume --source <id>` || `gbrain export` and `gbrain import` | pages only | an export carries each source's applied folder rules under `.gbrain/`, and import installs them before publishing any page (`--access-policy <source>` maps a multi-source export) |+| A shared agent (one bot serving a channel or many DMs) | read as its own credential, so it saw one view for everyone | its harness names each turn's audience (`X-Gbrain-On-Behalf-Of: alice-example, guest` or request-level `_meta.on_behalf_of`); the call reads only what every entry may read, within the agent's source grant, and only a one-member audience keeps the agent's private-page relaxation. The credential lists whom it may act for (`gbrain auth rescope --token <name> --may-act-for <list>`); every response carries `_meta.access`, and `whoami` returns it |### What to watch for after you upgrade@@ -35,6 +36,7 @@ identifiers and attribution are available in the pre-removal Git revision- A credential bound to a disabled or removed member is refused at verification (`access_member_disabled`).- Works the same on a repo-less brain: members, groups, bindings and folder rules live in the database. A source records which store holds its folder rules when its first rule is created, and only `gbrain access rule migrate --source <id>` moves them; doctor `access_policy_store_mismatch` names it when the filesystem changes.- Remote callers can no longer write pages under `.gbrain/`.+- A harness that sends an audience its credential's `may_act_for` does not list gets `on_behalf_of_not_permitted` with the operator's command; an audience inside tool arguments is always refused (`on_behalf_of_in_arguments`). `may_act_for: *` is accepted and doctor warns (`access_may_act_for_wildcard`).## [0.60.453.0] - 2026-10-25diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 75fb4b37a5..e886eec7b8 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -66,7 +66,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/modes-report.ts` — `buildModesReport(engine)` → `SearchModesReport` (`schema_version: 2`), the read-only dashboard behind `gbrain search modes` and the `search_modes` MCP op: `active_mode` + validity, the per-knob `resolved` attribution (`attributeKnob` over `KNOB_DESCRIPTIONS`, including the five `reranker_*` knobs), the three frozen `bundles`, `config_keys`, and `reranker_readiness` — `{model, enabled, ready, required_key, key_present, self_hosted, fix}` from `rerankerReadinessForEngine` + `describeRerankerFix` (a thrown readiness check still yields a `ready: false` verdict whose `fix` says to run `gbrain doctor`; the block never vanishes silently). `redactReadinessForRemote(report)` is what the `search_modes` op returns when `ctx.remote !== false`: `required_key`, `key_present` and `fix` are dropped and `self_hosted` is forced false — which env vars exist on the host is fingerprinting data and the fix names them; `ready` stays because it is observable anyway (reranked results carry `rerank_score`). `src/commands/search.ts:formatModesText` renders the runtime `Reranker:` line (`off (resolved) — …` / `<model> (enabled) — <KEY> present` / `<model> (enabled but NOT running) — <fix>`) and a per-bundle `reranker=… topNIn=… autocut=…` line. Pinned by `test/modes-report-reranker.test.ts`. The CLI dashboard leads with command-specific expansion: `query` follows the mode's expansion default (off in all modes) unless the call passes `expand`, while `search` is off. It discloses provider prerequisites/text flow and distinguishes retained bundle configuration from effective command behavior.- `src/core/search/private-visibility.ts` — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs keep their semantics; failed config reads enforce privacy. `privatePagesFilterFragment` authorizes concrete page rows and `isPrivatePage` is its row-side twin: explicit `private` hides a page, absent visibility is world for ordinary pages and private for extracted atoms (`type = 'atom'`) and synthesized concepts (`type = 'concept'` with `synthesized_by`), because their origin may be a private page or transcript. The page predicate also follows derived origins: an atom whose `source_slug` page is explicitly private, and a synthesized concept with a private input atom (or an input whose origin is private) over `concept-provenance` edges, are private whatever their own field says, so a later private flip of an origin reaches derived pages before any repair. Chronicle events follow `event.depth` (fail closed). Declared lineage matches `derived_from` slugs with `= ANY(ARRAY(...))`, not `IN (SELECT ... jsonb_array_elements_text(...))`: same rows, but the planner priced the IN form as a 100-row semi-join per page and pushed every read carrying the rule past `jit_above_cost` (`test/e2e/private-visibility-plan-postgres.test.ts`). `privateSnapshotFilterFragment` is the same rule on a row's own frontmatter for `page_versions`. `effectiveVisibility(origin)` (transcript or missing origin private, page origin per the read rule) and `strictestVisibility` are used by both `extract_atoms` paths, concept synthesis and `gbrain repair visibility`. Remote publication rechecks (`persistence/page-visibility.ts`) and the alias-inject recheck in `hybrid.ts` use the same rule. Tests: `test/private-visibility.test.ts`, `test/derived-page-visibility.test.ts` (PGLite and Postgres); link origins and timeline projections use independent ID-based predicates. `privateProvenanceFilterFragment` hides a fact whose provenance page (`s... (line truncated to 2000 chars)-- `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 `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`). A derivative of a page that names readers is 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 the managed drain, read with `git show` at the synced commit); `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` (v275 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`.+- `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 `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`). A derivative of a page that names readers is 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 the managed drain, read with `git show` at the synced commit); `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` (v275 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`.- `src/core/search/projection-readiness.ts` — one statement probes visible unsealed pages: ready, projection_pending, by_design (protected/archived only) or unknown; LIMIT 1 arms walk the v161 pending index, not pages. Cached per scope by DB generation (page clock, pages filenode, archive flags, no open tx); `GBRAIN_PROJECTION_READINESS_CACHE=0` disables.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex fc67327ee9..f3d937d0c9 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2849,6 +2849,46 @@ More: [docs/guides/repair.md#ghost-pages](../../docs/guides/repair.md#ghost-pageMore: [docs/guides/on-commit-sync.md#notifier-stalled](../../docs/guides/on-commit-sync.md#notifier-stalled)+### on_behalf_of_in_arguments++<a id="on_behalf_of_in_arguments"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A tool call carried on_behalf_of inside its arguments, where conversation text could set it, so it was refused and nothing was read. | Only harness code may name whose notes a shared agent reads: the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of, never tool arguments. | Remove on_behalf_of from the tool arguments. Harness code sends it as the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of; other stdio clients use a credential bound to one member or config mcp.stdio_member. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/write-refusals.md#on_behalf_of_in_arguments](../../docs/guides/write-refusals.md#on_behalf_of_in_arguments)++### on_behalf_of_invalid_audience++<a id="on_behalf_of_invalid_audience"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A shared agent's request named its audience (the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of) in a form gbrain does not accept: empty, more than 50 entries, an entry that is not a member id, group:<id> or guest, or a header and _meta that name different audiences. Nothing was read. | The audience decides whose notes the agent may read, so an audience gbrain cannot read exactly is refused instead of guessed. | Fix the harness code that sets the audience: 1-50 entries, each a member id, group:<id> or guest, the same in the header and _meta when both are sent. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/write-refusals.md#on_behalf_of_invalid_audience](../../docs/guides/write-refusals.md#on_behalf_of_invalid_audience)++### on_behalf_of_not_permitted++<a id="on_behalf_of_not_permitted"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A shared agent asserted an audience its credential's may_act_for does not list (for a stdio server, config mcp.stdio_may_act_for), so nothing was read. | A shared agent acts only for the people the brain operator approved for its credential; widening that list is the operator's decision, never the agent's. | The brain operator decides whether to approve the audience: gbrain auth rescope --token <name>\|--client <id> --may-act-for <list> on the brain host. Until then, call without the audience. | user | `gbrain doctor --json` | 1 | no |++More: [docs/guides/write-refusals.md#on_behalf_of_not_permitted](../../docs/guides/write-refusals.md#on_behalf_of_not_permitted)++### on_behalf_of_unknown_member++<a id="on_behalf_of_unknown_member"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A shared agent's audience names a member who is not enabled on this brain, or a group that does not exist, so nothing was read. | An unknown or disabled entry is refused rather than read as a guest, so a typo or a removed person never quietly changes what the agent reads. | Name enabled members and existing groups only (gbrain access member list --all, gbrain access group list on the brain host); a person who is not a member joins the audience as guest. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/write-refusals.md#on_behalf_of_unknown_member](../../docs/guides/write-refusals.md#on_behalf_of_unknown_member)+### origin_twin_mass_merge_refused<a id="origin_twin_mass_merge_refused"></a>diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex f913dfc7c2..6225c2d158 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -917,6 +917,19 @@ same on a repo-less brain and on a git-backed one.| <a id="access_policy_invalid"></a>`access_policy_invalid` | A source's committed `.gbrain/access.yml` (or a file given to `gbrain access rule import`) does not validate. The last applied rules stay in force and every prefix the file names reads as nobody for remote callers (the whole source when the file does not parse), so a typo never opens a folder. | `gbrain access rule list --source <id>` shows each problem with its line. Fix the file, commit it with `gbrain git commit-push`, and run `gbrain sync --source <id> --no-pull`. || <a id="access_policy_pending"></a>`access_policy_pending` | A narrowing change to a source's folder rules is still being stamped onto its pages, so pages under the folders it touches read as nobody for remote callers until it finishes (other folders keep the last applied rules). Remote reads carry this as a notice: an empty answer there is not proof of no notes. | Wait and retry. If it stays pending the apply was interrupted: on the brain host run `gbrain access resume --source <id>` (database store) or `gbrain sync --source <id> --no-pull` (git store); `gbrain access rule status --source <id>` shows the pending folders. |+## Shared-agent refusals++A shared agent's harness names the audience a request serves in the `X-Gbrain-On-Behalf-Of` header or request-level+`_meta.on_behalf_of`. These refusals come before any read, and none reveals page content. `may_act_for` and members+live in the database, so they are the same on a repo-less brain.++| Code | What happened | What to do |+|---|---|---|+| <a id="on_behalf_of_invalid_audience"></a>`on_behalf_of_invalid_audience` | The audience is empty, holds more than 50 entries, holds an entry that is not a member id, `group:<id>` or `guest`, or the header and `_meta.on_behalf_of` name different audiences (`_meta.on_behalf_of` must be a list of strings). Nothing was read. | Fix the harness code that sets it: 1-50 entries, the same in both channels when both are sent. Name a `group:<id>` for a channel larger than 50 people. |+| <a id="on_behalf_of_unknown_member"></a>`on_behalf_of_unknown_member` | The audience names a member who is disabled, removed or was never added, or a group that does not exist. It is refused rather than read as a guest. Nothing was read. | Name enabled members and existing groups only (`gbrain access member list --all`, `gbrain access group list`); a person who is not a member joins the audience as `guest`. |+| <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`. |+## Related- [Concurrent writes and durable receipts](concurrent-writes.md) — receipt states, retries, capacity limitsdiff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex 82fae2643f..e9c508b81e 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -239,6 +239,10 @@ Inside one source, bind each member's credential with `gbrain auth rescope--token <name> --member <id>` (or `--client`) and put `readable_by` on the pagesonly some members may read, or keep a whole folder to them with `gbrain accessrule add --prefix <folder>/ --readers <members> --source <id>`;+One agent serving several people in a shared channel holds `--may-act-for+<members>` instead, and its harness names each request's audience+(`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`); it reads only+what every named person may read.`gbrain access check --token <name>` shows theresult ([Model C](../tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape)).diff --git a/docs/protocol/MCP_META_CHANNELS.md b/docs/protocol/MCP_META_CHANNELS.mdindex f901fa3a25..cb7f4a1c1f 100644--- a/docs/protocol/MCP_META_CHANNELS.md+++ b/docs/protocol/MCP_META_CHANNELS.md@@ -32,11 +32,17 @@ shape for it.|-----|----------|----------|| `brain_hot_memory` | serve-http `metaHook` (`getBrainHotMemoryMeta`) | Hot-memory facts relevant to the call; each fact carries `trust_tier` and `origin`, and `suppressed` (`{withheld, review}`, present only when non-zero) counts unconfirmed agent-written facts activation control withheld, never their content || `retrieval` | `search`/`query` op handlers | `returned_count`, `retrieved_count`, `vector_enabled`, `expansion_applied`, `cache`, `token_budget`, `degraded[]` (closed stage vocabulary), `rerank_degraded` (on a call whose reranker failed: `{reason, fallback: "fused_order", calls_this_session}`; reason is `timeout`, `budget`, `rate_limited`, `unreachable`, `auth` or `provider_error`; no `fields: "full"` needed), `hint` (non-contractual prose), `rows` (`"lean"` or `"full"`: the row shape of content[0]; reported for remote callers and whenever `fields` is passed), `timings` (`{total_ms, stages_ms, other_ms, overlapped_ms?, parts_ms?}`, integer ms, every response; [search-explain.md](../guides/search-explain.md#see-where-the-time-went)) |+| `access` | dispatch (`appliedAccessSummary`, `src/core/access/caller.ts`), every remote response that reached the operation | The view the call was answered under: `member` and `groups` it read as (null and `[]` for an unbound caller or an audience of several entries), `audience` (the normalized `on_behalf_of` principals, or null), `policy_rev` (each source's applied folder-rule revision; null on a brain with no restriction), `relaxation` (`none`, `granted_sources` or `operator`: what relaxed `visibility: private`). `whoami` returns the same object as `access.applied`. || `warnings` | dispatch strict-params warn mode | `[{code: 'unknown_param', param, suggestion?}]` || `pagination` | `list_pages` op handler | `truncated` (more rows match), `limit` (effective), `clamped_from?` (the caller's limit when capped), `next?` (params for the following page: `{sort, updated_after, updated_after_slug}` under `updated_asc`, else `{offset}`). The model-visible counterpart is the `listing_truncated` notice block (kind `info`, never deduped), whose `fix.mcp` is the next-page call. |Inbound `_meta` (e.g. `_meta.session_id` inside tool ARGUMENTS) is a-separate, client-to-server plane. The eval-report `_meta.metric_glossary`+separate, client-to-server plane. Request-level `_meta.on_behalf_of` (a+sibling of `arguments`, list of member ids, `group:<id>` and `guest`) names a+shared agent's audience, like the `X-Gbrain-On-Behalf-Of` header; it is+bounded by the credential's `may_act_for`, and the same key inside tool+arguments is refused (`on_behalf_of_in_arguments`). See Model C in+[company-brain.md](../tutorials/company-brain.md). The eval-report `_meta.metric_glossary`lives in JSON BODIES of eval commands — a third, unrelated plane. Ambientrecall rides content/hooks, not `_meta`.diff --git a/docs/tutorials/company-brain.md b/docs/tutorials/company-brain.mdindex 6975e3c1c8..4f07158370 100644--- a/docs/tutorials/company-brain.md+++ b/docs/tutorials/company-brain.md@@ -144,6 +144,21 @@ A remote read of a page under a rule needs the caller's member to be on every ruOn a git-backed source the same rules live in `.gbrain/access.yml`: `rule add|rm` commit it through `gbrain git commit-push`, a hand edit takes effect when you commit it and run `gbrain sync`, and a widening commit stays held until `gbrain access apply` approves it (recorded in `.gbrain/access.approved`). A source keeps the store it had when its first rule was created; `gbrain access rule migrate --source <id>` (preview, then `--yes`) moves the rules when you attach or remove a repo. Remote callers cannot write `.gbrain/`.+**Shared agents: one agent, each person's view.** When one agent serves everyone (a Slack or Telegram bot), its harness code names whom each turn serves, and the agent reads only what all of them may read. List the people its credential may act for, then have the harness send the audience on every MCP request:++```bash+gbrain auth rescope --token team-bot --may-act-for alice-example,bob-example,group:team-a,guest+gbrain access check --token team-bot --as alice-example,guest # what that audience reads, and whether may_act_for covers it+```++```text+X-Gbrain-On-Behalf-Of: alice-example # a DM with Alice (gbrain serve --http)+X-Gbrain-On-Behalf-Of: alice-example, bob-example, guest # a channel with a non-member in it+"_meta": { "on_behalf_of": ["alice-example"] } # request-level _meta, a sibling of arguments (stdio and HTTP)+```++A page is returned only when every audience entry may read it (`guest` reads no restricted page, `group:team-a` counts as one entry for a large channel), within the agent's own source grant. The agent's `--private-pages granted-sources` and the operator hatches relax `visibility: private` only when the audience is exactly one member; a channel never sees a private page. The audience is read on every call, so a DM followed by a channel turn gets each its own view. An entry outside `may_act_for` refuses `on_behalf_of_not_permitted` (the operator widens the list with the command it prints), a disabled or unknown member refuses `on_behalf_of_unknown_member`, and an audience inside tool arguments, where conversation text could set it, refuses `on_behalf_of_in_arguments`. Every response carries the applied view in `_meta.access`, and `whoami` returns it as `access.applied` for a model whose harness hides `_meta`. Writes and `submit_agent` jobs keep the audience they were made for and re-check it before they commit or call a tool. A local stdio server takes its list from `gbrain config set mcp.stdio_may_act_for <list>`. `*` permits any member and `gbrain doctor` warns about it (`access_may_act_for_wildcard`). Each assertion is appended to `~/.gbrain/audit/access-audience-YYYY-Www.jsonl`. Where each person runs their own agent, a credential bound to that person's member stays the simpler setup. Shared agents work the same on a repo-less brain: `may_act_for` and the audience are database and request state.+For most company-brain installs (10+ teammates each with their own AI client), Model A is the right starting point. If you're running the fat-agent-serves-everyone pattern from the personal-brain tutorial, Model B is genuinely simpler. You can also mix: separate sources for the obviously-different ones (customer notes vs internal-only) AND a `partners/<slug>/` convention inside the shared source for per-person workspace.### Per-person folder structure inside each sourcediff --git a/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md b/plugin-variants/gbrain-coding/skills/conventions/brain-routing.mdindex 1486acc966..c5a7cfbe74 100644--- a/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md+++ b/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md@@ -27,7 +27,7 @@ is the right answer 90% of the time. Don't cross the boundary without areason.A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludes-this credential: check `whoami` (member, groups) before telling the user there are no notes.+this credential or the audience it acts for: check `whoami` (`access.applied`) before telling the user there are no notes.## 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 1486acc966..c5a7cfbe74 100644--- a/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md+++ b/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md@@ -27,7 +27,7 @@ is the right answer 90% of the time. Don't cross the boundary without areason.A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludes-this credential: check `whoami` (member, groups) before telling the user there are no notes.+this credential or the audience it acts for: check `whoami` (`access.applied`) before telling the user there are no notes.## When to switch braindiff --git a/plugin/skills/conventions/brain-routing.md b/plugin/skills/conventions/brain-routing.mdindex 1486acc966..c5a7cfbe74 100644--- a/plugin/skills/conventions/brain-routing.md+++ b/plugin/skills/conventions/brain-routing.md@@ -27,7 +27,7 @@ is the right answer 90% of the time. Don't cross the boundary without areason.A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludes-this credential: check `whoami` (member, groups) before telling the user there are no notes.+this credential or the audience it acts for: check `whoami` (`access.applied`) before telling the user there are no notes.## When to switch braindiff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.tsindex 35e0f829c1..7b13ea6e6b 100644--- a/scripts/check-engine-sql-dynamic.ts+++ b/scripts/check-engine-sql-dynamic.ts@@ -79,6 +79,7 @@ const VETTED_BUILDERS: Record<string, string> = {rederiveHiddenSql: 'src/core/eligibility/sql.ts: constant needs_rederive NOT EXISTS predicate over a literal table name and caller alias; no values',privateProvenanceFilterFragment: 'src/core/search/private-visibility.ts: constant fact-provenance visibility predicate over a caller alias',readersAllowedSql: 'src/core/search/private-visibility.ts: GBRA-218 readers predicate over a caller alias; splices only identities that pass validIdentity (member:/group: plus [a-z0-9._-]), else none',+ callerReadersAllowedSql: 'src/core/search/private-visibility.ts: GBRA-231 readersAllowedSql for the current caller, one conjunct per audience identity; each identity passes validIdentity',privacyForCaller: 'src/core/search/private-visibility.ts: the caller privacy arm (TRUE, or the given predicate ORed with private-readable source ids checked by isValidSourceId); callers pass a constant alias and a vetted predicate builder',privateProvenanceFilterUnderPolicy: 'src/core/search/private-visibility.ts: constant fact-provenance predicate (readers part with no identity, privacy part dropped only under an operator relaxation); no values',stagingNeedsTextSql: 'src/core/page-body/schema.ts: constant live-staging text-reference EXISTS predicate over a caller text alias; no values (Wave B purge)',diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 565cba56eb..48f55e8ddc 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -41,7 +41,7 @@ src/core/persistence/sync-run.ts 1686 ratchet new row: crossed the 1500 unlistedsrc/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 729 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts); +1 GBRA-218: put_page checks a remote readable_by before admission (logic in persistence/page-visibility.ts assertSubmittedReaders)-src/core/search/mode.ts 1716 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured); +5 GBRA-156: append-only xpr= knobsHash part (private-readable set); +7 GBRA-218 A1: append-only xid=/xhp= knobsHash parts (member identity, operator privacy relaxation)+src/core/search/mode.ts 1717 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured); +5 GBRA-156: append-only xpr= knobsHash part (private-readable set); +7 GBRA-218 A1: append-only xid=/xhp= knobsHash parts (member identity, operator privacy relaxation); +1 GBRA-231: append-only xau= knobsHash part (shared-agent audience identities)src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50")src/core/search/evidence-delivery.ts 1733 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)diff --git a/skills/conventions/brain-routing.md b/skills/conventions/brain-routing.mdindex 1486acc966..c5a7cfbe74 100644--- a/skills/conventions/brain-routing.md+++ b/skills/conventions/brain-routing.md@@ -27,7 +27,7 @@ is the right answer 90% of the time. Don't cross the boundary without areason.A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludes-this credential: check `whoami` (member, groups) before telling the user there are no notes.+this credential or the audience it acts for: check `whoami` (`access.applied`) before telling the user there are no notes.## When to switch braindiff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex ff8202496a..b46ff9c1d7 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": "b42b19223aa9dffbe783ce7c5c681d762377c740f3c609cbc555b9a60a035235","conventions/brain-first.md": "e0e4d7c4b760213325dffd286baf934720816a0b6aac5338538a0463e8fe77d2",- "conventions/brain-routing.md": "418cb37cfa5b297290f58104df167de727812f921b82f218f55b0a9295c505db",+ "conventions/brain-routing.md": "f11c3e7c4f98163aa6c68aa7d8f09a7acb7b6a8695f42eb7d92d4ee5787d428a","conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198","conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933","conventions/cross-modal.yaml": "c012c3d72614a87b1ee698173dce2a0fb0d057a54df7aab87993c4b07fff6280",diff --git a/src/commands/access.ts b/src/commands/access.tsindex 311c039bbb..8c0a8a07d5 100644--- a/src/commands/access.ts+++ b/src/commands/access.ts@@ -20,6 +20,7 @@ import { readClientGrant } from '../core/grants/service.ts';import { resolveTokenGrant } from '../core/grants/legacy-token.ts';import { isPrivacyPrivatePage } from '../core/search/private-visibility.ts';import { identityFor, normalizePrincipal, normalizeReaders, readersAllow } from '../core/access/principals.ts';+import { mayActForCovers, singleMemberAudience, type AudiencePrincipal } from '../core/access/audience.ts';import {addGroup, addMember, assertAccessId, disableMember, enableMember, getMember, legacyTokenByName, listGroups, listMembers,parseIdList, previewRemoveGroup, previewRemoveMember, removeGroup, removeGroupMembers, removeMember, type MemberRecord,@@ -177,10 +178,13 @@ export async function accessCheck(engine: BrainEngine, target: { token?: string;} else if (principal.startsWith('group:') && !(await listGroups(engine, principal.slice(6))).length) {throw opError('access_member_invalid', `--as names group "${principal.slice(6)}", which does not exist.`, 'List groups with gbrain access group list.', { reason: 'unknown_group', why: 'An audience names existing groups only.' });}- audience.push({ principal, covered_by_may_act_for: !!mayActFor && (mayActFor.includes('*') || mayActFor.includes(principal)) });+ audience.push({ principal, covered_by_may_act_for: mayActForCovers(mayActFor, principal as AudiencePrincipal) });}result.audience = audience;- result.explanation += ' may_act_for is stored only in this release; shared-agent audiences are enforced by a later release.';+ const missing = audience.filter(a => !a.covered_by_may_act_for).map(a => a.principal);+ result.explanation += missing.length+ ? ` A request naming this audience is refused (on_behalf_of_not_permitted): may_act_for does not list ${missing.join(', ')}.`+ : ` A request naming this audience reads only the pages every entry may read${singleMemberAudience(audience.map(a => a.principal)) ? '' : ' and no visibility: private page'}, within the grant above.`;}return result;}diff --git a/src/commands/auth.ts b/src/commands/auth.tsindex 9f676ae482..9ce2248946 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -1347,8 +1347,9 @@ Usage:--member <id|none> Bind the token or client to a member: remote reads ofpages naming readers (readable_by) see what that membermay read; 'none' unbinds (see gbrain access --help)- --may-act-for <list|none> Shared agents: member ids, group:<id>, guest or * it may- act for (stored; enforced by a later release)+ --may-act-for <list|none> Shared agents: member ids, group:<id>, guest or * the+ harness may name as a request's audience+ (X-Gbrain-On-Behalf-Of or _meta.on_behalf_of)--private-pages <granted-sources|none> Remote reads see visibility: private pages in thesources this grant names explicitly (never theno-grant floor, federation, a client's bound sourcediff --git a/src/commands/doctor/checks/shared-agent-access.ts b/src/commands/doctor/checks/shared-agent-access.tsnew file mode 100644index 0000000000..8ff39a6dae--- /dev/null+++ b/src/commands/doctor/checks/shared-agent-access.ts@@ -0,0 +1,55 @@+/**+ * GBRA-231 shared-agent doctor check (plan section 5, decision D6).+ *+ * - access_may_act_for_wildcard: credentials (access tokens, OAuth clients) whose may_act_for holds `*`, and a stdio+ * server whose config mcp.stdio_may_act_for does. Such a credential's harness may name any enabled member as a+ * request's audience and read what that member reads, so `*` is accepted but warned about; an explicit list is the+ * narrower setup.+ *+ * A brain that holds no member restriction (config access.restrictions_present) is not applicable: with no member,+ * an audience can only be a guest, who reads nothing a credential could not.+ */+import type { Check } from '../../doctor.ts';+import { agentFix, checkError, infoCheck } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { accessRestrictionsPresent } from '../../../core/search/private-visibility.ts';+import { STDIO_MAY_ACT_FOR_KEY } from '../../../core/access/audience.ts';++const name = 'access_may_act_for_wildcard';+const SAMPLE = 20;++async function runSharedAgentAccess(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ if (!(await accessRestrictionsPresent(engine).catch(() => true))) {+ return [infoCheck(name, 'Not applicable: no page names readers and no member exists.', 'not_applicable')];+ }+ try {+ const rows = await engine.executeRaw<{ kind: 'token' | 'client'; id: string; name: string }>(+ `SELECT * FROM (+ SELECT 'token' AS kind, id::text AS id, name FROM access_tokens WHERE revoked_at IS NULL AND '*' = ANY(may_act_for)+ UNION ALL+ SELECT 'client' AS kind, client_id AS id, COALESCE(client_name, client_id) AS name FROM oauth_clients WHERE deleted_at IS NULL AND '*' = ANY(may_act_for)+ ) w ORDER BY kind, name LIMIT ${SAMPLE}`);+ const [stdio] = await engine.executeRaw<{ value: string | null }>('SELECT value FROM config WHERE key = $1', [STDIO_MAY_ACT_FOR_KEY]);+ const stdioWild = (stdio?.value ?? '').split(',').map(s => s.trim()).includes('*');+ const named = [...rows.map(r => `${r.kind} ${r.name}`), ...(stdioWild ? [`config ${STDIO_MAY_ACT_FOR_KEY}`] : [])];+ const details = { credentials: rows.map(r => ({ kind: r.kind, name: r.name })), stdio: stdioWild, truncated: rows.length === SAMPLE };+ if (!named.length) return [{ name, status: 'ok', details, message: 'No credential may act for every member (no may_act_for holds *).' }];+ const first = rows[0];+ return [{ name, status: 'warn', details,+ message: `${named.length} credential(s) may act for any member (may_act_for holds *): ${named.slice(0, 5).join(', ')}. `+ + 'A harness using one can name any enabled member as its audience and read what that member reads. List the people it serves instead.',+ fix: first+ ? agentFix(['gbrain', 'access', 'check', first.kind === 'token' ? '--token' : '--client', first.kind === 'token' ? first.name : first.id, '--json'],+ 'Read-only: shows the credential\'s grant and may_act_for. Ask the user which members, groups or guest it serves before narrowing it with gbrain auth rescope ... --may-act-for <list>.', name, { ask_user: true })+ : agentFix(['gbrain', 'config', 'get', STDIO_MAY_ACT_FOR_KEY], `Read-only: shows ${STDIO_MAY_ACT_FOR_KEY}. Ask the user whom the stdio server serves before replacing * with that list.`, name, { ask_user: true }) }];+ } catch (error) {+ return [checkError(name, `run ${name}`, error)];+ }+}++export const sharedAgentAccessEntry: DoctorEntry = {+ name,+ emits: [name],+ run: runSharedAgentAccess,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 62b6185948..67318e61de 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -128,6 +128,7 @@ import { syncConfigKeysEntry } from './checks/sync-config-keys.ts';import { ghostPagesEntry } from './checks/ghost-pages.ts';import { memberAccessEntry } from './checks/member-access.ts';import { folderAccessEntry } from './checks/folder-access.ts';+import { sharedAgentAccessEntry } from './checks/shared-agent-access.ts';import { originTwinsEntry } from './checks/origin-twins.ts';import { slugPathMismatchEntry } from './checks/slug-path-mismatch.ts';import { renameIdentityDowngradesEntry } from './checks/rename-identity-downgrades.ts';@@ -208,6 +209,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [derivedVisibilityEntry,memberAccessEntry,folderAccessEntry,+ sharedAgentAccessEntry,rlsEntry,schemaVersionEntry,rlsEventTriggerEntry,diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex b28dfde4cb..3a39dcfa74 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -41,6 +41,7 @@ import {type McpSurface,} from '../mcp/surface.ts';import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';+import { ON_BEHALF_OF_HEADER } from '../core/access/audience.ts';import { serializeError } from '../core/errors.ts';import { VERSION } from '../version.ts';import { executeRawJsonb } from '../core/sql-query.ts';@@ -61,6 +62,8 @@ interface McpRequestState {resultRows: ResultRowsMode;/** Large pages: the same header marks gbrain's thin client, whose default get_page mode stays whole. Never authority. */thinClient: boolean;+ /** GBRA-231: the X-Gbrain-On-Behalf-Of header (a shared agent's audience); bounded by the credential's may_act_for in dispatch. */+ onBehalfOfHeader: string | undefined;}export function mountMcp(app: Express, ctx: ServeHttpContext): void {@@ -171,7 +174,8 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {const surfaceAllowedOps: ReadonlySet<string> | undefined =surface === 'full' && authInfo.allowedOperations == null ? undefined : new Set(mcpOperations.map(o => o.name));const thinClient = isGbrainThinClient(req.get(GBRAIN_CLIENT_HEADER));- const state: McpRequestState = { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps, resultRows, thinClient };+ const state: McpRequestState = { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps, resultRows, thinClient,+ onBehalfOfHeader: req.get(ON_BEHALF_OF_HEADER) };const server = createMcpRequestServer(ctx, state, writeback);await serveMcpRequest(server, req, res);}@@ -406,6 +410,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, requesinboundFrameBytes: DEFAULT_MAX_REQUEST_BODY_SIZE,...(sessionId ? { sessionId } : {}),...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}),+ onBehalfOf: { header: state.onBehalfOfHeader, requestMeta: (request.params as { _meta?: unknown })._meta },takesHoldersAllowList: tokenAllowList,sourceId: tokenSourceId,...(localFederated ? { localFederatedSourceIds: localFederated } : {}),diff --git a/src/core/access/audience.ts b/src/core/access/audience.tsnew file mode 100644index 0000000000..bd767ae1bb--- /dev/null+++ b/src/core/access/audience.ts@@ -0,0 +1,118 @@+/**+ * GBRA-231 (per-member read access, PR B, plan section 4): a shared agent acts+ * for an audience. Harness code, never the model, names the people a turn+ * serves (one person in a DM, everyone in a channel, `guest` for a+ * non-member) in the `X-Gbrain-On-Behalf-Of` header (serve --http) or in+ * request-level `_meta.on_behalf_of` (a sibling of `arguments`, stdio and+ * HTTP). The call then reads only what every audience entry may read, within+ * the agent's own source grant (caller.ts resolves the identities).+ *+ * This module holds the transport-independent parts: the grammar, the+ * argument-channel refusal, the may_act_for coverage test and the audit trail.+ * Every refusal happens before any work, and none reveals page content.+ */+import { catalogueError } from '../error-catalogue.ts';+import { createAuditWriter } from '../audit/audit-writer.ts';+import { normalizePrincipal } from './principals.ts';++/** The HTTP header a harness sets on every POST /mcp (case-insensitive). */+export const ON_BEHALF_OF_HEADER = 'X-Gbrain-On-Behalf-Of';+/** Config key listing whom a local stdio server may act for (the stdio twin of a credential's may_act_for). */+export const STDIO_MAY_ACT_FOR_KEY = 'mcp.stdio_may_act_for';+export const GUEST = 'guest';+export const MAX_AUDIENCE = 50;++export type AudiencePrincipal = `member:${string}` | `group:${string}` | typeof GUEST;++/** The raw audience channels a transport saw: the header value (undefined when absent) and request.params._meta. */+export interface AudienceChannels {+ header?: string | null;+ requestMeta?: unknown;+}++function invalid(what: string): never {+ throw catalogueError('on_behalf_of_invalid_audience', `The on_behalf_of audience is invalid: ${what}. Nothing was read.`,+ `Send 1-${MAX_AUDIENCE} entries, each a member id, group:<id> or guest, as ${ON_BEHALF_OF_HEADER}: alice-example, bob-example or as request-level _meta.on_behalf_of: ["alice-example", "bob-example"]; when both are sent they must name the same audience.`);+}++const shown = (value: unknown) => JSON.stringify(typeof value === 'string' && value.length > 64 ? `${value.slice(0, 64)}...` : value);++function entries(list: readonly unknown[], channel: string): AudiencePrincipal[] {+ if (list.length === 0) invalid(`${channel} names nobody`);+ if (list.length > MAX_AUDIENCE) invalid(`${channel} names ${list.length} entries (at most ${MAX_AUDIENCE}; name a group:<id> for a large channel)`);+ const out = new Set<AudiencePrincipal>();+ for (const raw of list) {+ if (typeof raw !== 'string') invalid(`${channel} holds ${shown(raw)}, which is not a string`);+ if (raw.trim().toLowerCase() === GUEST) { out.add(GUEST); continue; }+ const p = normalizePrincipal(raw);+ if (!p) invalid(`${channel} holds ${shown(raw)}, which is not a member id, group:<id> or guest`);+ out.add(p);+ }+ return [...out].sort();+}++/**+ * The normalized audience a request asserts (sorted, distinct), or null when it asserts none. A present but empty,+ * oversized or malformed channel, or a header and _meta that disagree, refuse on_behalf_of_invalid_audience.+ */+export function parseAudience(channels: AudienceChannels | undefined): AudiencePrincipal[] | null {+ const header = channels?.header ?? undefined;+ const meta = channels?.requestMeta;+ const metaRecord = meta !== null && typeof meta === 'object' && !Array.isArray(meta) ? meta as Record<string, unknown> : null;+ const metaPresent = !!metaRecord && Object.prototype.hasOwnProperty.call(metaRecord, 'on_behalf_of');+ if (header === undefined && !metaPresent) return null;+ const fromHeader = header === undefined ? null+ : entries(header.trim() === '' ? [] : header.split(',').map(s => s.trim()), `the ${ON_BEHALF_OF_HEADER} header`);+ let fromMeta: AudiencePrincipal[] | null = null;+ if (metaPresent) {+ const value = metaRecord!.on_behalf_of;+ if (!Array.isArray(value)) invalid('_meta.on_behalf_of is not a list of strings');+ fromMeta = entries(value, '_meta.on_behalf_of');+ }+ if (fromHeader && fromMeta && fromHeader.join(',') !== fromMeta.join(',')) invalid(`the ${ON_BEHALF_OF_HEADER} header and _meta.on_behalf_of name different audiences`);+ return fromHeader ?? fromMeta;+}++/** True when tool arguments carry an audience (top-level or inside an arguments-level _meta): only harness channels count. */+export function audienceInArguments(params: Record<string, unknown> | undefined): boolean {+ if (!params) return false;+ if (Object.prototype.hasOwnProperty.call(params, 'on_behalf_of')) return true;+ const meta = params._meta;+ return meta !== null && typeof meta === 'object' && !Array.isArray(meta) && Object.prototype.hasOwnProperty.call(meta, 'on_behalf_of');+}++export function audienceInArgumentsError() {+ return catalogueError('on_behalf_of_in_arguments', 'on_behalf_of is not accepted inside tool arguments, so nothing was read. Text in a conversation cannot choose whose notes an agent reads.',+ `Only harness code names an audience: the ${ON_BEHALF_OF_HEADER} header (gbrain serve --http) or request-level _meta.on_behalf_of, a sibling of arguments. Remove on_behalf_of from the arguments and call again. A stdio client that cannot set request-level _meta uses a credential bound to one member, or config mcp.stdio_member.`);+}++/** Whether a stored may_act_for list permits one audience entry: `*` or the exact principal (a group entry covers group:<id> only). */+export function mayActForCovers(mayActFor: readonly string[] | null | undefined, principal: AudiencePrincipal): boolean {+ return !!mayActFor && (mayActFor.includes('*') || mayActFor.includes(principal));+}++/** The audience a single member: only then does the agent's own privacy relaxation (granted_sources, a hatch) apply. */+export function singleMemberAudience(audience: readonly string[] | null | undefined): boolean {+ return !!audience && audience.length === 1 && audience[0]!.startsWith('member:');+}++/** One audience assertion as the trail records it: who asserted it, for whom, and the outcome. Never page content. */+export interface AudienceAuditEvent {+ ts: string;+ principal: string;+ transport: string;+ 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';+}++const audit = createAuditWriter<AudienceAuditEvent>({ featureName: 'access-audience', errorLabel: 'access-audience-audit', errorTrailer: '; continuing' });++/** Appends one assertion to ~/.gbrain/audit/access-audience-YYYY-Www.jsonl (GBRAIN_AUDIT_DIR honoured); best effort, never throws. */+export function logAudienceAssertion(event: Omit<AudienceAuditEvent, 'ts'>): void {+ audit.log({ ts: new Date().toISOString(), ...event });+}++export function readAudienceAssertions(): AudienceAuditEvent[] {+ return audit.readRecent();+}diff --git a/src/core/access/caller.ts b/src/core/access/caller.tsindex 4da361a8aa..d3ea4d86f6 100644--- a/src/core/access/caller.ts+++ b/src/core/access/caller.ts@@ -15,14 +15,20 @@ import type { BrainEngine } from '../engine.ts';import type { AuthInfo } from '../ops/contract.ts';import { accessRestrictionsPresent, remotePrivacyRelaxed, type CallerAccess, type FolderCoverage } from '../search/private-visibility.ts';import { ACCESS_ID_RE, identityFor, normalizePrincipal } from './principals.ts';+import { catalogueError } from '../error-catalogue.ts';+import { hostOnlyError } from '../ops/op-fix.ts';+import { currentCallerAccess } from '../search/private-visibility.ts';+import { GUEST, STDIO_MAY_ACT_FOR_KEY, mayActForCovers, singleMemberAudience, type AudiencePrincipal } from './audience.ts';+import { parseMayActFor } from './members.ts';/** Config key binding a local stdio MCP server to one member. */export const STDIO_MEMBER_KEY = 'mcp.stdio_member';-const MEMBER_SQL = (member: string) => `SELECT m.id, COALESCE(array_agg(g.group_id ORDER BY g.group_id) FILTER (WHERE g.group_id IS NOT NULL), '{}') AS groups+const MEMBERS_WHERE_SQL = (predicate: string) => `SELECT m.id, COALESCE(array_agg(g.group_id ORDER BY g.group_id) FILTER (WHERE g.group_id IS NOT NULL), '{}') AS groupsFROM access_members m LEFT JOIN access_group_members g ON g.member_id = m.id- WHERE m.id = (${member}) AND m.disabled_at IS NULL AND m.tombstoned_at IS NULL+ WHERE ${predicate} AND m.disabled_at IS NULL AND m.tombstoned_at IS NULLGROUP BY m.id`;+const MEMBER_SQL = (member: string) => MEMBERS_WHERE_SQL(`m.id = (${member})`);async function liveIdentity(engine: Pick<BrainEngine, 'executeRaw'>, memberSql: string, param: string): Promise<string[]> {try {@@ -71,25 +77,143 @@ export async function stdioMemberIdentity(engine: BrainEngine): Promise<string[]* stamped, an invalid policy file). An unreadable rulebook satisfies nothing and covers everything (fail closed).*/export async function folderAccessFor(engine: Pick<BrainEngine, 'executeRaw'>, identity: readonly string[]): Promise<{ satisfiedRuleIds: string[]; folderCoverage: FolderCoverage[] }> {+ return folderAccessForAll(engine, [identity]);+}++/**+ * GBRA-231: folderAccessFor for an audience. A rule is satisfied only when every identity meets its readers, so the+ * satisfied set is the intersection of each entry's set (empty when any entry, a guest included, meets none).+ */+export async function folderAccessForAll(engine: Pick<BrainEngine, 'executeRaw'>, identities: readonly (readonly string[])[]): Promise<{ satisfiedRuleIds: string[]; folderCoverage: FolderCoverage[] }> {try {- const rules = identity.length- ? await engine.executeRaw<{ source_id: string; rule_id: string }>('SELECT source_id, rule_id FROM access_rules WHERE readable_by && $1::text[]', [[...identity]])+ const union = [...new Set(identities.flat())];+ const rules = union.length && identities.length && identities.every(id => id.length > 0)+ ? await engine.executeRaw<{ source_id: string; rule_id: string; readable_by: string[] }>('SELECT source_id, rule_id, readable_by FROM access_rules WHERE readable_by && $1::text[]', [union]): [];+ const satisfied = rules.filter(r => identities.every(id => (r.readable_by ?? []).some(reader => id.includes(reader))));const coverage = await engine.executeRaw<{ source_id: string; prefix: string }>('SELECT DISTINCT source_id, prefix FROM access_pending_coverage ORDER BY source_id, prefix');- return { satisfiedRuleIds: rules.map(r => `${r.source_id}:${r.rule_id}`).sort(), folderCoverage: coverage.map(c => ({ source_id: c.source_id, prefix: c.prefix })) };+ return { satisfiedRuleIds: satisfied.map(r => `${r.source_id}:${r.rule_id}`).sort(), folderCoverage: coverage.map(c => ({ source_id: c.source_id, prefix: c.prefix })) };} catch {return { satisfiedRuleIds: [], folderCoverage: [{ source_id: '!unreadable', prefix: '' }] };}}-/** The CallerAccess fields for a remote operation (identity, privacy relaxation and the GBRA-156 private-readable set). */-export async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | undefined, privateSources: readonly string[] | undefined, transport?: string): Promise<Partial<CallerAccess>> {+/** Who asserts an audience: a verified credential (live call), a stored principal (a queued write or job), or a stdio server. */+export interface AudienceCaller {+ auth?: Pick<AuthInfo, 'member' | 'mayActFor' | 'clientId' | 'clientName'> & { principal?: { kind: string; id: string } };+ principal?: { kind: string; id: string };+ transport?: string;+}++/**+ * The may_act_for list that bounds `caller`: the verifier's join on a live call (read on every request), else a live+ * lookup from the stored principal (a revoked token or deleted client permits nothing), else for a stdio server+ * config mcp.stdio_may_act_for. Unreadable or ill-formed values permit nothing.+ */+async function mayActForOf(engine: Pick<BrainEngine, 'executeRaw'>, caller: AudienceCaller): Promise<string[] | null> {+ const auth = caller.auth;+ if (auth?.member !== undefined) return auth.mayActFor ?? null;+ const principal = auth?.principal ?? caller.principal;+ try {+ if (principal?.kind === 'legacy_token') {+ const [row] = await engine.executeRaw<{ may_act_for: unknown }>('SELECT may_act_for FROM access_tokens WHERE id::text = $1 AND revoked_at IS NULL', [principal.id]);+ return Array.isArray(row?.may_act_for) ? row!.may_act_for as string[] : null;+ }+ if (principal?.kind === 'oauth_client') {+ const [row] = await engine.executeRaw<{ may_act_for: unknown }>('SELECT may_act_for FROM oauth_clients WHERE client_id = $1 AND deleted_at IS NULL', [principal.id]);+ return Array.isArray(row?.may_act_for) ? row!.may_act_for as string[] : null;+ }+ if (principal?.kind === 'local_stdio' || (!auth && !principal && caller.transport === 'stdio')) {+ const [row] = await engine.executeRaw<{ value: string | null }>('SELECT value FROM config WHERE key = $1', [STDIO_MAY_ACT_FOR_KEY]);+ const raw = row?.value?.trim();+ return raw ? parseMayActFor(raw) : null;+ }+ } catch { /* unreadable: permits nothing */ }+ return null;+}++function audienceNotPermitted(caller: AudienceCaller, audience: readonly AudiencePrincipal[], mayActFor: readonly string[] | null, missing: readonly string[]) {+ const principal = caller.auth?.principal ?? caller.principal;+ const list = [...new Set([...(mayActFor ?? []), ...audience])].sort().join(',');+ const target = principal?.kind === 'legacy_token' ? { handle: `token ${caller.auth?.clientName ?? principal.id}`, argv: ['gbrain', 'auth', 'rescope', ...(caller.auth?.clientName ? ['--token', caller.auth.clientName] : ['--id', principal.id]), '--may-act-for', list] }+ : principal?.kind === 'oauth_client' ? { handle: `OAuth client ${principal.id}`, argv: ['gbrain', 'auth', 'rescope', '--client', principal.id, '--may-act-for', list] }+ : { handle: 'this stdio server', argv: ['gbrain', 'config', 'set', STDIO_MAY_ACT_FOR_KEY, list] };+ return hostOnlyError({ remote: true, transport: caller.transport === 'stdio' || target.handle === 'this stdio server' ? 'stdio' : 'http' }, 'on_behalf_of_not_permitted',+ `This connection (${target.handle}) may not act for ${missing.join(', ')}, so nothing was read.`,+ target.argv,+ 'Lets this credential act for the whole audience. Widening whose notes a shared agent may read is the brain operator\'s decision, never the agent\'s.',+ { suggestion: `A shared agent acts only for the people its credential lists in may_act_for. The brain operator decides whether to approve the audience ${audience.join(', ')} by running the command in fix on the brain host; until then, call without the audience.` });+}++function audienceUnknown(principal: string) {+ const group = principal.startsWith('group:');+ return catalogueError('on_behalf_of_unknown_member', `The audience names ${principal}, which is not ${group ? 'a group' : 'an enabled member'} on this brain, so nothing was read.`,+ `Name enabled members and existing groups only; a person who is not a member joins the audience as guest. The brain operator checks the ids with gbrain access ${group ? 'group' : 'member'} list${group ? '' : ' --all'}.`);+}++/**+ * GBRA-231: the identities of an asserted audience, in order: a member's live identity (itself and its groups), a+ * group as itself, a guest as the empty identity. Every entry must be in the caller's live may_act_for+ * (on_behalf_of_not_permitted, checked first so it never confirms whether an id exists) and name an enabled member+ * or an existing group (on_behalf_of_unknown_member). Read on every call, so a revoked permission or a disabled+ * member takes effect at once.+ */+export async function resolveAudienceIdentities(engine: Pick<BrainEngine, 'executeRaw'>, caller: AudienceCaller, audience: readonly AudiencePrincipal[]): Promise<string[][]> {+ const mayActFor = await mayActForOf(engine, caller);+ const missing = audience.filter(p => !mayActForCovers(mayActFor, p));+ if (missing.length) throw audienceNotPermitted(caller, audience, mayActFor, missing);+ const memberIds = audience.filter(p => p.startsWith('member:')).map(p => p.slice('member:'.length));+ const groupIds = audience.filter(p => p.startsWith('group:')).map(p => p.slice('group:'.length));+ const members = new Map<string, string[]>();+ const groups = new Set<string>();+ try {+ if (memberIds.length) {+ for (const row of await engine.executeRaw<{ id: string; groups: string[] }>(MEMBERS_WHERE_SQL('m.id = ANY($1::text[])'), [memberIds])) {+ members.set(row.id, (row.groups ?? []).filter(g => normalizePrincipal(`group:${g}`) === `group:${g}`));+ }+ }+ if (groupIds.length) for (const row of await engine.executeRaw<{ id: string }>('SELECT id FROM access_groups WHERE id = ANY($1::text[])', [groupIds])) groups.add(row.id);+ } catch { /* unreadable: every entry reads as unknown below */ }+ return audience.map(p => {+ if (p === GUEST) return [];+ if (p.startsWith('group:')) { if (!groups.has(p.slice(6))) throw audienceUnknown(p); return [p]; }+ const id = p.slice('member:'.length);+ const memberGroups = members.get(id);+ if (!memberGroups) throw audienceUnknown(p);+ return identityFor(id, memberGroups);+ });+}++/**+ * The CallerAccess fields for a remote operation (identity, privacy relaxation and the GBRA-156 private-readable set).+ * GBRA-231: with an asserted `audience` the identities are the audience's (resolveAudienceIdentities, which refuses+ * an entry outside may_act_for or naming no member), the source grant stays the caller's, and the caller's privacy+ * relaxation (granted_sources, an operator hatch) applies only when the audience is exactly one member: a channel+ * (several entries, a group or a guest) sees no visibility: private page.+ */+export async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | undefined, privateSources: readonly string[] | undefined, transport?: string, audience?: readonly AudiencePrincipal[] | null): Promise<Partial<CallerAccess>> {const [relaxed, restricted] = await Promise.all([remotePrivacyRelaxed(engine), accessRestrictionsPresent(engine)]);+ if (audience?.length) {+ const identities = await resolveAudienceIdentities(engine, { auth, transport }, audience);+ const single = singleMemberAudience(audience);+ return {+ identity: identities.length === 1 ? identities[0]! : [],+ audience: [...audience],+ audienceIdentities: identities.length > 1 ? identities : [],+ ...(restricted ? await folderAccessForAll(engine, identities) : { satisfiedRuleIds: [], folderCoverage: [] }),+ privateReadableSources: single ? privateSources ?? [] : [],+ hidePrivate: single ? !relaxed : true,+ applyRemoteReadPolicy: false,+ restricted,+ };+ }const identity = !restricted ? []: !auth && transport === 'stdio' ? await stdioMemberIdentity(engine): await memberIdentityFor(engine, auth);return {identity,+ audience: null,+ audienceIdentities: [],...(restricted ? await folderAccessFor(engine, identity) : { satisfiedRuleIds: [], folderCoverage: [] }),privateReadableSources: privateSources ?? [],hidePrivate: !relaxed,@@ -98,6 +222,41 @@ export async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | u};}+/**+ * GBRA-231: the view a remote call was answered under, as `_meta.access` on every remote response and `access.applied`+ * in whoami: the member and groups it read as (none for an audience of several entries), the asserted audience, the+ * applied folder-rule revision of each source the credential is granted (every source for an unauthenticated stdio+ * server; null on a brain with no restriction) and the privacy relaxation in force.+ */+export interface AppliedAccess {+ member: string | null;+ groups: string[];+ audience: string[] | null;+ policy_rev: Record<string, number> | null;+ relaxation: 'none' | 'granted_sources' | 'operator';+}++export async function appliedAccessSummary(engine: Pick<BrainEngine, 'executeRaw'>, auth?: AuthInfo, sourceIds: readonly (string | undefined)[] = []): Promise<AppliedAccess> {+ const access = currentCallerAccess();+ const member = access.identity.find(p => p.startsWith('member:'))?.slice('member:'.length) ?? null;+ let policyRev: Record<string, number> | null = null;+ if (access.restricted) {+ try {+ const rows = await engine.executeRaw<{ source_id: string; rev: number | string | null }>(+ 'SELECT source_id, max(revision) FILTER (WHERE applied_at IS NOT NULL) AS rev FROM access_policy_revisions GROUP BY source_id ORDER BY source_id');+ const visible = auth ? new Set([auth.sourceId, ...(auth.allowedSources ?? []), ...sourceIds].filter(Boolean)) : null;+ policyRev = Object.fromEntries(rows.filter(r => r.rev !== null && (!visible || visible.has(r.source_id))).map(r => [r.source_id, Number(r.rev)]));+ } catch { policyRev = null; }+ }+ return {+ member,+ groups: access.identity.filter(p => p.startsWith('group:')).map(p => p.slice('group:'.length)),+ audience: access.audience ? [...access.audience] : null,+ policy_rev: policyRev,+ relaxation: !access.hidePrivate ? 'operator' : access.privateReadableSources.length ? 'granted_sources' : 'none',+ };+}+/** What whoami and grant_diagnosis report about the caller's member identity. */export interface CallerAccessView {member: string | null;diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 7947285449..9c8fffb60c 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1271,6 +1271,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', id: 'private_pages_granted_sources_gbra156', text: 'Access tokens and OAuth clients have a new private-pages grant, `none` for every existing and new token and client, so remote reads still hide `visibility: private` pages until the brain host opts a connection in: `gbrain auth rescope --token <name> --private-pages granted-sources` (or `--client <id>`) lets it read private pages in the sources its grant names, and only those. A token with no source grant, federated sources the grant does not name and a request\'s `source_ids` never add one; `context_pack`, `delta` and writes keep hiding private pages. `--private-pages none` turns it off on the next request.' },{ since: 'TBD', id: 'member_read_access_gbra218', text: 'A page whose frontmatter names readers (`readable_by: [alice-example, group:team-a]`) is now read remotely only by a token, OAuth client or stdio server bound to a listed member (`gbrain access member add`, `gbrain auth rescope --token <name> --member <id>`, config `mcp.stdio_member`). Every other remote caller gets the same `not_found` as for a missing page, including unbound credentials, a `--private-pages granted-sources` bot and both escape hatches (`GBRAIN_REMOTE_PRIVATE_PAGES=1`, `search.remote_private_pages=visible`), which relax only `visibility: private`. A malformed `readable_by` reads as nobody, and a page derived from a restricted page reads as nobody remotely. Pages that already named `readable_by` before this upgrade read as nobody remotely until `gbrain repair access` (preview, then `--apply`). The local CLI is unchanged; `--as <member>` previews one member\'s view.' },{ since: 'TBD', id: 'member_access_hatch_scope_gbra218', text: 'On a brain where any page names readers or any member exists, the escape hatches no longer turn the remote read filter off: remote reads still hide pages the caller\'s member is not listed on, and secondary surfaces that use the identity-free filter (proactive brief, retrieval reflex, entity resolution, known-as-of) hide every restricted page and keep hiding `visibility: private` pages under a hatch. A brain with no restriction keeps the old hatch behaviour exactly. A credential bound to a disabled or removed member is refused at verification (`access_member_disabled`).' },+ { since: 'TBD', id: 'shared_agent_audience_gbra231', text: 'A shared agent can now read as the people a turn serves: its harness names the audience in the `X-Gbrain-On-Behalf-Of` header or request-level `_meta.on_behalf_of` (member ids, `group:<id>`, `guest`), and the call returns only pages every entry may read, within the agent\'s own source grant; a channel audience (more than one member, a group or a guest) never sees a `visibility: private` page. Each entry must be in the credential\'s `may_act_for` (`gbrain auth rescope --token <name> --may-act-for <list>`; for stdio, config `mcp.stdio_may_act_for`), which earlier releases stored without enforcing. An audience inside tool arguments is refused (`on_behalf_of_in_arguments`). Every remote MCP response now carries `_meta.access` (member, groups, audience, policy revisions, privacy relaxation), and `whoami` returns it as `access.applied`.' },+ { since: 'TBD', id: 'shared_agent_audience_gbra231', text: 'A shared agent can now read as the people a turn serves: its harness names the audience in the `X-Gbrain-On-Behalf-Of` header or request-level `_meta.on_behalf_of` (member ids, `group:<id>`, `guest`), and the call returns only pages every entry may read, within the agent\'s own source grant; a channel audience (more than one member, a group or a guest) never sees a `visibility: private` page. Each entry must be in the credential\'s `may_act_for` (`gbrain auth rescope --token <name> --may-act-for <list>`; for stdio, config `mcp.stdio_may_act_for`), which earlier releases stored without enforcing. An audience inside tool arguments is refused (`on_behalf_of_in_arguments`). Every remote MCP response now carries `_meta.access` (member, groups, audience, policy revisions, privacy relaxation), and `whoami` returns it as `access.applied`.' },{ since: 'TBD', id: 'folder_access_rules_gbra218', text: 'A source can now keep whole folders to named members with folder rules (`gbrain access rule add --prefix partners/alice-example/ --readers alice-example,group:team-a --source <id>`, preview then `--yes`). On a repo-less source the rules live in the database; on a git-backed source they live in `.gbrain/access.yml`, committed through `gbrain git commit-push` and applied on sync. A remote read of a page under a rule needs the caller\'s member to be listed on every rule covering it, on top of the page\'s own `readable_by`; no hatch, grant or `--as` relaxes it. Narrowing applies at once; a change that widens (removing a rule or a reader) is held until `gbrain access apply --source <id>` previews it and `--yes --expect <plan_hash>` approves it. While an apply is unfinished its prefixes read as nobody remotely (`access_policy_pending`, fixed by `gbrain access resume --source <id>`). `gbrain export` carries each source\'s applied rules under `.gbrain/`, and `gbrain import` installs them before any page (`--access-policy <source>` picks one source\'s rules from a multi-source export). Remote callers cannot write `.gbrain/` pages. Nothing changes on a source with no folder rule.' },];diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex f0c3b0c3c7..ea7ec0f97e 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -14,7 +14,7 @@// (help-text mentions count): accepting an ignored flag is the pre-#2185// status quo; missing a real one breaks working invocations.export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {- 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--approved', '--as', '--bind-token', '--brain', '--client', '--expect', '--file', '--groups', '--help', '--id', '--if-version', '--json', '--limit', '--may-act-for', '--member', '--members', '--migrate-legacy', '--name', '--operation', '--operations', '--prefix', '--private-pages', '--readers', '--refresh-operations', '--reset-default', '--revision', '--scopes', '--source', '--sources', '--takes-holders', '--to', '--token', '--yes'],+ 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--approved', '--as', '--bind-token', '--brain', '--client', '--expect', '--file', '--groups', '--help', '--http', '--id', '--if-version', '--json', '--limit', '--may-act-for', '--member', '--members', '--migrate-legacy', '--name', '--operation', '--operations', '--prefix', '--private-pages', '--readers', '--refresh-operations', '--reset-default', '--revision', '--scopes', '--source', '--sources', '--takes-holders', '--to', '--token', '--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', '--path', '--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'],@@ -51,7 +51,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', '--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', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--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', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--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', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--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', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--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', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--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', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--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-gpg-sign', '--no-hooks', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--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', '--preset', '--preview', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--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', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--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', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--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', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--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', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--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-gpg-sign', '--no-hooks', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--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', '--preset', '--preview', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--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', '--path', '--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', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--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'],@@ -77,14 +77,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', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--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'],- 'init': ['--access', '--access-policy', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--as', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--install', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--mcp-only', '--mcp-url', '--member', '--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-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--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', '--query', '--question', '--quiet', '--readers', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'init': ['--access', '--access-policy', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--as', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--install', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--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-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--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', '--query', '--question', '--quiet', '--readers', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--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', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--as', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--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', '--mcp-only', '--member', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--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-verify', '--no-worker', '--non-interactive', '--now', '--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', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--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', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--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', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--as', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--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', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--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-verify', '--no-worker', '--non-interactive', '--now', '--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', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--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', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--accept-pending', '--add', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--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-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--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': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--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-pull', '--no-renames', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--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'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],@@ -132,7 +132,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--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', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--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', '--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', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--cursor', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--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-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--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', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--cursor', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--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-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--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', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--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'],diff --git a/src/core/config-runtime-keys.ts b/src/core/config-runtime-keys.tsindex c3d29c47ca..4d2a626483 100644--- a/src/core/config-runtime-keys.ts+++ b/src/core/config-runtime-keys.ts@@ -20,5 +20,6 @@ export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = ['serve.cli_socket', // config.ts loadConfigWithEngine (snapshot only) → serve.ts: a Postgres serve answers CLI reads over a private Unix socket, default off'serve.vector_prewarm', // config.ts loadConfigWithEngine (snapshot only) → serve.ts: a Postgres serve prewarms the HNSW indexes into shared_buffers at start when they fit, default off'mcp.stdio_member', // access/caller.ts (GBRA-218): binds a local stdio MCP server to one member; unbound, stdio reads no page that names readers+ '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'access.restrictions_present', // search/private-visibility.ts (GBRA-218): '1' once a page names readers or a member exists (set by a migration trigger; sticky)];diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 255a78507b..2480334837 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -89,6 +89,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['access_policy_widening_held','access_policy_invalid','access_policy_store_mismatch',+ // GBRA-231: shared agents (doctor/checks/shared-agent-access.ts).+ 'access_may_act_for_wildcard','extractor_facts_expired','loop_facts_drift','ontology_facts_fenced',diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex 70b157aab6..433f4d0bbb 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -22,7 +22,7 @@ import { moveSlugBindings, recordRenameAlias } from '../page-state/rename-alias.import { segmentedRevertRefusal } from '../page-state/versions.ts';import { sanitizeText } from '../batch-rows.ts';import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion } from '../search/safe-chunks.ts';-import { privatePagesFilterFragment, privateSnapshotFilterFragment, privatePagesFilterForCaller, privacyForCaller, readersAllowedSql, callerIdentity } from '../search/private-visibility.ts';+import { privatePagesFilterFragment, privateSnapshotFilterFragment, privatePagesFilterForCaller, privacyForCaller, callerReadersAllowedSql } from '../search/private-visibility.ts';import { quarantineFilterFragment } from '../quarantine.ts';import { rederiveHiddenSql } from '../eligibility/sql.ts';import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, isMissingSchemaObject, warnOncePerProcess } from '../utils.ts';@@ -1011,7 +1011,7 @@ export async function getVersions<B extends boolean = true>(opts?: GetVersionsOpts<B>,): Promise<PageVersionRows<B>> {const privacy = opts?.excludePrivate- ? trustedSql(`AND ${privatePagesFilterForCaller('p')} AND ${readersAllowedSql('pv', callerIdentity(), 'snapshot')} AND ${privacyForCaller('p.source_id', privateSnapshotFilterFragment('pv'))}`) : sqlFragment``;+ ? trustedSql(`AND ${privatePagesFilterForCaller('p')} AND ${callerReadersAllowedSql('pv', 'snapshot')} AND ${privacyForCaller('p.source_id', privateSnapshotFilterFragment('pv'))}`) : sqlFragment``;const scope = opts?.sourceIds && opts.sourceIds.length > 0? sqlFragment`AND p.source_id = ANY(${opts.sourceIds}::text[])`: opts?.sourceId ? sqlFragment`AND p.source_id = ${opts.sourceId}` : sqlFragment``;diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 65ede92aa1..e4f319ce11 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -36,6 +36,11 @@ export const ERROR_CATALOGUE = {access_member_invalid: { code: 'access_member_invalid', docs: 'docs/guides/write-refusals.md#access_member_invalid' },access_member_id_retired: { code: 'access_member_id_retired', docs: 'docs/guides/write-refusals.md#access_member_id_retired' },access_member_disabled: { code: 'access_member_disabled', docs: 'docs/guides/write-refusals.md#access_member_disabled' },+ // GBRA-231 shared agents: the audience a harness asserts (X-Gbrain-On-Behalf-Of, _meta.on_behalf_of).+ on_behalf_of_invalid_audience: { code: 'on_behalf_of_invalid_audience', docs: 'docs/guides/write-refusals.md#on_behalf_of_invalid_audience' },+ 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' },// GBRA-218 (A2) folder rules: invalid rules and policy files, pending narrowing.access_rule_invalid: { code: 'access_rule_invalid', docs: 'docs/guides/write-refusals.md#access_rule_invalid' },access_policy_invalid: { code: 'access_policy_invalid', docs: 'docs/guides/write-refusals.md#access_policy_invalid' },diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 827db95364..f4d8b1d699 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -65,6 +65,10 @@ export const CODES = {absent_from_worktree: { class: 'caller', retryable: false, reasons: ['skip_worktree', 'deleted_locally'], summary: "Sync held one file that is committed at HEAD but missing from the working tree (a sparse checkout or a skip-worktree bit, or a local deletion that is not committed); the rest of the source synced.", why: "Sync imports from the working tree, so it cannot import a file that is not on disk, and treating it as deleted would drop a committed file silently. Whether the file comes back or its deletion is committed is the user's choice; classic sync re-screens the hold on every run.", docs: 'docs/guides/write-refusals.md#absent_from_worktree', suggestion: 'Restore the file (git restore -- <path>, or widen the sparse checkout) and the next sync imports it; or commit the deletion with gbrain git commit-push -m <msg> -- <path> and the next sync clears the hold.' },access_command_failed: { class: 'caller', summary: "Google connect credential error: access command failed.", docs: 'docs/guides/google-connect.md#troubleshooting' },access_member_disabled: { class: 'host_only', actor: 'user', reasons: ['disabled', 'removed', 'missing', 'malformed'], summary: "The credential (access token, OAuth client or stdio binding) is bound to a member who is disabled, removed or missing, so it was refused at verification and nothing was read.", why: 'A credential bound to a member reads as that member. While the member cannot read, the credential is refused rather than silently treated as unbound.', docs: 'docs/guides/write-refusals.md#access_member_disabled', suggestion: 'Ask the brain operator to enable the member (gbrain access member enable <id>) or rebind the credential (gbrain auth rescope --token <name>|--client <id> --member <id>|none).' },+ on_behalf_of_invalid_audience: { class: 'caller', summary: "A shared agent's request named its audience (the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of) in a form gbrain does not accept: empty, more than 50 entries, an entry that is not a member id, group:<id> or guest, or a header and _meta that name different audiences. Nothing was read.", why: 'The audience decides whose notes the agent may read, so an audience gbrain cannot read exactly is refused instead of guessed.', docs: 'docs/guides/write-refusals.md#on_behalf_of_invalid_audience', suggestion: 'Fix the harness code that sets the audience: 1-50 entries, each a member id, group:<id> or guest, the same in the header and _meta when both are sent.' },+ on_behalf_of_unknown_member: { class: 'caller', summary: "A shared agent's audience names a member who is not enabled on this brain, or a group that does not exist, so nothing was read.", why: 'An unknown or disabled entry is refused rather than read as a guest, so a typo or a removed person never quietly changes what the agent reads.', docs: 'docs/guides/write-refusals.md#on_behalf_of_unknown_member', suggestion: 'Name enabled members and existing groups only (gbrain access member list --all, gbrain access group list on the brain host); a person who is not a member joins the audience as guest.' },+ on_behalf_of_not_permitted: { class: 'host_only', actor: 'user', summary: "A shared agent asserted an audience its credential's may_act_for does not list (for a stdio server, config mcp.stdio_may_act_for), so nothing was read.", why: 'A shared agent acts only for the people the brain operator approved for its credential; widening that list is the operator\'s decision, never the agent\'s.', docs: 'docs/guides/write-refusals.md#on_behalf_of_not_permitted', suggestion: 'The brain operator decides whether to approve the audience: gbrain auth rescope --token <name>|--client <id> --may-act-for <list> on the brain host. Until then, call without the audience.' },+ on_behalf_of_in_arguments: { class: 'caller', summary: 'A tool call carried on_behalf_of inside its arguments, where conversation text could set it, so it was refused and nothing was read.', why: 'Only harness code may name whose notes a shared agent reads: the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of, never tool arguments.', docs: 'docs/guides/write-refusals.md#on_behalf_of_in_arguments', suggestion: 'Remove on_behalf_of from the tool arguments. Harness code sends it as the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of; other stdio clients use a credential bound to one member or config mcp.stdio_member.' },access_policy_invalid: { class: 'host_only', actor: 'user', docs: 'docs/guides/write-refusals.md#access_policy_invalid', summary: "A source's folder-rule policy (the committed .gbrain/access.yml, or a file given to gbrain access rule import) does not validate, so it was not applied: the last applied rules stay in force and every prefix the bad file names reads as nobody (the whole source when its prefixes cannot be read).", why: 'A typo in an access file must never open a folder: an unreadable revision keeps the previous rules and hides what it touches until it is fixed.', suggestion: 'Show each problem with its line (gbrain access rule list --source <id>), fix the file, commit it with gbrain git commit-push and sync the source (gbrain sync --source <id> --no-pull).', fix: { argv: ['gbrain', 'access', 'rule', 'list', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the applied rules and each problem in the policy file with its line; changes nothing.' } },access_policy_pending: { class: 'retryable', docs: 'docs/guides/write-refusals.md#access_policy_pending', summary: "A narrowing change to a source's folder rules is still being applied to its pages, so the prefixes it touches read as nobody until it finishes; pages under other prefixes keep the last applied rules.", why: 'Pages under a newly restricted folder are restamped in batches; until the last batch and its re-check pass land, they read as nobody instead of under the old rules.', suggestion: 'Retry shortly. If it stays pending, the apply was interrupted: the brain host finishes it with gbrain access resume --source <id> (database store) or gbrain sync --source <id> --no-pull (git store).', fix: { argv: ['gbrain', 'access', 'rule', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the pending prefixes and the revision being applied; changes nothing.' } },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, a prefix moved), 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.' } },diff --git a/src/core/minions/submission-authority.ts b/src/core/minions/submission-authority.tsindex 6ac0edb00b..3de234bc28 100644--- a/src/core/minions/submission-authority.ts+++ b/src/core/minions/submission-authority.ts@@ -21,7 +21,11 @@ export interface RemoteAgentAuthority {version: 1;kind: 'remote_agent';principal: { kind: 'oauth_client'; id: string };- grant: { scopes: string[]; sourceId: string; sourceCreatedAt: string; allowedTools: string[]; allowedSlugPrefixes: string[] };+ /**+ * GBRA-231: `actingFor` is the audience a shared agent asserted when it submitted the job. Every tool call the job+ * makes reads as that audience, re-resolved against the client's live may_act_for, never as the client's own member.+ */+ grant: { scopes: string[]; sourceId: string; sourceCreatedAt: string; allowedTools: string[]; allowedSlugPrefixes: string[]; actingFor?: string[] };payloadHash: string;}export interface RemoteJobAuthority {@@ -78,6 +82,7 @@ export function parseSubmissionAuthority(value: unknown): SubmissionAuthority |typeof g.sourceId !== 'string' || !isValidSourceId(g.sourceId) || typeof g.sourceCreatedAt !== 'string' ||!Array.isArray(g.allowedTools) || !g.allowedTools.length || !g.allowedTools.every(v => typeof v === 'string' && v.length) ||!Array.isArray(g.allowedSlugPrefixes) || !g.allowedSlugPrefixes.every(v => typeof v === 'string') ||+ (g.actingFor !== undefined && (!Array.isArray(g.actingFor) || !g.actingFor.length || g.actingFor.length > 50 || !g.actingFor.every(v => typeof v === 'string' && v.length))) ||typeof a.payloadHash !== 'string' || !/^[a-f0-9]{64}$/.test(a.payloadHash)) return null;return structuredClone(a) as unknown as RemoteAgentAuthority;}@@ -252,10 +257,13 @@ export async function prepareRemoteAgent(ctx: OperationContext, data: Record<str'submit_agent needs an OAuth client holding the agent scope and bound to the one source named in source_id. Ask the brain host operator for such a client, or ask the user to run gbrain agent run on the brain host.');const [source] = await ctx.engine.executeRaw<Record<string, unknown>>('SELECT archived, created_at FROM sources WHERE id = $1', [data.source_id]);if (!source || source.archived !== false) deny('agent source must be active', `Source ${data.source_id} is archived or missing. Name an active source in source_id.`);+ const { currentCallerAccess } = await import('../search/private-visibility.ts');+ const actingFor = currentCallerAccess().audience;const authority: RemoteAgentAuthority = {version: 1, kind: 'remote_agent', principal: { kind: 'oauth_client', id: principal.id },grant: { scopes: [...ctx.auth!.scopes], sourceId: data.source_id, sourceCreatedAt: new Date(source.created_at as string).toISOString(),- allowedTools: [...data.allowed_tools as string[]], allowedSlugPrefixes: [...data.allowed_slug_prefixes as string[]] },+ allowedTools: [...data.allowed_tools as string[]], allowedSlugPrefixes: [...data.allowed_slug_prefixes as string[]],+ ...(actingFor?.length ? { actingFor: [...actingFor] } : {}) },payloadHash: authorityDigest(data),};if (!parseSubmissionAuthority(authority)) deny('invalid agent grant', 'Send allowed_tools as a non-empty list of tool names and allowed_slug_prefixes as a list of strings.');diff --git a/src/core/minions/tools/brain-allowlist.ts b/src/core/minions/tools/brain-allowlist.tsindex a5e6e5393f..d9e9a3d002 100644--- a/src/core/minions/tools/brain-allowlist.ts+++ b/src/core/minions/tools/brain-allowlist.ts@@ -36,6 +36,8 @@ import { BRAIN_TOOL_ALLOWLIST } from './brain-tool-allowlist.ts';import { stagePutPage } from './staged-put-page.ts';import { withCallerAccess } from '../../search/private-visibility.ts';import { remoteCallerAccess } from '../../access/caller.ts';+import type { AudiencePrincipal } from '../../access/audience.ts';+import { currentSubmissionAuthority } from '../submission-authority.ts';// The allow-list itself lives in a handler-free module so the MCP surface// tiers (src/mcp/surface.ts) can read it without this module's operations import.@@ -311,8 +313,11 @@ function brainTool(op: Operation, opts: BuildBrainToolsOpts): ToolDef {: op.handler(opCtx, params);// GBRA-218: a remote-owned job reads as its client's member, looked up live on every call (a disabled member or// removed binding takes effect at the next tool call); never a GBRA-156 private-pages grant.+ // GBRA-231: a job a shared agent submitted for an audience reads as that audience, re-checked the same way.+ const submitted = currentSubmissionAuthority();+ const actingFor = submitted?.kind === 'remote_agent' ? submitted.grant.actingFor as AudiencePrincipal[] | undefined : undefined;const output = opCtx.auth- ? await withCallerAccess(await remoteCallerAccess(ctx.engine, opCtx.auth, []), run)+ ? await withCallerAccess(await remoteCallerAccess(ctx.engine, opCtx.auth, [], undefined, actingFor), run): await run();const rejection = op.name === 'put_page' ? putPageRejection(output) : null;if (rejection) throw new Error(rejection);diff --git a/src/core/ops/sources.ts b/src/core/ops/sources.tsindex b66de52843..3e6f2c9b79 100644--- a/src/core/ops/sources.ts+++ b/src/core/ops/sources.ts@@ -48,7 +48,10 @@ const whoami: Operation = {const entries = configReadiness(ctx.config, { transport }).entries;return transport === 'http' ? readinessHttpView(entries) : entries;};- const { accessView, credentialAccessView, stdioAccessView } = await import('../access/caller.ts');+ const { accessView, appliedAccessSummary, credentialAccessView, stdioAccessView } = await import('../access/caller.ts');+ // GBRA-231: the view this call is answered under (the shared-agent audience when the harness asserted one), so a+ // model can check it when its harness does not forward _meta.access.+ const withApplied = async <T extends object>(view: T) => ({ ...view, applied: await appliedAccessSummary(ctx.engine, ctx.auth, [ctx.sourceId, ...(ctx.localFederatedSourceIds ?? [])]) });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')@@ -67,7 +70,7 @@ const whoami: Operation = {if (verified.remote) scopes = verified.grant.scopes;} catch { /* no registration: no scopes */ }const session = ctx.stdioSurface;- return { transport: 'stdio', scopes, ...(session ? { surface: session.surface, surface_source: session.source } : {}), access: await stdioAccessView(ctx.engine), readiness: readiness('stdio') };+ return { transport: 'stdio', scopes, ...(session ? { surface: session.surface, surface_source: session.source } : {}), access: await withApplied(await stdioAccessView(ctx.engine)), readiness: readiness('stdio') };}if (!ctx.auth) {throw opError(@@ -86,7 +89,7 @@ const whoami: Operation = {client_id: ctx.auth.clientId,client_name: ctx.auth.clientName ?? ctx.auth.clientId,...await resolveAuthCapabilities(ctx.auth, ctx.engine, ctx.config, { surfaceCeiling: ctx.surfaceCeiling }),- access: await credentialAccessView(ctx.engine, ctx.auth),+ access: await withApplied(await credentialAccessView(ctx.engine, ctx.auth)),};}return {@@ -94,7 +97,7 @@ const whoami: Operation = {token_name: ctx.auth.clientName ?? ctx.auth.clientId,scopes: ctx.auth.scopes,expires_at: null,- access: await credentialAccessView(ctx.engine, ctx.auth),+ access: await withApplied(await credentialAccessView(ctx.engine, ctx.auth)),grant_diagnosis: await resolveGrantDiagnosis(ctx.auth, ctx.engine, ctx.config, { surfaceCeiling: ctx.surfaceCeiling }),readiness: readiness('http'),};diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.tsindex fb76323cb1..6099b7a556 100644--- a/src/core/persistence/authority.ts+++ b/src/core/persistence/authority.ts@@ -10,6 +10,7 @@ import { authSourcesFromGrant, grantFromTokenRow } from '../grants/model.ts';import { readLocalWriter, currentVerifiedLocalWriter, takeRegisteredWriterRow, verifyLocalWriter, type LocalGrant } from './identity.ts';import type { Principal, SqlEngine, WriteAuthority, WriteRequest } from './model.ts';import { authorizePageVisibility, excludesPrivateWrites } from './page-visibility.ts';+import { currentCallerAccess } from '../search/private-visibility.ts';import { pipelined, transactionMemo } from '../page-state/transactions.ts';function deny(message: string): never { throw new OperationError('permission_denied', message, 'Inspect the current writer registration and source/operation grants.'); }@@ -57,9 +58,13 @@ export async function submissionAuthority(ctx: OperationContext, operation: striif (!localGrant.sourceIds.includes('*') && !localGrant.sourceIds.includes(sourceId)) deny('The local grant excludes this source.');}const delegatedJobId = ctx.auth && ctx.viaSubagent ? jobNamespaceKey(ctx.subagentId) : undefined;+ const audience = ctx.remote !== false ? currentCallerAccess().audience : null;+ const actingFor = audience?.length ? [...audience] : undefined;const a: WriteAuthority = {version: 1, principal, remote: ctx.remote !== false, sourceId, sourceIncarnation,- excludePrivate: await excludesPrivateWrites(ctx.engine, ctx.remote !== false),+ // GBRA-231: a channel audience (anything but one member) never relaxes privacy, so its ceiling hides private pages.+ excludePrivate: (actingFor !== undefined && currentCallerAccess().hidePrivate) || await excludesPrivateWrites(ctx.engine, ctx.remote !== false),+ ...(actingFor ? { actingFor } : {}),autoLinkTrusted: ctx.remote === false || ctx.viaSubagent === true && !ctx.auth && !!ctx.allowedSlugPrefixes?.length,takesHolders: ctx.remote === false ? null : [...(ctx.takesHoldersAllowList ?? ['world'])],scopes: [...(ctx.auth?.scopes ?? localGrant?.scopes ?? [])],diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex dc1a890fcd..5b8ae83526 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -9,6 +9,11 @@ export interface WriteAuthority {remote: boolean;/** Original page-visibility ceiling; current policy can only narrow it. */excludePrivate?: boolean;+ /**+ * GBRA-231: the audience a shared agent asserted for the write (normalized member:<id>, group:<g>, guest). Preparation+ * and publication re-resolve it against the principal's live may_act_for and members, never the principal's own member.+ */+ actingFor?: string[];databaseOnlyReason?: 'subagent_sandbox' | 'disabled_by_config' | 'no_repo_configured' | 'connector_database' | 'unbound_source' | 'overwrite_restore' | 'detached';autoLinkTrusted?: boolean;restrictedNamespace?: boolean;diff --git a/src/core/persistence/page-visibility.ts b/src/core/persistence/page-visibility.tsindex e5d4d25137..1657e7253d 100644--- a/src/core/persistence/page-visibility.ts+++ b/src/core/persistence/page-visibility.ts@@ -1,7 +1,8 @@import { opError } from '../ops/contract.ts';-import { callerAccessAllowedSql, callerIdentity, readPolicyFragment, readRemotePolicyNow, withCallerAccess } from '../search/private-visibility.ts';+import { callerAccessAllowedSql, callerIdentities, currentCallerAccess, readPolicyFragment, readRemotePolicyNow, withCallerAccess } from '../search/private-visibility.ts';import { parseMarkdown } from '../markdown.ts';-import { folderAccessFor, memberIdentityFor } from '../access/caller.ts';+import { folderAccessForAll, memberIdentityFor, resolveAudienceIdentities } from '../access/caller.ts';+import type { AudiencePrincipal } from '../access/audience.ts';import { hasReaders, normalizePrincipal, normalizeReaders, readersAllow, NOBODY } from '../access/principals.ts';import { catalogueError } from '../error-catalogue.ts';import type { SqlEngine, WriteAuthority } from './model.ts';@@ -23,14 +24,29 @@ export async function authorizePageVisibility(engine: SqlEngine, authority: Writconst policy = await readRemotePolicyNow(engine);const hidePrivate = (authority.excludePrivate ?? true) || !policy.privacyRelaxed;if (!hidePrivate && !policy.restricted) return;- const identity = policy.restricted ? await memberIdentityFor(engine, authority) : [];- const folder = policy.restricted ? await folderAccessFor(engine, identity) : { satisfiedRuleIds: [], folderCoverage: [] };- const fragment = withCallerAccess({ folderCoverage: folder.folderCoverage }, () => readPolicyFragment('pages', identity, hidePrivate, folder.satisfiedRuleIds));+ const identities = policy.restricted ? await writerIdentities(engine, authority) : [[]];+ const folder = policy.restricted ? await folderAccessForAll(engine, identities) : { satisfiedRuleIds: [], folderCoverage: [] };+ const fragment = withCallerAccess({ folderCoverage: folder.folderCoverage }, () => readPolicyFragment('pages', { all: identities }, hidePrivate, folder.satisfiedRuleIds));const rows = await engine.executeRaw(`SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2AND NOT (${fragment}) LIMIT 1`, [authority.sourceId, slug]);if (rows.length) throw pageNotVisibleError();}+/**+ * The identities a stored write is checked under, re-resolved live: the principal's member, or (GBRA-231) every entry+ * of the audience it was accepted for, bounded by the principal's live may_act_for. An audience no longer permitted+ * or naming a disabled member resolves to the guest identity, which reads no restricted page (fail closed).+ */+async function writerIdentities(engine: SqlEngine, authority: WriteAuthority): Promise<string[][]> {+ if (!authority.actingFor?.length) return [await memberIdentityFor(engine, authority)];+ try {+ return await resolveAudienceIdentities(engine, { principal: authority.principal, transport: authority.principal.kind === 'local_stdio' ? 'stdio' : 'http' },+ authority.actingFor as AudiencePrincipal[]);+ } catch {+ return [[]];+ }+}+/*** GBRA-218: a remote write that touches an existing page outside the durable write path (graph edges, raw data)* must be able to read it under the member-access part; privacy keeps the rule each operation already had.@@ -51,7 +67,8 @@ export async function remoteTargetHidden(engine: SqlEngine, remote: boolean | un* YAML form) and keeps the page readable by the writer's `identity`. Checked at submission with the request's* identity and again at preparation with the identity re-resolved from the stored principal.*/-export function assertRemoteReadersValid(frontmatter: unknown, identity: readonly string[]): void {+export function assertRemoteReadersValid(frontmatter: unknown, identity: readonly string[] | readonly (readonly string[])[], audience?: readonly string[] | null): void {+ const identities = identity.length && typeof identity[0] !== 'string' ? identity as readonly (readonly string[])[] : [identity as readonly string[]];if (!hasReaders(frontmatter)) return;const value = (frontmatter as Record<string, unknown>).readable_by;if (normalizeReaders(frontmatter)?.[0] === NOBODY) {@@ -64,16 +81,21 @@ export function assertRemoteReadersValid(frontmatter: unknown, identity: readonlthrow catalogueError('readable_by_invalid', `readable_by is invalid: ${what}.`,`Nothing was written. Member and group ids are lower-case letters, digits, '.', '_' and '-' (1-64 characters); write the field as ${example} and submit again with a new request_id.`);}- if (!readersAllow(frontmatter, identity)) {+ if (!identities.every(id => readersAllow(frontmatter, id))) {+ if (audience?.length) {+ throw catalogueError('readable_by_invalid', 'readable_by would leave this page unreadable by the audience this connection acts for.',+ `Nothing was written. Every audience entry (${audience.join(', ')}) must stay a reader, and a guest can read no page that names readers; write the page without readable_by changes, or ask the user to change the readers on the brain host.`);+ }+ const one = identities[0] ?? [];throw catalogueError('readable_by_invalid', 'readable_by would leave this page unreadable by this connection.',- `Nothing was written. Keep this connection's member${identity.length ? ` (${identity.join(', ')})` : ' (this connection is bound to none)'} or one of its groups in readable_by, or ask the user to change the readers on the brain host.`);+ `Nothing was written. Keep this connection's member${one.length ? ` (${one.join(', ')})` : ' (this connection is bound to none)'} or one of its groups in readable_by, or ask the user to change the readers on the brain host.`);}}/** A remote put_page's readable_by, checked with the request's identity before anything is admitted (preparation checks it again). */export function assertSubmittedReaders(remote: boolean | undefined, slug: unknown, content: unknown): void {if (remote === false || typeof content !== 'string' || !content.includes('readable_by')) return;- assertRemoteReadersValid(parseMarkdown(content, typeof slug === 'string' ? slug : 'page').frontmatter, callerIdentity());+ assertRemoteReadersValid(parseMarkdown(content, typeof slug === 'string' ? slug : 'page').frontmatter, callerIdentities(), currentCallerAccess().audience);}/**@@ -87,7 +109,7 @@ export async function remoteReadersChecked<T extends { parsedPage: { frontmatterthrow catalogueError('readable_by_invalid', 'This write removes readable_by from a page that names readers.','Nothing was written. A remote write keeps the readable_by line: read the page with get_page include_content:true and keep its frontmatter, or ask the user to widen the page on the brain host.');}- assertRemoteReadersValid(after, await memberIdentityFor(engine, authority));+ assertRemoteReadersValid(after, await writerIdentities(engine, authority), authority.actingFor);return prepared;}diff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex da00404b1e..5020912219 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -1310,6 +1310,7 @@ export function knobsHash(if (ctx?.excludePrivate === true) {const access = currentCallerAccess();if (access.identity.length) parts.push(`xid=${createHash('sha256').update(access.identity.join(',')).digest('hex').slice(0, 16)}`);+ if (access.audienceIdentities.length) parts.push(`xau=${createHash('sha256').update(JSON.stringify(access.audienceIdentities)).digest('hex').slice(0, 16)}`);if (!access.hidePrivate) parts.push('xhp=0');}const h = createHash('sha256');diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex 23157aa50b..4bd014d1d9 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -23,7 +23,7 @@import { AsyncLocalStorage } from 'node:async_hooks';import type { BrainEngine } from '../engine.ts';import { isValidSourceId } from '../source-id.ts';-import { hasReaders, readersAllow, validIdentity } from '../access/principals.ts';+import { hasReaders, normalizePrincipal, readersAllow, validIdentity } from '../access/principals.ts';import { validPrefix, validQualifiedRuleId } from '../access/folder-rules.ts';export const REMOTE_PRIVATE_PAGES_KEY = 'search.remote_private_pages';@@ -70,8 +70,18 @@ export function privacyPartSql(pageAlias: string): string {* embedded as literals; anything else empties it (fail closed).*/export function accessAllowedSql(pageAlias: string, identity: readonly string[], satisfied: readonly string[] = satisfiedFor(identity)): string {+ return accessAllowedForAllSql(pageAlias, [identity], satisfied);+}++/**+ * GBRA-231 (shared agents): accessAllowedSql for an audience. A page passes only when every identity in+ * `identities` meets its readers (one conjunct each; a guest's empty identity meets no readers), and its folder rules+ * are all in `satisfied` (for an audience, the intersection of every entry's satisfied set).+ */+export function accessAllowedForAllSql(pageAlias: string, identities: readonly (readonly string[])[], satisfied: readonly string[]): string {if (!currentCallerAccess().restricted) return `(${pageAlias}.page_readers IS NULL AND ${pageAlias}.folder_rule_ids IS NULL)`;- return `(${readersAllowedSql(pageAlias, identity)} AND ${folderRulesAllowedSql(pageAlias, satisfied)} AND ${originAllowedSql(pageAlias)})`;+ const readers = (identities.length ? identities : [[]]).map(identity => readersAllowedSql(pageAlias, identity)).join(' AND ');+ return `(${readers} AND ${folderRulesAllowedSql(pageAlias, satisfied)} AND ${originAllowedSql(pageAlias)})`;}/**@@ -193,6 +203,14 @@ export function privatePagesFilterFragmentFast(pageAlias: string): string {*/export interface CallerAccess {identity: readonly string[];+ /**+ * GBRA-231 (shared agents): the normalized audience a request asserted (member:<id>, group:<g>, guest), or null.+ * Reported in _meta.access and whoami, carried by queued writes and agent jobs. With one entry, `identity` is that+ * entry's identity; with more, `identity` is empty (a site that reads it alone over-hides) and+ * `audienceIdentities` holds one identity per entry, every one of which must meet a page's readers.+ */+ audience: readonly string[] | null;+ audienceIdentities: readonly (readonly string[])[];/** GBRA-218 (A2): the source-qualified folder-rule ids (`<source>:<rule>`) the identity satisfies, from the applied rulebook. */satisfiedRuleIds: readonly string[];/** GBRA-218 (A2): prefixes that read as nobody (a narrowing being stamped, an invalid policy file); prefix '' is the whole source. */@@ -207,7 +225,7 @@ const callerAccessStore = new AsyncLocalStorage<CallerAccess>();/** The current read's caller-access record (see CallerAccess). */export function currentCallerAccess(): CallerAccess {- return callerAccessStore.getStore() ?? { identity: [], satisfiedRuleIds: [], folderCoverage: [], privateReadableSources: [], hidePrivate: !processPrivacyRelaxed(), applyRemoteReadPolicy: false, restricted: true };+ return callerAccessStore.getStore() ?? { identity: [], audience: null, audienceIdentities: [], satisfiedRuleIds: [], folderCoverage: [], privateReadableSources: [], hidePrivate: !processPrivacyRelaxed(), applyRemoteReadPolicy: false, restricted: true };}/** Runs `fn` under `access` merged over the current record; an invalid identity or source id empties that set (fail closed). */@@ -216,9 +234,16 @@ export function withCallerAccess<T>(access: Partial<CallerAccess>, fn: () => T):const identity = access.identity ?? base.identity;const sources = access.privateReadableSources ?? base.privateReadableSources;const validIds = identity.length > 0 && validIdentity(identity);- const satisfied = validIds ? access.satisfiedRuleIds ?? (access.identity ? [] : base.satisfiedRuleIds) : [];+ const fresh = access.identity !== undefined || access.audienceIdentities !== undefined;+ const audienceIdentities = (access.audienceIdentities ?? (fresh ? [] : base.audienceIdentities))+ .map(id => id.length && validIdentity(id) ? Object.freeze([...new Set(id)].sort()) : Object.freeze([] as string[]));+ const audience = access.audience !== undefined ? access.audience : fresh ? null : base.audience;+ const satisfiedOk = validIds || audienceIdentities.some(id => id.length > 0);+ const satisfied = satisfiedOk ? access.satisfiedRuleIds ?? (fresh ? [] : base.satisfiedRuleIds) : [];return callerAccessStore.run(Object.freeze({- identity: validIds ? Object.freeze([...new Set(identity)].sort()) : Object.freeze([]),+ identity: validIds && audienceIdentities.length <= 1 ? Object.freeze([...new Set(identity)].sort()) : Object.freeze([]),+ audience: audience && audience.every(validAudienceEntry) ? Object.freeze([...audience]) : audience ? Object.freeze([GUEST_ENTRY]) : null,+ audienceIdentities: Object.freeze(audienceIdentities.length > 1 ? audienceIdentities : []),satisfiedRuleIds: satisfied.length && satisfied.every(validQualifiedRuleId) ? Object.freeze([...new Set(satisfied)].sort()) : Object.freeze([]),folderCoverage: Object.freeze([...(access.folderCoverage ?? base.folderCoverage)].map(c => Object.freeze({ source_id: c.source_id, prefix: c.prefix }))),privateReadableSources: sources.length && sources.every(isValidSourceId) ? Object.freeze([...new Set(sources)]) : Object.freeze([]),@@ -243,11 +268,38 @@ export function privateReadableSources(): readonly string[] {return currentCallerAccess().privateReadableSources;}-/** The current caller's member identity; empty outside a bound remote read or a local --as. */+/** The current caller's member identity; empty outside a bound remote read or a local --as, and for an audience of several entries (see callerIdentities). */export function callerIdentity(): readonly string[] {return currentCallerAccess().identity;}+/** GBRA-231: every identity a page's readers must meet for the current caller: one per audience entry, else the caller's own. */+export function callerIdentities(): readonly (readonly string[])[] {+ const access = currentCallerAccess();+ return access.audienceIdentities.length ? access.audienceIdentities : [access.identity];+}++/** GBRA-231: readersAllow for the current caller (every audience entry must be a reader). */+export function callerReadersAllow(frontmatter: unknown): boolean {+ return callerIdentities().every(identity => readersAllow(frontmatter, identity));+}++/** GBRA-231: readersAllowedSql for the current caller, one conjunct per audience entry. */+export function callerReadersAllowedSql(alias: string, row: 'page' | 'snapshot' = 'page'): string {+ return callerIdentities().map(identity => readersAllowedSql(alias, identity, row)).join(' AND ');+}++const GUEST_ENTRY = 'guest';+function validAudienceEntry(entry: string): boolean {+ return entry === GUEST_ENTRY || normalizePrincipal(entry) === entry;+}++function callerAccessSql(pageAlias: string): string {+ const access = currentCallerAccess();+ return access.audienceIdentities.length ? accessAllowedForAllSql(pageAlias, access.audienceIdentities, access.satisfiedRuleIds)+ : accessAllowedSql(pageAlias, access.identity);+}+/*** `visiblePredicate` (a privacy-only predicate), widened to rows whose source* (`sourceIdSql`, a code-provided column reference) is in the current@@ -276,12 +328,12 @@ function callerPrivacySql(pageAlias: string, privacyPredicate: string): string {/** privatePagesFilterFragment for a remote read: the caller's member access, then the privacy part with its grant and hatch. Read sites only; derived-visibility decisions keep the plain fragment. */export function privatePagesFilterForCaller(pageAlias: string): string {- return `(${accessAllowedSql(pageAlias, callerIdentity())} AND ${callerPrivacySql(pageAlias, privacyPartSql(pageAlias))})`;+ return `(${callerAccessSql(pageAlias)} AND ${callerPrivacySql(pageAlias, privacyPartSql(pageAlias))})`;}/** The mandatory member-access part alone (readers and lineage) for the current caller; privacy is not tested. */export function callerAccessAllowedSql(pageAlias: string): string {- return accessAllowedSql(pageAlias, callerIdentity());+ return callerAccessSql(pageAlias);}/**@@ -290,13 +342,14 @@ export function callerAccessAllowedSql(pageAlias: string): string {* part, then the privacy part unless `hidePrivate` is false. With an empty* identity and `hidePrivate` it equals privatePagesFilterFragment.*/-export function readPolicyFragment(pageAlias: string, identity: readonly string[], hidePrivate: boolean, satisfied?: readonly string[]): string {- return `(${accessAllowedSql(pageAlias, identity, satisfied)} AND ${hidePrivate ? privacyPartSql(pageAlias) : 'TRUE'})`;+export function readPolicyFragment(pageAlias: string, identity: readonly string[] | { all: readonly (readonly string[])[] }, hidePrivate: boolean, satisfied?: readonly string[]): string {+ const access = 'all' in identity ? accessAllowedForAllSql(pageAlias, identity.all, satisfied ?? []) : accessAllowedSql(pageAlias, identity, satisfied);+ return `(${access} AND ${hidePrivate ? privacyPartSql(pageAlias) : 'TRUE'})`;}/** privatePagesFilterFragmentFast for a remote read. */export function privatePagesFilterFastForCaller(pageAlias: string): string {- return `(${accessAllowedSql(pageAlias, callerIdentity())} AND ${callerPrivacySql(pageAlias, privacyPartFastSql(pageAlias))})`;+ return `(${callerAccessSql(pageAlias)} AND ${callerPrivacySql(pageAlias, privacyPartFastSql(pageAlias))})`;}/** The fast form of privacyPartSql (see privatePagesFilterFragmentFast). */@@ -315,7 +368,7 @@ function privacyPartFastSql(pageAlias: string): string {*/export function isPrivatePageForCaller(page: { type?: string | null; frontmatter?: unknown; source_id?: string | null }): boolean {const access = currentCallerAccess();- if (!readersAllow(page.frontmatter, access.identity)) return true;+ if (!callerReadersAllow(page.frontmatter)) return true;if (!access.hidePrivate || !isPrivacyPrivatePage(page)) return false;return !(typeof page.source_id === 'string' && access.privateReadableSources.includes(page.source_id));}diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 4d48d68ce4..d4eceaa4f3 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -15,7 +15,8 @@ import type { OperationMeta } from '../core/ops/contract.ts';import { loadConfig } from '../core/config.ts';import { withRequestConfigSnapshot, withoutRequestConfigSnapshot } from '../core/config-snapshot.ts';import { withCallerAccess } from '../core/search/private-visibility.ts';-import { remoteCallerAccess } from '../core/access/caller.ts';+import { appliedAccessSummary, remoteCallerAccess } from '../core/access/caller.ts';+import { audienceInArguments, audienceInArgumentsError, logAudienceAssertion, parseAudience, type AudienceAuditEvent, type AudienceChannels, type AudiencePrincipal } from '../core/access/audience.ts';import { resolveBrainId } from '../core/brain-resolver.ts';import { getCliOptions } from '../core/cli-options.ts';import { VERB_NAMES, MEMORY_VERBS_VERSION } from '../core/verbs.ts';@@ -167,6 +168,11 @@ export interface ToolResult {}export interface DispatchOpts {+ /**+ * GBRA-231: the shared-agent audience channels the transport read from the request (the X-Gbrain-On-Behalf-Of+ * header, request-level `_meta`), set by harness code. Never populated from tool arguments, which are refused.+ */+ onBehalfOf?: AudienceChannels;/** #6696 (A5): set by the trusted transport for the user's own agent calls; never from wire params. */admissionOrigin?: OperationContext['admissionOrigin'];/** Configuration selected by the resident transport, never populated from wire params. */@@ -900,9 +906,29 @@ export async function dispatchToolCall(const privateSources = readOnly && opts.remote !== false && !WORLD_ONLY_PACK_OPS.has(name) ? opts.auth?.privatePages?.sources : undefined;const resolved = opts.metaHook && (opts.hotMemoryOff === true || hotMemoryOffIn(params)) ? { ...opts, metaHook: undefined } : opts;// GBRA-218: a remote call also carries its credential's member identity, which every caller-aware read checks page readers against.+ // GBRA-231: or the audience a shared agent's harness asserts, resolved (and refused) on every call before any work.const run = async () => {- const access = opts.remote === false ? { privateReadableSources: [] } : await remoteCallerAccess(engine, opts.auth, privateSources, opts.transport);- return withCallerAccess(access, () => withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, params, resolved)));+ if (opts.remote === false) return withCallerAccess({ privateReadableSources: [] }, () => withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, params, resolved)));+ let audience: AudiencePrincipal[] | null = null;+ let access: Awaited<ReturnType<typeof remoteCallerAccess>>;+ const assertion = (outcome: AudienceAuditEvent['outcome']) => logAudienceAssertion({ outcome, op: name, audience: audience ?? [], transport: opts.transport ?? 'unknown',+ principal: opts.auth?.principal ? `${opts.auth.principal.kind}:${opts.auth.principal.id}` : opts.transport === 'stdio' ? 'local_stdio' : 'unknown' });+ try {+ if (audienceInArguments(params)) throw audienceInArgumentsError();+ audience = parseAudience(opts.onBehalfOf);+ access = await remoteCallerAccess(engine, opts.auth, privateSources, opts.transport, audience);+ } catch (e) {+ if (!(e instanceof OperationError) || !String(e.code).startsWith('on_behalf_of_')) throw e;+ assertion(e.code as AudienceAuditEvent['outcome']);+ return errorResult(e, opts, { op: name });+ }+ if (audience) assertion('accepted');+ return withCallerAccess(access, async () => {+ const out = await withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, params, resolved));+ // _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, opts.auth, [opts.sourceId, ...(opts.localFederatedSourceIds ?? [])]) }; } catch { /* the key is absent */ }+ return out;+ });};if (name === 'search' || name === 'query') return withSearchConnectionBudget(() => withRequestConfigSnapshot(engine, run));return readOnlydiff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.tsindex 0fcac6d125..28b7e5a3ae 100644--- a/src/mcp/http-transport.ts+++ b/src/mcp/http-transport.ts@@ -37,6 +37,7 @@ import { httpInstructionTools } from './initialize-context.ts';import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';import { operations, operationsByName, opAllowedForBoundClient } from '../core/operations.ts';import { scopeDeniedError } from '../core/ops/op-fix.ts';+import { ON_BEHALF_OF_HEADER } from '../core/access/audience.ts';import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';import type { AuthInfo } from '../core/operations.ts';import { VERSION } from '../version.ts';@@ -552,7 +553,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {transport: 'http', inboundFrameBytes: bodyCap,takesHoldersAllowList: auth.takesHoldersAllowList,sourceId: auth.sourceId,- ...(localFederated ? { localFederatedSourceIds: localFederated } : {}),+ ...(localFederated ? { localFederatedSourceIds: localFederated } : {}), onBehalfOf: { header: req.headers.get(ON_BEHALF_OF_HEADER) ?? undefined, requestMeta: params?._meta },// #1336: thread the token's federated_read grant so read ops scope// to the operator-granted sources via sourceScopeOpts.auth: auth.auth,diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 2446f2def4..789a722318 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -484,7 +484,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS// stdio stays remote/untrusted.transport: 'stdio', inboundFrameBytes: MCP_STDIO_MAX_MESSAGE_BYTES,takesHoldersAllowList: ['world'],- ...(sessionId ? { sessionId } : {}), ...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}),+ ...(sessionId ? { sessionId } : {}), ...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}), onBehalfOf: { requestMeta: request.params?._meta },sourceId: sourceScope.sourceId,...(sourceScope.localFederatedSourceIds? { localFederatedSourceIds: sourceScope.localFederatedSourceIds }diff --git a/test/access-binding.test.ts b/test/access-binding.test.tsindex 272a401eaa..998bbae383 100644--- a/test/access-binding.test.ts+++ b/test/access-binding.test.ts@@ -175,7 +175,8 @@ for (const kind of testBackends()) {const auth = await verify(tokens.alice!.token);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' });+ 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' } });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' });diff --git a/test/access-on-behalf-of.test.ts b/test/access-on-behalf-of.test.tsnew file mode 100644index 0000000000..d3bf5cfbf9--- /dev/null+++ b/test/access-on-behalf-of.test.ts@@ -0,0 +1,450 @@+/**+ * GBRA-231: shared agents read as the audience their harness names (plan v6 section 4).+ *+ * 1. Protects: a shared agent's call carrying an audience (the X-Gbrain-On-Behalf-Of header or request-level+ * _meta.on_behalf_of) reads only the pages every audience entry may read (page readers and folder rules), within+ * the agent's source grant; a guest reads no restricted page; the agent's own member binding never adds to it; a+ * channel audience never sees a visibility: private page, whatever the agent's grant or an operator hatch says. The+ * audience is re-read on every call, bounded by the credential's live may_act_for (stdio: mcp.stdio_may_act_for),+ * and refused before work when it sits in tool arguments, is malformed, names someone outside may_act_for or names+ * no enabled member. Queued writes and agent jobs keep the audience they were accepted for.+ * 2. Fails when: an audience reads a page one of its entries may not read (on any read path), the agent's own member+ * leaks into an audience view (a guest turn sees the bot's pages), a prompt-injected argument picks the audience,+ * a refusal carries page content, a channel sees a private page, a later call keeps an earlier audience, the+ * semantic cache key ignores the audience, or a stored write or job reads as the credential's member instead of+ * its audience.+ * 3. Existing coverage (member-read-access, access-writes) pins single-member credentials only.+ * 4. Real seams: legacy tokens minted by the token service, bound by the member CLI functions, verified by the+ * serve --http verifier and by the legacy bearer transport over a real socket, dispatched through MCP dispatch on+ * a repo-less brain (no git checkout; folder rules in the database store); embeddings stubbed.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { parseRescopeTokenArgs, rescopeLegacyToken } from '../src/core/grants/legacy-token.ts';+import { 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 { __resetPrivateVisibilityCacheForTests, withCallerAccess } from '../src/core/search/private-visibility.ts';+import { knobsHash, resolveSearchMode } from '../src/core/search/mode.ts';+import { remoteCallerAccess } from '../src/core/access/caller.ts';+import { addGroup, addMember, bindCredential, disableMember } from '../src/core/access/members.ts';+import { proposeRevision } from '../src/core/access/policy.ts';+import { readAudienceAssertions, STDIO_MAY_ACT_FOR_KEY, type AudiencePrincipal } from '../src/core/access/audience.ts';+import { submissionAuthority, authorizeStoredRequest } from '../src/core/persistence/authority.ts';+import { admitWrite } from '../src/core/persistence/journal.ts';+import { buildBrainTools } from '../src/core/minions/tools/brain-allowlist.ts';+import { parseSubmissionAuthority, prepareRemoteAgent, withSubmissionAuthority, type RemoteAgentAuthority } from '../src/core/minions/submission-authority.ts';+import type { AuthInfo, OperationContext } from '../src/core/ops/contract.ts';+import { sharedAgentAccessEntry } from '../src/commands/doctor/checks/shared-agent-access.ts';+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';++const DIMS = 1536;+function vectorFor(text: string): number[] {+ const v = new Array<number>(DIMS).fill(0);+ for (const w of text.toLowerCase().match(/[a-z]+/g) ?? []) {+ let h = 0;+ for (const ch of w) h = (h * 31 + ch.charCodeAt(0)) >>> 0;+ v[h % DIMS] += 1;+ }+ const n = Math.hypot(...v) || 1;+ return v.map(x => x / n);+}++const SRC = 'obo-team';+const PAGES = {+ alice: { slug: 'notes/alice-plan', fm: ['readable_by: [alice-example]'], canary: 'canaryoboalice' },+ bob: { slug: 'notes/bob-plan', fm: ['readable_by: [bob-example]'], canary: 'canaryobobob' },+ both: { slug: 'notes/both-plan', fm: ['readable_by: [alice-example, bob-example]'], canary: 'canaryoboboth' },+ team: { slug: 'notes/team-plan', fm: ['readable_by: [group:team-a]'], canary: 'canaryoboteam' },+ dan: { slug: 'notes/dan-plan', fm: ['readable_by: [dan-example]'], canary: 'canaryobodan' },+ folder: { slug: 'partners/alice-example/brief', fm: [] as string[], canary: 'canaryobofolder' },+ quiet: { slug: 'notes/quiet-plan', fm: ['visibility: private'], canary: 'canaryoboquiet' },+} as const;+type Key = keyof typeof PAGES;+const RESTRICTED: Key[] = ['alice', 'bob', 'both', 'team', 'dan', 'folder', 'quiet'];+const OPEN = { slug: 'notes/open-plan', canary: 'canaryoboopen' };++const page = (key: Key) => ['---', 'type: note', 'title: ' + key + ' plan', ...PAGES[key].fm, '---', '# ' + key + ' plan', '',+ 'Harbor ledger planning notes ' + PAGES[key].canary + ' for the roadmap.'].join('\n');++/** Read paths (label, op, args); a path given the slug may echo it in a not-found error, so it counts content only. */+function reads(key: Key): Array<[string, string, Record<string, unknown>]> {+ const slug = PAGES[key].slug;+ return [+ ['search hybrid', 'search', { query: 'harbor ledger planning notes', fields: 'full', limit: 30 }],+ ['search keyword', 'search', { query: 'planning notes', match: 'keyword', fields: 'full', limit: 30 }],+ ['query', 'query', { query: 'harbor ledger planning notes', expand: false, fields: 'full', limit: 30 }],+ ['get_page', 'get_page', { slug }],+ ['list_pages', 'list_pages', { slug_prefix: slug.slice(0, slug.indexOf('/') + 1) }],+ ['get_chunks', 'get_chunks', { slug }],+ ['get_versions', 'get_versions', { slug, include_body: true }],+ ['resolve_slugs', 'resolve_slugs', { partial: slug.slice(slug.lastIndexOf('/') + 1) }],+ ];+}+const ECHOES_SLUG = new Set(['get_page', 'get_chunks', 'get_versions']);+const CORE = ['search keyword', 'get_page', 'list_pages'];++type Channels = { header?: string; meta?: unknown };++for (const kind of testBackends()) {+ describe('shared agents on_behalf_of (' + kind + ', repo-less)', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const tokens: Record<string, { id: string; token: string }> = {};+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ const verify = async (who: string) => await provider().verifyAccessToken(tokens[who]!.token) as unknown as AuthInfo;++ async function call(who: string | null, op: string, params: Record<string, unknown>, ch: Channels = {}, extra: { sessionId?: string } = {}) {+ const auth = who ? await verify(who) : undefined;+ const out: ToolResult = await dispatchToolCall(engine, op, { ...params }, {+ remote: true, transport: who ? 'http' : 'stdio', auth, sourceId: auth?.sourceId ?? SRC, takesHoldersAllowList: ['world'],+ ...(extra.sessionId ? { sessionId: extra.sessionId } : {}),+ onBehalfOf: { header: ch.header, requestMeta: ch.meta === undefined ? undefined : { on_behalf_of: ch.meta } },+ });+ const text = out.content.map(c => c.text).join('\n');+ let json: Record<string, unknown> = {};+ try { json = JSON.parse(text); } catch { /* prose */ }+ return { isError: out.isError === true, text, json, meta: out._meta };+ }+ const seen = (text: string, key: Key, label: string) => text.includes(PAGES[key].canary) || (!ECHOES_SLUG.has(label) && text.includes(PAGES[key].slug));++ /** Restricted keys a caller (under its channels) sees on any read path, and the paths where each was seen. */+ async function visible(who: string | null, ch: Channels, keys: readonly Key[] = RESTRICTED): Promise<Record<string, string[]>> {+ const out: Record<string, string[]> = {};+ for (const key of keys) {+ for (const [label, op, params] of reads(key)) {+ const { text } = await call(who, op, params, ch);+ if (seen(text, key, label)) (out[key] ??= []).push(label);+ }+ }+ return out;+ }+ /** Exactly the allowed restricted keys are visible, each on the core paths. */+ async function expectView(who: string | null, ch: Channels, allowed: Key[]) {+ const got = await visible(who, ch);+ expect({ who, ch, keys: Object.keys(got).sort() }).toEqual({ who, ch, keys: [...allowed].sort() });+ for (const key of allowed) for (const label of CORE) expect({ key, label, seen: got[key]!.includes(label) }).toEqual({ key, label, seen: true });+ }++ beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(vectorFor) })) as never);+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }+ __resetPrivateVisibilityCacheForTests();+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);+ for (const id of ['alice-example', 'bob-example', 'dan-example', 'eve-example']) await addMember(engine, id);+ await addGroup(engine, 'team-a', ['bob-example']);+ await addGroup(engine, 'team-b');+ await disableMember(engine, 'eve-example');+ await proposeRevision(engine, SRC, [{ id: 'alice', prefix: 'partners/alice-example/', readable_by: ['member:alice-example'] }], { origin: 'cli', store: 'database' });+ await importFromContent(engine, OPEN.slug, '---\ntype: note\ntitle: Open plan\n---\n# Open plan\n\nHarbor ledger planning notes ' + OPEN.canary + '.', { sourceId: SRC });+ for (const key of Object.keys(PAGES) as Key[]) {+ await importFromContent(engine, PAGES[key].slug, page(key), { sourceId: SRC });+ await engine.createVersion(PAGES[key].slug, { sourceId: SRC });+ }+ const mint = async (name: string, binding: { member?: string; mayActFor?: string[] }, scopes = ['read']) => {+ 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);+ };+ 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']);+ await mint('narrow', { mayActFor: ['member:alice-example'] });+ await mint('wild', { mayActFor: ['*'] });+ await mint('granted', { mayActFor: ['member:alice-example', 'member:bob-example'] });+ await mint('plain', {});+ await rescopeLegacyToken(engine, parseRescopeTokenArgs(['granted', '--private-pages', 'granted-sources']));+ }, 240_000);++ afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await close?.();+ }, 60_000);++ test('fixture control: without an audience the bot reads no restricted page and the dan-bound bot reads only dan\'s', async () => {+ await expectView('bot', {}, []);+ await expectView('bot-dan', {}, ['dan']);+ }, 240_000);++ test('a two-member audience reads only the pages both members may read', async () => {+ await expectView('bot', { header: 'alice-example, bob-example' }, ['both']);+ await expectView('bot', { meta: ['bob-example', 'alice-example'] }, ['both']);+ }, 240_000);++ test('a one-member audience reads as that member: page readers and folder rules', async () => {+ await expectView('bot', { meta: ['alice-example'] }, ['alice', 'both', 'folder']);+ await expectView('bot', { header: 'bob-example' }, ['bob', 'both', 'team']);+ }, 240_000);++ test('a group audience counts as one principal and reads what the group may read', async () => {+ await expectView('bot', { header: 'group:team-a' }, ['team']);+ }, 240_000);++ test('a guest reads no restricted page, and the agent\'s own member never adds to an audience view', async () => {+ await expectView('bot', { header: 'guest' }, []);+ await expectView('bot-dan', { header: 'guest' }, []);+ await expectView('bot-dan', { meta: ['alice-example', 'guest'] }, []);+ await expectView('bot-dan', { header: 'alice-example' }, ['alice', 'both', 'folder']);+ }, 240_000);++ test('the audience is read on every call: switching it mid-session never keeps an earlier view', async () => {+ const sessionId = 'obo-session-' + randomUUID();+ const get = (ch: Channels) => call('bot', 'get_page', { slug: PAGES.alice.slug }, ch, { sessionId });+ expect((await get({ header: 'alice-example' })).text).toContain(PAGES.alice.canary);+ expect((await get({ header: 'bob-example' })).text).not.toContain(PAGES.alice.canary);+ expect((await get({})).text).not.toContain(PAGES.alice.canary);+ expect((await get({ meta: ['alice-example'] })).text).toContain(PAGES.alice.canary);+ }, 120_000);++ test('an audience inside tool arguments is refused before any read, even beside a valid header', async () => {+ const cases: Array<[Record<string, unknown>, Channels]> = [+ [{ slug: PAGES.alice.slug, on_behalf_of: ['alice-example'] }, {}],+ [{ slug: PAGES.alice.slug, _meta: { on_behalf_of: ['alice-example'] } }, {}],+ [{ slug: PAGES.alice.slug, on_behalf_of: 'alice-example' }, { header: 'alice-example' }],+ ];+ for (const [params, ch] of cases) {+ const out = await call('bot', 'get_page', params, ch);+ expect({ isError: out.isError, code: out.json.code }).toEqual({ isError: true, code: 'on_behalf_of_in_arguments' });+ expect(out.text).not.toContain(PAGES.alice.canary);+ expect(out.json.docs).toContain('write-refusals.md#on_behalf_of_in_arguments');+ }+ }, 60_000);++ test('a malformed, empty, oversized or conflicting audience is refused before any read', async () => {+ const cases: Channels[] = [+ { header: '' }, { header: ' , ' }, { header: 'alice-example,,bob-example' }, { header: 'Not Valid' }, { header: 'ext:crm:42' },+ { meta: [] }, { meta: 'alice-example' }, { meta: [7] }, { meta: Array.from({ length: 51 }, (_, i) => 'm' + i + '-example') },+ { header: 'alice-example', meta: ['bob-example'] }, { header: 'alice-example, guest', meta: ['alice-example'] },+ ];+ for (const ch of cases) {+ const out = await call('bot', 'get_page', { slug: PAGES.both.slug }, ch);+ expect({ ch, code: out.json.code }).toEqual({ ch, code: 'on_behalf_of_invalid_audience' });+ expect(out.text).not.toContain(PAGES.both.canary);+ }+ const same = await call('bot', 'get_page', { slug: PAGES.both.slug }, { header: 'bob-example, Alice-Example', meta: ['alice-example', 'member:bob-example'] });+ expect(same.text).toContain(PAGES.both.canary);+ }, 120_000);++ test('an entry outside may_act_for is refused with the operator\'s command, before membership is checked, and no content', async () => {+ const out = await call('narrow', 'get_page', { slug: PAGES.alice.slug }, { header: 'alice-example, bob-example' });+ expect(out.json.code).toBe('on_behalf_of_not_permitted');+ expect(out.json.message).toContain('token narrow');+ expect(out.json.message).toContain('member:bob-example');+ expect(out.text).not.toContain(PAGES.alice.canary);+ const fix = out.json.fix as Record<string, unknown>;+ expect({ next: fix.next, argv: fix.argv }).toEqual({ next: 'tell_user_to_run',+ argv: ['gbrain', 'auth', 'rescope', '--token', 'narrow', '--may-act-for', 'member:alice-example,member:bob-example'] });+ expect((await call('narrow', 'get_page', { slug: PAGES.alice.slug }, { header: 'ghost-example' })).json.code).toBe('on_behalf_of_not_permitted');+ expect((await call('plain', 'get_page', { slug: PAGES.alice.slug }, { meta: ['alice-example'] })).json.code).toBe('on_behalf_of_not_permitted');+ expect((await call('bot', 'get_page', { slug: PAGES.alice.slug }, { header: 'group:team-b' })).json.code).toBe('on_behalf_of_not_permitted');+ }, 60_000);++ test('may_act_for is read on every call: narrowing it refuses the next call', async () => {+ expect((await call('narrow', 'get_page', { slug: PAGES.alice.slug }, { header: 'alice-example' })).text).toContain(PAGES.alice.canary);+ await bindCredential(engine, { kind: 'token', id: tokens.narrow!.id }, { mayActFor: null });+ try {+ expect((await call('narrow', 'get_page', { slug: PAGES.alice.slug }, { header: 'alice-example' })).json.code).toBe('on_behalf_of_not_permitted');+ } finally {+ await bindCredential(engine, { kind: 'token', id: tokens.narrow!.id }, { mayActFor: ['member:alice-example'] });+ }+ }, 60_000);++ test('an unknown or disabled member, or an unknown group, is refused rather than read as a guest', async () => {+ for (const header of ['ghost-example', 'eve-example', 'group:no-such-group', 'alice-example, ghost-example']) {+ const out = await call('wild', 'get_page', { slug: PAGES.alice.slug }, { header });+ expect({ header, code: out.json.code }).toEqual({ header, code: 'on_behalf_of_unknown_member' });+ expect(out.text).not.toContain(PAGES.alice.canary);+ }+ expect((await call('wild', 'get_page', { slug: PAGES.alice.slug }, { header: 'alice-example' })).text).toContain(PAGES.alice.canary);+ }, 60_000);++ test('privacy relaxes only for a one-member audience: granted_sources and the hatch never open a private page to a channel', async () => {+ const quiet = (ch: Channels) => call('granted', 'get_page', { slug: PAGES.quiet.slug }, ch).then(o => o.text.includes(PAGES.quiet.canary));+ expect(await quiet({ header: 'alice-example' })).toBe(true);+ expect(await quiet({ header: 'alice-example, bob-example' })).toBe(false);+ expect(await quiet({})).toBe(true);+ await withEnv({ GBRAIN_REMOTE_PRIVATE_PAGES: '1' }, async () => {+ expect((await call('bot', 'get_page', { slug: PAGES.quiet.slug }, { header: 'alice-example' })).text).toContain(PAGES.quiet.canary);+ expect((await call('bot', 'get_page', { slug: PAGES.quiet.slug }, { header: 'alice-example, guest' })).text).not.toContain(PAGES.quiet.canary);+ expect((await call('bot', 'search', { query: 'planning notes', match: 'keyword', fields: 'full', limit: 30 }, { header: 'group:team-a' })).text).not.toContain(PAGES.quiet.canary);+ });+ }, 120_000);++ test('every response carries _meta.access, and whoami returns the same view as access.applied', async () => {+ const out = await call('bot', 'search', { query: 'planning notes', match: 'keyword', limit: 5 }, { header: 'alice-example, bob-example' });+ const access = out.meta?.access as Record<string, unknown>;+ expect(access).toMatchObject({ member: null, groups: [], audience: ['member:alice-example', 'member:bob-example'], relaxation: 'none' });+ expect((access.policy_rev as Record<string, number>)[SRC]).toBeGreaterThan(0);+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', ['obo-other-src']);+ await proposeRevision(engine, 'obo-other-src', [{ id: 'other', prefix: 'other/', readable_by: ['member:bob-example'] }], { origin: 'cli', store: 'database' });+ const scoped = (await call('bot', 'get_page', { slug: OPEN.slug }, { header: 'alice-example' })).meta?.access as Record<string, unknown>;+ expect(Object.keys(scoped.policy_rev as Record<string, number>)).toEqual([SRC]);+ const single = await call('granted', 'get_page', { slug: OPEN.slug }, { meta: ['bob-example'] });+ expect(single.meta?.access).toMatchObject({ member: 'bob-example', groups: ['team-a'], audience: ['member:bob-example'], relaxation: 'granted_sources' });+ const plain = await call('bot-dan', 'get_page', { slug: OPEN.slug });+ expect(plain.meta?.access).toMatchObject({ member: 'dan-example', audience: null });+ const who = await call('bot-dan', 'whoami', {}, { header: 'guest' });+ expect((who.json.access as Record<string, unknown>).applied).toMatchObject({ member: null, groups: [], audience: ['guest'] });+ expect((who.json.access as Record<string, unknown>).member).toBe('dan-example');+ }, 60_000);++ test('the semantic cache key differs for each audience, and from an unbound caller', () => {+ const knobs = resolveSearchMode({ mode: 'balanced' });+ const under = (access: Parameters<typeof withCallerAccess>[0]) => withCallerAccess(access, () => knobsHash(knobs, { excludePrivate: true }));+ const unbound = under({ identity: [] });+ const pair = under({ identity: [], audience: ['member:alice-example', 'member:bob-example'], audienceIdentities: [['member:alice-example'], ['member:bob-example']] });+ const other = under({ identity: [], audience: ['guest', 'member:alice-example'], audienceIdentities: [[], ['member:alice-example']] });+ expect(new Set([unbound, pair, other]).size).toBe(3);+ });++ test('a write under an audience is checked against the audience: an unreadable target is not_found, readers must keep every entry', async () => {+ const hidden = await call('bot-dan', 'add_tag', { slug: PAGES.dan.slug, tag: 'x-tag' }, { header: 'guest' });+ expect(hidden.json.code).toBe('page_not_found');+ const lockout = await call('bot-dan', 'put_page', { slug: 'notes/channel-new', content: '---\ntype: note\nreadable_by: [alice-example]\n---\n# New\n\nNew.' }, { header: 'alice-example, bob-example' });+ expect(lockout.json).toMatchObject({ code: 'readable_by_invalid', message: expect.stringContaining('the audience this connection acts for') });+ const [rows] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE slug = 'notes/channel-new'");+ expect(rows!.n).toBe(0);+ const own = await call('bot-dan', 'add_tag', { slug: PAGES.dan.slug, tag: 'x-tag' });+ expect(own.isError).toBe(false);+ }, 120_000);++ test('a stored write keeps its audience: publication re-resolves it, never the principal\'s own member, and a revoked may_act_for refuses it', async () => {+ const auth = await verify('bot-dan');+ const ctx = { engine, config: { engine: 'pglite' }, sourceId: SRC, auth, remote: true, dryRun: false, takesHoldersAllowList: ['world'],+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [SRC]);+ const authority = await withCallerAccess(await remoteCallerAccess(engine, auth, undefined, 'http', ['member:alice-example']),+ () => submissionAuthority(ctx, 'add_tag', SRC, source!.incarnation, PAGES.alice.slug));+ expect(authority.actingFor).toEqual(['member:alice-example']);+ const row = await admitWrite(engine, { principal: authority.principal, authority, operation: 'add_tag', sourceId: SRC,+ sourceIncarnation: source!.incarnation, slug: PAGES.alice.slug, requestId: randomUUID(), callerIntent: {}, intent: {} });+ await authorizeStoredRequest(engine, row);+ await bindCredential(engine, { kind: 'token', id: tokens['bot-dan']!.id }, { mayActFor: ['guest'] });+ try {+ await expect(authorizeStoredRequest(engine, row)).rejects.toMatchObject({ code: 'page_not_found' });+ } finally {+ await bindCredential(engine, { kind: 'token', id: tokens['bot-dan']!.id }, { mayActFor: ['guest', 'member:alice-example', 'member:bob-example'] });+ }+ const guest = await withCallerAccess(await remoteCallerAccess(engine, auth, undefined, 'http', ['guest']),+ () => submissionAuthority(ctx, 'add_tag', SRC, source!.incarnation, OPEN.slug));+ expect({ actingFor: guest.actingFor, excludePrivate: guest.excludePrivate }).toEqual({ actingFor: ['guest'], excludePrivate: true });+ const danRow = await admitWrite(engine, { principal: guest.principal, authority: { ...guest }, operation: 'add_tag', sourceId: SRC,+ sourceIncarnation: source!.incarnation, slug: PAGES.dan.slug, requestId: randomUUID(), callerIntent: {}, intent: {} });+ await expect(authorizeStoredRequest(engine, danRow)).rejects.toMatchObject({ code: 'page_not_found' });+ }, 120_000);++ test('an agent job reads as the audience it was submitted for, never as its client\'s member', async () => {+ const { clientId } = await provider().registerClientManual('obo-agent', ['client_credentials'], 'read', [], SRC);+ await bindCredential(engine, { kind: 'client', id: clientId }, { member: 'dan-example', mayActFor: ['guest', 'member:alice-example'] });+ const tools = buildBrainTools({ subagentId: 9, engine, config: { engine: 'pglite' } as never, sourceId: SRC,+ delegatedAuth: { clientId, scopes: ['read', 'agent'], sourceId: SRC, allowedSources: [SRC] } });+ const getPage = tools.find(t => t.name === 'brain_get_page')!;+ const read = async (slug: string, actingFor?: string[]) => {+ const authority: RemoteAgentAuthority = { version: 1, kind: 'remote_agent', principal: { kind: 'oauth_client', id: clientId },+ grant: { scopes: ['read', 'agent'], sourceId: SRC, sourceCreatedAt: new Date(0).toISOString(), allowedTools: ['get_page'], allowedSlugPrefixes: [], ...(actingFor ? { actingFor } : {}) },+ payloadHash: '0'.repeat(64) };+ expect(parseSubmissionAuthority(authority)).not.toBeNull();+ try { return JSON.stringify(await withSubmissionAuthority(authority, () => getPage.execute({ slug }, { engine, jobId: 1, remote: true } as never))); }+ catch (e) { return String((e as Error).message); }+ };+ expect(await read(PAGES.dan.slug)).toContain(PAGES.dan.canary);+ expect(await read(PAGES.dan.slug, ['guest'])).not.toContain(PAGES.dan.canary);+ expect(await read(PAGES.alice.slug, ['member:alice-example'])).toContain(PAGES.alice.canary);+ expect(await read(PAGES.dan.slug, ['member:alice-example'])).not.toContain(PAGES.dan.canary);+ await engine.executeRaw("UPDATE oauth_clients SET scope = 'read agent', bound_tools = ARRAY['get_page'], bound_source_id = source_id, federated_read = ARRAY[source_id], delegated_namespace = 'job', delegated_slug_prefixes = NULL, bound_max_concurrent = 1 WHERE client_id = $1", [clientId]);+ const agentAuth = { token: 'x', clientId, scopes: ['read', 'agent'], sourceId: SRC, principal: { kind: 'oauth_client', id: clientId } } as unknown as AuthInfo;+ const submit = async (audience?: AudiencePrincipal[]) => withCallerAccess(await remoteCallerAccess(engine, agentAuth, undefined, 'http', audience ?? null),+ () => prepareRemoteAgent({ engine, auth: agentAuth, remote: true } as unknown as OperationContext, { source_id: SRC, allowed_tools: ['get_page'], allowed_slug_prefixes: [] }));+ expect((await submit(['member:alice-example'])).grant.actingFor).toEqual(['member:alice-example']);+ expect((await submit()).grant.actingFor).toBeUndefined();+ await bindCredential(engine, { kind: 'client', id: clientId }, { mayActFor: ['guest'] });+ expect(await read(PAGES.alice.slug, ['member:alice-example'])).not.toContain(PAGES.alice.canary);+ expect(parseSubmissionAuthority({ version: 1, kind: 'remote_agent', principal: { kind: 'oauth_client', id: clientId },+ grant: { scopes: ['agent'], sourceId: SRC, sourceCreatedAt: 'x', allowedTools: ['get_page'], allowedSlugPrefixes: [], actingFor: [] }, payloadHash: '0'.repeat(64) })).toBeNull();+ }, 120_000);++ test('a stdio server refuses every audience until mcp.stdio_may_act_for lists it', async () => {+ const refused = await call(null, 'get_page', { slug: PAGES.alice.slug }, { meta: ['alice-example'] });+ expect(refused.json.code).toBe('on_behalf_of_not_permitted');+ expect(((refused.json.fix as Record<string, unknown>).argv as string[]).slice(0, 5)).toEqual(['gbrain', 'config', 'set', STDIO_MAY_ACT_FOR_KEY, 'member:alice-example']);+ await engine.setConfig(STDIO_MAY_ACT_FOR_KEY, 'alice-example,guest');+ try {+ expect((await call(null, 'get_page', { slug: PAGES.alice.slug }, { meta: ['alice-example'] })).text).toContain(PAGES.alice.canary);+ expect((await call(null, 'get_page', { slug: PAGES.alice.slug }, { meta: ['guest'] })).text).not.toContain(PAGES.alice.canary);+ expect((await call(null, 'get_page', { slug: PAGES.bob.slug }, { meta: ['bob-example'] })).json.code).toBe('on_behalf_of_not_permitted');+ } finally {+ await engine.setConfig(STDIO_MAY_ACT_FOR_KEY, '');+ }+ }, 60_000);++ test('the legacy bearer transport reads the header and request-level _meta over a real socket', async () => {+ const 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 }),+ } });+ try {+ const post = async (headers: Record<string, string>, meta?: unknown) => {+ const res = await fetch('http://127.0.0.1:' + server.port + '/mcp', {+ method: 'POST', headers: { authorization: 'Bearer ' + tokens.bot!.token, 'content-type': 'application/json', ...headers },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'get_page', arguments: { slug: PAGES.alice.slug }, ...(meta ? { _meta: meta } : {}) } }),+ });+ return await res.text();+ };+ expect(await post({ 'x-gbrain-on-behalf-of': 'alice-example' })).toContain(PAGES.alice.canary);+ expect(await post({}, { on_behalf_of: ['alice-example'] })).toContain(PAGES.alice.canary);+ expect(await post({ 'X-Gbrain-On-Behalf-Of': 'bob-example' })).not.toContain(PAGES.alice.canary);+ expect(await post({})).not.toContain(PAGES.alice.canary);+ const conflict = await post({ 'x-gbrain-on-behalf-of': 'alice-example' }, { on_behalf_of: ['bob-example'] });+ expect(conflict).toContain('on_behalf_of_invalid_audience');+ expect(conflict).not.toContain(PAGES.alice.canary);+ } finally {+ server.stop(true);+ }+ }, 60_000);++ test('doctor warns on a may_act_for of * (credential or stdio) and is ok on explicit lists', async () => {+ const run = async () => (await sharedAgentAccessEntry.run({ engine } as unknown as DoctorContext) as Array<{ name: string; status: string; message: string }>)[0]!;+ const warned = await run();+ expect(warned.status).toBe('warn');+ expect(warned.message).toContain('token wild');+ await bindCredential(engine, { kind: 'token', id: tokens.wild!.id }, { mayActFor: ['member:alice-example'] });+ try {+ expect((await run()).status).toBe('ok');+ await engine.setConfig(STDIO_MAY_ACT_FOR_KEY, '*');+ try {+ const stdio = await run();+ expect(stdio.status).toBe('warn');+ expect(stdio.message).toContain(STDIO_MAY_ACT_FOR_KEY);+ } finally {+ await engine.setConfig(STDIO_MAY_ACT_FOR_KEY, '');+ }+ } finally {+ await bindCredential(engine, { kind: 'token', id: tokens.wild!.id }, { mayActFor: ['*'] });+ }+ }, 60_000);++ test('each assertion is appended to the audit trail with its outcome', async () => {+ const before = readAudienceAssertions().length;+ await call('bot', 'get_page', { slug: OPEN.slug }, { header: 'alice-example' });+ await call('narrow', 'get_page', { slug: OPEN.slug }, { header: 'bob-example' });+ const added = readAudienceAssertions().slice(before);+ expect(added.map(e => ({ outcome: e.outcome, audience: e.audience, op: e.op, transport: e.transport }))).toEqual([+ { outcome: 'accepted', audience: ['member:alice-example'], op: 'get_page', transport: 'http' },+ { outcome: 'on_behalf_of_not_permitted', audience: ['member:bob-example'], op: 'get_page', transport: 'http' },+ ]);+ expect(added[0]!.principal).toBe('legacy_token:' + tokens.bot!.id);+ }, 60_000);+ });+}diff --git a/test/e2e/helpers.ts b/test/e2e/helpers.tsindex a969828992..8cc7e06879 100644--- a/test/e2e/helpers.ts+++ b/test/e2e/helpers.ts@@ -43,6 +43,15 @@ const FIXTURES_DIR = resolve(import.meta.dir, 'fixtures');let engine: PostgresEngine | null = null;const ALL_TABLES = [+ // Per-member read access (members, groups, folder rules): a member left behind makes every later file's brain restricted.+ 'access_group_members',+ 'access_groups',+ 'access_members',+ 'access_pending_coverage',+ 'access_rules',+ 'access_policy_revisions',+ 'access_policy_migrations',+ 'access_policy_state',// C4 pinned questions: no FKs (pointers only); cleared so pins never leak across files.'question_evidence','pinned_questions',diff --git a/test/e2e/serve-http-on-behalf-of.test.ts b/test/e2e/serve-http-on-behalf-of.test.tsnew file mode 100644index 0000000000..ac937bd1ba--- /dev/null+++ b/test/e2e/serve-http-on-behalf-of.test.ts@@ -0,0 +1,110 @@+/**+ * GBRA-231 shared agents over the real `gbrain serve --http` (serve-http-mcp.ts): one bot token whose+ * may_act_for lists two members reads, per call, only what the asserted audience may read, from the+ * X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of, and every response names that view in+ * _meta.access.+ *+ * 1. Protects: the shared-agent read boundary on the production HTTP transport, not only dispatch.+ * 2. Fails when: serve-http drops the header or request _meta, a call reuses another call's audience, an+ * audience outside may_act_for reads anything, or _meta.access is missing.+ * 3. Existing coverage: test/access-on-behalf-of.test.ts pins dispatch and the legacy bearer transport.+ * 4. No production seam.+ *+ * Run: DATABASE_URL=... GBRAIN_TEST_ALLOW_DATABASE_URL=1 bun test test/e2e/serve-http-on-behalf-of.test.ts+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { setupDB, teardownDB, hasDatabase } from './helpers.ts';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { mintLegacyToken } from '../../src/core/token-mint.ts';+import { addMember, bindCredential } from '../../src/core/access/members.ts';++const skip = !hasDatabase();+const describeE2E = skip ? describe.skip : describe;+if (skip) console.log('Skipping E2E serve-http-on-behalf-of tests (DATABASE_URL not set)');++const PORT = 19162;+const BASE = `http://localhost:${PORT}`;+const PAGES = {+ alice: { slug: 'notes/obo-alice', readers: '[alice-example]', canary: 'canaryoboealice' },+ bob: { slug: 'notes/obo-bob', readers: '[bob-example]', canary: 'canaryoboebob' },+ both: { slug: 'notes/obo-both', readers: '[alice-example, bob-example]', canary: 'canaryoboeboth' },+} as const;+type Key = keyof typeof PAGES;++describeE2E('/mcp shared agent on_behalf_of over serve --http', () => {+ let serverProcess: ReturnType<typeof import('child_process').spawn> | null = null;+ let engine: PostgresEngine;+ let bot = '';++ beforeAll(async () => {+ engine = await setupDB();+ for (const id of ['alice-example', 'bob-example', 'dan-example']) await addMember(engine, id);+ for (const key of Object.keys(PAGES) as Key[]) {+ const p = PAGES[key];+ const out = await importFromContent(engine, p.slug, `---\ntype: note\nreadable_by: ${p.readers}\n---\n# Harbor plan ${key}\n\nHarbor plan notes ${p.canary}.`, { noEmbed: true });+ expect(out.status).toBe('imported');+ }+ const minted = await mintLegacyToken(engine, { name: 'obo-e2e-bot', takesHolders: ['world'], scopes: ['read'] });+ bot = minted.token;+ await bindCredential(engine, { kind: 'token', id: minted.id }, { member: 'dan-example', mayActFor: ['member:alice-example', 'member:bob-example', 'guest'] });+ const { spawn } = await import('child_process');+ serverProcess = spawn('bun', ['run', 'src/cli.ts', 'serve', '--http', '--port', String(PORT), '--public-url', BASE], {+ cwd: process.cwd(), env: { ...process.env }, stdio: ['ignore', 'pipe', 'pipe'],+ });+ let stderr = '';+ serverProcess.stderr?.on('data', (d: Buffer) => { stderr += d.toString(); });+ for (let i = 0; i < 30; i++) {+ try { if ((await fetch(`${BASE}/health`)).ok) return; } catch { /* not up yet */ }+ await new Promise(r => setTimeout(r, 500));+ }+ throw new Error('Server failed to start within 15s.\nstderr: ' + stderr.slice(-500));+ }, 60_000);++ afterAll(async () => {+ if (serverProcess) {+ serverProcess.kill('SIGTERM');+ await new Promise(r => setTimeout(r, 1000));+ if (!serverProcess.killed) serverProcess.kill('SIGKILL');+ }+ await teardownDB();+ }, 30_000);++ async function call(slug: string, ch: { header?: string; meta?: string[] }): Promise<{ text: string; meta: Record<string, unknown> | undefined }> {+ const res = await fetch(`${BASE}/mcp`, {+ method: 'POST',+ headers: { Authorization: `Bearer ${bot}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream',+ ...(ch.header !== undefined ? { 'X-Gbrain-On-Behalf-Of': ch.header } : {}) },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call',+ params: { name: 'get_page', arguments: { slug }, ...(ch.meta ? { _meta: { on_behalf_of: ch.meta } } : {}) } }),+ });+ expect(res.status).toBe(200);+ const body = (await res.text()).trim();+ const rpc = JSON.parse(body.startsWith('{') ? body : body.split('\n').filter(l => l.startsWith('data:')).pop()!.slice(5).trim());+ expect(rpc.error).toBeUndefined();+ return { text: rpc.result.content.map((c: { text: string }) => c.text).join('\n'), meta: rpc.result._meta };+ }+ const reads = async (ch: { header?: string; meta?: string[] }) => {+ const seen: Key[] = [];+ for (const key of Object.keys(PAGES) as Key[]) if ((await call(PAGES[key].slug, ch)).text.includes(PAGES[key].canary)) seen.push(key);+ return seen;+ };++ test('each call reads as its own audience, from the header or request _meta, and names it in _meta.access', async () => {+ expect(await reads({})).toEqual([]);+ expect(await reads({ header: 'alice-example' })).toEqual(['alice', 'both']);+ expect(await reads({ meta: ['bob-example'] })).toEqual(['bob', 'both']);+ expect(await reads({ header: 'alice-example,bob-example' })).toEqual(['both']);+ expect(await reads({ header: 'guest' })).toEqual([]);+ const named = await call(PAGES.both.slug, { header: 'alice-example, bob-example' });+ expect((named.meta?.access as Record<string, unknown>).audience).toEqual(['member:alice-example', 'member:bob-example']);+ expect((named.meta?.access as Record<string, unknown>).member).toBeNull();+ }, 60_000);++ test('an audience outside may_act_for reads nothing and names the operator command', async () => {+ const out = await call(PAGES.alice.slug, { header: 'alice-example, eve-example' });+ expect(out.text).toContain('on_behalf_of_not_permitted');+ expect(out.text).toContain('gbrain auth rescope --token obo-e2e-bot');+ expect(out.text).not.toContain(PAGES.alice.canary);+ }, 30_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 3c90092544..ef4395f250 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -16,6 +16,7 @@ test/access-binding.test.tstest/access-folder-lock-order.test.tstest/access-folder-rules.test.tstest/access-members.test.ts+test/access-on-behalf-of.test.tstest/access-writes.test.tstest/activation-unbound-rooted-6449.test.tstest/alias-source-cascade-5094.test.ts