Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Withhold hot memory from refused connections; serves pin is case-insensitive; shared_stdio_binding skips one-person brains

garrytan40eee7324fa8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 28eab72e36..ca838e8e26 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -26,11 +26,12 @@ identifiers and attribution are available in the pre-removal Git revision
### Itemized changes
-- `src/core/access/requester-scope.ts` (new): the gate, run in `dispatchToolCall` after access resolves and in every agent job tool call. Every read op and every read-scope op (`think` included) is gated unless it reads no page: `whoami`, `get_brain_identity`, `get_status_snapshot`, `search_modes`, `get_health`, the caller's own `join_brain` / `leave_brain` / `sync_brain_skills` / `request_tools`, and a non-admin credential's own `get_job` / `wait_job`. When the serves policy cannot be read it is read once more, and a second failure refuses retryably (`requester_scope_unknown`) rather than reading as one person; a bound credential is never refused that way.
+- `src/core/access/requester-scope.ts` (new): the gate, run in `dispatchToolCall` after access resolves and in every agent job tool call. Every read op and every read-scope op (`think` included) is gated unless it reads no page: `whoami`, `get_brain_identity`, `get_status_snapshot`, `search_modes`, `get_health`, the caller's own `join_brain` / `leave_brain` / `sync_brain_skills` / `request_tools`, and a non-admin credential's own `get_job` / `wait_job`. When the serves policy cannot be read it is read once more, and a second failure refuses retryably (`requester_scope_unknown`) rather than reading as one person; a bound credential is never refused that way. A connection whose reads are refused gets no `_meta.brain_hot_memory` on the calls the gate lets through (the exempt ops above and writes), so it cannot read recent facts through `whoami`.
+- `access.serves` is read without regard to case or surrounding spaces (`One` pins one person). `access.serves_since` is set once and never cleared, so a brain that served several people once and does again later gets no new grace.
- Migration v308 (number assigned at the merge slot): `reads_unscoped` on `access_tokens` and `oauth_clients`, and a trigger that keeps config `access.serves_derived` and sets `access.serves_since` once, the first time the brain serves several people, so a request reads both from its config snapshot. Disabling and re-enabling a member does not restart the grace. Nothing else is rewritten.
- `gbrain auth create`, `gbrain auth register-client` and the admin dashboard's key mint refuse an unbound credential on such a brain (`credential_scope_required`). `gbrain auth rescope ... --reads-unscoped --yes` (`none` removes it) is the explicit opt-out, written to the `access-reads-unscoped` audit file; `gbrain access check` reports it.
- The fix every refusal, notice, `whoami` note and `gbrain access owner` hint gives for stdio is the per-harness binding, `gbrain setup claude-code|codex --stdio-member <id>`, on PGLite and Postgres alike, or a per-person key over `gbrain serve --http` for a harness several people talk to. Nothing suggests `config set mcp.stdio_member`, and no upgrade, doctor or setup path writes it.
-- Doctor: `unscoped_shared_reads` fails per unbound credential with its state, grace end and bind command (warns while `access.requester_scope_enforce` is false); `shared_stdio_binding` fails when `mcp.stdio_member` is set on a host where OpenClaw or Hermes is installed, with `gbrain config unset mcp.stdio_member` as its ask-first fix. `gbrain post-upgrade` lists the unbound credentials.
+- Doctor: `unscoped_shared_reads` fails per unbound credential with its state, grace end and bind command (warns while `access.requester_scope_enforce` is false); `shared_stdio_binding` fails when `mcp.stdio_member` is set on a host where OpenClaw or Hermes is installed, with `gbrain config unset mcp.stdio_member` as its ask-first fix, and is not applicable on a brain that serves one person. `gbrain post-upgrade` lists the unbound credentials.
- `src/commands/setup-serves.ts`: a `hermes` on PATH counts as the Hermes agent only when it is a script, so React Native's compiled `hermes` engine no longer makes setup refuse `--stdio-member` or doctor fail `shared_stdio_binding`.
- Hosted brains keep `access.requester_scope_enforce false` until their control plane binds each connection; every unbound read then answers with the notice and nothing is refused.
- Docs: `docs/guides/write-refusals.md` (the three codes), `docs/guides/setup.md`, `docs/guides/multi-source-brains.md`, `docs/tutorials/company-brain.md`, `docs/architecture/key-files/access.md`; a behaviour-change notice row explains the change on upgrade.
diff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.md
index 714e4729cc..e396de8c12 100644
--- a/docs/architecture/key-files/access.md
+++ b/docs/architecture/key-files/access.md
@@ -8,6 +8,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/access/serves.ts` + `src/commands/access-serves.ts` (GST-363 PR 1) — whether a brain serves several people (`brainServes`: config `access.serves` `one`|`several` wins, else `access.serves_derived`, which migration v308's trigger keeps as `several` while 2+ members are enabled; `since` is `access.serves_since`, set once) and `gbrain access serves [several --members a,b [--yes]]`: preview, then config, members (kept when present), one folder rule `people/<member>/` per member through `addFolderRules` (`access-rules.ts`, the `rule add` preview-then-write path; a git store commits `.gbrain/access.yml` through the commit door), and one read-write token `member-<id>` per member through `auth-mint.ts` (the `auth create` mint) written to `<configDir>/member-keys/<id>.key` (0600, dir 0700, refused inside a git work tree: `access_serves_key_dir_in_git`). Idempotent on the member id; a token whose file is gone is reported, never re-minted. `GBRAIN_SETUP_ABORT_AFTER=serves-members|serves-rules|serves-key` is the crash seam. Doctor: `checks/unlabeled-people-folders.ts` fails a `people/<x>/` folder with pages no rule covers on a several-person brain. Tests: `test/setup-serves-several.test.ts` (both engines).
- `gbrain serve --stdio-member <id>` (GST-363 PR 3) — `parseStdioMemberFlag`, `registeredStdioMember` and `withStdioMember` live in `src/core/stdio-member-flag.ts` (kept out of `mcp-registration.ts` so serve and doctor pick up no registration flags); serve passes the value to `startMcpServer`, dispatch sets `OperationContext.stdioMember` only for an unauthenticated stdio call, and `caller.ts` resolves it live ahead of config `mcp.stdio_member` (a disabled or unknown member reads as nobody, no fallback). Stored writes stamp it on `WriteAuthority.stdioMember` (jsonb, no migration); a stdio watch uses principal id `registration` so the wake drain re-checks that member. Setup writes it into one claude-code or codex entry (`ClaudeSetupPlan`/`CodexSetupPlan.stdioMember`); inspection reports an owned entry's member so setup re-runs and `refreshHookLaunchers` carry it, and `setupRerunArgv` never names it.
- `src/core/access/requester-scope.ts` + `src/commands/doctor/checks/unscoped-shared-reads.ts` (GST-363 PR 2) — on a brain that serves several people (`servesPolicyFrom` in `search/private-visibility.ts`, read from the request config snapshot: explicit `access.serves` wins, else `access.serves_derived`; a brain pinned `one` never gates) a remote read from a connection bound to no member (no member identity, no audience, not attested, no `reads_unscoped`) is refused `requester_scope_required` before any work. Deny by default: every op not `mutating: true`, and every read-scope one (`think`), except `REQUESTER_SCOPE_EXEMPT` and `OWN_JOB_OPS` for a non-admin credential; `test/requester-scope.test.ts` pins the list and spies every handler. `requesterScopeGate` runs in `dispatchToolCall` after access resolves (attested calls exempt; an unreachable op keeps the unknown-tool envelope) and in `brain-allowlist.ts` `scopedJobAccess` per job tool call; a bound caller's access is never changed. `readsUnscoped`/`createdAt` come from the verifiers (`token-binding.ts` `credentialScopeFields`), else `credentialScopeFor`. Grace: 14 days from `access.serves_since` (migration v308's trigger sets it once) for connections created at or before it (unknown creation and stdio count as old), with `_meta.access.requester_scope`; `access.requester_scope_enforce false` (hosted) gives the notice only. An unreadable policy (`servesUnknown`) is read once more (`withServesReread`); a second failure refuses `requester_scope_unknown` (retryable). `assertCredentialScoped` refuses unbound `auth create`/`register-client` and `POST /admin/api/api-keys` (`credential_scope_required`); `--reads-unscoped [none]` changes go to the `access-reads-unscoped` audit file. `unscopedConnections` feeds doctor `unscoped_shared_reads`, `whoami` (`requesterScopeView`) and post-upgrade.
-- `src/core/access/stdio-bind-route.ts` + `src/commands/doctor/checks/shared-stdio-binding.ts` (GST-363 PR 2) — `stdioBindRoute()` is the one place that says how to bind an unbound stdio connection: `gbrain setup claude-code|codex --stdio-member <id>` for a harness one person uses (that harness entry, either engine), else a per-person `serve --http` key. The requester-scope refusal and notice, `gbrain access owner`'s Bind-one line and whoami's unbound note read it. Doctor `shared_stdio_binding` fails when `mcp.stdio_member` is set and `sharedStdioHarness()` (`setup-serves.ts`; a `hermes` on PATH counts only as a script, not React Native's compiled engine) finds OpenClaw or Hermes; fix `gbrain config unset mcp.stdio_member`. Tests: `test/shared-stdio-binding.test.ts`.
+- `src/core/access/stdio-bind-route.ts` + `src/commands/doctor/checks/shared-stdio-binding.ts` (GST-363 PR 2) — `stdioBindRoute()` is the one place that says how to bind an unbound stdio connection: `gbrain setup claude-code|codex --stdio-member <id>` for a harness one person uses (that harness entry, either engine), else a per-person `serve --http` key. The requester-scope refusal and notice, `gbrain access owner`'s Bind-one line and whoami's unbound note read it. Doctor `shared_stdio_binding` fails when `mcp.stdio_member` is set and `sharedStdioHarness()` (`setup-serves.ts`; a `hermes` on PATH counts only as a script, not React Native's compiled engine) finds OpenClaw or Hermes on a brain that serves several people (not applicable on a one-person brain); fix `gbrain config unset mcp.stdio_member`. `requesterScopeRefuses()` lets dispatch drop hot memory from the ops the gate does not cover for a connection it would refuse. Tests: `test/shared-stdio-binding.test.ts`.
- `src/core/ops/qm-memory.ts` (GST-359 D) — QM's memory provider pair. `memory_recall` reads the attested person's own last-24-hour facts on their member page (`listFactsSince` with `sourceMarkdownSlug`), then `rankFactsByQuestion` over the facts they may read, renders one plain line per fact (`plainFactText` strips fence and heading markers) and cuts at a line within `max_chars` (`boundFactLines`). A call that names `source_id` or `source_ids` (full surface only) reads as that scope instead: `recallSources` resolves them through `requestSourceScope` (a source outside the credential's grant is `permission_denied`), `SCOPE_READ_ACCESS` empties identity, actor and audience, so no own facts and no member-page fact are read, restricted pages stay hidden and privacy is never relaxed; the query is ranked on its first 2,000 characters (`MEMORY_RECALL_QUERY_CHARS`). `memory_write` validates 1-20 facts, derives each request id from uuidv5(member, idempotency_key) (`memoryWriteRequestId`) and saves through `remember`'s handler with `ctx.attestedOp = 'memory_write'`, which the stored write authority keeps (`WriteAuthority.attestedOp`) so publication and receipt reads re-check that operation's attest right. `qmMemoryToolResult` (dispatch) moves the result into `structuredContent` and leaves the model text in `content`; GST-1158 F2 does the same for an attested call to a contract v3 personal tool (`QM_PERSONAL_OPS`), keeping its JSON in `content` (a list as `structuredContent.results`; context_pack's text alone, like memory_recall), and dispatch measures that frame against the result cap again; each memory_recall fact carries `arm` (`own` or `ranked`, F5) and `own_page` (GST-2407: `member-facts.ts` `ownMemberFactIds`, the one set forget_fact's ownership gate also reads); `unlinkedRecallResult` is the empty success dispatch's `actorRefusal` returns for an unlinked person. Contract fixture: `scripts/build-qm-memory-contract.ts` writes `docs/contracts/qm-memory-provider/v1.json` (frozen, byte-identical) and `v2.json` (the scope read and write; `regen:all` artifacts; `v3.json` adds the personal tools with frozen result shapes; `v4.json` adds memory_propose, each personal tool's `scope_read` marking and `own_page`). Scope writes (GST-1113): `memory_write {source_id}` saves on `memory/scope` in a scope source listed in the credential's `attest_sources` (migration v293, on `access_tokens` and `oauth_clients`); `access/attest-sources.ts` holds `perCallWriteSource` (the one exemption from the one-write-source checks in `page-mutations.ts`, `memory-mutations.ts` and `persistence/authority.ts`, keyed to that slug and re-checked at publication through `actorCoverage(..., source)`), the sticky mark `sources.config.qm_scope` (set by `applyAttestSources` under row locks; `isSourceFederated` ignores federation on it), `assertScopeSourceGrant` (in `insertClientGrant`, `persistGrant`, `writeTokenGrant` and `insertUnifiedToken`) and `withoutScopeSources` (a person recall never reads a scope source). `member-facts.ts` `assertScopePageWriter` keeps other remote writers off `memory/scope`. Tests: `test/qm-scope-writes.test.ts` (both engines), `test/qm-memory-tools.test.ts` (both engines), `test/qm-personal-tools.test.ts` (v3 tools over dispatch, both engines), `test/qm-memory-contract.test.ts` (drift), `test/e2e/serve-http-qm-memory.test.ts` (keyless `serve --http`).
- `src/cli/enforced-member.ts` + `src/cli/enforced-member-classes.ts` + `src/cli/enforced-commit-push.ts`: enforced member mode ([guide](../../guides/enforced-member.md)). With `GBRAIN_ENFORCED_MEMBER` set, `enforcedGate` in `src/cli/main.ts` classifies the command before any dispatch (`enforcedClassOf`: read, write, allowed, silent or refused; anything unclassified is refused, exit 3, `enforced_member_refused`). An empty value, an unknown member or the owner id refuses everything. The gate classifies before help: a refused command refuses with `--help` too, and an allowed one prints only its static help. `checkEnforcedOpArgs` refuses a named source (`--source`, `--source-id`, `--source-ids`) the member cannot read or that is not registered, alike. Reads go through `dispatchToolCall` (with only the operation's declared params; the source travels as the call's `sourceId`) with `remote: true`, `transport: 'stdio'`, `stdioMember` and `enforcedMember: true` (dispatch forces `hidePrivate`, `owner: false` and no private-readable sources), minus other members' personal sources (`hiddenPersonalSources`; an explicit `--source` naming one refuses), and `namesHiddenPage` withholds any output that still names a hidden page. Writes stay trusted local writes (`ctx.remote` false): `checkEnforcedWrite` refuses a target the member cannot read (`memberPageView`) and any label change, and `remember` needs `--entity` naming a readable page (`checkEnforcedRemember`, the one decision point). `write-request` answers only ids in the member's receipt ledger (`recordEnforcedReceipts`, `configDir()/enforced-member/<member>.receipts`); any other id is swapped for a fresh one, so it answers as unknown. sync, `sources refresh` and `git commit-push` (checked by `checkEnforcedCommitPush`: every named path readable, no label or `.gbrain/` change, refused modes) run with output replaced by one line (`withWithheldOutput`, which also captures the fd-1 chain through `setStdoutCapture`); `doctor` prints only check names, statuses and counts (`withDoctorCounts`); sync and `sources refresh` take only their listed flags and a readable source (`syncSourceArg`); `entity` and every coverage notice drop the mention coverage count (`withoutCoverageCounts`); `timeline-add` refuses a gbrain fence marker; `hook` succeeds silently. The warm CLI socket, the persistence delegate and the skill-resolver fast path are skipped under the mode. Tests: `test/enforced-member.serial.test.ts` (CLI subprocesses, both engines, repo-less and git), `test/enforced-member-classes.test.ts` (every command and operation classified once).
diff --git a/docs/guides/setup.md b/docs/guides/setup.md
index d07f264026..78cae21d90 100644
--- a/docs/guides/setup.md
+++ b/docs/guides/setup.md
@@ -227,7 +227,8 @@ keys). A brain pinned `access.serves one` never refuses, however many members
it has.
Nothing binds stdio on its own: upgrade, post-upgrade and doctor never write
`mcp.stdio_member`, and `gbrain doctor` fails `shared_stdio_binding` when it is
-set on a host where OpenClaw or Hermes is installed (its fix is
+set on a host where OpenClaw or Hermes is installed and the brain serves several
+people (its fix is
`gbrain config unset mcp.stdio_member`). A team that shares everything may
mark one credential `gbrain auth rescope --token <name> --reads-unscoped --yes`
(`--reads-unscoped none` takes it back); every change is recorded in the
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 7020648107..9cf06b06fb 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -1082,7 +1082,7 @@ reads `state: "not_enforced"` and nothing is refused.
| Code | What happened | What to do |
|---|---|---|
-| <a id="requester_scope_required"></a>`requester_scope_required` | A remote read came from a connection bound to nobody. `reason` says which: `grace_ended` (the connection is older than the brain's several-people date and its 14 days ran out), `created_after` (it was created after that date, so it had to be scoped at creation) or `since_unknown` (the date could not be read; fail closed). The message names the connection and the operation. Nothing was read; the code is also in `structuredContent.error.code` and the audit trail (`access-audience`). Read-only identity and health calls (`whoami`, `get_brain_identity`, `get_status_snapshot`, `search_modes`, `get_health`, and a non-admin credential's own `get_job` / `wait_job`) still answer. | The brain operator runs `fix` on the brain host: `gbrain auth rescope --token <name> --member <id>` (or `--client <id>`; preview with `gbrain access check --token <name>`), or for a stdio server, when only one person uses that harness, `gbrain setup claude-code|codex --stdio-member <id>`, which binds that one harness entry on that machine, on PGLite or Postgres (setup refuses it where OpenClaw or Hermes is installed); for a harness several people talk to, give each person a key over HTTP instead (`gbrain serve --http` with `gbrain auth create <name> --member <id>` keys). `gbrain doctor` fails `shared_stdio_binding` when `mcp.stdio_member` is set on a host where OpenClaw or Hermes is installed. A shared agent instead lists whom it may act for (`--may-act-for`) and names the person on each call. Last resort, for a team that shares everything: `gbrain auth rescope --token <name> --reads-unscoped --yes` lets that one credential read every page no rule restricts for whoever is asking (`--reads-unscoped none` takes it back). |
+| <a id="requester_scope_required"></a>`requester_scope_required` | A remote read came from a connection bound to nobody. `reason` says which: `grace_ended` (the connection is older than the brain's several-people date and its 14 days ran out), `created_after` (it was created after that date, so it had to be scoped at creation) or `since_unknown` (the date could not be read; fail closed). The message names the connection and the operation. Nothing was read; the code is also in `structuredContent.error.code` and the audit trail (`access-audience`). Read-only identity and health calls (`whoami`, `get_brain_identity`, `get_status_snapshot`, `search_modes`, `get_health`, and a non-admin credential's own `get_job` / `wait_job`) still answer. | The brain operator runs `fix` on the brain host: `gbrain auth rescope --token <name> --member <id>` (or `--client <id>`; preview with `gbrain access check --token <name>`), or for a stdio server, when only one person uses that harness, `gbrain setup claude-code|codex --stdio-member <id>`, which binds that one harness entry on that machine, on PGLite or Postgres (setup refuses it where OpenClaw or Hermes is installed); for a harness several people talk to, give each person a key over HTTP instead (`gbrain serve --http` with `gbrain auth create <name> --member <id>` keys). `gbrain doctor` fails `shared_stdio_binding` when `mcp.stdio_member` is set on a host where OpenClaw or Hermes is installed and the brain serves several people. A shared agent instead lists whom it may act for (`--may-act-for`) and names the person on each call. Last resort, for a team that shares everything: `gbrain auth rescope --token <name> --reads-unscoped --yes` lets that one credential read every page no rule restricts for whoever is asking (`--reads-unscoped none` takes it back). |
| <a id="requester_scope_unknown"></a>`requester_scope_unknown` | A remote read came from a connection bound to nobody, and gbrain could not tell whether the brain serves one person or several: its config read failed (a statement timeout, a lock wait or a dropped pooled connection) and so did one re-read of the serves keys. Nothing was read. The message does not claim the brain serves several people, because that is what could not be read. A connection bound to a member is never refused this way. | Retry the same call after `retry_after_ms` (`fix.next` is `wait`). If it keeps failing, the brain host's operator checks the database with `gbrain doctor --json`. |
| <a id="credential_scope_required"></a>`credential_scope_required` | `gbrain auth create` or `gbrain auth register-client` was asked for a credential bound to no member on a brain that serves several people. Nothing was created. | Pass `--member <id>` (`gbrain access member list`), or `--may-act-for <members>` for a shared agent. `--reads-unscoped --yes` creates one that reads unscoped on purpose. |
diff --git a/src/commands/doctor/checks/shared-stdio-binding.ts b/src/commands/doctor/checks/shared-stdio-binding.ts
index 0b7b7a6803..321862fe2b 100644
--- a/src/commands/doctor/checks/shared-stdio-binding.ts
+++ b/src/commands/doctor/checks/shared-stdio-binding.ts
@@ -2,13 +2,15 @@
* GST-363 (PR 2): shared_stdio_binding. config mcp.stdio_member binds every stdio session on this host to one member,
* so a harness several people talk to (OpenClaw or Hermes, found by sharedStdioHarness) then reads as that member,
* private pages included, for whoever is asking it. Fails when the key is set and such a harness is installed, with the
- * unset command as the fix; ok when the key is set and no shared harness is installed; not applicable while it is unset.
+ * unset command as the fix; ok when the key is set and no shared harness is installed; not applicable while it is unset
+ * or the brain serves one person (every caller is then that person, so the binding takes nothing from anyone).
*/
import type { Check } from '../../doctor.ts';
import { agentFix, checkError, infoCheck } from '../check-fix.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
import { stdioMemberId } from '../../../core/access/caller.ts';
import { sharedStdioHarness } from '../../setup-serves.ts';
+import { brainServes } from '../../../core/access/serves.ts';
const NAME = 'shared_stdio_binding';
@@ -20,6 +22,10 @@ async function runSharedStdioBinding(ctx: DoctorContext): Promise<Check[]> {
checks.push(infoCheck(NAME, 'Not applicable: config mcp.stdio_member is unset, so no stdio session on this host reads as a member.', 'not_applicable'));
return checks;
}
+ if ((await brainServes(connectedEngine(ctx))).serves === 'one') {
+ checks.push(infoCheck(NAME, `Not applicable: this brain serves one person, so stdio sessions reading as ${member} (config mcp.stdio_member) read nothing kept from anyone else.`, 'not_applicable'));
+ return checks;
+ }
const harness = sharedStdioHarness();
if (!harness) {
checks.push({ name: 'shared_stdio_binding', status: 'ok', details: { stdio_member: member, shared_harness: null },
diff --git a/src/core/access/requester-scope.ts b/src/core/access/requester-scope.ts
index 7a234a0a93..7eeeaa1b59 100644
--- a/src/core/access/requester-scope.ts
+++ b/src/core/access/requester-scope.ts
@@ -129,6 +129,17 @@ export function requesterScopeGate(op: Pick<Operation, 'name' | 'mutating'> | un
throw requesterScopeRequired(op!.name, c, serves, transport, old ? 'grace_ended' : since === null ? 'since_unknown' : 'created_after');
}
+/** Whether requesterScopeGate would refuse a read from this connection, for the ops it does not gate. */
+export function requesterScopeRefuses(access: Partial<CallerAccess>, auth: ScopeAuth | undefined, via: string | undefined): boolean {
+ try {
+ requesterScopeGate({ name: 'search', mutating: false }, access, auth, via);
+ return false;
+ } catch (e) {
+ if (/^requester_scope_(required|unknown)$/.test(String((e as { code?: unknown }).code))) return true;
+ throw e;
+ }
+}
+
function boundToSomeone(access: Partial<CallerAccess>): boolean {
return !!access.audience?.length || !!access.actor || (access.identity ?? []).some(p => p.startsWith('member:'));
}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 2618a11403..f67af8bb09 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -76,7 +76,7 @@ export const CODES = {
access_policy_widening_held: { class: 'consent', actor: 'user', summary: "A change to a source's folder rules widens who may read (a rule removed, readers added, the old folder of a moved prefix), so it is recorded but held: the previous rules stay in force until an operator previews it with gbrain access apply --source <id> and approves the printed plan with --yes --expect <plan_hash> on the brain host.", why: 'Write access to the policy (a git commit or a rule edit) must not be enough to open a folder; widening needs a host-side preview and an explicit approval.', suggestion: 'Ask the user whether to approve the widening; the brain host previews it with gbrain access apply --source <id>.', fix: { argv: ['gbrain', 'access', 'apply', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews the held widening (pages and members gaining access) and prints the plan hash an approval binds; changes nothing.' } },
access_policy_store_mismatch: { class: 'host_only', actor: 'user', summary: "A source's persisted folder-rule store (sources.config.access_store) disagrees with what this host sees (a git store with no visible work tree, or a database store whose root became a repository), so the persisted store and its applied rules stay in force and nothing switches on its own.", why: 'Inferring the store per host would let a missing checkout or a stray git init change which rules apply; only gbrain access rule migrate moves them, and neither direction widens.', suggestion: 'On the brain host, preview the move with gbrain access rule migrate --source <id>, then apply it by adding --yes.', fix: { argv: ['gbrain', 'access', 'rule', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the persisted store and the applied rules; changes nothing.' } },
access_rule_invalid: { class: 'caller', docs: 'docs/guides/write-refusals.md#access_rule_invalid', summary: 'A folder rule given to gbrain access rule add is invalid (its prefix is not a literal lower-case folder ending in /, holds .. or *, its readers are not member ids or group:<id>, or another rule already covers the prefix), so nothing was written.', why: 'Prefixes are matched literally against slugs; a pattern or a typo would silently restrict the wrong pages or none.', suggestion: 'Write the prefix as a slug folder ending in / (partners/alice-example/) and the readers as member ids or group:<id>.' },
- requester_scope_required: { class: 'host_only', actor: 'user', reasons: ['grace_ended', 'created_after', 'since_unknown'], docs: 'docs/guides/write-refusals.md#requester_scope_required', summary: 'A remote read came from a connection bound to no member (an access token, an OAuth client or a local stdio server) on a brain that serves several people (two or more enabled members, or config access.serves = several), so it was refused before any work and nothing was read.', why: 'On a brain that serves several people a connection bound to nobody reads every page no rule restricts, for whoever is asking; gbrain refuses rather than guess whose notes a read is for. A connection that existed when the brain started serving several people gets 14 days of in-band notices first (reason grace_ended); one created after that is refused at once (created_after).', suggestion: 'On the brain host, bind the connection to the person it serves: gbrain auth rescope --token <name>|--client <id> --member <id> (preview with gbrain access check --token <name>), or for a stdio server, when only one person uses that harness, gbrain setup claude-code|codex --stdio-member <id>, which binds that one harness entry on that machine (refused where OpenClaw or Hermes is installed); for a harness several people talk to, give each person a key over HTTP instead (gbrain serve --http with gbrain auth create <name> --member <id> keys). A shared agent lists whom it may act for (--may-act-for) and names the person on each call. Last resort: --reads-unscoped --yes lets that one credential read every page no rule restricts for any asker.' },
+ requester_scope_required: { class: 'host_only', actor: 'user', reasons: ['grace_ended', 'created_after', 'since_unknown'], docs: 'docs/guides/write-refusals.md#requester_scope_required', summary: 'A remote read came from a connection bound to no member (an access token, an OAuth client or a local stdio server) on a brain that serves several people (two or more enabled members, or config access.serves = several), so it was refused before any work and nothing was read.', why: 'On a brain that serves several people a connection bound to nobody reads every page no rule restricts, for whoever is asking; gbrain refuses rather than guess whose notes a read is for. A connection that existed when the brain started serving several people gets 14 days of in-band notices first (reason grace_ended); one created after that is refused at once (created_after).', suggestion: 'On the brain host, bind the connection to the person it serves: gbrain auth rescope --token <name>|--client <id> --member <id> (preview with gbrain access check --token <name>), or for a stdio server, when only one person uses that harness, gbrain setup claude-code --stdio-member <id> (gbrain setup codex --stdio-member <id> on Codex), which binds that one harness entry on that machine (refused where OpenClaw or Hermes is installed); for a harness several people talk to, give each person a key over HTTP instead (gbrain serve --http with gbrain auth create <name> --member <id> keys). A shared agent lists whom it may act for (--may-act-for) and names the person on each call. Last resort: --reads-unscoped --yes lets that one credential read every page no rule restricts for any asker.' },
requester_scope_unknown: { class: 'retryable', retryable: true, actor: 'provider', docs: 'docs/guides/write-refusals.md#requester_scope_unknown', summary: 'A remote read came from a connection bound to no member, and whether the brain serves one person or several could not be read (the config read failed, and so did one re-read), so it was refused before any work and nothing was read.', why: 'A statement timeout, a lock wait or a dropped pooled connection can fail one config read while the next read succeeds. Reading that as a one-person brain would let a connection bound to nobody read every page no rule restricts on a brain that may serve several people, so gbrain refuses until it can tell.', suggestion: 'Retry the same call in a few seconds. If it keeps failing, the brain host\'s operator checks the database with gbrain doctor --json. A connection bound to a member is never refused this way.' },
credential_scope_required: { class: 'caller', docs: 'docs/guides/write-refusals.md#credential_scope_required', summary: 'gbrain auth create or gbrain auth register-client was asked for a credential bound to no member on a brain that serves several people, so nothing was created.', why: 'A credential bound to nobody on such a brain is refused on every read (requester_scope_required); creating one would hand out a key that cannot work, or one that reads everyone\'s unmarked notes.', suggestion: 'Bind it to the person it serves: gbrain auth create <name> --member <id> (gbrain access member list names the members). A shared agent passes --may-act-for <members> instead; --reads-unscoped --yes creates one that reads every page no rule restricts for any asker, on purpose.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists the members a credential can be bound to.' } },
access_serves_roster_empty: { class: 'caller', summary: 'gbrain setup --serves several or gbrain access serves several was given no people (no --members, an empty --members-file), so nothing was written.', why: 'Each person gets a member, a folder only they read and a key bound to them; the installer never guesses who they are.', suggestion: 'Name every person: --members alice-example,bob-example, or --members-file <file> with one id per line.' },
diff --git a/src/core/schema-migrations/v308-requester-scope.ts b/src/core/schema-migrations/v308-requester-scope.ts
index b03cc47da6..490b200b36 100644
--- a/src/core/schema-migrations/v308-requester-scope.ts
+++ b/src/core/schema-migrations/v308-requester-scope.ts
@@ -35,7 +35,7 @@ BEGIN
FROM access_members WHERE disabled_at IS NULL AND tombstoned_at IS NULL;
INSERT INTO config (key, value) VALUES ('access.serves_derived', derived)
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value WHERE config.value IS DISTINCT FROM EXCLUDED.value;
- SELECT btrim(value) INTO explicit FROM config WHERE key = 'access.serves';
+ SELECT lower(btrim(value)) INTO explicit FROM config WHERE key = 'access.serves';
IF (CASE WHEN explicit IN ('one', 'several') THEN explicit ELSE derived END) = 'several' THEN
INSERT INTO config (key, value) VALUES ('access.serves_since', to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"'))
ON CONFLICT (key) DO NOTHING;
diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.ts
index 229c7f1a8b..50aadb37f8 100644
--- a/src/core/search/private-visibility.ts
+++ b/src/core/search/private-visibility.ts
@@ -1019,7 +1019,7 @@ export interface RemotePolicy { privacyRelaxed: boolean; restricted: boolean; ow
/** GST-363: an explicit access.serves wins over the trigger-kept member count; enforcement is on unless set to false. */
export function servesPolicyFrom(config: Record<string, string | undefined>): ServesPolicy {
- const explicit = config[SERVES_KEY]?.trim();
+ const explicit = config[SERVES_KEY]?.trim().toLowerCase();
const fromConfig = explicit === 'one' || explicit === 'several';
const since = Date.parse(config[SERVES_SINCE_KEY]?.trim() ?? '');
return {
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index ea50192985..f29cccec3b 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -16,7 +16,7 @@ import { loadConfig } from '../core/config.ts';
import { withRequestConfigSnapshot, withoutRequestConfigSnapshot } from '../core/config-snapshot.ts';
import { withCallerAccess } from '../core/search/private-visibility.ts';
import { appliedAccessSummary, folderAccessFor, remoteCallerAccess } from '../core/access/caller.ts';
-import { credentialScopeFor, requesterScopeGate, requiresRequesterScope, withServesReread, type RequesterScopeNotice } from '../core/access/requester-scope.ts';
+import { credentialScopeFor, requesterScopeGate, requesterScopeRefuses, requiresRequesterScope, withServesReread, type RequesterScopeNotice } from '../core/access/requester-scope.ts';
import { audienceInArguments, audienceInArgumentsError, logAudienceAssertion, parseAudience, type AudienceAuditEvent, type AudienceChannels, type AudiencePrincipal } from '../core/access/audience.ts';
import { ACTOR_ARGUMENT, actorNotAttested, EXTERNAL_ID_RE, resolveAttestedActor, type ActorChannels } from '../core/access/actor.ts';
import { attestedReadMode, SCOPE_READ_ACCESS, withReadMode, type ReadMode } from '../core/access/scope-read.ts';
@@ -1041,6 +1041,10 @@ export async function dispatchToolCall(
const credential = opts.auth ? await credentialScopeFor(engine, opts.auth) : undefined;
access = await withServesReread(engine, access, credential);
scopeNotice = requesterScopeGate(op, access, credential, opts.transport);
+ } else if (!attested?.actor && reachable && scoped.metaHook) {
+ // GST-363: the ops the gate lets through (exempt reads, writes) carry no hot memory to a connection whose reads it refuses.
+ const credential = opts.auth ? await credentialScopeFor(engine, opts.auth) : undefined;
+ if (requesterScopeRefuses(await withServesReread(engine, access, credential), credential, opts.transport)) scoped = { ...scoped, metaHook: undefined };
}
} catch (e) {
// GST-359: a call that names a person gets every failure here (a lock timeout reading its link included) in the
diff --git a/test/requester-scope.test.ts b/test/requester-scope.test.ts
index 7f77d099a8..d1ea5b61c6 100644
--- a/test/requester-scope.test.ts
+++ b/test/requester-scope.test.ts
@@ -44,6 +44,7 @@ import { takeBindingFlags } from '../src/commands/auth-binding.ts';
import { ownerLines } from '../src/commands/access.ts';
import { buildBrainTools } from '../src/core/minions/tools/brain-allowlist.ts';
import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { getBrainHotMemoryMeta } from '../src/core/facts/meta-hook.ts';
import { testBackends } from './helpers/test-backends.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { runCli } from './helpers/cli-spawn.ts';
@@ -166,9 +167,11 @@ for (const kind of testBackends()) {
await enableMember(engine, 'bob-example');
expect(await engine.getConfig('access.serves_derived')).toBe('several');
expect(await engine.getConfig('access.serves_since')).toBe(since);
- await engine.setConfig('access.serves', 'one');
- expect((await brainServes(engine)).serves).toBe('one');
- expect((await search('old-unbound')).meta?.access?.requester_scope).toBeUndefined();
+ for (const pinned of ['one', ' One ']) {
+ await engine.setConfig('access.serves', pinned);
+ expect({ pinned, serves: (await brainServes(engine)).serves }).toEqual({ pinned, serves: 'one' });
+ expect((await search('old-unbound')).meta?.access?.requester_scope).toBeUndefined();
+ }
await engine.unsetConfig('access.serves');
}, 60_000);
@@ -251,6 +254,26 @@ for (const kind of testBackends()) {
expect(JSON.stringify(audit)).not.toContain(keys['old-unbound']!.token);
}, 60_000);
+ test('a refused unbound connection gets no hot memory on the ops the gate lets through (exempt reads, writes); a bound one still does', async () => {
+ await setSince(15);
+ const fact = await dispatchToolCall(engine, 'remember', { fact: 'Harbor ledger notes canaryhotfact', provenance: 'fixture' }, { remote: false, sourceId: 'default' });
+ expect(fact.isError).toBeFalsy();
+ const hot = async (tool: string, args: Record<string, unknown>, stdioMember?: string) => {
+ const out = await dispatchToolCall(engine, tool, args, { remote: true, transport: 'stdio', sourceId: 'default', takesHoldersAllowList: ['world'],
+ metaHook: getBrainHotMemoryMeta, sessionId: `hot-${tool}-${stdioMember ?? 'unbound'}`, ...(stdioMember ? { stdioMember } : {}) });
+ return { isError: out.isError === true, all: JSON.stringify(out) };
+ };
+ expect((await stdio('search', { query: 'harbor ledger notes', match: 'keyword', limit: 10 })).json).toMatchObject({ code: 'requester_scope_required', reason: 'grace_ended' });
+ for (const tool of ['whoami', 'get_brain_identity', 'search_modes']) {
+ const out = await hot(tool, {});
+ expect({ tool, isError: out.isError, leaked: out.all.includes('canaryhotfact') }).toEqual({ tool, isError: false, leaked: false });
+ }
+ const write = await hot('remember', { fact: 'Harbor ledger notes canaryhotwrite', provenance: 'fixture' });
+ expect(write.all.includes('canaryhotfact')).toBe(false);
+ const bound = await hot('whoami', {}, 'alice-example');
+ expect({ isError: bound.isError, sees: bound.all.includes('canaryhotfact') }).toEqual({ isError: false, sees: true });
+ }, 60_000);
+
test('over HTTP, a member-bound key is unaffected', async () => {
const out = await search('alice-key');
expect(out.isError).toBe(false);
diff --git a/test/shared-stdio-binding.test.ts b/test/shared-stdio-binding.test.ts
index f2754df774..9ca1f94879 100644
--- a/test/shared-stdio-binding.test.ts
+++ b/test/shared-stdio-binding.test.ts
@@ -2,7 +2,8 @@
* GST-363 (PR 2): doctor shared_stdio_binding. config mcp.stdio_member binds every stdio session on the host to one
* member, so on a host where a harness several people talk to (OpenClaw, Hermes; sharedStdioHarness) is installed,
* that harness reads as that member, private pages included. The check fails there with the unset command as its
- * fix, passes when no shared harness is installed, and is not applicable while the key is unset. Repo-less PGLite.
+ * fix, passes when no shared harness is installed, and is not applicable while the key is unset or the brain serves one
+ * person (R94: the owner's own harness keeps its binding). Repo-less PGLite.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
@@ -22,6 +23,7 @@ describe('doctor shared_stdio_binding (pglite, repo-less)', () => {
beforeAll(async () => {
home = mkdtempSync(join(tmpdir(), 'gbrain-shared-stdio-'));
engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema();
+ await engine.setConfig('access.serves', 'several');
}, 120_000);
afterAll(async () => { await engine?.disconnect(); rmSync(home, { recursive: true, force: true }); }, 60_000);
@@ -30,6 +32,19 @@ describe('doctor shared_stdio_binding (pglite, repo-less)', () => {
expect(await doctor({ HERMES_HOME: hermes })).toMatchObject({ name: 'shared_stdio_binding', status: 'ok', readiness_state: 'not_applicable' });
});
+ test('R94: on a brain that serves one person (pinned, in any case), set with OpenClaw installed is not applicable and offers no unset', async () => {
+ await engine.setConfig('mcp.stdio_member', 'alice-example');
+ const openclaw = join(home, 'openclaw-one'); mkdirSync(openclaw);
+ for (const pinned of ['one', 'One']) {
+ await engine.setConfig('access.serves', pinned);
+ const c = await doctor({ OPENCLAW_STATE_DIR: openclaw });
+ expect({ pinned, check: c }).toMatchObject({ pinned, check: { name: 'shared_stdio_binding', status: 'ok', readiness_state: 'not_applicable' } });
+ expect(c.fix).toBeUndefined();
+ }
+ await engine.setConfig('access.serves', 'several');
+ await engine.unsetConfig('mcp.stdio_member');
+ });
+
test('set with no shared harness on the host: ok', async () => {
await engine.setConfig('mcp.stdio_member', 'alice-example');
const c = await doctor();