Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

setup --stdio-member: refuse on a Postgres brain, preview the binding on a dry run, never bind after failed labelling (GST-363 fix-check)

garrytan3806a44ee6bf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a3540cf4ad..0e4f2f4af3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,7 +17,7 @@ identifiers and attribution are available in the pre-removal Git revision
### Itemized changes
- `gbrain setup claude-code|codex --serves one|several`, `--members <id,...>`, `--members-file <file>` (`src/commands/setup.ts`, `src/commands/setup-serves.ts`). Setup stays engine-free: the labelling, the serves read and the bound reads run as children of the launcher. An empty roster refuses `access_serves_roster_empty`.
-- On a brain that already serves several people (2+ enabled members, or `access.serves = several`; explicit wins), a plain setup refuses `setup_serves_several` and writes nothing unless an existing `mcp.stdio_member` naming an enabled member binds the connection; naming an owner no longer exempts it. Setup never writes `mcp.stdio_member` on its own: it is brain-wide, so it would bind every stdio MCP session on the host, including the shared sessions of OpenClaw or Hermes. `--stdio-member <member>` (with `--serves several`, claude-code or codex only) writes it and says so; it refuses where OpenClaw or Hermes is installed, and it is never recorded or replayed by a re-run. A brain setup cannot read refuses `setup_serves_unreadable`.
+- On a brain that already serves several people (2+ enabled members, or `access.serves = several`; explicit wins), a plain setup refuses `setup_serves_several` and writes nothing unless an existing `mcp.stdio_member` naming an enabled member binds the connection; naming an owner no longer exempts it. Setup never writes `mcp.stdio_member` on its own: it is brain-wide, so it would bind every stdio MCP session on the host, including the shared sessions of OpenClaw or Hermes. `--stdio-member <member>` (with `--serves several`, claude-code or codex on a local PGLite brain) writes it and says so; it refuses where OpenClaw or Hermes is installed and on a Postgres brain other machines can open, and it is never recorded or replayed by a re-run. A brain setup cannot read refuses `setup_serves_unreadable`.
- `gbrain access serves` (read-only view) and `gbrain access serves several --members ... [--yes]` (`src/commands/access-serves.ts`): the labelling on its own, preview first. Keys are idempotent on the member id (token `member-<id>`); a key whose file is gone is reported with the revoke step, never re-minted on its own. Key files never go inside a git work tree, symlinks resolved (`access_serves_key_dir_in_git`); a kept key file must hold the live key, and a minted key whose file cannot be written is revoked. An existing rule on `people/<member>/` that anyone else reads is BLOCKED, and the receipt lists people folders no rule covers.
- `src/core/access/serves.ts` (new): `brainServes(engine)`, the one read of whether a brain serves several people.
- `src/commands/auth-mint.ts` (new): the token mint `gbrain auth create` used inline, shared with the labelling; `auth create` output is unchanged.
diff --git a/docs/guides/access-designations.md b/docs/guides/access-designations.md
index 5be021ebd7..f8cedfe2a9 100644
--- a/docs/guides/access-designations.md
+++ b/docs/guides/access-designations.md
@@ -16,8 +16,11 @@ Five kinds of caller read a brain:
- **Local CLI** on the brain host (`remote = false`). Reads everything.
- **The owner**: a remote credential (token or OAuth client) or stdio server bound to the member named by
`gbrain access owner set <member>` (config `access.owner_member`). Bind each of the owner's agents, delegates and
- sub-agents included, with `gbrain auth rescope --token <name> --member <owner>` (stdio: `gbrain config set
- mcp.stdio_member <owner>`). On a single-user brain this is how the owner's own agent reads the whole brain.
+ sub-agents included, with `gbrain auth rescope --token <name> --member <owner>`. A stdio harness only the owner
+ uses: `gbrain setup <harness> --serves several --stdio-member <owner>`, which makes every stdio session on this
+ host read as the owner, private pages included; a harness several people talk to gets one key per person over
+ `gbrain serve --http` (`gbrain auth create --member <id>`). On a single-user brain this is how the owner's own
+ agent reads the whole brain.
- **Other members**: credentials bound to any other enabled member.
- **Public or unbound callers**: credentials bound to no member, and audiences that include a guest.
- **Shared rooms**: a shared agent speaking for an audience of several people (`X-Gbrain-On-Behalf-Of` /
diff --git a/docs/guides/setup.md b/docs/guides/setup.md
index 4216a90f56..93fe474ca0 100644
--- a/docs/guides/setup.md
+++ b/docs/guides/setup.md
@@ -179,8 +179,9 @@ restricts, and the harness's instructions keep the one-person scoping lines.
the host, from any harness, read as that member, including pages only that member
may read. Bind it only on a machine one person uses:
`gbrain setup claude-code --serves several --members ... --stdio-member <member>`
-(claude-code or codex only; refused where OpenClaw or Hermes is installed, because
-their shared sessions would read as that member too). A bot that answers several
+(claude-code or codex on a local PGLite brain only; refused where OpenClaw or Hermes
+is installed, because their shared sessions would read as that member too, and on a
+Postgres brain, which other machines can open). A bot that answers several
people runs `gbrain serve --http` with each member's key.
The preview runs first, and a BLOCKED line (a disabled member, an existing rule on
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 3e0e30c0ae..67f0db8ec8 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -374,7 +374,7 @@ test/serve-http-github-webhook.test.ts handler wiring (source pin) 1 source-surf
test/serve-http-mcp-transport-cleanup.test.ts POST /mcp transport cleanup (#2844) 2 source-surface-helper
test/serve-http-metrics.test.ts serve-http.ts wiring (structural — the two defects of the original PR) 2 source-surface-helper
test/serve-stdin-eof-drain.test.ts serve-sync-runner stays off the boot path (#4409) 1 readFileSync
-test/setup-serves-several.test.ts gbrain setup --serves (spawned, PGLite) 8 readFileSync
+test/setup-serves-several.test.ts gbrain setup --serves (spawned, PGLite) 9 readFileSync
test/setup-serves-several.test.ts labelling refuses or reports what it cannot make safe (pglite, repo-less) 8 readFileSync
test/setup.test.ts gbrain setup: setup migrations on the brain it creates (Cat 41 run 4) 3 readFileSync
test/shared-skills-catalog.test.ts (file-level) 22 readFileSync
diff --git a/src/commands/setup-serves.ts b/src/commands/setup-serves.ts
index 77f1f802a0..ab22f1dc51 100644
--- a/src/commands/setup-serves.ts
+++ b/src/commands/setup-serves.ts
@@ -6,8 +6,8 @@
* reads as. An existing brain it cannot read refuses (setup_serves_unreadable). A one-person setup (the default)
* on a brain that serves several people refuses (setup_serves_several) unless config mcp.stdio_member already
* binds the stdio connection. Setup writes mcp.stdio_member only for --stdio-member <enabled member> with
- * --serves several on claude-code or codex: the key is brain-wide, so it binds every stdio session on the host,
- * and setup refuses the flag where a shared-stdio harness (sharedStdioHarness) is installed. The brain-first text
+ * --serves several on claude-code or codex of a local PGLite brain: the key lives in the brain, so it binds every
+ * stdio session that opens it, and setup refuses the flag where a shared-stdio harness (sharedStdioHarness) is installed. The brain-first text
* says the connection is already scoped only once it is bound.
* - `--serves several --members a,b` runs `gbrain access serves several --yes --json` (members, one folder rule per
* member, one bound key per member in a 0600 file) and proves the labels with one bound read per member
@@ -16,6 +16,7 @@
import { existsSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
+import { openclawStateDir } from '../core/setup/brain-first.ts';
import { opError, OperationError } from '../core/ops/contract.ts';
import { bunSpawnSync } from '../core/spawn.ts';
import { readRoster, rosterEmpty, type ServesReceipt, type ServesStatus, receiptLines, receiptOk } from './access-serves.ts';
@@ -25,7 +26,7 @@ export interface ServesFlags { serves?: 'one' | 'several'; members?: string; mem
/** A harness installed on this host whose stdio sessions serve several conversations (OpenClaw, Hermes), or null. */
export function sharedStdioHarness(): string | null {
const onPath = (bin: string) => { try { return !!Bun.which(bin, { PATH: process.env.PATH ?? '' }); } catch { return false; } };
- if (onPath('openclaw') || existsSync(join(homedir(), '.openclaw'))) return 'OpenClaw';
+ if (onPath('openclaw') || existsSync(openclawStateDir())) return 'OpenClaw';
if (onPath('hermes') || existsSync(process.env.HERMES_HOME?.trim() || join(homedir(), '.hermes'))) return 'Hermes';
return null;
}
@@ -121,9 +122,10 @@ export interface ServesPlan { roster: string[]; status: ServesStatus | null }
* Before setup writes anything: the roster (an empty one refuses), the brain's serves view (none for a brain setup is
* about to create, or while this registration's own stdio serve holds a PGLite brain), and the one-person refusal.
*/
-export function servesPreflight(flags: ServesFlags, launcher: string, harness: string, hasBrain: boolean, liveOurs: boolean): ServesPlan | OperationError {
+export function servesPreflight(flags: ServesFlags, launcher: string, harness: string, hasBrain: boolean, liveOurs: boolean, pglite: boolean): ServesPlan | OperationError {
const roster = servesRoster(flags, harness);
if (roster instanceof OperationError) return roster;
+ if (flags.stdioMember && !pglite) return opError('invalid_params', 'This brain is a Postgres database other machines can open, and mcp.stdio_member is stored in the brain, so --stdio-member would bind stdio sessions on every machine that opens it, including a shared OpenClaw or Hermes host; nothing was written.', 'Leave the stdio server unbound, or bind a single-person harness with a member key over serve --http.');
if (flags.stdioMember && !roster.includes(flags.stdioMember)) return opError('invalid_params', `--stdio-member ${flags.stdioMember} is not one of the people in --members; nothing was written.`, 'Name a member listed in --members.');
if (flags.serves === 'several' && liveOurs) {
return opError('setup_owner_conflict', 'A live stdio serve started by this registration holds the PGLite brain, and labelling several people needs to write to it; nothing was written.',
@@ -144,7 +146,9 @@ export function servesApply(flags: ServesFlags, launcher: string, harness: strin
: { mode: 'several' as const, note: `the new brain is created first; then ${plan.roster.join(', ')} each get a member, a folder rule and a bound key` };
const reread = several && !flags.dryRun ? readServesStatus(launcher) : null;
const status = reread ? ('status' in reread ? reread.status : null) : plan.status;
- const stdio = bindStdio(launcher, harness, several && !status ? { serves: 'several', from: 'config', enabled_members: plan.roster, owner: null, stdio_member: null } : status, flags.stdioMember, flags.dryRun);
+ const preview = several && flags.dryRun && status?.serves !== 'several';
+ const member = labelled && !servesOk({ ...labelled, brain_serves: 'one' }) ? undefined : flags.stdioMember;
+ const stdio = bindStdio(launcher, harness, preview ? { serves: 'several', from: 'config', enabled_members: plan.roster, owner: null, stdio_member: status?.stdio_member ?? null } : status, member, flags.dryRun);
if (!labelled && !stdio) return null;
const outcome: ServesOutcome = { ...(labelled ?? { mode: 'one' as const }), brain_serves: 'one', ...(stdio ? { stdio } : {}),
...(reread && 'error' in reread ? { error: `reading the brain back failed: ${reread.error}` } : {}) };
@@ -155,13 +159,13 @@ export function servesApply(flags: ServesFlags, launcher: string, harness: strin
/** The stdio binding on a brain that serves several people: kept, written for the member a person named, else unbound. */
export function bindStdio(launcher: string, harness: string, status: ServesStatus | null, member: string | undefined, dryRun: boolean): ServesOutcome['stdio'] {
if (!status || status.serves !== 'several') return undefined;
- if (status.stdio_member) return { member: status.stdio_member, action: 'keep', detail: `this harness reads as ${status.stdio_member} (config mcp.stdio_member)` };
+ if (status.stdio_member) return { member: status.stdio_member, action: 'keep', detail: `this harness reads as ${status.stdio_member} (config mcp.stdio_member)${member && member !== status.stdio_member ? `; --stdio-member ${member} ignored, since setup never replaces an existing binding` : ''}` };
if (!member || !status.enabled_members.includes(member)) return { member: null, action: 'unbound', detail: `stdio sessions on this brain read only pages no rule restricts, so this harness's instructions keep the one-person scoping lines; to bind a harness that only that person uses, run gbrain setup ${harness} --serves several --stdio-member <member>` };
if (!dryRun) {
const r = child(launcher, ['config', 'set', 'mcp.stdio_member', member]);
if (!r.ok) return { member: null, action: 'unbound', detail: `writing mcp.stdio_member = ${member} failed, so stdio stays unbound: ${r.stderr.trim()}` };
}
- return { member, action: 'write', detail: `every stdio MCP session on this brain, from any harness on this host, now reads as ${member}, including pages only ${member} may read (config mcp.stdio_member)` };
+ return { member, action: 'write', detail: `${dryRun ? 'would bind: ' : ''}every stdio MCP session on this brain, from any harness on this host, now reads as ${member}, including pages only ${member} may read (config mcp.stdio_member)` };
}
export function servesOk(o: ServesOutcome | null): boolean {
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index 83c19adaa2..307d705a64 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -524,7 +524,7 @@ export async function runSetup(args: string[]): Promise<number> {
actor: 'agent', argv: ['gbrain', 'bootstrap', 'harness', '--remove', '--dry-run'],
why: 'Preview removing the bootstrap harness wiring first, or keep it and skip setup.', verify: verifyDryRun('claude-code', flags.name) }), out);
}
- const servesPlan = servesPreflight(flags, launcher, 'claude-code', !!cfg, !!liveOwner?.ours);
+ const servesPlan = servesPreflight(flags, launcher, 'claude-code', !!cfg, !!liveOwner?.ours, !cfg || cfg.engine === 'pglite');
if (servesPlan instanceof OperationError) return refuse(servesPlan, out);
const brainCreate = !cfg;
@@ -702,7 +702,7 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainCon
actor: 'agent', argv: harnessLane ? ['gbrain', 'bootstrap', 'harness', '--remove', '--dry-run'] : ['gbrain', 'setup', 'codex', laneEvents.every((e) => e === 'SessionEnd') ? '--no-capture' : '--no-hooks', '--dry-run', '--json'],
why: harnessLane ? 'Preview removing the bootstrap harness wiring first, or keep it and skip setup.' : 'Keep the bootstrap lane for those events and preview setup without them.', verify: verifyDryRun('codex', flags.name) }), out);
}
- const servesPlan = servesPreflight(flags, launcher, 'codex', !!cfg, !!liveOwner?.ours);
+ const servesPlan = servesPreflight(flags, launcher, 'codex', !!cfg, !!liveOwner?.ours, !cfg || cfg.engine === 'pglite');
if (servesPlan instanceof OperationError) return refuse(servesPlan, out);
const brainCreate = !cfg;
diff --git a/test/setup-serves-several.test.ts b/test/setup-serves-several.test.ts
index f9f60ee8fe..8617d90ce2 100644
--- a/test/setup-serves-several.test.ts
+++ b/test/setup-serves-several.test.ts
@@ -31,6 +31,7 @@ import { noGrantFederatedScope } from '../src/core/source-resolver.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
import { labelSeveral, receiptOk, servesStatus, type ServesReceipt } from '../src/commands/access-serves.ts';
import { setupRerunArgv } from '../src/core/setup/launcher-lanes.ts';
+import { servesPreflight } from '../src/commands/setup-serves.ts';
import { readdirSync } from 'node:fs';
import { addMember } from '../src/core/access/members.ts';
import { unlabeledPeopleFoldersEntry } from '../src/commands/doctor/checks/unlabeled-people-folders.ts';
@@ -289,7 +290,7 @@ function box(): Box {
chmodSync(bin, 0o755);
return { root, home, bin };
}
-const gbrain = (b: Box, args: string[], env: Record<string, string | undefined> = {}) => runCli(args, { env: { ...CLEAN, HOME: b.home, GBRAIN_HOME: b.home, ...env }, timeoutMs: 120_000 });
+const gbrain = (b: Box, args: string[], env: Record<string, string | undefined> = {}) => runCli(args, { env: { ...CLEAN, HOME: b.home, GBRAIN_HOME: b.home, OPENCLAW_STATE_DIR: join(b.root, 'openclaw-state'), OPENCLAW_PROFILE: undefined, HERMES_HOME: join(b.root, 'hermes-home'), ...env }, timeoutMs: 120_000 });
async function setup(b: Box, args: string[]): Promise<CliResult & { doc: any }> {
const r = await gbrain(b, ['setup', ...args, '--gbrain-bin', b.bin]);
let doc: any = null;
@@ -326,6 +327,10 @@ describe('gbrain setup --serves (spawned, PGLite)', () => {
test('--serves several labels each person, proves it with bound reads, prints key paths never values; a re-run keeps it all', async () => {
const b = box();
await brainWithPages(b);
+ const preview = await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example', '--stdio-member', 'alice-example', '--dry-run']);
+ expect(preview.exitCode).toBe(0);
+ expect(preview.stdout).toContain('stdio would bind: every stdio MCP session on this brain');
+ expect(await stdioKey(b)).toBe('');
const first = await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example']);
expect(first.exitCode).toBe(0);
for (const m of ROSTER) {
@@ -373,14 +378,13 @@ describe('gbrain setup --serves (spawned, PGLite)', () => {
expect((await gbrain(b, ['access', 'owner', 'set', 'alice-example'])).exitCode).toBe(0);
const workspace = join(b.root, 'oc-workspace');
mkdirSync(workspace);
- const labelled = await setup(b, ['openclaw', '--serves', 'several', '--members', ROSTER.join(','), '--workspace', workspace]);
- expect(labelled.stdout + labelled.stderr).not.toContain('reads as alice-example');
- expect(await stdioKey(b)).toBe('');
+ expect(existsSync(join(b.root, 'openclaw-state'))).toBe(false);
const refusals: Array<[string[], string, Record<string, string>]> = [
[['claude-code', '--stdio-member', 'alice-example'], '--stdio-member needs --serves several', {}],
[['openclaw', '--serves', 'several', '--members', ROSTER.join(','), '--workspace', workspace, '--stdio-member', 'alice-example'], 'claude-code or codex', {}],
[['claude-code', '--instructions-only', '--serves', 'several', '--stdio-member', 'alice-example'], 'claude-code or codex', {}],
[['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--stdio-member', 'alice-example'], "OpenClaw's shared sessions", { PATH: `${fakeOpenclaw(b)}:${process.env.PATH}` }],
+ [['codex', '--serves', 'several', '--members', ROSTER.join(','), '--stdio-member', 'alice-example'], "Hermes's shared sessions", { HERMES_HOME: b.root }],
];
for (const [args, says, env] of refusals) {
const r = await gbrain(b, ['setup', ...args, '--gbrain-bin', b.bin], env);
@@ -388,8 +392,17 @@ describe('gbrain setup --serves (spawned, PGLite)', () => {
expect(r.stderr).toContain(says);
expect(await stdioKey(b)).toBe('');
}
+ const labelled = await setup(b, ['openclaw', '--serves', 'several', '--members', ROSTER.join(','), '--workspace', workspace]);
+ expect(labelled.stdout + labelled.stderr).not.toContain('reads as alice-example');
+ expect(await stdioKey(b)).toBe('');
}, 360_000);
+ test('--stdio-member refuses on a Postgres brain other machines can open, before reading or writing anything', () => {
+ const refused = servesPreflight({ serves: 'several', members: 'alice-example,bob-example', stdioMember: 'alice-example', dryRun: false }, '/nonexistent/gbrain', 'claude-code', true, false, false);
+ expect(refused).toMatchObject({ code: 'invalid_params' });
+ expect((refused as Error).message).toContain('every machine that opens it');
+ });
+
test('a brain setup cannot read refuses and writes nothing', async () => {
const b = box();
expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);