Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

setup --serves several: refuse what it cannot make safe and prove each folder directly (GST-363 review fixes)

garrytan6dab435658c7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c39399fdc5..d0ddbd594b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,17 +12,17 @@ identifiers and attribution are available in the pre-removal Git revision
## [Unreleased]
-**A brain that serves several people can now be set up the safe way in one command: each person gets a member, a folder only they read and a key bound to them, and doctor fails when a person's folder has no owner.** When one bot answers several people from one brain with one unbound key, it pulls one person's notes into another person's answers (garrytan/harness-evals#363 measured 15 to 47.5% of trials; bots reading through member-bound keys stayed at 0 to 0.5%). `gbrain setup claude-code --serves several --members alice-example,bob-example` writes `access.serves = several`, adds the members, adds a folder rule `people/<member>/` per member through the folder-rule path (committed to `.gbrain/access.yml` on a repo brain, the database rule log on a repo-less one), mints one read-write key per member through the `auth create` mint into a 0600 file under `~/.gbrain/member-keys/`, and proves with a bound read per member that each sees only its own folder and world pages. Re-runs keep everything and never replace a key; a partial failure finishes on the next run. A one-person brain sees no change: `--serves one` stays the default and its output is unchanged.
+**A brain that serves several people can now be set up the safe way in one command: each person gets a member, a folder only they read and a key bound to them, and doctor fails when a person's folder has no owner.** When one bot answers several people from one brain with one unbound key, it pulls one person's notes into another person's answers (garrytan/harness-evals#363 measured 15 to 47.5% of trials; bots reading through member-bound keys stayed at 0 to 0.5%). `gbrain setup claude-code --serves several --members alice-example,bob-example` writes `access.serves = several`, adds the members, adds a folder rule `people/<member>/` per member through the folder-rule path (committed to `.gbrain/access.yml` on a repo brain, the database rule log on a repo-less one), mints one read-write key per member through the `auth create` mint (granted the labelled source) into a 0600 file under `~/.gbrain/member-keys/`, and proves by reading every other member's folder as each member that none is visible. Re-runs keep everything and never replace a key; a partial failure finishes on the next run, and anything the preview marks BLOCKED stops the run before it writes. A one-person brain sees no change: `--serves one` stays the default and its output is unchanged.
### 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 the connection is bound: when the brain names an owner (`access.owner_member`), setup writes `mcp.stdio_member = <owner>`; an existing `mcp.stdio_member` is kept.
-- `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 (`access_serves_key_dir_in_git`).
+- 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 the connection is bound: when the brain names an enabled owner (`access.owner_member`), setup writes `mcp.stdio_member = <owner>`; an existing `mcp.stdio_member` naming an enabled member is kept. 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.
- `src/commands/access-rules.ts`: `addFolderRules` adds rules through the same preview-then-write path as `gbrain access rule add`.
-- Brain-first block and per-turn rule (`src/core/setup/brain-first.ts`): on a several-person install the `source_ids` / "apply your own access rules" line becomes "This connection reads only what the person asking may read." One-person text is unchanged; doctor's `harness_wiring` repair names `--serves several` for such a block.
+- Brain-first block and per-turn rule (`src/core/setup/brain-first.ts`): on a several-person install whose stdio server is bound to a member, the `source_ids` / "apply your own access rules" line becomes "This connection reads only what the person asking may read." (`--instructions-only --serves several` checks the brain first). One-person text is unchanged; doctor's `harness_wiring` repair names `--serves several` for such a block.
- New doctor check `unlabeled_people_folders` (`src/commands/doctor/checks/unlabeled-people-folders.ts`): on a several-person brain, fails for each top-level `people/<name>/` folder with pages that no folder rule (on that folder or on `people/`) covers; the fix previews the rule and asks the user who reads it. Not applicable on a one-person brain.
- Docs: `docs/guides/setup.md` ("A brain that serves several people"), `INSTALL_FOR_AGENTS.md`, `skills/setup/SKILL.md`, `skills/conventions/brain-routing.md`.
- Tests: `test/setup-serves-several.test.ts` (PGLite repo-less and Postgres in process with the minted keys verified by the serve --http verifier; spawned setup on PGLite; a repo brain with a real git repository).
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index 4ce2658ef3..9c6f4877d4 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -151,7 +151,7 @@ When the brain will answer several people (a team bot, a shared channel), ask th
user who they are and add `--serves several --members <id,...>`: each person gets
a member, a folder `people/<member>/` only they read and a key bound to them
(`~/.gbrain/member-keys/<member>.key`, 0600; relay paths, never key values), and
-the receipt proves each member reads only their folder plus world pages.
+the receipt proves no member reads another member's folder.
`setup_serves_several` means the brain already serves several people and the
connection would be bound to nobody: rerun with its fix, or name the owner
(`gbrain access owner set <member>`) first. Doctor's `unlabeled_people_folders`
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 0866bfb8c2..0776e9175c 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -4514,6 +4514,14 @@ More: [docs/guides/repair.md#setup-owner-conflict](../../docs/guides/repair.md#s
|---|---|---|---|---|---|---|
| gbrain setup for one person was run on a brain that serves several people, and the stdio connection it would write is bound to nobody, so setup wrote nothing. | On a brain that serves several people an unbound connection reads every page no rule restricts, for whoever is asking; setup never writes one. | Run gbrain setup <harness> --serves several --members <id,...> to label each person, or name the brain owner first (gbrain access owner set <member>) so this harness reads as the owner. Run: gbrain access serves --json | agent | `repeat the read that failed` | 1 | no |
+### setup_serves_unreadable
+
+<a id="setup_serves_unreadable"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| gbrain setup could not read whether the existing brain serves several people, so it wrote nothing. | Setup writes an unbound connection only on a brain it knows serves one person; a brain it cannot read might serve several. | Run gbrain access serves --json to see why the brain cannot be read, fix that, then run setup again. Run: gbrain access serves --json | agent | `repeat the read that failed` | 1 | no |
+
### shared_skills_unavailable
<a id="shared_skills_unavailable"></a>
diff --git a/docs/guides/setup.md b/docs/guides/setup.md
index 033f9ab272..384482f273 100644
--- a/docs/guides/setup.md
+++ b/docs/guides/setup.md
@@ -168,19 +168,27 @@ For each person this adds a member (existing ones are kept), a folder rule
`.gbrain/access.yml` through `gbrain git commit-push`; repo-less brain: the
database rule log), and one key bound to that member, written to
`~/.gbrain/member-keys/<member>.key` (mode 0600, never inside a git checkout; the
-receipt prints the path, never the key). It sets `access.serves = several`, then
-proves the labels with one read per member (`gbrain find people/ --as <member>`):
-each member sees its own folder and world pages, never another member's folder.
+receipt prints the path, never the key). It sets `access.serves = several` last,
+then proves the labels by reading every other member's folder as each member
+(`gbrain find people/<other>/ --as <member>`): none may return a page.
+The receipt also lists any other `people/<name>/` folder that no rule covers, since
+every member reads it, and the run is not OK until it has a rule.
When the brain names an owner (`gbrain access owner set <member>`), this harness's
-own stdio server is bound to it (`mcp.stdio_member`); a bot that answers several
+own stdio server is bound to it (`mcp.stdio_member`); until it is bound, its
+instructions keep the one-person scoping lines. A bot that answers several
people runs `gbrain serve --http` with each member's key.
-Every step is idempotent on the member id, so a re-run after a failure finishes the
-rest. A key whose file is gone is reported, never replaced on its own: revoke it
-(`gbrain auth revoke member-<id>`) and run setup again. An empty roster refuses.
+The preview runs first, and a BLOCKED line (a disabled member, an existing rule on
+`people/<member>/` that someone else also reads, a key whose file is gone or holds
+another key) stops the whole run with nothing written. Every step is idempotent on
+the member id, so a re-run after a failure finishes the rest; a key whose file could
+not be written is revoked on the spot. A key whose file is gone is never replaced on
+its own: revoke it (`gbrain auth revoke member-<id>`) and run setup again. An
+empty roster refuses.
`--serves one` (the default) changes nothing, but on a brain that already serves
several people a plain setup refuses (`setup_serves_several`) rather than write a
-connection bound to nobody, unless an owner or `mcp.stdio_member` binds it.
+connection bound to nobody, unless an owner or `mcp.stdio_member` binds it, and
+a brain setup cannot read refuses (`setup_serves_unreadable`).
`gbrain doctor` fails `unlabeled_people_folders` when such a brain has a
`people/<name>/` folder with pages and no rule naming its readers.
`gbrain access serves several --members ...` does the labelling alone (preview, then
@@ -195,8 +203,9 @@ brain. So setup also writes one short marked block (`<!-- gbrain:brain-first:beg
session: before answering any turn, search the brain first, read the best hit,
fill gaps with other tools, apply your own access rules (`source_ids` narrows a
search to what the current requester may see), then finish the task. On a brain
-that serves several people the access line says instead that the connection reads
-only what the person asking may read (see below).
+that serves several people, once this harness's stdio server is bound to a member,
+the access line says instead that the connection reads only what the person asking
+may read (see below).
| Harness | File |
|---|---|
diff --git a/llms-full.txt b/llms-full.txt
index 84901b4437..965bb4568d 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -2843,7 +2843,7 @@ When the brain will answer several people (a team bot, a shared channel), ask th
user who they are and add `--serves several --members <id,...>`: each person gets
a member, a folder `people/<member>/` only they read and a key bound to them
(`~/.gbrain/member-keys/<member>.key`, 0600; relay paths, never key values), and
-the receipt proves each member reads only their folder plus world pages.
+the receipt proves no member reads another member's folder.
`setup_serves_several` means the brain already serves several people and the
connection would be bound to nobody: rerun with its fix, or name the owner
(`gbrain access owner set <member>`) first. Doctor's `unlabeled_people_folders`
diff --git a/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md b/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md
index 38aa93af09..f056816e2b 100644
--- a/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md
+++ b/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md
@@ -28,7 +28,7 @@ reason.
A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludes
this credential or the audience it acts for: check `whoami` (`access.applied`) before telling the user there are no notes.
-On a brain that serves several people (`gbrain access serves`), each connection already reads as the person asking: don't scope it yourself.
+On a brain that serves several people (`gbrain access serves`), a connection bound to a member (`whoami` names it) already reads as the person asking; an unbound one still needs the scoping above.
## When to switch brain
diff --git a/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md b/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md
index 38aa93af09..f056816e2b 100644
--- a/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md
+++ b/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md
@@ -28,7 +28,7 @@ reason.
A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludes
this credential or the audience it acts for: check `whoami` (`access.applied`) before telling the user there are no notes.
-On a brain that serves several people (`gbrain access serves`), each connection already reads as the person asking: don't scope it yourself.
+On a brain that serves several people (`gbrain access serves`), a connection bound to a member (`whoami` names it) already reads as the person asking; an unbound one still needs the scoping above.
## When to switch brain
diff --git a/plugin/skills/conventions/brain-routing.md b/plugin/skills/conventions/brain-routing.md
index 38aa93af09..f056816e2b 100644
--- a/plugin/skills/conventions/brain-routing.md
+++ b/plugin/skills/conventions/brain-routing.md
@@ -28,7 +28,7 @@ reason.
A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludes
this credential or the audience it acts for: check `whoami` (`access.applied`) before telling the user there are no notes.
-On a brain that serves several people (`gbrain access serves`), each connection already reads as the person asking: don't scope it yourself.
+On a brain that serves several people (`gbrain access serves`), a connection bound to a member (`whoami` names it) already reads as the person asking; an unbound one still needs the scoping above.
## When to switch brain
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index c96e9b68f5..5b16690214 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -374,8 +374,8 @@ 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) 5 readFileSync
-test/setup-serves-several.test.ts labelling several people (${kind}, repo-less) 7 readFileSync
+test/setup-serves-several.test.ts gbrain setup --serves (spawned, PGLite) 7 readFileSync
+test/setup-serves-several.test.ts labelling refuses or reports what it cannot make safe (pglite, repo-less) 7 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
test/shared-skills-export.serial.test.ts (file-level) 7 readFileSync
diff --git a/skills/conventions/brain-routing.md b/skills/conventions/brain-routing.md
index 38aa93af09..f056816e2b 100644
--- a/skills/conventions/brain-routing.md
+++ b/skills/conventions/brain-routing.md
@@ -28,7 +28,7 @@ reason.
A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludes
this credential or the audience it acts for: check `whoami` (`access.applied`) before telling the user there are no notes.
-On a brain that serves several people (`gbrain access serves`), each connection already reads as the person asking: don't scope it yourself.
+On a brain that serves several people (`gbrain access serves`), a connection bound to a member (`whoami` names it) already reads as the person asking; an unbound one still needs the scoping above.
## When to switch brain
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 848fde975a..fd5e3ac588 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -46,7 +46,7 @@
"context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab",
"conventions/agent-operator-protocol.md": "12c7b876994b96babdffa903326f7e23253d54ad9023248820337f56f8770512",
"conventions/brain-first.md": "f84f03b9619a1c9302a231bd43957c6987d55084f56eee351434b85ec2646a5c",
- "conventions/brain-routing.md": "a8eaf769fbc42cafa0f5ddec65032ffff80739c961f4bdd3d8999ce64104ee21",
+ "conventions/brain-routing.md": "753703b94fcb10d42cb52fb0c85d7a8c9769df84b0df622dd04ae0d943bb84b1",
"conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198",
"conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933",
"conventions/cross-modal.yaml": "c012c3d72614a87b1ee698173dce2a0fb0d057a54df7aab87993c4b07fff6280",
diff --git a/src/commands/access-serves.ts b/src/commands/access-serves.ts
index 65731425c2..307db7ca60 100644
--- a/src/commands/access-serves.ts
+++ b/src/commands/access-serves.ts
@@ -9,20 +9,22 @@
* (preview, then write at the previewed revision; a git-store source commits .gbrain/access.yml through the commit
* door, a repo-less source writes the database revision log), and mints one key per member through the auth create
* mint, bound to that member and written to a 0600 file under <configDir>/member-keys/, never inside a git work tree.
- * Every step is idempotent on the member id, so a re-run after a partial failure converges; the receipt names paths,
+ * A preview with any BLOCKED line writes nothing; config access.serves is written last, once members, rules and keys
+ * are in place. Every step is idempotent on the member id, so a re-run after a partial failure converges; the receipt names paths,
* never key values. `gbrain setup <harness> --serves several` runs this as a child and adds the bound-read proof.
*/
-import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
-import { dirname, join } from 'node:path';
+import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
+import { dirname, join, relative } from 'node:path';
import type { BrainEngine } from '../core/engine.ts';
import { configDir } from '../core/config.ts';
+import { hashToken } from '../core/utils.ts';
import { opError } from '../core/ops/contract.ts';
import { usageError } from '../cli/cli-error.ts';
import { normalizeRule, type FolderRule } from '../core/access/folder-rules.ts';
import { addMember, getMember, parseIdList } from '../core/access/members.ts';
import { ownerMemberId } from '../core/access/owner.ts';
import { stdioMemberId } from '../core/access/caller.ts';
-import { brainServes, SERVES_KEY, type ServesView } from '../core/access/serves.ts';
+import { brainServes, SERVES_KEY, unlabeledPeopleFolders, type PeopleFolder, type ServesView } from '../core/access/serves.ts';
import { addFolderRules, currentFolderRules } from './access-rules.ts';
import { mintToken } from './auth-mint.ts';
@@ -32,7 +34,7 @@ export const memberKeyDir = (): string => join(configDir(), MEMBER_KEY_DIR);
export interface ServesStatus extends ServesView { owner: string | null; stdio_member: string | null }
-type Step = 'config' | 'members' | 'rules' | 'keys';
+type Step = 'members' | 'rules' | 'keys' | 'config';
export interface ServesReceipt {
serves: 'several';
source_id: string;
@@ -43,6 +45,8 @@ export interface ServesReceipt {
rule_write?: { store: string; revision: number | null; state: string; git_commit?: string | null };
keys: Array<{ member: string; token_name: string; path: string; action: 'mint' | 'keep' | 'blocked'; detail?: string }>;
key_dir: string;
+ /** People folders with pages that no rule covers once this run's rules are in place: every member reads them. */
+ unlabeled: PeopleFolder[];
/** The steps finished before a failure (partial-failure report); every one is idempotent, so a re-run converges. */
completed: Step[];
error?: { code: string; message: string };
@@ -60,16 +64,21 @@ export function rosterEmpty(command: string): Error {
{ why: 'Each person gets a member, a folder only they read and a key bound to them; setup never guesses who they are.' });
}
-/** The first directory at or above `dir` that holds .git, or null. */
+/** The first directory at or above `dir` that holds .git, or null; symlinks are resolved, so a link into a checkout counts. */
function gitRootAbove(dir: string): string | null {
- for (let d = dir; ; d = dirname(d)) {
+ let existing = dir;
+ while (!existsSync(existing) && dirname(existing) !== existing) existing = dirname(existing);
+ const physical = join(realpathSync(existing), relative(existing, dir));
+ for (let d = physical; ; d = dirname(d)) {
if (existsSync(join(d, '.git'))) return d;
if (dirname(d) === d) return null;
}
}
export async function servesStatus(engine: BrainEngine): Promise<ServesStatus> {
- return { ...(await brainServes(engine)), owner: await ownerMemberId(engine), stdio_member: await stdioMemberId(engine) };
+ const view = await brainServes(engine);
+ const live = (id: string | null) => (id && view.enabled_members.includes(id) ? id : null);
+ return { ...view, owner: live(await ownerMemberId(engine)), stdio_member: live(await stdioMemberId(engine)) };
}
async function plan(engine: BrainEngine, roster: string[], sourceId: string): Promise<ServesReceipt> {
@@ -93,25 +102,35 @@ async function plan(engine: BrainEngine, roster: string[], sourceId: string): Pr
if ('problem' in r) return { id, prefix: `people/${id}/`, readers: [id], action: 'blocked', detail: r.problem };
const clash = base.find(b => b.prefix === r.rule.prefix || b.id === r.rule.id);
if (!clash) return { id: r.rule.id, prefix: r.rule.prefix, readers: r.rule.readable_by, action: 'add' };
- if (clash.prefix === r.rule.prefix && clash.readable_by.includes(`member:${id}`)) return { id: clash.id, prefix: clash.prefix, readers: clash.readable_by, action: 'keep' };
+ if (clash.prefix === r.rule.prefix && clash.readable_by.length === 1 && clash.readable_by[0] === `member:${id}`) return { id: clash.id, prefix: clash.prefix, readers: clash.readable_by, action: 'keep' };
+ const readers = clash.readable_by.map(p => p.replace(/^member:/, '')).join(', ');
return { id: r.rule.id, prefix: r.rule.prefix, readers: r.rule.readable_by, action: 'blocked',
- detail: `rule "${clash.id}" on ${clash.prefix} already exists and does not name ${id}; change it with gbrain access rule add --id ${clash.id} --prefix ${clash.prefix} --readers <list>` };
+ detail: `rule "${clash.id}" on ${clash.prefix} already exists, readable by ${readers}, not by ${id} alone; change it with gbrain access rule add --id ${clash.id} --prefix ${clash.prefix} --readers ${id} --source ${sourceId}` };
});
const keys: ServesReceipt['keys'] = [];
for (const id of roster) {
const name = memberKeyName(id);
const path = join(keyDir, `${id}.key`);
- const [token] = await engine.executeRaw<{ member_id: string | null }>('SELECT member_id FROM access_tokens WHERE name = $1 AND revoked_at IS NULL', [name]);
+ const [token] = await engine.executeRaw<{ member_id: string | null; token_hash: string }>('SELECT member_id, token_hash FROM access_tokens WHERE name = $1 AND revoked_at IS NULL', [name]);
if (members.find(m => m.id === id)?.action === 'blocked') keys.push({ member: id, token_name: name, path, action: 'blocked', detail: 'the member is not enabled' });
else if (!token) keys.push({ member: id, token_name: name, path, action: 'mint' });
else if (token.member_id !== id) keys.push({ member: id, token_name: name, path, action: 'blocked', detail: `a token named ${name} exists but is not bound to ${id}; revoke it (gbrain auth revoke ${name}) or bind it (gbrain auth rescope --token ${name} --member ${id})` });
else if (!existsSync(path)) keys.push({ member: id, token_name: name, path, action: 'blocked', detail: `the key ${name} exists but its file is gone and a key is shown only once; revoke it (gbrain auth revoke ${name}) and run this again to mint a new one` });
+ else if (hashToken(readFileSync(path, 'utf8').trim()) !== token.token_hash) keys.push({ member: id, token_name: name, path, action: 'blocked', detail: `the file does not hold the live key ${name} (it was revoked and made again, or another brain wrote it); revoke it (gbrain auth revoke ${name}) and run this again to mint a new one` });
else keys.push({ member: id, token_name: name, path, action: 'keep' });
}
return { serves: 'several', source_id: sourceId, applied: false, config: { key: SERVES_KEY, value: 'several', action: explicit === 'several' ? 'keep' : 'write' },
- members, rules, keys, key_dir: keyDir, completed: [] };
+ members, rules, keys, key_dir: keyDir, unlabeled: await unlabeledOutside(engine, sourceId, rules), completed: [] };
}
+/** Unlabeled people folders, not counting the ones this run's rules cover. */
+async function unlabeledOutside(engine: BrainEngine, sourceId: string, rules: ServesReceipt['rules']): Promise<PeopleFolder[]> {
+ const covered = new Set(rules.filter(r => r.action !== 'blocked').map(r => r.prefix));
+ return (await unlabeledPeopleFolders(engine)).filter(u => !(u.source === sourceId && covered.has(u.prefix)));
+}
+
+const blocked = (r: ServesReceipt): boolean => [...r.members, ...r.rules, ...r.keys].some(x => x.action === 'blocked');
+
function writeKeyFile(path: string, token: string): void {
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
chmodSync(dirname(path), 0o700);
@@ -128,11 +147,9 @@ function abortAfter(step: string): void {
/** Plans, and with `apply` writes, the several-people labelling; a failure is reported in the receipt, never thrown. */
export async function labelSeveral(engine: BrainEngine, roster: string[], sourceId: string, apply: boolean, json: boolean): Promise<ServesReceipt> {
const receipt = await plan(engine, roster, sourceId);
- if (!apply) return receipt;
+ if (!apply || blocked(receipt)) return receipt;
receipt.applied = true;
try {
- if (receipt.config.action === 'write') await engine.setConfig(SERVES_KEY, 'several');
- receipt.completed.push('config');
for (const m of receipt.members.filter(x => x.action === 'add')) await addMember(engine, m.id);
receipt.completed.push('members');
abortAfter('serves-members');
@@ -144,17 +161,28 @@ export async function labelSeveral(engine: BrainEngine, roster: string[], source
receipt.completed.push('rules');
abortAfter('serves-rules');
for (const k of receipt.keys.filter(x => x.action === 'mint')) {
- const minted = await mintToken(engine, k.token_name, { scopes: ['read', 'write'], binding: { member: k.member } });
- writeKeyFile(k.path, minted.token);
+ const minted = await mintToken(engine, k.token_name, { scopes: ['read', 'write'], binding: { member: k.member },
+ ...(sourceId === 'default' ? {} : { sources: { kind: 'scalar' as const, writeSource: sourceId } }) });
+ try {
+ writeKeyFile(k.path, minted.token);
+ } catch (e) {
+ await engine.executeRaw('UPDATE access_tokens SET revoked_at = now() WHERE id = $1 AND revoked_at IS NULL', [minted.id]);
+ throw e;
+ }
abortAfter('serves-key');
}
receipt.completed.push('keys');
+ if (receipt.config.action === 'write') await engine.setConfig(SERVES_KEY, 'several');
+ receipt.completed.push('config');
+ receipt.unlabeled = await unlabeledOutside(engine, sourceId, receipt.rules);
} catch (e) {
receipt.error = { code: (e as { code?: string }).code ?? 'internal_error', message: e instanceof Error ? e.message : String(e) };
}
return receipt;
}
+const ruleWritePending = (r: ServesReceipt): boolean => !!r.rule_write && r.rule_write.state !== 'applied' && r.rule_write.state !== 'unchanged';
+
export function receiptLines(r: ServesReceipt): string[] {
const verb = (a: string) => (r.applied ? { add: 'added', mint: 'minted', write: 'written', keep: 'kept', blocked: 'BLOCKED' } : { add: 'will add', mint: 'will mint', write: 'will write', keep: 'keep', blocked: 'BLOCKED' })[a] ?? a;
return [
@@ -164,12 +192,14 @@ export function receiptLines(r: ServesReceipt): string[] {
...r.rules.map(x => ` rule ${x.prefix} readable by ${x.readers.map(p => p.replace(/^member:/, '')).join(', ')} (${verb(x.action)})${x.detail ? `: ${x.detail}` : ''}`),
...(r.rule_write ? [` ${r.rule_write.store} store, revision ${r.rule_write.revision ?? '-'} ${r.rule_write.state}${r.rule_write.git_commit ? `, committed ${r.rule_write.git_commit.slice(0, 12)}` : ''}`] : []),
...r.keys.map(k => ` key ${k.member}: ${k.path} (${verb(k.action)}${k.action === 'blocked' ? '' : ', 0600'}; token ${k.token_name})${k.detail ? `: ${k.detail}` : ''}`),
+ ...(ruleWritePending(r) ? [` The rules are not enforced yet: finish with gbrain access resume --source ${r.source_id}`] : []),
+ ...r.unlabeled.map(u => ` unlabeled ${u.source}:${u.prefix} (${u.pages} page(s)) has no folder rule, so every member reads it: name its readers with gbrain access rule add --prefix ${u.prefix} --readers <list> --source ${u.source}, or add the person with --members`),
...(r.error ? [`Stopped: ${r.error.message}`, ` Finished before it stopped: ${r.completed.join(', ') || 'nothing'}. Every step is idempotent: run the same command again to finish.`] : []),
- ...(r.applied ? [] : ['Nothing written. Add --yes to apply.']),
+ ...(r.applied ? [] : [blocked(r) ? 'Nothing written: fix each BLOCKED line, then run this again.' : 'Nothing written. Add --yes to apply.']),
];
}
-export const receiptOk = (r: ServesReceipt): boolean => !r.error && [...r.members, ...r.rules, ...r.keys].every(x => x.action !== 'blocked');
+export const receiptOk = (r: ServesReceipt): boolean => !r.error && !blocked(r) && !ruleWritePending(r) && (!r.applied || r.unlabeled.length === 0);
export async function runAccessServes(engine: BrainEngine, mode: string | undefined, args: string[], json: boolean, flagValue: (args: string[], name: string) => string | undefined): Promise<void> {
if (mode === undefined) {
diff --git a/src/commands/auth-mint.ts b/src/commands/auth-mint.ts
index f8f2c70ca2..e0e508c8e1 100644
--- a/src/commands/auth-mint.ts
+++ b/src/commands/auth-mint.ts
@@ -6,12 +6,13 @@
import type { BrainEngine } from '../core/engine.ts';
import { generateToken, hashToken } from '../core/utils.ts';
import { insertUnifiedToken } from '../core/token-mint.ts';
+import type { GrantSources } from '../core/grants/model.ts';
import { setTokenMinTrust } from '../core/trust/min-trust.ts';
import type { TrustTier } from '../core/trust/tier.ts';
import { bindCredential, type BindingPatch, type BindingResult } from '../core/access/members.ts';
import { checkBindingTarget } from './auth-binding.ts';
-export interface MintTokenOpts { takesHolders?: string[]; scopes?: string[]; minTrust?: TrustTier; binding?: BindingPatch | null }
+export interface MintTokenOpts { takesHolders?: string[]; scopes?: string[]; minTrust?: TrustTier; binding?: BindingPatch | null; sources?: GrantSources }
export interface MintedToken { token: string; id: string; takesHolders: string[]; bound: BindingResult | null }
export async function mintToken(engine: BrainEngine, name: string, opts: MintTokenOpts = {}): Promise<MintedToken> {
@@ -26,7 +27,7 @@ export async function mintToken(engine: BrainEngine, name: string, opts: MintTok
// grandfathered full-access grant.
const [row] = await insertUnifiedToken(engine, {
name, tokenHash: hashToken(token), ...(opts.scopes !== undefined ? { scopes: opts.scopes } : {}),
- grant: { sources: { kind: 'default' }, takesHolders, allowedOperations: null },
+ grant: { sources: opts.sources ?? { kind: 'default' }, takesHolders, allowedOperations: null },
});
// #5575 (CEO-18): the read floor; the CLI is the only writer of it.
if (opts.minTrust) await setTokenMinTrust(engine, row!.id, opts.minTrust);
diff --git a/src/commands/doctor/checks/unlabeled-people-folders.ts b/src/commands/doctor/checks/unlabeled-people-folders.ts
index 5dfcc1cb44..83c10481b8 100644
--- a/src/commands/doctor/checks/unlabeled-people-folders.ts
+++ b/src/commands/doctor/checks/unlabeled-people-folders.ts
@@ -8,8 +8,7 @@
import type { Check } from '../../doctor.ts';
import { agentFix, checkError, infoCheck } from '../check-fix.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
-import { appliedRules } from '../../../core/access/policy.ts';
-import { brainServes } from '../../../core/access/serves.ts';
+import { brainServes, unlabeledPeopleFolders } from '../../../core/access/serves.ts';
const NAME = 'unlabeled_people_folders';
@@ -22,16 +21,7 @@ async function runUnlabeledPeopleFolders(ctx: DoctorContext): Promise<Check[]> {
checks.push(infoCheck(NAME, 'Not applicable: this brain serves one person (fewer than two enabled members and no access.serves = several).', 'not_applicable'));
return checks;
}
- const folders = await engine.executeRaw<{ source_id: string; folder: string; pages: number }>(
- `SELECT source_id, split_part(slug, '/', 2) AS folder, count(*)::int AS pages FROM pages
- WHERE deleted_at IS NULL AND slug LIKE 'people/%/%' GROUP BY 1, 2 ORDER BY 1, 2`);
- const rulesBySource = new Map<string, string[]>();
- const unlabeled: Array<{ source: string; prefix: string; pages: number }> = [];
- for (const f of folders) {
- if (!rulesBySource.has(f.source_id)) rulesBySource.set(f.source_id, (await appliedRules(engine, f.source_id)).map(r => r.prefix));
- const prefix = `people/${f.folder}/`;
- if (!rulesBySource.get(f.source_id)!.some(p => p === prefix || p === 'people/')) unlabeled.push({ source: f.source_id, prefix, pages: Number(f.pages) });
- }
+ const unlabeled = await unlabeledPeopleFolders(engine);
const why = view.from === 'config' ? 'config access.serves is several' : `it has ${view.enabled_members.length} enabled members`;
if (!unlabeled.length) {
checks.push({ name: 'unlabeled_people_folders', status: 'ok', details: { serves: view, folders: [] }, message: `This brain serves several people (${why}), and every people/<name>/ folder with pages has a folder rule naming its readers.` });
diff --git a/src/commands/setup-serves.ts b/src/commands/setup-serves.ts
index 03379682d9..24b8ec920a 100644
--- a/src/commands/setup-serves.ts
+++ b/src/commands/setup-serves.ts
@@ -3,23 +3,23 @@
* write here is a child of the absolute launcher (as `gbrain init` is):
*
* - `gbrain access serves --json` reads whether the brain serves several people, its owner and the member the
- * stdio server reads as. A one-person setup (the default) on a brain that serves several people refuses
- * (setup_serves_several) unless the stdio connection it writes is bound: to config mcp.stdio_member, or to the
- * owner (access.owner_member), which setup then writes as mcp.stdio_member.
+ * stdio server 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 the stdio connection
+ * it writes is bound: to config mcp.stdio_member, or to the owner (access.owner_member), which setup then writes
+ * as mcp.stdio_member. 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
- * (`gbrain find people/ --as <member> --json`): each sees its own folder and world pages, never another
- * member's folder.
+ * per other member (`gbrain find people/<other>/ --as <member> --json`): none returns a page.
*/
import { opError, OperationError } from '../core/ops/contract.ts';
import { readRoster, rosterEmpty, type ServesReceipt, type ServesStatus, receiptLines, receiptOk } from './access-serves.ts';
export interface ServesFlags { serves?: 'one' | 'several'; members?: string; membersFile?: string; source?: string; dryRun: boolean }
-export interface ProofLine { member: string; own: number; world: number; leaked: string[] }
+export interface ProofLine { member: string; own: number; leaked: string[] }
export interface ServesOutcome {
mode: 'one' | 'several';
- /** Whether the brain serves several people once this run is done: the brain-first text follows it. */
+ /** 'several' once the brain serves several people and this harness's connection is bound: the brain-first text follows it. */
brain_serves: 'one' | 'several';
note?: string;
receipt?: ServesReceipt;
@@ -49,22 +49,31 @@ export function servesRoster(flags: ServesFlags, harness: string): string[] | Op
}
}
-/** The brain's serves view through a child, or null when there is no brain yet or the child cannot read it. */
-export function readServesStatus(launcher: string): ServesStatus | null {
+/** The brain's serves view through a child, or the child's error when it cannot read the brain. */
+export function readServesStatus(launcher: string): { status: ServesStatus } | { error: string } {
const r = child(launcher, ['access', 'serves', '--json']);
- return r.ok ? parsed<ServesStatus>(r.stdout) : null;
+ const status = r.ok ? parsed<ServesStatus>(r.stdout) : null;
+ return status && 'serves' in status ? { status } : { error: (r.stderr || r.stdout).trim() || 'gbrain access serves --json printed nothing' };
+}
+
+export function servesUnreadable(error: string, harness: string): OperationError {
+ return opError('setup_serves_unreadable', `Setup could not read whether this brain serves several people (${error.split('\n')[0]}), so it cannot tell whether the ${harness} connection would read for everyone. Nothing was written.`,
+ 'Run gbrain access serves --json to see why the brain cannot be read, fix that, then run setup again.',
+ { fix: { argv: ['gbrain', 'access', 'serves', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: shows whom the brain serves, or the error that stops setup reading it.' } });
}
/** The refusal for a one-person setup that would write an unbound connection on a brain that serves several people. */
export function servesOneRefusal(status: ServesStatus | null, harness: string): OperationError | null {
if (!status || status.serves !== 'several' || status.stdio_member || status.owner) return null;
const why = status.from === 'config' ? 'config access.serves is several' : `it has ${status.enabled_members.length} enabled members (${status.enabled_members.join(', ')})`;
- const argv = ['gbrain', 'setup', harness, '--serves', 'several', '--members', status.enabled_members.join(',') || '<id,...>'];
+ const labelled = status.from === 'config';
+ const argv = labelled ? ['gbrain', 'config', 'set', 'mcp.stdio_member', '<member>'] : ['gbrain', 'setup', harness, '--serves', 'several', '--members', status.enabled_members.join(',') || '<id,...>'];
return opError('setup_serves_several',
`This brain serves several people (${why}), and the ${harness} connection setup would write is bound to nobody, so it would read every page no rule restricts for whoever asks. Nothing was written.`,
- `Run ${argv.join(' ')} to label each person, or name the owner first (gbrain access owner set <member>) so this harness reads as the owner.`,
+ labelled ? `Bind this harness to the person it serves with ${argv.join(' ')} (or name the owner: gbrain access owner set <member>), then run setup again.`
+ : `Run ${argv.join(' ')} to label each person, or name the owner first (gbrain access owner set <member>) so this harness reads as the owner.`,
{ fix: { argv, consent: ['credentials'], actor: 'user', ask_user: true, requires_exclusive: false,
- why: 'Adds a member, a folder only that member reads and a bound key for each person, and binds this harness to the owner when one is named.',
+ why: labelled ? 'Makes the local stdio server read as that member; the user picks who it serves.' : 'Adds a member, a folder only that member reads and a bound key for each person, and binds this harness to the owner when one is named.',
verify: { argv: ['gbrain', 'access', 'serves', '--json'] } } });
}
@@ -73,16 +82,23 @@ function runServesSeveral(launcher: string, roster: string[], flags: ServesFlags
const r = child(launcher, ['access', 'serves', 'several', '--members', roster.join(','), ...(flags.source ? ['--source', flags.source] : []), ...(flags.dryRun ? [] : ['--yes']), '--json']);
const receipt = parsed<ServesReceipt>(r.stdout);
if (!receipt || !('members' in receipt)) return { mode: 'several', error: (r.stderr || r.stdout).trim() || 'gbrain access serves several failed' };
- if (flags.dryRun || receipt.error) return { mode: 'several', receipt };
+ if (flags.dryRun || receipt.error || !receipt.applied) return { mode: 'several', receipt };
+ const source = flags.source ? ['--source-id', flags.source] : [];
+ const read = (member: string, prefix: string, limit: number) => {
+ const found = child(launcher, ['find', prefix, '--as', member, '--limit', String(limit), ...source, '--json']);
+ return { pages: parsed<{ pages?: Array<{ slug: string }> }>(found.stdout)?.pages, error: (found.stderr || found.stdout).trim() };
+ };
const proof: ProofLine[] = [];
for (const member of roster) {
- const found = child(launcher, ['find', 'people/', '--as', member, '--limit', '500', ...(flags.source ? ['--source-id', flags.source] : []), '--json']);
- const pages = parsed<{ pages?: Array<{ slug: string }> }>(found.stdout)?.pages;
- if (!pages) return { mode: 'several', receipt, proof, error: `the bound read as ${member} failed: ${(found.stderr || found.stdout).trim()}` };
- const others = roster.filter(m => m !== member).map(m => `people/${m}/`);
- proof.push({ member, own: pages.filter(p => p.slug.startsWith(`people/${member}/`)).length,
- world: pages.filter(p => !roster.some(m => p.slug.startsWith(`people/${m}/`))).length,
- leaked: pages.map(p => p.slug).filter(s => others.some(o => s.startsWith(o))) });
+ const own = read(member, `people/${member}/`, 500);
+ if (!own.pages) return { mode: 'several', receipt, proof, error: `the bound read as ${member} failed: ${own.error}` };
+ const leaked: string[] = [];
+ for (const other of roster.filter(m => m !== member)) {
+ const seen = read(member, `people/${other}/`, 20);
+ if (!seen.pages) return { mode: 'several', receipt, proof, error: `the bound read as ${member} failed: ${seen.error}` };
+ leaked.push(...seen.pages.map(p => p.slug));
+ }
+ proof.push({ member, own: own.pages.length, leaked });
}
return { mode: 'several', receipt, proof };
}
@@ -100,7 +116,9 @@ export function servesPreflight(flags: ServesFlags, launcher: string, harness: s
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.',
`Quit the ${harness} session that started it, then run setup again.`, { reason: 'live_serve', docs: 'docs/guides/repair.md#setup-owner-conflict' });
}
- const status = hasBrain && !liveOurs ? readServesStatus(launcher) : null;
+ const read = hasBrain && !liveOurs ? readServesStatus(launcher) : null;
+ if (read && 'error' in read) return servesUnreadable(read.error, harness);
+ const status = read?.status ?? null;
if (flags.serves === 'several') return { roster, status };
const refusal = servesOneRefusal(status, harness);
return refusal ?? { roster, status };
@@ -111,17 +129,21 @@ export function servesApply(flags: ServesFlags, launcher: string, plan: ServesPl
const several = flags.serves === 'several';
const labelled = !several ? null : hasBrain || !flags.dryRun ? runServesSeveral(launcher, plan.roster, flags)
: { 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 status = several && !flags.dryRun ? readServesStatus(launcher) : plan.status;
+ const reread = several && !flags.dryRun ? readServesStatus(launcher) : null;
+ const status = reread ? ('status' in reread ? reread.status : null) : plan.status;
const stdio = bindStdioToOwner(launcher, several && !status ? { serves: 'several', from: 'config', enabled_members: plan.roster, owner: null, stdio_member: null } : status, flags.dryRun);
if (!labelled && !stdio) return null;
- return { ...(labelled ?? { mode: 'one' as const }), brain_serves: several || status?.serves === 'several' ? 'several' : 'one', ...(stdio ? { stdio } : {}) };
+ 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}` } : {}) };
+ const bound = !!stdio && stdio.action !== 'unbound';
+ return { ...outcome, brain_serves: bound && servesOk(outcome) ? 'several' : 'one' };
}
/** Binds this harness's stdio server to the owner on a brain that serves several people, when nothing binds it yet. */
export function bindStdioToOwner(launcher: string, status: ServesStatus | null, 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.owner) return { member: null, action: 'unbound', detail: 'this harness reads as nobody in particular: name the owner (gbrain access owner set <member>) and run setup again to bind it' };
+ if (!status.owner) return { member: null, action: 'unbound', detail: 'this harness reads as nobody in particular (only pages no rule restricts), so its instructions keep the one-person scoping lines: bind it with gbrain config set mcp.stdio_member <member> or name the owner (gbrain access owner set <member>), then run setup again' };
if (!dryRun) {
const r = child(launcher, ['config', 'set', 'mcp.stdio_member', status.owner]);
if (!r.ok) return { member: null, action: 'unbound', detail: `gbrain config set mcp.stdio_member ${status.owner} failed: ${r.stderr.trim()}` };
@@ -138,7 +160,7 @@ export function servesLines(o: ServesOutcome, dryRun: boolean): string[] {
...(o.receipt ? receiptLines(o.receipt).filter(l => !(dryRun && l.startsWith('Nothing written'))) : []),
...(o.proof ?? []).map(p => p.leaked.length
? ` proof ${p.member} reads pages of another member's folder: ${p.leaked.join(', ')}`
- : ` proof a read bound to ${p.member} sees its own folder (${p.own} page(s)) and ${p.world} world page(s) under people/, and no other member's folder`),
+ : ` proof a read bound to ${p.member} sees its own folder (${p.own} page(s)) and no page of another member's folder`),
...(o.stdio ? [` stdio ${o.stdio.detail}`] : []),
...(o.note ? [` labels ${o.note}`] : []),
...(o.error ? [` error ${o.error}`] : []),
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index f764d85c4e..faca86017d 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -47,7 +47,7 @@ import { claudeUserSettingsPath, type ClaudeHookEvent } from '../core/bootstrap/
import { readHarnessReceiptState } from '../core/bootstrap/format.ts';
import { smokeStdioRegistration } from './doctor/checks/harness-wiring.ts';
import { finishFreshSetupMigrations } from './setup-migrations.ts';
-import { servesApply, servesLines, servesOk, servesPreflight, type ServesOutcome } from './setup-serves.ts';
+import { readServesStatus, servesApply, servesLines, servesOk, servesPreflight, type ServesOutcome } from './setup-serves.ts';
import type { McpSurface } from '../mcp/surface.ts';
import {
SETUP_CAPABILITIES,
@@ -869,6 +869,15 @@ function describeInstructions(o: BrainFirstOutcome, dryRun: boolean): string {
return `${describeBrainFirstOutcome(o, dryRun)} [${o.decision.source}; ${how}]`;
}
+/** --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();
+ const read = launcher && launcher.startsWith('/') ? readServesStatus(launcher) : null;
+ const ok = !!read && 'status' in read && read.status.serves === 'several' && !!read.status.stdio_member;
+ if (!ok) process.stderr.write('gbrain setup: --serves several: this brain does not serve several people with a bound stdio server, so the instructions keep the one-person scoping lines.\n');
+ return ok;
+}
+
/**
* `--instructions-only`, and the harnesses whose MCP registration setup does
* not write (opencode, openclaw, hermes, cursor): manage the brain-first
@@ -880,7 +889,7 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>
const adapter = HARNESS_ADAPTERS.find((a) => a.id === harness)!;
const envSurface = process.env.GBRAIN_SURFACE;
const surface = flags.surface ?? (isRegistrationSurface(envSurface) ? envSurface : undefined);
- const access: BrainFirstAccess = { kind: 'mcp', server: flags.name, ...(surface ? { surface } : {}), ...(flags.serves === 'several' ? { serves: 'several' as const } : {}) };
+ 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 };
if (!isBrainFirstHarness(harness)) {
const pasted: BrainFirstAccess = adapter.connection === 'thin-cli' ? { kind: 'cli', launcher: flags.gbrainBin ?? 'gbrain' } : access;
diff --git a/src/core/access/serves.ts b/src/core/access/serves.ts
index bfc9064e5b..fa17daea7b 100644
--- a/src/core/access/serves.ts
+++ b/src/core/access/serves.ts
@@ -7,6 +7,7 @@
* Everything lives in the database, so a repo-less brain gets it unchanged.
*/
import type { BrainEngine } from '../engine.ts';
+import { appliedRules } from './policy.ts';
export const SERVES_KEY = 'access.serves';
@@ -24,3 +25,20 @@ export async function brainServes(engine: Pick<BrainEngine, 'getConfig' | 'execu
if (explicit === 'one' || explicit === 'several') return { serves: explicit, from: 'config', enabled_members: members };
return { serves: members.length >= 2 ? 'several' : 'one', from: 'members', enabled_members: members };
}
+
+export interface PeopleFolder { source: string; prefix: string; pages: number }
+
+/** Top-level people/<x>/ folders holding pages that no applied rule covers (a rule on people/<x>/ or on people/). */
+export async function unlabeledPeopleFolders(engine: Pick<BrainEngine, 'executeRaw'>): Promise<PeopleFolder[]> {
+ const folders = await engine.executeRaw<{ source_id: string; folder: string; pages: number }>(
+ `SELECT source_id, split_part(slug, '/', 2) AS folder, count(*)::int AS pages FROM pages
+ WHERE deleted_at IS NULL AND slug LIKE 'people/%/%' GROUP BY 1, 2 ORDER BY 1, 2`);
+ const rulesBySource = new Map<string, string[]>();
+ const unlabeled: PeopleFolder[] = [];
+ for (const f of folders) {
+ if (!rulesBySource.has(f.source_id)) rulesBySource.set(f.source_id, (await appliedRules(engine, f.source_id)).map(r => r.prefix));
+ const prefix = `people/${f.folder}/`;
+ if (!rulesBySource.get(f.source_id)!.some(p => p === prefix || p === 'people/')) unlabeled.push({ source: f.source_id, prefix, pages: Number(f.pages) });
+ }
+ return unlabeled;
+}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 7cd4494f6b..7a46fb7933 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -723,6 +723,7 @@ export const CODES = {
setup_hosted_connection: { class: 'caller', summary: "This machine already reaches a hosted brain, so gbrain setup will not create a second, local brain.", why: 'A new local brain would split memory: sessions would read and write the empty local brain while useful memory stays on the hosted one.', docs: 'docs/guides/repair.md#setup-hosted-connection', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which brain the harness registration reaches.' } },
setup_owner_conflict: { class: 'caller', summary: "Another owner holds what gbrain setup would change: a live server owns this PGLite brain, or the harness configuration holds an entry setup did not write.", why: 'A PGLite brain has one writer, so a second server would fail on its lock; an entry setup did not record by hash is the user\'s or another install\'s and is never overwritten.', reasons: ['live_serve', 'unowned_entry', 'other_install', 'harness_lane'], docs: 'docs/guides/repair.md#setup-owner-conflict', fix: { argv: ['gbrain', 'setup', 'claude-code', '--dry-run', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the resolved target and which owner blocks it, without writing anything.' } },
setup_serves_several: { class: 'caller', summary: 'gbrain setup for one person was run on a brain that serves several people, and the stdio connection it would write is bound to nobody, so setup wrote nothing.', why: 'On a brain that serves several people an unbound connection reads every page no rule restricts, for whoever is asking; setup never writes one.', suggestion: 'Run gbrain setup <harness> --serves several --members <id,...> to label each person, or name the brain owner first (gbrain access owner set <member>) so this harness reads as the owner.', fix: { argv: ['gbrain', 'access', 'serves', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: shows why the brain counts as several people, its members, its owner and the member the stdio server reads as.' } },
+ setup_serves_unreadable: { class: 'caller', summary: 'gbrain setup could not read whether the existing brain serves several people, so it wrote nothing.', why: 'Setup writes an unbound connection only on a brain it knows serves one person; a brain it cannot read might serve several.', suggestion: 'Run gbrain access serves --json to see why the brain cannot be read, fix that, then run setup again.', fix: { argv: ['gbrain', 'access', 'serves', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: shows whom the brain serves, or the error that stops setup reading it.' } },
hook_session_cwd: { class: 'caller', summary: "A gbrain hook or stdio MCP entry (setup, the turn-rule lane, gbrain bootstrap's lanes) starts gbrain in the session's directory, or the hook launcher it names would not run.", why: 'Script-mode gbrain is a Bun script, and Bun runs the working directory\'s bunfig.toml preload and loads its .env before gbrain starts; harnesses run hooks and stdio MCP servers in the session directory, so a cloned repository could run code on every prompt or session.', reasons: ['session_cwd', 'missing', 'stale', 'foreign'], docs: 'docs/guides/repair.md#hook-session-cwd', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Names the hook and the setup command that rewrites it through the launcher.' } },
turn_hook_not_loaded: { class: 'caller', summary: "The per-turn hook that puts \"check gbrain first\" next to every user turn is missing, untrusted, or does not load in the harness.", why: 'Agents use the brain when that rule reaches them on every turn; registering the MCP server or writing an instruction file alone leaves them answering without it.', reasons: ['missing', 'untrusted', 'hook_failed', 'no_rule', 'not_loaded'], docs: 'docs/guides/repair.md#turn-hook-not-loaded', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which harness has no working per-turn hook and the command that wires it.' } },
shared_skills_unavailable: { class: 'unavailable', summary: "The shared-skills operation was refused." },
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 9ad3edd7da..c65c4b9d0c 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6841,7 +6841,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_invalid\" | \"commit_paths_skipped\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"setup_serves_several\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_catalog_mismatch\" | \"skill_catalog_too_large\" | \"skill_catalog_unknown\" | \"skill_index_incompatible\" | \"skill_index_locked\" | \"skill_index_missing\" | \"skill_index_removed\" | \"skill_resolve_invalid_input\" | \"skill_resolve_no_input\" | \"skill_resolve_timeout\" | \"skill_resolver_config_invalid\" | \"skill_resolver_config_unreadable\" | \"skill_resolver_setup_incomplete\" | \"skill_resolver_internal\" | \"skill_source_invalid\" | \"skill_source_unreadable\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_invalid\" | \"commit_paths_skipped\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"setup_serves_several\" | \"setup_serves_unreadable\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_catalog_mismatch\" | \"skill_catalog_too_large\" | \"skill_catalog_unknown\" | \"skill_index_incompatible\" | \"skill_index_locked\" | \"skill_index_missing\" | \"skill_index_removed\" | \"skill_resolve_invalid_input\" | \"skill_resolve_no_input\" | \"skill_resolve_timeout\" | \"skill_resolver_config_invalid\" | \"skill_resolver_config_unreadable\" | \"skill_resolver_setup_incomplete\" | \"skill_resolver_internal\" | \"skill_source_invalid\" | \"skill_source_unreadable\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/setup-serves-several.test.ts b/test/setup-serves-several.test.ts
index 232bc098e1..76b3b99e94 100644
--- a/test/setup-serves-several.test.ts
+++ b/test/setup-serves-several.test.ts
@@ -18,7 +18,7 @@
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -29,7 +29,8 @@ import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
import { sqlQueryForEngine } from '../src/core/sql-query.ts';
import { noGrantFederatedScope } from '../src/core/source-resolver.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
-import { labelSeveral, type ServesReceipt } from '../src/commands/access-serves.ts';
+import { labelSeveral, receiptOk, servesStatus, type ServesReceipt } from '../src/commands/access-serves.ts';
+import { addMember } from '../src/core/access/members.ts';
import { unlabeledPeopleFoldersEntry } from '../src/commands/doctor/checks/unlabeled-people-folders.ts';
import type { DoctorContext } from '../src/commands/doctor/context.ts';
import { addFolderRules } from '../src/commands/access-rules.ts';
@@ -111,7 +112,8 @@ for (const kind of testBackends()) {
test('labels each person: members, folder rules, a bound read-write key per member in a 0600 file outside git', async () => {
const r = await label(ROSTER);
expect(r.error).toBeUndefined();
- expect(r.completed).toEqual(['config', 'members', 'rules', 'keys']);
+ expect(r.completed).toEqual(['members', 'rules', 'keys', 'config']);
+ expect(r.unlabeled).toEqual([]);
expect(r.members.map(m => m.action)).toEqual(['add', 'add']);
expect(r.rules.map(x => [x.prefix, x.readers, x.action])).toEqual([['people/alice-example/', ['member:alice-example'], 'add'], ['people/bob-example/', ['member:bob-example'], 'add']]);
expect(r.rule_write).toMatchObject({ store: 'database', state: 'applied' });
@@ -156,7 +158,7 @@ for (const kind of testBackends()) {
const roster = [...ROSTER, 'erin-example', 'finn-example'];
const stopped = await label(roster, { GBRAIN_SETUP_ABORT_AFTER: 'serves-key' });
expect(stopped.error?.message).toContain('serves-key');
- expect(stopped.completed).toEqual(['config', 'members', 'rules']);
+ expect(stopped.completed).toEqual(['members', 'rules']);
const keyDir = join(home, '.gbrain', 'member-keys');
expect(existsSync(join(keyDir, 'erin-example.key'))).toBe(true);
expect(existsSync(join(keyDir, 'finn-example.key'))).toBe(false);
@@ -179,6 +181,87 @@ for (const kind of testBackends()) {
});
}
+describe('labelling refuses or reports what it cannot make safe (pglite, repo-less)', () => {
+ let engine: BrainEngine;
+ let home: string;
+ const label = (roster: string[], gbrainHome?: string, sourceId = 'default') => withEnv({ GBRAIN_HOME: gbrainHome ?? home, GBRAIN_SETUP_ABORT_AFTER: undefined }, () => labelSeveral(engine, roster, sourceId, true, true));
+ const liveToken = async (name: string) => (await engine.executeRaw<{ source_grant: string }>('SELECT source_grant FROM access_tokens WHERE name = $1 AND revoked_at IS NULL', [name]))[0];
+ const memberCount = async (id: string) => Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM access_members WHERE id = $1', [id]))[0]!.n);
+ beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema();
+ home = tempDir('gbrain-serves-refuse-');
+ }, 120_000);
+ afterAll(async () => { await engine?.disconnect(); }, 60_000);
+
+ test('a key directory inside a git work tree, or linked into one, refuses before anything is written', async () => {
+ const repo = tempDir('gbrain-serves-git-');
+ execFileSync('git', ['init', '-q', repo]);
+ mkdirSync(join(repo, 'brain-home'));
+ const linked = join(tempDir('gbrain-serves-link-'), 'home');
+ symlinkSync(join(repo, 'brain-home'), linked);
+ for (const gbrainHome of [repo, linked]) {
+ await expect(label(['kim-example'], gbrainHome)).rejects.toMatchObject({ code: 'access_serves_key_dir_in_git' });
+ }
+ expect(await memberCount('kim-example')).toBe(0);
+ expect(await engine.getConfig('access.serves')).toBeFalsy();
+ expect(existsSync(join(repo, 'brain-home', '.gbrain', 'member-keys'))).toBe(false);
+ }, 60_000);
+
+ test('an existing rule that lets someone else read a folder blocks the whole run, and nothing is written', async () => {
+ for (const m of ['lee-example', 'mia-example']) await addMember(engine, m);
+ await addFolderRules(engine, 'default', [{ id: 'people-lee-example', prefix: 'people/lee-example/', readable_by: ['member:lee-example', 'member:mia-example'] }], { apply: true, json: true });
+ const r = await label(['lee-example', 'mia-example']);
+ expect(r.applied).toBe(false);
+ expect(receiptOk(r)).toBe(false);
+ expect(r.rules.find(x => x.prefix === 'people/lee-example/')).toMatchObject({ action: 'blocked' });
+ expect(r.rules.find(x => x.prefix === 'people/lee-example/')!.detail).toContain('mia-example');
+ expect(await liveToken('member-mia-example')).toBeUndefined();
+ expect(await engine.getConfig('access.serves')).toBeFalsy();
+ }, 60_000);
+
+ test('a key file that does not hold the live key is BLOCKED, never reported as kept', async () => {
+ expect((await label(['nia-example'])).keys[0]!.action).toBe('mint');
+ writeFileSync(join(home, '.gbrain', 'member-keys', 'nia-example.key'), 'gbrain_notthelivekey\n', { mode: 0o600 });
+ const r = await label(['nia-example']);
+ expect(r.keys[0]).toMatchObject({ action: 'blocked' });
+ expect(r.keys[0]!.detail).toContain('does not hold the live key member-nia-example');
+ }, 60_000);
+
+ test('a key file that cannot be written revokes the key it just minted, and the next run mints a new one', async () => {
+ const path = join(home, '.gbrain', 'member-keys', 'oli-example.key');
+ mkdirSync(join(path, 'in-the-way'), { recursive: true });
+ const r = await label(['oli-example']);
+ expect(r.error).toBeDefined();
+ expect(r.completed).toEqual(['members', 'rules']);
+ expect(await liveToken('member-oli-example')).toBeUndefined();
+ rmSync(path, { recursive: true });
+ const again = await label(['oli-example']);
+ expect(again.error).toBeUndefined();
+ expect(again.keys[0]!.action).toBe('mint');
+ }, 60_000);
+
+ test('keys minted for a named source are granted that source', async () => {
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', ['team']);
+ const r = await label(['pat-example'], undefined, 'team');
+ expect(r.error).toBeUndefined();
+ expect(await liveToken('member-pat-example')).toMatchObject({ source_grant: 'scalar' });
+ }, 60_000);
+
+ test('people folders no rule covers are reported, and the run is not ok', async () => {
+ await importFromContent(engine, 'people/quinn-example/notes', pageText('people/quinn-example/notes', 'quinncanary'), { sourceId: 'default', noEmbed: true });
+ const r = await label(['ray-example']);
+ expect(r.error).toBeUndefined();
+ expect(r.unlabeled).toEqual([{ source: 'default', prefix: 'people/quinn-example/', pages: 1 }]);
+ expect(receiptOk(r)).toBe(false);
+ }, 60_000);
+
+ test('an owner or stdio member who is not an enabled member does not count as binding the connection', async () => {
+ await engine.setConfig('access.owner_member', 'zed-example');
+ await engine.setConfig('mcp.stdio_member', 'zed-example');
+ expect(await servesStatus(engine)).toMatchObject({ owner: null, stdio_member: null });
+ }, 60_000);
+});
+
const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');
const CLEAN = { CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: undefined, GBRAIN_SOURCE: undefined, GBRAIN_SURFACE: undefined, GBRAIN_HOOKS: undefined, GBRAIN_SETUP_ABORT_AFTER: undefined };
interface Box { root: string; home: string; bin: string }
@@ -217,17 +300,48 @@ describe('gbrain setup --serves (spawned, PGLite)', () => {
const key = readFileSync(join(b.home, '.gbrain', 'member-keys', `${m}.key`), 'utf8').trim();
expect(first.stdout + first.stderr).not.toContain(key);
expect(first.stdout).toContain(`key ${m}: ${join(b.home, '.gbrain', 'member-keys', `${m}.key`)} (minted, 0600; token member-${m})`);
- expect(first.stdout).toContain(`proof a read bound to ${m} sees its own folder (1 page(s)) and 1 world page(s) under people/, and no other member's folder`);
+ expect(first.stdout).toContain(`proof a read bound to ${m} sees its own folder (1 page(s)) and no page of another member's folder`);
}
expect(first.stdout).toContain('stdio this harness reads as nobody in particular');
- expect(claudeMd(b)).toContain(`- ${SERVES_SEVERAL_LINE}`);
+ expect(claudeMd(b)).not.toContain(SERVES_SEVERAL_LINE);
+ expect(claudeMd(b)).toContain('apply your own access rules to what comes back');
const again = await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example', '--json']);
expect(again.exitCode).toBe(0);
expect(again.doc.serves.receipt.keys.map((k: any) => k.action)).toEqual(['keep', 'keep']);
expect(again.doc.serves.proof).toEqual([
- { member: 'alice-example', own: 1, world: 1, leaked: [] },
- { member: 'bob-example', own: 1, world: 1, leaked: [] },
+ { member: 'alice-example', own: 1, leaked: [] },
+ { member: 'bob-example', own: 1, leaked: [] },
]);
+ expect(again.doc.serves.brain_serves).toBe('one');
+ expect((await gbrain(b, ['access', 'owner', 'set', 'alice-example'])).exitCode).toBe(0);
+ const bound = await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example', '--json']);
+ expect(bound.exitCode).toBe(0);
+ expect(bound.doc.serves).toMatchObject({ brain_serves: 'several', stdio: { member: 'alice-example', action: 'write' } });
+ expect(claudeMd(b)).toContain(`- ${SERVES_SEVERAL_LINE}`);
+ }, 360_000);
+
+ 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);
+ const broken = join(b.root, 'bin', 'gbrain-unreadable');
+ writeFileSync(broken, `#!/bin/sh
+if [ "$1" = access ] && [ "$2" = serves ]; then echo 'the brain is locked' >&2; exit 1; fi
+exec '${process.execPath}' --no-env-file '${CLI}' "$@"
+`);
+ chmodSync(broken, 0o755);
+ const r = await gbrain(b, ['setup', 'claude-code', '--json', '--gbrain-bin', broken]);
+ expect(r.exitCode).not.toBe(0);
+ expect(r.stdout + r.stderr).toContain('setup_serves_unreadable');
+ expect(existsSync(join(b.home, '.claude.json'))).toBe(false);
+ }, 240_000);
+
+ test('--instructions-only --serves several keeps the one-person lines unless the brain serves several people with a bound stdio server', async () => {
+ const b = box();
+ expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
+ const r = await setup(b, ['claude-code', '--instructions-only', '--serves', 'several']);
+ expect(r.exitCode).toBe(0);
+ expect(r.stderr).toContain('keep the one-person scoping lines');
+ expect(claudeMd(b)).not.toContain(SERVES_SEVERAL_LINE);
}, 240_000);
test('an empty roster refuses with the fix and writes nothing', async () => {