Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
QM scope writes: per-call attested write source, scope pages, scope-source read guard (GST-1113)
garrytan0489a832e613
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 204c52a603..52622bab05 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -26,6 +26,17 @@ identifiers and attribution are available in the pre-removal Git revisionQM clients that read v1 keep working unchanged. A shared-scope turn should name its sources and read the v2 contract.+**QM can now save a shared scope's memory (a project, channel or team) as well as each person's, and nothing else can read that scope.** `memory_write` gains `source_id`: named, the facts go to that scope source's `memory/scope` page, world-readable inside the source, still attested to the person who said them. The operator lists the scope sources on the QM credential with `gbrain auth rescope --attest-sources`, which marks each one a scope source for good. A scope source is never federated and never joins another credential's read grant, so its memory is read only by naming it from the scope credential, and a person read never sees it.++| Situation | Before | Now |+|---|---|---|+| `memory_write` with `source_id` | refused (`unknown_param`) | saves on `memory/scope` in that source when the credential lists it in `--attest-sources`; otherwise `permission_denied` reason `source_not_attested`; the credential's own write source is `invalid_params` reason `source_is_member_source` |+| `gbrain auth rescope --attest-sources a,b\|none` | no such flag | lists the scope sources; refuses `default`, a federated source, the own write source, a source another credential reads, ops beyond the memory tools and the private-pages grant |+| A grant, token or registration that reads a scope source | n/a | refused (`QM scope source`), also after the scope credential is revoked |+| `sources federate` / `sources restore` on a scope source | federates | refused / restored unfederated; a federated flag on a scope source is ignored |+| Remote write to `memory/scope` (put_page, remember, delete_page, tags, links, timeline) | allowed like any page | refused unless it is a scope `memory_write` |+| `memory_recall` without sources from a credential that reads a scope source | n/a | never reads the scope source |+## [0.60.555.0] - 2026-11-02**`gbrain query --limit N` without a token budget returns N rows again, a budgeted facts block takes at most N rows, the facts block never outscores the pages, and the CLI names fact rows instead of printing `undefined` (#8411).** Since the facts block went on by default (v0.60.491.0), it also ran on queries that passed no budget, because the shipped no-budget evidence plan carries an implicit 24,000-token budget. Its 22% share let up to 40 fact rows in ahead of the pages, so `--limit 3` could print more than a dozen fact rows before the 3 pages. Each block row was scored a hair above the top page, so they all showed the same score and outranked every hit, and the human CLI printed them as `[0.84xx] undefined -- …` because fact rows have no page slug.diff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.mdindex 9b6d84eef0..fd16d2069d 100644--- a/docs/architecture/key-files/access.md+++ b/docs/architecture/key-files/access.md@@ -4,4 +4,4 @@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/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`).+- `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). Scope writes (GST-1113): `memory_write {source_id}` saves on `memory/scope` in a scope source listed in the credential's `attest_sources` (migration v287, on `access_tokens` and `oauth_clients`); `access/attest-sources.ts` holds `perCallWriteSource` (the one exemption from the one-write-source checks in `page-mutations.ts`, `memory-mutations.ts` and `persistence/authority.ts`, keyed to that slug and re-checked at publication through `actorCoverage(..., source)`), the sticky mark `sources.config.qm_scope` (set by `applyAttestSources` under row locks; `isSourceFederated` ignores federation on it), `assertScopeSourceGrant` (in `insertClientGrant`, `persistGrant`, `writeTokenGrant` and `insertUnifiedToken`) and `withoutScopeSources` (a person recall never reads a scope source). `member-facts.ts` `assertScopePageWriter` keeps other remote writers off `memory/scope`. Tests: `test/qm-scope-writes.test.ts` (both engines). 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/contracts/qm-memory-provider/README.md b/docs/contracts/qm-memory-provider/README.mdindex ac762541ca..0133176ec8 100644--- a/docs/contracts/qm-memory-provider/README.md+++ b/docs/contracts/qm-memory-provider/README.md@@ -11,4 +11,6 @@ It is generated from the live operation registry by`test/qm-memory-contract.test.ts` fails when the committed file drifts.A change to the shape is a new file, `v2.json`; `v1.json` stays until QM moves.+`v2.json` adds `source_id` / `source_ids` on `memory_recall` (scope reads, `scope_read`) and `source_id` on+`memory_write` (scope writes, `scope_write`).Operator setup is in [docs/guides/qm.md](../../guides/qm.md).diff --git a/docs/contracts/qm-memory-provider/v2.json b/docs/contracts/qm-memory-provider/v2.jsonindex c5cd903b8a..4d72a1bc87 100644--- a/docs/contracts/qm-memory-provider/v2.json+++ b/docs/contracts/qm-memory-provider/v2.json@@ -123,6 +123,10 @@"acting_user": {"type": "string","description": "Set by the trusted system: equal to the x-qm-actor header, or omit."+ },+ "source_id": {+ "type": "string",+ "description": "Save on this scope source's shared page (memory/scope), read by everyone who reads that source; it must be one of the credential's scope sources. Omit to save for the person alone."}},"required": [@@ -252,6 +256,21 @@]},"poll": "get_write_request {request_id}"+ },+ "scope_write": {+ "argument": "source_id",+ "rule": "names one of the credential's scope sources (attest_sources, which the brain operator sets on the host); checked on the call and again when the write publishes, so a source the operator drops refuses queued writes; omit it to save for the person alone, exactly as without it",+ "saved_as": {+ "page": "memory/scope",+ "readers": "none: whoever holds read on the scope source, which only scope credentials may",+ "visibility": "world",+ "provenance": "qm:<actor id>; <caller provenance>"+ },+ "request_id": "uuidv5(uuidv5(namespace, \"member:<member>#source:<source_id>\"), idempotency_key) for the first fact; later facts derive from it; without source_id the member derivation above is unchanged",+ "replay": "per person and source: the same idempotency_key in another source is a separate write",+ "pending": "a scope source with a repository publishes git-first through its writer and answers pending until it commits; a source without one commits to the database",+ "recall": "read it with memory_recall source_id (read as the scope); a memory_recall without sources never reads a scope source",+ "withdrawal": "forget and forget_fact reach only the person's own member page, so a scope fact is not_found remotely"}},"errors": {@@ -336,7 +355,7 @@"class": "caller","summary": "A parameter is missing, has the wrong type, or has an invalid value.","docs": "docs/guides/error-codes.md#invalid_params",- "note": "Bad arguments, refused before anything is saved. A reused idempotency_key with different facts carries write_error idempotency_conflict; a claim the person forgot carries the fact_withdrawn message."+ "note": "Bad arguments, refused before anything is saved. A reused idempotency_key with different facts carries write_error idempotency_conflict; a claim the person forgot carries the fact_withdrawn message. A memory_write whose source_id is the credential's own source carries reason source_is_member_source (omit source_id instead)."},{"code": "scope_denied",@@ -385,7 +404,7 @@"class": "host_only","summary": "This caller is not authorized for the operation.","docs": "docs/guides/error-codes.md#permission_denied",- "note": "memory_recall named a source (source_id or source_ids) outside the credential's read grant; nothing was read."+ "note": "memory_recall named a source (source_id or source_ids) outside the credential's read grant; nothing was read. memory_write named a source_id that is not one of the credential's scope sources (reason source_not_attested, also at publication after the operator drops it), or the scope page names readers (reason scope_page_not_shared); nothing was saved."}]},diff --git a/docs/guides/qm.md b/docs/guides/qm.mdindex 4e6dd33a18..744b3f408a 100644--- a/docs/guides/qm.md+++ b/docs/guides/qm.md@@ -4,7 +4,7 @@ QM, a trusted system that already knows who each person is, keeps per-personmemory in a brain through two MCP tools: `memory_recall` reads what the person mayread, and `memory_write` saves facts only they read back. Both run as the person QMnames in the `x-qm-actor` header. The wire contract QM vendors is-[`docs/contracts/qm-memory-provider/v1.json`](../contracts/qm-memory-provider/README.md).+[`docs/contracts/qm-memory-provider/v1.json`](../contracts/qm-memory-provider/README.md); `v2.json` adds scope reads and writes.## Set up on the brain host@@ -46,6 +46,37 @@ a repo exists, saved facts go through the same git-first writer door as `remembeid in `fact_ids`. The same key from the same person replays the firstreceipt; from another person it is a separate write. A write still publishinganswers `status: "pending"` with a `request_id` for `get_write_request`.+- `memory_write {facts, idempotency_key, source_id}` (contract v2) saves the facts on a shared+ scope's page `memory/scope` in that scope source instead, `visibility: world`, readable by every+ credential that reads the source. The source must be in the credential's `--attest-sources`; any other+ source is `permission_denied` reason `source_not_attested`, and the credential's own write source is+ `invalid_params` reason `source_is_member_source` (leave `source_id` out for the person's own page).+ The person is still attested and named in the provenance. A key replays per source.++## Shared scopes (projects, channels, teams)++Give each scope its own source and list it on the QM credential:++```bash+gbrain sources add scope-acme-example --path <dir> # on a repo brain: git-first, like member pages+gbrain sources add scope-acme-example # on a repo-less brain+gbrain auth rescope --client <client_id> --attest-sources scope-acme-example --federated-read <home>,scope-acme-example+```++Listing a source marks it a scope source for good (`sources.config.qm_scope`): revoking or rotating the+credential leaves the mark. A scope source is never federated (`sources federate` refuses, `sources restore`+leaves it unfederated, a federated flag on it is ignored), and no other client, token or registration may+add it to a read grant, so its memory is read only by naming it in `memory_recall` from the scope+credential. A person read (no sources named) never reads a scope source. A source others already read,+`default`, a federated source and the credential's own write source cannot be listed; a credential with+scope sources keeps its attested ops within `forget,forget_fact,get_write_request,memory_recall,memory_write` and cannot+hold `--private-pages granted-sources`. A leaked scope credential secret reads and writes every listed scope:+restrict it with `--operations` to the memory tools. Remote writes to `memory/scope` other than a scope+`memory_write` are refused, and a `memory/scope` page that names readers, is private or sits under a folder+rule takes no scope fact (`scope_page_not_shared`). On a repo-backed scope source, anyone who can push to its+repository can also author `memory/scope.md`, because git is the parent; its history keeps every actor's id+through provenance. Each repo-backed scope source is one more writer claim, so its writes may answer `pending`+until a writer publishes them.On success the result is in `structuredContent`, and `content` holds only the textfor the model. A person not yet linked gets an empty `memory_recall` withdiff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex c9289e493e..d9ada0c3b7 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -1007,6 +1007,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` and `takes_add|update|resolve|supersede`; 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="source_not_attested"></a>`permission_denied` reason `source_not_attested` / `scope_page_not_shared`, `invalid_params` reason `source_is_member_source` | A scope `memory_write` (`source_id`, contract v2) named a source that is not in the credential's `--attest-sources` or not a marked scope source (also when a queued write publishes after the source was dropped), or its own write source; or the scope's `memory/scope` page names readers, is private or sits under a folder rule. Nothing was written. | The operator lists the source with `gbrain auth rescope --client <id> --attest-sources <list>`, or removes `readable_by` / `visibility: private` / the folder rule from `memory/scope`. For the person's own page, leave `source_id` out. See [shared scopes](qm.md#shared-scopes-projects-channels-teams). || <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 6f04e3daab..bdbd0128fe 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -246,7 +246,8 @@ what every named person may read.A trusted system that already knows who each person is (QM) instead holds theattest right: register a client-credentials client, grant it with `gbrain authrescope --client <id> --attest-actor qm [--attest-ops <op,...>]` (default-`get_write_request,memory_recall,memory_write`), and link each person's canonical id with `gbrain+`get_write_request,memory_recall,memory_write`; `--attest-sources <scope sources>` lets `memory_write` save to a shared scope's+`memory/scope` page, see the [QM guide](../guides/qm.md#shared-scopes-projects-channels-teams)), and link each person's canonical id with `gbrainaccess member link <member> --qm <id>` (`unlink`, `links`). Its `x-qm-actor`header then runs each attested operation as that member, never reading privatepages; see [attested-actor refusals](../guides/write-refusals.md#attested-actor-refusals).diff --git a/scripts/build-qm-memory-contract.ts b/scripts/build-qm-memory-contract.tsindex 2d7c3f7a29..8c7875e99b 100644--- a/scripts/build-qm-memory-contract.ts+++ b/scripts/build-qm-memory-contract.ts@@ -13,6 +13,7 @@ import { operations } from '../src/core/operations.ts';import { paramDefToSchema } from '../src/mcp/tool-defs.ts';import { CODES } from '../src/core/error-registry.ts';import { ACTOR_ARGUMENT, ACTOR_DEFERRED_OPS, ACTOR_HEADER, DEFAULT_ATTEST_OPS, EXTERNAL_ID_RE, QM_AUDIENCE_HEADER } from '../src/core/access/actor-model.ts';+import { SCOPE_PAGE_SLUG } from '../src/core/access/principals.ts';import { IDEMPOTENCY_KEY_RE, MEMORY_RECALL_MAX_CHARS, MEMORY_RECALL_QUERY_CHARS, MEMORY_WRITE_KINDS, MEMORY_WRITE_MAX_FACTS, MEMORY_WRITE_PROVENANCE_MAX, OWN_RECENT_WINDOW_HOURS, QM_MEMORY_OPS, unlinkedRecallResult } from '../src/core/ops/qm-memory.ts';export type QmContractVersion = 1 | 2;@@ -76,7 +77,8 @@ export function buildQmMemoryContract(version: QmContractVersion): Record<stringconst codes = v2 ? [...ERROR_CODES, 'permission_denied' as const] : ERROR_CODES;const notes: Record<string, string | undefined> = v2 ? { ...ERROR_NOTES,actor_not_attested: 'With no x-qm-actor header, acting_user is accepted only from a credential bound to a member and only naming that member (its member id or a canonical id linked to it); the call then runs exactly as the credential.',- permission_denied: 'memory_recall named a source (source_id or source_ids) outside the credential\'s read grant; nothing was read.' } : ERROR_NOTES;+ invalid_params: `${ERROR_NOTES.invalid_params} A memory_write whose source_id is the credential's own source carries reason source_is_member_source (omit source_id instead).`,+ permission_denied: 'memory_recall named a source (source_id or source_ids) outside the credential\'s read grant; nothing was read. memory_write named a source_id that is not one of the credential\'s scope sources (reason source_not_attested, also at publication after the operator drops it), or the scope page names readers (reason scope_page_not_shared); nothing was saved.' } : ERROR_NOTES;return {contract: 'gbrain.qm-memory-provider', version,transport: { protocol: 'mcp', session: 'stateless', session_header_issued: false, success_codes_in: 'structuredContent',@@ -116,6 +118,16 @@ export function buildQmMemoryContract(version: QmContractVersion): Record<stringretries: 'never retried server-side; a write still publishing answers pending',committed: { content: 'Saved <N> fact(s).', structuredContent: { status: 'committed', request_id: 'uuid', fact_ids: ['string'] }, fact_ids: 'distinct; facts repeating one claim in a call share one id, and <N> counts distinct facts' },pending: { content: 'Accepted <N> fact(s); <M> still publishing.', structuredContent: { status: 'pending', request_id: 'uuid', fact_ids: ['string'], pending_request_ids: ['uuid'] }, poll: 'get_write_request {request_id}' },+ ...(v2 ? { scope_write: {+ argument: 'source_id',+ rule: 'names one of the credential\'s scope sources (attest_sources, which the brain operator sets on the host); checked on the call and again when the write publishes, so a source the operator drops refuses queued writes; omit it to save for the person alone, exactly as without it',+ saved_as: { page: SCOPE_PAGE_SLUG, readers: 'none: whoever holds read on the scope source, which only scope credentials may', visibility: 'world', provenance: 'qm:<actor id>; <caller provenance>' },+ request_id: 'uuidv5(uuidv5(namespace, "member:<member>#source:<source_id>"), idempotency_key) for the first fact; later facts derive from it; without source_id the member derivation above is unchanged',+ replay: 'per person and source: the same idempotency_key in another source is a separate write',+ pending: 'a scope source with a repository publishes git-first through its writer and answers pending until it commits; a source without one commits to the database',+ recall: 'read it with memory_recall source_id (read as the scope); a memory_recall without sources never reads a scope source',+ withdrawal: 'forget and forget_fact reach only the person\'s own member page, so a scope fact is not_found remotely',+ } } : {}),},errors: {shape: { isError: true, content: 'one JSON text block with top-level code, message, suggestion and optional reason and fix', structuredContent: { error: { code: 'string', message: 'string', reason: 'string?', write_error: 'string?', fix: 'object?' } } },diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.tsindex 29c3b6b411..d9b78d47a3 100644--- a/scripts/check-engine-sql-dynamic.ts+++ b/scripts/check-engine-sql-dynamic.ts@@ -82,7 +82,7 @@ const VETTED_BUILDERS: Record<string, string> = {callerReadersAllowedSql: 'src/core/search/private-visibility.ts: GBRA-231 readersAllowedSql for the current caller, one conjunct per audience identity; each identity passes validIdentity',privacyForCaller: 'src/core/search/private-visibility.ts: the caller privacy arm (TRUE, or the given predicate ORed with private-readable source ids checked by isValidSourceId); callers pass a constant alias and a vetted predicate builder',factVisibilitySql: 'src/core/access/member-facts.ts: visibility values filtered to the constant set world/private; widened only by memberFactAdmitSql, whose member id passed ACCESS_ID_RE (no quote) and whose page test is privatePagesFilterForCaller; no values',- onMemberPageSql: 'src/core/access/member-facts.ts: constant memory/members/ prefix test over a code-provided facts alias; no values',+ onOwnedMemoryPageSql: 'src/core/access/member-facts.ts: constant memory/members/ prefix and memory/scope slug test over a code-provided facts alias; no values',privateProvenanceFilterUnderPolicy: 'src/core/search/private-visibility.ts: constant fact-provenance predicate (readers part with no identity, or the caller identity on its own member page whose id passed ACCESS_ID_RE; privacy part dropped only under an operator relaxation); no values',stagingNeedsTextSql: 'src/core/page-body/schema.ts: constant live-staging text-reference EXISTS predicate over a caller text alias; no values (Wave B purge)',atomRetirementPurgeHold: 'src/core/persistence/atom-retirement-hold.ts: constant #7013 restorable-atom purge-hold predicate over a caller pages alias; no values',diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 02c4a7def9..9b7eb67f22 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -30,7 +30,7 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connesrc/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)src/commands/bootstrap.ts 2153 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts); +4 #8426/#8428: the user-scope MCP registration, its verify and the workspace and Codex SessionEnd hooks start gbrain through the hook launcher (logic in core/setup/hook-launcher.ts); +2 #8435: the user-global opencode entry starts serve through the hook launcher (logic in core/setup/hook-launcher.ts)src/core/minions/worker.ts 1795 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts); +1 GBRA-158 #7239: refusal.ts import (a deterministic refusal ends the job at once; classification in minions/refusal.ts); +3 #7242 lane reservation: lanes import and the longJobNames/shortJobReservedSlots defaults (the claim passes claimExclusions; policy in minions/lanes.ts); +2 #7242 terminal hook: onJobSettled default and the settle call (logic in terminal-hook.ts); #7252 x #7249 merge: both sides grew the file, re-summed (1794 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (1795 measured)-src/commands/sources.ts 2102 ratchet +3 G7b-2: sources host-repo dispatch and help row (body in sources-host-repo.ts and core/persistence/hosted-repo.ts); +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.ts); +1 GBRA-156: the sources add non-federated warning line; re-summed at the master 33d73cb5 merge (2086 measured); +4 G8a git-canonical: sources canonical dispatch, doc line and help rows (body in sources-canonical.ts, plan and apply in persistence/git-conversion.ts); GBRA-156: sources add --json and its next step (logic in sources-add-next.ts); re-summed at the master ade6d638 merge (2100 measured); +2 GBRA-220 PR 2: the unmanaged sources add routes --kind meetings|slack to the shared lifecycle parser (body in sources-add-api.ts); re-summed at the master b85dd645 merge (2102 measured)+src/commands/sources.ts 2103 ratchet +3 G7b-2: sources host-repo dispatch and help row (body in sources-host-repo.ts and core/persistence/hosted-repo.ts); +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.ts); +1 GBRA-156: the sources add non-federated warning line; re-summed at the master 33d73cb5 merge (2086 measured); +4 G8a git-canonical: sources canonical dispatch, doc line and help rows (body in sources-canonical.ts, plan and apply in persistence/git-conversion.ts); GBRA-156: sources add --json and its next step (logic in sources-add-next.ts); re-summed at the master ade6d638 merge (2100 measured); +2 GBRA-220 PR 2: the unmanaged sources add routes --kind meetings|slack to the shared lifecycle parser (body in sources-add-api.ts); re-summed at the master b85dd645 merge (2102 measured); +1 GST-1113: sources federate refuses a QM scope source (one line; the check lives in core/access/attest-sources.ts)src/core/link-extraction.ts 2424 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1); +3 G5 (GBRA-60): extractBodyLinks masks the ## Links fence (links-fence.ts), whose rows are projected as their own edgessrc/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budgetsrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1614 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +4 GST-1094/GST-900: the memory_recall scope-read, member-bound acting_user, recall max_chars and unknown_param _meta-only rows (since TBD until the merge slot)+src/core/behavior-change-notice.ts 1615 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +4 GST-1094/GST-900: the memory_recall scope-read, member-bound acting_user, recall max_chars and unknown_param _meta-only rows (since TBD until the merge slot); +1 GST-1113: the qm_scope_writes_gst1113 row (since TBD until the merge slot; rows are data and cannot move)diff --git a/src/commands/auth-binding.ts b/src/commands/auth-binding.tsindex c3c3e99fa8..2346327273 100644--- a/src/commands/auth-binding.ts+++ b/src/commands/auth-binding.ts@@ -4,17 +4,28 @@ import { memberIdentity, parseMayActFor, parseMemberFlag, type BindingPatch, typimport { ATTEST_SYSTEMS, DEFAULT_ATTEST_OPS, parseAttestOps } from '../core/access/actor.ts';import { operationsByName } from '../core/operations.ts';import { opError } from '../core/ops/contract.ts';+import { assertValidSourceId } from '../core/source-id.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-sources'] 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-sources': 'Pass a comma-separated list of scope sources an attested memory_write may name (source_id), or none.',};+/** GST-1113: `--attest-sources a,b|none`: distinct source ids (each checked against the brain when applied), or null. */+function parseAttestSources(value: string): string[] | null {+ if (value.trim() === 'none') return null;+ const sources = [...new Set(value.split(',').map(s => s.trim()).filter(Boolean))];+ if (!sources.length) throw opError('invalid_params', '--attest-sources needs at least one source.', 'Pass a comma-separated list of scope source ids, or none to clear it.');+ for (const s of sources) assertValidSourceId(s);+ return sources.sort();+}+function parseAttestActor(value: string): string | null {if (value.trim() === 'none') return null;if (ATTEST_SYSTEMS.includes(value.trim())) return value.trim();@@ -40,7 +51,8 @@ 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 patch.attestOps = parseAttestOps(value, name => operationsByName[name]);+ else if (flag === '--attest-ops') patch.attestOps = parseAttestOps(value, name => operationsByName[name]);+ else patch.attestSources = parseAttestSources(value);seen = true;}return { args: out, patch: seen ? patch : null };@@ -52,6 +64,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(', ')}${b.attest_sources?.length ? `; scope sources: ${b.attest_sources.join(', ')}` : ''}` : '';return ` Member: ${b.member ?? 'none'}; may act for: ${b.may_act_for?.join(', ') ?? 'none'}${attest}${b.changed ? (dryRun ? ' (preview, not written)' : ' (updated)') : ''}`;}diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex ef2db55d28..190092cd54 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -1171,6 +1171,7 @@ async function runFederate(engine: BrainEngine, args: string[], value: boolean):console.error(`Source "${id}" not found.`);process.exit(4);}+ if (value) await (await import('../core/access/attest-sources.ts')).assertNotScopeSource(engine, id);const config = parseConfig(src.config);config.federated = value;await engine.executeRaw(diff --git a/src/core/access/actor-model.ts b/src/core/access/actor-model.tsindex 6589d9ed3f..40b2627289 100644--- a/src/core/access/actor-model.ts+++ b/src/core/access/actor-model.ts@@ -27,7 +27,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-1113: `sources` are the scope sources an attested memory_write may name per call (attest_sources); null = none. */+export interface AttestRight { system: string; ops: string[]; sources: string[] | null }export interface AttestedActor { system: string; external_id: string; member: string }/**@@ -40,7 +41,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 sources = Array.isArray(row!.attest_sources) ? (row!.attest_sources as unknown[]).filter((v): v is string => typeof v === 'string') : null;+ return { system, ops, sources: sources?.length ? sources : null };}/** 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..c8f7083958 100644--- a/src/core/access/actor.ts+++ b/src/core/access/actor.ts@@ -21,6 +21,7 @@ import { identityFor } from './principals.ts';import { isMissingSchemaObject } from '../utils.ts';import { memberIdentity } from './members.ts';import { folderAccessFor, memberIdentityFor } from './caller.ts';+import { markedScopeSources, sourceNotAttested } from './attest-sources.ts';import { ACTOR_ARGUMENT, ACTOR_DEFERRED_OPS, ACTOR_HEADER, attestRightFrom, DEFAULT_ATTEST_OPS, EXTERNAL_ID_RE, QM_AUDIENCE_HEADER, type AttestedActor, type AttestRight } from './actor-model.ts';export * from './actor-model.ts';@@ -46,12 +47,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_sources' AS attest_sources, 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_sources' AS attest_sources, 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);@@ -178,11 +179,13 @@ export async function linkedMember(engine: Pick<BrainEngine, 'executeRaw'>, syst* live attest right for the system, and a live link from the id to an enabled member. Returns that member's identity;* throws actor_not_attested (no_attest_right) or actor_unlinked.*/-export async function actorCoverage(engine: Pick<BrainEngine, 'executeRaw'>, caller: ActorCaller, actor: { system: string; external_id: string }, transport?: string, op?: string):+export async function actorCoverage(engine: Pick<BrainEngine, 'executeRaw'>, caller: ActorCaller, actor: { system: string; external_id: string }, transport?: string, op?: string, source?: string):Promise<{ member: string; groups: string[]; identity: string[] }> {const right = await attestRightOf(engine, caller);if (!right || right.system !== actor.system) throw actorNotAttested('no_attest_right', caller, { op: op ?? 'stored', transport });if (op !== undefined && (!right.ops.includes(op) || ACTOR_DEFERRED_OPS.has(op))) throw actorNotAttested('op_not_attested', caller, { op, transport, right });+ // GST-1113: a write accepted for a per-call scope source needs the live right to still list it.+ if (source !== undefined && (!right.sources?.includes(source) || !(await markedScopeSources(engine as BrainEngine, [source])).has(source))) throw sourceNotAttested(source);const linked = EXTERNAL_ID_RE.test(actor.external_id) ? await linkedMember(engine, actor.system, actor.external_id) : null;if (!linked) throw actorUnlinked(actor.external_id, transport);return linked;@@ -192,8 +195,8 @@ export async function actorCoverage(engine: Pick<BrainEngine, 'executeRaw'>, cal* A stored attested authority (a queued write, an agent job) re-resolved through actorCoverage: the same member must* still be covered and, when `op` is given (publication, a job tool call), the operation must still be attested.*/-export async function storedActorIdentity(engine: Pick<BrainEngine, 'executeRaw'>, principal: Principal, actor: AttestedActor, op?: string): Promise<string[]> {- const covered = await actorCoverage(engine, { principal }, actor, undefined, op);+export async function storedActorIdentity(engine: Pick<BrainEngine, 'executeRaw'>, principal: Principal, actor: AttestedActor, op?: string, source?: string): Promise<string[]> {+ const covered = await actorCoverage(engine, { principal }, actor, undefined, op, source);if (covered.member !== actor.member) throw actorUnlinked(actor.external_id);return covered.identity;}diff --git a/src/core/access/attest-sources.ts b/src/core/access/attest-sources.tsnew file mode 100644index 0000000000..c937db2c32--- /dev/null+++ b/src/core/access/attest-sources.ts@@ -0,0 +1,180 @@+/**+ * GST-1113 (gaps 1+2 of the internal QM provider): scope sources. Each shared QM scope (a project, channel, team or org)+ * is its own gbrain source, marked `config.qm_scope: true`. The mark is sticky: it is set when the source first enters a+ * credential's `attest_sources` and no credential change clears it, so the scope's memory stays fenced after the scope+ * credential is revoked, rotated or narrowed. An attested memory_write may name a marked source its credential lists+ * (source_id) and lands on that source's scope page (`memory/scope`, world facts read by whoever holds read on the+ * source). Four rules keep a scope's audience exactly the credentials that list it:+ * - perCallWriteSource / storedPerCallWriteSource: the one exception to one write source per credential, only for the+ * scope page, live at submission and re-checked at publication (actorCoverage with the source);+ * - assertScopeSourceGrant: no credential's read grant may name a marked source it does not list itself;+ * - assertAttestSources: a source joins attest_sources (and is marked) only when no other credential reads it and it is+ * not default, federated or the credential's own write source; it leaves only after the credential's read grant drops it;+ * - a marked source is never federated (isSourceFederated reads the mark), so no connection without a grant reads it.+ * Everything is database state, so a repo-less brain gets it unchanged.+ */+import type { BrainEngine } from '../engine.ts';+import type { OperationContext } from '../ops/contract.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import type { WriteAuthority } from '../persistence/model.ts';+import { currentCallerAccess } from '../search/private-visibility.ts';+import { sqlQueryForEngine, type SqlQuery } from '../sql-query.ts';+import { GrantError, grantFromRow, grantFromTokenRow, type ClientGrant, type GrantSources } from '../grants/model.ts';+import { isScopeSourceConfig, normalizeSourceConfig, parseSourceConfig } from '../sources-load.ts';+import { SCOPE_PAGE_SLUG } from './principals.ts';++/** The attested operations a credential with attest_sources may run: the memory pair, receipts and own-page withdrawal. */+export const SCOPE_ATTEST_OPS: ReadonlySet<string> = new Set(['forget', 'forget_fact', 'get_write_request', 'memory_recall', 'memory_write']);++/**+ * Whether this live write may target `sourceId` instead of the credential's own source: an attested memory_write that+ * named it, on a right listing it, and (when the slug is known) only for the scope page.+ */+export function perCallWriteSource(ctx: Pick<OperationContext, 'remote' | 'attestedOp' | 'attestedSource' | 'auth'>, sourceId: string, slug?: string): boolean {+ if (ctx.remote === false || ctx.attestedOp !== 'memory_write' || ctx.attestedSource !== sourceId) return false;+ if (slug !== undefined && slug !== SCOPE_PAGE_SLUG) return false;+ return !!currentCallerAccess().actor && !!ctx.auth?.attest?.sources?.includes(sourceId);+}++/**+ * The stored form: the scope source an attested memory_write was accepted for, when this authority writes it to the+ * scope page, else null. authorizeWrite exempts the owner's write source for it and re-checks it (actorCoverage).+ */+export function storedPerCallWriteSource(a: Pick<WriteAuthority, 'actingFor' | 'attestedOp' | 'attestedSource' | 'sourceId'>, slug: string): string | null {+ return a.actingFor && !Array.isArray(a.actingFor) && a.attestedOp === 'memory_write' && a.attestedSource === a.sourceId && slug === SCOPE_PAGE_SLUG+ ? a.attestedSource : null;+}++export function sourceNotAttested(sourceId: string): OperationError {+ return opError('permission_denied', `Source ${sourceId} is not one of this connection's scope sources, so nothing was saved.`,+ 'Send source_id only for a scope source the brain operator listed for this credential with gbrain auth rescope --attest-sources, or omit it to save on the person\'s own member page.',+ { reason: 'source_not_attested', why: 'A scope source holds memory every member of that scope reads; only the sources the operator listed may receive it.' });+}++type Db = BrainEngine | SqlQuery;+const sqlOf = (db: Db): SqlQuery => typeof db === 'function' ? db : sqlQueryForEngine(db);++/**+ * The marked scope sources among `ids`. `lock` takes their rows FOR UPDATE (inside the caller's transaction), so a grant+ * write and an attest_sources change on the same source serialize instead of each missing the other's commit.+ */+export async function markedScopeSources(db: Db, ids: readonly string[], lock = false): Promise<Set<string>> {+ if (!ids.length) return new Set();+ const sql = sqlOf(db);+ const list = JSON.stringify([...new Set(ids)]);+ const rows = lock+ ? await sql`SELECT id, config FROM sources WHERE id IN (SELECT jsonb_array_elements_text(${list}::text::jsonb)) ORDER BY id FOR UPDATE`+ : await sql`SELECT id, config FROM sources WHERE id IN (SELECT jsonb_array_elements_text(${list}::text::jsonb))`;+ return new Set(rows.filter(r => isScopeSourceConfig(r.config)).map(r => String(r.id)));+}++export interface CredentialRef { kind: 'token' | 'client'; id: string }+interface CredentialSources { ref: CredentialRef; reads: string[]; write: string | null; attest: string[]; privatePages: boolean; label: string }++const same = (a: CredentialRef, b: CredentialRef | null | undefined) => !!b && a.kind === b.kind && a.id === b.id;+const strings = (v: unknown): string[] => Array.isArray(v) ? v.filter((s): s is string => typeof s === 'string') : [];++/** The sources an OAuth client's grant reads: none, or its write source (default when unset) and federated_read. */+export function clientGrantReads(g: Pick<ClientGrant, 'sourcesNone' | 'sourceId' | 'federatedRead'>): string[] {+ return g.sourcesNone === true ? [] : [...new Set([g.sourceId ?? 'default', ...g.federatedRead])];+}++/** A principal grant's read sources and write source. */+export function sourcesOf(s: GrantSources): { reads: string[]; write: string | null } {+ if (s.kind === 'default') return { reads: ['default'], write: 'default' };+ if (s.kind === 'scalar') return { reads: [s.writeSource], write: s.writeSource };+ if (s.kind === 'federated') return { reads: [...new Set([s.writeSource, ...s.readSources])], write: s.writeSource };+ return { reads: [], write: null };+}++/** Every live credential's read sources, write source and attest_sources, read through the canonical grant model. */+async function credentialSources(sql: SqlQuery): Promise<CredentialSources[]> {+ const clients = await sql`SELECT * FROM oauth_clients WHERE (to_jsonb(oauth_clients)->>'deleted_at') IS NULL`;+ const tokens = await sql`SELECT * FROM access_tokens WHERE revoked_at IS NULL`;+ return [+ ...clients.map(row => {+ const g = grantFromRow(row);+ return { ref: { kind: 'client' as const, id: g.clientId }, reads: clientGrantReads(g), write: g.sourcesNone === true ? null : g.sourceId ?? 'default',+ attest: strings(row.attest_sources), privatePages: row.private_pages === 'granted_sources', label: `OAuth client ${g.clientId}` };+ }),+ ...tokens.map(row => ({ ref: { kind: 'token' as const, id: String(row.id) }, ...sourcesOf(grantFromTokenRow(row).sources),+ attest: strings(row.attest_sources), privatePages: row.private_pages === 'granted_sources', label: `token ${String(row.name ?? row.id)}` })),+ ];+}++/**+ * Refuses a grant whose read sources name a marked scope source this credential does not list. `self` is the credential+ * being written (null for one not inserted yet), whose stored attest_sources are honoured.+ */+export async function assertScopeSourceGrant(db: Db, self: CredentialRef | null, reads: readonly string[], opts: { privatePages?: boolean } = {}): Promise<void> {+ const sql = sqlOf(db);+ if (opts.privatePages && self && (await credentialSources(sql)).find(c => same(c.ref, self))?.attest.length) {+ throw new GrantError('invalid_grant', 'This credential lists scope sources (--attest-sources), so it cannot hold the private-pages grant; nothing changed. '+ + 'A scope credential reads only shared memory: use a separate credential for private pages.');+ }+ if (!reads.length) return;+ const marked = await markedScopeSources(sql, reads, true);+ if (!marked.size) return;+ const own = self ? (await credentialSources(sql)).find(c => same(c.ref, self))?.attest ?? [] : [];+ const reserved = [...marked].filter(s => !own.includes(s)).sort();+ if (!reserved.length) return;+ throw new GrantError('invalid_grant', `Source ${reserved.join(', ')} is a QM scope source, so only the scope credential may read it; nothing changed. `+ + 'A scope\'s memory is read only through the credential that lists it in --attest-sources. Grant another source instead.');+}++function attestInvalid(message: string, suggestion: string): OperationError {+ return opError('invalid_params', message, suggestion, { reason: 'scope_source_reserved',+ why: 'A scope source holds memory every member of that scope reads: only credentials that list it may read it, so it must not already be readable by anyone else.' });+}++/**+ * Checks an attest_sources change for one credential (gbrain auth rescope --attest-sources) and marks each newly listed+ * source, inside the caller's transaction. The mark is never cleared here.+ */+export async function applyAttestSources(db: Db, self: CredentialRef, next: readonly string[] | null, before: readonly string[] | null, opts: { dryRun?: boolean } = {}): Promise<void> {+ const added = (next ?? []).filter(s => !(before ?? []).includes(s));+ const dropped = (before ?? []).filter(s => !(next ?? []).includes(s));+ if (!added.length && !dropped.length) return;+ const sql = sqlOf(db);+ await markedScopeSources(sql, added, true);+ const all = await credentialSources(sql);+ const mine = all.find(c => same(c.ref, self));+ const stillRead = dropped.filter(s => mine?.reads.includes(s));+ if (stillRead.length) {+ throw attestInvalid(`This credential still reads ${stillRead.join(', ')}, so it cannot leave --attest-sources; nothing changed.`,+ 'Remove it from the read grant first (gbrain auth rescope ... --federated-read <list without it>), then from --attest-sources.');+ }+ if (added.length && mine?.privatePages) {+ throw attestInvalid('This credential holds the private-pages grant, so it cannot list scope sources; nothing changed.', 'Clear it first (gbrain auth rescope ... --private-pages none): a scope credential reads only shared memory.');+ }+ for (const s of added) {+ const [row] = await sql`SELECT archived, config FROM sources WHERE id = ${s}`;+ if (!row || row.archived === true) throw attestInvalid(`--attest-sources names ${s}, which is not an active source.`, 'Add a dedicated source for the scope first (gbrain sources add <id>: with a path on a repo brain, without one on a repo-less brain), then list it.');+ if (s === 'default' || parseSourceConfig(row.config).federated === true) throw attestInvalid(`--attest-sources names ${s}, which every connection without a source grant reads (${s === 'default' ? 'the default source' : 'a federated source'}).`, 'Use a dedicated, unfederated source per scope.');+ if (mine?.write === s) throw attestInvalid(`--attest-sources names ${s}, this credential's own write source (where member pages live).`, 'Keep member pages and each scope in separate sources: list only scope sources.');+ const readers = all.filter(c => !same(c.ref, self) && c.reads.includes(s) && !c.attest.includes(s));+ if (readers.length) {+ throw attestInvalid(`--attest-sources names ${s}, which ${readers.slice(0, 3).map(c => c.label).join(', ')}${readers.length > 3 ? ` and ${readers.length - 3} more` : ''} can already read.`,+ `Remove ${s} from those credentials' read grants first, or use a new source for the scope.`);+ }+ }+ if (opts.dryRun) return;+ for (const s of added) {+ const [row] = await sql`SELECT config FROM sources WHERE id = ${s}`;+ await sql`UPDATE sources SET config = ${JSON.stringify({ ...normalizeSourceConfig(row!.config), qm_scope: true, federated: false })}::text::jsonb WHERE id = ${s}`;+ }+}++/** A remote memory_recall that names no source reads no scope source: a scope is read only by naming it. */+export async function withoutScopeSources(ctx: Pick<OperationContext, 'remote' | 'engine'>, sources: string[]): Promise<string[]> {+ if (ctx.remote === false) return sources;+ const marked = await markedScopeSources(ctx.engine, sources);+ return marked.size ? sources.filter(s => !marked.has(s)) : sources;+}++/** Refuses `gbrain sources federate` on a scope source: federation would let every connection without a source grant read it. */+export async function assertNotScopeSource(db: Db, sourceId: string): Promise<void> {+ if ((await markedScopeSources(db, [sourceId])).size) {+ throw attestInvalid(`Source ${sourceId} is a QM scope source, so it cannot be federated.`, 'Leave it unfederated; the scope credential reads it by grant.');+ }+}diff --git a/src/core/access/member-facts.ts b/src/core/access/member-facts.tsindex 83d7e76bd2..9d14b4f868 100644--- a/src/core/access/member-facts.ts+++ b/src/core/access/member-facts.ts@@ -12,12 +12,16 @@*/import { createHash } from 'node:crypto';import type { OperationContext } from '../ops/contract.ts';-import { currentCallerAccess, folderRestrictedSql, privatePagesFilterForCaller } from '../search/private-visibility.ts';-import { ACCESS_ID_RE, MEMBER_PAGE_PREFIX, normalizeReaders } from './principals.ts';+import { currentCallerAccess, folderRestrictedSql, isDerivationPrivate, privatePagesFilterForCaller, withFolderRestricted } from '../search/private-visibility.ts';+import type { BrainEngine } from '../engine.ts';+import { ACCESS_ID_RE, MEMBER_PAGE_PREFIX, normalizeReaders, SCOPE_PAGE_SLUG } from './principals.ts';import { opError, type OperationError } from '../ops/contract.ts';import { slugifyPath } from '../sync.ts';-export { MEMBER_PAGE_PREFIX };+export { MEMBER_PAGE_PREFIX, SCOPE_PAGE_SLUG };++/** GST-1113: the scope page or anything under its reserved prefix. */+export const isScopePageSlug = (slug: string): boolean => slug === SCOPE_PAGE_SLUG || slug.startsWith(`${SCOPE_PAGE_SLUG}/`);export const memberPageSlug = (member: string): string => `${MEMBER_PAGE_PREFIX}${member}`;@@ -68,6 +72,34 @@ export function assertMemberPageWriter(ctx: Pick<OperationContext, 'remote'>, sl`Nothing was written. Pages under ${MEMBER_PAGE_PREFIX} hold one member's own facts; write elsewhere, or save a fact with remember as that member.`);}+/**+ * GST-1113: a remote write to the scope page (memory/scope, or under it) is only an attested memory_write that named its+ * scope source (access/attest-sources.ts); trusted local callers are unaffected. A receipt read (write_request) is not a+ * write: ownRequestAccessible has already kept it to the member who wrote it.+ */+export function assertScopePageWriter(ctx: Pick<OperationContext, 'remote' | 'attestedOp' | 'attestedSource'>, slug: string, opName: string): void {+ if (ctx.remote === false || !isScopePageSlug(slug) || opName === 'write_request') return;+ if (slug === SCOPE_PAGE_SLUG && ctx.attestedOp === 'memory_write' && ctx.attestedSource !== undefined && currentCallerAccess().actor) return;+ throw opError('permission_denied', `${opName}: ${slug} is written remotely only by an attested memory_write to its scope source.`,+ `Nothing was written. ${SCOPE_PAGE_SLUG} holds a shared scope's memory; write elsewhere.`);+}++/** Whether a scope page is shared with its whole source: no readers, no privacy and no folder rule narrow it (a squatted page is not). */+export async function scopePageIsShared(engine: Pick<BrainEngine, 'executeRaw'>, page: { source_id: string; slug: string; type?: string | null; frontmatter?: unknown }): Promise<boolean> {+ return normalizeReaders(page.frontmatter) === null && !isDerivationPrivate(await withFolderRestricted(engine, page));+}++export function scopePageNotShared(sourceId: string): OperationError {+ return opError('permission_denied', `${SCOPE_PAGE_SLUG} in source ${sourceId} names readers, is private or sits under a folder rule, so no scope fact is saved there.`,+ `Nothing was saved. The brain host removes readable_by and visibility: private from ${SCOPE_PAGE_SLUG} in ${sourceId}, or the folder rule covering it (the scope source's read grant is its audience), then the fact can be saved again.`,+ { reason: 'scope_page_not_shared' });+}++/** The frontmatter of the scope page its first fact creates: no readers, so the source's read grant is its audience. */+export function scopePageFrontmatter(): string {+ return ['---', 'type: note', 'title: Scope memory', '---', ''].join('\n');+}+/** The frontmatter of a member page its first fact creates: the member is its only reader. */export function memberPageFrontmatter(member: string): string {return ['---', 'type: note', `title: Memory of ${member}`, 'readable_by:', ` - member:${member}`, '---', ''].join('\n');@@ -96,28 +128,31 @@ export function factVisibilitySql(alias: string, visibility: readonly string[]):return own === 'FALSE' ? listed : `(${listed} OR ${own})`;}-/** Facts on any member page, as SQL: writers that dedup, supersede or contest never cross from one member's page to another. */-export function onMemberPageSql(alias: string): string {- return `starts_with(COALESCE(${alias}.source_markdown_slug, ''), '${MEMBER_PAGE_PREFIX}')`;+/**+ * Facts on any owned memory page (a member page or a scope page), as SQL: writers that dedup, supersede or contest never+ * cross from one such page to another or to an ordinary page.+ */+export function onOwnedMemoryPageSql(alias: string): string {+ return `(starts_with(COALESCE(${alias}.source_markdown_slug, ''), '${MEMBER_PAGE_PREFIX}') OR ${alias}.source_markdown_slug = '${SCOPE_PAGE_SLUG}')`;}/**- * GST-359 D: the withdrawal-ledger subject of a fact, as SQL. A fact on a member page is withdrawn for that page alone- * (its slug), so forgetting it never reaches another member's copy of the same claim; any other fact keeps its entity- * ('*' without one).+ * GST-359 D: the withdrawal-ledger subject of a fact, as SQL. A fact on an owned memory page (a member page, GST-1113 a+ * scope page) is withdrawn for that page alone (its slug), so forgetting it never reaches another copy of the same claim;+ * any other fact keeps its entity ('*' without one).*/export function factWithdrawalSubjectSql(alias: string): string {- return `CASE WHEN ${onMemberPageSql(alias)} THEN ${alias}.source_markdown_slug ELSE COALESCE(${alias}.entity_slug, '*') END`;+ return `CASE WHEN ${onOwnedMemoryPageSql(alias)} THEN ${alias}.source_markdown_slug ELSE COALESCE(${alias}.entity_slug, '*') END`;}-/** Whether withdrawal row `w` covers fact `f`, as SQL: every subject ('*'), the fact's entity, or the member page it sits on. */+/** Whether withdrawal row `w` covers fact `f`, as SQL: every subject ('*'), the fact's entity, or the owned memory page it sits on. */export function withdrawalCoversFactSql(w: string, f: string): string {- return `(${w}.subject = '*' OR ${w}.subject = COALESCE(${f}.entity_slug, '*') OR (${onMemberPageSql(f)} AND ${w}.subject = ${f}.source_markdown_slug))`;+ return `(${w}.subject = '*' OR ${w}.subject = COALESCE(${f}.entity_slug, '*') OR (${onOwnedMemoryPageSql(f)} AND ${w}.subject = ${f}.source_markdown_slug))`;}-/** The member page a claim is checked on for withdrawals, or null: `slug` when it is one, so a page-scoped withdrawal applies there alone. */-export function memberWithdrawalSubject(slug: string | null | undefined): string | null {- return slug && slug.startsWith(MEMBER_PAGE_PREFIX) ? slug : null;+/** The owned memory page a claim is checked on for withdrawals, or null: `slug` when it is one, so a page-scoped withdrawal applies there alone. */+export function ownedPageWithdrawalSubject(slug: string | null | undefined): string | null {+ return slug && (slug.startsWith(MEMBER_PAGE_PREFIX) || slug === SCOPE_PAGE_SLUG) ? slug : null;}/**diff --git a/src/core/access/members.ts b/src/core/access/members.tsindex c9778bba91..5d9fccf774 100644--- a/src/core/access/members.ts+++ b/src/core/access/members.ts@@ -16,7 +16,8 @@ import type { SqlQuery } from '../sql-query.ts';import { opError, type OperationError } from '../ops/contract.ts';import type { Action } from '../agent-output.ts';import { ACCESS_ID_RE, identityFor, normalizePrincipal } from './principals.ts';-import { ACTOR_DEFERRED_OPS } from './actor-model.ts';+import { ACTOR_DEFERRED_OPS, DEFAULT_ATTEST_OPS } from './actor-model.ts';+import { applyAttestSources, SCOPE_ATTEST_OPS } from './attest-sources.ts';export interface MemberRecord {id: string;@@ -289,8 +290,9 @@ export function parseMemberFlag(raw: string): string | null {}/** GST-359 C1: attestActor names the system whose actor header this credential may send (null clears it 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-1113: attestSources lists the scope sources an attested memory_write may name (null clears it; access/attest-sources.ts). */+export interface BindingPatch { member?: string | null; mayActFor?: string[] | null; attestActor?: string | null; attestOps?: string[] | null; attestSources?: string[] | null }+export interface BindingResult { member: string | null; may_act_for: string[] | null; attest_actor?: string; attest_ops?: string[] | null; attest_sources?: string[] | 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 +307,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_sources: string[] | null; grant_types?: string[] | null; confidential?: boolean }>(+ `SELECT member_id, may_act_for, attest_actor, attest_ops, attest_sources${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 +317,14 @@ 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 attestSources = attestActor === null ? null : patch.attestSources === undefined ? before.attest_sources : patch.attestSources?.length ? [...new Set(patch.attestSources)].sort() : null;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.attestSources != null && attestActor === null) throw attestRefused('--attest-sources needs the attest right.', 'Pass --attest-actor qm with it.');+ // GST-1113: a credential that writes scope memory runs only the memory operations as a person, never a general read.+ const outside = attestSources ? (attestOps ?? DEFAULT_ATTEST_OPS).filter(op => !SCOPE_ATTEST_OPS.has(op)) : [];+ if (outside.length) throw attestRefused(`${what} lists scope sources (--attest-sources), so its attested operations stay within ${[...SCOPE_ATTEST_OPS].join(', ')}; ${outside.join(', ')} is not.`, 'Drop those operations (--attest-ops), or use a separate credential for them.');+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 +335,18 @@ 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);- 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]);+ || attestActor !== before.attest_actor || JSON.stringify(attestOps ?? null) !== JSON.stringify(before.attest_ops ?? null)+ || JSON.stringify(attestSources ?? null) !== JSON.stringify(before.attest_sources ?? null);+ if (changed) {+ // GST-1113: the scope-source checks, the marks and the binding commit together, under the scope sources' row locks.+ await engine.transaction(async tx => {+ await applyAttestSources(tx, target, attestSources ?? null, before.attest_sources ?? null, opts);+ if (opts.dryRun) return;+ await tx.executeRaw(`UPDATE ${table} SET member_id = $2, may_act_for = $3::text[], attest_actor = $4, attest_ops = $5::text[], attest_sources = $6::text[] WHERE ${key} = $1`,+ [target.id, member, mayActFor, attestActor, attestOps, attestSources]);+ });}- 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_sources: attestSources ?? null } : {}), changed };}/** A credential bound to a member that cannot read: verification refuses it. */diff --git a/src/core/access/principals.ts b/src/core/access/principals.tsindex 09c44430b4..62a90b98d5 100644--- a/src/core/access/principals.ts+++ b/src/core/access/principals.ts@@ -15,6 +15,8 @@ export const ACCESS_ID_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;export const NOBODY = '!nobody';/** GST-359 C2: where a member's own facts live, `memory/members/<member>` (access/member-facts.ts). */export const MEMBER_PAGE_PREFIX = 'memory/members/';+/** GST-1113: where a shared scope's facts live in its own scope source, `memory/scope` (access/member-facts.ts). */+export const SCOPE_PAGE_SLUG = 'memory/scope';const MAX_READERS = 256;export type Principal = `member:${string}` | `group:${string}`;diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 3e70413583..453997915f 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1414,6 +1414,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.553.0', id: 'empty_nonstring_args_gst927', text: 'Read tools now treat an optional argument as not provided when its own schema rules the value out: 0 where the range starts above zero (limit: 0, around_chunk_id: 0, schema_version: 0 and others), [] where the list must not be empty (types, only, traverse_graph hops), {} where the object needs a field (get_page lines and bytes), false on get_versions diff, and get_page context without grep. These calls used to refuse with invalid_params; now they answer as if the argument were left out. get_page known_as_of beside window or view arguments still refuses, and the refusal names the arguments to drop.' },{ 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: 'qm_scope_writes_gst1113', text: '`memory_write` now takes `source_id`: a credential that lists the source in `gbrain auth rescope --attest-sources` saves the facts on that scope source\'s `memory/scope` page (`visibility: world`, attested to the person); any other source is refused (`permission_denied` reason `source_not_attested`, or `invalid_params` reason `source_is_member_source` for its own write source). Listing a source marks it a QM scope source for good: it is never federated (`sources federate` refuses, `sources restore` leaves it unfederated) and no other grant, token or registration may read it. Remote writes to `memory/scope` other than a scope `memory_write` are refused, and `memory_recall` without sources never reads a scope source.' },{ 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: '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..08265967be 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-sources', '--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-sources', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--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-sources', '--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,7 +77,7 @@ 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-sources', '--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'],@@ -114,7 +114,7 @@ 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-sources', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--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'],@@ -128,7 +128,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],'skillpack-check': ['--accept-pending', '--as', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--timings', '--wait', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--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-sources', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--channels', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--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'],diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex 5260f9eca3..0db4b67e08 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_sources'],['belief_events', 'swept', 'belief_ledger', 'event_key source_id slug subject_kind subject_key event_type origin trust_tier writer_tier tier_basis visibility value value_hash prior_hash state_hash cause claim_fp redacted_fields'],['belief_page_lifetimes', 'out_of_scope', 'text_free_ledger', 'source_id slug'],['belief_redactions', 'out_of_scope', 'text_free_ledger', 'source_id subject_key field field_hash released_hash'],@@ -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_sources'],['oauth_codes', 'out_of_scope', 'secret_material', 'code_hash client_id scopes code_challenge code_challenge_method redirect_uri state resource'],['oauth_grant_audit', 'out_of_scope', 'no_memory_text', 'client_id actor action before_grant after_grant'],['oauth_tokens', 'out_of_scope', 'secret_material', 'token_hash token_type client_id scopes resource grant_type'],diff --git a/src/core/destructive-guard.ts b/src/core/destructive-guard.tsindex 0166cace81..14e091a4c1 100644--- a/src/core/destructive-guard.ts+++ b/src/core/destructive-guard.ts@@ -390,7 +390,9 @@ export async function restoreSource(const result=await runManagedSourceLifecycle(engine,{operation:'restore',sourceId,refederate});return !result.noop;}await assertUnmanagedCanonicalWriter(engine, 'sources restore');- const federatedPatch = refederate ? '{"federated": true}' : '{"federated": false}';+ // GST-1113: a scope source is never federated, so restore leaves it unfederated.+ const federate = refederate && !(await (await import('./access/attest-sources.ts')).markedScopeSources(engine, [sourceId])).size;+ const federatedPatch = federate ? '{"federated": true}' : '{"federated": false}';const rows = await engine.executeRaw<{ id: string }>(`UPDATE sourcesSET archived = false,diff --git a/src/core/engine-sql/facts.ts b/src/core/engine-sql/facts.tsindex 64b3eb4704..f9ce1acff5 100644--- a/src/core/engine-sql/facts.ts+++ b/src/core/engine-sql/facts.ts@@ -30,7 +30,7 @@ import { compileRowNormalizer } from './normalize.ts';import { projectionEligibleSql } from '../eligibility/sql.ts';import { FACT_WITHDRAWAL_STAMP_DEFERRED_SETTING } from '../facts/insert-guard-schema.ts';import { privateProvenanceFilterUnderPolicy } from '../search/private-visibility.ts';-import { factVisibilitySql, onMemberPageSql } from '../access/member-facts.ts';+import { factVisibilitySql, onOwnedMemoryPageSql } from '../access/member-facts.ts';import { storedTrustTier } from '../trust/tier.ts';import { ensureWellFormed } from '../text-safe.ts';@@ -589,7 +589,7 @@ export async function findCandidateDuplicates(? sqlFragment`AND (attributed_to IS NULL OR attributed_to = ${opts.attributedTo})`: sqlFragment``;const members = opts?.onlyPage ? sqlFragment` AND source_markdown_slug = ${opts.onlyPage}`- : opts?.excludeMemberPages ? sqlFragment` AND NOT ${trustedSql(onMemberPageSql('facts'))}` : sqlFragment``;+ : opts?.excludeMemberPages ? sqlFragment` AND NOT ${trustedSql(onOwnedMemoryPageSql('facts'))}` : sqlFragment``;// Validity-lapsed rows are not dedup candidates: a re-stated fact after// its valid_until lapses re-inserts fresh (WP5 read-time TTL honesty).if (opts?.arm === 'keyword') return findKeywordCandidates(exec, source_id, entitySlug, factText, k, opts);@@ -657,7 +657,7 @@ async function findKeywordCandidates(AND (f.valid_until IS NULL OR f.valid_until > now())AND f.source != ALL(${AUDIT_ROW_SOURCES}::text[])${comparable}- ${speaker}${opts.onlyPage ? sqlFragment` AND f.source_markdown_slug = ${opts.onlyPage}` : opts.excludeMemberPages ? sqlFragment` AND NOT ${trustedSql(onMemberPageSql('f'))}` : sqlFragment``}+ ${speaker}${opts.onlyPage ? sqlFragment` AND f.source_markdown_slug = ${opts.onlyPage}` : opts.excludeMemberPages ? sqlFragment` AND NOT ${trustedSql(onOwnedMemoryPageSql('f'))}` : sqlFragment``}AND q.q IS NOT NULL AND to_tsvector(${lang}::regconfig, f.fact) @@ q.qORDER BY ts_rank_cd(to_tsvector(${lang}::regconfig, f.fact), q.q) DESC, f.created_at DESC, f.id DESCLIMIT ${k}diff --git a/src/core/facts/capture-dedup.ts b/src/core/facts/capture-dedup.tsindex e754b9f9fc..ac97d95b90 100644--- a/src/core/facts/capture-dedup.ts+++ b/src/core/facts/capture-dedup.ts@@ -35,7 +35,7 @@ import { corpusFileSessionId } from '../context/corpus-segments.ts';import { writeHeartbeat } from '../context/hook-heartbeat.ts';import { normalizeAlias } from '../search/alias-normalize.ts';import { cosineSimilarity } from './classify.ts';-import { onMemberPageSql } from '../access/member-facts.ts';+import { onOwnedMemoryPageSql } from '../access/member-facts.ts';export const CAPTURE_LANES = ['hook:writeback', 'sweep:corpus', 'hook:compact'] as const;export const CAPTURE_DEDUP_WINDOW_MS = 15 * 60 * 1000;@@ -176,7 +176,7 @@ export async function findCaptureDuplicate(scope: CaptureScope, candidate: CaptuAND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3) AND expired_at IS NULL AND (valid_until IS NULL OR valid_until>now())AND ($4::text IS NULL OR attributed_to IS NULL OR attributed_to=$4)AND ($5::text IS NULL OR source_markdown_slug IS DISTINCT FROM $5 OR source NOT LIKE 'cli:extract-conversation-facts%')- AND NOT ${onMemberPageSql('facts')}+ AND NOT ${onOwnedMemoryPageSql('facts')}ORDER BY created_at DESC, id DESC LIMIT ${CAPTURE_DEDUP_SCAN_LIMIT}`,[scope.sourceId, visibilities, candidate.fact, candidate.attributedTo ?? null, scope.replacingPage ?? null]);const conversation = canonicalConversationKey(scope.sessionId);diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.tsindex 407686c4d6..578398c7ca 100644--- a/src/core/facts/single-prepare.ts+++ b/src/core/facts/single-prepare.ts@@ -10,7 +10,7 @@ import { readSupersessionThreshold } from './supersession-threshold.ts';import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';import { pageNotVisibleError } from '../persistence/page-visibility.ts';import { slugUnderBoundPrefixes } from '../ops/context.ts';-import { memberWithdrawalSubject, onMemberPageSql, withdrawalCoversFactSql } from '../access/member-facts.ts';+import { ownedPageWithdrawalSubject, onOwnedMemoryPageSql, withdrawalCoversFactSql } from '../access/member-facts.ts';export type FactCandidate = FactRow & { source_markdown_slug: string | null; row_num: number | null };export interface FactDecision { status: 'inserted' | 'duplicate' | 'superseded'; candidate: FactCandidate | null; }@@ -52,7 +52,7 @@ export async function prepareFactEmbedding(fact: string, signal?: AbortSignal, d*/export async function assertFactNotWithdrawn(engine: BrainEngine, sourceId: string, input: SingleFactIntent, opts: { excludePrivate?: boolean } = {}): Promise<void> {await assertFactNotPurged(engine, sourceId, input);- if (await isFactWithdrawn(engine, sourceId, input.visibility, input.fact, input.entity_slug, memberWithdrawalSubject(input.page_slug))) throw await factWithdrawnRefusal(engine, sourceId, input, opts);+ if (await isFactWithdrawn(engine, sourceId, input.visibility, input.fact, input.entity_slug, ownedPageWithdrawalSubject(input.page_slug))) throw await factWithdrawnRefusal(engine, sourceId, input, opts);}/**@@ -72,7 +72,7 @@ export async function factWithdrawnRefusal(engine: BrainEngine, sourceId: stringAND ${withdrawalCoversFactSql('w', 'f')}WHERE f.source_id=$1 AND f.visibility=$2 AND f.expired_at IS NOT NULLAND gbrain_fact_fingerprint(f.fact)=gbrain_fact_fingerprint($3) AND (w.subject='*' OR w.subject=$4::text OR w.subject=$5::text)`,- [sourceId, input.visibility, input.fact, input.entity_slug, memberWithdrawalSubject(input.page_slug)]);+ [sourceId, input.visibility, input.fact, input.entity_slug, ownedPageWithdrawalSubject(input.page_slug)]);if (backing?.hidden && !backing.visible) return pageNotVisibleError();}const [row] = await engine.executeRaw<{ subject: string; withdrawn_at: string; visibility: 'world' | 'private' }>(`SELECT w.subject,w.visibility,w.withdrawn_at::text AS withdrawn_at@@ -83,7 +83,7 @@ export async function factWithdrawnRefusal(engine: BrainEngine, sourceId: stringGROUP BY w.subject,w.visibility,w.withdrawn_atHAVING $5::boolean=false OR COALESCE(bool_or(${seen(6)}), false) OR NOT COALESCE(bool_or(f.id IS NOT NULL), false)ORDER BY (w.subject<>'*') DESC, w.withdrawn_at DESC LIMIT 1`,- [sourceId, input.visibility, input.fact, input.entity_slug, opts.excludePrivate === true, memberWithdrawalSubject(input.page_slug)]);+ [sourceId, input.visibility, input.fact, input.entity_slug, opts.excludePrivate === true, ownedPageWithdrawalSubject(input.page_slug)]);const error = verbError('invalid_params', FACT_WITHDRAWN_MESSAGE, FACT_WITHDRAWN_SUGGESTION);if (row) error.withdrawn = { at: new Date(row.withdrawn_at).toISOString(), subject: row.subject === '*' ? 'all_entities' : row.subject, visibility: row.visibility };return error;@@ -125,7 +125,7 @@ export async function decideSingleFact(engine: BrainEngine, sourceId: string, inAND entity_slug IS NOT DISTINCT FROM $2 AND visibility=$3 AND expired_at IS NULLAND (valid_until IS NULL OR valid_until>now()) AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($4)AND ($5::text IS NULL OR attributed_to IS NULL OR attributed_to=$5)${opts.excludePrivate && !input.page_slug ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}- AND ${input.page_slug ? 'source_markdown_slug=$6' : `($6::text IS NULL AND NOT ${onMemberPageSql('facts')})`}+ AND ${input.page_slug ? 'source_markdown_slug=$6' : `($6::text IS NULL AND NOT ${onOwnedMemoryPageSql('facts')})`}ORDER BY id LIMIT 1`, [sourceId, input.entity_slug, input.visibility, input.fact, input.attributed_to ?? null, input.page_slug ?? null]);if (exact) return { status: 'duplicate', candidate: { ...exact, id: Number(exact.id) } };if (embedding && input.entity_slug) {diff --git a/src/core/facts/withdrawal-discovery.ts b/src/core/facts/withdrawal-discovery.tsindex 8cb5209722..9818cd6d12 100644--- a/src/core/facts/withdrawal-discovery.ts+++ b/src/core/facts/withdrawal-discovery.ts@@ -7,7 +7,7 @@ import { fenceTooLargeError, readStoredFence } from '../page-body/read-range.ts'import { FENCE_MAX_BYTES } from '../page-body/limits.ts';import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../facts-fence.ts';import type { BodyRegion } from '../page-body/types.ts';-import { onMemberPageSql } from '../access/member-facts.ts';+import { onOwnedMemoryPageSql } from '../access/member-facts.ts';export const WITHDRAWAL_LIMITS = { targets: 256, targetBytes: 1024 * 1024, scanMs: 10_000, batch: 128, matchRows: 16_384, matchBytes: 8 * 1024 * 1024 } as const;export interface WithdrawalTarget { slug: string; page_id: number; revision: string }@@ -130,7 +130,7 @@ export async function discoverWithdrawalTargets(engine: BrainEngine, sourceId: sFROM jsonb_to_recordset($2::text::jsonb) k(visibility text,fact_hash text,subject text,norm text)JOIN facts f ON f.source_id=$1 AND f.visibility=k.visibilityAND gbrain_fact_fingerprint(f.fact)=COALESCE(encode(sha256(convert_to(k.norm,'UTF8')),'hex'),k.fact_hash)- AND (k.subject='*' OR f.entity_slug=k.subject OR (${onMemberPageSql('f')} AND f.source_markdown_slug=k.subject))+ AND (k.subject='*' OR f.entity_slug=k.subject OR (${onOwnedMemoryPageSql('f')} AND f.source_markdown_slug=k.subject))JOIN pages p ON p.source_id=f.source_id AND p.slug=COALESCE(f.source_markdown_slug,f.entity_slug)`, [sourceId, keys]);for (const row of provenance) affected.add(row.id);if (affected.size > WITHDRAWAL_LIMITS.targets) await refuseAffected(engine, sourceId, affected);diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.tsindex bce0dfed37..65f237593f 100644--- a/src/core/facts/withdrawal.ts+++ b/src/core/facts/withdrawal.ts@@ -10,7 +10,7 @@ import { outcomeMarkerSql } from './audit-sources.ts';import { coverageActive, noteBelief, readLedgerSource, withBeliefBatch } from '../belief/ledger.ts';import { createPageVersion } from '../page-state/versions.ts';import { validateSlug } from '../utils.ts';-import { factWithdrawalSubjectSql, onMemberPageSql } from '../access/member-facts.ts';+import { factWithdrawalSubjectSql, onOwnedMemoryPageSql } from '../access/member-facts.ts';export interface WithdrawalCommit {withdrawn: boolean;@@ -57,7 +57,7 @@ export async function recordFactWithdrawal(): Promise<WithdrawalCommit> {// GST-359 D: an attested person's own member-page fact (memberPage) is admitted besides world facts; the caller checked it.const admit = `AND ($3::boolean=false OR visibility='world' OR (visibility='private' AND source_markdown_slug=$4::text))${opts.excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}`;- const pageScoped = `(${onMemberPageSql('facts')} AND source_markdown_slug=$4)`;+ const pageScoped = `(${onOwnedMemoryPageSql('facts')} AND source_markdown_slug=$4)`;return engine.transaction(async tx => {// A managed caller takes this EXCLUSIVE source lock before authority,// counters and request rows. Repeating an already-held lock is safe.diff --git a/src/core/grants/legacy-token.ts b/src/core/grants/legacy-token.tsindex 5fd25ef067..37f02e79ba 100644--- a/src/core/grants/legacy-token.ts+++ b/src/core/grants/legacy-token.ts@@ -37,6 +37,7 @@ import {tokenGrantFromPermissions, validatePrincipalGrant, TOKEN_GRANT_COLUMNS, type LegacyGrantAxis, type PrincipalGrant, type PrivatePagesGrant,} from './model.ts';import { parsePrivatePagesFlag } from './cli.ts';+import { assertScopeSourceGrant, sourcesOf } from '../access/attest-sources.ts';export type { LegacyGrantAxis } from './model.ts';@@ -198,6 +199,8 @@ function schemaError(error: unknown): unknown {/** Write the unified columns and the `permissions` mirror in one UPDATE; returns the new revision. */async function writeTokenGrant(tx: BrainEngine, row: Record<string, unknown>, grant: TokenGrantAxes, scopes?: string[]): Promise<number> {+ const before = sourcesOf(grantFromTokenRow(row).sources).reads;+ await assertScopeSourceGrant(tx, { kind: 'token', id: String(row.id) }, sourcesOf(grant.sources).reads.filter(s => !before.includes(s)));const [written] = await executeRawJsonb<{ grant_revision: number }>(tx,`UPDATE access_tokens SET source_grant = $2, source_id = $3, federated_read = $4::text[], allowed_operations = $5::text[],@@ -304,6 +307,7 @@ async function rescopeInTransaction(tx: BrainEngine, args: RescopeTokenArgs): Prconst write = !args.dryRun && (edits || Boolean(args.adopt));const revision = write ? await writeTokenGrant(tx, row, next, args.scopes) : current.revision;if (write && privatePages !== current.privatePages) {+ await assertScopeSourceGrant(tx, { kind: 'token', id }, [], { privatePages: privatePages === 'granted_sources' });await tx.executeRaw('UPDATE access_tokens SET private_pages = $2 WHERE id = $1::uuid', [id, privatePages]);}return {diff --git a/src/core/grants/service.ts b/src/core/grants/service.tsindex c9a5fd06a2..53fc5f4654 100644--- a/src/core/grants/service.ts+++ b/src/core/grants/service.ts@@ -2,6 +2,7 @@ import type { BrainEngine } from '../engine.ts';import { sqlQueryForEngine, type SqlQuery } from '../sql-query.ts';import { GrantError, grantFromRow, normalizeGrantBrain, validateClientGrant, type ClientGrant, type GrantPatch, type GrantValidationContext } from './model.ts';import { catalogProvenance, grantCatalog, type CatalogProvenance } from './profiles.ts';+import { assertScopeSourceGrant, clientGrantReads } from '../access/attest-sources.ts';export type GrantDatabase = BrainEngine | SqlQuery;const query = (db: GrantDatabase): SqlQuery => typeof db === 'function' ? db : sqlQueryForEngine(db);@@ -77,6 +78,7 @@ export async function readClientCatalogProvenance(db: GrantDatabase, clientId: s/** Called after validation. Never exposes the credential in the audit document. */export async function insertClientGrant(sql: SqlQuery, grant: ClientGrant, metadata: GrantClientMetadata, actor = 'operator'): Promise<void> {+ await assertScopeSourceGrant(sql, null, clientGrantReads(grant));await sql`WITH created AS (INSERT INTO oauth_clients (client_id, client_name, client_secret_hash, redirect_uris, grant_types,@@ -190,6 +192,8 @@ export async function recordFirstConsentInTransaction(db: GrantDatabase, clientI/** One UPDATE+audit statement: SQL-only provider callers get atomicity too. */export async function persistGrant(sql: SqlQuery, before: ClientGrant, after: ClientGrant, actor: string, action: string): Promise<void> {+ const widened = clientGrantReads(after).filter(s => !clientGrantReads(before).includes(s));+ await assertScopeSourceGrant(sql, { kind: 'client', id: before.clientId }, widened, { privatePages: after.privatePages === 'granted_sources' && before.privatePages !== 'granted_sources' });const result = await sql`WITH updated AS (UPDATE oauth_clients SETdiff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 791d1713d6..51d74048c7 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -6252,6 +6252,10 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["type": "string","description": "Set by the trusted system: equal to the x-qm-actor header, or omit.","fullSurfaceOnly": true+ },+ "source_id": {+ "type": "string",+ "description": "Save on this scope source's shared page (memory/scope), read by everyone who reads that source; it must be one of the credential's scope sources. Omit to save for the person alone."}},"scope": "write",diff --git a/src/core/ops/context.ts b/src/core/ops/context.tsindex dd13aab7d9..42b987f5ec 100644--- a/src/core/ops/context.ts+++ b/src/core/ops/context.ts@@ -25,7 +25,7 @@ import { stampEvidence } from '../search/evidence.ts';import { captureEvalCandidate, isEvalCaptureEnabled, isEvalScrubEnabled } from '../eval-capture.ts';import type { SearchResult, HybridSearchMeta, PageReadScope, PageReadPolicy } from '../types.ts';import { resolveExcludePrivatePages, isPrivatePage } from '../search/private-visibility.ts';-import { assertMemberPageWriter } from '../access/member-facts.ts';+import { assertMemberPageWriter, assertScopePageWriter } from '../access/member-facts.ts';import { pageNotVisibleError, remoteTargetHidden } from '../persistence/page-visibility.ts';// --- Agent-contract fixes shared by the op error sites ---@@ -376,6 +376,7 @@ export function slugOutsideCallerFence(ctx: OperationContext, slug: string): boo*/export function enforceClientSlugFence(ctx: OperationContext, slug: string, opName: string): void {assertMemberPageWriter(ctx, slug, opName);+ assertScopePageWriter(ctx, slug, opName);if (ctx.auth?.fenceProjectionDegraded) {throw opError('permission_denied',diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 1477396e24..82f91c4b68 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -306,7 +306,7 @@ export interface AuthInfo {* the operations an attested call may run. 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[]; sources: string[] | null } | null;/*** Human-readable agent name resolved at token-verification time.* For OAuth clients this is `oauth_clients.client_name`; for legacy@@ -597,6 +597,11 @@ export interface OperationContext {* never from arguments; the stored authority keeps it, so publication re-checks that operation's attest right.*/attestedOp?: string;+ /**+ * GST-1113: the scope source an attested memory_write named (source_id), allowed by the credential's attest_sources+ * (access/attest-sources.ts). Set by the handler, never from arguments; the stored authority keeps it.+ */+ attestedSource?: string;/*** #4216 — defer chunk embeddings on put_page writes: importFromContent runs* noEmbed and the standing embed machinery (embed phase / phase-enddiff --git a/src/core/ops/qm-memory.ts b/src/core/ops/qm-memory.tsindex b73e73d702..9fdcd59f31 100644--- a/src/core/ops/qm-memory.ts+++ b/src/core/ops/qm-memory.ts@@ -24,7 +24,8 @@ import { parseSourceIdsParam, requestSourceScope, SOURCE_IDS_PARAM } from './seaimport type { FactRow } from '../engine.ts';import { resolveReadEligibility } from '../eligibility/policy.ts';import { currentCallerAccess, resolveExcludePrivatePages, withCallerAccess, type CallerAccess } from '../search/private-visibility.ts';-import { callerMember, memberPageSlug } from '../access/member-facts.ts';+import { callerMember, memberPageSlug, SCOPE_PAGE_SLUG } from '../access/member-facts.ts';+import { markedScopeSources, sourceNotAttested, withoutScopeSources } from '../access/attest-sources.ts';import { ACTOR_ARGUMENT, ACTOR_HEADER } from '../access/actor-model.ts';import { uuidV5 } from '../persistence/preconditions.ts';import { isStrictIsoDateTime } from '../utils.ts';@@ -134,7 +135,7 @@ async function recallSources(ctx: OperationContext, p: Record<string, unknown>):const sourceIds = parseSourceIdsParam(ctx, 'memory_recall', p.source_ids);if (sourceIdParam === undefined && sourceIds === undefined) {const scope = federatedSearchScope(ctx, undefined);- return { sources: [...new Set(scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? ctx.sourceId ?? 'default'])], named: false };+ return { sources: await withoutScopeSources(ctx, [...new Set(scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? ctx.sourceId ?? 'default'])]), named: false };}const scope = await requestSourceScope(ctx, sourceIdParam, sourceIds);return { sources: [...new Set(scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : []))], named: true };@@ -185,8 +186,9 @@ const memory_recall: Operation = {};/** The request id of fact `index` in a memory_write: uuidv5 of the key under the member's own namespace for fact 0, derived from it after. */-export async function memoryWriteRequestId(member: string, idempotencyKey: string, index: number): Promise<string> {- const root = uuidV5(uuidV5(QM_MEMORY_REQUEST_NAMESPACE, `member:${member}`), idempotencyKey);+export async function memoryWriteRequestId(member: string, idempotencyKey: string, index: number, scopeSource?: string): Promise<string> {+ // GST-1113: a scope write keys under (member, source), so one key never replays across sources; '#' is outside member ids.+ const root = uuidV5(uuidV5(QM_MEMORY_REQUEST_NAMESPACE, scopeSource === undefined ? `member:${member}` : `member:${member}#source:${scopeSource}`), idempotencyKey);if (index === 0) return root;const { childRequestId } = await import('../remember-batch.ts');return childRequestId(root, index);@@ -242,6 +244,7 @@ const memory_write: Operation = {},idempotency_key: { type: 'string', required: true, description: '1-128 visible ASCII characters; the same key replays this write.' },[ACTOR_ARGUMENT]: actorParam,+ source_id: { type: 'string', description: `Save on this scope source's shared page (${SCOPE_PAGE_SLUG}), read by everyone who reads that source; it must be one of the credential's scope sources. Omit to save for the person alone.` },},scope: 'write',annotations: { title: 'memory_write (QM memory write)', idempotentHint: true },@@ -255,15 +258,22 @@ const memory_write: Operation = {throw invalid('idempotency_key must be 1 to 128 visible ASCII characters (no spaces).', 'Send a stable key per write, for example a UUID; the same key replays the same write.');}const key = p.idempotency_key;+ const scopeSource = p.source_id === undefined ? undefined : parseSourceIdParam(p.source_id, 'memory_write');+ if (scopeSource !== undefined && scopeSource === (ctx.auth?.sourceId ?? ctx.sourceId)) {+ throw opError('invalid_params', `source_id ${scopeSource} is this connection's own source, where the person's member page lives; nothing was saved.`,+ 'Omit source_id to save for the person alone; send source_id only for a shared scope\'s source.', { reason: 'source_is_member_source' });+ }+ if (scopeSource !== undefined && (!ctx.auth?.attest?.sources?.includes(scopeSource) || !(await markedScopeSources(ctx.engine, [scopeSource])).has(scopeSource))) throw sourceNotAttested(scopeSource);+ const writeCtx: OperationContext = scopeSource === undefined ? ctx : { ...ctx, sourceId: scopeSource, attestedSource: scopeSource };const parsed = parseFacts(p.facts, actor.external_id);// Every fact's replay intent carries the whole batch, so a key reused with more, fewer or other facts is an// idempotency_conflict at its first fact, before anything new is written.const qm_batch = createHash('sha256').update(JSON.stringify(parsed)).digest('hex');- const items = await Promise.all(parsed.map(async (f, i) => ({ ...f, qm_batch, request_id: await memoryWriteRequestId(actor.member, key, i) })));+ const items = await Promise.all(parsed.map(async (f, i) => ({ ...f, qm_batch, request_id: await memoryWriteRequestId(actor.member, key, i, scopeSource) })));const { verbOperations } = await import('../verbs.ts');const remember = verbOperations.find(op => op.name === 'remember')!;for (const [index, item] of items.entries()) {- try { await remember.handler({ ...ctx, attestedOp: 'memory_write', dryRun: true }, item); } catch (e) {+ try { await remember.handler({ ...writeCtx, attestedOp: 'memory_write', dryRun: true }, item); } catch (e) {if (e instanceof OperationError) e.message = `facts[${index}]: ${e.message} Nothing was saved.`;throw e;}@@ -275,8 +285,10 @@ const memory_write: Operation = {const principal = await requestPrincipalForContext(ctx);for (const [index, item] of parsed.entries()) {if (await getWriteRequest(ctx.engine, principal, items[index]!.request_id)) continue;- const intent = { fact: item.fact as string, kind: (item.kind ?? 'fact') as never, visibility: 'private' as const, entity_slug: null, page_slug: memberPageSlug(actor.member) };- try { await assertFactNotWithdrawn(ctx.engine, ctx.sourceId ?? 'default', intent, { excludePrivate }); } catch (e) {+ const intent = scopeSource === undefined+ ? { fact: item.fact as string, kind: (item.kind ?? 'fact') as never, visibility: 'private' as const, entity_slug: null, page_slug: memberPageSlug(actor.member) }+ : { fact: item.fact as string, kind: (item.kind ?? 'fact') as never, visibility: 'world' as const, entity_slug: null, page_slug: SCOPE_PAGE_SLUG };+ try { await assertFactNotWithdrawn(ctx.engine, writeCtx.sourceId ?? 'default', intent, { excludePrivate }); } catch (e) {if (e instanceof OperationError) e.message = `facts[${index}]: ${e.message} Nothing was saved.`;throw e;}@@ -285,7 +297,7 @@ const memory_write: Operation = {const saved: Array<{ request_id: string; fact_id?: string; pending?: true }> = [];for (const [index, item] of items.entries()) {try {- const out = await remember.handler({ ...ctx, attestedOp: 'memory_write' }, item) as { id?: string | number } | null;+ const out = await remember.handler({ ...writeCtx, attestedOp: 'memory_write' }, item) as { id?: string | number } | null;saved.push({ request_id: item.request_id, ...(out?.id !== undefined ? { fact_id: String(out.id) } : {}) });} catch (e) {if (e instanceof OperationError && e.writeError === 'write_pending') { saved.push({ request_id: item.request_id, pending: true }); continue; }diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.tsindex 25a04081cf..d5ed750384 100644--- a/src/core/persistence/authority.ts+++ b/src/core/persistence/authority.ts@@ -13,6 +13,7 @@ import { authorizePageVisibility, excludesPrivateWritesAtAdmission } from './pagimport { currentCallerAccess } from '../search/private-visibility.ts';import { parseStoredActor, storedActorIdentity } from '../access/actor.ts';import { sameAttestedActor } from '../access/member-facts.ts';+import { perCallWriteSource, storedPerCallWriteSource } from '../access/attest-sources.ts';import { pipelined, transactionMemo } from '../page-state/transactions.ts';function deny(message: string): never { throw new OperationError('permission_denied', message, 'Inspect the current writer registration and source/operation grants.'); }@@ -69,6 +70,7 @@ export async function submissionAuthority(ctx: OperationContext, operation: striexcludePrivate: (actingFor !== undefined && currentCallerAccess().hidePrivate) || await excludesPrivateWritesAtAdmission(ctx.engine, ctx.remote !== false),...(actingFor ? { actingFor } : {}),...(access?.actor && ctx.attestedOp ? { attestedOp: ctx.attestedOp } : {}),+ ...(perCallWriteSource(ctx, sourceId, slug) ? { attestedSource: sourceId } : {}),autoLinkTrusted: ctx.remote === false || ctx.viaSubagent === true && !ctx.auth && !!ctx.allowedSlugPrefixes?.length,takesHolders: ctx.remote === false ? null : [...(ctx.takesHoldersAllowList ?? ['world'])],scopes: [...(ctx.auth?.scopes ?? localGrant?.scopes ?? [])],@@ -79,7 +81,7 @@ export async function submissionAuthority(ctx: OperationContext, operation: stridelegatedPrefixes: ctx.allowedSlugPrefixes?.length ? [...ctx.allowedSlugPrefixes]: typeof ctx.subagentId === 'number' ? [`wiki/agents/${ctx.subagentId}/*`] : [] } : {}),};- if (ctx.auth?.sourceId != null && ctx.auth.sourceId !== sourceId) deny('The source is outside this writer grant.');+ if (ctx.auth?.sourceId != null && ctx.auth.sourceId !== sourceId && !a.attestedSource) deny('The source is outside this writer grant.');if (!prefixAllowed(a.slugPrefixes, slug)) deny('The target is outside this writer grant.');await authorizeWrite(ctx.engine, a, operation, slug);if (!skillWrite(operation)) await authorizePageVisibility(ctx.engine, a, slug);@@ -152,13 +154,15 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, operaif (a.actingFor && !Array.isArray(a.actingFor)) {const actor = parseStoredActor(a.actingFor);if (!actor) deny('The accepted attested actor is malformed.');- await storedActorIdentity(engine, a.principal, actor, a.attestedOp ?? operation);+ await storedActorIdentity(engine, a.principal, actor, a.attestedOp ?? operation, storedPerCallWriteSource(a, slug) ?? undefined);}+ // GST-1113: the one exception to the owner's single write source (the scope page), re-checked against the live attest_sources above.+ const ownSource = (source: unknown) => source === a.sourceId || storedPerCallWriteSource(a, slug) !== null;const suffix = lock ? ' FOR SHARE' : '';if (a.principal.kind === 'oauth_client') {const [row] = await engine.executeRaw<Record<string, unknown>>(`SELECT deleted_at,scope,source_id,allowed_operations,bound_slug_prefixes,bound_tools,delegated_namespace,delegated_slug_prefixes FROM oauth_clients WHERE client_id=$1${suffix}`, [a.principal.id]);- if (!row || row.deleted_at != null || row.source_id !== a.sourceId) deny('The owning OAuth client is revoked or its source changed.');+ if (!row || row.deleted_at != null || !ownSource(row.source_id)) deny('The owning OAuth client is revoked or its source changed.');const scopes = typeof row.scope === 'string' ? row.scope.split(/\s+/) : [];assertSkillWriteScopes(scopes, operation, a.remote);if (skillWrite(operation) && (!strings(row.allowed_operations) || !row.allowed_operations.includes(operation))) deny('The current skill operation grant was removed.');@@ -178,7 +182,7 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, operaassertSkillWriteScopes(normalizeTokenScopes(row.scopes) ?? [], operation, a.remote);const liveOperations = grant.allowedOperations;if (!operationAllowed(liveOperations, granted) || skillWrite(operation) && !liveOperations?.includes(operation)) deny('The current legacy operation grant excludes this write.');- if (!hasScope(grant.scopes, 'write') || authSourcesFromGrant(grant).sourceId !== a.sourceId) deny('The current token no longer permits this source write.');+ if (!hasScope(grant.scopes, 'write') || !ownSource(authSourcesFromGrant(grant).sourceId)) deny('The current token no longer permits this source write.');return;}if (a.principal.kind === 'local_cli' || a.principal.kind === 'local_stdio') {@@ -273,7 +277,7 @@ function onceReads(engine: BrainEngine): BrainEngine {export async function ownRequestAccessible(ctx: OperationContext, row: WriteRequest): Promise<boolean> {try {const engine = onceReads(ctx.engine);- const auth = await submissionAuthority({ ...ctx, engine, attestedOp: row.authority?.attestedOp }, row.operation, row.source_id, row.source_incarnation, row.slug);+ const auth = await submissionAuthority({ ...ctx, engine, attestedOp: row.authority?.attestedOp, attestedSource: row.authority?.attestedSource }, row.operation, row.source_id, row.source_incarnation, row.slug);if (auth.principal.kind !== row.principal_kind || auth.principal.id !== row.principal_id) return false;// GST-359 C2: under one attest credential, a receipt belongs to the person it was written for.if (!sameAttestedActor(row.authority?.actingFor)) return false;diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 60ed34db2a..61737e1360 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -30,7 +30,8 @@ import { prepareMemoryMutation } from './memory-prepare.ts';import { retryWriteAdmission } from './admission-retry.ts';import { privateProvenanceFilterFragment, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';import { markBeliefCommits } from '../belief/append.ts';-import { callerMember, memberFactAdmitSql, memberFactPage, memberPageIsOwn, memberPageNotOwned, memberPageSlug } from '../access/member-facts.ts';+import { callerMember, memberFactAdmitSql, memberFactPage, memberPageIsOwn, memberPageNotOwned, memberPageSlug, scopePageIsShared, scopePageNotShared, SCOPE_PAGE_SLUG } from '../access/member-facts.ts';+import { perCallWriteSource } from '../access/attest-sources.ts';export { prepareMemoryMutation } from './memory-prepare.ts';/** Only semantic appends without an explicit caller revision can be recomputed. */@@ -50,7 +51,7 @@ async function submission(ctx: OperationContext, operation: string, params: Recoconst p: Record<string, unknown> = { ...params, ...parseMutationPrecondition(params) };const requestId = typeof p.request_id === 'string' ? p.request_id : randomUUID();const sourceId = typeof p.source_id === 'string' ? p.source_id : ctx.sourceId ?? 'default';- if (ctx.remote !== false && sourceId !== (ctx.auth?.sourceId ?? ctx.sourceId ?? 'default')) {+ if (ctx.remote !== false && sourceId !== (ctx.auth?.sourceId ?? ctx.sourceId ?? 'default') && !perCallWriteSource(ctx, sourceId)) {throw opError('permission_denied', 'This source is outside the current write grant.',`This connection may write only to source ${ctx.auth?.sourceId ?? ctx.sourceId ?? 'default'}. Omit source_id to write there, or ask the brain host's operator to grant source ${sourceId}.`);}@@ -91,7 +92,8 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourcthrow opError('page_not_found', 'The target entity is not writable by this caller.',`Entity page ${slug} in source ${sourceId} is deleted or not visible to this caller, so nothing was saved. Remember the fact against a visible entity, or without an entity (it is then filed under memory/unattributed).`);}- if (memberPage && snapshot && !memberPageIsOwn(memberPage, snapshot.page.frontmatter)) throw memberPageNotOwned(memberPage);+ if (memberPage === SCOPE_PAGE_SLUG) { if (snapshot && !await scopePageIsShared(ctx.engine, { ...snapshot.page, source_id: sourceId, slug })) throw scopePageNotShared(sourceId); }+ else if (memberPage && snapshot && !memberPageIsOwn(memberPage, snapshot.page.frontmatter)) throw memberPageNotOwned(memberPage);if (inferred && !snapshot) throw new InferredTargetRejected('NO_ENTITY');// Wave B: a segmented entity page over the single-string ceiling cannot take a fence row; named or inferred, the save refuses// before admission instead of misfiling it. Below the ceiling an inferred target's checks read the page back whole, as preparation does.@@ -193,8 +195,10 @@ export async function submitRememberMutation(ctx: OperationContext, params: Recoconst entity = typeof p.entity === 'string' && !isNullLikeEntity(p.entity) ? p.entity.trim() : null;const resolved = entity ? await resolveRememberEntity(ctx, sourceId, entity) : null;// GST-359 C2: a remote member's fact is private, on its member page, and never inferred onto another page.- const memberPage = memberFactPage(ctx);- const call: RememberCall = memberPage ? { p: { ...p, visibility: 'private', infer_entity: false }, visibilityDefaulted: false }+ // GST-1113: an attested memory_write that named a scope source saves world facts on that source's scope page instead.+ const scopePage = perCallWriteSource(ctx, sourceId);+ const memberPage = scopePage ? SCOPE_PAGE_SLUG : memberFactPage(ctx);+ const call: RememberCall = memberPage ? { p: { ...p, visibility: scopePage ? 'world' : 'private', infer_entity: false }, visibilityDefaulted: false }: { p, visibilityDefaulted: opts.visibilityDefaulted === true };const inference = entity === null && !memberPage ? await inferRememberTarget(ctx, sourceId, source, call) : null;const linked = inference && 'target' in inference ? inference : null;@@ -220,7 +224,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco// The transport's session (MCP `_meta.session_id`) is recorded on the fact, as extract_facts records// it, so recall's session_id filter finds single facts too. Identity only — never a trust surface.intent: { ...callerIntent, entity_slug: entitySlug, fence, valid_from: typeof p.valid_from === 'string' ? new Date(p.valid_from).toISOString() : new Date().toISOString(), valid_until: validUntil?.toISOString() ?? null,- visibility, ...(call.visibilityDefaulted ? { visibility_defaulted: true } : {}), ...(memberPage ? { member_page: true } : {}),+ visibility, ...(call.visibilityDefaulted ? { visibility_defaulted: true } : {}), ...(scopePage ? { scope_page: true } : memberPage ? { member_page: true } : {}),...(linked ? { entity_inferred: linked.via } : {}), ...(inference && 'warning' in inference ? { entity_warning: inference.warning } : {}),session_id: ctx.sessionId ?? null },authority, worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null });diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 968d11c751..b13fc9e8ee 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -23,7 +23,7 @@ import { prepareFenceFactAppend, prepareFenceFactCreate, requestReceiptFix, typeimport { privateProvenanceFilterFragment, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';import { tightenToPage } from '../facts/visibility.ts';import { noteBelief } from '../belief/ledger.ts';-import { MEMBER_PAGE_PREFIX, memberPageFrontmatter, memberPageIsOwn, memberPageNotOwned, onMemberPageSql } from '../access/member-facts.ts';+import { MEMBER_PAGE_PREFIX, memberPageFrontmatter, memberPageIsOwn, memberPageNotOwned, onOwnedMemoryPageSql, scopePageFrontmatter, scopePageIsShared, scopePageNotShared } from '../access/member-facts.ts';function conflict(row: WriteRequest): never {throw opError('revision_conflict', 'The memory changed during semantic preparation.',@@ -57,7 +57,7 @@ async function activeUnlinkedCopy(engine: BrainEngine, sourceId: string, input:const [row] = await engine.executeRaw<{ id: number }>(`SELECT id FROM factsWHERE source_id=$1 AND visibility=$2 AND entity_slug IS NULL AND expired_at IS NULLAND (valid_until IS NULL OR valid_until > now()) AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3)${excludePrivate && !input.page_slug ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}- AND ${input.page_slug ? 'source_markdown_slug=$4' : `($4::text IS NULL AND NOT ${onMemberPageSql('facts')})`}+ AND ${input.page_slug ? 'source_markdown_slug=$4' : `($4::text IS NULL AND NOT ${onOwnedMemoryPageSql('facts')})`}ORDER BY id DESC LIMIT 1`, [sourceId, input.visibility, input.fact, input.page_slug ?? null]);return row ? Number(row.id) : null;}@@ -73,12 +73,13 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeconst p = row.intent;const input: SingleFactIntent = { fact: String(p.fact).trim(), kind: (p.kind ?? 'fact') as SingleFactIntent['kind'],visibility: (p.visibility ?? 'world') as SingleFactIntent['visibility'], entity_slug: p.entity_slug as string | null,- ...(p.member_page === true ? { page_slug: row.slug } : {}) };+ ...(p.member_page === true || p.scope_page === true ? { page_slug: row.slug } : {}) };const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });- // GST-359 C2: a member page another write created after this one was accepted is the same page, not a recreation.- const createdSince = p.member_page === true && row.page_id === null && snapshot !== null && !snapshot.page.deleted_at;+ // GST-359 C2: a member page (GST-1113: or scope page) another write created after this one was accepted is the same page, not a recreation.+ const createdSince = (p.member_page === true || p.scope_page === true) && row.page_id === null && snapshot !== null && !snapshot.page.deleted_at;if ((snapshot?.page.id ?? null) !== row.page_id && !createdSince) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted entity was deleted or recreated.');if (p.member_page === true && snapshot && !memberPageIsOwn(row.slug, snapshot.page.frontmatter)) throw memberPageNotOwned(row.slug);+ if (p.scope_page === true && snapshot && !await scopePageIsShared(engine, { ...snapshot.page, source_id: row.source_id, slug: row.slug })) throw scopePageNotShared(row.source_id);// A defaulted visibility never lands broader than the target page as it stands at publication.if (p.visibility_defaulted === true && snapshot) input.visibility = tightenToPage(input.visibility, await withFolderRestricted(engine, snapshot.page));if (p.expected_revision !== undefined) assertPageRevision(snapshot, engineMutationPrecondition(parseMutationPrecondition(p)));@@ -150,6 +151,9 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque} else if (p.fence === true && p.member_page === true) {fence = await prepareFenceFactCreate(engine, row, config, { fact, pendingTier: fenceAppendPendingTier(writerTier),frontmatter: memberPageFrontmatter(row.slug.slice(MEMBER_PAGE_PREFIX.length)), heading: `# Memory of ${row.slug.slice(MEMBER_PAGE_PREFIX.length)}` }, signal);+ } else if (p.fence === true && p.scope_page === true) {+ fence = await prepareFenceFactCreate(engine, row, config, { fact, pendingTier: fenceAppendPendingTier(writerTier),+ frontmatter: scopePageFrontmatter(), heading: '# Scope memory' }, signal);}// The belief ledger records the superseded fact in its own stream, so that stream's page key is held too.const supersededStream = status === 'superseded' ? decision.candidate!.source_markdown_slug ?? decision.candidate!.entity_slug ?? null : null;diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex 56201b3c9f..740208011a 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -21,6 +21,8 @@ export interface WriteAuthority {actingFor?: string[] | { system: string; external_id: string; member: string };/** GST-359 D: the attested operation this write serves when it differs from the stored one (memory_write as remember). */attestedOp?: string;+ /** GST-1113: the scope source an attested memory_write named instead of the principal's own; publication re-checks attest_sources. */+ attestedSource?: string;databaseOnlyReason?: 'subagent_sandbox' | 'disabled_by_config' | 'no_repo_configured' | 'connector_database' | 'unbound_source' | 'overwrite_restore' | 'detached';autoLinkTrusted?: boolean;restrictedNamespace?: boolean;diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex db14f3647f..eeac55d766 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -47,6 +47,7 @@ import { pipelined } from '../page-state/transactions.ts';import { holdsSummarizedToolCalls, isQuotedPageType, quotesTier, unquoteTranscriptText } from '../search/transcript-quote.ts';import { readStoredBody } from '../facts/file-body-guard.ts';import { isMirrorOnlyPage, sourceMirrorReadOnly } from './mirror-read-only.ts';+import { perCallWriteSource } from '../access/attest-sources.ts';export async function requestPrincipalForContext(ctx: OperationContext): Promise<Principal> {// #5994: a failed-writes replay is admitted under the original writer.@@ -141,7 +142,7 @@ export function pageMutationSource(ctx: OperationContext, params: Record<string,`Pass source_id as one source (for example ${ctx.sourceId && ctx.sourceId !== '__all__' ? ctx.sourceId : 'default'}); writes never fan out across sources.`);}const granted = ctx.auth?.sourceId ?? ctx.sourceId ?? 'default';- if (ctx.remote !== false && sourceId !== granted) {+ if (ctx.remote !== false && sourceId !== granted && !perCallWriteSource(ctx, sourceId)) {throw new OperationError('permission_denied', 'This source is outside the current write grant.',`This connection writes only to source ${granted}. Pass source_id ${granted} (or omit it), or ask the brain host's operator to grant write access to ${sourceId}.`);}diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.tsindex a4fc456ce1..be5afb3de9 100644--- a/src/core/persistence/source-lifecycle.ts+++ b/src/core/persistence/source-lifecycle.ts@@ -259,7 +259,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL}else if(input.operation==='archive') await tx.executeRaw(`UPDATE sources SET archived=true,archived_at=COALESCE(archived_at,now()),archive_expires_at=COALESCE(archive_expires_at,now()+interval '72 hours'),config=$2::text::jsonb WHERE id=$1`,[input.sourceId,JSON.stringify({...source?.config,federated:false})]);else if(input.operation==='restore') await tx.executeRaw(`UPDATE sources SET archived=false,archived_at=NULL,archive_expires_at=NULL,- config=$2::text::jsonb WHERE id=$1`,[input.sourceId,JSON.stringify({...source?.config,federated:input.refederate!==false})]);+ config=$2::text::jsonb WHERE id=$1`,[input.sourceId,JSON.stringify({...source?.config,federated:input.refederate!==false&&source?.config?.qm_scope!==true})]);else if(input.operation==='rebind'&&relocated){// #5914 (P1.3c): the recorded root now resolves through a symlink to the new directory; the worktree keeps its id// and its ownership records move to the real path (reservation under the new sha256(root) name, stamp naming it).diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex cefcc3051f..b5b8f9738d 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -292,6 +292,8 @@ export async function runMemoryWrite<T>(run: () => Promise<T>): Promise<T> {const frozen = verbError(code,diagnostic?.message ?? error.message,diagnostic?.suggestion ?? error.suggestion ?? 'Inspect writer status before retrying.');if (diagnostic) frozen.detail = diagnostic.reason;if (error.code === 'idempotency_conflict' && error.fix) frozen.fix = error.fix;+ // GST-1113: a refusal's reason (scope_page_not_shared, source_not_attested) rides along additively; the frozen code stays.+ if (error.reason && !frozen.reason) frozen.reason = error.reason;// #6608: an unbound-source refusal keeps its detail, docs and ask-the-user fix additively; the frozen code stays.if (error.detail === 'unbound_source') Object.assign(frozen, { detail: error.detail, docs: error.docs, fix: error.fix, retryable: error.retryable });if (isWriteErrorCode(error.code)) frozen.writeError=error.code;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..f5153c14c1 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-qm-attest-sources.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-qm-attest-sources.ts b/src/core/schema-migrations/v287-qm-attest-sources.tsnew file mode 100644index 0000000000..34f70286b2--- /dev/null+++ b/src/core/schema-migrations/v287-qm-attest-sources.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-1113 (gaps 1+2 of the internal QM provider): attest_sources, the+// sources an attested memory_write may name per call (source_id), beside+// attest_actor and attest_ops (v286). NULL = none: the credential writes only+// its own source, as before. A source listed here is a scope source: it holds+// a shared scope's memory page (memory/scope) and no credential that does not+// list it may read it (enforced on every grant write, access/attest-sources.ts).+// Database only, so a repo-less brain gets it unchanged. Nothing is rewritten+// on upgrade. No schema.sql mirror: like v286, these exist only through+// migrations.+export const v287: Migration = {+ version: 287,+ name: 'qm_attest_sources',+ idempotent: true,+ sql: `+ALTER TABLE access_tokens ADD COLUMN IF NOT EXISTS attest_sources TEXT[];+ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS attest_sources TEXT[];+`,+};diff --git a/src/core/sources-load.ts b/src/core/sources-load.tsindex 5e4675e35c..ee329e321f 100644--- a/src/core/sources-load.ts+++ b/src/core/sources-load.ts@@ -196,10 +196,18 @@ export function relativeSourceLocalPathSkipWarning(sourceId: string, localPath:);}-/** True iff the source's config.federated field is the literal boolean true. */+/**+ * True iff the source's config.federated field is the literal boolean true. GST-1113: a QM scope source+ * (config.qm_scope) is never federated, whatever its federated key says, so no connection without a grant reads it.+ */export function isSourceFederated(config: unknown): boolean {const parsed = parseSourceConfig(config);- return parsed.federated === true;+ return parsed.federated === true && parsed.qm_scope !== true;+}++/** GST-1113: whether a source is a QM scope source (config.qm_scope, set when a credential first lists it in attest_sources). */+export function isScopeSourceConfig(config: unknown): boolean {+ return parseSourceConfig(config).qm_scope === true;}/**diff --git a/src/core/token-mint.ts b/src/core/token-mint.tsindex 16fca7d4e8..23e98c806c 100644--- a/src/core/token-mint.ts+++ b/src/core/token-mint.ts@@ -20,6 +20,7 @@ import type { BrainEngine } from './engine.ts';import { ALLOWED_SCOPES_LIST, assertAllowedScopes } from './scope.ts';import type { SqlQuery } from './sql-query.ts';import { opError } from './ops/contract.ts';+import { assertScopeSourceGrant, sourcesOf } from './access/attest-sources.ts';import { generateToken, hashToken, isUndefinedColumnError } from './utils.ts';import { permissionsMirror, tokenGrantColumnValues, tokenGrantFromPermissions, TOKEN_GRANT_COLUMNS, type GrantSources, type PrincipalGrant } from './grants/model.ts';@@ -103,6 +104,7 @@ export async function insertUnifiedToken(engine: BrainEngine, opts: {grant: Pick<PrincipalGrant, 'sources' | 'allowedOperations' | 'takesHolders'>;}): Promise<Array<{ id: string }>> {const scopes = opts.scopes === undefined ? null : `{${opts.scopes.join(',')}}`;+ await assertScopeSourceGrant(engine, null, sourcesOf(opts.grant.sources).reads);try {return await engine.executeRaw<{ id: string }>(`INSERT INTO access_tokens (name, token_hash, scopes, permissions, ${TOKEN_GRANT_COLUMNS.join(', ')}, grant_revision)diff --git a/src/core/trust/supersede-handlers.ts b/src/core/trust/supersede-handlers.tsindex a0adf8d4eb..8ba91c584e 100644--- a/src/core/trust/supersede-handlers.ts+++ b/src/core/trust/supersede-handlers.ts@@ -21,7 +21,7 @@ import { currentWriteTrust, withTrustPromotion, withWriteAttribution } from '../import { normalizeDimension } from '../chronicle/ontology.ts';import { verbError, type OperationError } from '../ops/contract.ts';import type { Principal } from '../persistence/model.ts';-import { onMemberPageSql } from '../access/member-facts.ts';+import { onOwnedMemoryPageSql } from '../access/member-facts.ts';import {decisionResult, getTrustProposal, insertTrustProposal, pendingTrustProposalsFor, registerTrustProposalHandler, transitionTrustProposal, trustProposalRef,type TrustDecision, type TrustDecisionContext, type TrustProposalAction, type TrustProposalRow,@@ -59,7 +59,7 @@ export async function lexicalContestCandidate(engine: BrainEngine, sourceId: strconst rows = await engine.executeRaw<{ id: number; fact: string; trust_tier: string }>(`SELECT id, fact, trust_tier FROM facts WHERE source_id = $1 AND entity_slug = $2 AND kind = $3 AND visibility = $4AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now()) AND ${trustRankSql('trust_tier')} > ${trustRankSql('$5::text')}- AND ${input.page_slug ? 'source_markdown_slug = $6' : `($6::text IS NULL AND NOT ${onMemberPageSql('facts')})`}+ AND ${input.page_slug ? 'source_markdown_slug = $6' : `($6::text IS NULL AND NOT ${onOwnedMemoryPageSql('facts')})`}ORDER BY id DESC LIMIT 200`, [sourceId, input.entity_slug, input.kind, input.visibility, writer, input.page_slug ?? null]);const mine = slotTokens(input.fact);let best: { id: number; trust_tier: TrustTier; score: number } | null = null;diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex f4198bc7d4..e330b8cabb 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_sources ARRAY/_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_sources ARRAY/_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..9b077fd2c8 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_sources ARRAY/_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_sources ARRAY/_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..c05e506f6f 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_sources ARRAY/_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_sources ARRAY/_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..272ce20b85 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_sources ARRAY/_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_sources ARRAY/_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..a4907052f7 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_sources ARRAY/_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_sources ARRAY/_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..4cccdf656d 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_sources ARRAY/_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_sources ARRAY/_text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex fa354be715..8a7a5a42a7 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.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_sources ARRAY/_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_sources ARRAY/_text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 3d8b84b351..5e94ee6ba6 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -445,6 +445,7 @@ test/purge-missing-cache-6911.test.tstest/purge-read-surfaces.test.tstest/purge-sync-tombstone-hold-7130.test.tstest/qm-memory-tools.test.ts+test/qm-scope-writes.test.tstest/read-meta-diag.test.tstest/recall-page-fill.test.tstest/receipt-compaction-newest-sync-gbra130.test.tsdiff --git a/test/qm-memory-contract.test.ts b/test/qm-memory-contract.test.tsindex a02dba7e03..ea95e2d9fb 100644--- a/test/qm-memory-contract.test.ts+++ b/test/qm-memory-contract.test.ts@@ -98,6 +98,12 @@ describe('QM memory-provider contract v2 (GST-1094 scope read, GST-900)', () =>expect(fixture.errors.codes.map((c: { code: string }) => c.code)).toContain('permission_denied');const v1 = JSON.parse(readFileSync(QM_CONTRACT_PATH, 'utf8'));expect(fixture.wave_2).toEqual(v1.wave_2);- expect(fixture.memory_write).toEqual(v1.memory_write);+ const { scope_write: scopeWrite, ...memoryWrite } = fixture.memory_write;+ expect(memoryWrite).toEqual(v1.memory_write);+ const write = fixture.tools.find((t: { name: string }) => t.name === 'memory_write');+ expect(write.input_schema.properties.source_id.type).toBe('string');+ expect(write.input_schema.required).toEqual(v1.tools.find((t: { name: string }) => t.name === 'memory_write').input_schema.required);+ expect(scopeWrite.saved_as).toMatchObject({ page: 'memory/scope', visibility: 'world' });+ expect(scopeWrite.rule).toContain('attest_sources');});});diff --git a/test/qm-scope-writes.test.ts b/test/qm-scope-writes.test.tsnew file mode 100644index 0000000000..5112b84b88--- /dev/null+++ b/test/qm-scope-writes.test.ts@@ -0,0 +1,333 @@+/**+ * GST-1113: gaps 1+2 of the internal QM provider. memory_write's per-call scope source (source_id), checked against the+ * credential's attest_sources, saves world facts on that source's scope page (memory/scope); the scope-source mark keeps+ * every other credential from reading it.+ *+ * 1. Protects: a scope write lands only on memory/scope in a marked source the attest credential lists, as world facts+ * with qm provenance; a second member reads it through memory_recall source_id; the person route never reads a scope;+ * a source outside the list, the credential's own source, an unattested call, a squatted page and every other remote+ * writer of memory/scope are refused with nothing written; publication re-checks the list; request ids key per+ * source; scope and member copies of one claim never merge; no credential grant, token or federation exposes a+ * marked source, and the mark outlives the scope credential.+ * 2. Fails when: any of the above regresses.+ * 3. Existing coverage: test/qm-memory-tools.test.ts pins the member-page memory pair; test/qm-memory-contract.test.ts+ * pins the contract (v1 byte-identical, v2 scope_write).+ * 4. Real seams: OAuth client-credentials tokens verified by the provider, MCP dispatch, the persistence coordinator on a+ * repo-less brain, the grants service and token mint; embeddings stubbed.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { 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 { linkMember } from '../src/core/access/actor.ts';+import { assertNotScopeSource, markedScopeSources } from '../src/core/access/attest-sources.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { authorizeWrite } from '../src/core/persistence/authority.ts';+import { memoryWriteRequestId } from '../src/core/ops/qm-memory.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { rescopeClientGrant } from '../src/core/grants/service.ts';+import { rescopeLegacyToken } from '../src/core/grants/legacy-token.ts';+import { isSourceFederated, loadAllSources, parseSourceConfig } from '../src/core/sources-load.ts';+import { restoreSource, softDeleteSource } from '../src/core/destructive-guard.ts';+import { proposeRevision } from '../src/core/access/policy.ts';+import type { AuthInfo } from '../src/core/ops/contract.ts';+import { testBackends } from './helpers/test-backends.ts';+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';+import { durableGitRepo, git } from './helpers/git-publication.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+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 HOME = 'qm-home';+const SCOPE_A = 'scope-a';+const SCOPE_B = 'scope-b';+const SCOPE_C = 'scope-c';+const SHARED = 'team-shared';+const ALICE_ID = 'U0ALICE';+const BOB_ID = 'U0BOB';+const MEMORY_OPS = ['forget', 'forget_fact', 'get_write_request', 'memory_recall', 'memory_write'];+const tokenArgs = { reset: [], refreshOperations: false, allNew: false, dryRun: false, json: false } as const;++describe('scope sources (pure)', () => {+ test('a marked source is never federated, whatever its federated key says', () => {+ expect(isSourceFederated({ federated: true })).toBe(true);+ expect(isSourceFederated({ federated: true, qm_scope: true })).toBe(false);+ expect(isSourceFederated(JSON.stringify({ federated: true, qm_scope: true }))).toBe(false);+ });++ test('request ids key a scope write per source; without a source they are the member ids v1 published', async () => {+ const own = await memoryWriteRequestId('alice-example', 'key-1', 0);+ expect(await memoryWriteRequestId('alice-example', 'key-1', 0, undefined)).toBe(own);+ const a = await memoryWriteRequestId('alice-example', 'key-1', 0, SCOPE_A);+ expect(a).not.toBe(own);+ expect(await memoryWriteRequestId('alice-example', 'key-1', 0, SCOPE_A)).toBe(a);+ expect(await memoryWriteRequestId('alice-example', 'key-1', 0, SCOPE_B)).not.toBe(a);+ expect(await memoryWriteRequestId('bob-example', 'key-1', 0, SCOPE_A)).not.toBe(a);+ });+});++for (const kind of testBackends()) {+ describe('scope writes (' + 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 tokens: Record<string, string> = {};+ const clients: Record<string, { id: string; secret: string }> = {};+ type Who = { token: string; actor?: string };+ const alice: Who = { token: 'scopes', actor: ALICE_ID };+ const bob: Who = { token: 'scopes', actor: BOB_ID };++ async function call(as: Who, op: string, params: Record<string, unknown>, extra: { writeWaitMs?: number } = {}) {+ const auth = await provider().verifyAccessToken(tokens[as.token]!) as unknown as AuthInfo;+ const out: ToolResult = await dispatchToolCall(engine, op, { ...params }, {+ remote: true, transport: 'http', auth, sourceId: auth.sourceId, takesHoldersAllowList: ['world'],+ ...(as.actor !== undefined ? { actor: { header: as.actor } } : {}), ...extra,+ });+ const text = out.content.map(c => c.text).join('\n');+ let json: Record<string, any> = {};+ try { json = JSON.parse(text); } catch { /* plain text */ }+ return { isError: out.isError === true, text, json, structured: out.structuredContent as Record<string, any> | undefined, all: text + JSON.stringify(out.structuredContent ?? {}) };+ }+ const write = (as: Who, facts: Array<Record<string, unknown>>, args: Record<string, unknown> = {}, key: string = randomUUID()) =>+ call(as, 'memory_write', { facts, idempotency_key: key, ...args }, { writeWaitMs: 30_000 });+ const factRows = (needle: string) => engine.executeRaw<Record<string, any>>(+ 'SELECT id, source_id, visibility, source_markdown_slug, source FROM facts WHERE fact LIKE $1 ORDER BY id', ['%' + needle + '%']);+ const register = async (name: string, source: string, grantTypes = ['client_credentials']) => {+ const c = await provider().registerClientManual('s-' + name + '-' + randomUUID().slice(0, 8), grantTypes, 'read write', [], source);+ return (clients[name] = { id: c.clientId, secret: c.clientSecret ?? '' });+ };+ const refusal = async (p: Promise<unknown>) => { try { await p; return null; } catch (e) { return e as Error & { code?: string; reason?: string }; } };++ 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 [HOME, SCOPE_A, SCOPE_B, SCOPE_C, SHARED]) 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 linkMember(engine, 'bob-example', 'qm', BOB_ID);+ const scopes = await register('scopes', HOME);+ await bindCredential(engine, { kind: 'client', id: scopes.id }, { attestActor: 'qm', attestOps: MEMORY_OPS, attestSources: [SCOPE_A, SCOPE_B, SCOPE_C] });+ await rescopeClientGrant(engine, scopes.id, { federatedRead: [HOME, SCOPE_A, SCOPE_B, SCOPE_C] }, { actor: 'test' });+ const personal = await register('personal', HOME);+ await bindCredential(engine, { kind: 'client', id: personal.id }, { attestActor: 'qm', attestOps: MEMORY_OPS });+ const plain = await register('plain', SHARED);+ for (const name of ['scopes', 'personal', 'plain']) tokens[name] = (await provider().exchangeClientCredentials(clients[name]!.id, clients[name]!.secret)).access_token;+ }, 120_000);++ afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await disposePersistenceConsumer(engine).catch(() => undefined);+ await close?.();+ });++ test('a scope write lands world on memory/scope in that source only; another member recalls it by naming the source; no person read sees it', async () => {+ expect([...await markedScopeSources(engine, [HOME, SCOPE_A, SCOPE_B, SCOPE_C, SHARED])].sort()).toEqual([SCOPE_A, SCOPE_B, SCOPE_C]);+ const key = randomUUID();+ const out = await write(alice, [{ fact: 'The launch moves to Thursday canaryscopea', provenance: 'slack:C0SCOPE/p1' }], { source_id: SCOPE_A }, key);+ expect(out.isError).toBe(false);+ expect(out.structured).toEqual({ status: 'committed', request_id: await memoryWriteRequestId('alice-example', key, 0, SCOPE_A), fact_ids: [expect.any(String)] });+ const rows = await factRows('canaryscopea');+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({ source_id: SCOPE_A, visibility: 'world', source_markdown_slug: 'memory/scope' });+ expect(String(rows[0]!.source)).toContain('qm:' + ALICE_ID + '; slack:C0SCOPE/p1');+ const [page] = await engine.executeRaw<{ page_readers: string[] | null }>('SELECT page_readers FROM pages WHERE source_id = $1 AND slug = $2', [SCOPE_A, 'memory/scope']);+ expect(page!.page_readers).toBeNull();+ const named = await call(bob, 'memory_recall', { query: 'launch Thursday', source_id: SCOPE_A });+ expect(named.isError).toBe(false);+ expect(named.text).toContain('canaryscopea');+ for (const as of [alice, bob, { token: 'personal', actor: ALICE_ID }]) {+ const person = await call(as, 'memory_recall', { query: 'launch Thursday' });+ expect(person.isError).toBe(false);+ expect(person.all).not.toContain('canaryscopea');+ }+ const other = await call(bob, 'memory_recall', { query: 'launch Thursday', source_id: SCOPE_B });+ expect(other.all).not.toContain('canaryscopea');+ }, 60_000);++ test('get_write_request finds a scope receipt for the member who wrote it, and for no other member', async () => {+ const out = await write(alice, [{ fact: 'Receipt check canaryreceipt', provenance: 'turn r' }], { source_id: SCOPE_A });+ const id = out.structured!.request_id;+ const own = await call(alice, 'get_write_request', { request_id: id });+ expect(own.isError).toBe(false);+ expect(own.all).toContain(id);+ const other = await call(bob, 'get_write_request', { request_id: id });+ expect(other.isError).toBe(true);+ expect(other.all).toContain('not_found');+ }, 60_000);++ test('a source outside attest_sources, the own source and an unattested call are refused with nothing written', async () => {+ const cases: Array<[Who, string, string, string | undefined]> = [+ [alice, SHARED, 'source_not_attested', undefined],+ [{ token: 'personal', actor: ALICE_ID }, SCOPE_A, 'source_not_attested', undefined],+ [alice, HOME, 'source_is_member_source', 'invalid_params'],+ [{ token: 'scopes' }, SCOPE_A, 'actor_required', 'actor_not_attested'],+ [{ token: 'plain' }, SCOPE_A, 'actor_required', 'actor_not_attested'],+ ];+ for (const [as, source, reason, code] of cases) {+ const out = await write(as, [{ fact: 'Refused scope write canaryscoperefused', provenance: 'x' }], { source_id: source });+ expect({ isError: out.isError, reason: out.json.reason }).toEqual({ isError: true, reason });+ if (code) expect(out.json.code).toBe(code);+ }+ expect(await factRows('canaryscoperefused')).toHaveLength(0);+ }, 60_000);++ test('one key replays per source and is a separate write in another source; scope and member copies of a claim never merge', async () => {+ const key = 'scope-key-' + randomUUID();+ const fact = [{ fact: 'Standup is at nine canarysamekeyscope', provenance: 'turn 1' }];+ const a = await write(alice, fact, { source_id: SCOPE_A }, key);+ const again = await write(alice, fact, { source_id: SCOPE_A }, key);+ expect(again.structured).toEqual(a.structured);+ const b = await write(alice, fact, { source_id: SCOPE_B }, key);+ const own = await write(alice, fact, {}, key);+ expect(own.structured!.request_id).toBe(await memoryWriteRequestId('alice-example', key, 0));+ expect(new Set([a, b, own].map(r => r.structured!.request_id)).size).toBe(3);+ const rows = await factRows('canarysamekeyscope');+ expect(rows.map(r => r.source_id + ':' + r.source_markdown_slug + ':' + r.visibility).sort())+ .toEqual([HOME + ':memory/members/alice-example:private', SCOPE_A + ':memory/scope:world', SCOPE_B + ':memory/scope:world']);+ }, 60_000);++ test('publication re-checks attest_sources: a stored scope write is refused once the operator drops the source', async () => {+ const out = await write(alice, [{ fact: 'Budget review moved canaryrecheck', provenance: 'turn 2' }], { source_id: SCOPE_C });+ expect(out.structured!.status).toBe('committed');+ const [row] = await engine.executeRaw<{ authority: any }>('SELECT authority FROM persistence_requests WHERE request_id = $1::uuid', [out.structured!.request_id]);+ const authority = typeof row!.authority === 'string' ? JSON.parse(row!.authority) : row!.authority;+ expect(authority.attestedSource).toBe(SCOPE_C);+ await authorizeWrite(engine as never, authority, 'remember', 'memory/scope');+ expect((await refusal(authorizeWrite(engine as never, authority, 'remember', 'notes/elsewhere')))?.message).toBeTruthy();+ await rescopeClientGrant(engine, clients.scopes!.id, { federatedRead: [HOME, SCOPE_A, SCOPE_B] }, { actor: 'test' });+ await bindCredential(engine, { kind: 'client', id: clients.scopes!.id }, { attestSources: [SCOPE_A, SCOPE_B] });+ const refused = await refusal(authorizeWrite(engine as never, authority, 'remember', 'memory/scope'));+ expect(refused?.reason).toBe('source_not_attested');+ expect((await markedScopeSources(engine, [SCOPE_C])).has(SCOPE_C)).toBe(true);+ const after = await write(alice, [{ fact: 'After the drop canaryrecheckafter', provenance: 'turn 3' }], { source_id: SCOPE_C });+ expect(after.json.reason).toBe('source_not_attested');+ expect(await factRows('canaryrecheckafter')).toHaveLength(0);+ }, 60_000);++ test('a squatted scope page takes no scope write; no other remote writer may write memory/scope', async () => {+ await importFromContent(engine, 'memory/scope', '---\ntype: note\ntitle: Scope memory\nreadable_by:\n - member:alice-example\n - member:bob-example\n---\n# Scope memory\n', { sourceId: SCOPE_B });+ const squat = await write(alice, [{ fact: 'Squatted scope canarysquatscope', provenance: 'x' }], { source_id: SCOPE_B });+ expect({ isError: squat.isError, reason: squat.json.reason }).toEqual({ isError: true, reason: 'scope_page_not_shared' });+ await importFromContent(engine, 'memory/scope', '---\ntype: note\ntitle: Scope memory\nreadable_by:\n - member:bob-example\n---\n# Scope memory\n', { sourceId: SCOPE_B });+ const hidden = await write(alice, [{ fact: 'Hidden squat canarysquatscope', provenance: 'x' }], { source_id: SCOPE_B });+ expect({ isError: hidden.isError, write_error: hidden.json.write_error }).toEqual({ isError: true, write_error: 'page_not_found' });+ expect(await factRows('canarysquatscope')).toHaveLength(0);+ for (const slug of ['memory/scope', 'memory/scope/notes']) {+ const put = await call({ token: 'plain' }, 'put_page', { slug, content: '---\ntype: note\ntitle: x\n---\nforged canaryforged' });+ expect(put.isError).toBe(true);+ expect(put.all).toContain('memory/scope');+ }+ const remember = await call({ token: 'plain' }, 'remember', { fact: 'Forged scope fact canaryforgedfact', entity: 'memory/scope' });+ expect(remember.isError).toBe(true);+ expect(await factRows('canaryforged')).toHaveLength(0);+ const writers: Array<[string, Record<string, unknown>]> = [+ ['delete_page', { slug: 'memory/scope' }], ['add_tag', { slug: 'memory/scope', tag: 'x' }],+ ['add_link', { from: 'memory/scope', to: 'notes/x' }], ['add_timeline_entry', { slug: 'memory/scope', date: '2026-01-01', summary: 'x' }],+ ];+ for (const [op, args] of writers) {+ const refused = await call({ token: 'plain' }, op, args);+ expect({ op, isError: refused.isError, guarded: refused.all.includes('written remotely only by an attested memory_write') }).toEqual({ op, isError: true, guarded: true });+ }+ await importFromContent(engine, 'memory/scope', '---\ntype: note\ntitle: Scope memory\n---\n# Scope memory\n', { sourceId: SCOPE_B });+ await proposeRevision(engine, SCOPE_B, [{ id: 'scope-folder', prefix: 'memory/', readable_by: ['member:alice-example', 'member:bob-example'] }], { origin: 'cli', store: 'database' });+ const ruled = await write(alice, [{ fact: 'Folder ruled canaryfolderscope', provenance: 'x' }], { source_id: SCOPE_B });+ expect({ isError: ruled.isError, reason: ruled.json.reason }).toEqual({ isError: true, reason: 'scope_page_not_shared' });+ expect(await factRows('canaryfolderscope')).toHaveLength(0);+ }, 60_000);++ test('no grant, token or federation exposes a scope source, and the mark outlives the scope credential', async () => {+ const grantRefused = await refusal(rescopeClientGrant(engine, clients.plain!.id, { federatedRead: [SHARED, SCOPE_A] }, { actor: 'test' }));+ expect(grantRefused?.message).toContain('QM scope source');+ expect((await refusal(register('newscope', SCOPE_A)))?.message).toContain('QM scope source');+ expect((await refusal(mintLegacyToken(engine, { name: 'scope-tok-' + randomUUID().slice(0, 8), scopes: ['read'], takesHolders: ['world'], sourceGrant: [SCOPE_A] })))?.message).toContain('QM scope source');+ const legacy = await mintLegacyToken(engine, { name: 'plain-tok-' + randomUUID().slice(0, 8), scopes: ['read'], takesHolders: ['world'], sourceGrant: [SHARED] });+ expect((await refusal(rescopeLegacyToken(engine, { ...tokenArgs, reset: [], target: { id: legacy.id }, sources: [SHARED, SCOPE_B] })))?.message).toContain('QM scope source');+ expect((await refusal(assertNotScopeSource(engine, SCOPE_A)))?.reason).toBe('scope_source_reserved');+ const federated = async () => (await loadAllSources(engine, { federatedOnly: true })).map(s => s.id);+ expect(await softDeleteSource(engine, SCOPE_A)).not.toBeNull();+ expect(await restoreSource(engine, SCOPE_A)).toBe(true);+ expect(await federated()).not.toContain(SCOPE_A);+ const [restored] = await engine.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id = $1', [SCOPE_A]);+ expect(parseSourceConfig(restored!.config)).toMatchObject({ federated: false, qm_scope: true });+ await engine.executeRaw(`UPDATE sources SET config = COALESCE(config, '{}'::jsonb) || jsonb_build_object('federated', true) WHERE id = $1`, [SCOPE_A]);+ expect(await federated()).not.toContain(SCOPE_A);+ expect((await markedScopeSources(engine, [SCOPE_A])).has(SCOPE_A)).toBe(true);+ expect((await refusal(rescopeClientGrant(engine, clients.scopes!.id, { privatePages: 'granted_sources' }, { actor: 'test' })))?.message).toContain('private-pages');+ await engine.executeRaw(`UPDATE oauth_clients SET deleted_at = now() WHERE client_id = $1`, [clients.scopes!.id]);+ expect((await refusal(rescopeClientGrant(engine, clients.plain!.id, { federatedRead: [SHARED, SCOPE_A] }, { actor: 'test' })))?.message).toContain('QM scope source');+ await engine.executeRaw(`UPDATE oauth_clients SET deleted_at = NULL WHERE client_id = $1`, [clients.scopes!.id]);+ }, 60_000);++ test('attest_sources changes refuse sources others read, default, the own source, a shrink still read, and wider attested ops', async () => {+ const personal = { kind: 'client' as const, id: clients.personal!.id };+ const reason = async (patch: Parameters<typeof bindCredential>[2]) => (await refusal(bindCredential(engine, personal, patch)) as { reason?: string; message: string } | null);+ expect((await reason({ attestSources: [SHARED] }))?.message).toContain('can already read');+ expect((await reason({ attestSources: ['default'] }))?.reason).toBe('scope_source_reserved');+ expect((await reason({ attestSources: [HOME] }))?.message).toContain('own write source');+ expect((await reason({ attestSources: ['no-such-source'] }))?.message).toContain('not an active source');+ expect((await refusal(bindCredential(engine, { kind: 'client', id: clients.scopes!.id }, { attestSources: [SCOPE_A] })))?.message).toContain('still reads');+ expect((await refusal(bindCredential(engine, { kind: 'client', id: clients.scopes!.id }, { attestOps: [...MEMORY_OPS, 'search'] })))?.message).toContain('scope sources');+ expect((await refusal(bindCredential(engine, { kind: 'client', id: clients.plain!.id }, { attestSources: [SCOPE_A] })))?.message).toContain('attest right');+ expect((await markedScopeSources(engine, [SHARED, HOME])).size).toBe(0);+ }, 60_000);+ });+}++describe('scope writes (pglite, repo-backed)', () => {+ test('a scope write to a repo-backed scope source is committed to that source\'s git checkout under the writer door', () => managedBrain(async ({ engine, root }) => {+ const scopeRoot = join(dirname(root), 'scope');+ 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);+ try {+ await addMember(engine, 'alice-example');+ await linkMember(engine, 'alice-example', 'qm', ALICE_ID);+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ const c = await provider.registerClientManual('s-repo-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], 'default');+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { attestActor: 'qm', attestOps: MEMORY_OPS, attestSources: ['scope-repo'] });+ await rescopeClientGrant(engine, c.clientId, { federatedRead: ['default', 'scope-repo'] }, { actor: 'test' });+ const auth = await provider.verifyAccessToken((await provider.exchangeClientCredentials(c.clientId, c.clientSecret ?? '')).access_token) as unknown as AuthInfo;+ const result = await dispatchToolCall(engine, 'memory_write', { facts: [{ fact: 'The repo scope ships Friday canaryreposcope', provenance: 'slack:C0REPO/p1' }], idempotency_key: randomUUID(), source_id: 'scope-repo' },+ { remote: true, transport: 'http', auth, sourceId: auth.sourceId, actor: { header: ALICE_ID }, writeWaitMs: 30_000 });+ expect(result.isError).not.toBe(true);+ expect(['committed', 'pending']).toContain((result.structuredContent as { status: string }).status);+ await settleManagedGitEffects(engine, 'scope-repo');+ const file = readFileSync(join(scopeRoot, 'memory/scope.md'), 'utf8');+ expect(file).toContain('canaryreposcope');+ expect(file).not.toContain('readable_by');+ expect(git(scopeRoot, 'log', '--format=%H', '--', 'memory/scope.md').trim()).not.toBe('');+ expect(git(scopeRoot, 'status', '--porcelain', '--', 'memory').trim()).toBe('');+ expect(existsSync(join(root, 'memory/scope.md'))).toBe(false);+ const [row] = await engine.executeRaw<{ source_id: string; visibility: string }>("SELECT source_id, visibility FROM facts WHERE fact LIKE '%canaryreposcope%'");+ expect(row).toEqual({ source_id: 'scope-repo', visibility: 'world' });+ } finally { __setEmbedTransportForTests(null); resetGateway(); }+ }, { setup: async ({ engine, root }) => {+ const scopeRoot = join(dirname(root), 'scope');+ for (const dir of [root, scopeRoot]) { mkdirSync(dir, { recursive: true }); writeFileSync(join(dir, '.gitignore'), '\n'); durableGitRepo(dir, ['.gitignore']); }+ await engine.executeRaw('INSERT INTO sources (id, name, local_path) VALUES ($1, $1, $2)', ['scope-repo', scopeRoot]);+ await claimWorktree(engine, 'scope-repo', scopeRoot);+ } }), 120_000);+});diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex e003c79540..78c3625d61 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-1113 (migration v287) - attest_sources, the scope sources an attested memory_write may name. Same posture as+ // v286: absent from both schema blobs; readers go through to_jsonb(row), so a schema without it reads as none.+ 'access_tokens.attest_sources',+ 'oauth_clients.attest_sources',// 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',