Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(qm): scope-read seam for attested named-source reads, attest_read per credential, actorless refusal, doctor check (GST-1158 E1, F3, F4)
garrytand6519666c8d5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex db2f561cf2..c3a552280a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,8 @@ identifiers and attribution are available in the pre-removal Git revision## [Unreleased]+**An attested read that names its sources now reads as those sources' audience for every read QM can list, and an operator can say whether a credential serves rooms or one person's own turns.** `get_page`, `entity`, `whois`, `get_backlinks`, `get_timeline`, `find_experts`, `volunteer_context` and `query`, called with `x-qm-actor` and `source_id` or `source_ids`, now read the way `memory_recall` does: the person's restricted pages and their member page read as missing, a source outside the grant is refused, and `__all__` or `all_sources` is refused, so a shared turn can never pull one member's private pages into a channel. `get_timeline` gains `source_id` and `source_ids`, and `find_experts` and `volunteer_context` gain `source_ids`; `volunteer_context` refuses `stats: true` under that read. `gbrain auth rescope --attest-read person|scope|none` sets how a credential reads named sources: `person` narrows to them but reads as the person (for a DM client), and `scope` keeps the audience read and also refuses any call that names no person (`actor_not_attested`, reason `actor_required`). Unset keeps today's behavior, so no existing client changes. `gbrain doctor` warns (`attest_read_shared_scope`) when a person credential reads a source another attest credential reads as the scope. `context_pack` is not covered yet. `v1.json` and `v2.json` are unchanged; on a repo-less brain all of it is database state and works the same.+**An attested call can no longer write pages directly: `add_timeline_entry`, `add_link`, `put_page` and `edit_page` are not attestable.** They write to pages that everyone who reads the page sees, so a trusted system acting as one person could put that person's words in front of a whole audience with no one approving them. They now wait for owner-approved proposals, the way `capture` and take writes already do. An operator whose `--attest-ops` list names one of them sees `gbrain auth rescope` refuse the list, and each attested call to it is refused (`actor_not_attested`, reason `op_not_attested`); a queued attested write of one fails when it publishes. Unattested calls, and credentials bound to a member, are unchanged. `v2.json` lists the new deferred operations; `v1.json` is unchanged.**A `memory_recall` that names sources reads as that scope, never as the attested person, so a shared turn can no longer recall one member's private facts into a shared channel.** `memory_recall` gains `source_id` and `source_ids`. Named, the read drops the person's own recent facts and every member-page fact, keeps restricted pages hidden and never relaxes `visibility: private`. The contract for it is the new `docs/contracts/qm-memory-provider/v2.json`; `v1.json` stays byte-identical and a test holds it there. Three smaller provider fixes ride along.diff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.mdindex 9b6d84eef0..76e00b13e9 100644--- a/docs/architecture/key-files/access.md+++ b/docs/architecture/key-files/access.md@@ -3,5 +3,5 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/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 before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit; a database with no revision yet replays each committed `access.yml` since the `access.approved` baseline, so a rebuild holds a removal a plain commit made); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v283 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. Shared agents (B, GBRA-231): `audience.ts` parses the audience a harness asserts (`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`, 1-50 principals, `guest` = the empty identity; the same key inside tool arguments is refused) and appends each assertion to `access-audience-YYYY-Www.jsonl`. Dispatch resolves it on every remote call through `caller.ts` (`resolveAudienceIdentities`: every entry must be in the credential's live `may_act_for`, then name an enabled member or existing group); the caller-access record then carries `audienceIdentities`, and `accessAllowedForAllSql` needs one readers conjunct per identity, folder rules the intersection of each entry's satisfied set (`folderAccessForAll`). Privacy relaxes only for a one-member audience. Writes carry the audience as `WriteAuthority.actingFor` (re-resolved at publication) and agent jobs as `grant.actingFor`. Every remote response carries `_meta.access` (`appliedAccessSummary`), which `whoami` returns as `access.applied`; doctor `access_may_act_for_wildcard` (`checks/shared-agent-access.ts`) warns on `*`. Tests: `test/access-on-behalf-of.test.ts` (both engines), `test/e2e/serve-http-on-behalf-of.test.ts`. Attested actor (C1, GST-359): `actor-model.ts` (dependency-free: `x-qm-actor`, `acting_user`, `EXTERNAL_ID_RE` = 1-256 visible ASCII, `attestRightFrom`: the right counts only for a member-less credential whose token is legacy or `client_credentials`, read from `oauth_tokens.grant_type`) and `actor.ts`. `resolveAttestedActor` runs in dispatch before any work: an invalid id refuses `actor_not_attested` (`invalid_actor_id`) before any lookup, then the right, the op list (`attest_ops`, default `get_write_request,memory_recall,memory_write`), `acting_user` = header (stripped), and `actorCoverage` (the one coverage test: live right plus a live link in `access_member_links` to an enabled member, compared exactly) or `actor_unlinked`. `ACTOR_DEFERRED_OPS` (`capture`, `extract_facts`, take writes, `list_write_conflicts`) are never attestable until each is keyed to the member: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration v286. Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`. Member facts (C2, GST-359): `member-facts.ts`. A remote `remember` from an attested actor or a lone-member credential (`callerMember`, never an audience of several) writes to `memory/members/<member>` (`memberFactPage`; `persistence/memory-prepare.ts` creates the page with `readable_by: [member:<id>]`), `visibility: private`, `infer_entity` off, the entity kept as `entity_slug`. A member id whose page slug `slugifyPath` would change (`a--b`, `zed-`) is refused (`invalid_params`). The page must name that member alone (`memberPageIsOwn`, checked at submission and again in preparation, `memberPageNotOwned`), and remote writes under `memory/members/` go only to the caller's own page (`assertMemberPageWriter`, called from `ops/context.ts` `enforceClientSlugFence`, so every remote page write passes it; trusted local callers are unaffected). Reads widen a world-only fact list only by `memberFactAdmitSql` (a private fact on the caller's own live member page whose readers and folder rules admit the caller; `factVisibilitySql` in `engine-sql/facts.ts` and `search/fact-relevance.ts`), and `privateProvenanceFilterUnderPolicy` judges a member-page fact's source page as the caller (every other fact keeps the empty identity, so a fact from a page that names readers stays hidden from every remote caller). Writers never cross pages: `facts/single-prepare.ts` (`SingleFactIntent.page_slug`) and `trust/supersede-handlers.ts` dedup, supersede and contest only within the member page, and no other write matches a fact there (`onMemberPageSql`); consolidation skips facts whose page names readers (`readersSourcedFactSql`). Per-person keys: `callerIdentityKey` joins the hot-memory cache key (`facts/meta-hook.ts`, `::xid=`), `callerSessionKey` the `delta` cursor (`ops/facts.ts`), `sameAttestedActor` gates receipts (`persistence/authority.ts` `ownRequestAccessible`) and replays (`persistence/journal.ts`), and `get_agent_job` and the owner-fenced `get_job`, `wait_job`, `get_job_progress`, `list_jobs` and `cancel_job` match the job's `grant.actor` (system, external id, member; `jobActorSql` in `minions/types.ts`), so a job with an actor reads as missing to the bare client and to other actors. Tests: `test/access-member-facts.test.ts` (both engines), `test/access-member-sweep.test.ts` (every attestable op as Bob, the bare client and an unbound credential; `test/helpers/member-sweep.ts`), `test/e2e/serve-http-member-sweep.test.ts` (two members over a real `serve --http` on a keyless repo-less brain).+- `src/core/access/` (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 before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit; a database with no revision yet replays each committed `access.yml` since the `access.approved` baseline, so a rebuild holds a removal a plain commit made); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v283 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. Shared agents (B, GBRA-231): `audience.ts` parses the audience a harness asserts (`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`, 1-50 principals, `guest` = the empty identity; the same key inside tool arguments is refused) and appends each assertion to `access-audience-YYYY-Www.jsonl`. Dispatch resolves it on every remote call through `caller.ts` (`resolveAudienceIdentities`: every entry must be in the credential's live `may_act_for`, then name an enabled member or existing group); the caller-access record then carries `audienceIdentities`, and `accessAllowedForAllSql` needs one readers conjunct per identity, folder rules the intersection of each entry's satisfied set (`folderAccessForAll`). Privacy relaxes only for a one-member audience. Writes carry the audience as `WriteAuthority.actingFor` (re-resolved at publication) and agent jobs as `grant.actingFor`. Every remote response carries `_meta.access` (`appliedAccessSummary`), which `whoami` returns as `access.applied`; doctor `access_may_act_for_wildcard` (`checks/shared-agent-access.ts`) warns on `*`. Tests: `test/access-on-behalf-of.test.ts` (both engines), `test/e2e/serve-http-on-behalf-of.test.ts`. Attested actor (C1, GST-359): `actor-model.ts` (dependency-free: `x-qm-actor`, `acting_user`, `EXTERNAL_ID_RE` = 1-256 visible ASCII, `attestRightFrom`: the right counts only for a member-less credential whose token is legacy or `client_credentials`, read from `oauth_tokens.grant_type`) and `actor.ts`. `resolveAttestedActor` runs in dispatch before any work: an invalid id refuses `actor_not_attested` (`invalid_actor_id`) before any lookup, then the right, the op list (`attest_ops`, default `get_write_request,memory_recall,memory_write`), `acting_user` = header (stripped), and `actorCoverage` (the one coverage test: live right plus a live link in `access_member_links` to an enabled member, compared exactly) or `actor_unlinked`. GST-1158: `scope-read.ts` holds `SCOPE_READ_ACCESS` (no identity, actor or audience; privacy never relaxed) and `SCOPE_READ_OPS`; dispatch runs an attested call to one of those ops that names `source_id`/`source_ids` under that record (`attestedReadMode`, which refuses `__all__`/`all_sources`), or as the person when the right's `attest_read` (v287, `--attest-read`) is `person`, and handlers read the mode with `currentReadMode`. `attest_read = 'scope'` refuses a call that names no actor (`actor_required`). Tests: `test/qm-scope-read.test.ts` (both engines), `test/doctor-attest-read-shared-scope.test.ts`. `ACTOR_DEFERRED_OPS` (`capture`, `extract_facts`, take writes, `list_write_conflicts`) are never attestable until each is keyed to the member: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration v286. Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`. Member facts (C2, GST-359): `member-facts.ts`. A remote `remember` from an attested actor or a lone-member credential (`callerMember`, never an audience of several) writes to `memory/members/<member>` (`memberFactPage`; `persistence/memory-prepare.ts` creates the page with `readable_by: [member:<id>]`), `visibility: private`, `infer_entity` off, the entity kept as `entity_slug`. A member id whose page slug `slugifyPath` would change (`a--b`, `zed-`) is refused (`invalid_params`). The page must name that member alone (`memberPageIsOwn`, checked at submission and again in preparation, `memberPageNotOwned`), and remote writes under `memory/members/` go only to the caller's own page (`assertMemberPageWriter`, called from `ops/context.ts` `enforceClientSlugFence`, so every remote page write passes it; trusted local callers are unaffected). Reads widen a world-only fact list only by `memberFactAdmitSql` (a private fact on the caller's own live member page whose readers and folder rules admit the caller; `factVisibilitySql` in `engine-sql/facts.ts` and `search/fact-relevance.ts`), and `privateProvenanceFilterUnderPolicy` judges a member-page fact's source page as the caller (every other fact keeps the empty identity, so a fact from a page that names readers stays hidden from every remote caller). Writers never cross pages: `facts/single-prepare.ts` (`SingleFactIntent.page_slug`) and `trust/supersede-handlers.ts` dedup, supersede and contest only within the member page, and no other write matches a fact there (`onMemberPageSql`); consolidation skips facts whose page names readers (`readersSourcedFactSql`). Per-person keys: `callerIdentityKey` joins the hot-memory cache key (`facts/meta-hook.ts`, `::xid=`), `callerSessionKey` the `delta` cursor (`ops/facts.ts`), `sameAttestedActor` gates receipts (`persistence/authority.ts` `ownRequestAccessible`) and replays (`persistence/journal.ts`), and `get_agent_job` and the owner-fenced `get_job`, `wait_job`, `get_job_progress`, `list_jobs` and `cancel_job` match the job's `grant.actor` (system, external id, member; `jobActorSql` in `minions/types.ts`), so a job with an actor reads as missing to the bare client and to other actors. Tests: `test/access-member-facts.test.ts` (both engines), `test/access-member-sweep.test.ts` (every attestable op as Bob, the bare client and an unbound credential; `test/helpers/member-sweep.ts`), `test/e2e/serve-http-member-sweep.test.ts` (two members over a real `serve --http` on a keyless repo-less brain).- `src/core/ops/qm-memory.ts` (GST-359 D) — QM's memory provider pair. `memory_recall` reads the attested person's own last-24-hour facts on their member page (`listFactsSince` with `sourceMarkdownSlug`), then `rankFactsByQuestion` over the facts they may read, renders one plain line per fact (`plainFactText` strips fence and heading markers) and cuts at a line within `max_chars` (`boundFactLines`). `memory_write` validates 1-20 facts, derives each request id from uuidv5(member, idempotency_key) (`memoryWriteRequestId`) and saves through `remember`'s handler with `ctx.attestedOp = 'memory_write'`, which the stored write authority keeps (`WriteAuthority.attestedOp`) so publication and receipt reads re-check that operation's attest right. `qmMemoryToolResult` (dispatch) moves the result into `structuredContent` and leaves the model text in `content`; `unlinkedRecallResult` is the empty success dispatch's `actorRefusal` returns for an unlinked person. Contract fixture: `scripts/build-qm-memory-contract.ts` writes `docs/contracts/qm-memory-provider/v1.json` (a `regen:all` artifact). Tests: `test/qm-memory-tools.test.ts` (both engines), `test/qm-memory-contract.test.ts` (drift), `test/e2e/serve-http-qm-memory.test.ts` (keyless `serve --http`).diff --git a/docs/guides/qm.md b/docs/guides/qm.mdindex c8cf081af1..b2fe867c88 100644--- a/docs/guides/qm.md+++ b/docs/guides/qm.md@@ -27,6 +27,30 @@ A client whose `bound_slug_prefixes` do not cover `memory/members/<member>` is rLinks and the right are database state, so a repo-less brain works the same; wherea repo exists, saved facts go through the same git-first writer door as `remember`.+### Reads that name sources++An attested call to `get_page`, `entity`, `whois`, `get_backlinks`, `get_timeline`,+`find_experts`, `volunteer_context`, `query` or `memory_recall` that names `source_id`+or `source_ids` reads those sources as their audience, never as the person: the+person's restricted pages and their member page read as missing, a source outside+the grant is refused, and `__all__` or `all_sources` is refused (`invalid_params`).+`volunteer_context` refuses `stats: true` there. List the ops a client needs with+`--attest-ops`. `context_pack` is not a scope read yet, so keep it off a client that+serves shared turns.++Set how each client reads named sources with `--attest-read`:++```bash+gbrain auth rescope --client <room_client_id> --attest-read scope # every call must name a person+gbrain auth rescope --client <dm_client_id> --attest-read person # named sources, read as the person+```++`scope` also refuses any call that names no person (`actor_not_attested`, reason+`actor_required`), so the client never reads as itself. `person` is for a client that+serves only one person's own conversations; a `person` client that reads a source a+room client reads is flagged by `gbrain doctor` (`attest_read_shared_scope`). Unset+(`none`) reads named sources as the scope and still serves calls that name no person.+## What the tools do- `memory_recall {query, max_chars?, source_id?, source_ids?}` answers plain text, one fact per line@@ -38,7 +62,8 @@ a repo exists, saved facts go through the same git-first writer door as `remembeone line: line breaks and control characters in it become spaces. Ranking iskeyword-only on a keyless brain. A call that names sources (`source_id`,`source_ids`, narrowed inside the credential's grant) reads as that scope,- never as the person: no own facts first and no fact from any member page.+ never as the person: no own facts first and no fact from any member page+ (unless the client is set `--attest-read person`; see below).Name the shared scope on a shared turn; leave sources out only for theperson's own conversations.- `memory_write {facts, idempotency_key}` saves 1-20 facts ondiff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex ed17169204..f14eaee2f7 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -1006,7 +1006,7 @@ Links and the right live in the database, so they are the same on a repo-less br| Code | What happened | What to do ||---|---|---|-| <a id="actor_not_attested"></a>`actor_not_attested` | The call named a person in a way gbrain does not honour. `reason` says which: `no_attest_right` (the credential holds no attest right, or the token of an attest client was issued before the upgrade or by another grant: the message then says to take a new client-credentials token), `op_not_attested` (the operation is not in the credential's attested operations, or is not attestable yet: `list_write_conflicts`, `capture`, `extract_facts`, `takes_add|update|resolve|supersede` and the direct page writes `add_timeline_entry`, `add_link`, `put_page` and `edit_page`; also when a queued write or agent job tool call runs after its operation was removed from the list), `argument_mismatch` (the `acting_user` argument differs from the header, or, with no header on a credential bound to a member, names anyone but that member; its own member id or a canonical id linked to it is dropped and the call runs exactly as the credential), `argument_without_attestation` (`acting_user` came without an attested header from a credential bound to no member, over stdio, or beside an `on_behalf_of` audience), `invalid_actor_id` (the header or argument is not 1-256 visible ASCII characters), `actor_required` (`memory_write` named no attested person) or `audience_not_supported` (the request carries `x-qm-audience`, QM's channel audience, which is refused on every call until wave 2). Nothing was read or written. | `no_attest_right` and `op_not_attested` are the brain operator's call: `fix` carries `gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]`. The other five are fixed in the calling harness: send the canonical id unchanged in the header from the attest credential, the same value or nothing in `acting_user` (on a member-bound credential with no header: its own member id, a canonical id linked to it, or nothing), and no `x-qm-audience`. |+| <a id="actor_not_attested"></a>`actor_not_attested` | The call named a person in a way gbrain does not honour. `reason` says which: `no_attest_right` (the credential holds no attest right, or the token of an attest client was issued before the upgrade or by another grant: the message then says to take a new client-credentials token), `op_not_attested` (the operation is not in the credential's attested operations, or is not attestable yet: `list_write_conflicts`, `capture`, `extract_facts`, `takes_add|update|resolve|supersede` and the direct page writes `add_timeline_entry`, `add_link`, `put_page` and `edit_page`; also when a queued write or agent job tool call runs after its operation was removed from the list), `argument_mismatch` (the `acting_user` argument differs from the header, or, with no header on a credential bound to a member, names anyone but that member; its own member id or a canonical id linked to it is dropped and the call runs exactly as the credential), `argument_without_attestation` (`acting_user` came without an attested header from a credential bound to no member, over stdio, or beside an `on_behalf_of` audience), `invalid_actor_id` (the header or argument is not 1-256 visible ASCII characters), `actor_required` (`memory_write` named no attested person, or a credential set `--attest-read scope` sent a call that names no person) or `audience_not_supported` (the request carries `x-qm-audience`, QM's channel audience, which is refused on every call until wave 2). Nothing was read or written. | `no_attest_right` and `op_not_attested` are the brain operator's call: `fix` carries `gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]`. The other five are fixed in the calling harness: send the canonical id unchanged in the header from the attest credential, the same value or nothing in `acting_user` (on a member-bound credential with no header: its own member id, a canonical id linked to it, or nothing), and no `x-qm-audience`. || <a id="actor_unlinked"></a>`actor_unlinked` | The id is not linked to an enabled member: never linked, unlinked, or the member is disabled or removed. Ids compare exactly, with no case folding. Nothing was read or written. A queued write or agent job made for the person is refused the same way when its link is gone or now names another member. `memory_recall` answers it as an empty success instead (`structuredContent: {facts: [], truncated: false, code: "actor_unlinked"}`), so a person not yet linked reads nothing. | The brain operator links it: `gbrain access member link <member> --qm <id>` (or `gbrain access member enable <member>`). |## Relateddiff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex 2789e58730..b0bdd081f0 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -263,6 +263,10 @@ read or write is not yet kept to the person: `list_write_conflicts`, `capture`,`add_timeline_entry`, `add_link`, `put_page` and `edit_page`, which wait for owner-approvedproposals. An `--attest-ops` list that already names one of these is refused for it(`actor_not_attested`, reason `op_not_attested`), and a queued attested write of one fails when it publishes.+An attested read that names `source_id` or `source_ids` (`get_page`, `entity`, `whois`, `get_backlinks`,+`get_timeline`, `find_experts`, `volunteer_context`, `query`, `memory_recall`) reads those sources as their+audience, never as the person; `--attest-read person` makes such reads run as the person, and `--attest-read scope`+also refuses every call that names no person (`actor_required`) ([QM guide](../guides/qm.md#reads-that-name-sources)).`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/src/commands/auth-binding.ts b/src/commands/auth-binding.tsindex c3c3e99fa8..c9d8370968 100644--- a/src/commands/auth-binding.ts+++ b/src/commands/auth-binding.ts@@ -6,15 +6,23 @@ import { operationsByName } from '../core/operations.ts';import { opError } from '../core/ops/contract.ts';import { usageError } from '../cli/cli-error.ts';-const FLAGS = ['--member', '--may-act-for', '--attest-actor', '--attest-ops'] as const;+const FLAGS = ['--member', '--may-act-for', '--attest-actor', '--attest-ops', '--attest-read'] as const;type Flag = typeof FLAGS[number];const NEEDS: Record<Flag, string> = {'--member': 'Pass a member id, or none to unbind (gbrain access member list).','--may-act-for': 'Pass a comma-separated list of member ids, group:<id>, guest or *, or none.','--attest-actor': 'Pass qm (the system whose x-qm-actor header this credential may send), or none.','--attest-ops': 'Pass a comma-separated list of operations an attested call may run (default get_write_request,memory_recall,memory_write).',+ '--attest-read': 'Pass person (a call that names sources reads them as the person), scope (as the scope, and every call must name a person) or none (the default: named sources read as the scope).',};+function parseAttestRead(value: string): 'person' | 'scope' | null {+ const v = value.trim();+ if (v === 'none') return null;+ if (v === 'person' || v === 'scope') return v;+ throw opError('invalid_params', `--attest-read ${value} is not a read mode.`, NEEDS['--attest-read']);+}+function parseAttestActor(value: string): string | null {if (value.trim() === 'none') return null;if (ATTEST_SYSTEMS.includes(value.trim())) return value.trim();@@ -23,7 +31,8 @@ function parseAttestActor(value: string): string | null {/*** GBRA-218: `--member <id>|none` and `--may-act-for <list>|none` on auth create, rescope and register-client;- * GST-359 C1: `--attest-actor qm|none` and `--attest-ops <list>` (the attest right). Strips them from `args` (the+ * GST-359 C1: `--attest-actor qm|none` and `--attest-ops <list>` (the attest right); GST-1158 F3: `--attest-read+ * person|scope|none` (how an attested call that names sources reads them). Strips them from `args` (the* grant parsers never see them) and returns the binding patch, or null when no such flag was passed. An ill-formed* value throws access_member_invalid or invalid_params.*/@@ -40,6 +49,7 @@ export function takeBindingFlags(args: string[]): { args: string[]; patch: Bindiif (flag === '--member') patch.member = parseMemberFlag(value);else if (flag === '--may-act-for') patch.mayActFor = parseMayActFor(value);else if (flag === '--attest-actor') patch.attestActor = parseAttestActor(value);+ else if (flag === '--attest-read') patch.attestRead = parseAttestRead(value);else patch.attestOps = parseAttestOps(value, name => operationsByName[name]);seen = true;}@@ -52,6 +62,6 @@ export async function checkBindingTarget(engine: BrainEngine, patch: BindingPatc}export function bindingLine(b: BindingResult, dryRun = false): string {- const attest = b.attest_actor ? `; attests actor: ${b.attest_actor} for ${(b.attest_ops ?? DEFAULT_ATTEST_OPS).join(', ')}` : '';+ const attest = b.attest_actor ? `; attests actor: ${b.attest_actor} for ${(b.attest_ops ?? DEFAULT_ATTEST_OPS).join(', ')}; named sources read as: ${b.attest_read ?? 'scope (default)'}` : '';return ` Member: ${b.member ?? 'none'}; may act for: ${b.may_act_for?.join(', ') ?? 'none'}${attest}${b.changed ? (dryRun ? ' (preview, not written)' : ' (updated)') : ''}`;}diff --git a/src/commands/auth.ts b/src/commands/auth.tsindex 3579944cd8..a08387b404 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -1357,6 +1357,9 @@ Usage:the person a QM call serves (x-qm-actor; linked with gbrainaccess member link); ops default get_write_request,memory_recall,memory_write+ --attest-read <person|scope|none> How an attested call that names sources reads them:+ person, or scope (every call must then name a person);+ none (default) reads them as the scope--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/attest-read-access.ts b/src/commands/doctor/checks/attest-read-access.tsnew file mode 100644index 0000000000..a5a1b8a9ef--- /dev/null+++ b/src/commands/doctor/checks/attest-read-access.ts@@ -0,0 +1,72 @@+/**+ * GST-1158 F3 doctor check (read-only).+ *+ * - attest_read_shared_scope: an attest credential set `--attest-read person` whose read grant (federated_read, or+ * its source grant) includes a source that a different attest credential reads as the scope (attest_read 'scope',+ * or unset, which reads named sources as the scope). Such a source serves shared turns, so a person credential that+ * reads it as the person can return that person's restricted pages where a room sees them. Warned, never changed:+ * whether the credential serves only one person's own turns is the operator's call.+ *+ * Database only, so a repo-less brain gets the same check. Not applicable while no attest credential is set to person.+ */+import type { Check } from '../../doctor.ts';+import { agentFix, checkError, infoCheck } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { authSourcesFromGrant, grantFromClient, grantFromRow, grantFromTokenRow, type PrincipalGrant } from '../../../core/grants/model.ts';+import { NO_SOURCES } from '../../../core/source-id.ts';++const name = 'attest_read_shared_scope';+const SAMPLE = 20;++type Credential = { kind: 'token' | 'client'; id: string; name: string; read: string | null; sources: string[] };++function readSources(grant: PrincipalGrant): string[] {+ const auth = authSourcesFromGrant(grant);+ return (auth.allowedSources ?? [auth.sourceId]).filter(s => s !== NO_SOURCES);+}++async function attestReadVerdict(ctx: DoctorContext): Promise<Check> {+ const engine = connectedEngine(ctx);+ try {+ const rows = await engine.executeRaw<{ kind: 'token' | 'client'; id: string; name: string; row: Record<string, unknown> }>(+ `SELECT 'token' AS kind, t.id::text AS id, t.name, to_jsonb(t) AS row FROM access_tokens t+ WHERE t.revoked_at IS NULL AND to_jsonb(t)->>'attest_actor' IS NOT NULL+ UNION ALL+ SELECT 'client' AS kind, c.client_id AS id, COALESCE(c.client_name, c.client_id) AS name, to_jsonb(c) - 'client_secret_hash' AS row FROM oauth_clients c+ WHERE (to_jsonb(c)->>'deleted_at') IS NULL AND to_jsonb(c)->>'attest_actor' IS NOT NULL+ ORDER BY 1, 3`);+ const credentials: Credential[] = rows.map(r => {+ const row = typeof r.row === 'string' ? JSON.parse(r.row) as Record<string, unknown> : r.row;+ const grant = r.kind === 'token' ? grantFromTokenRow(row) : grantFromClient(grantFromRow(row));+ return { kind: r.kind, id: r.id, name: r.name, read: typeof row.attest_read === 'string' ? row.attest_read : null, sources: readSources(grant) };+ });+ const persons = credentials.filter(c => c.read === 'person');+ if (!persons.length) return infoCheck(name, 'Not applicable: no attest credential reads named sources as the person (--attest-read person).', 'not_applicable');+ const shared = persons.map(p => ({ ...p, shared: p.sources.filter(s => credentials.some(o => o !== p && o.read !== 'person' && o.sources.includes(s))) }))+ .filter(p => p.shared.length);+ const details = { credentials: shared.slice(0, SAMPLE).map(p => ({ kind: p.kind, name: p.name, shared_sources: p.shared })), truncated: shared.length > SAMPLE };+ if (!shared.length) return { name, status: 'ok', details, message: `${persons.length} attest credential(s) read named sources as the person, and none reads a source another attest credential reads as the scope.` };+ const first = shared[0]!;+ return { name, status: 'warn', details,+ message: `${shared.length} attest credential(s) set --attest-read person can read a source another attest credential reads as the scope: `+ + `${shared.slice(0, 5).map(p => `${p.kind} ${p.name} (${p.shared.join(', ')})`).join('; ')}. `+ + 'A call that names such a source reads as the person, so what it returns can reach everyone in a shared turn. Keep person credentials for one person\'s own turns.',+ fix: agentFix(['gbrain', 'access', 'check', first.kind === 'token' ? '--token' : '--client', first.kind === 'token' ? first.name : first.id, '--json'],+ 'Read-only: shows the credential\'s grant. Ask the user whether it serves only one person\'s own turns; if not, set it to scope with gbrain auth rescope ... --attest-read scope.', name, { ask_user: true }) };+ } catch (error) {+ return checkError(name, `run ${name}`, error);+ }+}++async function runAttestReadAccess(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ const { name: _name, ...verdict } = await attestReadVerdict(ctx);+ checks.push({ name: 'attest_read_shared_scope', ...verdict });+ return checks;+}++export const attestReadAccessEntry: DoctorEntry = {+ name: 'attest_read_shared_scope',+ emits: ['attest_read_shared_scope'],+ run: runAttestReadAccess,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 0cac843d8d..bc0a054abe 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -135,6 +135,7 @@ 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 { attestReadAccessEntry } from './checks/attest-read-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';@@ -219,6 +220,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [memberAccessEntry,folderAccessEntry,sharedAgentAccessEntry,+ attestReadAccessEntry,rlsEntry,functionSearchPathEntry,schemaVersionEntry,diff --git a/src/core/access/actor-model.ts b/src/core/access/actor-model.tsindex af4ebad99f..0d759cf491 100644--- a/src/core/access/actor-model.ts+++ b/src/core/access/actor-model.ts@@ -29,7 +29,8 @@ export const ACTOR_DEFERRED_OPS: ReadonlySet<string> = new Set([/** Canonical person ids: 1-256 visible ASCII characters (QM's credential broker rule), no case folding. */export const EXTERNAL_ID_RE = /^[\x21-\x7e]{1,256}$/;-export interface AttestRight { system: string; ops: string[] }+/** GST-1158 F3: `read` is how an attested call that names sources reads them; absent (the column unset) reads as the scope. */+export interface AttestRight { system: string; ops: string[]; read?: 'person' | 'scope' }export interface AttestedActor { system: string; external_id: string; member: string }/**@@ -42,7 +43,8 @@ export function attestRightFrom(row: Record<string, unknown> | undefined, grant:if (typeof system !== 'string' || !ATTEST_SYSTEMS.includes(system) || member != null) return null;if (grant !== 'legacy' && grant !== 'client_credentials') return null;const ops = Array.isArray(row!.attest_ops) ? (row!.attest_ops as unknown[]).filter((v): v is string => typeof v === 'string') : [...DEFAULT_ATTEST_OPS];- return { system, ops };+ const read = row!.attest_read === 'person' || row!.attest_read === 'scope' ? row!.attest_read : null;+ return { system, ops, ...(read ? { read } : {}) };}/** The verify join plus the live attest right, for AuthInfo (a verifier spreads the result). */diff --git a/src/core/access/actor.ts b/src/core/access/actor.tsindex 0c373aa93e..8d39eae752 100644--- a/src/core/access/actor.ts+++ b/src/core/access/actor.ts@@ -46,12 +46,12 @@ export async function attestRightOf(engine: Pick<BrainEngine, 'executeRaw'>, caltry {if (principal?.kind === 'legacy_token') {const [row] = await engine.executeRaw<Record<string, unknown>>(- 'SELECT attest_actor, attest_ops, member_id FROM access_tokens WHERE id::text = $1 AND revoked_at IS NULL', [principal.id]);+ `SELECT attest_actor, attest_ops, to_jsonb(access_tokens)->>'attest_read' AS attest_read, member_id FROM access_tokens WHERE id::text = $1 AND revoked_at IS NULL`, [principal.id]);return attestRightFrom(row, 'legacy', row?.member_id);}if (principal?.kind === 'oauth_client') {const [row] = await engine.executeRaw<Record<string, unknown>>(- `SELECT attest_actor, attest_ops, member_id, grant_types, client_secret_hash IS NOT NULL AS confidential FROM oauth_clients+ `SELECT attest_actor, attest_ops, to_jsonb(oauth_clients)->>'attest_read' AS attest_read, member_id, grant_types, client_secret_hash IS NOT NULL AS confidential FROM oauth_clientsWHERE client_id = $1 AND (to_jsonb(oauth_clients)->>'deleted_at') IS NULL`, [principal.id]);const cc = Array.isArray(row?.grant_types) && (row!.grant_types as unknown[]).includes('client_credentials') && row!.confidential === true;return attestRightFrom(row, cc ? 'client_credentials' : null, row?.member_id);@@ -134,6 +134,10 @@ export function actorNotAttested(reason: ActorReason, caller: ActorCaller, ctx:return opError('actor_not_attested', `The ${ACTOR_ARGUMENT} argument is accepted only on an attested call, so nothing was read or written.`,`Remove ${ACTOR_ARGUMENT} from the arguments. A trusted system names the person in the ${ACTOR_HEADER} header from a credential holding the attest right (gbrain auth rescope ... --attest-actor qm on the brain host).`, { reason, docs });case 'actor_required':+ if (ctx.right?.read === 'scope') {+ return opError('actor_not_attested', `This credential reads and writes only for an attested person (--attest-read scope), and this call names none (no ${ACTOR_HEADER} header), so nothing was read or written.`,+ `Send ${ACTOR_HEADER} with the person's canonical id on every call from this credential. A call that serves nobody in particular uses a credential without the attest right.`, { reason, docs });+ }return opError('actor_not_attested', `${ctx.op} writes only as an attested person, and this call names none (no ${ACTOR_HEADER} header on a credential holding the attest right), so nothing was written.`,`Send ${ACTOR_HEADER} with the person's canonical id from a credential the brain operator granted the attest right (${rescope(['--attest-actor', 'qm']).join(' ')}). To save a fact as yourself, call remember.`, { reason, docs });case 'audience_not_supported':@@ -224,19 +228,23 @@ export interface ActorChannels { header?: string | null; audience?: string | nul/*** The attested-actor decision for one remote call, made before any work. Null when the call names no actor (no header,- * no argument): the caller's own identity or B's audience applies. Otherwise the access record and the arguments with+ * no argument): the caller's own identity or B's audience applies; GST-1158 F4: a credential whose attest right says+ * `attest_read = 'scope'` is refused there instead (actor_required), so it never reads as itself. Otherwise the access record and the arguments with* `acting_user` stripped, or a refusal: actor_not_attested with its reason, actor_unlinked, or B's* on_behalf_of_invalid_audience when an on_behalf_of audience is asserted too.*/export async function resolveAttestedActor(engine: Pick<BrainEngine, 'executeRaw'>, input: {channels?: ActorChannels; params: Record<string, unknown> | undefined; op: string; opShape: AttestableOpShape | undefined;auth?: ActorCaller['auth']; transport?: string; audienceAsserted: boolean;-}): Promise<{ actor?: AttestedActor; access?: Partial<CallerAccess>; params: Record<string, unknown> } | null> {+}): Promise<{ actor?: AttestedActor; access?: Partial<CallerAccess>; params: Record<string, unknown>; read?: AttestRight['read'] } | null> {const header = input.channels?.header ?? undefined;const hasArgument = !!input.params && Object.prototype.hasOwnProperty.call(input.params, ACTOR_ARGUMENT);const caller: ActorCaller = { auth: input.auth };if (input.channels?.audience != null) throw actorNotAttested('audience_not_supported', caller, { op: input.op, transport: input.transport });- if (header === undefined && !hasArgument) return null;+ if (header === undefined && !hasArgument) {+ if (input.transport !== 'stdio' && input.auth?.attest?.read === 'scope') throw actorNotAttested('actor_required', caller, { op: input.op, transport: input.transport, right: input.auth.attest });+ return null;+ }const ctx = { op: input.op, transport: input.transport };const argument = hasArgument ? input.params![ACTOR_ARGUMENT] : undefined;if ((header !== undefined && !EXTERNAL_ID_RE.test(header)) || (hasArgument && (typeof argument !== 'string' || !EXTERNAL_ID_RE.test(argument)))) {@@ -258,7 +266,7 @@ export async function resolveAttestedActor(engine: Pick<BrainEngine, 'executeRawconst covered = await actorCoverage(engine, caller, { system: right.system, external_id: header }, input.transport);const actor: AttestedActor = { system: right.system, external_id: header, member: covered.member };const { [ACTOR_ARGUMENT]: _stripped, ...params } = input.params ?? {};- return { actor, access: await attestedCallerAccess(engine, actor, covered.identity), params };+ return { actor, access: await attestedCallerAccess(engine, actor, covered.identity), params, ...(right.read ? { read: right.read } : {}) };}/**diff --git a/src/core/access/members.ts b/src/core/access/members.tsindex c9778bba91..0e8f39addc 100644--- a/src/core/access/members.ts+++ b/src/core/access/members.ts@@ -288,9 +288,9 @@ export function parseMemberFlag(raw: string): string | null {return raw.trim() === 'none' ? null : assertAccessId(raw);}-/** GST-359 C1: attestActor names the system whose actor header this credential may send (null clears it and attestOps). */-export interface BindingPatch { member?: string | null; mayActFor?: string[] | null; attestActor?: string | null; attestOps?: string[] | null }-export interface BindingResult { member: string | null; may_act_for: string[] | null; attest_actor?: string; attest_ops?: string[] | null; changed: boolean }+/** GST-359 C1: attestActor names the system whose actor header this credential may send (null clears it, attestOps and attestRead). */+export interface BindingPatch { member?: string | null; mayActFor?: string[] | null; attestActor?: string | null; attestOps?: string[] | null; attestRead?: 'person' | 'scope' | null }+export interface BindingResult { member: string | null; may_act_for: string[] | null; attest_actor?: string; attest_ops?: string[] | null; attest_read?: 'person' | 'scope' | null; changed: boolean }function attestRefused(message: string, suggestion: string): OperationError {return opError('invalid_params', message, suggestion, { why: 'Only a credential bound to no member that authenticates as itself (a client-credentials client with a secret, or a legacy token) may name the people a trusted system serves.' });@@ -305,8 +305,8 @@ export async function bindCredential(engine: BrainEngine, target: { kind: 'tokenif (patch.member != null) await requireEnabledMember(engine, patch.member);const table = target.kind === 'token' ? 'access_tokens' : 'oauth_clients';const key = target.kind === 'token' ? 'id::text' : 'client_id';- const [before] = await engine.executeRaw<{ member_id: string | null; may_act_for: string[] | null; attest_actor: string | null; attest_ops: string[] | null; grant_types?: string[] | null; confidential?: boolean }>(- `SELECT member_id, may_act_for, attest_actor, attest_ops${target.kind === 'client' ? ', grant_types, client_secret_hash IS NOT NULL AS confidential' : ''} FROM ${table} WHERE ${key} = $1`, [target.id]);+ const [before] = await engine.executeRaw<{ member_id: string | null; may_act_for: string[] | null; attest_actor: string | null; attest_ops: string[] | null; attest_read: 'person' | 'scope' | null; grant_types?: string[] | null; confidential?: boolean }>(+ `SELECT member_id, may_act_for, attest_actor, attest_ops, attest_read${target.kind === 'client' ? ', grant_types, client_secret_hash IS NOT NULL AS confidential' : ''} FROM ${table} WHERE ${key} = $1`, [target.id]);if (!before) {throw opError('invalid_params', `No ${target.kind === 'token' ? 'token' : 'OAuth client'} "${target.id}" exists.`,target.kind === 'token' ? 'List tokens with gbrain auth list.' : 'List clients with gbrain auth clients --json.');@@ -315,8 +315,10 @@ export async function bindCredential(engine: BrainEngine, target: { kind: 'tokenconst mayActFor = patch.mayActFor === undefined ? before.may_act_for : patch.mayActFor;const attestActor = patch.attestActor === undefined ? before.attest_actor : patch.attestActor;const attestOps = attestActor === null ? null : patch.attestOps === undefined ? before.attest_ops : patch.attestOps;+ const attestRead = attestActor === null ? null : patch.attestRead === undefined ? before.attest_read : patch.attestRead;const what = target.kind === 'token' ? 'This token' : `OAuth client ${target.id}`;if (patch.attestOps != null && attestActor === null) throw attestRefused('--attest-ops needs the attest right.', 'Pass --attest-actor qm with it.');+ if (patch.attestRead != null && attestActor === null) throw attestRefused('--attest-read needs the attest right.', 'Pass --attest-actor qm with it.');const deferred = (patch.attestOps ?? []).filter(op => ACTOR_DEFERRED_OPS.has(op));if (deferred.length) throw attestRefused(`--attest-ops names ${deferred.join(', ')}, which an attested actor cannot run yet.`, `Leave them out. Not attestable yet: ${[...ACTOR_DEFERRED_OPS].join(', ')}.`);if (attestActor !== null && (patch.attestActor !== undefined || patch.member !== undefined)) {@@ -327,12 +329,12 @@ export async function bindCredential(engine: BrainEngine, target: { kind: 'token}}const changed = member !== before.member_id || JSON.stringify(mayActFor ?? null) !== JSON.stringify(before.may_act_for ?? null)- || attestActor !== before.attest_actor || JSON.stringify(attestOps ?? null) !== JSON.stringify(before.attest_ops ?? null);+ || attestActor !== before.attest_actor || JSON.stringify(attestOps ?? null) !== JSON.stringify(before.attest_ops ?? null) || (attestRead ?? null) !== (before.attest_read ?? null);if (changed && !opts.dryRun) {- await engine.executeRaw(`UPDATE ${table} SET member_id = $2, may_act_for = $3::text[], attest_actor = $4, attest_ops = $5::text[] WHERE ${key} = $1`,- [target.id, member, mayActFor, attestActor, attestOps]);+ await engine.executeRaw(`UPDATE ${table} SET member_id = $2, may_act_for = $3::text[], attest_actor = $4, attest_ops = $5::text[], attest_read = $6 WHERE ${key} = $1`,+ [target.id, member, mayActFor, attestActor, attestOps, attestRead ?? null]);}- return { member, may_act_for: mayActFor ?? null, ...(attestActor ? { attest_actor: attestActor, attest_ops: attestOps ?? null } : {}), changed };+ return { member, may_act_for: mayActFor ?? null, ...(attestActor ? { attest_actor: attestActor, attest_ops: attestOps ?? null, attest_read: attestRead ?? null } : {}), changed };}/** A credential bound to a member that cannot read: verification refuses it. */diff --git a/src/core/access/scope-read.ts b/src/core/access/scope-read.tsnew file mode 100644index 0000000000..c3cdbfbf62--- /dev/null+++ b/src/core/access/scope-read.ts@@ -0,0 +1,60 @@+/**+ * GST-1158 E1: the scope read. An attested call (access/actor.ts) to an operation in SCOPE_READ_OPS that names+ * `source_id` or `source_ids` runs under SCOPE_READ_ACCESS: no member identity, actor or audience, so no member page+ * and no restricted page is read, and privacy is never relaxed. The record only takes identity away, so a scope read+ * only ever hides. A credential whose attest right says `attest_read = 'person'` (F3) narrows to the named sources but+ * reads as the person. `__all__` and `all_sources` are refused under scope, so a scope read always names its sources.+ * Everything lives in the database, so a repo-less brain gets it unchanged.+ */+import { AsyncLocalStorage } from 'node:async_hooks';+import { opError, type OperationError } from '../ops/contract.ts';+import { ALL_SOURCES } from '../source-id.ts';+import type { CallerAccess } from '../search/private-visibility.ts';++/** GST-1094: the caller record of a scope read. It is read as the scope, never as the person. */+export const SCOPE_READ_ACCESS: Partial<CallerAccess> = {+ identity: [], audienceIdentities: [], audience: null, actor: null, satisfiedRuleIds: [], folderCoverage: [], privateReadableSources: [],+ hidePrivate: true, applyRemoteReadPolicy: false, restricted: true, remotePolicy: { privacyRelaxed: false, restricted: true },+};++/** GST-1158 E1: the reads an attested call that names sources runs as the scope. context_pack stays out until it is confined to the named sources. */+export const SCOPE_READ_OPS: ReadonlySet<string> = new Set([+ 'memory_recall', 'get_page', 'entity', 'whois', 'get_backlinks', 'get_timeline', 'find_experts', 'volunteer_context', 'query',+]);++export type ReadMode = 'scope' | 'person';+const readModeStore = new AsyncLocalStorage<ReadMode>();++/** How the current attested call reads its named sources; undefined when dispatch decided nothing (no attested call naming sources, or another door). */+export function currentReadMode(): ReadMode | undefined {+ return readModeStore.getStore();+}++export function withReadMode<T>(mode: ReadMode | null, fn: () => T): T {+ return mode ? readModeStore.run(mode, fn) : fn();+}++function namesSources(params: Record<string, unknown> | undefined): boolean {+ const id = params?.source_id;+ const ids = params?.source_ids;+ return (id !== undefined && id !== null && id !== '')+ || (Array.isArray(ids) ? ids.length > 0 : typeof ids === 'string' ? ids.trim() !== '' : ids !== undefined && ids !== null);+}++/**+ * The read mode of one attested call: 'scope' or 'person' when the operation is in SCOPE_READ_OPS and the call names+ * sources, else null. A scope read that asks for every source (`__all__`, `all_sources`) is refused with invalid_params.+ */+export function attestedReadMode(op: string, params: Record<string, unknown> | undefined, attestRead: ReadMode | null | undefined): ReadMode | null {+ if (!SCOPE_READ_OPS.has(op) || !namesSources(params)) return null;+ if (attestRead === 'person') return 'person';+ const ids = params?.source_ids;+ if (params?.source_id === ALL_SOURCES || params?.all_sources === true || (Array.isArray(ids) && ids.includes(ALL_SOURCES))) throw scopeAllSourcesRefused(op);+ return 'scope';+}++function scopeAllSourcesRefused(op: string): OperationError {+ return opError('invalid_params', `${op}: a call that names sources reads them as their audience, so '${ALL_SOURCES}' and all_sources are refused. Nothing was read.`,+ 'Name the sources to read in source_id or source_ids, or leave them out to read as the person.',+ { why: 'A scope read must name exactly the sources it reads, so it never widens past the scope the turn serves.' });+}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 228296895c..43af8b1859 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1415,6 +1415,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', id: 'memory_recall_scope_read_gst1094', text: '`memory_recall` now takes `source_id` and `source_ids`. A call that names sources reads as their audience, never as the attested person: no own recent facts first and no fact from any member page; a page restricted to named readers stays hidden and `visibility: private` is never relaxed. A source outside the credential\'s read grant is refused (`permission_denied`) and `__all__` is refused (`invalid_params`). Without sources, `memory_recall` is unchanged. The contract is `docs/contracts/qm-memory-provider/v2.json`; `v1.json` is unchanged.' },{ since: 'TBD', id: 'member_bound_acting_user_gst900', text: 'A credential bound to a member may now send `acting_user` with no `x-qm-actor` header: its own member id, or a canonical id linked to that member, is dropped and the call runs exactly as the credential; any other value is refused (`actor_not_attested` reason `argument_mismatch`). A credential bound to no member is still refused (`argument_without_attestation`).' },{ since: 'TBD', id: 'recall_max_chars_harn15', text: '`recall` now takes `max_chars` (a whole number from 200 to 12000, as `memory_recall`): it keeps the whole facts, then results, whose text fits, adds no marker and returns `truncated`; without it `recall` is unchanged.' },+ { since: 'TBD', id: 'attest_scope_read_ops_gst1158', text: 'An attested call (`x-qm-actor`) to `get_page`, `entity`, `whois`, `get_backlinks`, `get_timeline`, `find_experts`, `volunteer_context` or `query` that names `source_id` or `source_ids` now reads as those sources\' audience, as `memory_recall` already did: the person\'s pages restricted to named readers and their member page `memory/members/<member>` read as missing, a source outside the credential\'s read grant is refused, and `__all__` or `all_sources` beside a named source is refused (`invalid_params`). `get_timeline` gains `source_id` and `source_ids`, `find_experts` and `volunteer_context` gain `source_ids`, and `volunteer_context` refuses `stats: true` under that read. `gbrain auth rescope --attest-read person|scope|none` sets how an attest credential reads named sources: `person` narrows to them but reads as the person; `scope` reads them as their audience and refuses every call that names no person (`actor_not_attested` reason `actor_required`), reading nothing; unset (the default) keeps the scope read and still serves calls that name no person. `gbrain doctor` warns (`attest_read_shared_scope`) when a person credential reads a source another attest credential reads as the scope.' },{ since: 'TBD', id: 'attest_direct_page_writes_deferred_gst1158', text: 'An attested call (`x-qm-actor`) may no longer run `add_timeline_entry`, `add_link`, `put_page` or `edit_page`: they write pages every reader of the page sees, so they wait for owner-approved proposals. `gbrain auth rescope --attest-ops` refuses a list that names one, a credential whose list already names one is refused for it on every attested call (`actor_not_attested`, reason `op_not_attested`), and a queued attested write of one fails when it publishes. Unattested calls and member-bound credentials are unchanged.' },{ since: 'TBD', id: 'unknown_param_meta_only_harn15', text: 'A read that ignores a parameter the tool does not declare (`mcp.strict_params` `warn`, the default) no longer adds a `[gbrain notice unknown_param kind=info]` text block to the result: the warning is only in `_meta.warnings` (`{code: \'unknown_param\', param, suggestion?}`), so a harness that stores tool output in its turns never stores it. Writes still refuse unknown parameters, and `reject` mode is unchanged.' },];diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 0b077b701b..7345de7860 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -14,13 +14,13 @@// (help-text mentions count): accepting an ignored flag is the pre-#2185// status quo; missing a real one breaks working invocations.export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {- 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--approved', '--as', '--attest-actor', '--attest-ops', '--bind-token', '--brain', '--client', '--dry-run', '--expect', '--file', '--grant-types', '--groups', '--help', '--http', '--id', '--if-version', '--json', '--limit', '--may-act-for', '--member', '--members', '--migrate-legacy', '--name', '--operation', '--operations', '--prefix', '--private-pages', '--qm', '--readers', '--refresh-operations', '--reset-default', '--revision', '--scopes', '--source', '--sources', '--takes-holders', '--to', '--token', '--tools-json', '--yes'],+ 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--bind-token', '--brain', '--client', '--dry-run', '--expect', '--file', '--grant-types', '--groups', '--help', '--http', '--id', '--if-version', '--json', '--limit', '--may-act-for', '--member', '--members', '--migrate-legacy', '--name', '--operation', '--operations', '--prefix', '--private-pages', '--qm', '--readers', '--refresh-operations', '--reset-default', '--revision', '--scopes', '--source', '--sources', '--takes-holders', '--to', '--token', '--tools-json', '--yes'],'advisor': ['--apply', '--brain', '--help', '--json', '--skills-dir', '--source', '--workspace', '--yes'],'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],'anomalies': ['--all', '--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--request-id', '--sigma', '--since', '--source'],'append': ['--brain', '--expect-tail', '--expected-revision', '--file', '--force', '--help', '--json', '--region', '--request-id', '--separator', '--source'],'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--install', '--json', '--legacy-lock', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--only', '--path', '--prefer-postgres', '--probe', '--repo', '--require-db', '--skip-verify', '--source', '--statement-timeout', '--uninstall', '--url', '--yes'],- 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--allowed-operations', '--apply', '--attest-actor', '--attest-ops', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expect', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--may-act-for', '--member', '--members', '--migrate-legacy', '--min-trust', '--no-pull', '--operation', '--operations', '--origin', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--private-pages', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retire', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--unsettle', '--usage', '--wait', '--warn-only', '--yes'],+ 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--allowed-operations', '--apply', '--attest-actor', '--attest-ops', '--attest-read', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expect', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--may-act-for', '--member', '--members', '--migrate-legacy', '--min-trust', '--no-pull', '--operation', '--operations', '--origin', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--private-pages', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retire', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--unsettle', '--usage', '--wait', '--warn-only', '--yes'],'autopilot': ['--apply', '--batch', '--brain', '--channel', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--pause', '--phase', '--quiet', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--restart-only', '--resume', '--retry-global', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],'backup': ['--accept-pending', '--as', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--purge-mirror', '--quiet', '--restore-only', '--source', '--timeout', '--timings', '--wait'],@@ -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-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--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', '--attest-actor', '--attest-ops', '--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', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--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', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--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', '--instructions', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--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-instructions', '--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', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--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', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--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', '--source-ids', '--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', '--unsettle', '--unshallow', '--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-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--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', '--attest-actor', '--attest-ops', '--attest-read', '--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', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--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', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--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', '--instructions', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--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-instructions', '--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', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--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', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--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', '--source-ids', '--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', '--unsettle', '--unshallow', '--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', '--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', '--gbrain-bin', '--get', '--harness', '--help', '--instructions', '--instructions-only', '--jq', '--json', '--limit', '--name-only', '--no-instructions', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--workspace', '--yes'],'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--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', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--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', '--grammar', '--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', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--link', '--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-hooks', '--no-instructions', '--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', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--shared-skills', '--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', '--unsettle', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'init': ['--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--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', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--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', '--grammar', '--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', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--link', '--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-hooks', '--no-instructions', '--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', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--shared-skills', '--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', '--unsettle', '--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', '--assign-corpus', '--attest-actor', '--attest-ops', '--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', '--clear', '--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', '--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', '--qm', '--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', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--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', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--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', '--admin-intent', '--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', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-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', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--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', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--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', '--session', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--yes'],+ 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--attest-read', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--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', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--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', '--session', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--yes'],'mcp': ['--admin-token-file', '--advertise', '--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'],@@ -114,25 +114,25 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--as', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--cursor', '--cwd', '--day', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--principal', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--rules', '--run', '--scopes', '--seat', '--session', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],'repair-jsonb': ['--accept-pending', '--as', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--attest-actor', '--attest-ops', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--private-pages', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--attest-actor', '--attest-ops', '--attest-read', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--private-pages', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],'retrieval-upgrade': ['--accept-pending', '--all', '--as', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--timings', '--to', '--wait', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--request-id', '--slug-prefix', '--source'],'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--path', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],'self-upgrade': ['--apply', '--brain', '--channel', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],- 'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--advertise', '--all-new', '--apply-rewrites', '--attest-actor', '--attest-ops', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--may-act-for', '--member', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--private-pages', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],+ 'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--advertise', '--all-new', '--apply-rewrites', '--attest-actor', '--attest-ops', '--attest-read', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--may-act-for', '--member', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--private-pages', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],'setup': ['--accept-capabilities', '--advertise', '--agent', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--force', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--link', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--runtime', '--save', '--scope', '--source', '--source-ids', '--surface', '--token', '--url', '--workspace', '--yes'],'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--loop', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],'skillpack-check': ['--accept-pending', '--as', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--timings', '--wait', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--as', '--attest-actor', '--attest-ops', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--channels', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--lookback-days', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--max-requests', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--private-pages', '--probe', '--profile', '--progress-interval', '--progress-json', '--provider', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--rebase', '--record', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--skip', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--sync-interval-min', '--takes-holders', '--timeout', '--timezone', '--timings', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--transcript', '--unindexed', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--visibility', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--channels', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--lookback-days', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--max-requests', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--private-pages', '--probe', '--profile', '--progress-interval', '--progress-json', '--provider', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--rebase', '--record', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--skip', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--sync-interval-min', '--takes-holders', '--timeout', '--timezone', '--timings', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--transcript', '--unindexed', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--visibility', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--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', '--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', '--clear', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--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', '--grammar', '--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', '--input', '--install', '--instructions-only', '--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-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--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', '--session', '--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', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--workspace', '--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', '--attest-read', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--clear', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--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', '--grammar', '--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', '--input', '--install', '--instructions-only', '--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-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--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', '--session', '--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', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--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/deletion-inventory.ts b/src/core/deletion-inventory.tsindex 5260f9eca3..4a349b72d5 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -44,7 +44,7 @@ const ROWS: readonly Row[] = [['access_policy_revisions', 'out_of_scope', 'no_memory_text', 'source_id rules digest origin proposed_by approved_by change_kind operation_id'],['access_policy_state', 'out_of_scope', 'no_memory_text', 'source_id'],['access_rules', 'out_of_scope', 'no_memory_text', 'source_id rule_id prefix readable_by created_by'],- ['access_tokens', 'out_of_scope', 'secret_material', 'name token_hash scopes permissions source_grant source_id federated_read allowed_operations takes_holders min_trust private_pages member_id may_act_for attest_actor attest_ops'],+ ['access_tokens', 'out_of_scope', 'secret_material', 'name token_hash scopes permissions source_grant source_id federated_read allowed_operations takes_holders min_trust private_pages member_id may_act_for attest_actor attest_ops attest_read'],['belief_events', 'swept', 'belief_ledger', 'event_key source_id slug subject_kind subject_key event_type origin trust_tier writer_tier tier_basis visibility value value_hash prior_hash state_hash cause claim_fp redacted_fields'],['belief_page_lifetimes', 'out_of_scope', 'text_free_ledger', 'source_id slug'],['belief_redactions', 'out_of_scope', 'text_free_ledger', 'source_id subject_key field field_hash released_hash'],@@ -114,7 +114,7 @@ const ROWS: readonly Row[] = [['minion_lease_pressure_log', 'out_of_scope', 'no_memory_text', 'lease_key queue_name job_name model provider'],['minion_self_fix_log', 'out_of_scope', 'no_memory_text', 'classifier_bucket policy_applied outcome'],['needs_rederive', 'out_of_scope', 'text_free_ledger', 'derived_table derived_id source_id reason'],- ['oauth_clients', 'out_of_scope', 'secret_material', 'client_id client_secret_hash client_name redirect_uris grant_types scope token_endpoint_auth_method source_id federated_read bound_tools bound_source_id bound_brain_id bound_slug_prefixes surface surface_set_by allowed_operations delegated_slug_prefixes delegated_namespace grant_profile grant_repair_reasons source_grant takes_holders min_trust registered_via private_pages member_id may_act_for attest_actor attest_ops'],+ ['oauth_clients', 'out_of_scope', 'secret_material', 'client_id client_secret_hash client_name redirect_uris grant_types scope token_endpoint_auth_method source_id federated_read bound_tools bound_source_id bound_brain_id bound_slug_prefixes surface surface_set_by allowed_operations delegated_slug_prefixes delegated_namespace grant_profile grant_repair_reasons source_grant takes_holders min_trust registered_via private_pages member_id may_act_for attest_actor attest_ops attest_read'],['oauth_codes', 'out_of_scope', 'secret_material', 'code_hash client_id scopes code_challenge code_challenge_method redirect_uri state resource'],['oauth_grant_audit', 'out_of_scope', 'no_memory_text', 'client_id actor action before_grant after_grant'],['oauth_tokens', 'out_of_scope', 'secret_material', 'token_hash token_type client_id scopes resource grant_type'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 0513efa87e..2a674ffac5 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -97,6 +97,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['access_policy_store_mismatch',// GBRA-231: shared agents (doctor/checks/shared-agent-access.ts).'access_may_act_for_wildcard',+ // GST-1158 F3: attest credentials that read a shared-scope source as the person (doctor/checks/attest-read-access.ts).+ 'attest_read_shared_scope','extractor_facts_expired','loop_facts_drift','ontology_facts_fenced',diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex d81f674ea9..a2bad534f6 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -2469,6 +2469,17 @@ export const OPERATION_MANIFEST: OperationMeta[] = [],"description": "Lowest trust tier to return (the connection floor still applies).","fullSurfaceOnly": true+ },+ "source_id": {+ "type": "string",+ "description": "Read only this source."+ },+ "source_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Narrow to these sources (omit or [] for all you can read)."}},"scope": "read",@@ -5450,6 +5461,13 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["days": {"type": "number","description": "Stats window in days (default 30; stats mode only)."+ },+ "source_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Narrow to these sources (omit or [] for all you can read)."}},"cliHints": {@@ -6325,6 +6343,13 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["explain": {"type": "boolean","description": "Include factor breakdown per result (expertise, recency, salience)."+ },+ "source_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Narrow to these sources (omit or [] for all you can read)."}},"cliHints": {diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 1477396e24..cb9a61b7ac 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -303,10 +303,10 @@ export interface AuthInfo {mayActFor?: string[] | null;/*** GST-359 C1: the live right to name the person a call serves (x-qm-actor), joined by the verifier: the system and- * the operations an attested call may run. Null when the credential holds none, is bound to a member, or (an OAuth+ * the operations an attested call may run, and (GST-1158 F3) how it reads named sources. Null when the credential holds none, is bound to a member, or (an OAuth* client) its token did not come from the client-credentials grant. Undefined when no verifier joined it.*/- attest?: { system: string; ops: string[] } | null;+ attest?: { system: string; ops: string[]; read?: 'person' | 'scope' } | null;/*** Human-readable agent name resolved at token-verification time.* For OAuth clients this is `oauth_clients.client_name`; for legacydiff --git a/src/core/ops/insights.ts b/src/core/ops/insights.tsindex b7654e6f20..f3f233e259 100644--- a/src/core/ops/insights.ts+++ b/src/core/ops/insights.ts@@ -18,6 +18,8 @@ import type { Operation } from './contract.ts';import { opError } from './contract.ts';import { invalidParam, paramUse } from './op-fix.ts';import { federatedSearchScope, sourceScopeOpts, readPolicyOpts } from './context.ts';+import { parseSourceIdsParam, requestSourceScope, SOURCE_IDS_PARAM } from './search-source-scope.ts';+import { currentReadMode } from '../access/scope-read.ts';import {FIND_EXPERTS_DESCRIPTION,FIND_CONTRADICTIONS_DESCRIPTION,@@ -69,10 +71,17 @@ const volunteer_context: Operation = {'APPROXIMATE: "used" = pages.last_retrieved_at > volunteered_at.',},days: { type: 'number', description: 'Stats window in days (default 30; stats mode only).' },+ source_ids: SOURCE_IDS_PARAM,},handler: async (ctx, p) => {const { parseWindow, volunteerContext, volunteerUsageStats } = await import('../context/volunteer.ts');- const scope = sourceScopeOpts(ctx);+ // GST-1158 E1: under the scope record the stats summary (volunteering across whole sources) is refused.+ const asScope = currentReadMode() === 'scope';+ if (p.stats === true && asScope) {+ throw invalidParam(ctx, 'volunteer_context', 'stats', '`stats` summarizes volunteering across whole sources, so a call that names sources as their audience cannot ask for it.', { example: false });+ }+ const named = parseSourceIdsParam(ctx, 'volunteer_context', p.source_ids);+ const scope = named === undefined ? sourceScopeOpts(ctx) : await requestSourceScope(ctx, undefined, named);const sourceIds = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : ['default']);if (p.stats === true) {@@ -100,7 +109,7 @@ const volunteer_context: Operation = {// surname) — file-plane gate, threaded per ResolvePointersOpts.lexicalArms: lexicalArmsEnabled(loadCfgForArms()),// N8-1: the same private-page gate remote search applies.- excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote),+ excludePrivate: asScope || await resolveExcludePrivatePages(ctx.engine, ctx.remote),// #5575: token floor + min_trust + activation control (CEO-20, DX-10).eligibility: await proactiveEligibility(ctx, 'volunteer', { minTrust: p.min_trust }),onWithheld: keys => { for (const k of keys) withheldKeys.add(k); },@@ -158,6 +167,7 @@ const find_experts: Operation = {type: 'boolean',description: 'Include factor breakdown per result (expertise, recency, salience).',},+ source_ids: SOURCE_IDS_PARAM,},handler: async (ctx, p) => {const { findExperts } = await import('../../commands/whoknows.ts');@@ -177,7 +187,8 @@ const find_experts: Operation = {const { loadActivePackBestEffort, expertTypesFromPack } = await import('../schema-pack/index.ts');const pack = await loadActivePackBestEffort(ctx);const types = pack ? expertTypesFromPack(pack.manifest) : [];- const scope = await readPolicyOpts(ctx);+ const sourceIds = parseSourceIdsParam(ctx, 'find_experts', p.source_ids);+ const scope = await readPolicyOpts(ctx, sourceIds === undefined ? undefined : await requestSourceScope(ctx, undefined, sourceIds));const experts = await findExperts(ctx.engine, {topic,limit: typeof p.limit === 'number' ? p.limit : undefined,diff --git a/src/core/ops/qm-memory.ts b/src/core/ops/qm-memory.tsindex b73e73d702..19d69fb085 100644--- a/src/core/ops/qm-memory.ts+++ b/src/core/ops/qm-memory.ts@@ -23,7 +23,8 @@ import { federatedSearchScope, parseSourceIdParam } from './context.ts';import { parseSourceIdsParam, requestSourceScope, SOURCE_IDS_PARAM } from './search-source-scope.ts';import type { FactRow } from '../engine.ts';import { resolveReadEligibility } from '../eligibility/policy.ts';-import { currentCallerAccess, resolveExcludePrivatePages, withCallerAccess, type CallerAccess } from '../search/private-visibility.ts';+import { currentCallerAccess, resolveExcludePrivatePages, withCallerAccess } from '../search/private-visibility.ts';+import { currentReadMode, SCOPE_READ_ACCESS } from '../access/scope-read.ts';import { callerMember, memberPageSlug } from '../access/member-facts.ts';import { ACTOR_ARGUMENT, ACTOR_HEADER } from '../access/actor-model.ts';import { uuidV5 } from '../persistence/preconditions.ts';@@ -118,16 +119,6 @@ async function ownRecentFacts(ctx: OperationContext, sources: string[], read: Rereturn lists.flat().sort((a, b) => b.created_at.getTime() - a.created_at.getTime() || b.id - a.id).slice(0, MEMORY_RECALL_ARM_LIMIT);}-/**- * GST-1094: the caller record of a recall that names sources. It is read as the scope, never as the person: no member- * identity, actor or audience, so no member-page fact is admitted and every restricted page is hidden, and privacy is- * never relaxed.- */-const SCOPE_READ_ACCESS: Partial<CallerAccess> = {- identity: [], audienceIdentities: [], audience: null, actor: null, satisfiedRuleIds: [], folderCoverage: [], privateReadableSources: [],- hidePrivate: true, applyRemoteReadPolicy: false, restricted: true, remotePolicy: { privacyRelaxed: false, restricted: true },-};-/** The sources a recall reads and whether it names them; a named recall whose sources intersect to none reads nothing. */async function recallSources(ctx: OperationContext, p: Record<string, unknown>): Promise<{ sources: string[]; named: boolean }> {const sourceIdParam = parseSourceIdParam(p.source_id, 'memory_recall');@@ -179,7 +170,8 @@ const memory_recall: Operation = {handler: async (ctx, p) => {const { query, maxChars } = recallArguments(p);const { sources, named } = await recallSources(ctx, p);- if (!named || ctx.remote === false) return recallFacts(ctx, query, maxChars, sources, named);+ const mode = currentReadMode();+ if (!named || ctx.remote === false || mode) return recallFacts(ctx, query, maxChars, sources, named && mode !== 'person');return withCallerAccess(SCOPE_READ_ACCESS, () => recallFacts(ctx, query, maxChars, sources, true));},};diff --git a/src/core/ops/search-source-scope.ts b/src/core/ops/search-source-scope.tsindex 49b50a74cd..c5f3dcdb29 100644--- a/src/core/ops/search-source-scope.ts+++ b/src/core/ops/search-source-scope.ts@@ -26,7 +26,7 @@ export const SOURCE_IDS_PARAM = {};/** `source_ids` as distinct, trimmed source ids; undefined when absent. */-export function parseSourceIdsParam(ctx: OperationContext, tool: 'search' | 'query' | 'recall' | 'list_pages' | 'memory_recall', raw: unknown): string[] | undefined {+export function parseSourceIdsParam(ctx: OperationContext, tool: 'search' | 'query' | 'recall' | 'list_pages' | 'memory_recall' | 'get_timeline' | 'find_experts' | 'volunteer_context', raw: unknown): string[] | undefined {if (raw === undefined || raw === null) return undefined;// #5390: OpenAI-family MCP clients fill every optional param with an empty value; [] and a blank string mean absent.if (Array.isArray(raw) && raw.length === 0) return undefined;diff --git a/src/core/ops/timeline.ts b/src/core/ops/timeline.tsindex 72e0bca21b..259ef083e9 100644--- a/src/core/ops/timeline.ts+++ b/src/core/ops/timeline.ts@@ -10,7 +10,8 @@ import { MERGE_PRECONDITION_PARAMS, WRITE_REQUEST_PARAM } from '../persistence/pimport { opError, type Operation } from './contract.ts';import { opTransport } from './op-fix.ts';-import { readPolicyOpts } from './context.ts';+import { parseSourceIdParam, readPolicyOpts } from './context.ts';+import { parseSourceIdsParam, requestSourceScope, SOURCE_IDS_PARAM } from './search-source-scope.ts';import { MIN_TRUST_PARAM, resolveReadEligibility } from '../eligibility/policy.ts';import { stampRowTrust } from '../eligibility/stamp.ts';import { quoteTimelineRows } from './timeline-quote.ts';@@ -86,11 +87,18 @@ const get_timeline: Operation = {until: { type: 'string', description: 'Alias for before; accepted for agent callers' },limit: { type: 'number', description: 'Maximum number of timeline entries to return' },min_trust: MIN_TRUST_PARAM,+ source_id: { type: 'string', description: 'Read only this source.' },+ source_ids: SOURCE_IDS_PARAM,},handler: async (ctx, p) => {// #2200: route through sourceScopeOpts so a federated grant reaches the// engine via TimelineOpts.sourceIds; scalar/unset unchanged.- const scope = await readPolicyOpts(ctx);+ // GST-1158 E1: source_id / source_ids narrow inside the grant, as search does.+ const sourceIdParam = parseSourceIdParam(p.source_id, 'get_timeline');+ const sourceIds = parseSourceIdsParam(ctx, 'get_timeline', p.source_ids);+ const named = sourceIdParam !== undefined || sourceIds !== undefined ? await requestSourceScope(ctx, sourceIdParam, sourceIds) : undefined;+ if (named?.sourceIds?.length === 0) return [];+ const scope = await readPolicyOpts(ctx, named);// #4352 remediation: a `visibility: private` page's timeline reads// exactly like a missing page's ([]) for untrusted callers — no// existence oracle.diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 1cc03f5078..7f0d6e1be8 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 286;+export const LATEST_SCHEMA_VERSION = 287;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 7bb4dcc090..3dc804572f 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -287,6 +287,7 @@ import { v283 } from './v283-folder-access-rules.ts';import { v284 } from './v284-access-page-indexes.ts';import { v285 } from './v285-slug-rename-history.ts';import { v286 } from './v286-qm-actor-links.ts';+import { v287 } from './v287-attest-read.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -572,4 +573,5 @@ export const MIGRATIONS: Migration[] = [v284,v285,v286,+ v287,];diff --git a/src/core/schema-migrations/v287-attest-read.ts b/src/core/schema-migrations/v287-attest-read.tsnew file mode 100644index 0000000000..7f4f66a08b--- /dev/null+++ b/src/core/schema-migrations/v287-attest-read.ts@@ -0,0 +1,23 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// GST-1158 F3: how an attested call that names sources reads them, a credential+// column beside attest_ops: attest_read 'person' (narrows to the named sources+// but reads as the person) or 'scope' (reads as the scope, and F4: a call that+// names no person is refused). NULL keeps the fail-closed rule (named means+// scope), so no existing credential changes. Readers read it through+// to_jsonb(row), so a schema before it reads as NULL; any other value reads as+// NULL too. Database only, so a repo-less brain gets it unchanged. Nothing is+// rewritten on upgrade. No schema.sql mirror, like v286. Numbered on the+// GBRA-284 branch; expect a renumber at the merge slot.+export const v287: Migration = {+ version: 287,+ name: 'attest_read',+ idempotent: true,+ sql: `+ALTER TABLE access_tokens ADD COLUMN IF NOT EXISTS attest_read TEXT;+ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS attest_read TEXT;+`,+};diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 1c9727cc2e..587d57f0d7 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -18,6 +18,7 @@ import { withCallerAccess } from '../core/search/private-visibility.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 { ACTOR_ARGUMENT, actorNotAttested, EXTERNAL_ID_RE, resolveAttestedActor, type ActorChannels } from '../core/access/actor.ts';+import { attestedReadMode, SCOPE_READ_ACCESS, withReadMode, type ReadMode } from '../core/access/scope-read.ts';import { qmMemoryToolResult, recallArguments, unlinkedRecallResult } from '../core/ops/qm-memory.ts';import { resolveBrainId } from '../core/brain-resolver.ts';import { getCliOptions } from '../core/cli-options.ts';@@ -923,6 +924,7 @@ export async function dispatchToolCall(let audience: AudiencePrincipal[] | null = null;let attested: Awaited<ReturnType<typeof resolveAttestedActor>> = null;let access: Awaited<ReturnType<typeof remoteCallerAccess>>;+ let readMode: ReadMode | null = null;const header = opts.actor?.header ?? undefined;const actorNamed = header !== undefined || opts.actor?.audience != null || (!!args && Object.prototype.hasOwnProperty.call(args, ACTOR_ARGUMENT));const assertion = (outcome: AudienceAuditEvent['outcome'], reason?: string) => logAudienceAssertion({ outcome, op: name,@@ -934,7 +936,9 @@ export async function dispatchToolCall(audience = parseAudience(opts.onBehalfOf);attested = await resolveAttestedActor(engine, { channels: opts.actor, params: args, op: name, opShape: op,auth: opts.auth, transport: opts.transport, audienceAsserted: audience !== null });- access = attested?.access ?? await remoteCallerAccess(engine, opts.auth, privateSources, opts.transport, audience);+ // GST-1158 E1: an attested read that names sources reads as the scope (access/scope-read.ts), or as the person on an attest_read person credential.+ readMode = attested?.actor ? attestedReadMode(name, attested.params, attested.read) : null;+ access = readMode === 'scope' ? SCOPE_READ_ACCESS : attested?.access ?? await remoteCallerAccess(engine, opts.auth, privateSources, opts.transport, audience);} catch (e) {// GST-359: a call that names a person gets every failure here (a lock timeout reading its link included) in the// envelope QM reads, never a thrown call; anything else keeps the caller's own error path.@@ -948,7 +952,7 @@ export async function dispatchToolCall(if (audience || attested?.actor) assertion('accepted');const callParams = attested ? attested.params : args;return withCallerAccess(access, async () => {- const out = await withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, callParams, resolved));+ const out = await withRequestIdentityMemo(() => withReadMode(readMode, () => dispatchResolvedCall(engine, name, callParams, 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 qmMemoryToolResult(name, out);diff --git a/test/doctor-attest-read-shared-scope.test.ts b/test/doctor-attest-read-shared-scope.test.tsnew file mode 100644index 0000000000..ee06d4f12f--- /dev/null+++ b/test/doctor-attest-read-shared-scope.test.ts@@ -0,0 +1,81 @@+/**+ * GST-1158 F3: the attest_read_shared_scope doctor check.+ *+ * 1. Protects: an attest credential set --attest-read person whose read grant includes a source another attest+ * credential reads as the scope (attest_read scope, or unset) is warned about, by name and source; nothing is changed.+ * 2. Fails when: such a credential passes as ok, a source read only by person credentials or by credentials without the+ * attest right is flagged, or the check writes anything.+ * 3. Real seams: OAuth clients and legacy tokens registered through the provider and the token service, bound with+ * bindCredential, on a repo-less brain (PGLite always, Postgres when DATABASE_URL is set).+ */+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 { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { bindCredential } from '../src/core/access/members.ts';+import { attestReadAccessEntry } from '../src/commands/doctor/checks/attest-read-access.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++for (const kind of testBackends()) {+ describe('attest_read_shared_scope doctor check (' + kind + ', repo-less)', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ const run = async () => (await attestReadAccessEntry.run({ engine } as unknown as DoctorContext) as Array<{ name: string; status: string; message: string; readiness_state?: string; details?: any }>)[0]!;+ const client = async (name: string, reads: string[], patch: Parameters<typeof bindCredential>[2] | null) => {+ const c = await provider().registerClientManual(name + '-' + randomUUID().slice(0, 8), ['client_credentials'], 'read', [], reads[0]!);+ await provider().rescopeClient(c.clientId, { federatedRead: reads });+ if (patch) await bindCredential(engine, { kind: 'client', id: c.clientId }, patch);+ return c.clientId;+ };+ const credentialRows = () => engine.executeRaw('SELECT client_id, attest_actor, attest_read, federated_read FROM oauth_clients ORDER BY client_id');++ beforeAll(async () => {+ 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(); }+ for (const id of ['source-a', 'source-room', 'source-solo']) await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [id]);+ }, 120_000);+ afterAll(async () => { await close?.(); }, 60_000);++ test('not applicable while no attest credential reads as the person; a brain category check', async () => {+ await client('scope-room', ['source-room'], { attestActor: 'qm' });+ const check = await run();+ expect({ name: check.name, status: check.status, state: check.readiness_state }).toEqual({ name: 'attest_read_shared_scope', status: 'ok', state: 'not_applicable' });+ expect(categorizeCheck('attest_read_shared_scope')).toBe('brain');+ }, 60_000);++ test('a person credential reading only sources no scope credential reads is ok, whatever plain or person credentials read', async () => {+ await client('person-solo', ['source-solo'], { attestActor: 'qm', attestRead: 'person' });+ await client('person-solo-two', ['source-solo'], { attestActor: 'qm', attestRead: 'person' });+ await client('plain-solo', ['source-solo'], null);+ expect((await run()).status).toBe('ok');+ }, 60_000);++ test('a person credential reading a source an unset or scope attest credential reads is warned, by name and source, and nothing is written', async () => {+ const person = await client('person-shared', ['source-a', 'source-room'], { attestActor: 'qm', attestRead: 'person' });+ const before = await credentialRows();+ const check = await run();+ expect(check.status).toBe('warn');+ expect(check.message).toContain('person-shared');+ expect(check.details.credentials).toEqual([{ kind: 'client', name: expect.stringContaining('person-shared'), shared_sources: ['source-room'] }]);+ expect(await credentialRows()).toEqual(before);+ await bindCredential(engine, { kind: 'client', id: person }, { attestRead: 'scope' });+ expect((await run()).status).toBe('ok');+ const legacy = await mintLegacyToken(engine, { name: 'person-legacy-' + randomUUID().slice(0, 8), scopes: ['read'], takesHolders: ['world'], sourceGrant: ['source-solo'] });+ await bindCredential(engine, { kind: 'token', id: legacy.id }, { attestActor: 'qm', attestRead: 'person' });+ expect((await run()).status).toBe('ok');+ await client('unset-solo', ['source-solo'], { attestActor: 'qm' });+ const token = await run();+ expect(token.status).toBe('warn');+ expect(token.details.credentials).toHaveLength(3);+ expect(token.details.credentials).toContainEqual({ kind: 'token', name: expect.stringContaining('person-legacy'), shared_sources: ['source-solo'] });+ expect(token.message).toContain('person-solo');+ }, 60_000);+ });+}diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex f4198bc7d4..a34f21ad2e 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -1821,7 +1821,8 @@"17 member_id text/text NULL","18 may_act_for ARRAY/_text NULL","19 attest_actor text/text NULL",- "20 attest_ops ARRAY/_text NULL"+ "20 attest_ops ARRAY/_text NULL",+ "21 attest_read text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -3051,7 +3052,8 @@"34 member_id text/text NULL","35 may_act_for ARRAY/_text NULL","36 attest_actor text/text NULL",- "37 attest_ops ARRAY/_text NULL"+ "37 attest_ops ARRAY/_text NULL",+ "38 attest_read text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex e4f7385f81..fc1a42191f 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -1821,7 +1821,8 @@"17 member_id text/text NULL","18 may_act_for ARRAY/_text NULL","19 attest_actor text/text NULL",- "20 attest_ops ARRAY/_text NULL"+ "20 attest_ops ARRAY/_text NULL",+ "21 attest_read text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -3051,7 +3052,8 @@"34 member_id text/text NULL","35 may_act_for ARRAY/_text NULL","36 attest_actor text/text NULL",- "37 attest_ops ARRAY/_text NULL"+ "37 attest_ops ARRAY/_text NULL",+ "38 attest_read text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex c5a2315f26..126addd9dd 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -1817,7 +1817,8 @@"17 member_id text/text NULL","18 may_act_for ARRAY/_text NULL","19 attest_actor text/text NULL",- "20 attest_ops ARRAY/_text NULL"+ "20 attest_ops ARRAY/_text NULL",+ "21 attest_read text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -3047,7 +3048,8 @@"34 member_id text/text NULL","35 may_act_for ARRAY/_text NULL","36 attest_actor text/text NULL",- "37 attest_ops ARRAY/_text NULL"+ "37 attest_ops ARRAY/_text NULL",+ "38 attest_read text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 34af7dec47..598ecc77a4 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -1822,7 +1822,8 @@"17 member_id text/text NULL","18 may_act_for ARRAY/_text NULL","19 attest_actor text/text NULL",- "20 attest_ops ARRAY/_text NULL"+ "20 attest_ops ARRAY/_text NULL",+ "21 attest_read text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -3063,7 +3064,8 @@"34 member_id text/text NULL","35 may_act_for ARRAY/_text NULL","36 attest_actor text/text NULL",- "37 attest_ops ARRAY/_text NULL"+ "37 attest_ops ARRAY/_text NULL",+ "38 attest_read text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex e401b9f252..08a81c4be7 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -1822,7 +1822,8 @@"17 member_id text/text NULL","18 may_act_for ARRAY/_text NULL","19 attest_actor text/text NULL",- "20 attest_ops ARRAY/_text NULL"+ "20 attest_ops ARRAY/_text NULL",+ "21 attest_read text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -3063,7 +3064,8 @@"34 member_id text/text NULL","35 may_act_for ARRAY/_text NULL","36 attest_actor text/text NULL",- "37 attest_ops ARRAY/_text NULL"+ "37 attest_ops ARRAY/_text NULL",+ "38 attest_read text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex be145948fd..69ff55ca7a 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -1818,7 +1818,8 @@"17 member_id text/text NULL","18 may_act_for ARRAY/_text NULL","19 attest_actor text/text NULL",- "20 attest_ops ARRAY/_text NULL"+ "20 attest_ops ARRAY/_text NULL",+ "21 attest_read text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -3059,7 +3060,8 @@"34 member_id text/text NULL","35 may_act_for ARRAY/_text NULL","36 attest_actor text/text NULL",- "37 attest_ops ARRAY/_text NULL"+ "37 attest_ops ARRAY/_text NULL",+ "38 attest_read text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 59c0a17a68..f64c5eb7ab 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 269480,- "stdoutSha256": "a5efd152d5b57d8cab862c842421d4b321090631a5c72139cc5d1195e2849563",+ "stdoutBytes": 270345,+ "stdoutSha256": "1fcac9cc1c378b84b6a7f374d552d89bc91be602408aea211b7d40596539e64d","toolNames": ["remember","entity",@@ -2861,6 +2861,8 @@"min_trust": "string?","since": "string?","slug": "string",+ "source_id": "string?",+ "source_ids": "array?","until": "string?"},"required_scopes": [],@@ -2898,6 +2900,17 @@"description": "Slug of the page whose timeline entries to return.","type": "string"},+ "source_id": {+ "description": "Read only this source.",+ "type": "string"+ },+ "source_ids": {+ "description": "Narrow to these sources (omit or [] for all you can read).",+ "items": {+ "type": "string"+ },+ "type": "array"+ },"until": {"description": "Alias for before; accepted for agent callers","type": "string"@@ -6323,6 +6336,7 @@"min_trust": "string?","prior_context": "string?","session_id": "string?",+ "source_ids": "array?","stats": "boolean?","turn": "number?","window": "string?"@@ -6362,6 +6376,13 @@"description": "Optional caller session id, logged for attribution.","type": "string"},+ "source_ids": {+ "description": "Narrow to these sources (omit or [] for all you can read).",+ "items": {+ "type": "string"+ },+ "type": "array"+ },"stats": {"description": "Return the volunteered-vs-used precision summary instead of volunteering. APPROXIMATE: \"used\" = pages.last_retrieved_at > volunteered_at.","type": "boolean"@@ -7286,6 +7307,7 @@"parameters": {"explain": "boolean?","limit": "number?",+ "source_ids": "array?","topic": "string?"},"required_scopes": [],@@ -7299,6 +7321,13 @@"description": "Max results (default 5).","type": "number"},+ "source_ids": {+ "description": "Narrow to these sources (omit or [] for all you can read).",+ "items": {+ "type": "string"+ },+ "type": "array"+ },"topic": {"description": "The topic to route. Free-form natural language.","type": "string"diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 3885dd16cd..4e1148d1b7 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1037,6 +1037,15 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: no attest credential reads named sources as the person (--attest-read person).",+ "name": "attest_read_shared_scope",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex a4c0ccefa0..579110f1f5 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1084,6 +1084,15 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: no attest credential reads named sources as the person (--attest-read person).",+ "name": "attest_read_shared_scope",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 143798ccae..fe47db47d2 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1080,6 +1080,15 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Not applicable: no attest credential reads named sources as the person (--attest-read person).",+ "name": "attest_read_shared_scope",+ "readiness_state": "not_applicable",+ "severity": "info",+ "status": "ok"+ },{"category": "ops","elapsed_ms": "<volatile>",diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex da3e4c0c44..8c28b75051 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -389,6 +389,10 @@"category": "brain","name": "access_may_act_for_wildcard"},+ {+ "category": "brain",+ "name": "attest_read_shared_scope"+ },{"category": "ops","name": "rls"diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 237f7b9d91..a3e2270f3d 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6570,7 +6570,7 @@"members": ["allowedOperations?: string[] | null | undefined","allowedSources?: string[] | undefined",- "attest?: { system: string; ops: string[]; } | null | undefined",+ "attest?: { system: string; ops: string[]; read?: \"person\" | \"scope\"; } | null | undefined","boundBrainId?: string | null | undefined","boundMaxConcurrent?: number | undefined","boundSlugPrefixes?: string[] | undefined",diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex ee9ef3da61..3bf5e87d41 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 281,+ "count": 282,"gaps": [17,18,@@ -94,7 +94,7 @@"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67","withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59"},- "latest": 286,+ "latest": 287,"records": [{"handler": {@@ -4648,6 +4648,19 @@"transaction": "absent","verify": "absent","version": 286+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "attest_read",+ "sql": {+ "length": 139,+ "sha256": "17083c8352b9c8b501aa46e7ba59eb4e3fcfb37566616820bb48a735f3adeb8b"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 287}],"versions": [@@ -4931,7 +4944,8 @@283,284,285,- 286+ 286,+ 287]},"normalizer": "migrations-record-v1"diff --git a/test/qm-scope-read.test.ts b/test/qm-scope-read.test.tsnew file mode 100644index 0000000000..d5fa7d7961--- /dev/null+++ b/test/qm-scope-read.test.ts@@ -0,0 +1,323 @@+/**+ * GST-1158 E1, F3, F4: attested reads that name sources (the scope read), the attest_read credential setting, and the+ * actorless refusal on a credential set to scope.+ *+ * 1. Protects: an attested call to get_page, entity, whois, get_backlinks, get_timeline, find_experts,+ * volunteer_context, query or memory_recall that names source_id/source_ids reads as the scope (no member identity):+ * the person's restricted page (readable_by them) and their member page memory/members/<member> are not_found or+ * absent, exactly like a page that does not exist; a source outside the grant is refused; __all__ and all_sources are+ * refused under scope. A credential set --attest-read person narrows to the named sources but reads as the person. A+ * credential set --attest-read scope refuses every call that names no person (actor_required), reading nothing; an+ * unset one (NULL) keeps today's behavior.+ * 2. Fails when: any of those reads returns a restricted or member-page canary under scope, a refusal differs from a+ * missing page, an out-of-grant source reads, a person credential loses its own pages, or an actorless call from a+ * scope credential reads anything.+ * 3. Existing coverage: test/qm-memory-tools.test.ts pins memory_recall's scope read (GST-1094); test/access-qm-actor.test.ts+ * pins the attested actor. This file pins the dispatch rule and every op in SCOPE_READ_OPS.+ * 4. Real seams: OAuth clients issued tokens by the provider's client-credentials grant, verified by the provider,+ * dispatched through MCP dispatch with remote=true on a repo-less brain (no git checkout anywhere); writes go through+ * the persistence coordinator; embeddings stubbed. PGLite always, Postgres when DATABASE_URL is set.+ */+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 { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { addMember, bindCredential } from '../src/core/access/members.ts';+import { attestRightOf, linkMember } from '../src/core/access/actor.ts';+import { takeBindingFlags, bindingLine } from '../src/commands/auth-binding.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import type { AuthInfo } from '../src/core/ops/contract.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.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 = 'source-a';+const ROOM = 'source-room';+const OTHER = 'source-other';+const ALICE_ID = 'U0ALICE';+const SCOPE_OPS = ['entity', 'find_experts', 'get_backlinks', 'get_page', 'get_timeline', 'get_write_request', 'memory_recall', 'memory_write', 'query', 'volunteer_context', 'whois'];+const RESTRICTED = 'companies/zephyr-restricted-example';+const ACME = 'companies/acme-example';+const MEMBER_PAGE = 'memory/members/alice-example';+const CANARIES = ['canaryrestrictedbody', 'canaryrestrictedtimeline', 'canaryrestrictedexpert', 'canarymemberfact', 'Memory of alice-example'];+const SLUGS = ['zephyr-restricted-example', 'ivo-galewright', 'quill-restricted-example', 'members/alice-example'];+const company = (title: string, extra: string[], body: string) => ['---', 'type: company', 'title: ' + title, ...extra, '---', '# ' + title, '', body].join('\n');+const person = (title: string, extra: string[], body: string) => ['---', 'type: person', 'title: ' + title, ...extra, '---', '# ' + title, '', body].join('\n');++describe('attest_read flag parsing (pure)', () => {+ test('--attest-read takes person, scope or none; anything else is refused', () => {+ expect(takeBindingFlags(['--attest-read', 'person']).patch).toEqual({ attestRead: 'person' });+ expect(takeBindingFlags(['--attest-read=scope']).patch).toEqual({ attestRead: 'scope' });+ expect(takeBindingFlags(['--attest-read', 'none']).patch).toEqual({ attestRead: null });+ expect(() => takeBindingFlags(['--attest-read', 'room'])).toThrow(/--attest-read room/);+ });++ test('the binding line names how named sources read, scope when unset', () => {+ expect(bindingLine({ member: null, may_act_for: null, attest_actor: 'qm', attest_ops: null, attest_read: 'person', changed: true }))+ .toContain('named sources read as: person');+ expect(bindingLine({ member: null, may_act_for: null, attest_actor: 'qm', attest_ops: null, changed: false })).toContain('named sources read as: scope (default)');+ });+});++for (const kind of testBackends()) {+ describe('scope reads, attest_read and actorless refusal (' + kind + ', repo-less)', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ const clients: Record<string, { id: string; secret: string; token: string }> = {};+ const verify = async (bearer: string) => await provider().verifyAccessToken(bearer) as unknown as AuthInfo;++ async function call(client: string, op: string, params: Record<string, unknown>, actor: string | null = ALICE_ID, extra: { writeWaitMs?: number; remote?: boolean } = {}) {+ const out: ToolResult = await dispatchToolCall(engine, op, { ...params }, {+ remote: extra.remote ?? true, transport: 'http', auth: await verify(clients[client]!.token), sourceId: SRC, takesHoldersAllowList: ['world'],+ ...(actor !== null ? { actor: { header: actor } } : {}), ...(extra.writeWaitMs ? { writeWaitMs: extra.writeWaitMs } : {}),+ });+ const text = out.content.map(c => c.text).join('\n');+ let json: Record<string, any> = {};+ try { json = JSON.parse(out.content[0]?.text ?? ''); } catch { /* prose */ }+ return { isError: out.isError === true, text, json, structured: out.structuredContent as Record<string, any> | undefined,+ all: text + JSON.stringify(out._meta ?? {}) + JSON.stringify(out.structuredContent ?? {}) };+ }+ const hidden = (out: { all: string }, slugs = true) => { for (const c of [...CANARIES, ...(slugs ? SLUGS : [])]) expect(out.all).not.toContain(c); };+ async function refused(p: Promise<Awaited<ReturnType<typeof call>>>, code: string, reason?: string) {+ const out = await p;+ expect({ isError: out.isError, code: out.json.code, reason: out.json.reason }).toEqual({ isError: true, code, reason });+ hidden(out, false);+ return out;+ }++ 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();+ for (const id of [SRC, ROOM, OTHER]) await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [id]);+ for (const id of ['alice-example', 'bob-example']) await addMember(engine, id);+ await linkMember(engine, 'alice-example', 'qm', ALICE_ID);+ await importFromContent(engine, ACME, company('Acme Example', [], 'Acme example harbor ledger tariffs canaryworldacme.'), { sourceId: SRC });+ await importFromContent(engine, RESTRICTED, company('Zephyr Restricted Example', ['readable_by: [alice-example]'], 'Zephyr harbor ledger tariffs canaryrestrictedbody.'), { sourceId: SRC });+ await importFromContent(engine, 'people/quill-restricted-example', person('Quill Restricted Example', ['readable_by: [alice-example]'], 'Quill leads harbor ledger tariffs canaryrestrictedexpert.'), { sourceId: SRC });+ await importFromContent(engine, 'people/wren-world-example', person('Wren World Example', [], 'Wren leads harbor ledger tariffs canaryworldexpert.'), { sourceId: SRC });+ await importFromContent(engine, 'people/ivo-galewright', person('Ivo Galewright', ['readable_by: [alice-example]'], 'Ivo works on harbor ledgers.'), { sourceId: SRC });+ await importFromContent(engine, 'people/nell-thistlewood', person('Nell Thistlewood', [], 'Nell works on harbor ledgers canaryworldsurname.'), { sourceId: SRC });+ await importFromContent(engine, 'companies/room-example', company('Room Example', [], 'Room example harbor ledger tariffs canaryroompage.'), { sourceId: ROOM });+ await importFromContent(engine, 'companies/other-example', company('Other Example', [], 'Other example harbor ledger tariffs canaryotherpage.'), { sourceId: OTHER });+ await engine.addTimelineEntry(RESTRICTED, { date: '2026-10-01', summary: 'Zephyr board review canaryrestrictedtimeline' } as never, { sourceId: SRC });+ await engine.addTimelineEntry(ACME, { date: '2026-10-02', summary: 'Acme board review canaryworldtimeline' } as never, { sourceId: SRC });+ await engine.addLink(RESTRICTED, ACME, 'zephyr cites acme', 'mentions', 'manual', undefined, undefined, { fromSourceId: SRC, toSourceId: SRC });+ await engine.addLink('people/wren-world-example', ACME, 'wren cites acme', 'mentions', 'manual', undefined, undefined, { fromSourceId: SRC, toSourceId: SRC });+ const register = async (name: string, read?: 'person' | 'scope') => {+ const c = await provider().registerClientManual('scope-' + name + '-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], SRC);+ await provider().rescopeClient(c.clientId, { federatedRead: [SRC, ROOM] });+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { attestActor: 'qm', attestOps: SCOPE_OPS, ...(read ? { attestRead: read } : {}) });+ clients[name] = { id: c.clientId, secret: c.clientSecret ?? '', token: (await provider().exchangeClientCredentials(c.clientId, c.clientSecret ?? '')).access_token };+ };+ await register('unset');+ await register('scope', 'scope');+ await register('person', 'person');+ const wrote = await call('unset', 'memory_write', { facts: [{ fact: 'Alice prefers the harbor ledger tariffs canarymemberfact', provenance: 'turn 1' }], idempotency_key: randomUUID() }, ALICE_ID, { writeWaitMs: 30_000 });+ expect(wrote.structured?.status).toBe('committed');+ __resetPrivateVisibilityCacheForTests();+ }, 240_000);++ afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await disposePersistenceConsumer(engine).catch(() => undefined);+ await close?.();+ }, 60_000);++ test('attest_read is stored beside attest_ops, carried in the attest right, cleared with the right and refused without it', async () => {+ expect((await attestRightOf(engine, { principal: { kind: 'oauth_client', id: clients.person!.id } }))?.read).toBe('person');+ expect((await attestRightOf(engine, { principal: { kind: 'oauth_client', id: clients.scope!.id } }))?.read).toBe('scope');+ expect((await attestRightOf(engine, { principal: { kind: 'oauth_client', id: clients.unset!.id } }))?.read).toBeUndefined();+ expect((await verify(clients.person!.token)).attest?.read).toBe('person');+ const c = await provider().registerClientManual('scope-flip-' + randomUUID().slice(0, 8), ['client_credentials'], 'read', [], SRC);+ const target = { kind: 'client' as const, id: c.clientId };+ await expect(bindCredential(engine, target, { attestRead: 'person' })).rejects.toThrow(/--attest-read needs the attest right/);+ expect(await bindCredential(engine, target, { attestActor: 'qm', attestRead: 'person' })).toMatchObject({ attest_actor: 'qm', attest_read: 'person', changed: true });+ expect(await bindCredential(engine, target, { attestRead: 'person' })).toMatchObject({ attest_read: 'person', changed: false });+ expect(await bindCredential(engine, target, { attestRead: 'scope' }, { dryRun: true })).toMatchObject({ attest_read: 'scope', changed: true });+ expect((await engine.executeRaw<{ attest_read: string | null }>('SELECT attest_read FROM oauth_clients WHERE client_id = $1', [c.clientId]))[0]?.attest_read).toBe('person');+ expect(await bindCredential(engine, target, { attestRead: null })).toMatchObject({ attest_read: null, changed: true });+ await bindCredential(engine, target, { attestRead: 'scope' });+ expect(await bindCredential(engine, target, { attestActor: null })).toMatchObject({ changed: true });+ expect((await engine.executeRaw<Record<string, unknown>>('SELECT attest_actor, attest_ops, attest_read FROM oauth_clients WHERE client_id = $1', [c.clientId]))[0])+ .toEqual({ attest_actor: null, attest_ops: null, attest_read: null });+ }, 120_000);++ test('get_page that names sources reads as the scope: the restricted page and the member page are not_found like a missing page', async () => {+ expect((await call('unset', 'get_page', { slug: RESTRICTED })).text).toContain('canaryrestrictedbody');+ expect((await call('unset', 'get_page', { slug: MEMBER_PAGE })).text).toContain('Memory of alice-example');+ const missing = await call('unset', 'get_page', { slug: 'companies/nobody-example', source_id: SRC });+ expect(missing.json.code).toBe('page_not_found');+ for (const client of ['unset', 'scope']) {+ for (const slug of [RESTRICTED, MEMBER_PAGE]) {+ const out = await call(client, 'get_page', { slug, source_id: SRC });+ expect({ isError: out.isError, code: out.json.code }).toEqual({ isError: true, code: missing.json.code });+ expect(out.json.message).toBe(missing.json.message?.replace('companies/nobody-example', slug));+ hidden(out, false);+ }+ expect((await call(client, 'get_page', { slug: ACME, source_id: SRC })).text).toContain('canaryworldacme');+ expect((await call(client, 'get_page', { slug: 'companies/room-example', source_id: ROOM })).text).toContain('canaryroompage');+ await refused(call(client, 'get_page', { slug: 'companies/other-example', source_id: OTHER }), 'permission_denied');+ await refused(call(client, 'get_page', { slug: RESTRICTED, source_id: '__all__' }), 'invalid_params');+ }+ }, 120_000);++ test('entity and whois that name sources never find the restricted page; a source outside the grant is refused', async () => {+ expect((await call('unset', 'entity', { name: 'Zephyr Restricted Example' })).json.found).toBe(true);+ expect((await call('unset', 'whois', { query: 'Zephyr Restricted Example' })).json.matches?.length).toBe(1);+ for (const client of ['unset', 'scope']) {+ const card = await call(client, 'entity', { name: 'Zephyr Restricted Example', source_id: SRC });+ expect({ isError: card.isError, found: card.json.found }).toEqual({ isError: false, found: false });+ hidden(card);+ expect((await call(client, 'entity', { name: 'Acme Example', source_id: SRC })).json.found).toBe(true);+ const who = await call(client, 'whois', { query: 'Zephyr Restricted Example', source_id: SRC });+ expect({ isError: who.isError, matches: who.json.matches }).toEqual({ isError: false, matches: [] });+ hidden(who);+ expect((await call(client, 'whois', { query: 'Acme Example', source_id: SRC })).json.matches?.length).toBe(1);+ expect((await call(client, 'entity', { name: 'Other Example', source_id: OTHER })).isError).toBe(true);+ await refused(call(client, 'whois', { query: 'Other Example', source_id: OTHER }), 'permission_denied');+ await refused(call(client, 'whois', { query: 'Acme Example', source_id: '__all__' }), 'invalid_params');+ }+ }, 120_000);++ test('get_backlinks that names sources drops links from the restricted page; all_sources is refused under scope', async () => {+ expect((await call('unset', 'get_backlinks', { slug: ACME })).text).toContain('zephyr-restricted-example');+ for (const client of ['unset', 'scope']) {+ const out = await call(client, 'get_backlinks', { slug: ACME, source_id: SRC });+ expect(out.isError).toBe(false);+ expect(out.text).toContain('wren-world-example');+ hidden(out);+ await refused(call(client, 'get_backlinks', { slug: ACME, source_id: OTHER }), 'permission_denied');+ await refused(call(client, 'get_backlinks', { slug: ACME, source_id: SRC, all_sources: true }), 'invalid_params');+ }+ }, 120_000);++ test('get_timeline narrows to source_id/source_ids inside the grant and, named, reads as the scope', async () => {+ expect((await call('unset', 'get_timeline', { slug: RESTRICTED })).text).toContain('canaryrestrictedtimeline');+ const missing = await call('unset', 'get_timeline', { slug: 'companies/nobody-example', source_id: SRC });+ for (const client of ['unset', 'scope']) {+ for (const args of [{ source_id: SRC }, { source_ids: [SRC] }, { source_ids: [SRC, ROOM] }]) {+ const out = await call(client, 'get_timeline', { slug: RESTRICTED, ...args });+ expect({ isError: out.isError, text: out.text }).toEqual({ isError: false, text: missing.text });+ hidden(out);+ expect((await call(client, 'get_timeline', { slug: ACME, ...args })).text).toContain('canaryworldtimeline');+ }+ expect((await call(client, 'get_timeline', { slug: ACME, source_ids: [ROOM] })).text).not.toContain('canaryworldtimeline');+ await refused(call(client, 'get_timeline', { slug: ACME, source_ids: [OTHER] }), 'permission_denied');+ await refused(call(client, 'get_timeline', { slug: ACME, source_id: OTHER }), 'permission_denied');+ }+ expect((await call('unset', 'get_timeline', { slug: ACME, source_ids: [ROOM] }, null)).text).not.toContain('canaryworldtimeline');+ }, 120_000);++ test('find_experts takes source_ids and, named, never ranks the restricted person', async () => {+ const asPerson = await call('unset', 'find_experts', { topic: 'harbor ledger tariffs', limit: 10 });+ expect(asPerson.isError).toBe(false);+ expect(asPerson.text).toContain('quill-restricted-example');+ for (const client of ['unset', 'scope']) {+ const out = await call(client, 'find_experts', { topic: 'harbor ledger tariffs', limit: 10, source_ids: [SRC] });+ expect(out.isError).toBe(false);+ expect(out.text).toContain('wren-world-example');+ hidden(out);+ await refused(call(client, 'find_experts', { topic: 'harbor ledger tariffs', source_ids: [OTHER] }), 'permission_denied');+ }+ }, 120_000);++ test('volunteer_context takes source_ids; under scope its pointer and lexical arms never volunteer a restricted page, and stats is refused', async () => {+ const window = 'user: what about Zephyr Restricted Example and Acme Example? did Galewright and Thistlewood reply? notes on zephyr restricted example';+ const local = await call('unset', 'volunteer_context', { window, min_confidence: 0.5, max_pages: 5 }, null, { remote: false });+ for (const slug of [RESTRICTED, 'people/ivo-galewright']) expect(local.text).toContain(slug);+ for (const client of ['unset', 'scope']) {+ const out = await call(client, 'volunteer_context', { window, min_confidence: 0.5, max_pages: 5, source_ids: [SRC] });+ expect(out.isError).toBe(false);+ for (const slug of [ACME, 'people/nell-thistlewood']) expect(out.text).toContain(slug);+ hidden(out);+ const room = await call(client, 'volunteer_context', { window: 'user: tell me about Room Example and Acme Example', min_confidence: 0.5, source_ids: [ROOM] });+ expect(room.text).toContain('companies/room-example');+ expect(room.text).not.toContain(ACME);+ await refused(call(client, 'volunteer_context', { window, source_ids: [OTHER] }), 'permission_denied');+ await refused(call(client, 'volunteer_context', { stats: true, source_ids: [SRC] }), 'invalid_params');+ }+ expect((await call('unset', 'volunteer_context', { stats: true }, null)).isError).toBe(false);+ }, 120_000);++ test('query that names sources reads as the scope: no restricted page or member-page fact', async () => {+ const asPerson = await call('unset', 'query', { query: 'harbor ledger tariffs', limit: 20 });+ expect(asPerson.text).toContain('canaryrestrictedbody');+ for (const client of ['unset', 'scope']) {+ for (const args of [{ source_id: SRC }, { source_ids: [SRC, ROOM] }]) {+ const out = await call(client, 'query', { query: 'harbor ledger tariffs', limit: 20, ...args });+ expect(out.isError).toBe(false);+ expect(out.text).toContain('canaryworldacme');+ hidden(out);+ }+ await refused(call(client, 'query', { query: 'harbor ledger tariffs', source_ids: [OTHER] }), 'permission_denied');+ await refused(call(client, 'query', { query: 'harbor ledger tariffs', source_id: '__all__' }), 'invalid_params');+ }+ }, 120_000);++ test('memory_recall keeps reading named sources as the scope through the shared rule', async () => {+ const asPerson = await call('unset', 'memory_recall', { query: 'harbor ledger tariffs', max_chars: 12_000 });+ expect(asPerson.text).toContain('canarymemberfact');+ for (const client of ['unset', 'scope']) {+ const out = await call(client, 'memory_recall', { query: 'harbor ledger tariffs', max_chars: 12_000, source_ids: [SRC] });+ expect(out.isError).toBe(false);+ hidden(out);+ await refused(call(client, 'memory_recall', { query: 'harbor ledger tariffs', source_ids: [OTHER] }), 'permission_denied');+ }+ }, 120_000);++ test('an empty source_ids names nothing, so the call reads as the person', async () => {+ expect((await call('scope', 'get_timeline', { slug: RESTRICTED, source_ids: [] })).text).toContain('canaryrestrictedtimeline');+ }, 120_000);++ test('a credential set --attest-read person narrows to the named sources but reads as the person, for every scope-read op', async () => {+ expect((await call('person', 'get_page', { slug: RESTRICTED, source_id: SRC })).text).toContain('canaryrestrictedbody');+ expect((await call('person', 'get_page', { slug: MEMBER_PAGE, source_id: SRC })).text).toContain('Memory of alice-example');+ expect((await call('person', 'entity', { name: 'Zephyr Restricted Example', source_id: SRC })).json.found).toBe(true);+ expect((await call('person', 'whois', { query: 'Zephyr Restricted Example', source_id: SRC })).json.matches?.length).toBe(1);+ expect((await call('person', 'get_backlinks', { slug: ACME, source_id: SRC })).text).toContain('zephyr-restricted-example');+ expect((await call('person', 'get_timeline', { slug: RESTRICTED, source_ids: [SRC] })).text).toContain('canaryrestrictedtimeline');+ expect((await call('person', 'find_experts', { topic: 'harbor ledger tariffs', limit: 10, source_ids: [SRC] })).text).toContain('quill-restricted-example');+ expect((await call('person', 'query', { query: 'harbor ledger tariffs', limit: 20, source_ids: [SRC] })).text).toContain('canaryrestrictedbody');+ expect((await call('person', 'memory_recall', { query: 'harbor ledger tariffs', max_chars: 12_000, source_ids: [SRC] })).text).toContain('canarymemberfact');+ expect((await call('person', 'get_page', { slug: 'companies/room-example', source_id: SRC })).json.code).toBe('page_not_found');+ await refused(call('person', 'get_page', { slug: 'companies/other-example', source_id: OTHER }), 'permission_denied');+ expect((await call('person', 'volunteer_context', { stats: true, source_ids: [SRC] })).isError).toBe(false);+ }, 120_000);++ test('F4: a credential set --attest-read scope refuses every call that names no person, reading nothing; unset and person credentials are unchanged', async () => {+ for (const [op, params] of [['get_page', { slug: ACME }], ['get_page', { slug: ACME, source_id: SRC }], ['memory_recall', { query: 'harbor ledger tariffs' }],+ ['query', { query: 'harbor ledger tariffs' }], ['get_write_request', { request_id: randomUUID() }]] as const) {+ const out = await refused(call('scope', op, params, null), 'actor_not_attested', 'actor_required');+ expect(out.json.message).toContain('--attest-read scope');+ expect(out.all).not.toContain('canaryworldacme');+ }+ for (const client of ['unset', 'person']) {+ const out = await call(client, 'get_page', { slug: ACME }, null);+ expect(out.isError).toBe(false);+ expect(out.text).toContain('canaryworldacme');+ }+ }, 120_000);+ });+}diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex e003c79540..daf53575e9 100644--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@ -1217,6 +1217,10 @@ const COLUMN_EXEMPTIONS = new Set<string>(['oauth_clients.attest_actor','oauth_clients.attest_ops','oauth_tokens.grant_type',+ // GST-1158 F3 (migration v287) - how an attested call that names sources reads them. Same posture as v286: absent+ // from both schema blobs; readers read it through to_jsonb(row), so a schema before it reads as NULL (the scope).+ 'access_tokens.attest_read',+ 'oauth_clients.attest_read',// GBRA-218 A2 (migration v283) - folder rules. Same posture as v282: absent from both schema blobs; the migration// creates the folder_rule_ids trigger and functions itself, and no index or function in either blob references it.'pages.folder_rule_ids',