Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(access): GST-359 C2 key agent jobs to the attested actor; remember, delta, receipts and agent jobs attestable
garrytan4b6bdffa9212
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e153bc0cca..14b71c2a9d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,7 +28,9 @@ identifiers and attribution are available in the pre-removal Git revision| Changing folder rules | | narrowing applies at once; widening is held until `gbrain access apply --source <id>` previews it and `--yes --expect <plan_hash>` approves it; an unfinished apply reads as nobody remotely until `gbrain access resume --source <id>` || `gbrain export` and `gbrain import` | pages only | an export carries each source's applied folder rules under `.gbrain/`, and import installs them before publishing any page (`--access-policy <source>` maps a multi-source export) || A shared agent (one bot serving a channel or many DMs) | read as its own credential, so it saw one view for everyone | its harness names each turn's audience (`X-Gbrain-On-Behalf-Of: alice-example, guest` or request-level `_meta.on_behalf_of`); the call reads only what every entry may read, within the agent's source grant, and only a one-member audience keeps the agent's private-page relaxation. The credential lists whom it may act for (`gbrain auth rescope --token <name> --may-act-for <list>`); every response carries `_meta.access`, and `whoami` returns it |-| A trusted system that names the person (QM) | | a client-credentials client granted `gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]` sends `x-qm-actor: <canonical id>`; each attested operation runs as the member that id is linked to (`gbrain access member link <member> --qm <id>`, `unlink`, `links`), never reading private pages, and queued writes and jobs re-check the link and the operation list. Agent jobs, write receipts, `delta` and fact and take writes are not attestable yet. Refusals carry `structuredContent.error` (`actor_not_attested`, `actor_unlinked`). Every MCP server's `serverInfo` now has a one-line `description` |+| A trusted system that names the person (QM) | | a client-credentials client granted `gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]` sends `x-qm-actor: <canonical id>`; each attested operation runs as the member that id is linked to (`gbrain access member link <member> --qm <id>`, `unlink`, `links`), never reading private pages, and queued writes and jobs re-check the link and the operation list. `capture`, `extract_facts`, `forget`, `forget_fact`, take writes and `list_write_conflicts` are not attestable yet. Refusals carry `structuredContent.error` (`actor_not_attested`, `actor_unlinked`). Every MCP server's `serverInfo` now has a one-line `description` |+| A member saves a fact remotely (`remember` attested as a person, or from a credential bound to one member) | from a member-bound credential, went on the entity page as a fact every reader of the source recalled; an attested call could not run `remember` | goes on the member's own page `memory/members/<member>` (created with `readable_by: [member:<id>]`), private, with the entity kept as metadata; only that member recalls it, and it never dedups against, supersedes or contests another page's fact, never consolidates into a take and keeps its readers through a fence rebuild and relink. Two people's identical words make two facts |+| One attest client serving several people | hot memory, `delta` cursors, write receipts and agent jobs were keyed by the client | each is keyed by the person too: Alice and Bob on one session id never share a hot-memory payload or a `delta` cursor, Bob and the bare client get `not_found` for Alice's receipt (`get_write_request`, `list_write_requests`, `cancel_write_request`) and agent job (`get_agent_job`), and Alice's `request_id` never replays for Bob. `remember`, `delta`, the receipt ops, `submit_agent` and `get_agent_job` are now attestable |### What to watch for after you upgradediff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 1c9d0dff7f..89adc56fa7 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -66,7 +66,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/modes-report.ts` — `buildModesReport(engine)` → `SearchModesReport` (`schema_version: 2`), the read-only dashboard behind `gbrain search modes` and the `search_modes` MCP op: `active_mode` + validity, the per-knob `resolved` attribution (`attributeKnob` over `KNOB_DESCRIPTIONS`, including the five `reranker_*` knobs), the three frozen `bundles`, `config_keys`, and `reranker_readiness` — `{model, enabled, ready, required_key, key_present, self_hosted, fix}` from `rerankerReadinessForEngine` + `describeRerankerFix` (a thrown readiness check still yields a `ready: false` verdict whose `fix` says to run `gbrain doctor`; the block never vanishes silently). `redactReadinessForRemote(report)` is what the `search_modes` op returns when `ctx.remote !== false`: `required_key`, `key_present` and `fix` are dropped and `self_hosted` is forced false — which env vars exist on the host is fingerprinting data and the fix names them; `ready` stays because it is observable anyway (reranked results carry `rerank_score`). `src/commands/search.ts:formatModesText` renders the runtime `Reranker:` line (`off (resolved) — …` / `<model> (enabled) — <KEY> present` / `<model> (enabled but NOT running) — <fix>`) and a per-bundle `reranker=… topNIn=… autocut=…` line. Pinned by `test/modes-report-reranker.test.ts`. The CLI dashboard leads with command-specific expansion: `query` follows the mode's expansion default (off in all modes) unless the call passes `expand`, while `search` is off. It discloses provider prerequisites/text flow and distinguishes retained bundle configuration from effective command behavior.- `src/core/search/private-visibility.ts` — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs keep their semantics; failed config reads enforce privacy. `privatePagesFilterFragment` authorizes concrete page rows and `isPrivatePage` is its row-side twin: explicit `private` hides a page, absent visibility is world for ordinary pages and private for extracted atoms (`type = 'atom'`) and synthesized concepts (`type = 'concept'` with `synthesized_by`), because their origin may be a private page or transcript. The page predicate also follows derived origins: an atom whose `source_slug` page is explicitly private, and a synthesized concept with a private input atom (or an input whose origin is private) over `concept-provenance` edges, are private whatever their own field says, so a later private flip of an origin reaches derived pages before any repair. Chronicle events follow `event.depth` (fail closed). Declared lineage matches `derived_from` slugs with `= ANY(ARRAY(...))`, not `IN (SELECT ... jsonb_array_elements_text(...))`: same rows, but the planner priced the IN form as a 100-row semi-join per page and pushed every read carrying the rule past `jit_above_cost` (`test/e2e/private-visibility-plan-postgres.test.ts`). `privateSnapshotFilterFragment` is the same rule on a row's own frontmatter for `page_versions`. `effectiveVisibility(origin)` (transcript or missing origin private, page origin per the read rule) and `strictestVisibility` are used by both `extract_atoms` paths, concept synthesis and `gbrain repair visibility`. Remote publication rechecks (`persistence/page-visibility.ts`) and the alias-inject recheck in `hybrid.ts` use the same rule. Tests: `test/private-visibility.test.ts`, `test/derived-page-visibility.test.ts` (PGLite and Postgres); link origins and timeline projections use independent ID-based predicates. `privateProvenanceFilterFragment` hides a fact whose provenance page (`s... (line truncated to 2000 chars)-- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). A derivative of a page that names readers is hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and the managed drain, read with `git show` at the synced commit); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v275 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. 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 `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` (agent jobs, write receipts, `delta`, fact and take writes) are never attestable until C2 keys each 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 v276 (provisional). Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`.+- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). A derivative of a page that names readers is hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and the managed drain, read with `git show` at the synced commit); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v275 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. Shared agents (B, GBRA-231): `audience.ts` parses the audience a harness asserts (`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`, 1-50 principals, `guest` = the empty identity; the same key inside tool arguments is refused) and appends each assertion to `access-audience-YYYY-Www.jsonl`. Dispatch resolves it on every remote call through `caller.ts` (`resolveAudienceIdentities`: every entry must be in the credential's live `may_act_for`, then name an enabled member or existing group); the caller-access record then carries `audienceIdentities`, and `accessAllowedForAllSql` needs one readers conjunct per identity, folder rules the intersection of each entry's satisfied set (`folderAccessForAll`). Privacy relaxes only for a one-member audience. Writes carry the audience as `WriteAuthority.actingFor` (re-resolved at publication) and agent jobs as `grant.actingFor`. Every remote response carries `_meta.access` (`appliedAccessSummary`), which `whoami` returns as `access.applied`; doctor `access_may_act_for_wildcard` (`checks/shared-agent-access.ts`) warns on `*`. Tests: `test/access-on-behalf-of.test.ts` (both engines), `test/e2e/serve-http-on-behalf-of.test.ts`. 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 `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`, `forget`, `forget_fact`, 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 v276 (provisional). 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`. 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 fact's source page as the 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` matches the job's `grant.actor` (system, external id, member; `ops/jobs.ts`). 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/search/projection-readiness.ts` — one statement probes visible unsealed pages: ready, projection_pending, by_design (protected/archived only) or unknown; LIMIT 1 arms walk the v161 pending index, not pages. Cached per scope by DB generation (page clock, pages filenode, archive flags, no open tx); `GBRAIN_PROJECTION_READINESS_CACHE=0` disables.diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 23ce53d3a6..ec5b94b1b0 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -940,7 +940,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: `submit_agent`, `get_agent_job`, `get_write_request`, `list_write_requests`, `cancel_write_request`, `list_write_conflicts`, `delta`, `remember`, `capture`, `extract_facts`, `forget`, `forget_fact` 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), `argument_without_attestation` (`acting_user` came without an attested header) or `invalid_actor_id` (the header or argument is not 1-256 visible ASCII characters). 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 three are fixed in the calling harness: send the canonical id unchanged in the header, and the same value or nothing in `acting_user`. |+| <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`, `forget`, `forget_fact` 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), `argument_without_attestation` (`acting_user` came without an attested header) or `invalid_actor_id` (the header or argument is not 1-256 visible ASCII characters). 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 three are fixed in the calling harness: send the canonical id unchanged in the header, and the same value or nothing in `acting_user`. || <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. | 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 d998ef0f21..32577fbf54 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -250,8 +250,12 @@ rescope --client <id> --attest-actor qm [--attest-ops <op,...>]` (defaultaccess 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).+`remember` saves to the person's own page `memory/members/<member>` (private,+read back only by that member), and `delta` cursors, write receipts+(`get_write_request`, `list_write_requests`, `cancel_write_request`) and agent+jobs (`submit_agent`, `get_agent_job`) belong to the person they were made for.Not attestable yet, because what they read or write is not yet kept to the-person: `submit_agent`, `get_agent_job`, `get_write_request`, `list_write_requests`, `cancel_write_request`, `list_write_conflicts`, `delta`, `remember`, `capture`, `extract_facts`, `forget`, `forget_fact` and `takes_add|update|resolve|supersede`.+person: `list_write_conflicts`, `capture`, `extract_facts`, `forget`, `forget_fact` and `takes_add|update|resolve|supersede`.`gbrain access check --token <name>` shows theresult ([Model C](../tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape)).diff --git a/docs/tutorials/company-brain.md b/docs/tutorials/company-brain.mdindex 678cb2fa68..75467ac95c 100644--- a/docs/tutorials/company-brain.md+++ b/docs/tutorials/company-brain.md@@ -167,7 +167,7 @@ gbrain auth rescope --client <client_id> --attest-actor qm # default ops: mgbrain access member link alice-example --qm U0ALICE # --dry-run previews; unlink and links manage them```-Each request then carries `x-qm-actor: U0ALICE`, and each attested operation runs as `alice-example` (page reads, and page writes such as `put_page` or `add_tag` when listed in `--attest-ops`), never reading `visibility: private` pages, whatever the client's own grant says. Not attestable yet, because what they read or write is not yet kept to the person: `submit_agent`, `get_agent_job`, `get_write_request`, `list_write_requests`, `cancel_write_request`, `list_write_conflicts`, `delta`, `remember`, `capture`, `extract_facts`, `forget`, `forget_fact` and `takes_add|update|resolve|supersede`. Under the header, `tools/list` lists only the attested operations and `resources/read` is refused. An `acting_user` argument must equal the header and is stripped. A client without the right, an operation outside `--attest-ops`, or an id that is not 1-256 visible ASCII characters refuses `actor_not_attested`; an id with no link to an enabled member refuses `actor_unlinked`. Ids compare exactly, unlink and disable take effect on the next call, and queued writes and jobs re-check the link before they commit or call a tool. Links and the right are database state, so this works the same on a repo-less brain.+Each request then carries `x-qm-actor: U0ALICE`, and each attested operation runs as `alice-example` (page reads, and page writes such as `put_page` or `add_tag` when listed in `--attest-ops`), never reading `visibility: private` pages, whatever the client's own grant says. A fact the person saves (`remember`) goes on their own page `memory/members/<member>`, which names them as its only reader, so another member, the client's bare calls and an unbound credential never recall it; `delta` cursors, write receipts and agent jobs (`submit_agent`, `get_agent_job`) are kept to the person the same way. Not attestable yet, because what they read or write is not yet kept to the person: `list_write_conflicts`, `capture`, `extract_facts`, `forget`, `forget_fact` and `takes_add|update|resolve|supersede`. Under the header, `tools/list` lists only the attested operations and `resources/read` is refused. An `acting_user` argument must equal the header and is stripped. A client without the right, an operation outside `--attest-ops`, or an id that is not 1-256 visible ASCII characters refuses `actor_not_attested`; an id with no link to an enabled member refuses `actor_unlinked`. Ids compare exactly, unlink and disable take effect on the next call, and queued writes and jobs re-check the link before they commit or call a tool. Links and the right are database state, so this works the same on a repo-less brain.For most company-brain installs (10+ teammates each with their own AI client), Model A is the right starting point. If you're running the fat-agent-serves-everyone pattern from the personal-brain tutorial, Model B is genuinely simpler. You can also mix: separate sources for the obviously-different ones (customer notes vs internal-only) AND a `partners/<slug>/` convention inside the shared source for per-person workspace.diff --git a/src/core/access/actor-model.ts b/src/core/access/actor-model.tsindex 66bde6f55e..84a96bdf14 100644--- a/src/core/access/actor-model.ts+++ b/src/core/access/actor-model.ts@@ -11,15 +11,13 @@ export const ATTEST_SYSTEMS: readonly string[] = ['qm'];export const DEFAULT_ATTEST_OPS: readonly string[] = ['memory_recall', 'memory_write'];/*** Operations no attested call may run yet: what they read or write is not keyed to the person, so one person could- * see another's result (an agent job's output, a write receipt, a delta feed) or write facts and takes every reader- * sees. GST-359 C2 removes each entry as it keys that operation to the member (member-scoped facts, jobs, receipts).- * Refused at `--attest-ops`, at every call and when a stored write or job tool call is re-resolved.+ * change or see another's (a fact withdrawn by id, a conflict list across writers) or write facts and takes every+ * reader sees. GST-359 C2 keyed remember (the member page), delta cursors, write receipts and agent jobs to the person+ * and removed them. Refused at `--attest-ops`, at every call and when a stored write or job tool call is re-resolved.*/export const ACTOR_DEFERRED_OPS: ReadonlySet<string> = new Set([- 'submit_agent', 'get_agent_job',- 'get_write_request', 'list_write_requests', 'cancel_write_request', 'list_write_conflicts',- 'delta',- 'remember', 'capture', 'extract_facts', 'forget', 'forget_fact',+ 'list_write_conflicts',+ 'capture', 'extract_facts', 'forget', 'forget_fact','takes_add', 'takes_update', 'takes_resolve', 'takes_supersede',]);diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex aa49a48744..c8b9b016ac 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1272,7 +1272,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', id: 'member_read_access_gbra218', text: 'A page whose frontmatter names readers (`readable_by: [alice-example, group:team-a]`) is now read remotely only by a token, OAuth client or stdio server bound to a listed member (`gbrain access member add`, `gbrain auth rescope --token <name> --member <id>`, config `mcp.stdio_member`). Every other remote caller gets the same `not_found` as for a missing page, including unbound credentials, a `--private-pages granted-sources` bot and both escape hatches (`GBRAIN_REMOTE_PRIVATE_PAGES=1`, `search.remote_private_pages=visible`), which relax only `visibility: private`. A malformed `readable_by` reads as nobody, and a page derived from a restricted page reads as nobody remotely. Pages that already named `readable_by` before this upgrade read as nobody remotely until `gbrain repair access` (preview, then `--apply`). The local CLI is unchanged; `--as <member>` previews one member\'s view.' },{ since: 'TBD', id: 'member_access_hatch_scope_gbra218', text: 'On a brain where any page names readers or any member exists, the escape hatches no longer turn the remote read filter off: remote reads still hide pages the caller\'s member is not listed on, and secondary surfaces that use the identity-free filter (proactive brief, retrieval reflex, entity resolution, known-as-of) hide every restricted page and keep hiding `visibility: private` pages under a hatch. A brain with no restriction keeps the old hatch behaviour exactly. A credential bound to a disabled or removed member is refused at verification (`access_member_disabled`).' },{ since: 'TBD', id: 'shared_agent_audience_gbra231', text: 'A shared agent can now read as the people a turn serves: its harness names the audience in the `X-Gbrain-On-Behalf-Of` header or request-level `_meta.on_behalf_of` (member ids, `group:<id>`, `guest`), and the call returns only pages every entry may read, within the agent\'s own source grant; a channel audience (more than one member, a group or a guest) never sees a `visibility: private` page. Each entry must be in the credential\'s `may_act_for` (`gbrain auth rescope --token <name> --may-act-for <list>`; for stdio, config `mcp.stdio_may_act_for`), which earlier releases stored without enforcing. An audience inside tool arguments is refused (`on_behalf_of_in_arguments`). Every remote MCP response now carries `_meta.access` (member, groups, audience, policy revisions, privacy relaxation), and `whoami` returns it as `access.applied`.' },- { since: 'TBD', id: 'qm_attested_actor_gst359', text: 'A trusted system can now name the person a call serves: a client-credentials client the brain host grants the attest right (`gbrain auth rescope --client <id> --attest-actor qm`) sends `x-qm-actor: <canonical id>`, and each attested operation runs as the member that id is linked to (`gbrain access member link <member> --qm <id>`), never reading `visibility: private` pages; agent jobs, write receipts, `delta` and fact and take writes are not attestable yet. A call that sends `x-qm-actor` or an `acting_user` argument without that right, for an operation outside the credential\'s `--attest-ops`, or with an id that is not 1-256 visible ASCII characters is refused (`actor_not_attested`); an id with no link to an enabled member is refused (`actor_unlinked`). Refusals carry their code in `structuredContent.error`. Every MCP server\'s `serverInfo` now includes a one-line `description`.' },+ { since: 'TBD', id: 'qm_attested_actor_gst359', text: 'A trusted system can now name the person a call serves: a client-credentials client the brain host grants the attest right (`gbrain auth rescope --client <id> --attest-actor qm`) sends `x-qm-actor: <canonical id>`, and each attested operation runs as the member that id is linked to (`gbrain access member link <member> --qm <id>`), never reading `visibility: private` pages; `capture`, `extract_facts`, `forget`, `forget_fact`, take writes and `list_write_conflicts` are not attestable yet. A call that sends `x-qm-actor` or an `acting_user` argument without that right, for an operation outside the credential\'s `--attest-ops`, or with an id that is not 1-256 visible ASCII characters is refused (`actor_not_attested`); an id with no link to an enabled member is refused (`actor_unlinked`). Refusals carry their code in `structuredContent.error`. Every MCP server\'s `serverInfo` now includes a one-line `description`.' },+ { since: 'TBD', id: 'member_facts_gst359', text: 'A fact a member saves remotely (`remember` attested as a person, or from a credential bound to one member) now goes on that member\'s own page `memory/members/<member>`, created with `readable_by: [member:<id>]`, as a `visibility: private` fact with the entity kept as metadata, instead of on the entity page where every reader of the source recalled it. Only that member recalls it; it never dedups against, supersedes or contests another page\'s fact, never consolidates into a take, and keeps its readers through a fence rebuild and relink. Under one attest client, hot memory, `delta` cursors, write receipts (`get_write_request`, `list_write_requests`, `cancel_write_request`, replays by `request_id`) and agent jobs (`get_agent_job`) are kept to the person they were made for: another person and the client\'s bare calls get `not_found`. `remember`, `delta`, the receipt operations, `submit_agent` and `get_agent_job` are now attestable.' },{ since: 'TBD', id: 'folder_access_rules_gbra218', text: 'A source can now keep whole folders to named members with folder rules (`gbrain access rule add --prefix partners/alice-example/ --readers alice-example,group:team-a --source <id>`, preview then `--yes`). On a repo-less source the rules live in the database; on a git-backed source they live in `.gbrain/access.yml`, committed through `gbrain git commit-push` and applied on sync. A remote read of a page under a rule needs the caller\'s member to be listed on every rule covering it, on top of the page\'s own `readable_by`; no hatch, grant or `--as` relaxes it. Narrowing applies at once; a change that widens (removing a rule or a reader) is held until `gbrain access apply --source <id>` previews it and `--yes --expect <plan_hash>` approves it. While an apply is unfinished its prefixes read as nobody remotely (`access_policy_pending`, fixed by `gbrain access resume --source <id>`). `gbrain export` carries each source\'s applied rules under `.gbrain/`, and `gbrain import` installs them before any page (`--access-policy <source>` picks one source\'s rules from a multi-source export). Remote callers cannot write `.gbrain/` pages. Nothing changes on a source with no folder rule.' },];diff --git a/src/core/cycle/phases/consolidate.ts b/src/core/cycle/phases/consolidate.tsindex 4798df33f9..abd2545a39 100644--- a/src/core/cycle/phases/consolidate.ts+++ b/src/core/cycle/phases/consolidate.ts@@ -140,6 +140,13 @@ export function parseClusterThreshold(value: string): number {return n;}+/** GST-359 C2: `facts` without those on a page that names readers (a member page): they never become a take on the entity page. */+async function withoutReadersSourced(engine: BrainEngine, facts: FactRow[]): Promise<FactRow[]> {+ const rows = await engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE id = ANY($1::bigint[]) AND ${readersSourcedFactSql('facts')}`, [facts.map(f => f.id)]);+ const restricted = new Set(rows.map(row => Number(row.id)));+ return facts.filter(f => !restricted.has(f.id));+}+export async function runPhaseConsolidate(engine: BrainEngine,opts: ConsolidatePhaseOpts = {},@@ -229,10 +236,7 @@ export async function runPhaseConsolidate(});// Takes here are the user's own (holder 'self'): a claim the assistant or// a named third party asserted is never promoted into one.- // GST-359 C2: a fact on a page that names readers (a member page) never becomes a take on the entity page.- const restricted = new Set((await engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE id = ANY($1::bigint[]) AND ${readersSourcedFactSql('facts')}`,- [candidates.map(f => f.id)])).map(row => Number(row.id)));- const unconsolidated = candidates.filter(f => !restricted.has(f.id) && (!managed || f.visibility === 'world') && (!f.attributed_to || f.attributed_to === 'user'));+ const unconsolidated = (await withoutReadersSourced(engine, candidates)).filter(f => (!managed || f.visibility === 'world') && (!f.attributed_to || f.attributed_to === 'user'));if (unconsolidated.length < minPerBucket) {bucketsSkipped += 1;continue;diff --git a/src/core/ops/jobs.ts b/src/core/ops/jobs.tsindex fca8b58e69..423b4df4a3 100644--- a/src/core/ops/jobs.ts+++ b/src/core/ops/jobs.ts@@ -346,6 +346,16 @@ function delegationDenied(ctx: OperationContext, error: Error & { reasons: strin// protected-name guard. Bindings are enforced PER-OP, not per-name.// 3. The dispatcher is the subagent handler with the gateway-native loop// (agent.use_gateway_loop is auto-on for submit_agent jobs).+/**+ * GST-359 C2: the attested actor an agent job belongs to (its accepted grant's actor), as [system, external_id,+ * member], '' outside an attested call. A remote agent job never coalesces (queue.add coalesces application jobs only).+ */+async function callerJobActor(): Promise<[string, string, string]> {+ const { currentCallerAccess } = await import('../search/private-visibility.ts');+ const actor = currentCallerAccess().actor;+ return actor ? [actor.system, actor.external_id, actor.member] : ['', '', ''];+}+const submit_agent: Operation = {name: 'submit_agent',idempotent: false,@@ -573,8 +583,11 @@ const get_agent_job: Operation = {FROM minion_jobs jWHERE j.id = $1AND j.name = 'subagent'- AND j.data->>'__owner_client_id' = $2`,- [id, clientId],+ AND j.data->>'__owner_client_id' = $2+ AND COALESCE(j.submission_authority->'grant'->'actor'->>'system', '') = $3+ AND COALESCE(j.submission_authority->'grant'->'actor'->>'external_id', '') = $4+ AND COALESCE(j.submission_authority->'grant'->'actor'->>'member', '') = $5`,+ [id, clientId, ...await callerJobActor()],);if (rows.length === 0) {// Uniform envelope: foreign-owned and nonexistent ids arediff --git a/test/access-member-facts.test.ts b/test/access-member-facts.test.tsindex 8107632c46..b7267e32ae 100644--- a/test/access-member-facts.test.ts+++ b/test/access-member-facts.test.ts@@ -22,7 +22,7 @@ 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, __setEmbedTransportForTests } from '../src/core/ai/gateway.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';@@ -57,7 +57,7 @@ const ALICE_ID = 'U0ALICE';const BOB_ID = '[email protected]';const ACME = 'companies/acme-example';const CANARY = { alice: 'canaryfactalice', bob: 'canaryfactbob' } as const;-const ATTEST_OPS = ['context_pack', 'delta', 'get_page', 'get_write_request', 'list_write_requests', 'put_page', 'recall', 'remember', 'search', 'whoami'];+const ATTEST_OPS = ['cancel_write_request', 'context_pack', 'delta', 'get_page', 'get_write_request', 'list_write_requests', 'put_page', 'recall', 'remember', 'search', 'whoami'];for (const kind of testBackends()) {describe('member facts and member-scoped reads (' + kind + ', repo-less)', () => {@@ -113,7 +113,7 @@ for (const kind of testBackends()) {await linkMember(engine, 'bob-example', 'qm', BOB_ID);}, 120_000);- afterAll(async () => { await close?.(); });+ afterAll(async () => { __setEmbedTransportForTests(null); resetGateway(); await close?.(); });test('an attested member fact lands private on the member page, created by it, with the entity kept as metadata', async () => {const out = await remember(who.alice(), 'Alice prefers oolong for harbor reviews ' + CANARY.alice, { entity: ACME, visibility: 'world' });@@ -184,7 +184,6 @@ for (const kind of testBackends()) {test('a member stops reading its own facts once its page\'s readers no longer name it', async () => {const bobPage = 'memory/members/bob-example';- const [before] = await engine.executeRaw<{ frontmatter: unknown }>('SELECT frontmatter FROM pages WHERE source_id = $1 AND slug = $2', [SRC, bobPage]);await engine.executeRaw(`UPDATE pages SET frontmatter = jsonb_set(frontmatter, '{readable_by}', '["group:team-a"]'::jsonb) WHERE source_id = $1 AND slug = $2`, [SRC, bobPage]);__resetPrivateVisibilityCacheForTests();const [narrowed] = await engine.executeRaw<{ page_readers: string[] }>('SELECT page_readers FROM pages WHERE source_id = $1 AND slug = $2', [SRC, bobPage]);@@ -197,7 +196,7 @@ for (const kind of testBackends()) {});}} finally {- await engine.executeRaw('UPDATE pages SET frontmatter = $3::jsonb WHERE source_id = $1 AND slug = $2', [SRC, bobPage, JSON.stringify(before!.frontmatter)]);+ await engine.executeRaw("UPDATE pages SET frontmatter = jsonb_set(frontmatter, '{readable_by}', jsonb_build_array('member:bob-example')) WHERE source_id = $1 AND slug = $2", [SRC, bobPage]);__resetPrivateVisibilityCacheForTests();}expect((await call(who.bobToken(), 'recall', { query: 'harbor' })).all).toContain(CANARY.bob);@@ -227,16 +226,20 @@ for (const kind of testBackends()) {expect(JSON.stringify(bare.meta ?? {})).not.toContain(CANARY.alice);}, 60_000);- test('delta: Alice then Bob on one session id keep separate cursors', async () => {+ test('delta: Alice, Bob and the bare client on one session id keep separate cursors, and only Alice sees her new fact', async () => {const session = 'delta-session-' + randomUUID().slice(0, 6);- const first = await call(who.alice(), 'delta', { session_id: session });- expect(first.isError).toBe(false);- expect(first.all).toContain('started this session');- const bob = await call(who.bob(), 'delta', { session_id: session });- expect(bob.isError).toBe(false);- expect(bob.all).toContain('started this session');- const bobAgain = await call(who.bob(), 'delta', { session_id: session });- expect(bobAgain.all).not.toContain(CANARY.alice);+ for (const as of [who.alice(), who.bob(), who.bare()]) {+ const first = await call(as, 'delta', { session_id: session });+ expect(first.isError).toBe(false);+ expect(first.all).toContain('started this session');+ }+ expect((await remember(who.alice(), 'Alice moves the harbor review to friday ' + CANARY.alice + 'delta')).isError).toBe(false);+ expect((await call(who.alice(), 'delta', { session_id: session })).all).toContain(CANARY.alice + 'delta');+ for (const as of [who.bob(), who.bare()]) {+ const later = await call(as, 'delta', { session_id: session });+ expect(later.isError).toBe(false);+ expect(later.all).not.toContain(CANARY.alice);+ }}, 60_000);test('receipts: Alice\'s write receipt is invisible to Bob and the bare client, and her request_id never replays for Bob', async () => {@@ -253,6 +256,12 @@ for (const kind of testBackends()) {expect(listed.all).not.toContain(requestId);}expect((await call(who.alice(), 'list_write_requests', {})).all).toContain(requestId);+ for (const as of [who.bob(), who.bare()]) {+ const cancelled = await call(as, 'cancel_write_request', { request_id: requestId });+ expect({ isError: cancelled.isError, code: cancelled.json.code ?? cancelled.json.error }).toEqual({ isError: true, code: 'not_found' });+ }+ const own = await call(who.alice(), 'cancel_write_request', { request_id: requestId });+ expect(own.json.code ?? own.json.error ?? own.json.state).not.toBe('not_found');const replay = await remember(who.bob(), 'Alice signs the harbor charter ' + CANARY.alice + 'r', { request_id: requestId });expect(replay.isError).toBe(true);expect(replay.all).not.toContain('"id":"' + factId + '"');@@ -271,6 +280,33 @@ for (const kind of testBackends()) {expect(bobReplay.json.code ?? bobReplay.json.error).toBe('idempotency_conflict');}, 60_000);+ test('agent jobs: Alice\'s job is hers alone, and two people\'s identical submissions never share a job', async () => {+ const reg = await provider().registerClientManual('c2-agent-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], SRC);+ await engine.executeRaw("UPDATE oauth_clients SET scope = 'read write agent', bound_tools = $2, bound_source_id = source_id, federated_read = ARRAY[source_id], delegated_namespace = 'job', delegated_slug_prefixes = NULL, bound_max_concurrent = 5 WHERE client_id = $1", [reg.clientId, ['get_page', 'search']]);+ await bindCredential(engine, { kind: 'client', id: reg.clientId }, { attestActor: 'qm', attestOps: ['get_agent_job', 'get_page', 'submit_agent'] });+ tokens.agent = (await provider().exchangeClientCredentials(reg.clientId, reg.clientSecret!)).access_token;+ const as = { alice: { token: 'agent', actor: ALICE_ID }, bob: { token: 'agent', actor: BOB_ID }, bare: { token: 'agent' } };+ const prompt = 'Summarize the harbor ledger notes';+ const ids: Record<string, number> = {};+ for (const [name, caller] of Object.entries(as)) {+ const out = await call(caller, 'submit_agent', { prompt });+ expect(out.isError, out.text).toBe(false);+ expect(out.json.coalesced).toBeUndefined();+ ids[name] = Number(out.json.id);+ }+ expect(new Set(Object.values(ids)).size).toBe(3);+ const canary = 'canaryagentjobalice';+ await engine.executeRaw("UPDATE minion_jobs SET status = 'completed', result = jsonb_build_object('text', $2::text), finished_at = now() WHERE id = $1", [ids.alice, canary]);+ expect((await call(as.alice, 'get_agent_job', { id: ids.alice })).all).toContain(canary);+ for (const caller of [as.bob, as.bare]) {+ const got = await call(caller, 'get_agent_job', { id: ids.alice });+ expect({ isError: got.isError, code: got.json.code ?? got.json.error }).toEqual({ isError: true, code: 'not_found' });+ expect(got.all).not.toContain(canary);+ }+ expect((await call(as.bob, 'get_agent_job', { id: ids.bob })).isError).toBe(false);+ expect((await call(as.bare, 'get_agent_job', { id: ids.bare })).isError).toBe(false);+ }, 60_000);+test('two members saving the same words get two facts, each on its own page', async () => {const words = 'I like jasmine tea at the harbor canarydupword';const a = await remember(who.alice(), words);diff --git a/test/access-member-sweep.test.ts b/test/access-member-sweep.test.tsindex 089027011b..111ee552c8 100644--- a/test/access-member-sweep.test.ts+++ b/test/access-member-sweep.test.ts@@ -17,7 +17,7 @@ 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, __setEmbedTransportForTests } from '../src/core/ai/gateway.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 } from '../src/mcp/dispatch.ts';@@ -128,7 +128,7 @@ for (const kind of testBackends()) {fixture.factId = String(fact!.id);}, 120_000);- afterAll(async () => { await close?.(); });+ afterAll(async () => { __setEmbedTransportForTests(null); resetGateway(); await close?.(); });test('the canary is reachable by its owner (the sweep is not vacuous)', async () => {const alice: Who = { label: 'alice', token: 'qm', actor: ALICE_ID };diff --git a/test/access-qm-actor.test.ts b/test/access-qm-actor.test.tsindex 20ab0ddca9..34c0b634d8 100644--- a/test/access-qm-actor.test.ts+++ b/test/access-qm-actor.test.ts@@ -23,7 +23,7 @@ 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 { executeRawJsonb, sqlQueryForEngine } from '../src/core/sql-query.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';import { mintLegacyToken } from '../src/core/token-mint.ts';import { parseRescopeTokenArgs, rescopeLegacyToken } from '../src/core/grants/legacy-token.ts';import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';@@ -401,28 +401,26 @@ for (const kind of testBackends()) {expect(() => parseAttestOps('get_page,' + op, lookup)).toThrow(/cannot run yet/);await expect(bindCredential(engine, { kind: 'client', id: clients.qm!.id }, { attestActor: 'qm', attestOps: ['get_page', op] })).rejects.toMatchObject({ code: 'invalid_params' });}- for (const op of ['get_agent_job', 'submit_agent', 'get_write_request', 'list_write_requests', 'cancel_write_request', 'delta', 'remember', 'capture', 'extract_facts']) {+ // GST-359 C2 keyed remember, delta, the write receipts and agent jobs to the person (test/access-member-facts.test.ts).+ for (const op of ['capture', 'extract_facts', 'forget', 'forget_fact', 'takes_add', 'list_write_conflicts']) {expect(ACTOR_DEFERRED_OPS.has(op)).toBe(true);}+ for (const op of ['get_agent_job', 'submit_agent', 'get_write_request', 'list_write_requests', 'cancel_write_request', 'delta', 'remember']) {+ expect(ACTOR_DEFERRED_OPS.has(op)).toBe(false);+ }const { clientId, clientSecret } = await provider().registerClientManual('qm-jobs-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], SRC);await engine.executeRaw("UPDATE oauth_clients SET scope = 'read write agent', bound_tools = $2, bound_source_id = source_id, federated_read = ARRAY[source_id], delegated_namespace = 'job', delegated_slug_prefixes = NULL, bound_max_concurrent = 1 WHERE client_id = $1", [clientId, ['get_page', ...ACTOR_DEFERRED_OPS]]);await bindCredential(engine, { kind: 'client', id: clientId }, { attestActor: 'qm', attestOps: ['get_page'] });await engine.executeRaw('UPDATE oauth_clients SET attest_ops = $2 WHERE client_id = $1', [clientId, ['get_page', ...ACTOR_DEFERRED_OPS]]);const bearer = (await provider().exchangeClientCredentials(clientId, clientSecret!)).access_token;- const canary = 'canaryqmjobresult';- const [job] = await executeRawJsonb<{ id: number }>(engine,- `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, result, finished_at) VALUES ('{}'::jsonb, 'subagent', 'default', 'completed', $1::jsonb, $2::jsonb, now()) RETURNING id`,- [], [{ __owner_client_id: clientId, actor: { system: 'qm', external_id: ALICE_ID, member: 'alice-example' } }, { text: canary }]);- expect((await call(bearer, 'get_agent_job', { id: Number(job!.id) })).text).toContain(canary);- const asBob = await refused(call(bearer, 'get_agent_job', { id: Number(job!.id) }, { actor: BOB_ID }), 'actor_not_attested', 'op_not_attested');- expect(asBob.text).not.toContain(canary);- expect(asBob.structured!.error!.fix).toBeUndefined();const deferredCalls: Array<[string, Record<string, unknown>]> = [- ['list_write_requests', {}], ['get_write_request', { id: randomUUID() }], ['cancel_write_request', { id: randomUUID() }],- ['delta', {}], ['remember', { content: 'alice-example prefers tea' }], ['capture', { content: 'note' }],- ['submit_agent', { prompt: 'x' }], ['extract_facts', { text: 'x' }],+ ['list_write_conflicts', {}], ['capture', { content: 'note' }], ['extract_facts', { text: 'x' }],+ ['forget_fact', { id: '1' }], ['takes_add', { page_slug: PAGES.alice.slug, claim: 'x' }],];- for (const [op, params] of deferredCalls) await refused(call(bearer, op, params, { actor: ALICE_ID }), 'actor_not_attested', 'op_not_attested');+ for (const [op, params] of deferredCalls) {+ const out = await refused(call(bearer, op, params, { actor: ALICE_ID }), 'actor_not_attested', 'op_not_attested');+ expect(out.structured!.error!.fix).toBeUndefined();+ }expect((await call(bearer, 'get_page', { slug: PAGES.alice.slug }, { actor: ALICE_ID })).text).toContain(PAGES.alice.canary);}, 120_000);