Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Shared-credential warning: silent on a brain that serves one person, and its fix binds the credential first

garrytan445360ffc310
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a42160f1a3..3cf730652e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,7 +24,7 @@ identifiers and attribution are available in the pre-removal Git revision
**An install that hands one unscoped credential to an agent several people talk to now says so, loudly, and doctor reports it.** In the HARN-13 host-harness pilot, one bot token over a brain that held many channels' chat made agents answer people with other people's messages: telling the agent gbrain was live cost 9 to 21 points of pass rate, and every added cross-scope failure cited a channel page the bot grant returned. A credential reads the same pages whoever talks to its agent (an unbound one everything its grant reaches, one bound to a member what that member may read), so gbrain warns.
-The `unscoped_multi_user_token` safety notice fires from `gbrain setup openclaw|hermes|grok-bot|muse`, from `setup claude-code` when a chat-channel plugin is enabled, from `mcp grant` and `connect` for a bot harness or a grant that reads chat from 2+ channels, from `skillpack scaffold` into an OpenClaw or Hermes workspace, and from `auth create` and `auth register-client` when the new credential reads chat from 2+ channels. It names the fixes (a one-source grant, `sources unfederate`, `GBRAIN_SOURCE` plus `sources unfederate` for a stdio agent, `visibility: private`, a credential bound to each person with `gbrain auth create <name> --member <id>`, or one shared agent with `--may-act-for` and a per-request audience), says plainly when the chat sits in one source and no source grant can separate it, and says that `source_ids` narrows only the call that sends it. A credential holding `--may-act-for` is not flagged, and the notice says its harness must name an audience on every call, because a call that names none reads the credential's full grant. The new read-only doctor check `unscoped_multi_user_token` runs the same detection over every active token, OAuth client and wired local agent. No grant, default or scoping behaviour changes, and no exit code moves.
+The `unscoped_multi_user_token` safety notice fires from `gbrain setup openclaw|hermes|grok-bot|muse`, from `setup claude-code` when a chat-channel plugin is enabled, from `mcp grant` and `connect` for a bot harness or a grant that reads chat from 2+ channels, from `skillpack scaffold` into an OpenClaw or Hermes workspace, and from `auth create` and `auth register-client` when the new credential reads chat from 2+ channels. It fires only on a brain that serves several people (`gbrain access serves`); on a one-person brain the routes stay silent and the doctor check is not applicable. Its fix leads with binding the credential (`gbrain auth rescope --token <name> --member <id>`, or `--may-act-for <members>` for one agent several people share, or `gbrain setup <harness> --serves several` for a local agent), names a source rescope, `sources unfederate` or `GBRAIN_SOURCE` only as narrowings that leave the credential unbound, says plainly when the chat sits in one source and no source grant can separate it, and says that `source_ids` narrows only the call that sends it. A credential holding `--may-act-for` is not flagged, and the notice says its harness must name an audience on every call, because a call that names none reads the credential's full grant. The new read-only doctor check `unscoped_multi_user_token` runs the same detection over every active token, OAuth client and wired local agent. No grant, default or scoping behaviour changes, and no exit code moves.
### Itemized changes
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.md
index 8fe68d7e9a..5825b8c821 100644
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@ -9,7 +9,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/grants/` — canonical OAuth client grant model shared by CLI, admin HTTP, provisioning, and worker admission. `model.ts` validates active sources, independent direct/delegated fences, explicit reviewed tools, namespaces, concurrency, spend, and TTL; `host`/`current` brain aliases normalize to the serving brain (`null`), while other IDs need independently verified host identity. `profiles.ts` snapshots current eligible operation names for six explicit profiles; new defaults are renewable 1 hour (static 30 days), concurrency 1, unlimited delegated spend, and an operator-set `full` surface for every profile except `delegating-agent` (`starter`); only an explicit profile application changes an existing client's surface. `catalogProvenance()` is the operation catalog a snapshot is written against: `service.ts` adds it as `catalogProvenance` to the audit document of every write that sets a new snapshot (registration included), and `readClientCatalogProvenance` returns it only while that audit row's snapshot is still the client's snapshot (null for grants written without it; never synthesized). `allowed_operations = NULL` preserves legacy scope-based behavior; a new profile missing its snapshot fails closed. `service.ts` locks the client, checks `grant_revision`, and commits the grant, secret-free audit, and original ceilings for pending/active legacy jobs atomically; stale edits fail, repeated repair is a no-op, and repair preserves populated limits. Issued scopes intersect live scopes on access and refresh; source/path/operation/delegation changes are live, newly added scopes require new issuance, and TTL changes do not rewrite existing expiry. `migration.ts` splits legacy fences and removes only invalid `agent` grants with repair reasons; it loads registry validation lazily only after locking existing delegated clients, so empty engine imports and cold migrations do not register unrelated background sinks. This justified engine-live import is line-marked; constraints still install when no clients exist. F3 one grant shape: `model.ts` also holds `PrincipalGrant` (`GrantSources` = `default` | `scalar` | `federated` | `none`), `grantFromTokenRow` (unified rows read the `access_tokens` grant columns and any axis whose `permissions` mirror disagrees evaluates deny-all and is listed in `drift`; an unconverted `source_grant IS NULL` row reads as the conversion `migrateLegacyTokens` would write, and a malformed `permissions` value denies every axis), `GRANT_MIRROR_WINDOW_ENDS` (the date until which the `permissions` mirror is written and drift is enforced; doctor reports it), `authSourcesFromGrant` (the AuthInfo source fields every token reader uses: both HTTP transports, publication `authority.ts`, job admission, shared-skill membership and policy), `grantFromClient`, `validatePrincipalGrant` (tokens and clients may hold `none`); `ClientGrant.sourcesNone` (`oauth_clients.source_grant = 'none'`: NULL `source_id`, empty `federated_read`, verified as `NO_SOURCES`) and `ClientGrant.takesHolders` (`oauth_clients.takes_holders`, NULL = `['world']`; read by `verifyAccessToken` and `authorizeTakeHolder`), both added by migration v203 (fragment `oauth-client-axes-schema.ts`) and set through `auth rescope --client --sources none|--takes-holders` and `permissionsMirror`. `access-token-schema.ts` is the column fragment (migration `f3_access_token_grants`); v202 (`legacy_token_grant_conversion`) converts every legacy grant in bulk. Tests: `test/legacy-token-grant-conversion.test.ts`. `legacy-token.ts` is the token grant editor behind `gbrain auth rescope --token` (aliases `rescope-token`, `permissions set-takes-holders`): one `FOR UPDATE` transaction that writes the columns, bumps `grant_revision` (`--if-version` compare-and-set) and rewrites `permissions` as a mirror with every other key preserved; `none` = explicit empty list; refresh previews and widens only by named operations; a drifted token refuses edits until `--adopt-permissions` or `--adopt-columns`; `migrateLegacyTokens` (`--migrate-legacy` and schema migration v202) writes the columns for every unmigrated token without changing a grant and skips malformed JSONB; `resolveTokenGrant` is the HTTP auth read (both transports): a legacy-shape row converts on that read with one `source_grant IS NULL`-guarded UPDATE (concurrent first reads convert once; a failed write such as a read-only role authorizes with the identical in-memory conversion); `resolveRescopeTarget` refuses a bare name that matches a token and a client. `cli.ts` splits `auth rescope` targets and maps the unified client flags onto `auth rescope-client`'s patch. An explicit empty `permissions.source_id` decodes (`parseLegacyTokenScope` in `src/core/legacy-token-scope.ts`) to the `NO_SOURCES` sentinel, which `sourceScopeOpts`, the dispatch fence (`enforceBoundClientOpAllowList`, `fence=no_source_grant`), `submissionAuthority` and `POST /ingest` refuse and publication reauthorization rejects; it never regains the `default` floor. `schema.ts` supplies migration147/bootstrap columns and invariants for both engines. SQL JSON passes through `text::jsonb` for driver parity. Tests: `test/client-grants.test.ts`, OAuth compatibility suites, and `test/e2e/client-grants.test.ts` (Postgres CAS, job ceilings, and actual HTTP preview/edit). GBRA-156 private-pages axis: `PrivatePagesGrant` (`none` | `granted_sources`) lives in `access_tokens.private_pages` and `oauth_clients.private_pages` (migration v280, never in the legacy permissions mirror); `privatePagesSources` counts only explicitly named sources (scalar write source, federated write plus read sources; never the `default` floor), and `privatePagesAuth` builds `AuthInfo.privatePages` for HTTP and OAuth verification; MCP dispatch runs a remote read under `withPrivateReadableSources` (`src/core/search/private-visibility.ts`, an AsyncLocalStorage), whose `*ForCaller` predicate twins and `orPrivateReadableSource` OR those sources in at read sites only, never at stored-visibility decisions.
-- `src/core/grants/shared-exposure.ts` + `src/commands/shared-exposure-local.ts` + `src/commands/doctor/checks/unscoped-multi-user-token.ts` — GST-363 warning when one credential that reads the same pages whoever asks (unbound, or bound to one member) serves an agent several people use; a credential holding `may_act_for` is skipped (auth create, register-client and the doctor check). Signals: a bot harness (`BOT_HARNESSES`), a Claude Code chat-channel plugin (settings.json `enabledPlugins`; read with the bot-workspace test in `shared-exposure-local.ts`, so the core reads no file or environment), or chat pages from 2+ channels in the read set (`chatChannelCensus`: chat types incl. `pageTypesForAllowed` slack/iMessage aliases; channel = frontmatter channel/chat/conversation, else a `#name` title, else the source; each DM page alone; private pages hidden unless the remote-private hatch is on). `credentialReadSources` mirrors dispatch: an unscoped legacy token reads default plus federated sources, an unscoped OAuth client `default`, scalar and federated grants what they name; `stdioReadSources` resolves like the stdio server. `sharedTokenNotice` builds the `unscoped_multi_user_token` safety notice (fixes chosen by whether the chat spans 2+ sources, then the per-person setups: a credential bound to each member, or `--may-act-for` with a per-request audience); `writeExposureNotice` prints it on stderr. Routes: setup (bot harnesses, claude-code channel plugin), mcp grant, connect, skillpack scaffold, auth create, auth register-client; none changes a grant or an exit code. The doctor check warns on credentials or wired local agents with multi-channel chat in reach, reports a bot harness alone as info, and gives a remote caller a count only. Tests: `test/shared-exposure.test.ts`, `test/shared-exposure-routes.test.ts` (repo-less PGLite).
+- `src/core/grants/shared-exposure.ts` + `src/commands/shared-exposure-local.ts` + `src/commands/doctor/checks/unscoped-multi-user-token.ts` — GST-363 warning when one credential that reads the same pages whoever asks (unbound, or bound to one member) serves an agent several people use; a credential holding `may_act_for` is skipped (auth create, register-client and the doctor check). Signals: a bot harness (`BOT_HARNESSES`), a Claude Code chat-channel plugin (settings.json `enabledPlugins`; read with the bot-workspace test in `shared-exposure-local.ts`, so the core reads no file or environment), or chat pages from 2+ channels in the read set (`chatChannelCensus`: chat types incl. `pageTypesForAllowed` slack/iMessage aliases; channel = frontmatter channel/chat/conversation, else a `#name` title, else the source; each DM page alone; private pages hidden unless the remote-private hatch is on). `credentialReadSources` mirrors dispatch: an unscoped legacy token reads default plus federated sources, an unscoped OAuth client `default`, scalar and federated grants what they name; `stdioReadSources` resolves like the stdio server. `sharedTokenNotice` builds the `unscoped_multi_user_token` safety notice, silent when `exposureServes` / `brainServes` (`src/core/access/serves.ts`) says the brain serves one person (fixes lead with binding: `bindArgv`, `auth rescope --member` or `--may-act-for`, `setup <harness> --serves several`; a source rescope is named as a narrowing that leaves the credential unbound); `writeExposureNotice` prints it on stderr. Routes: setup (bot harnesses, claude-code channel plugin), mcp grant, connect, skillpack scaffold, auth create, auth register-client; none changes a grant or an exit code. The doctor check is not applicable on a one-person brain, warns on credentials or wired local agents with multi-channel chat in reach, reports a bot harness alone as info, and gives a remote caller a count only. Tests: `test/shared-exposure.test.ts`, `test/shared-exposure-routes.test.ts` (repo-less PGLite).
- `src/core/grants/lifecycle.ts` + `src/commands/serve-http-clients.ts` — owner-authenticated client inspection, setup, export and lifecycle endpoints. Token invalidation/revoke/delete lock the OAuth client row, require reviewed revisions and explicit application, and commit an audit record atomically. Deletion records a tombstone while preserving request history and spending reservations/settlement; missing clients become terminal delegated denials while transient lookup failures remain retryable.
- `src/commands/serve-http-api-keys.ts` — owner-dashboard legacy API keys (`/admin/api/api-keys`). Mint validates the request (`parseApiKeyMintRequest`: name 1-128 printable characters, registered scopes, active source ids, holder grammar) and goes through `mintLegacyToken`, so keys are born on the unified grant columns; omitted fields take the `gbrain auth create` defaults (scopes `read,write`, never `admin` unless listed; no source grant; holders `['world']`), reported in `defaults_applied` beside the effective grant. Refusals are `invalid_params` agent envelopes with `why` and a `fix`; nothing is minted. The token appears only in the mint response, never in logs or SSE. The list returns ids, scopes, sources and holders through `grantFromTokenRow`; revoke takes the row id (`revokeLegacyTokenById`) and refuses a name. Pinned by `test/serve-http-api-keys.test.ts`.
diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.md
index f9ff5d325e..5a9800e50a 100644
--- a/docs/mcp/ADMIN.md
+++ b/docs/mcp/ADMIN.md
@@ -437,11 +437,16 @@ rates by 9 to 21 points, and every added cross-scope failure cited a channel
page the bot grant returned.
gbrain warns with `unscoped_multi_user_token` (a safety notice) when an
-install route sets up such access:
+install route sets up such access on a brain that serves several people
+(`gbrain access serves`: config `access.serves`, else two or more enabled
+members). On a brain that serves one person every credential reads that
+person's own pages, so no route warns and the doctor check is not applicable.
+When whom the brain serves cannot be read (no local brain, a remote host), the
+warning stays on.
| Route | Warns when |
|---|---|
-| `gbrain setup openclaw`, `setup hermes`, `setup grok-bot`, `setup muse` | always (a bot harness) |
+| `gbrain setup openclaw`, `setup hermes`, `setup grok-bot`, `setup muse` | a bot harness |
| `gbrain setup claude-code` | a chat-channel plugin (telegram, discord, slack, imessage, whatsapp, signal) is enabled |
| `gbrain mcp grant`, `gbrain connect` | the harness is a bot harness, or the grant reads chat from 2+ channels |
| `gbrain skillpack scaffold` | the target is OpenClaw's or Hermes's own workspace |
@@ -464,22 +469,29 @@ warns when one of them reads chat from 2+ channels, and reports a wired bot
harness with no such chat as information. A remote `run_doctor` caller gets a
count, never credential names.
-Fix it with today's commands:
-
-- When the channels sit in different sources, grant one audience's source
- only: `gbrain auth rescope --token <name> --sources <source>` (or
- `--client <id>`), or for a new harness grant
- `gbrain mcp grant <name> --source <source> --federated-read <source>`. Keep
- a channel's source out of unscoped reads with `gbrain sources unfederate <id>`.
-- For a local stdio agent, set `GBRAIN_SOURCE=<source>` in its MCP server
- environment and run `gbrain sources unfederate <source>`: the pin covers
- reads that name no source, and a federated sibling source stays nameable.
+Fix it by binding first:
+
+- Bind the credential to the person who uses the agent:
+ `gbrain auth rescope --token <name> --member <id>` (or `--client <id>`). For
+ one agent several people share, bind it to their audience instead:
+ `gbrain auth rescope --token <name> --may-act-for <members>`, and have its
+ harness name each request's audience. For a local stdio agent, label each
+ person and bind its server with
+ `gbrain setup <harness> --serves several --members <id,...>`
+ (`--stdio-member <member>` when one person alone uses it).
+- Narrowing only, which leaves the credential unbound: when the channels sit
+ in different sources, grant one audience's source with
+ `gbrain auth rescope --token <name> --sources <source>` (or for a new harness
+ grant `gbrain mcp grant <name> --source <source> --federated-read <source>`),
+ or pin a stdio agent with `GBRAIN_SOURCE=<source>` and
+ `gbrain sources unfederate <source>`. Keep a channel's source out of unscoped
+ reads with `gbrain sources unfederate <id>`.
- When the chat sits in one source, a source grant cannot separate it: mark
the pages nobody else may see `visibility: private`. That hides them from
the agent only while its access may not read private pages.
- Don't rely on `source_ids`: it narrows only the call that sends it, so
recall, list_pages or any read without it reads the token's full grant.
- The fix is a narrower grant (`gbrain auth rescope …`) or per-person access.
+ The fix is per-person access.
- Per-person access: give each person's agent its own credential bound to
them (`gbrain access member add <id>`, then
`gbrain auth create <name> --member <id>`) and put `readable_by` on pages
diff --git a/src/commands/auth.ts b/src/commands/auth.ts
index b4c75a3907..4a5b130a86 100644
--- a/src/commands/auth.ts
+++ b/src/commands/auth.ts
@@ -35,7 +35,7 @@ import { parseClientRescopeArgs, parseRescopeGrantArgs, splitRescopeTarget, type
import { GRANT_PROFILES, GrantError, TOKEN_TTL_MAX_SECONDS, TOKEN_TTL_MIN_SECONDS, grantFromClient, privatePagesFromColumn, type ClientGrant, type PrivatePagesGrant } from '../core/grants/model.ts';
import { cliRenderContext, renderAction, type RenderedAction } from '../core/agent-output.ts';
import type { INSTALL_SURFACE_SET_BY } from '../mcp/surface.ts';
-import { credentialCensus, sharedTokenNotice, writeExposureNotice } from '../core/grants/shared-exposure.ts';
+import { credentialCensus, exposureServes, sharedTokenNotice, writeExposureNotice } from '../core/grants/shared-exposure.ts';
import { migrateLegacyTokens, parseRescopeTokenArgs, renderLegacyGrantAxis, rescopeLegacyToken, resolveRescopeTarget, type MigrateLegacyResult, type RescopeTokenResult } from '../core/grants/legacy-token.ts';
import { bindCredential, type BindingPatch, type BindingResult } from '../core/access/members.ts';
import { bindingLine, checkBindingTarget, takeBindingFlags } from './auth-binding.ts';
@@ -103,7 +103,7 @@ async function create(name: string, opts: { takesHolders?: string[]; scopes?: st
console.log(`Revoke with: gbrain auth revoke "${name}" (or gbrain auth revoke --id <id> from auth list)`);
console.log(`Change its grants: gbrain auth rescope --token "${name}" --takes-holders world,garry (or --sources, --operations)`);
const grant = { principal: { kind: 'legacy_token' as const, id }, scopes: opts.scopes ?? ['read', 'write', 'admin'], sources: { kind: 'default' as const } };
- if (!opts.binding?.mayActFor?.length) writeExposureNotice(sharedTokenNotice({ kind: 'legacy_token', name }, { census: await credentialCensus(engine, grant) }));
+ if (!opts.binding?.mayActFor?.length) writeExposureNotice(sharedTokenNotice({ kind: 'legacy_token', name }, { census: await credentialCensus(engine, grant), serves: await exposureServes(engine) }));
});
} catch (e: any) {
if (e instanceof OperationError) exitCliError(e, 'auth');
@@ -786,7 +786,7 @@ async function registerClient(name: string, args: string[]) {
}
if (bound) console.log(bindingLine(bound));
const grant = await readClientGrant(engine, registered.clientId).then(grantFromClient).catch(() => null);
- if (grant && !binding.patch?.mayActFor?.length) writeExposureNotice(sharedTokenNotice({ kind: 'oauth_client', id: registered.clientId, name }, { census: await credentialCensus(engine, grant) }));
+ if (grant && !binding.patch?.mayActFor?.length) writeExposureNotice(sharedTokenNotice({ kind: 'oauth_client', id: registered.clientId, name }, { census: await credentialCensus(engine, grant), serves: await exposureServes(engine) }));
});
} catch (e: any) {
if (e instanceof OperationError) exitCliError(e, 'auth');
diff --git a/src/commands/doctor/checks/unscoped-multi-user-token.ts b/src/commands/doctor/checks/unscoped-multi-user-token.ts
index 1bba59af2f..47b8e05a0c 100644
--- a/src/commands/doctor/checks/unscoped-multi-user-token.ts
+++ b/src/commands/doctor/checks/unscoped-multi-user-token.ts
@@ -15,6 +15,7 @@
* is skipped: the per-person fix names it, and its notice says a call that
* names no audience reads its full grant.
* A remote caller (run_doctor only) gets counts, never credential names.
+ * Not applicable on a brain that serves one person (access.serves).
*/
import { grantFromClient, grantFromRow, grantFromTokenRow, type PrincipalGrant } from '../../../core/grants/model.ts';
import { BOT_HARNESSES, NOTICE_CODE, chatChannelCensus, credentialReadSources, exposureFix, exposureReasons,
@@ -23,12 +24,18 @@ import { claudeCodeChannelPlugins } from '../../shared-exposure-local.ts';
import { readBrainFirstLedger } from '../../../core/setup/brain-first.ts';
import type { Check } from '../../doctor.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { infoCheck } from '../check-fix.ts';
+import { brainServes } from '../../../core/access/serves.ts';
interface Finding { subject: ExposureSubject; label: string; reasons: string[]; census: ChatCensus }
async function runUnscopedMultiUserToken(ctx: DoctorContext): Promise<Check[]> {
const checks: Check[] = [];
const engine = connectedEngine(ctx);
+ const serves = await brainServes(engine).catch(() => null);
+ if (serves?.serves === 'one') {
+ return [infoCheck(NOTICE_CODE, `Not applicable: this brain serves one person (${serves.from === 'config' ? 'config access.serves is one' : `${serves.enabled_members.length} enabled member(s)`}), so every credential reads that person's own pages.`, 'not_applicable')];
+ }
const memo = new Map<string, Promise<ChatCensus>>();
const census = (sources: string[]) => {
const key = [...sources].sort().join(',');
diff --git a/src/commands/mcp.ts b/src/commands/mcp.ts
index 464746eae6..748021e34f 100644
--- a/src/commands/mcp.ts
+++ b/src/commands/mcp.ts
@@ -11,7 +11,7 @@ import { validateHarnessArguments, MCP_GRANT_ARGUMENTS } from '../core/harness/a
import { createMcpAdminHttp, hasAdminCredential, McpAdminError, redactAdminValue } from './mcp-admin-http.ts';
import { runMcpAdmin } from './mcp-admin.ts';
import { grantFromClient } from '../core/grants/model.ts';
-import { credentialCensus, renderedExposure, sharedTokenNotice, writeExposureNotice } from '../core/grants/shared-exposure.ts';
+import { credentialCensus, exposureServes, renderedExposure, sharedTokenNotice, writeExposureNotice } from '../core/grants/shared-exposure.ts';
const HELP = `gbrain mcp — provision access on the host; install it inside the harness
@@ -148,6 +148,7 @@ export async function runMcp(args: string[], engine?: BrainEngine): Promise<void
const exposure = sharedTokenNotice({ kind: 'oauth_client', id: result.grant.clientId || input.name, name: input.name }, {
harness: harnessAdapter(input.harness).id,
census: engine && !hasAdminCredential(args) ? await credentialCensus(engine, grantFromClient(result.grant)) : null,
+ serves: engine && !hasAdminCredential(args) ? await exposureServes(engine) : null,
});
writeExposureNotice(exposure);
console.log(JSON.stringify({ status: result.dry_run ? 'preview' : 'granted', grant: result.grant, before: result.before,
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index 77f051de94..46c0a24665 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -32,7 +32,7 @@ import { inspectTurnHook, TURN_HOOK_NATIVE_INSPECT, turnHookFix, verifyTurnHook,
import { opError, OperationError } from '../core/ops/contract.ts';
import { cliRenderContext, renderCliError, renderNotice, type Action, type Notice } from '../core/agent-output.ts';
import { writeCliNotices } from '../core/interop-notices.ts';
-import { renderedExposure, sharedTokenNotice, writeExposureNotice } from '../core/grants/shared-exposure.ts';
+import { BOT_HARNESSES, renderedExposure, sharedTokenNotice, writeExposureNotice, type ExposureServes } from '../core/grants/shared-exposure.ts';
import { claudeCodeChannelPlugins } from './shared-exposure-local.ts';
import { setupFirstRunNotices } from './init-first-run.ts';
import { hostedOptionMuted, hostedOptionNotice, writeHostedOption } from '../core/onboard/hosted-option.ts';
@@ -580,7 +580,7 @@ export async function runSetup(args: string[]): Promise<number> {
const instructions = brainFirstFor('claude-code', flags, mcpAccess(flags.name, plan.advertise ?? surface, serves), { scope, projectDir });
const skills = skillsFor('claude-code', flags, launcher, { scope, projectDir }, instructions);
const resolver = await resolverFor('claude-code', flags, launcher);
- return finish(out, { dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes, instructions, skills, resolver, serves });
+ return finish(out, { dryRun: true, target, consent, steps, states: [], verify: null, notices: [], notes, instructions, skills, resolver, serves, launcher });
}
let notices: Notice[] = [];
@@ -605,7 +605,7 @@ export async function runSetup(args: string[]): Promise<number> {
const states = ['configured', ...(verify.ok ? ['connection-verified', 'native-pending'] : [])];
const turnHook = plan.events.includes('UserPromptSubmit') && instructions?.decision.value === 'accepted' ? verifyTurnHook('claude-code', { projectDir }) : null;
const code = await finish(out, { dryRun: false, target: { ...target, registration_owner: pluginOwner ? 'plugin' : 'setup' }, consent: result.receipt.consent, steps: result.steps, states, verify, notices, notes,
- preserved: Object.keys(result.edited).map((event) => ({ kind: 'hook', event, reason: 'edited' })), instructions, skills, turnHook, resolver, serves });
+ preserved: Object.keys(result.edited).map((event) => ({ kind: 'hook', event, reason: 'edited' })), instructions, skills, turnHook, resolver, serves, launcher });
if (turnHook && !turnHook.ok) return out.json ? 1 : refuse(turnHookNotLoaded('claude-code', turnHook, ['gbrain', 'setup', 'claude-code', ...(scope === 'project' ? ['--scope', 'project'] : [])]), out);
return verify.ok || pluginOwner ? code : 1;
} catch (e) {
@@ -961,6 +961,12 @@ function describeInstructions(o: BrainFirstOutcome, dryRun: boolean): string {
return `${describeBrainFirstOutcome(o, dryRun)} [${o.decision.source}; ${how}]`;
}
+/** Whom the brain behind this launcher serves, for the shared-token warning; null when it cannot be read (the warning stays on). */
+function exposureServesVia(launcher: string | null | undefined): ExposureServes {
+ const read = launcher && launcher.startsWith('/') ? readServesStatus(launcher) : null;
+ return read && 'status' in read ? read.status.serves : null;
+}
+
/** --serves several on the instructions alone: the brain must serve several people and its stdio server be bound. */
function servesBound(flags: SetupFlags): boolean {
const launcher = flags.gbrainBin ?? resolveGbrainBin();
@@ -983,7 +989,8 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>
const surface = flags.surface ?? (isRegistrationSurface(envSurface) ? envSurface : undefined);
const access: BrainFirstAccess = { kind: 'mcp', server: flags.name, ...(surface ? { surface } : {}), ...(flags.serves === 'several' && servesBound(flags) ? { serves: 'several' as const } : {}) };
const mcp = { setup: flags.instructionsOnly ? 'unchanged' as const : 'manual' as const, docs: adapter.guide };
- const exposure = flags.remove ? null : sharedTokenNotice({ kind: 'stdio', harness }, { harness });
+ const exposure = flags.remove || !BOT_HARNESSES.includes(harness) ? null
+ : sharedTokenNotice({ kind: 'stdio', harness }, { harness, serves: exposureServesVia(flags.gbrainBin ?? resolveGbrainBin()) });
const notices = renderedExposure(exposure);
if (!isBrainFirstHarness(harness)) {
const pasted: BrainFirstAccess = adapter.connection === 'thin-cli' ? { kind: 'cli', launcher: flags.gbrainBin ?? 'gbrain' } : access;
@@ -1104,11 +1111,13 @@ async function finish(out: Out, doc: {
turnHook?: TurnHookVerdict | null;
resolver?: ResolverSetupResult | null;
serves?: ServesOutcome | null;
+ launcher?: string;
}): Promise<number> {
const harness = doc.harness ?? 'claude-code';
const state = doc.states.at(-1) ?? null;
const code = skillsFailed(doc.skills ?? null) || doc.resolver?.error || !servesOk(doc.serves ?? null) ? 1 : 0;
- const exposure = harness === 'claude-code' && !doc.remove ? sharedTokenNotice({ kind: 'stdio', harness }, { channelPlugins: claudeCodeChannelPlugins() }) : null;
+ const plugins = harness === 'claude-code' && !doc.remove ? claudeCodeChannelPlugins() : [];
+ const exposure = plugins.length ? sharedTokenNotice({ kind: 'stdio', harness }, { channelPlugins: plugins, serves: exposureServesVia(doc.launcher) }) : null;
const notices = exposure ? [...doc.notices, exposure] : doc.notices;
if (out.json) {
await writeJsonDocument(`${JSON.stringify({
diff --git a/src/core/grants/shared-exposure.ts b/src/core/grants/shared-exposure.ts
index 8f19208256..6da4f79707 100644
--- a/src/core/grants/shared-exposure.ts
+++ b/src/core/grants/shared-exposure.ts
@@ -14,6 +14,11 @@
* - `multi_channel_chat`: the read set holds remote-visible chat pages from
* MULTI_CHANNEL_MIN or more distinct channels (every DM page counts alone).
*
+ * The warning applies only to a brain that serves several people
+ * (access.serves, src/core/access/serves.ts): on a one-person brain every
+ * credential reads that person's own pages, so nothing is flagged. When whom
+ * the brain serves cannot be read, the warning stays on.
+ *
* Every input is a database row or a harness config file (read by
* src/commands/shared-exposure-local.ts), never git, so a repo-less brain is
* covered the same way as a repo brain.
@@ -27,6 +32,7 @@ import { localFederatedSourceIds, resolveSourceWithTier } from '../source-resolv
import { privatePagesFilterFragmentFast, resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { pageTypesForAllowed } from '../facts/conversation-types.ts';
import type { PrincipalGrant } from './model.ts';
+import { brainServes } from '../access/serves.ts';
export const NOTICE_CODE = 'unscoped_multi_user_token';
export const BOT_HARNESSES: readonly string[] = ['openclaw', 'hermes', 'grok-bot', 'muse'];
@@ -38,6 +44,17 @@ export const MULTI_CHANNEL_MIN = 2;
const DOCS = 'docs/mcp/ADMIN.md#one-token-several-people';
export type ExposureReason = 'bot_harness' | 'channel_plugin' | 'multi_channel_chat';
+/** Whom the brain serves: 'one' silences the warning, null (unreadable) keeps it. */
+export type ExposureServes = 'one' | 'several' | null;
+
+/** brainServes for the warning; null when it cannot be read, so an install route never fails on its warning. */
+export async function exposureServes(engine: Pick<BrainEngine, 'getConfig' | 'executeRaw'>): Promise<ExposureServes> {
+ try {
+ return (await brainServes(engine)).serves;
+ } catch {
+ return null;
+ }
+}
/** `chat_sources`: the read sources that hold chat; channels across 2+ of them can be split by source grants, within one they cannot. */
export interface ChatCensus { sources: string[]; chat_pages: number; channels: number; chat_sources: string[] }
@@ -123,7 +140,14 @@ export function subjectLabel(s: ExposureSubject): string {
/** Source grants can separate channels only when they sit in different sources. */
const splitBySource = (census: ChatCensus | null | undefined): boolean => !census || census.chat_sources.length >= 2;
-/** The narrowing command: a credential's rescope, or a stdio server pinned to one source. Null when no source split exists. */
+/** The binding command: a credential bound to a member, or the harness's people labelled and its server bound. */
+export function bindArgv(s: ExposureSubject): string[] {
+ if (s.kind === 'legacy_token') return ['gbrain', 'auth', 'rescope', '--token', s.name, '--member', '<member>'];
+ if (s.kind === 'oauth_client') return ['gbrain', 'auth', 'rescope', '--client', s.id, '--member', '<member>'];
+ return ['gbrain', 'setup', s.harness, '--serves', 'several', '--members', '<id,...>'];
+}
+
+/** The narrowing command: a credential's source rescope, which leaves it unbound. Null when no source split exists. */
export function narrowArgv(s: ExposureSubject, census?: ChatCensus | null): string[] | null {
if (!splitBySource(census)) return null;
if (s.kind === 'legacy_token') return ['gbrain', 'auth', 'rescope', '--token', s.name, '--sources', '<source>'];
@@ -145,38 +169,40 @@ const PER_PERSON = 'Per-person access: give each person\'s agent its own credent
+ 'Never bind a shared agent\'s credential to one person: it then reads as that person for everyone who talks to it.';
/**
- * Today's fixes, chosen by where the chat lives, then the per-person setup.
- * One string so every route prints the same commands.
+ * The fixes, binding first: a credential bound to the person who uses the
+ * agent, or to the audience several people share; then the narrowings, which
+ * leave the credential unbound. One string so every route prints the same commands.
*/
export function remedyText(s: ExposureSubject, census?: ChatCensus | null): string {
- const steps: string[] = [];
+ const target = s.kind === 'legacy_token' ? `--token ${s.name}` : s.kind === 'oauth_client' ? `--client ${s.id}` : null;
+ const steps: string[] = [target
+ ? `bind the credential to the person who uses this agent (gbrain auth rescope ${target} --member <id>), or, for one agent several people share, to their audience (gbrain auth rescope ${target} --may-act-for <members>; its harness then names each request's audience)`
+ : `label each person and bind this harness's server (${bindArgv(s).join(' ')}; --stdio-member <member> when one person alone uses the harness)`];
if (splitBySource(census)) {
steps.push(s.kind === 'stdio'
- ? 'pin the agent to one audience\'s source by setting GBRAIN_SOURCE=<source> in its MCP server environment and running gbrain sources unfederate <source> (a federated sibling source stays nameable)'
- : `grant one audience's source only (${narrowArgv(s, census)!.join(' ')}; a new harness grant: gbrain mcp grant <name> --source <source> --federated-read <source>)`);
+ ? 'narrowing only, which leaves the server unbound: pin the agent to one audience\'s source by setting GBRAIN_SOURCE=<source> in its MCP server environment and running gbrain sources unfederate <source> (a federated sibling source stays nameable)'
+ : `narrowing only, which leaves the token unbound: ${narrowArgv(s, census)!.join(' ')} (a new harness grant: gbrain mcp grant <name> --source <source> --federated-read <source>)`);
steps.push('keep a channel\'s source out of unscoped reads (gbrain sources unfederate <id>)');
} else {
steps.push(`the chat sits in one source (${census!.chat_sources[0]}), so a source grant cannot separate it`);
}
steps.push('mark pages nobody else may see visibility: private (hidden from this agent unless its access may read private pages)');
- return `Fix: ${steps.join('; ')}. source_ids narrows only the call that sends it, so recall, list_pages or any read without it reads the token's full grant; the fix is ${splitBySource(census) ? 'a narrower grant (gbrain auth rescope …) or per-person access' : 'per-person access'}, not per-call narrowing. ${PER_PERSON}`;
+ return `Fix: ${steps.join('; ')}. source_ids narrows only the call that sends it, so recall, list_pages or any read without it reads the token's full grant; the fix is per-person access, not per-call narrowing. ${PER_PERSON}`;
}
export function exposureFix(s: ExposureSubject, census?: ChatCensus | null): Action {
- const argv = narrowArgv(s, census);
const verify = { argv: ['gbrain', 'doctor', '--only', NOTICE_CODE, '--json'] };
const message = `${subjectLabel(s)} lets the agent read every channel it reaches, so when several people use the agent it may show one person another person's messages. ${remedyText(s, census).replace(/^Fix: (.)/, (_m, c: string) => c.toUpperCase())}`;
- if (argv) {
- return { ask_user: true, argv, consent: ['credentials'], actor: 'agent', requires_exclusive: false, docs: DOCS, verify,
- inputs: [{ name: 'source', how: 'Ask the user which one source this agent\'s audience may read (gbrain sources list).' }],
- why: 'Narrowing the grant limits what the agent can show anyone to one audience\'s source; the secret is unchanged.', user_message: message };
- }
- return { ask_user: true, consent: [], actor: 'user', requires_exclusive: false, docs: DOCS, verify,
- why: 'Scoping this agent is the user\'s choice: a credential per person, a shared-channel audience, one source, private pages or a narrower deployment.', user_message: message };
+ return { ask_user: true, argv: bindArgv(s), consent: ['credentials'], actor: 'agent', requires_exclusive: false, docs: DOCS, verify,
+ inputs: s.kind === 'stdio'
+ ? [{ name: 'id,...', how: 'Ask the user who talks to this agent (gbrain access member list); use --stdio-member <member> instead when one person alone uses it.' }]
+ : [{ name: 'member', how: 'Ask the user which member uses this agent (gbrain access member list); when several people share it, rescope with --may-act-for <members> instead.' }],
+ why: 'A bound credential reads only what its member, or each request\'s audience, may read; the secret is unchanged.', user_message: message };
}
-/** The install-time warning. Null when no signal holds. */
-export function sharedTokenNotice(s: ExposureSubject, input: { harness?: string; channelPlugins?: readonly string[]; census?: ChatCensus | null }): Notice | null {
+/** The install-time warning. Null when the brain serves one person or no signal holds. */
+export function sharedTokenNotice(s: ExposureSubject, input: { harness?: string; channelPlugins?: readonly string[]; census?: ChatCensus | null; serves?: ExposureServes }): Notice | null {
+ if (input.serves === 'one') return null;
const reasons = exposureReasons(input);
if (reasons.length === 0) return null;
const fix = exposureFix(s, input.census);
diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.json
index 56f3b63244..1189e76d0f 100644
--- a/test/fixtures/goldens/doctor/content-pglite-human.json
+++ b/test/fixtures/goldens/doctor/content-pglite-human.json
@@ -201,7 +201,7 @@
" [OK] legacy_token_grant_drift: No legacy token grant has drifted from its permissions mirror.",
" [OK] legacy_token_null_scope: Every active legacy token has explicit scopes.",
" [OK] grant_new_ops_available: Every active client and token can call the operations its scopes allow.",
- " [OK] unscoped_multi_user_token: No credential or local agent that reads the same pages for everyone can read chat from several channels.",
+ " [INFO] unscoped_multi_user_token: Not applicable: this brain serves one person (0 enabled member(s)), so every credential reads that person's own pages.",
" [OK] image_assets: No image assets indexed yet",
" [OK] ocr_health: OCR not in use (or no images ingested with OCR opt-in)",
" [OK] image_embedding_coverage: No image pages indexed yet.",
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
index c7c6109bf1..5d35d871cc 100644
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -2478,8 +2478,10 @@
{
"category": "ops",
"elapsed_ms": "<volatile>",
- "message": "No credential or local agent that reads the same pages for everyone can read chat from several channels.",
+ "message": "Not applicable: this brain serves one person (0 enabled member(s)), so every credential reads that person's own pages.",
"name": "unscoped_multi_user_token",
+ "readiness_state": "not_applicable",
+ "severity": "info",
"status": "ok"
},
{
diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
index ceaa989c57..75999ea7d6 100644
--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
@@ -2650,8 +2650,10 @@
{
"category": "ops",
"elapsed_ms": "<volatile>",
- "message": "No credential or local agent that reads the same pages for everyone can read chat from several channels.",
+ "message": "Not applicable: this brain serves one person (0 enabled member(s)), so every credential reads that person's own pages.",
"name": "unscoped_multi_user_token",
+ "readiness_state": "not_applicable",
+ "severity": "info",
"status": "ok"
},
{
@@ -7780,8 +7782,10 @@
{
"category": "ops",
"elapsed_ms": "<volatile>",
- "message": "No credential or local agent that reads the same pages for everyone can read chat from several channels.",
+ "message": "Not applicable: this brain serves one person (0 enabled member(s)), so every credential reads that person's own pages.",
"name": "unscoped_multi_user_token",
+ "readiness_state": "not_applicable",
+ "severity": "info",
"status": "ok"
},
{
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index 4ecf96283f..5b64fdd44c 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -2661,8 +2661,10 @@
{
"category": "ops",
"elapsed_ms": "<volatile>",
- "message": "No credential or local agent that reads the same pages for everyone can read chat from several channels.",
+ "message": "Not applicable: this brain serves one person (0 enabled member(s)), so every credential reads that person's own pages.",
"name": "unscoped_multi_user_token",
+ "readiness_state": "not_applicable",
+ "severity": "info",
"status": "ok"
},
{
@@ -7799,8 +7801,10 @@
{
"category": "ops",
"elapsed_ms": "<volatile>",
- "message": "No credential or local agent that reads the same pages for everyone can read chat from several channels.",
+ "message": "Not applicable: this brain serves one person (0 enabled member(s)), so every credential reads that person's own pages.",
"name": "unscoped_multi_user_token",
+ "readiness_state": "not_applicable",
+ "severity": "info",
"status": "ok"
},
{
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index a89426823c..18670ba678 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -2277,8 +2277,10 @@
{
"category": "ops",
"elapsed_ms": "<volatile>",
- "message": "No credential or local agent that reads the same pages for everyone can read chat from several channels.",
+ "message": "Not applicable: this brain serves one person (0 enabled member(s)), so every credential reads that person's own pages.",
"name": "unscoped_multi_user_token",
+ "readiness_state": "not_applicable",
+ "severity": "info",
"status": "ok"
},
{
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index e5185eb77a..4b4a4063de 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -2333,8 +2333,10 @@
{
"category": "ops",
"elapsed_ms": "<volatile>",
- "message": "No credential or local agent that reads the same pages for everyone can read chat from several channels.",
+ "message": "Not applicable: this brain serves one person (0 enabled member(s)), so every credential reads that person's own pages.",
"name": "unscoped_multi_user_token",
+ "readiness_state": "not_applicable",
+ "severity": "info",
"status": "ok"
},
{
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index aa02e9524b..4d908d0af7 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -2344,8 +2344,10 @@
{
"category": "ops",
"elapsed_ms": "<volatile>",
- "message": "No credential or local agent that reads the same pages for everyone can read chat from several channels.",
+ "message": "Not applicable: this brain serves one person (0 enabled member(s)), so every credential reads that person's own pages.",
"name": "unscoped_multi_user_token",
+ "readiness_state": "not_applicable",
+ "severity": "info",
"status": "ok"
},
{
diff --git a/test/shared-exposure-routes.test.ts b/test/shared-exposure-routes.test.ts
index 7c60767331..753cca5deb 100644
--- a/test/shared-exposure-routes.test.ts
+++ b/test/shared-exposure-routes.test.ts
@@ -102,6 +102,7 @@ describe('brain routes on a repo-less keyless brain', () => {
async function brain(titles: string[]) {
const b = box();
expect((await runCli(['init', '--pglite', '--no-embedding', '--non-interactive'], { env: b.env, cwd: b.root, timeoutMs: 120_000 })).exitCode).toBe(0);
+ expect((await runCli(['config', 'set', 'access.serves', 'several'], { env: b.env, cwd: b.root })).exitCode).toBe(0);
for (const [i, title] of titles.entries()) {
const file = join(b.root, `p${i}.md`);
writeFileSync(file, page(title));
diff --git a/test/shared-exposure-serves.test.ts b/test/shared-exposure-serves.test.ts
new file mode 100644
index 0000000000..9d2aae4d59
--- /dev/null
+++ b/test/shared-exposure-serves.test.ts
@@ -0,0 +1,145 @@
+/**
+ * GST-363 follow-up (GBRA-108 ruling on Train A): the unscoped_multi_user_token
+ * warning applies only to a brain that serves several people (access.serves,
+ * src/core/access/serves.ts). On a one-person brain every credential reads that
+ * person's own pages, so the doctor check is not applicable and the install
+ * routes stay silent, including a bot harness on the owner's brain (R94). On a
+ * brain that serves several people the fix leads with binding the credential
+ * to a member; a source rescope is named only as a narrowing that leaves the
+ * token unbound. Repo-less PGLite brains throughout.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { insertUnifiedToken } from '../src/core/token-mint.ts';
+import { sharedTokenNotice } from '../src/core/grants/shared-exposure.ts';
+import { unscopedMultiUserTokenEntry } from '../src/commands/doctor/checks/unscoped-multi-user-token.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+
+const CODE = 'unscoped_multi_user_token';
+let engine: PGLiteEngine;
+const roots: string[] = [];
+const tmp = () => { const d = mkdtempSync(join(tmpdir(), 'gbrain-exposure-serves-')); roots.push(d); return d; };
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { if (engine) await engine.disconnect(); for (const r of roots) rmSync(r, { recursive: true, force: true }); }, 60_000);
+
+async function brainWithTwoChannels(serves: 'one' | 'several' | null) {
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw('DELETE FROM access_tokens');
+ await engine.executeRaw('DELETE FROM access_members');
+ if (serves) await engine.setConfig('access.serves', serves); else await engine.executeRaw("DELETE FROM config WHERE key = 'access.serves'");
+ await engine.setConfig('search.remote_private_pages', 'hidden');
+ __resetPrivateVisibilityCacheForTests();
+ for (const [slug, title] of [['chats/a', '#alpha, Jul 2'], ['chats/b', '#beta, Jul 2']]) {
+ await engine.putPage(slug!, { type: 'slack' as any, title: title!, compiled_truth: 'hello', frontmatter: {} });
+ }
+ await insertUnifiedToken(engine, { name: 'team-bot', tokenHash: 'hash-team-bot', grant: { sources: { kind: 'default' }, takesHolders: ['world'], allowedOperations: null } });
+}
+const doctor = async (home = tmp()) => withEnv({ GBRAIN_HOME: home, HOME: home, CLAUDE_CONFIG_DIR: join(home, '.claude') }, async () =>
+ (await unscopedMultiUserTokenEntry.run({ engine, args: [] } as unknown as DoctorContext) as any[])[0]);
+const census = { sources: ['default'], chat_pages: 2, channels: 2, chat_sources: ['default'] };
+const across = { sources: ['a', 'b'], chat_pages: 2, channels: 2, chat_sources: ['a', 'b'] };
+
+describe('one-person brain', () => {
+ test('doctor: not applicable when the member count says one person', async () => {
+ await brainWithTwoChannels(null);
+ await engine.executeRaw("INSERT INTO access_members (id) VALUES ('owner-example')");
+ const check = await doctor();
+ expect(check).toMatchObject({ name: CODE, status: 'ok', readiness_state: 'not_applicable' });
+ expect(check.message).toContain('serves one person');
+ expect(check.fix).toBeUndefined();
+ });
+
+ test('doctor: not applicable when access.serves is one, even with a wired bot harness (R94)', async () => {
+ await brainWithTwoChannels('one');
+ await engine.executeRaw("INSERT INTO access_members (id) VALUES ('owner-example'), ('bob-example')");
+ const home = tmp();
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'agent-instructions.json'), JSON.stringify({ entries: [{ harness: 'openclaw', path: join(home, 'SOUL.md'), status: 'installed', block_version: 1, access: { kind: 'mcp', server: 'gbrain' }, writer: 'gbrain setup openclaw' }] }));
+ const check = await doctor(home);
+ expect(check).toMatchObject({ status: 'ok', readiness_state: 'not_applicable' });
+ expect(check.message).toContain('config access.serves is one');
+ });
+
+ test('the notice is silent for every subject when the brain serves one person', () => {
+ expect(sharedTokenNotice({ kind: 'legacy_token', name: 'team-bot' }, { census, serves: 'one' })).toBeNull();
+ expect(sharedTokenNotice({ kind: 'oauth_client', id: 'c1' }, { census, serves: 'one' })).toBeNull();
+ expect(sharedTokenNotice({ kind: 'stdio', harness: 'openclaw' }, { harness: 'openclaw', serves: 'one' })).toBeNull();
+ });
+});
+
+describe('brain that serves several people', () => {
+ test('doctor warns and its fix binds the credential to a member', async () => {
+ await brainWithTwoChannels('several');
+ const check = await doctor();
+ expect(check.status).toBe('warn');
+ expect(check.fix).toMatchObject({ ask_user: true, argv: ['gbrain', 'auth', 'rescope', '--token', 'team-bot', '--member', '<member>'] });
+ });
+
+ test('the fix text leads with binding and names a source rescope only as an unbound narrowing', () => {
+ for (const c of [census, across]) {
+ const n = sharedTokenNotice({ kind: 'legacy_token', name: 'team-bot' }, { census: c, serves: 'several' })!;
+ const fix = n.why.slice(n.why.indexOf('Fix: '));
+ expect(fix.startsWith('Fix: bind the credential to the person who uses this agent (gbrain auth rescope --token team-bot --member <id>)')).toBe(true);
+ expect(fix).toContain('gbrain auth rescope --token team-bot --may-act-for <members>');
+ expect(fix.indexOf('--member <id>')).toBeLessThan(fix.indexOf('--may-act-for'));
+ if (c === across) {
+ expect(fix).toContain('narrowing only, which leaves the token unbound: gbrain auth rescope --token team-bot --sources <source>');
+ expect(fix.indexOf('--may-act-for')).toBeLessThan(fix.indexOf('--sources'));
+ } else {
+ expect(fix).not.toContain('--sources');
+ }
+ expect(n.fix!.argv).toEqual(['gbrain', 'auth', 'rescope', '--token', 'team-bot', '--member', '<member>']);
+ }
+ const client = sharedTokenNotice({ kind: 'oauth_client', id: 'c1' }, { census, serves: 'several' })!;
+ expect(client.fix!.argv).toEqual(['gbrain', 'auth', 'rescope', '--client', 'c1', '--member', '<member>']);
+ const bot = sharedTokenNotice({ kind: 'stdio', harness: 'openclaw' }, { harness: 'openclaw', serves: 'several' })!;
+ expect(bot.why).toContain('Fix: label each person and bind this harness\'s server (gbrain setup openclaw --serves several --members <id,...>');
+ });
+});
+
+describe('install routes on a one-person brain', () => {
+ const page = (title: string) => '---\ntitle: "' + title + '"\ntype: slack\n---\nhello\n';
+ function box() {
+ const root = tmp();
+ const home = join(root, 'home');
+ mkdirSync(home, { recursive: true });
+ const env = { HOME: home, GBRAIN_HOME: home, CLAUDE_CONFIG_DIR: join(home, '.claude'), HERMES_HOME: undefined, OPENCLAW_STATE_DIR: undefined,
+ OPENCLAW_WORKSPACE_DIR: undefined, OPENCLAW_PROFILE: undefined, GBRAIN_SOURCE: undefined, GBRAIN_AGENT_INSTRUCTIONS: undefined };
+ const bin = join(root, 'gbrain');
+ writeFileSync(bin, '#!/bin/sh\nexec \'' + process.execPath + '\' \'' + join(import.meta.dir, '..', 'src', 'cli.ts') + '\' "$@"\n');
+ chmodSync(bin, 0o755);
+ return { root, home, env, bin };
+ }
+
+ test('auth create and setup openclaw (a bot harness on the owner brain, R94) stay silent', async () => {
+ const b = box();
+ expect((await runCli(['init', '--pglite', '--no-embedding', '--non-interactive'], { env: b.env, cwd: b.root, timeoutMs: 120_000 })).exitCode).toBe(0);
+ for (const [i, title] of ['#alpha-team, Jul 2', '#beta-team, Jul 3'].entries()) {
+ const file = join(b.root, 'p' + i + '.md');
+ writeFileSync(file, page(title));
+ const put = Bun.spawnSync(['sh', '-c', '\'' + b.bin + '\' put chats/p' + i + ' < \'' + file + '\''], { env: Object.fromEntries(Object.entries({ ...process.env, ...b.env }).filter(([, v]) => v !== undefined)) as Record<string, string> });
+ expect(put.exitCode).toBe(0);
+ }
+ const token = await runCli(['auth', 'create', 'owner-bot'], { env: b.env, cwd: b.root });
+ expect(token.stdout).toMatch(/gbrain_[0-9a-f]+/);
+ expect(token.stderr).not.toContain(CODE);
+ const ws = join(b.home, '.openclaw', 'workspace');
+ mkdirSync(ws, { recursive: true });
+ const setup = JSON.parse((await runCli(['setup', 'openclaw', '--workspace', ws, '--gbrain-bin', b.bin, '--dry-run', '--json'], { env: b.env, cwd: b.root })).stdout);
+ expect((setup.notices ?? []).map((n: any) => n.code)).not.toContain(CODE);
+ const several = await runCli(['config', 'set', 'access.serves', 'several'], { env: b.env, cwd: b.root });
+ expect(several.exitCode).toBe(0);
+ expect((await runCli(['auth', 'create', 'shared-bot'], { env: b.env, cwd: b.root })).stderr).toContain(CODE);
+ }, 240_000);
+});
diff --git a/test/shared-exposure.test.ts b/test/shared-exposure.test.ts
index adada0ecd9..d5454941a3 100644
--- a/test/shared-exposure.test.ts
+++ b/test/shared-exposure.test.ts
@@ -40,6 +40,7 @@ async function reset() {
await engine.executeRaw('DELETE FROM oauth_clients');
await engine.executeRaw("DELETE FROM sources WHERE id <> 'default'");
await engine.setConfig('search.remote_private_pages', 'hidden');
+ await engine.setConfig('access.serves', 'several');
__resetPrivateVisibilityCacheForTests();
}
const chat = (slug: string, title: string, frontmatter: Record<string, unknown> = {}, type = 'slack', sourceId = 'default') =>
@@ -139,14 +140,15 @@ describe('signals and the warning', () => {
expect(split.why).toContain('another person\'s messages');
expect(split.why).toContain('gbrain auth rescope --token bot --sources <source>');
expect(split.why).toContain('gbrain sources unfederate <id>');
- expect(split.fix).toMatchObject({ ask_user: true, argv: ['gbrain', 'auth', 'rescope', '--token', 'bot', '--sources', '<source>'], consent: ['credentials'] });
+ expect(split.fix).toMatchObject({ ask_user: true, argv: ['gbrain', 'auth', 'rescope', '--token', 'bot', '--member', '<member>'], consent: ['credentials'] });
const one = sharedTokenNotice({ kind: 'oauth_client', id: 'c1' }, { census: within })!;
expect(one.why).toContain('the chat sits in one source (default), so a source grant cannot separate it');
- expect(one.why).not.toContain('auth rescope');
+ expect(one.why).not.toContain('--sources');
+ expect(one.why).toContain('gbrain auth rescope --client c1 --member <id>');
expect(one.why).toContain('the fix is per-person access, not per-call narrowing');
- expect(split.why).toContain('the fix is a narrower grant (gbrain auth rescope …) or per-person access, not per-call narrowing');
+ expect(split.why).toContain('the fix is per-person access, not per-call narrowing');
expect(one.why).toContain('gbrain auth create <name> --may-act-for <members>');
- expect(one.fix!.argv).toBeUndefined();
+ expect(one.fix!.argv).toEqual(['gbrain', 'auth', 'rescope', '--client', 'c1', '--member', '<member>']);
for (const n of [split, one]) {
expect(n.why).toContain('visibility: private (hidden from this agent unless its access may read private pages)');
expect(n.why).not.toContain('hidden from every remote caller');
@@ -164,7 +166,7 @@ describe('signals and the warning', () => {
expect(bot.why).toContain('gbrain auth create <name> --member <id>');
expect(exposureFix({ kind: 'stdio', harness: 'hermes' }).why).not.toContain('cannot tell');
expect(sharedTokenNotice({ kind: 'stdio', harness: 'claude-code' }, { harness: 'claude-code' })).toBeNull();
- expect(exposureFix({ kind: 'stdio', harness: 'hermes' }).argv).toBeUndefined();
+ expect(exposureFix({ kind: 'stdio', harness: 'hermes' }).argv).toEqual(['gbrain', 'setup', 'hermes', '--serves', 'several', '--members', '<id,...>']);
});
test('Claude Code channel plugins and bot workspaces are read from config paths', () => {
@@ -195,7 +197,7 @@ describe('doctor unscoped_multi_user_token', () => {
const warn = await doctor();
expect(warn.status).toBe('warn');
expect(warn.message).toContain('The token "team-bot" reaches 2 channels in chan-a, chan-b');
- expect(warn.fix).toMatchObject({ ask_user: true, argv: ['gbrain', 'auth', 'rescope', '--token', 'team-bot', '--sources', '<source>'] });
+ expect(warn.fix).toMatchObject({ ask_user: true, argv: ['gbrain', 'auth', 'rescope', '--token', 'team-bot', '--member', '<member>'] });
expect(categorizeCheck('unscoped_multi_user_token')).toBeDefined();
await engine.executeRaw('DELETE FROM access_tokens');
await token('team-bot', ['chan-a']);