Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(access): GST-359 C2 review: A1 provenance filter outside member pages, actor-fenced job reads and cancel, member page ownership, slug-stable member ids
garrytan3fbe1e016764
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 14b71c2a9d..3cfe768fe5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -29,8 +29,8 @@ identifiers and attribution are available in the pre-removal Git revision| `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. `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 |+| 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. The page must name that member alone, or the fact is refused; remote `put_page`, `edit_page`, `delete_page` and every other remote page write under `memory/members/` are refused (`permission_denied`) unless the caller is that member. A member id a repo brain would store under another slug (`a--b`, `zed-`) holds no member facts (`invalid_params`) |+| 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 the client's own `get_job`, `wait_job`, `get_job_progress`, `list_jobs` and `cancel_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 89adc56fa7..3d764018ed 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` (`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/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`. 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/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/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex 32577fbf54..252c7f1985 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -251,7 +251,7 @@ access 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+read back only by that member, written remotely by no one else), and `delta` cursors, write receipts(`get_write_request`, `list_write_requests`, `cancel_write_request`) and agentjobs (`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 thediff --git a/docs/tutorials/company-brain.md b/docs/tutorials/company-brain.mdindex 75467ac95c..dfc6c0b754 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. 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.+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, and no one but that member writes under `memory/members/<member>` remotely; `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/member-facts.ts b/src/core/access/member-facts.tsindex 43e155460f..5ae673e78d 100644--- a/src/core/access/member-facts.ts+++ b/src/core/access/member-facts.ts@@ -13,9 +13,11 @@import { createHash } from 'node:crypto';import type { OperationContext } from '../ops/contract.ts';import { callerAccessAllowedSql, currentCallerAccess, folderRestrictedSql } from '../search/private-visibility.ts';-import { ACCESS_ID_RE } from './principals.ts';+import { ACCESS_ID_RE, MEMBER_PAGE_PREFIX, normalizeReaders } from './principals.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import { slugifyPath } from '../sync.ts';-export const MEMBER_PAGE_PREFIX = 'memory/members/';+export { MEMBER_PAGE_PREFIX };export const memberPageSlug = (member: string): string => `${MEMBER_PAGE_PREFIX}${member}`;@@ -28,11 +30,42 @@ export function callerMember(): string | null {return member && ACCESS_ID_RE.test(member) ? member : null;}-/** The member page a remote memory write goes to, or null when the caller writes as no single member (local or unbound). */+/**+ * The member page a remote memory write goes to, or null when the caller writes as no single member (local or+ * unbound). A member id whose page slug a repo brain would rename on sync (`a--b`, `zed-`) is refused: its facts+ * would land on another path.+ */export function memberFactPage(ctx: Pick<OperationContext, 'remote'>): string | null {if (ctx.remote === false) return null;const member = callerMember();- return member ? memberPageSlug(member) : null;+ if (!member) return null;+ const slug = memberPageSlug(member);+ if (slugifyPath(slug) !== slug) {+ throw opError('invalid_params', `Member id ${member} cannot hold member facts: its page ${slug} would be stored as ${slugifyPath(slug)}.`,+ 'Nothing was saved. The brain host gives this person a member id without repeated, leading or trailing separators (gbrain access member add) and links it instead.');+ }+ return slug;+}++/** Whether a member page is that member's own: its readers are exactly the member (a squatted or widened page is not). */+export function memberPageIsOwn(slug: string, frontmatter: unknown): boolean {+ const readers = normalizeReaders(frontmatter);+ return readers?.length === 1 && readers[0] === `member:${slug.slice(MEMBER_PAGE_PREFIX.length)}`;+}++/** The refusal for a member fact whose member page names any readers but that member alone. */+export function memberPageNotOwned(slug: string): OperationError {+ return opError('permission_denied', `${slug} does not name its member alone as its reader, so no member fact is saved there.`,+ `Nothing was saved. The brain host restores readable_by: [member:${slug.slice(MEMBER_PAGE_PREFIX.length)}] on ${slug}, then the fact can be saved again.`);+}++/** A remote write under memory/members/ goes only to the caller's own member page; trusted local callers are unaffected. */+export function assertMemberPageWriter(ctx: Pick<OperationContext, 'remote'>, slug: string, opName: string): void {+ if (ctx.remote === false || !slug.startsWith(MEMBER_PAGE_PREFIX)) return;+ const member = callerMember();+ if (member && slug === memberPageSlug(member)) return;+ throw opError('permission_denied', `${opName}: ${slug} is written remotely only by its own member.`,+ `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.`);}/** The frontmatter of a member page its first fact creates: the member is its only reader. */diff --git a/src/core/access/principals.ts b/src/core/access/principals.tsindex 304167adcf..20f181bb16 100644--- a/src/core/access/principals.ts+++ b/src/core/access/principals.ts@@ -13,6 +13,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/';const MAX_READERS = 256;export type Principal = `member:${string}` | `group:${string}`;diff --git a/src/core/minions/job-list-page.ts b/src/core/minions/job-list-page.tsindex eadfe719ce..a69a0352b4 100644--- a/src/core/minions/job-list-page.ts+++ b/src/core/minions/job-list-page.ts@@ -4,7 +4,7 @@* resumes after the last row returned. The per-call cap for remote callers lives in ops/read-paging.ts.*/import type { BrainEngine } from '../engine.ts';-import { rowToMinionJob, type MinionJob } from './types.ts';+import { jobActorSql, NO_JOB_ACTOR, rowToMinionJob, type JobActor, type MinionJob } from './types.ts';export class JobListCursorError extends Error {constructor(message: string) { super(message); this.name = 'JobListCursorError'; }@@ -20,7 +20,7 @@ export function parseJobListCursor(raw: string): { micros: string; id: number }}export async function listJobPage(engine: BrainEngine, opts: {- status?: string; queue?: string; name?: string; ownerClientId?: string; limit: number; cursor?: string;+ status?: string; queue?: string; name?: string; ownerClientId?: string; ownerActor?: JobActor; limit: number; cursor?: string;}): Promise<{ jobs: MinionJob[]; next_cursor?: string }> {const params: unknown[] = [];const where: string[] = [];@@ -32,7 +32,10 @@ export async function listJobPage(engine: BrainEngine, opts: {if (opts.status) { params.push(opts.status); where.push(`status = $${params.length}`); }if (opts.queue) { params.push(opts.queue); where.push(`queue = $${params.length}`); }if (opts.name) { params.push(opts.name); where.push(`name = $${params.length}`); }- if (opts.ownerClientId) { params.push(opts.ownerClientId); where.push(`data->>'__owner_client_id' = $${params.length}`); }+ if (opts.ownerClientId) {+ params.push(opts.ownerClientId); where.push(`data->>'__owner_client_id' = $${params.length}`);+ where.push(jobActorSql(params.length + 1)); params.push(...(opts.ownerActor ?? NO_JOB_ACTOR));+ }params.push(opts.limit + 1);const rows = await engine.executeRaw<Record<string, unknown> & { created_us: string | number }>(`SELECT *, ${CREATED_US}::text AS created_us FROM minion_jobs ${where.length ? `WHERE ${where.join(' AND ')}` : ''}diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.tsindex cc0353b07e..8e5302aa23 100644--- a/src/core/minions/queue.ts+++ b/src/core/minions/queue.ts@@ -14,7 +14,7 @@ import type {MinionJob, MinionJobInput, MinionJobStatus, InboxMessage, TokenUpdate,MinionQueueOpts, ChildDoneMessage, ChildOutcome, Attachment, AttachmentInput,} from './types.ts';-import { rowToMinionJob, rowToInboxMessage, rowToAttachment } from './types.ts';+import { rowToMinionJob, rowToInboxMessage, rowToAttachment, jobActorSql, NO_JOB_ACTOR, type JobActor } from './types.ts';import { WATCHDOG_SUSPECT_MARK, releaseWatchdogClaim, requeueCoRunnerStalls, unmarkedJobSql } from './watchdog-attribution.ts';export { WATCHDOG_SUSPECT_MARK } from './watchdog-attribution.ts';import { coalesceOnIdempotencyKey, decideCoalesce, insertOrCoalesce } from './idempotency-coalesce.ts';@@ -772,8 +772,8 @@ export class MinionQueue {** Returns the *root* (the job matching id), not an arbitrary descendant.*/- async cancelJob(id: number, opts?: { ownerClientId?: string }): Promise<MinionJob | null> {- const cancelled = await this.cancelJobs([id], opts?.ownerClientId ? { ownerClientId: opts.ownerClientId } : undefined);+ async cancelJob(id: number, opts?: { ownerClientId?: string; ownerActor?: JobActor }): Promise<MinionJob | null> {+ const cancelled = await this.cancelJobs([id], opts?.ownerClientId ? { ownerClientId: opts.ownerClientId, ownerActor: opts.ownerActor } : undefined);const root = cancelled.find(j => j.id === id);return root ?? null;}@@ -1032,7 +1032,7 @@ export class MinionQueue {* every surface keyed on a reason prefix (jobs stats, doctor) would* silently report zero without this parameter.*/- async cancelJobs(ids: number[], opts?: { reason?: string; rootStatuses?: MinionJobStatus[]; ownerClientId?: string }): Promise<MinionJob[]> {+ async cancelJobs(ids: number[], opts?: { reason?: string; rootStatuses?: MinionJobStatus[]; ownerClientId?: string; ownerActor?: JobActor }): Promise<MinionJob[]> {if (ids.length === 0) return [];// opts.rootStatuses re-checks each ROOT id's status ATOMICALLY inside the// cancel UPDATE's CTE seed. The waiting-TTL sweep passes ['waiting'] to@@ -1055,7 +1055,7 @@ export class MinionQueue {SELECT id, 0 AS d FROM minion_jobsWHERE id = ANY($1::int[])AND ($3::text[] IS NULL OR status = ANY($3::text[]))- AND ($4::text IS NULL OR data->>'__owner_client_id' = $4::text)+ AND ($4::text IS NULL OR (data->>'__owner_client_id' = $4::text AND ${jobActorSql(5)}))UNION ALLSELECT m.id, descendants.d + 1FROM minion_jobs m@@ -1077,7 +1077,7 @@ export class MinionQueue {WHERE id IN (SELECT id FROM descendants)AND status IN ('waiting','active','delayed','waiting-children','paused')RETURNING *`,- [ids, opts?.reason ?? null, rootStatuses, ownerClientId]+ [ids, opts?.reason ?? null, rootStatuses, ownerClientId, ...(opts?.ownerActor ?? NO_JOB_ACTOR)]);if (rows.length === 0) return [];diff --git a/src/core/minions/terminal-events.ts b/src/core/minions/terminal-events.tsindex bb20ea43ef..efea88079d 100644--- a/src/core/minions/terminal-events.ts+++ b/src/core/minions/terminal-events.ts@@ -6,7 +6,7 @@* (remove_on_complete / remove_on_fail) and pruned rows are not events.*/import type { BrainEngine } from '../engine.ts';-import { rowToMinionJob, type MinionJob } from './types.ts';+import { jobActorSql, NO_JOB_ACTOR, rowToMinionJob, type JobActor, type MinionJob } from './types.ts';export class TerminalCursorError extends Error {constructor(message: string) { super(message); this.name = 'TerminalCursorError'; }@@ -24,7 +24,7 @@ export function parseTerminalCursor(raw: string): { micros: string; id: number }const FINISHED_US = "(EXTRACT(EPOCH FROM finished_at) * 1000000)::bigint";-export async function listFinishedSince(engine: BrainEngine, since: string, opts: { queue?: string; name?: string; limit?: number; ownerClientId?: string } = {}): Promise<{ jobs: MinionJob[]; next_cursor: string }> {+export async function listFinishedSince(engine: BrainEngine, since: string, opts: { queue?: string; name?: string; limit?: number; ownerClientId?: string; ownerActor?: JobActor } = {}): Promise<{ jobs: MinionJob[]; next_cursor: string }> {const cursor = parseTerminalCursor(since);const params: unknown[] = [cursor.micros, cursor.id];const where = [@@ -34,7 +34,10 @@ export async function listFinishedSince(engine: BrainEngine, since: string, opts];if (opts.queue) { params.push(opts.queue); where.push(`queue = $${params.length}`); }if (opts.name) { params.push(opts.name); where.push(`name = $${params.length}`); }- if (opts.ownerClientId) { params.push(opts.ownerClientId); where.push(`data->>'__owner_client_id' = $${params.length}`); }+ if (opts.ownerClientId) {+ params.push(opts.ownerClientId); where.push(`data->>'__owner_client_id' = $${params.length}`);+ where.push(jobActorSql(params.length + 1)); params.push(...(opts.ownerActor ?? NO_JOB_ACTOR));+ }params.push(Math.max(1, Math.min(500, Math.floor(opts.limit ?? 50))));const rows = await engine.executeRaw<Record<string, unknown> & { finished_us: string | number }>(`SELECT *, ${FINISHED_US}::text AS finished_us FROM minion_jobs WHERE ${where.join(' AND ')}diff --git a/src/core/minions/types.ts b/src/core/minions/types.tsindex 1abb098a9b..4f775c5c59 100644--- a/src/core/minions/types.ts+++ b/src/core/minions/types.ts@@ -831,3 +831,19 @@ export interface SubagentResult {*/oneshot_skipped?: boolean;}++/**+ * GST-359 C2: the attested actor an agent job belongs to. submit_agent stores it in the accepted grant+ * (`submission_authority.grant.actor`); every owner-fenced job read and cancel also matches it, so behind one attest+ * client a job is visible only to the person it was submitted for, and a job without one only to unattested calls.+ */+export type JobActor = readonly [string, string, string];++/** The actor of a caller without an attested one. */+export const NO_JOB_ACTOR: JobActor = ['', '', ''];++/** SQL: the job's accepted actor equals the three parameters starting at `$first`. `alias` is a code-provided table alias. */+export function jobActorSql(first: number, alias?: string): string {+ const actor = `${alias ? alias + '.' : ''}submission_authority->'grant'->'actor'`;+ return ['system', 'external_id', 'member'].map((key, i) => `COALESCE(${actor}->>'${key}', '') = $${first + i}::text`).join(' AND ');+}diff --git a/src/core/ops/context.ts b/src/core/ops/context.tsindex 61cc2a5fed..7985f498f7 100644--- a/src/core/ops/context.ts+++ b/src/core/ops/context.ts@@ -25,6 +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 { assertRemoteTargetReadable, remoteTargetHidden } from '../persistence/page-visibility.ts';// --- Agent-contract fixes shared by the op error sites ---@@ -374,6 +375,7 @@ export function slugOutsideCallerFence(ctx: OperationContext, slug: string): boo* 'notes-archive/...' by startsWith construction.*/export function enforceClientSlugFence(ctx: OperationContext, slug: string, opName: string): void {+ assertMemberPageWriter(ctx, slug, opName);if (ctx.auth?.fenceProjectionDegraded) {throw opError('permission_denied',diff --git a/src/core/ops/jobs.ts b/src/core/ops/jobs.tsindex 423b4df4a3..a2044054fd 100644--- a/src/core/ops/jobs.ts+++ b/src/core/ops/jobs.ts@@ -1,5 +1,7 @@import { prepareRemoteJob, prepareRemoteAgent, assertRemoteJobControl } from '../minions/submission-authority.ts';import type { MinionJob } from '../minions/types.ts';+import { jobActorSql, NO_JOB_ACTOR, type JobActor } from '../minions/types.ts';+import { currentCallerAccess } from '../search/private-visibility.ts';function publicJob(job: MinionJob) {const { submission_authority: _authority, ...visible } = job;@@ -126,8 +128,8 @@ function jobStateError(id: unknown, message: string, need: string): OperationErr*/async function assertJobOwned(ctx: OperationContext, id: number, owner: string): Promise<void> {const rows = await ctx.engine.executeRaw<{ id: number }>(- `SELECT id FROM minion_jobs WHERE id = $1 AND data->>'__owner_client_id' = $2`,- [id, owner],+ `SELECT id FROM minion_jobs WHERE id = $1 AND data->>'__owner_client_id' = $2 AND ${jobActorSql(3)}`,+ [id, owner, ...callerJobActor()],);if (rows.length === 0) {throw jobNotFound(`Job not found: ${id}`);@@ -347,13 +349,12 @@ function delegationDenied(ctx: OperationContext, error: Error & { reasons: strin// 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).+ * GST-359 C2: the caller's attested actor, matched against a job's accepted grant (jobActorSql in minions/types.ts). A remote+ * agent job never coalesces (queue.add coalesces application jobs only), so two people's submissions stay two jobs.*/-async function callerJobActor(): Promise<[string, string, string]> {- const { currentCallerAccess } = await import('../search/private-visibility.ts');+function callerJobActor(): JobActor {const actor = currentCallerAccess().actor;- return actor ? [actor.system, actor.external_id, actor.member] : ['', '', ''];+ return actor ? [actor.system, actor.external_id, actor.member] : NO_JOB_ACTOR;}const submit_agent: Operation = {@@ -584,10 +585,8 @@ const get_agent_job: Operation = {WHERE j.id = $1AND j.name = 'subagent'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()],+ AND ${jobActorSql(3, 'j')}`,+ [id, clientId, ...callerJobActor()],);if (rows.length === 0) {// Uniform envelope: foreign-owned and nonexistent ids are@@ -712,7 +711,7 @@ const list_jobs: Operation = {try {const page = await listFinishedSince(ctx.engine, String(p.finished_since), {queue: p.queue as string | undefined, name: p.name as string | undefined, limit: (p.limit as number) || 50,- ...(owner !== null ? { ownerClientId: owner } : {}),+ ...(owner !== null ? { ownerClientId: owner, ownerActor: callerJobActor() } : {}),});return { jobs: await project(page.jobs), next_cursor: page.next_cursor };} catch (e) {@@ -728,7 +727,7 @@ const list_jobs: Operation = {status: p.status as string | undefined, queue: p.queue as string | undefined, name: p.name as string | undefined, limit,...(p.cursor !== undefined && p.cursor !== null ? { cursor: String(p.cursor) } : {}),// #4098: SQL-side ownership fence for agent-scoped callers.- ...(owner !== null ? { ownerClientId: owner } : {}),+ ...(owner !== null ? { ownerClientId: owner, ownerActor: callerJobActor() } : {}),});} catch (e) {if (e instanceof JobListCursorError) throw invalidParam(ctx, 'list_jobs', 'cursor', `list_jobs: ${e.message}`, { example: '1792000000000000:42' });@@ -762,7 +761,7 @@ const cancel_job: Operation = {// #4098: the owner predicate rides the recursive cancel's CTE seed — a// fenced caller can cancel only roots it owns (descendants of an owned// root cascade as usual). Foreign and missing ids share one envelope.- const cancelled = await queue.cancelJob(p.id as number, owner !== null ? { ownerClientId: owner } : undefined);+ const cancelled = await queue.cancelJob(p.id as number, owner !== null ? { ownerClientId: owner, ownerActor: callerJobActor() } : undefined);if (!cancelled) throw jobStateError(p.id, `Cannot cancel job ${p.id} (may already be in terminal status)`, 'Only waiting, active, delayed or paused jobs can be cancelled.');// private_queue_owner_token is a capability credential (lease renewal /// attach), not job data — never expose it over MCP envelopes.diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 1a8d4a7875..8a19dcab1c 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -30,7 +30,7 @@ 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 { memberFactPage } from '../access/member-facts.ts';+import { memberFactPage, memberPageIsOwn, memberPageNotOwned } from '../access/member-facts.ts';export { prepareMemoryMutation } from './memory-prepare.ts';/** Only semantic appends without an explicit caller revision can be recomputed. */@@ -91,6 +91,7 @@ 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 (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.diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 5d5eee637e..560f29d1fb 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -32,7 +32,7 @@ import { withPageTierKept } from '../trust/fence-append.ts';import { 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, onMemberPageSql } from '../access/member-facts.ts';+import { MEMBER_PAGE_PREFIX, memberPageFrontmatter, memberPageIsOwn, memberPageNotOwned, onMemberPageSql } from '../access/member-facts.ts';function receiptFix(row: WriteRequest): Action {return row.principal_kind === 'local_cli'@@ -109,6 +109,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque// 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;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);// 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)));diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex f158a981ae..ed81dbbc83 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -23,7 +23,7 @@import { AsyncLocalStorage } from 'node:async_hooks';import type { BrainEngine } from '../engine.ts';import { isValidSourceId } from '../source-id.ts';-import { hasReaders, normalizePrincipal, readersAllow, validIdentity } from '../access/principals.ts';+import { hasReaders, MEMBER_PAGE_PREFIX, normalizePrincipal, readersAllow, validIdentity } from '../access/principals.ts';import { validPrefix, validQualifiedRuleId } from '../access/folder-rules.ts';export const REMOTE_PRIVATE_PAGES_KEY = 'search.remote_private_pages';@@ -605,18 +605,19 @@ export function privateTimelineEventFilterForCaller(timelineAlias: string): stri*//*** GBRA-218: privateProvenanceFilterFragment for the fact reads a caller gates on `excludePrivate`. The readers part- * always applies, judged as the caller: a fact held in or extracted from a page that names readers reaches only the- * callers that page admits (none outside a caller record); the privacy part is dropped when an operator relaxed- * privacy for this remote read, which is what the hatches did to these reads before member access (`excludePrivate`- * was false then). Outside a remote record nothing relaxes it.+ * always applies (a world fact held in or extracted from a page that names readers stays hidden from every remote+ * caller, as with the plain fragment); the privacy part is dropped when an operator relaxed privacy for this remote+ * read, which is what the hatches did to these reads before member access (`excludePrivate` was false then).+ * Outside a remote record nothing relaxes it. GST-359 C2: a fact on a member page (`memory/members/<member>`) alone+ * is judged as the caller (its member identity, or every audience entry), so its member reads it back.*/export function privateProvenanceFilterUnderPolicy(factAlias: string): string {- // GST-359 C2: judged as the caller (its member identity, or every audience entry), so a fact on a page that names- // readers reaches exactly the callers who read that page; outside a caller record the identity is empty (hide all).const access = currentCallerAccess();const identity = access.audienceIdentities.length ? { all: access.audienceIdentities } : access.identity;- return `NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = ${factAlias}.source_id ` +- `AND pp.slug = ${factAlias}.source_markdown_slug AND NOT ${readPolicyFragment('pp', identity, !callerRelaxesPrivacy(), access.satisfiedRuleIds)})`;+ const hide = !callerRelaxesPrivacy();+ const memberPage = `starts_with(pp.slug, '${MEMBER_PAGE_PREFIX}')`;+ return `NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = ${factAlias}.source_id AND pp.slug = ${factAlias}.source_markdown_slug ` ++ `AND NOT CASE WHEN ${memberPage} THEN ${readPolicyFragment('pp', identity, hide, access.satisfiedRuleIds)} ELSE ${readPolicyFragment('pp', [], hide)} END)`;}/** True only inside a remote caller record whose read an operator relaxed (the env hatch or the config opt-out). */diff --git a/test/access-member-facts.test.ts b/test/access-member-facts.test.tsindex b7267e32ae..1f601796d1 100644--- a/test/access-member-facts.test.ts+++ b/test/access-member-facts.test.ts@@ -32,6 +32,7 @@ import { addMember, bindCredential } from '../src/core/access/members.ts';import { linkMember } from '../src/core/access/actor.ts';import { memberPageSlug } from '../src/core/access/member-facts.ts';import { decideSingleFact, type SingleFactIntent } from '../src/core/facts/single-prepare.ts';+import { prepareMemoryMutation } from '../src/core/persistence/memory-prepare.ts';import { runFactsRelink } from '../src/core/facts/relink.ts';import { runPhaseConsolidate } from '../src/core/cycle/phases/consolidate.ts';import { serializePageToMarkdown } from '../src/core/markdown.ts';@@ -57,7 +58,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 = ['cancel_write_request', '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', 'delete_page', 'delta', 'edit_page', '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)', () => {@@ -305,6 +306,82 @@ for (const kind of testBackends()) {}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);+ // The agent-scoped job reads and cancel (no header: the client's own lane) never reach a person's job.+ for (const [op, params] of [['get_job', {}], ['wait_job', { timeout_s: 1 }], ['get_job_progress', {}], ['cancel_job', {}]] as const) {+ const got = await call(as.bare, op, { id: ids.alice, ...params });+ expect({ op, isError: got.isError, code: got.json.code ?? got.json.error }).toMatchObject({ op, isError: true });+ expect(got.all).not.toContain(canary);+ expect(got.all).not.toContain(prompt);+ }+ for (const params of [{}, { status: 'completed' }, { finished_since: '0:0' }]) {+ const listed = await call(as.bare, 'list_jobs', params);+ expect(listed.isError, listed.text).toBe(false);+ expect(listed.all).not.toContain(canary);+ expect(listed.all).not.toContain('"id":' + ids.alice + ',');+ }+ expect((await call(as.bare, 'get_job', { id: ids.bare })).isError).toBe(false);+ expect((await call(as.bare, 'list_jobs', {})).all).toContain('"id":' + ids.bare + ',');+ const [state] = await engine.executeRaw<{ status: string }>('SELECT status FROM minion_jobs WHERE id = $1', [ids.alice]);+ expect(state!.status).toBe('completed');+ const [bobState] = await engine.executeRaw<{ status: string }>('SELECT status FROM minion_jobs WHERE id = $1', [ids.bob]);+ expect((await call(as.bare, 'cancel_job', { id: ids.bob })).isError).toBe(true);+ expect((await engine.executeRaw<{ status: string }>('SELECT status FROM minion_jobs WHERE id = $1', [ids.bob]))[0]!.status).toBe(bobState!.status);+ }, 60_000);++ test('member pages: nobody else writes one remotely, and a squatted or widened page takes no member fact', async () => {+ const CAROL_ID = 'U0CAROL';+ const DAVE_ID = 'U0DAVE';+ for (const [id, ext] of [['carol-example', CAROL_ID], ['dave-example', DAVE_ID]] as const) {+ await addMember(engine, id);+ await linkMember(engine, id, 'qm', ext);+ }+ const carol = { token: 'qm', actor: CAROL_ID };+ const dave = { token: 'qm', actor: DAVE_ID };+ const squat = '---\ntype: note\ntitle: Memory of carol-example\nreadable_by:\n - member:bob-example\n - member:carol-example\n---\n# Memory of carol-example\n';+ for (const as of [who.bob(), who.bobToken(), who.bare()]) {+ const put = await call(as, 'put_page', { slug: 'memory/members/carol-example', content: '---\ntype: note\ntitle: Squat\n---\n# Squat\n' });+ expect({ isError: put.isError, code: put.json.code ?? put.json.error }).toEqual({ isError: true, code: 'permission_denied' });+ const edit = await call(as, 'edit_page', { slug: 'memory/members/alice-example', expected_revision: '00000000-0000-0000-0000-000000000000', edits: [{ old_text: 'Memory', new_text: 'Mine' }] });+ expect({ isError: edit.isError, code: edit.json.code ?? edit.json.error }).toEqual({ isError: true, code: 'permission_denied' });+ const del = await call(as, 'delete_page', { slug: 'memory/members/alice-example' });+ expect({ isError: del.isError, code: del.json.code ?? del.json.error }).toEqual({ isError: true, code: 'permission_denied' });+ }+ const [alicePage] = await engine.executeRaw<{ deleted_at: unknown; page_readers: string[] }>('SELECT deleted_at, page_readers FROM pages WHERE source_id = $1 AND slug = $2', [SRC, 'memory/members/alice-example']);+ expect(alicePage).toMatchObject({ deleted_at: null, page_readers: ['member:alice-example'] });+ expect(await engine.executeRaw('SELECT 1 FROM pages WHERE source_id = $1 AND slug = $2', [SRC, 'memory/members/carol-example'])).toHaveLength(0);+ // A page squatted before Carol's first fact (readers Bob and Carol) takes none of her facts.+ await importFromContent(engine, 'memory/members/carol-example', squat, { sourceId: SRC });+ const squatId = 'c2-squat-' + randomUUID().slice(0, 6);+ const squatted = await remember(carol, 'Carol keeps the harbor ledger key canarycarolsquat', { request_id: squatId });+ // remember answers in its verb contract: an authorization refusal is scope_denied.+ expect({ isError: squatted.isError, code: squatted.json.code, message: squatted.json.message }).toMatchObject({ isError: true, code: 'scope_denied', message: expect.stringContaining('does not name its member alone') });+ expect(await engine.executeRaw('SELECT 1 FROM facts WHERE fact LIKE $1', ['%canarycarolsquat%'])).toHaveLength(0);+ // Refused at submission: nothing was accepted, so there is no receipt.+ expect((await call(carol, 'get_write_request', { request_id: squatId })).json.code).toBe('not_found');+ // Dave's page later made world: his next fact is refused, never saved where every reader recalls it.+ expect((await remember(dave, 'Dave books the harbor dock canarydaveone')).isError).toBe(false);+ await importFromContent(engine, 'memory/members/dave-example', '---\ntype: note\ntitle: Memory of dave-example\n---\n# Memory of dave-example\n', { sourceId: SRC });+ const widened = await remember(dave, 'Dave books the harbor crane canarydavetwo');+ expect({ isError: widened.isError, code: widened.json.code, message: widened.json.message }).toMatchObject({ isError: true, code: 'scope_denied', message: expect.stringContaining('does not name its member alone') });+ expect(await engine.executeRaw('SELECT 1 FROM facts WHERE fact LIKE $1', ['%canarydavetwo%'])).toHaveLength(0);+ }, 120_000);++ test('preparation refuses a member fact once its page no longer names that member alone', async () => {+ const slug = 'memory/members/erin-example';+ await importFromContent(engine, slug, '---\ntype: note\ntitle: Memory of erin-example\nreadable_by:\n - member:bob-example\n - member:erin-example\n---\n# Memory of erin-example\n', { sourceId: SRC });+ const row = { operation: 'remember', request_id: 'c2-prepare-' + randomUUID().slice(0, 6), source_id: SRC, slug, page_id: null,+ intent: { fact: 'Erin signs the harbor lease canaryerinprep', kind: 'fact', visibility: 'private', entity_slug: null, fence: true, member_page: true, valid_from: new Date().toISOString() } };+ await expect(prepareMemoryMutation(engine, row as never, {} as never)).rejects.toMatchObject({ code: 'permission_denied' });+ }, 60_000);++ test('a member id whose page slug a repo brain would rename holds no member facts', async () => {+ for (const id of ['frank--example', 'gina-']) {+ await addMember(engine, id);+ await linkMember(engine, id, 'qm', 'U0' + id.replace(/[^a-z]/g, '').toUpperCase());+ const out = await remember({ token: 'qm', actor: 'U0' + id.replace(/[^a-z]/g, '').toUpperCase() }, 'A harbor fact canaryslug' + id.length);+ expect({ isError: out.isError, code: out.json.code ?? out.json.error }).toEqual({ isError: true, code: 'invalid_params' });+ expect(await engine.executeRaw('SELECT 1 FROM pages WHERE source_id = $1 AND slug LIKE $2', [SRC, 'memory/members/' + id.slice(0, 4) + '%'])).toHaveLength(0);+ }}, 60_000);test('two members saving the same words get two facts, each on its own page', async () => {