Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Split two slow test files so none comes near CI's 300 s per-file limit (#9376)

Garry Tan238cbd5e69bd
diff --git a/changelog.d/capy-split-slow-enforced-member-tests.md b/changelog.d/capy-split-slow-enforced-member-tests.md
new file mode 100644
index 0000000000..45f1d4ee14
--- /dev/null
+++ b/changelog.d/capy-split-slow-enforced-member-tests.md
@@ -0,0 +1,7 @@
+**Two slow test files are split along their own seams, so no file comes near CI's 300-second per-file limit.** `test/enforced-member.serial.test.ts` took 185 to 191 s on a 4-vCPU machine, and CI killed it at 300 s on slow runners with no assertion failing. It is now three serial files that take at most 77 s each. `test/setup-serves-several.test.ts` took 193 to 240 s and is now three unit files that take at most 78 s each. The tests and assertions are unchanged (27 and 645, and 27 and 270), and no product code, timeout, budget or retry count changed.
+
+### Tests
+
+- `test/enforced-member.serial.test.ts` keeps the reads and refusals. Writes and the git commit-push suite move to `test/enforced-member-writes.serial.test.ts`, and the `access.enforced_member_writes` case moves to `test/enforced-member-writes-setting.serial.test.ts`. Each file seeds its own brain through `test/helpers/enforced-member-brain.ts`.
+- The spawned `gbrain setup` cases split out of `test/setup-serves-several.test.ts` into `test/setup-serves-stdio-member.test.ts` and `test/setup-serves-upgrade.test.ts`, with the shared box in `test/helpers/setup-serves-box.ts`.
+- The new serial files get rows in `scripts/serial-files.tsv`, `test/postgres-unit-arms.txt` and `scripts/postgres-arm-weights.json`. The unit and serial weight maps get no hand-added rows, because they must match the miner's metadata, so new files use the p75 estimate until the next re-mine.
diff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.json
index ea141ee49f..bade3a9a4c 100644
--- a/scripts/postgres-arm-weights.json
+++ b/scripts/postgres-arm-weights.json
@@ -88,6 +88,8 @@
"test/embed-once-per-content-version.serial.test.ts": 17930,
"test/embed-stale-images-managed-6529.test.ts": 11128,
"test/embedding-completion-atomic.serial.test.ts": 8616,
+ "test/enforced-member-writes-setting.serial.test.ts": 47833,
+ "test/enforced-member-writes.serial.test.ts": 69196,
"test/enforced-member.serial.test.ts": 180449,
"test/engine-sql-facts-keyset.test.ts": 6534,
"test/extract-all-stamp-intersection.serial.test.ts": 6869,
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index 4dd2e5e9cc..4cacaa7a16 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -8,6 +8,8 @@ test/http-db-config.serial.test.ts global-state global-state: binds HTTP listene
test/access-as.serial.test.ts global-state global-state: spawns real gbrain CLI children (src/cli.ts --as) that each open one on-disk PGLite brain and take its file lock in a temp GBRAIN_HOME; the cases seed and read that one brain in order
test/access-room-cli.serial.test.ts global-state global-state: spawns real gbrain CLI children (src/cli.ts --room) that each open one on-disk PGLite brain in a temp GBRAIN_HOME, and runs a live PGLite persistence owner on a socket in its own temp home that later cases delegate reads to
test/enforced-member.serial.test.ts global-state global-state: spawns real gbrain CLI children (src/cli.ts under GBRAIN_ENFORCED_MEMBER) that each open one on-disk PGLite brain and take its file lock in a temp GBRAIN_HOME, or one isolated Postgres database; the cases seed and read that one brain in order
+test/enforced-member-writes-setting.serial.test.ts global-state global-state: spawns real gbrain CLI children (src/cli.ts under GBRAIN_ENFORCED_MEMBER) that each open one on-disk PGLite brain and take its file lock in a temp GBRAIN_HOME, or one isolated Postgres database; the cases seed and read that one brain in order
+test/enforced-member-writes.serial.test.ts global-state global-state: spawns real gbrain CLI children (src/cli.ts under GBRAIN_ENFORCED_MEMBER) that each open one on-disk PGLite brain and take its file lock in a temp GBRAIN_HOME, or one isolated Postgres database; the cases seed and read that one brain in order
test/access-binding.serial.test.ts global-state global-state: spawns real gbrain CLI children (auth create|rescope|register-client, access member) that each open one on-disk PGLite brain and take its file lock in a temp GBRAIN_HOME; later cases read the bindings earlier ones wrote
test/admin-grant-outcome.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect; binds local servers/ports
test/advisor-backup-coverage.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_BACKUP_CHECK)
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 4eb038b235..46f05d7d32 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -384,8 +384,6 @@ test/serve-http-mcp-transport-cleanup.test.ts POST /mcp transport cleanup (#2844
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-pi-skill-extension.test.ts (file-level) 6 readFileSync
-test/setup-serves-several.test.ts gbrain setup --serves (spawned, PGLite) 11 readFileSync
-test/setup-serves-several.test.ts labelling refuses or reports what it cannot make safe (pglite, repo-less) 8 readFileSync
test/setup.test.ts gbrain setup: setup migrations on the brain it creates (Cat 41 run 4) 3 readFileSync
test/shared-skills-catalog.test.ts (file-level) 22 readFileSync
test/shared-skills-export.serial.test.ts (file-level) 15 readFileSync
diff --git a/test/enforced-member-writes-setting.serial.test.ts b/test/enforced-member-writes-setting.serial.test.ts
new file mode 100644
index 0000000000..932b30cc13
--- /dev/null
+++ b/test/enforced-member-writes-setting.serial.test.ts
@@ -0,0 +1,106 @@
+/**
+ * GST-2476 G2: enforced member mode (GBRAIN_ENFORCED_MEMBER) as real CLI subprocesses against a repo-less brain on
+ * disk (PGLite, and Postgres when DATABASE_URL is set): the access.enforced_member_writes key. Each file of the
+ * enforced member suites seeds its own brain (test/helpers/enforced-member-brain.ts).
+ *
+ * 1. Protects: refuse turns every member write away before any lookup with one constant text, refuse_pages turns page
+ * writes away, checked restores the per-page check; member reads and the trusted CLI are unchanged under each.
+ * 2. Fails when: a member write lands or names a slug under refuse, a read changes, or a trusted write is refused.
+ * 3. Existing coverage: test/enforced-member-writes-off.test.ts (the key's parsing, in process).
+ * 4. Real seams: src/cli.ts dispatch, gbrain config set, local writes.
+ */
+import { describe, expect, test } from 'bun:test';
+import { testBackends } from './helpers/test-backends.ts';
+import { enforcedMemberBrain, FIRST, leaks, MEMBER, NOTICE, PAGES, WRITES_OFF_FIRST } from './helpers/enforced-member-brain.ts';
+
+for (const kind of testBackends()) {
+ describe('enforced member mode: access.enforced_member_writes (' + kind + ', repo-less)', () => {
+ const brain = enforcedMemberBrain(kind);
+ const { cli, withBrain } = brain;
+
+ test('access.enforced_member_writes refuse: every member write refuses before any lookup, reads and the trusted CLI are unchanged', async () => {
+ const KEY = 'access.enforced_member_writes';
+ const setKey = async (value: string) => {
+ const r = await cli(['config', 'set', KEY, value], { member: null });
+ expect({ value, exit: r.exitCode, err: r.exitCode === 0 ? '' : r.stderr }).toEqual({ value, exit: 0, err: '' });
+ };
+ const page = (title: string, fm = '') => '---\ntype: note\ntitle: ' + JSON.stringify(title) + '\n' + fm + '---\n# ' + title + '\n\nHarbor ledger planning notes for the roadmap.\n';
+ const writes: Array<[string[], string | undefined]> = [
+ [['put', 'notes/writes-off-new-example'], page('Writes off new')],
+ [['put', PAGES.open.slug], page(PAGES.open.title)],
+ [['put', PAGES.other.slug], page(PAGES.other.title, 'readable_by: ["bob-example"]\n')],
+ [['link', PAGES.open.slug, PAGES.team.slug], undefined],
+ [['unlink', PAGES.open.slug, PAGES.other.slug], undefined],
+ [['tag', PAGES.open.slug, 'writes-off-tag'], undefined],
+ [['untag', PAGES.open.slug, 'writes-off-tag'], undefined],
+ [['timeline-add', PAGES.open.slug, '2026-02-01', 'Writes off event'], undefined],
+ [['remember', 'Writes off fact canaryemwritesoff', '--entity', PAGES.open.slug, '--provenance', 'test turn'], undefined],
+ ];
+ const counts = () => withBrain(async engine => {
+ const out: Record<string, number> = {};
+ for (const table of ['pages', 'links', 'tags', 'timeline_entries', 'facts']) out[table] = (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM ' + table))[0]!.n;
+ out.content = (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE compiled_truth LIKE '%' || $1 || '%'", [PAGES.open.canary]))[0]!.n;
+ return out;
+ });
+ const reads: string[][] = [['list', '--json'], ['get', PAGES.open.slug], ['search', 'harbor ledger', '--json'], ['recall', PAGES.open.slug, '--json'], ['stats', '--by', 'type', '--json']];
+ const readAll = async () => {
+ const out: Array<{ args: string; exit: number; out: string; notice: boolean }> = [];
+ for (const args of reads) { const r = await cli(args); out.push({ args: args.join(' '), exit: r.exitCode, out: r.stdout, notice: r.stderr.includes(NOTICE) }); }
+ return out;
+ };
+ const checkedReads = await readAll();
+ const before = await counts();
+ try {
+ await setKey('refuse');
+ expect(await readAll()).toEqual(checkedReads);
+ const texts = new Set<string>();
+ for (const [args, stdin] of writes) {
+ const r = await cli(args, { stdin });
+ const first = r.stderr.split('\n')[0];
+ expect({ args: args.join(' '), exit: r.exitCode, first, out: r.stdout, leaks: leaks(r.stdout + r.stderr) })
+ .toEqual({ args: args.join(' '), exit: 3, first: WRITES_OFF_FIRST, out: '', leaks: [] });
+ texts.add(r.stderr);
+ }
+ expect(texts.size).toBe(1);
+ const [text] = [...texts];
+ expect(text).toContain('Recovery: nothing was saved');
+ expect(text).toContain('Why: This brain turned off member writes under this mode');
+ expect(text).toContain('brain owner');
+ for (const slug of ['notes/writes-off-new-example', PAGES.open.slug, PAGES.other.slug, 'notes', 'harbor']) expect({ slug, named: text!.includes(slug) }).toEqual({ slug, named: false });
+ const json = await cli(['put', 'notes/writes-off-new-example', '--json'], { stdin: page('Writes off new') });
+ expect({ exit: json.exitCode, envelope: json.stdout.includes('enforced_member_refused'), reason: /"reason":\s*"writes_off"/.test(json.stdout) })
+ .toEqual({ exit: 3, envelope: true, reason: true });
+ const receipt = await cli(['write-request', crypto.randomUUID()]);
+ expect(receipt.stderr).not.toContain(WRITES_OFF_FIRST);
+ expect(await counts()).toEqual(before);
+ for (const value of ['chekced', 'REFUSE ']) {
+ await setKey(value);
+ const r = await cli(['tag', PAGES.open.slug, 'writes-off-tag']);
+ expect({ value, exit: r.exitCode, first: r.stderr.split('\n')[0], why: r.stderr.includes('turned off member writes') }).toEqual({ value, exit: 3, first: WRITES_OFF_FIRST, why: true });
+ }
+ await setKey('refuse_pages');
+ for (const [args, stdin] of writes) {
+ const r = await cli(args, { stdin });
+ expect({ args: args.join(' '), exit: r.exitCode, first: r.stderr.split('\n')[0], why: r.stderr.includes('Why: This brain turned off member page writes under this mode') })
+ .toEqual({ args: args.join(' '), exit: 3, first: WRITES_OFF_FIRST, why: true });
+ }
+ expect(await readAll()).toEqual(checkedReads);
+ expect(await counts()).toEqual(before);
+ await setKey('refuse');
+ for (const [args, stdin] of writes.filter(([a]) => a[0] !== 'put' || a[1] === 'notes/writes-off-new-example')) {
+ const r = await cli(args, { member: null, stdin });
+ expect({ args: args.join(' '), exit: r.exitCode, err: r.exitCode === 0 ? '' : r.stderr }).toEqual({ args: args.join(' '), exit: 0, err: '' });
+ }
+ const after = await counts();
+ expect({ pages: after.pages, facts: after.facts, timeline: after.timeline_entries }).toEqual({ pages: before.pages + 1, facts: before.facts + 1, timeline: before.timeline_entries + 1 });
+ await setKey('checked');
+ const allowed = await cli(['tag', PAGES.open.slug, 'writes-checked-tag']);
+ expect({ exit: allowed.exitCode, err: allowed.exitCode === 0 ? '' : allowed.stderr }).toEqual({ exit: 0, err: '' });
+ const hidden = await cli(['put', PAGES.other.slug], { stdin: page('Overwrite') });
+ expect({ exit: hidden.exitCode, first: hidden.stderr.split('\n')[0] }).toEqual({ exit: 3, first: FIRST(MEMBER, 'put') });
+ } finally {
+ await withBrain(engine => engine.executeRaw('DELETE FROM config WHERE key = $1', [KEY]));
+ }
+ }, 900_000);
+ });
+}
diff --git a/test/enforced-member-writes.serial.test.ts b/test/enforced-member-writes.serial.test.ts
new file mode 100644
index 0000000000..4d796b6e68
--- /dev/null
+++ b/test/enforced-member-writes.serial.test.ts
@@ -0,0 +1,322 @@
+/**
+ * GST-2476 G2: enforced member mode (GBRAIN_ENFORCED_MEMBER) as real CLI subprocesses against a repo-less brain on
+ * disk (PGLite, and Postgres when DATABASE_URL is set): writes, and git commit-push and sync on a repo brain. Reads and
+ * refusals live in test/enforced-member.serial.test.ts; each file seeds its own brain.
+ *
+ * 1. Protects: writes refuse a page the member cannot read and every label change, and an allowed write lands exactly
+ * as a trusted local write (an owner-bound key reads it); write-request shows only the member's own receipts;
+ * timeline-add refuses a gbrain fence; --source reads carry the scope; entity mentions leave a hidden page out;
+ * commit-push refuses a hidden file, a label change and a policy file.
+ * 2. Fails when: a write reaches a hidden page or changes a label, a mode write lands member-private, another
+ * member's receipt is distinguishable from an unknown id, or commit-push commits a refused path.
+ * 3. Existing coverage: test/enforced-member.serial.test.ts (reads), test/enforced-member-writes-off.test.ts (the key).
+ * 4. Real seams: src/cli.ts dispatch, local writes, MCP dispatch as an owner-bound key, a real git remote.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createEngine } from '../src/core/engine-factory.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { CLI, enforcedMemberBrain, FIRST, MEMBER, PAGES, REMEMBER_FIRST, REMEMBER_RETRY, WRITES_OFF_FIRST } from './helpers/enforced-member-brain.ts';
+
+for (const kind of testBackends()) {
+ describe('enforced member mode: writes (' + kind + ', repo-less)', () => {
+ const brain = enforcedMemberBrain(kind);
+ const { cli, withBrain } = brain;
+
+ test('writes refuse a hidden target and every label change', async () => {
+ const page = (title: string, fm = '') => '---\ntype: note\ntitle: ' + title + '\n' + fm + '---\n# ' + title + '\n\nBody text.\n';
+ const refused: Array<[string[], string, string | undefined]> = [
+ [['put', PAGES.other.slug], 'put', page('Overwrite')],
+ [['put', PAGES.folder.slug], 'put', page('Overwrite')],
+ [['put', 'team-b/new-example'], 'put', page('New under rule')],
+ [['put', 'notes/labelled-example'], 'put', page('Labelled', 'readable_by: [alice-example]\n')],
+ [['put', 'notes/private-new-example'], 'put', page('Private new', 'visibility: private\n')],
+ [['put', PAGES.open.slug], 'put', page('Open example plan', 'visibility: private\n')],
+ [['link', PAGES.open.slug, PAGES.other.slug], 'link', undefined],
+ [['tag', PAGES.priv.slug, 'x'], 'tag', undefined],
+ [['remember', 'A fact', '--entity', PAGES.open.slug, '--provenance', 'test', '--visibility', 'private'], 'remember', undefined],
+ ];
+ for (const [args, command, stdin] of refused) {
+ const r = await cli(args, { stdin });
+ expect({ args: args.join(' '), exit: r.exitCode, first: r.stderr.split('\n')[0] }).toEqual({ args: args.join(' '), exit: 3, first: FIRST(MEMBER, command) });
+ expect(r.stderr.toLowerCase()).not.toContain('exists');
+ }
+ for (const args of [['remember', 'A fact', '--provenance', 'test'], ['remember', 'A fact', '--entity', PAGES.other.slug, '--provenance', 'test'], ['remember', 'A fact', '--entity', 'Notes/Open-Example', '--provenance', 'test']]) {
+ const r = await cli(args);
+ const lines = r.stderr.split('\n');
+ expect({ args: args.join(' '), exit: r.exitCode, first: lines[0], second: lines[1], out: r.stdout }).toEqual({ args: args.join(' '), exit: 3, first: REMEMBER_FIRST, second: REMEMBER_RETRY, out: '' });
+ expect(r.stderr).toContain('Recovery: nothing was saved, so retrying with --entity is safe.');
+ expect(r.stderr.toLowerCase()).not.toContain('exists');
+ }
+ await withBrain(async engine => {
+ const rows = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE fact = 'A fact'");
+ expect(rows[0]!.n).toBe(0);
+ });
+ const control = await cli(['get', PAGES.other.slug], { member: null });
+ expect(control.stdout).toContain(PAGES.other.canary);
+ }, 600_000);
+
+ test('an allowed write lands as a trusted local write, readable by an owner-bound key', async () => {
+ const put = await cli(['put', 'notes/alice-example-draft'], { stdin: '---\ntype: note\ntitle: Alice draft\n---\n# Alice draft\n\nDraft canaryemdraft.\n' });
+ expect({ exit: put.exitCode, err: put.exitCode === 0 ? '' : put.stderr }).toEqual({ exit: 0, err: '' });
+ const remember = await cli(['remember', 'Harbor ledger fact canaryemremember', '--entity', PAGES.open.slug, '--provenance', 'test turn']);
+ expect({ exit: remember.exitCode, err: remember.exitCode === 0 ? '' : remember.stderr }).toEqual({ exit: 0, err: '' });
+ await withBrain(async engine => {
+ const [row] = await engine.executeRaw<{ frontmatter: unknown }>("SELECT frontmatter FROM pages WHERE slug = 'notes/alice-example-draft'");
+ const fm = (typeof row!.frontmatter === 'string' ? JSON.parse(row!.frontmatter) : row!.frontmatter) as Record<string, unknown>;
+ expect(fm.readable_by).toBeUndefined();
+ expect(fm.visibility).toBeUndefined();
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const auth = await provider.verifyAccessToken(brain.ownerToken) as unknown as AuthInfo;
+ const call = async (op: string, params: Record<string, unknown>) => (await dispatchToolCall(engine, op, params, { remote: true, transport: 'http', auth, sourceId: 'default', takesHoldersAllowList: ['world'] })).content.map(c => c.text).join('\n');
+ expect(await call('get_page', { slug: 'notes/alice-example-draft' })).toContain('canaryemdraft');
+ expect(await call('recall', { entity: PAGES.open.slug })).toContain('canaryemremember');
+ });
+ }, 300_000);
+
+ test("write-request reads the member's own receipts; any other id answers exactly as an unknown one", async () => {
+ const body = '---\ntype: note\ntitle: Receipt example\n---\n# Receipt example\n\nBody.\n';
+ const own = await cli(['put', 'notes/alice-example-receipt', '--json'], { stdin: body });
+ expect(own.exitCode).toBe(0);
+ const ownId = JSON.parse(own.stdout).request_id as string;
+ const other = await cli(['put', 'notes/owner-example-receipt', '--json'], { member: null, stdin: body });
+ const otherId = JSON.parse(other.stdout).request_id as string;
+ expect({ ownId: typeof ownId, otherId: typeof otherId, same: ownId === otherId }).toEqual({ ownId: 'string', otherId: 'string', same: false });
+ expect((await cli(['write-request', otherId], { member: null })).exitCode).toBe(0);
+ for (const json of [false, true]) {
+ const flag = json ? ['--json'] : [];
+ const mine = await cli(['write-request', ownId, ...flag]);
+ expect({ json, exit: mine.exitCode, id: mine.stdout.includes(ownId) }).toEqual({ json, exit: 0, id: true });
+ const unknown = await cli(['write-request', crypto.randomUUID(), ...flag]);
+ expect(unknown.exitCode).not.toBe(0);
+ for (const id of [otherId, otherId.toUpperCase(), 'not-a-request-id']) {
+ const r = await cli(['write-request', id, ...flag]);
+ expect({ json, id, exit: r.exitCode, out: r.stdout, err: r.stderr }).toEqual({ json, id, exit: unknown.exitCode, out: unknown.stdout, err: unknown.stderr });
+ expect((r.stdout + r.stderr).toLowerCase()).not.toContain('exists');
+ expect(r.stdout + r.stderr).not.toContain('owner-example-receipt');
+ }
+ }
+ }, 300_000);
+
+ test('timeline-add refuses a gbrain fence in its summary, detail or source', async () => {
+ const takes = '<!--- gbrain:takes:begin -->\n| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|\n| 1 | Injected take canaryemtake | take | owner-example | 0.9 | 2026-01 | test |\n<!--- gbrain:takes:end -->';
+ const facts = '<!-- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|\n| 1 | Injected canaryeminj | fact | 0.9 | private | high | 2026-01-05 | | x | |\n<!-- gbrain:facts:end -->';
+ for (const args of [
+ ['timeline-add', PAGES.open.slug, '2026-01-03', 'Event summary', '--detail', '\n' + takes + '\n'],
+ ['timeline-add', PAGES.open.slug, '2026-01-04', 'Event two', '--detail', '\n' + facts + '\n'],
+ ['timeline-add', PAGES.open.slug, '2026-01-05', 'Event three <!--- gbrain:takes:begin -->'],
+ ['timeline-add', PAGES.open.slug, '2026-01-06', 'Event four', '--source', '<!---gbrain:facts:end -->'],
+ ]) {
+ const r = await cli(args);
+ expect({ date: args[2], exit: r.exitCode, first: r.stderr.split('\n')[0] }).toEqual({ date: args[2], exit: 3, first: FIRST(MEMBER, 'timeline-add') });
+ }
+ const plain = await cli(['timeline-add', PAGES.open.slug, '2026-01-07', 'A plain event']);
+ expect({ exit: plain.exitCode, err: plain.exitCode === 0 ? '' : plain.stderr }).toEqual({ exit: 0, err: '' });
+ await withBrain(async engine => {
+ const t = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM takes WHERE claim LIKE '%canaryemtake%'");
+ const f = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE fact LIKE '%canaryeminj%'");
+ const e = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM timeline_entries WHERE summary LIKE 'Event%'");
+ expect({ takes: t[0]!.n, facts: f[0]!.n, entries: e[0]!.n }).toEqual({ takes: 0, facts: 0, entries: 0 });
+ });
+ }, 300_000);
+
+ test('--source on a read carries the scope like a remote credential; an unknown source refuses like a hidden one', async () => {
+ await withBrain(async engine => {
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('team-src', 'team-src') ON CONFLICT DO NOTHING");
+ await importFromContent(engine, 'notes/team-src-page', '---\ntype: note\ntitle: Team source page\n---\n# Team source page\n\nHarbor team body canaryemteamsrc.\n', { sourceId: 'team-src', noEmbed: true });
+ });
+ for (const args of [['get', 'notes/team-src-page', '--source', 'team-src'], ['list', '--source', 'team-src', '--json'], ['search', 'harbor team', '--source', 'team-src', '--json']]) {
+ const r = await cli(args);
+ expect({ args: args[0], exit: r.exitCode, seen: /team-src-page|canaryemteamsrc/.test(r.stdout), nudge: /sole non-default|routing to source/.test(r.stderr) })
+ .toEqual({ args: args[0], exit: 0, seen: true, nudge: false });
+ }
+ const hidden = await cli(['get', 'notes/never-written-example', '--source', 'bob-dm']);
+ for (const args of [['get', 'notes/never-written-example', '--source', 'nosuch-example'], ['get', 'notes/never-written-example', '--source-id', 'nosuch-example']]) {
+ const r = await cli(args);
+ expect({ args: args.join(' '), exit: r.exitCode, err: r.stderr, out: r.stdout }).toEqual({ args: args.join(' '), exit: hidden.exitCode, err: hidden.stderr, out: hidden.stdout });
+ }
+ expect(hidden.exitCode).toBe(3);
+ }, 300_000);
+
+ test("entity text_mentions lists a visible page that names the entity and leaves a hidden one out", async () => {
+ const page = (slug: string, type: string, title: string, fm: string, body: string) =>
+ '---\ntype: ' + type + '\ntitle: ' + JSON.stringify(title) + '\n' + fm + '---\n# ' + title + '\n\n' + body + '\n';
+ await withBrain(async engine => {
+ await importFromContent(engine, 'people/carol-example', page('people/carol-example', 'person', 'Carol Example', '', 'A person page.'), { sourceId: 'default', noEmbed: true });
+ await importFromContent(engine, 'notes/bob-carol-memo', page('notes/bob-carol-memo', 'note', 'Bob memo canaryemtmhidden', 'readable_by: [bob-example]\n', 'Met Carol Example about the canaryemtmhidden plan.'), { sourceId: 'default', noEmbed: true });
+ await importFromContent(engine, 'notes/open-carol-memo', page('notes/open-carol-memo', 'note', 'Open memo canaryemtmopen', '', 'Met Carol Example about the open plan.'), { sourceId: 'default', noEmbed: true });
+ });
+ const marks = ['notes/bob-carol-memo', 'Bob memo canaryemtmhidden', 'canaryemtmhidden'];
+ const trusted = JSON.parse((await cli(['entity', 'Carol Example', '--json'], { member: null })).stdout);
+ expect({ control: trusted.card?.text_mentions?.pages?.map((x: { slug: string }) => x.slug).sort() }).toEqual({ control: ['notes/bob-carol-memo', 'notes/open-carol-memo'] });
+ const r = await cli(['entity', 'Carol Example', '--json']);
+ const tm = JSON.parse(r.stdout).card?.text_mentions;
+ expect({ exit: r.exitCode, slugs: tm?.pages?.map((x: { slug: string }) => x.slug), total: tm?.total, leaks: marks.filter(m => (r.stdout + r.stderr).includes(m)) })
+ .toEqual({ exit: 0, slugs: ['notes/open-carol-memo'], total: 1, leaks: [] });
+ const human = await cli(['entity', 'Carol Example']);
+ expect({ exit: human.exitCode, open: human.stdout.includes('notes/open-carol-memo'), count: /text of 1 other page/.test(human.stdout), leaks: marks.filter(m => (human.stdout + human.stderr).includes(m)) })
+ .toEqual({ exit: 0, open: true, count: true, leaks: [] });
+ }, 300_000);
+ });
+}
+
+for (const kind of testBackends()) {
+ describe('enforced member mode: git commit-push and sync (' + kind + ')', () => {
+ let root: string, home: string, checkout: string;
+ let config: Record<string, unknown>;
+ let closePg: (() => Promise<void>) | null = null;
+
+ function env(member: string | null): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined) out[k] = v;
+ for (const k of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_BRAIN_ID', 'GBRAIN_SOURCE', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY', 'GEMINI_API_KEY', 'GBRAIN_ENFORCED_MEMBER']) delete out[k];
+ return { ...out, HOME: home, GBRAIN_HOME: home, GBRAIN_SELF_UPGRADE_MODE: 'off', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SWEEP: '0', GBRAIN_CLI_SOCKET: '0',
+ GIT_AUTHOR_NAME: 'Example', GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'Example', GIT_COMMITTER_EMAIL: '[email protected]', ...(member === null ? {} : { GBRAIN_ENFORCED_MEMBER: member }) };
+ }
+ async function cli(args: string[], member: string | null = MEMBER) {
+ const proc = Bun.spawn(['bun', 'run', CLI, ...args], { cwd: checkout, env: env(member), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { stdout, stderr, exitCode };
+ }
+ const git = (...args: string[]) => execFileSync('git', ['-C', checkout, ...args], { env: env(null), stdio: ['ignore', 'pipe', 'pipe'] }).toString();
+ const note = (title: string, fm = '') => '---\ntype: note\ntitle: ' + title + '\n' + fm + '---\n# ' + title + '\n\nHarbor notes.\n';
+
+ beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'gb-enforced-git-'));
+ home = join(root, 'home');
+ checkout = join(root, 'checkout');
+ const remote = join(root, 'remote.git');
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ execFileSync('git', ['init', '-q', '--bare', '-b', 'main', remote]);
+ execFileSync('git', ['clone', '-q', remote, checkout], { stdio: 'ignore' });
+ mkdirSync(join(checkout, 'notes'), { recursive: true });
+ writeFileSync(join(checkout, 'notes', 'open-git.md'), note('Open git'));
+ writeFileSync(join(checkout, 'notes', 'bob-git.md'), note('Bob git', 'readable_by: [bob-example]\n'));
+ git('checkout', '-q', '-b', 'main');
+ git('add', '-A');
+ git('commit', '-qm', 'synthetic content');
+ git('push', '-q', 'origin', 'main');
+ if (kind === 'postgres') {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ await pg.engine.disconnect();
+ config = { engine: 'postgres', database_url: pg.databaseUrl };
+ closePg = pg.close;
+ } else {
+ config = { engine: 'pglite', database_path: join(root, 'db') };
+ }
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(config));
+ const engine = await createEngine(config as never);
+ await engine.connect(config as never);
+ try {
+ if (kind === 'pglite') await engine.initSchema();
+ for (const id of [MEMBER, 'bob-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);
+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('repo-src', 'repo-src', $1)", [checkout]);
+ } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ const synced = await cli(['sync', '--source', 'repo-src', '--no-pull', '--no-embed'], null);
+ expect({ exit: synced.exitCode, err: synced.exitCode === 0 ? '' : synced.stderr }).toEqual({ exit: 0, err: '' });
+ }, 300_000);
+
+ afterAll(async () => {
+ rmSync(root, { recursive: true, force: true });
+ await closePg?.();
+ }, 60_000);
+
+ test('commit-push refuses a hidden file, a label change, a policy file and the refused modes', async () => {
+ writeFileSync(join(checkout, 'notes', 'bob-git.md'), note('Bob git', 'readable_by: [bob-example]\n') + 'More.\n');
+ writeFileSync(join(checkout, 'notes', 'open-git.md'), note('Open git', 'visibility: private\n'));
+ mkdirSync(join(checkout, '.gbrain'), { recursive: true });
+ writeFileSync(join(checkout, '.gbrain', 'access.yml'), 'rules: []\n');
+ const cases: string[][] = [
+ ['git', 'commit-push', '--path', checkout, '-m', 'x', '--', 'notes/bob-git.md'],
+ ['git', 'commit-push', '--path', checkout, '-m', 'x', '--', 'notes/open-git.md'],
+ ['git', 'commit-push', '--path', checkout, '-m', 'x', '--', 'notes'],
+ ['git', 'commit-push', '--path', checkout, '-m', 'x', '--', '.gbrain/access.yml'],
+ ['git', 'commit-push', '--path', checkout, '--pending'],
+ ['git', 'commit-push', '--path', checkout, '--push-only'],
+ ['git', 'guard', '--install'],
+ ];
+ for (const args of cases) {
+ const r = await cli(args);
+ const command = args[1] === 'guard' ? 'git guard' : 'git commit-push';
+ expect({ args: args.slice(-1)[0], exit: r.exitCode, first: r.stderr.split('\n')[0] }).toEqual({ args: args.slice(-1)[0], exit: 3, first: FIRST(MEMBER, command) });
+ }
+ expect(git('status', '--porcelain')).toContain('notes/bob-git.md');
+ git('checkout', '-q', '--', 'notes');
+ rmSync(join(checkout, '.gbrain'), { recursive: true, force: true });
+ }, 300_000);
+
+ test('commit-push of a readable new file and --pull run with their output withheld', async () => {
+ writeFileSync(join(checkout, 'notes', 'alice-git.md'), note('Alice git'));
+ const r = await cli(['git', 'commit-push', '--path', checkout, '-m', 'alice note', '--', 'notes/alice-git.md']);
+ expect({ exit: r.exitCode, out: r.stdout, err: r.stderr }).toEqual({ exit: 0, out: '', err: 'gbrain: git commit-push finished; its output is withheld under GBRAIN_ENFORCED_MEMBER\n' });
+ expect(git('log', '--format=%s', '-1').trim()).toBe('alice note');
+ const pull = await cli(['git', 'commit-push', '--path', checkout, '--pull']);
+ expect({ exit: pull.exitCode, out: pull.stdout, err: pull.stderr }).toEqual({ exit: 0, out: '', err: 'gbrain: git commit-push finished; its output is withheld under GBRAIN_ENFORCED_MEMBER\n' });
+ }, 300_000);
+
+ test('access.enforced_member_writes: refuse closes named-path commit-push, refuse_pages keeps it; --pull, --dry-run and sync run under both', async () => {
+ const setKey = async (value: string) => {
+ const r = await cli(['config', 'set', 'access.enforced_member_writes', value], null);
+ expect({ value, exit: r.exitCode, err: r.exitCode === 0 ? '' : r.stderr }).toEqual({ value, exit: 0, err: '' });
+ };
+ const WITHHELD = (command: string) => 'gbrain: ' + command + ' finished; its output is withheld under GBRAIN_ENFORCED_MEMBER\n';
+ const stillRuns = async (mode: string) => {
+ const pull = await cli(['git', 'commit-push', '--path', checkout, '--pull']);
+ expect({ mode, exit: pull.exitCode, out: pull.stdout, err: pull.stderr }).toEqual({ mode, exit: 0, out: '', err: WITHHELD('git commit-push') });
+ const dry = await cli(['git', 'commit-push', '--path', checkout, '--dry-run', '-m', 'dry', '--', 'notes/alice-git-mode.md']);
+ expect({ mode, exit: dry.exitCode, out: dry.stdout, err: dry.stderr }).toEqual({ mode, exit: 0, out: '', err: WITHHELD('git commit-push') });
+ const sync = await cli(['sync', '--source', 'repo-src', '--no-pull', '--no-embed']);
+ expect({ mode, exit: sync.exitCode, out: sync.stdout, err: sync.stderr }).toEqual({ mode, exit: 0, out: '', err: WITHHELD('sync') });
+ };
+ try {
+ writeFileSync(join(checkout, 'notes', 'alice-git-mode.md'), note('Alice git mode'));
+ await setKey('refuse');
+ const headBefore = git('rev-parse', 'HEAD').trim();
+ const texts = new Set<string>();
+ for (const path of ['notes/alice-git-mode.md', 'notes/bob-git.md', 'notes/never-written-git.md']) {
+ const r = await cli(['git', 'commit-push', '--path', checkout, '-m', 'x', '--', path]);
+ expect({ path, exit: r.exitCode, first: r.stderr.split('\n')[0], out: r.stdout }).toEqual({ path, exit: 3, first: WRITES_OFF_FIRST, out: '' });
+ texts.add(r.stderr);
+ }
+ expect(texts.size).toBe(1);
+ expect([...texts][0]).toContain('turned off member writes');
+ expect(git('rev-parse', 'HEAD').trim()).toBe(headBefore);
+ await stillRuns('refuse');
+ await setKey('refuse_pages');
+ const r = await cli(['git', 'commit-push', '--path', checkout, '-m', 'alice note under refuse_pages', '--', 'notes/alice-git-mode.md']);
+ expect({ exit: r.exitCode, out: r.stdout, err: r.stderr }).toEqual({ exit: 0, out: '', err: WITHHELD('git commit-push') });
+ expect(git('log', '--format=%s', '-1').trim()).toBe('alice note under refuse_pages');
+ const hidden = await cli(['git', 'commit-push', '--path', checkout, '-m', 'x', '--', 'notes/bob-git.md']);
+ expect({ exit: hidden.exitCode, first: hidden.stderr.split('\n')[0] }).toEqual({ exit: 3, first: FIRST(MEMBER, 'git commit-push') });
+ await stillRuns('refuse_pages');
+ } finally {
+ const engine = await createEngine(config as never);
+ await engine.connect(config as never);
+ try { await engine.executeRaw("DELETE FROM config WHERE key = 'access.enforced_member_writes'"); } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ }
+ }, 300_000);
+
+ test('sync runs with its output withheld; sync status is refused', async () => {
+ const r = await cli(['sync', '--source', 'repo-src', '--no-pull', '--no-embed']);
+ expect({ exit: r.exitCode, out: r.stdout, err: r.stderr }).toEqual({ exit: 0, out: '', err: 'gbrain: sync finished; its output is withheld under GBRAIN_ENFORCED_MEMBER\n' });
+ const json = await cli(['sync', '--source', 'repo-src', '--no-pull', '--no-embed', '--json']);
+ expect({ exit: json.exitCode, out: json.stdout, err: json.stderr }).toEqual({ exit: 0, out: '', err: 'gbrain: sync finished; its output is withheld under GBRAIN_ENFORCED_MEMBER\n' });
+ for (const args of [['sync', '--source', 'repo-src', '--repo', root, '--no-pull'], ['sync', '--repo', checkout], ['sync', '--source', 'repo-src', '--reset-checkpoint']]) {
+ const refused = await cli(args);
+ expect({ args: args.join(' '), exit: refused.exitCode, first: refused.stderr.split('\n')[0] }).toEqual({ args: args.join(' '), exit: 3, first: FIRST(MEMBER, 'sync') });
+ }
+ const status = await cli(['sync', 'status', '--source', 'repo-src']);
+ expect({ exit: status.exitCode, first: status.stderr.split('\n')[0] }).toEqual({ exit: 3, first: FIRST(MEMBER, 'sync status') });
+ }, 300_000);
+ });
+}
diff --git a/test/enforced-member.serial.test.ts b/test/enforced-member.serial.test.ts
index ba20026390..2ef6d3ae6c 100644
--- a/test/enforced-member.serial.test.ts
+++ b/test/enforced-member.serial.test.ts
@@ -1,62 +1,24 @@
/**
* GST-2476 G2: enforced member mode (GBRAIN_ENFORCED_MEMBER) as real CLI subprocesses against a repo-less brain on
- * disk (PGLite, and Postgres when DATABASE_URL is set).
+ * disk (PGLite, and Postgres when DATABASE_URL is set): reads and refusals. Writes live in
+ * test/enforced-member-writes.serial.test.ts and access.enforced_member_writes in
+ * test/enforced-member-writes-setting.serial.test.ts; each file seeds its own brain (test/helpers/enforced-member-brain.ts).
*
* 1. Protects: under the mode every read-filtered command shows no slug, title, body, fact or count of a page the member
* cannot read (another member's readers, visibility: private, a folder rule it does not satisfy, another member's
* personal source); every refused class, an unknown member, an empty value and the owner id refuse with the exact
- * first line; hook succeeds silently; writes refuse a page the member cannot read and every label change, and an
- * allowed write lands exactly as a trusted local write (an owner-bound key reads it); unset changes nothing.
- * 2. Fails when: any of those reads names a hidden page, a refusal prints anything else first or exits 0, a write
- * reaches a hidden page or changes a label, a mode write lands member-private, or the variable unset changes output.
+ * first line; hook succeeds silently; doctor prints only names, statuses and counts; unset changes nothing.
+ * 2. Fails when: any of those reads names a hidden page, a refusal prints anything else first or exits 0, or the
+ * variable unset changes output.
* 3. Existing coverage: test/access-as.serial.test.ts (--as, which keeps ctx.remote false and is refused here).
- * 4. Real seams: src/cli.ts and src/cli/main.ts dispatch, MCP dispatch as the member's stdio server, local writes.
+ * 4. Real seams: src/cli.ts and src/cli/main.ts dispatch, local reads.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
-import { execFileSync } from 'node:child_process';
-import { tmpdir } from 'node:os';
-import { join, resolve } from 'node:path';
-import { createEngine } from '../src/core/engine-factory.ts';
-import type { BrainEngine } from '../src/core/engine.ts';
-import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
-import { proposeRevision } from '../src/core/access/policy.ts';
-import { bindCredential } from '../src/core/access/members.ts';
-import { setOwner } from '../src/core/access/owner.ts';
-import { mintLegacyToken } from '../src/core/token-mint.ts';
-import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
-import { sqlQueryForEngine } from '../src/core/sql-query.ts';
-import { dispatchToolCall } from '../src/mcp/dispatch.ts';
-import { importFromContent } from '../src/core/import-file.ts';
-import type { AuthInfo } from '../src/core/ops/contract.ts';
+import { describe, expect, test } from 'bun:test';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
import { OPERATION_CLASSES } from '../src/cli/enforced-member-classes.ts';
import { testBackends } from './helpers/test-backends.ts';
-import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
-
-const CLI = join(resolve(import.meta.dir, '..'), 'src', 'cli.ts');
-const MEMBER = 'alice-example';
-const OWNER = 'owner-example';
-const FIRST = (who: string, command: string) => 'gbrain: refused under GBRAIN_ENFORCED_MEMBER=' + who + ': ' + command + ' [GBRAIN_ENFORCED_REFUSED]';
-const NOTICE = 'gbrain: results limited to what GBRAIN_ENFORCED_MEMBER=' + MEMBER + ' may read';
-const REMEMBER_FIRST = 'gbrain: refused under GBRAIN_ENFORCED_MEMBER=' + MEMBER + ': remember saves a fact only with --entity <slug of a page you can read>; nothing was saved [GBRAIN_ENFORCED_REFUSED]';
-const WRITES_OFF_FIRST = 'gbrain: refused under GBRAIN_ENFORCED_MEMBER=' + MEMBER + ': writes are off for members on this brain; nothing was saved [GBRAIN_ENFORCED_REFUSED]';
-const REMEMBER_RETRY = 'Retry: gbrain remember "<one fact>" --entity <exact slug of a page you can read, from gbrain find or gbrain search> --provenance "<where you learned it>"';
-
-const PAGES = {
- open: { slug: 'notes/open-example', title: 'Open example plan', canary: 'canaryemopen', fm: {} as Record<string, unknown>, source: 'default' },
- mine: { slug: 'notes/alice-example-plan', title: 'Alice example plan', canary: 'canaryemmine', fm: { readable_by: [MEMBER] }, source: 'default' },
- team: { slug: 'team-a/roadmap-example', title: 'Team a roadmap', canary: 'canaryemteam', fm: {}, source: 'default' },
- other: { slug: 'notes/bob-example-plan', title: 'Bob example secret', canary: 'canaryemother', fm: { readable_by: ['bob-example'] }, source: 'default' },
- priv: { slug: 'notes/quiet-example', title: 'Quiet example memo', canary: 'canaryempriv', fm: { visibility: 'private' }, source: 'default' },
- folder: { slug: 'team-b/budget-example', title: 'Team b budget', canary: 'canaryemfolder', fm: {}, source: 'default' },
- personal: { slug: 'notes/dm-example', title: 'Direct example thread', canary: 'canaryempersonal', fm: {}, source: 'bob-dm' },
-} as const;
-type Key = keyof typeof PAGES;
-const VISIBLE: Key[] = ['open', 'mine', 'team'];
-const HIDDEN: Key[] = ['other', 'priv', 'folder', 'personal'];
-const HIDDEN_FACT = 'canaryemfacthidden';
-const OPEN_FACT = 'canaryemfactopen';
-const HIDDEN_MARKS = [...HIDDEN.flatMap(k => [PAGES[k].slug, PAGES[k].title, PAGES[k].canary]), HIDDEN_FACT];
+import { enforcedMemberBrain, FIRST, HIDDEN, HIDDEN_FACT, leaks, MEMBER, NOTICE, OPEN_FACT, OWNER, PAGES, VISIBLE, type Key } from './helpers/enforced-member-brain.ts';
/** Every read-class operation with arguments, so a read op added to the allow-list without a row here fails. */
const READS: Array<[op: string, args: string[]]> = [
@@ -93,77 +55,8 @@ test('every read-class operation has a no-trace row', () => {
for (const kind of testBackends()) {
describe('enforced member mode (' + kind + ', repo-less)', () => {
- let root: string, home: string;
- let config: Record<string, unknown>;
- let closePg: (() => Promise<void>) | null = null;
- let ownerToken = '';
-
- function env(extra: Record<string, string | undefined>): Record<string, string> {
- const out: Record<string, string> = {};
- for (const [k, v] of Object.entries(process.env)) if (v !== undefined) out[k] = v;
- for (const k of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_BRAIN_ID', 'GBRAIN_SOURCE', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY', 'GEMINI_API_KEY', 'GBRAIN_ENFORCED_MEMBER']) delete out[k];
- const merged: Record<string, string | undefined> = { ...out, HOME: home, GBRAIN_HOME: home, GBRAIN_SELF_UPGRADE_MODE: 'off', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SWEEP: '0', GBRAIN_CLI_SOCKET: '0', ...extra };
- return Object.fromEntries(Object.entries(merged).filter(([, v]) => v !== undefined)) as Record<string, string>;
- }
- async function cli(args: string[], opts: { member?: string | null; stdin?: string } = {}) {
- const member = opts.member === undefined ? MEMBER : opts.member;
- const proc = Bun.spawn(['bun', 'run', CLI, ...args], { cwd: root, env: env({ GBRAIN_ENFORCED_MEMBER: member ?? undefined }),
- stdin: opts.stdin === undefined ? 'ignore' : new Blob([opts.stdin]), stdout: 'pipe', stderr: 'pipe' });
- const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
- return { stdout, stderr, exitCode };
- }
- async function withBrain<T>(run: (engine: BrainEngine) => Promise<T>): Promise<T> {
- const engine = await createEngine(config as never);
- await engine.connect(config as never);
- try { return await run(engine); } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }
- }
- const leaks = (text: string) => HIDDEN_MARKS.filter(m => text.toLowerCase().includes(m.toLowerCase()));
-
- beforeAll(async () => {
- root = mkdtempSync(join(tmpdir(), 'gb-enforced-'));
- home = join(root, 'home');
- mkdirSync(join(home, '.gbrain'), { recursive: true });
- if (kind === 'postgres') {
- const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
- await pg.engine.disconnect();
- config = { engine: 'postgres', database_url: pg.databaseUrl };
- closePg = pg.close;
- } else {
- config = { engine: 'pglite', database_path: join(root, 'db') };
- }
- writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(config));
- await withBrain(async engine => {
- if (kind === 'pglite') await engine.initSchema();
- await engine.executeRaw("INSERT INTO sources (id, name, config) VALUES ('bob-dm', 'bob-dm', '{\"federated\": true}'::jsonb) ON CONFLICT (id) DO NOTHING");
- for (const id of [MEMBER, 'bob-example', OWNER]) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);
- await engine.executeRaw("INSERT INTO access_groups (id) VALUES ('team-a'), ('team-b') ON CONFLICT DO NOTHING");
- await engine.executeRaw("INSERT INTO access_group_members (group_id, member_id) VALUES ('team-a', $1), ('team-b', 'bob-example')", [MEMBER]);
- await engine.executeRaw("INSERT INTO access_member_sources (member_id, source_id) VALUES ('bob-example', 'bob-dm')");
- await proposeRevision(engine, 'default', [
- { id: 'team-a', prefix: 'team-a/', readable_by: ['group:team-a'] },
- { id: 'team-b', prefix: 'team-b/', readable_by: ['group:team-b'] },
- ] as never, { origin: 'cli', store: 'database' } as never);
- for (const key of Object.keys(PAGES) as Key[]) {
- const p = PAGES[key];
- const fm = Object.entries(p.fm).map(([k, v]) => k + ': ' + JSON.stringify(v)).join('\n');
- await importFromContent(engine, p.slug, '---\ntype: note\ntitle: ' + JSON.stringify(p.title) + '\n' + (fm ? fm + '\n' : '') + '---\n# ' + p.title + '\n\nHarbor ledger planning notes ' + p.canary + ' for the roadmap.\n', { sourceId: p.source, noEmbed: true });
- }
- await engine.addLink(PAGES.open.slug, PAGES.other.slug, 'see the secret plan', 'mentions');
- await engine.addLink(PAGES.other.slug, PAGES.open.slug, 'back to open', 'mentions');
- await engine.addTimelineEntry(PAGES.other.slug, { date: '2026-01-02', summary: 'Hidden event ' + HIDDEN_FACT } as never, { sourceId: 'default' });
- await engine.insertFact({ fact: 'Harbor ledger fact ' + HIDDEN_FACT, entity_slug: PAGES.other.slug, visibility: 'world', source: 'test', embedding: null }, { source_id: 'default' });
- await engine.insertFact({ fact: 'Harbor ledger fact ' + OPEN_FACT, entity_slug: PAGES.open.slug, visibility: 'world', source: 'test', embedding: null }, { source_id: 'default' });
- const minted = await mintLegacyToken(engine, { name: 'owner-key', scopes: ['read'], takesHolders: ['world'] } as never);
- ownerToken = minted.token;
- await bindCredential(engine, { kind: 'token', id: minted.id }, { member: OWNER });
- await setOwner(engine, OWNER);
- });
- }, 240_000);
-
- afterAll(async () => {
- rmSync(root, { recursive: true, force: true });
- await closePg?.();
- }, 60_000);
+ const brain = enforcedMemberBrain(kind);
+ const { cli, withBrain } = brain;
test('fixture control: the trusted CLI (variable unset) reads the hidden pages', async () => {
const r = await cli(['list', '--json'], { member: null });
@@ -261,81 +154,6 @@ for (const kind of testBackends()) {
}
}, 120_000);
- test('writes refuse a hidden target and every label change', async () => {
- const page = (title: string, fm = '') => '---\ntype: note\ntitle: ' + title + '\n' + fm + '---\n# ' + title + '\n\nBody text.\n';
- const refused: Array<[string[], string, string | undefined]> = [
- [['put', PAGES.other.slug], 'put', page('Overwrite')],
- [['put', PAGES.folder.slug], 'put', page('Overwrite')],
- [['put', 'team-b/new-example'], 'put', page('New under rule')],
- [['put', 'notes/labelled-example'], 'put', page('Labelled', 'readable_by: [alice-example]\n')],
- [['put', 'notes/private-new-example'], 'put', page('Private new', 'visibility: private\n')],
- [['put', PAGES.open.slug], 'put', page('Open example plan', 'visibility: private\n')],
- [['link', PAGES.open.slug, PAGES.other.slug], 'link', undefined],
- [['tag', PAGES.priv.slug, 'x'], 'tag', undefined],
- [['remember', 'A fact', '--entity', PAGES.open.slug, '--provenance', 'test', '--visibility', 'private'], 'remember', undefined],
- ];
- for (const [args, command, stdin] of refused) {
- const r = await cli(args, { stdin });
- expect({ args: args.join(' '), exit: r.exitCode, first: r.stderr.split('\n')[0] }).toEqual({ args: args.join(' '), exit: 3, first: FIRST(MEMBER, command) });
- expect(r.stderr.toLowerCase()).not.toContain('exists');
- }
- for (const args of [['remember', 'A fact', '--provenance', 'test'], ['remember', 'A fact', '--entity', PAGES.other.slug, '--provenance', 'test'], ['remember', 'A fact', '--entity', 'Notes/Open-Example', '--provenance', 'test']]) {
- const r = await cli(args);
- const lines = r.stderr.split('\n');
- expect({ args: args.join(' '), exit: r.exitCode, first: lines[0], second: lines[1], out: r.stdout }).toEqual({ args: args.join(' '), exit: 3, first: REMEMBER_FIRST, second: REMEMBER_RETRY, out: '' });
- expect(r.stderr).toContain('Recovery: nothing was saved, so retrying with --entity is safe.');
- expect(r.stderr.toLowerCase()).not.toContain('exists');
- }
- await withBrain(async engine => {
- const rows = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE fact = 'A fact'");
- expect(rows[0]!.n).toBe(0);
- });
- const control = await cli(['get', PAGES.other.slug], { member: null });
- expect(control.stdout).toContain(PAGES.other.canary);
- }, 600_000);
-
- test('an allowed write lands as a trusted local write, readable by an owner-bound key', async () => {
- const put = await cli(['put', 'notes/alice-example-draft'], { stdin: '---\ntype: note\ntitle: Alice draft\n---\n# Alice draft\n\nDraft canaryemdraft.\n' });
- expect({ exit: put.exitCode, err: put.exitCode === 0 ? '' : put.stderr }).toEqual({ exit: 0, err: '' });
- const remember = await cli(['remember', 'Harbor ledger fact canaryemremember', '--entity', PAGES.open.slug, '--provenance', 'test turn']);
- expect({ exit: remember.exitCode, err: remember.exitCode === 0 ? '' : remember.stderr }).toEqual({ exit: 0, err: '' });
- await withBrain(async engine => {
- const [row] = await engine.executeRaw<{ frontmatter: unknown }>("SELECT frontmatter FROM pages WHERE slug = 'notes/alice-example-draft'");
- const fm = (typeof row!.frontmatter === 'string' ? JSON.parse(row!.frontmatter) : row!.frontmatter) as Record<string, unknown>;
- expect(fm.readable_by).toBeUndefined();
- expect(fm.visibility).toBeUndefined();
- const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
- const auth = await provider.verifyAccessToken(ownerToken) as unknown as AuthInfo;
- const call = async (op: string, params: Record<string, unknown>) => (await dispatchToolCall(engine, op, params, { remote: true, transport: 'http', auth, sourceId: 'default', takesHoldersAllowList: ['world'] })).content.map(c => c.text).join('\n');
- expect(await call('get_page', { slug: 'notes/alice-example-draft' })).toContain('canaryemdraft');
- expect(await call('recall', { entity: PAGES.open.slug })).toContain('canaryemremember');
- });
- }, 300_000);
-
- test("write-request reads the member's own receipts; any other id answers exactly as an unknown one", async () => {
- const body = '---\ntype: note\ntitle: Receipt example\n---\n# Receipt example\n\nBody.\n';
- const own = await cli(['put', 'notes/alice-example-receipt', '--json'], { stdin: body });
- expect(own.exitCode).toBe(0);
- const ownId = JSON.parse(own.stdout).request_id as string;
- const other = await cli(['put', 'notes/owner-example-receipt', '--json'], { member: null, stdin: body });
- const otherId = JSON.parse(other.stdout).request_id as string;
- expect({ ownId: typeof ownId, otherId: typeof otherId, same: ownId === otherId }).toEqual({ ownId: 'string', otherId: 'string', same: false });
- expect((await cli(['write-request', otherId], { member: null })).exitCode).toBe(0);
- for (const json of [false, true]) {
- const flag = json ? ['--json'] : [];
- const mine = await cli(['write-request', ownId, ...flag]);
- expect({ json, exit: mine.exitCode, id: mine.stdout.includes(ownId) }).toEqual({ json, exit: 0, id: true });
- const unknown = await cli(['write-request', crypto.randomUUID(), ...flag]);
- expect(unknown.exitCode).not.toBe(0);
- for (const id of [otherId, otherId.toUpperCase(), 'not-a-request-id']) {
- const r = await cli(['write-request', id, ...flag]);
- expect({ json, id, exit: r.exitCode, out: r.stdout, err: r.stderr }).toEqual({ json, id, exit: unknown.exitCode, out: unknown.stdout, err: unknown.stderr });
- expect((r.stdout + r.stderr).toLowerCase()).not.toContain('exists');
- expect(r.stdout + r.stderr).not.toContain('owner-example-receipt');
- }
- }
- }, 300_000);
-
test('doctor under the mode prints only check names, statuses and counts', async () => {
const trusted = await cli(['doctor', '--json'], { member: null });
const r = await cli(['doctor', '--json']);
@@ -354,7 +172,7 @@ for (const kind of testBackends()) {
}, 300_000);
test('sync and sources refresh take only their listed flags and a source the member reads', async () => {
- const other = join(root, 'other-checkout');
+ const other = join(brain.root, 'other-checkout');
mkdirSync(join(other, 'notes'), { recursive: true });
writeFileSync(join(other, 'notes', 'other-diary.md'), '---\ntype: note\ntitle: Other diary canaryemdiary\n---\n# Other diary\n\nBody canaryemdiary.\n');
const before = await withBrain(engine => engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages'));
@@ -396,33 +214,11 @@ for (const kind of testBackends()) {
});
}, 300_000);
- test('timeline-add refuses a gbrain fence in its summary, detail or source', async () => {
- const takes = '<!--- gbrain:takes:begin -->\n| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|\n| 1 | Injected take canaryemtake | take | owner-example | 0.9 | 2026-01 | test |\n<!--- gbrain:takes:end -->';
- const facts = '<!-- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|\n| 1 | Injected canaryeminj | fact | 0.9 | private | high | 2026-01-05 | | x | |\n<!-- gbrain:facts:end -->';
- for (const args of [
- ['timeline-add', PAGES.open.slug, '2026-01-03', 'Event summary', '--detail', '\n' + takes + '\n'],
- ['timeline-add', PAGES.open.slug, '2026-01-04', 'Event two', '--detail', '\n' + facts + '\n'],
- ['timeline-add', PAGES.open.slug, '2026-01-05', 'Event three <!--- gbrain:takes:begin -->'],
- ['timeline-add', PAGES.open.slug, '2026-01-06', 'Event four', '--source', '<!---gbrain:facts:end -->'],
- ]) {
- const r = await cli(args);
- expect({ date: args[2], exit: r.exitCode, first: r.stderr.split('\n')[0] }).toEqual({ date: args[2], exit: 3, first: FIRST(MEMBER, 'timeline-add') });
- }
- const plain = await cli(['timeline-add', PAGES.open.slug, '2026-01-07', 'A plain event']);
- expect({ exit: plain.exitCode, err: plain.exitCode === 0 ? '' : plain.stderr }).toEqual({ exit: 0, err: '' });
- await withBrain(async engine => {
- const t = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM takes WHERE claim LIKE '%canaryemtake%'");
- const f = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE fact LIKE '%canaryeminj%'");
- const e = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM timeline_entries WHERE summary LIKE 'Event%'");
- expect({ takes: t[0]!.n, facts: f[0]!.n, entries: e[0]!.n }).toEqual({ takes: 0, facts: 0, entries: 0 });
- });
- }, 300_000);
-
test('--help: a refused command refuses, an allowed one prints its static help and runs nothing', async () => {
- const mountPath = join(root, 'help-mount');
+ const mountPath = join(brain.root, 'help-mount');
const refused: Array<[string[], string]> = [
[['creds', 'list', '--json', '--help'], 'creds'], [['google', 'status', '--json', '--help'], 'google'],
- [['mounts', 'add', 'help-mount', '--path', mountPath, '--engine', 'pglite', '--db-path', join(root, 'help.db'), '--help'], 'mounts'],
+ [['mounts', 'add', 'help-mount', '--path', mountPath, '--engine', 'pglite', '--db-path', join(brain.root, 'help.db'), '--help'], 'mounts'],
[['sources', 'list', '--json', '--help'], 'sources list'], [['sync', 'status', '--help'], 'sync status'], [['config', 'show', '--help'], 'config'],
[['friction', 'log', '--kind', 'friction', '--message', 'x', '--help'], 'friction'],
];
@@ -436,7 +232,7 @@ for (const kind of testBackends()) {
.toEqual({ args: args.join(' '), exit: 0, ran: false, help: true });
}
const { existsSync } = await import('node:fs');
- expect({ mount: existsSync(mountPath), db: existsSync(join(root, 'help.db')) }).toEqual({ mount: false, db: false });
+ expect({ mount: existsSync(mountPath), db: existsSync(join(brain.root, 'help.db')) }).toEqual({ mount: false, db: false });
}, 300_000);
test('entity prints no mention coverage count under the mode', async () => {
@@ -450,129 +246,6 @@ for (const kind of testBackends()) {
expect({ exit: human.exitCode, pending: /page\(s\) pending/.test(human.stdout) }).toEqual({ exit: 0, pending: false });
}, 300_000);
- test('--source on a read carries the scope like a remote credential; an unknown source refuses like a hidden one', async () => {
- await withBrain(async engine => {
- await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('team-src', 'team-src') ON CONFLICT DO NOTHING");
- await importFromContent(engine, 'notes/team-src-page', '---\ntype: note\ntitle: Team source page\n---\n# Team source page\n\nHarbor team body canaryemteamsrc.\n', { sourceId: 'team-src', noEmbed: true });
- });
- for (const args of [['get', 'notes/team-src-page', '--source', 'team-src'], ['list', '--source', 'team-src', '--json'], ['search', 'harbor team', '--source', 'team-src', '--json']]) {
- const r = await cli(args);
- expect({ args: args[0], exit: r.exitCode, seen: /team-src-page|canaryemteamsrc/.test(r.stdout), nudge: /sole non-default|routing to source/.test(r.stderr) })
- .toEqual({ args: args[0], exit: 0, seen: true, nudge: false });
- }
- const hidden = await cli(['get', 'notes/never-written-example', '--source', 'bob-dm']);
- for (const args of [['get', 'notes/never-written-example', '--source', 'nosuch-example'], ['get', 'notes/never-written-example', '--source-id', 'nosuch-example']]) {
- const r = await cli(args);
- expect({ args: args.join(' '), exit: r.exitCode, err: r.stderr, out: r.stdout }).toEqual({ args: args.join(' '), exit: hidden.exitCode, err: hidden.stderr, out: hidden.stdout });
- }
- expect(hidden.exitCode).toBe(3);
- }, 300_000);
-
- test("entity text_mentions lists a visible page that names the entity and leaves a hidden one out", async () => {
- const page = (slug: string, type: string, title: string, fm: string, body: string) =>
- '---\ntype: ' + type + '\ntitle: ' + JSON.stringify(title) + '\n' + fm + '---\n# ' + title + '\n\n' + body + '\n';
- await withBrain(async engine => {
- await importFromContent(engine, 'people/carol-example', page('people/carol-example', 'person', 'Carol Example', '', 'A person page.'), { sourceId: 'default', noEmbed: true });
- await importFromContent(engine, 'notes/bob-carol-memo', page('notes/bob-carol-memo', 'note', 'Bob memo canaryemtmhidden', 'readable_by: [bob-example]\n', 'Met Carol Example about the canaryemtmhidden plan.'), { sourceId: 'default', noEmbed: true });
- await importFromContent(engine, 'notes/open-carol-memo', page('notes/open-carol-memo', 'note', 'Open memo canaryemtmopen', '', 'Met Carol Example about the open plan.'), { sourceId: 'default', noEmbed: true });
- });
- const marks = ['notes/bob-carol-memo', 'Bob memo canaryemtmhidden', 'canaryemtmhidden'];
- const trusted = JSON.parse((await cli(['entity', 'Carol Example', '--json'], { member: null })).stdout);
- expect({ control: trusted.card?.text_mentions?.pages?.map((x: { slug: string }) => x.slug).sort() }).toEqual({ control: ['notes/bob-carol-memo', 'notes/open-carol-memo'] });
- const r = await cli(['entity', 'Carol Example', '--json']);
- const tm = JSON.parse(r.stdout).card?.text_mentions;
- expect({ exit: r.exitCode, slugs: tm?.pages?.map((x: { slug: string }) => x.slug), total: tm?.total, leaks: marks.filter(m => (r.stdout + r.stderr).includes(m)) })
- .toEqual({ exit: 0, slugs: ['notes/open-carol-memo'], total: 1, leaks: [] });
- const human = await cli(['entity', 'Carol Example']);
- expect({ exit: human.exitCode, open: human.stdout.includes('notes/open-carol-memo'), count: /text of 1 other page/.test(human.stdout), leaks: marks.filter(m => (human.stdout + human.stderr).includes(m)) })
- .toEqual({ exit: 0, open: true, count: true, leaks: [] });
- }, 300_000);
-
- test('access.enforced_member_writes refuse: every member write refuses before any lookup, reads and the trusted CLI are unchanged', async () => {
- const KEY = 'access.enforced_member_writes';
- const setKey = async (value: string) => {
- const r = await cli(['config', 'set', KEY, value], { member: null });
- expect({ value, exit: r.exitCode, err: r.exitCode === 0 ? '' : r.stderr }).toEqual({ value, exit: 0, err: '' });
- };
- const page = (title: string, fm = '') => '---\ntype: note\ntitle: ' + JSON.stringify(title) + '\n' + fm + '---\n# ' + title + '\n\nHarbor ledger planning notes for the roadmap.\n';
- const writes: Array<[string[], string | undefined]> = [
- [['put', 'notes/writes-off-new-example'], page('Writes off new')],
- [['put', PAGES.open.slug], page(PAGES.open.title)],
- [['put', PAGES.other.slug], page(PAGES.other.title, 'readable_by: ["bob-example"]\n')],
- [['link', PAGES.open.slug, PAGES.team.slug], undefined],
- [['unlink', PAGES.open.slug, PAGES.other.slug], undefined],
- [['tag', PAGES.open.slug, 'writes-off-tag'], undefined],
- [['untag', PAGES.open.slug, 'writes-off-tag'], undefined],
- [['timeline-add', PAGES.open.slug, '2026-02-01', 'Writes off event'], undefined],
- [['remember', 'Writes off fact canaryemwritesoff', '--entity', PAGES.open.slug, '--provenance', 'test turn'], undefined],
- ];
- const counts = () => withBrain(async engine => {
- const out: Record<string, number> = {};
- for (const table of ['pages', 'links', 'tags', 'timeline_entries', 'facts']) out[table] = (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM ' + table))[0]!.n;
- out.content = (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE compiled_truth LIKE '%' || $1 || '%'", [PAGES.open.canary]))[0]!.n;
- return out;
- });
- const reads: string[][] = [['list', '--json'], ['get', PAGES.open.slug], ['search', 'harbor ledger', '--json'], ['recall', PAGES.open.slug, '--json'], ['stats', '--by', 'type', '--json']];
- const readAll = async () => {
- const out: Array<{ args: string; exit: number; out: string; notice: boolean }> = [];
- for (const args of reads) { const r = await cli(args); out.push({ args: args.join(' '), exit: r.exitCode, out: r.stdout, notice: r.stderr.includes(NOTICE) }); }
- return out;
- };
- const checkedReads = await readAll();
- const before = await counts();
- try {
- await setKey('refuse');
- expect(await readAll()).toEqual(checkedReads);
- const texts = new Set<string>();
- for (const [args, stdin] of writes) {
- const r = await cli(args, { stdin });
- const first = r.stderr.split('\n')[0];
- expect({ args: args.join(' '), exit: r.exitCode, first, out: r.stdout, leaks: leaks(r.stdout + r.stderr) })
- .toEqual({ args: args.join(' '), exit: 3, first: WRITES_OFF_FIRST, out: '', leaks: [] });
- texts.add(r.stderr);
- }
- expect(texts.size).toBe(1);
- const [text] = [...texts];
- expect(text).toContain('Recovery: nothing was saved');
- expect(text).toContain('Why: This brain turned off member writes under this mode');
- expect(text).toContain('brain owner');
- for (const slug of ['notes/writes-off-new-example', PAGES.open.slug, PAGES.other.slug, 'notes', 'harbor']) expect({ slug, named: text!.includes(slug) }).toEqual({ slug, named: false });
- const json = await cli(['put', 'notes/writes-off-new-example', '--json'], { stdin: page('Writes off new') });
- expect({ exit: json.exitCode, envelope: json.stdout.includes('enforced_member_refused'), reason: /"reason":\s*"writes_off"/.test(json.stdout) })
- .toEqual({ exit: 3, envelope: true, reason: true });
- const receipt = await cli(['write-request', crypto.randomUUID()]);
- expect(receipt.stderr).not.toContain(WRITES_OFF_FIRST);
- expect(await counts()).toEqual(before);
- for (const value of ['chekced', 'REFUSE ']) {
- await setKey(value);
- const r = await cli(['tag', PAGES.open.slug, 'writes-off-tag']);
- expect({ value, exit: r.exitCode, first: r.stderr.split('\n')[0], why: r.stderr.includes('turned off member writes') }).toEqual({ value, exit: 3, first: WRITES_OFF_FIRST, why: true });
- }
- await setKey('refuse_pages');
- for (const [args, stdin] of writes) {
- const r = await cli(args, { stdin });
- expect({ args: args.join(' '), exit: r.exitCode, first: r.stderr.split('\n')[0], why: r.stderr.includes('Why: This brain turned off member page writes under this mode') })
- .toEqual({ args: args.join(' '), exit: 3, first: WRITES_OFF_FIRST, why: true });
- }
- expect(await readAll()).toEqual(checkedReads);
- expect(await counts()).toEqual(before);
- await setKey('refuse');
- for (const [args, stdin] of writes.filter(([a]) => a[0] !== 'put' || a[1] === 'notes/writes-off-new-example')) {
- const r = await cli(args, { member: null, stdin });
- expect({ args: args.join(' '), exit: r.exitCode, err: r.exitCode === 0 ? '' : r.stderr }).toEqual({ args: args.join(' '), exit: 0, err: '' });
- }
- const after = await counts();
- expect({ pages: after.pages, facts: after.facts, timeline: after.timeline_entries }).toEqual({ pages: before.pages + 1, facts: before.facts + 1, timeline: before.timeline_entries + 1 });
- await setKey('checked');
- const allowed = await cli(['tag', PAGES.open.slug, 'writes-checked-tag']);
- expect({ exit: allowed.exitCode, err: allowed.exitCode === 0 ? '' : allowed.stderr }).toEqual({ exit: 0, err: '' });
- const hidden = await cli(['put', PAGES.other.slug], { stdin: page('Overwrite') });
- expect({ exit: hidden.exitCode, first: hidden.stderr.split('\n')[0] }).toEqual({ exit: 3, first: FIRST(MEMBER, 'put') });
- } finally {
- await withBrain(engine => engine.executeRaw('DELETE FROM config WHERE key = $1', [KEY]));
- }
- }, 900_000);
-
test('variable unset: output is unchanged', async () => {
for (const args of [['list', '--json'], ['get', PAGES.other.slug], ['stats', '--json']]) {
const a = await cli(args, { member: null });
@@ -583,154 +256,3 @@ for (const kind of testBackends()) {
}, 300_000);
});
}
-
-for (const kind of testBackends()) {
- describe('enforced member mode: git commit-push and sync (' + kind + ')', () => {
- let root: string, home: string, checkout: string;
- let config: Record<string, unknown>;
- let closePg: (() => Promise<void>) | null = null;
-
- function env(member: string | null): Record<string, string> {
- const out: Record<string, string> = {};
- for (const [k, v] of Object.entries(process.env)) if (v !== undefined) out[k] = v;
- for (const k of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_BRAIN_ID', 'GBRAIN_SOURCE', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY', 'GEMINI_API_KEY', 'GBRAIN_ENFORCED_MEMBER']) delete out[k];
- return { ...out, HOME: home, GBRAIN_HOME: home, GBRAIN_SELF_UPGRADE_MODE: 'off', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SWEEP: '0', GBRAIN_CLI_SOCKET: '0',
- GIT_AUTHOR_NAME: 'Example', GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'Example', GIT_COMMITTER_EMAIL: '[email protected]', ...(member === null ? {} : { GBRAIN_ENFORCED_MEMBER: member }) };
- }
- async function cli(args: string[], member: string | null = MEMBER) {
- const proc = Bun.spawn(['bun', 'run', CLI, ...args], { cwd: checkout, env: env(member), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
- const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
- return { stdout, stderr, exitCode };
- }
- const git = (...args: string[]) => execFileSync('git', ['-C', checkout, ...args], { env: env(null), stdio: ['ignore', 'pipe', 'pipe'] }).toString();
- const note = (title: string, fm = '') => '---\ntype: note\ntitle: ' + title + '\n' + fm + '---\n# ' + title + '\n\nHarbor notes.\n';
-
- beforeAll(async () => {
- root = mkdtempSync(join(tmpdir(), 'gb-enforced-git-'));
- home = join(root, 'home');
- checkout = join(root, 'checkout');
- const remote = join(root, 'remote.git');
- mkdirSync(join(home, '.gbrain'), { recursive: true });
- execFileSync('git', ['init', '-q', '--bare', '-b', 'main', remote]);
- execFileSync('git', ['clone', '-q', remote, checkout], { stdio: 'ignore' });
- mkdirSync(join(checkout, 'notes'), { recursive: true });
- writeFileSync(join(checkout, 'notes', 'open-git.md'), note('Open git'));
- writeFileSync(join(checkout, 'notes', 'bob-git.md'), note('Bob git', 'readable_by: [bob-example]\n'));
- git('checkout', '-q', '-b', 'main');
- git('add', '-A');
- git('commit', '-qm', 'synthetic content');
- git('push', '-q', 'origin', 'main');
- if (kind === 'postgres') {
- const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
- await pg.engine.disconnect();
- config = { engine: 'postgres', database_url: pg.databaseUrl };
- closePg = pg.close;
- } else {
- config = { engine: 'pglite', database_path: join(root, 'db') };
- }
- writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(config));
- const engine = await createEngine(config as never);
- await engine.connect(config as never);
- try {
- if (kind === 'pglite') await engine.initSchema();
- for (const id of [MEMBER, 'bob-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);
- await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('repo-src', 'repo-src', $1)", [checkout]);
- } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }
- const synced = await cli(['sync', '--source', 'repo-src', '--no-pull', '--no-embed'], null);
- expect({ exit: synced.exitCode, err: synced.exitCode === 0 ? '' : synced.stderr }).toEqual({ exit: 0, err: '' });
- }, 300_000);
-
- afterAll(async () => {
- rmSync(root, { recursive: true, force: true });
- await closePg?.();
- }, 60_000);
-
- test('commit-push refuses a hidden file, a label change, a policy file and the refused modes', async () => {
- writeFileSync(join(checkout, 'notes', 'bob-git.md'), note('Bob git', 'readable_by: [bob-example]\n') + 'More.\n');
- writeFileSync(join(checkout, 'notes', 'open-git.md'), note('Open git', 'visibility: private\n'));
- mkdirSync(join(checkout, '.gbrain'), { recursive: true });
- writeFileSync(join(checkout, '.gbrain', 'access.yml'), 'rules: []\n');
- const cases: string[][] = [
- ['git', 'commit-push', '--path', checkout, '-m', 'x', '--', 'notes/bob-git.md'],
- ['git', 'commit-push', '--path', checkout, '-m', 'x', '--', 'notes/open-git.md'],
- ['git', 'commit-push', '--path', checkout, '-m', 'x', '--', 'notes'],
- ['git', 'commit-push', '--path', checkout, '-m', 'x', '--', '.gbrain/access.yml'],
- ['git', 'commit-push', '--path', checkout, '--pending'],
- ['git', 'commit-push', '--path', checkout, '--push-only'],
- ['git', 'guard', '--install'],
- ];
- for (const args of cases) {
- const r = await cli(args);
- const command = args[1] === 'guard' ? 'git guard' : 'git commit-push';
- expect({ args: args.slice(-1)[0], exit: r.exitCode, first: r.stderr.split('\n')[0] }).toEqual({ args: args.slice(-1)[0], exit: 3, first: FIRST(MEMBER, command) });
- }
- expect(git('status', '--porcelain')).toContain('notes/bob-git.md');
- git('checkout', '-q', '--', 'notes');
- rmSync(join(checkout, '.gbrain'), { recursive: true, force: true });
- }, 300_000);
-
- test('commit-push of a readable new file and --pull run with their output withheld', async () => {
- writeFileSync(join(checkout, 'notes', 'alice-git.md'), note('Alice git'));
- const r = await cli(['git', 'commit-push', '--path', checkout, '-m', 'alice note', '--', 'notes/alice-git.md']);
- expect({ exit: r.exitCode, out: r.stdout, err: r.stderr }).toEqual({ exit: 0, out: '', err: 'gbrain: git commit-push finished; its output is withheld under GBRAIN_ENFORCED_MEMBER\n' });
- expect(git('log', '--format=%s', '-1').trim()).toBe('alice note');
- const pull = await cli(['git', 'commit-push', '--path', checkout, '--pull']);
- expect({ exit: pull.exitCode, out: pull.stdout, err: pull.stderr }).toEqual({ exit: 0, out: '', err: 'gbrain: git commit-push finished; its output is withheld under GBRAIN_ENFORCED_MEMBER\n' });
- }, 300_000);
-
- test('access.enforced_member_writes: refuse closes named-path commit-push, refuse_pages keeps it; --pull, --dry-run and sync run under both', async () => {
- const setKey = async (value: string) => {
- const r = await cli(['config', 'set', 'access.enforced_member_writes', value], null);
- expect({ value, exit: r.exitCode, err: r.exitCode === 0 ? '' : r.stderr }).toEqual({ value, exit: 0, err: '' });
- };
- const WITHHELD = (command: string) => 'gbrain: ' + command + ' finished; its output is withheld under GBRAIN_ENFORCED_MEMBER\n';
- const stillRuns = async (mode: string) => {
- const pull = await cli(['git', 'commit-push', '--path', checkout, '--pull']);
- expect({ mode, exit: pull.exitCode, out: pull.stdout, err: pull.stderr }).toEqual({ mode, exit: 0, out: '', err: WITHHELD('git commit-push') });
- const dry = await cli(['git', 'commit-push', '--path', checkout, '--dry-run', '-m', 'dry', '--', 'notes/alice-git-mode.md']);
- expect({ mode, exit: dry.exitCode, out: dry.stdout, err: dry.stderr }).toEqual({ mode, exit: 0, out: '', err: WITHHELD('git commit-push') });
- const sync = await cli(['sync', '--source', 'repo-src', '--no-pull', '--no-embed']);
- expect({ mode, exit: sync.exitCode, out: sync.stdout, err: sync.stderr }).toEqual({ mode, exit: 0, out: '', err: WITHHELD('sync') });
- };
- try {
- writeFileSync(join(checkout, 'notes', 'alice-git-mode.md'), note('Alice git mode'));
- await setKey('refuse');
- const headBefore = git('rev-parse', 'HEAD').trim();
- const texts = new Set<string>();
- for (const path of ['notes/alice-git-mode.md', 'notes/bob-git.md', 'notes/never-written-git.md']) {
- const r = await cli(['git', 'commit-push', '--path', checkout, '-m', 'x', '--', path]);
- expect({ path, exit: r.exitCode, first: r.stderr.split('\n')[0], out: r.stdout }).toEqual({ path, exit: 3, first: WRITES_OFF_FIRST, out: '' });
- texts.add(r.stderr);
- }
- expect(texts.size).toBe(1);
- expect([...texts][0]).toContain('turned off member writes');
- expect(git('rev-parse', 'HEAD').trim()).toBe(headBefore);
- await stillRuns('refuse');
- await setKey('refuse_pages');
- const r = await cli(['git', 'commit-push', '--path', checkout, '-m', 'alice note under refuse_pages', '--', 'notes/alice-git-mode.md']);
- expect({ exit: r.exitCode, out: r.stdout, err: r.stderr }).toEqual({ exit: 0, out: '', err: WITHHELD('git commit-push') });
- expect(git('log', '--format=%s', '-1').trim()).toBe('alice note under refuse_pages');
- const hidden = await cli(['git', 'commit-push', '--path', checkout, '-m', 'x', '--', 'notes/bob-git.md']);
- expect({ exit: hidden.exitCode, first: hidden.stderr.split('\n')[0] }).toEqual({ exit: 3, first: FIRST(MEMBER, 'git commit-push') });
- await stillRuns('refuse_pages');
- } finally {
- const engine = await createEngine(config as never);
- await engine.connect(config as never);
- try { await engine.executeRaw("DELETE FROM config WHERE key = 'access.enforced_member_writes'"); } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }
- }
- }, 300_000);
-
- test('sync runs with its output withheld; sync status is refused', async () => {
- const r = await cli(['sync', '--source', 'repo-src', '--no-pull', '--no-embed']);
- expect({ exit: r.exitCode, out: r.stdout, err: r.stderr }).toEqual({ exit: 0, out: '', err: 'gbrain: sync finished; its output is withheld under GBRAIN_ENFORCED_MEMBER\n' });
- const json = await cli(['sync', '--source', 'repo-src', '--no-pull', '--no-embed', '--json']);
- expect({ exit: json.exitCode, out: json.stdout, err: json.stderr }).toEqual({ exit: 0, out: '', err: 'gbrain: sync finished; its output is withheld under GBRAIN_ENFORCED_MEMBER\n' });
- for (const args of [['sync', '--source', 'repo-src', '--repo', root, '--no-pull'], ['sync', '--repo', checkout], ['sync', '--source', 'repo-src', '--reset-checkpoint']]) {
- const refused = await cli(args);
- expect({ args: args.join(' '), exit: refused.exitCode, first: refused.stderr.split('\n')[0] }).toEqual({ args: args.join(' '), exit: 3, first: FIRST(MEMBER, 'sync') });
- }
- const status = await cli(['sync', 'status', '--source', 'repo-src']);
- expect({ exit: status.exitCode, first: status.stderr.split('\n')[0] }).toEqual({ exit: 3, first: FIRST(MEMBER, 'sync status') });
- }, 300_000);
- });
-}
diff --git a/test/helpers/enforced-member-brain.ts b/test/helpers/enforced-member-brain.ts
new file mode 100644
index 0000000000..c95fa73c3b
--- /dev/null
+++ b/test/helpers/enforced-member-brain.ts
@@ -0,0 +1,135 @@
+/**
+ * The shared fixture of the enforced member mode suites (GST-2476 G2): one repo-less brain on disk (PGLite, or one
+ * isolated Postgres database), seeded with pages each member can or cannot read, and a spawner that runs the real
+ * src/cli.ts as a child under GBRAIN_ENFORCED_MEMBER in a temp GBRAIN_HOME.
+ *
+ * Each suite file that calls enforcedMemberBrain() inside its describe gets its own brain, seeded the same way, so a
+ * file never sees another file's writes. Used by test/enforced-member.serial.test.ts (reads and refusals),
+ * test/enforced-member-writes.serial.test.ts (writes) and test/enforced-member-writes-setting.serial.test.ts
+ * (access.enforced_member_writes).
+ */
+import { afterAll, beforeAll } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { createEngine } from '../../src/core/engine-factory.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { proposeRevision } from '../../src/core/access/policy.ts';
+import { bindCredential } from '../../src/core/access/members.ts';
+import { setOwner } from '../../src/core/access/owner.ts';
+import { mintLegacyToken } from '../../src/core/token-mint.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import type { TestBackend } from './test-backends.ts';
+import { isolatedPersistencePostgres } from './persistence-postgres.ts';
+
+export const CLI = join(resolve(import.meta.dir, '..', '..'), 'src', 'cli.ts');
+export const MEMBER = 'alice-example';
+export const OWNER = 'owner-example';
+export const FIRST = (who: string, command: string) => 'gbrain: refused under GBRAIN_ENFORCED_MEMBER=' + who + ': ' + command + ' [GBRAIN_ENFORCED_REFUSED]';
+export const NOTICE = 'gbrain: results limited to what GBRAIN_ENFORCED_MEMBER=' + MEMBER + ' may read';
+export const REMEMBER_FIRST = 'gbrain: refused under GBRAIN_ENFORCED_MEMBER=' + MEMBER + ': remember saves a fact only with --entity <slug of a page you can read>; nothing was saved [GBRAIN_ENFORCED_REFUSED]';
+export const WRITES_OFF_FIRST = 'gbrain: refused under GBRAIN_ENFORCED_MEMBER=' + MEMBER + ': writes are off for members on this brain; nothing was saved [GBRAIN_ENFORCED_REFUSED]';
+export const REMEMBER_RETRY = 'Retry: gbrain remember "<one fact>" --entity <exact slug of a page you can read, from gbrain find or gbrain search> --provenance "<where you learned it>"';
+
+export const PAGES = {
+ open: { slug: 'notes/open-example', title: 'Open example plan', canary: 'canaryemopen', fm: {} as Record<string, unknown>, source: 'default' },
+ mine: { slug: 'notes/alice-example-plan', title: 'Alice example plan', canary: 'canaryemmine', fm: { readable_by: [MEMBER] }, source: 'default' },
+ team: { slug: 'team-a/roadmap-example', title: 'Team a roadmap', canary: 'canaryemteam', fm: {}, source: 'default' },
+ other: { slug: 'notes/bob-example-plan', title: 'Bob example secret', canary: 'canaryemother', fm: { readable_by: ['bob-example'] }, source: 'default' },
+ priv: { slug: 'notes/quiet-example', title: 'Quiet example memo', canary: 'canaryempriv', fm: { visibility: 'private' }, source: 'default' },
+ folder: { slug: 'team-b/budget-example', title: 'Team b budget', canary: 'canaryemfolder', fm: {}, source: 'default' },
+ personal: { slug: 'notes/dm-example', title: 'Direct example thread', canary: 'canaryempersonal', fm: {}, source: 'bob-dm' },
+} as const;
+export type Key = keyof typeof PAGES;
+export const VISIBLE: Key[] = ['open', 'mine', 'team'];
+export const HIDDEN: Key[] = ['other', 'priv', 'folder', 'personal'];
+export const HIDDEN_FACT = 'canaryemfacthidden';
+export const OPEN_FACT = 'canaryemfactopen';
+export const HIDDEN_MARKS = [...HIDDEN.flatMap(k => [PAGES[k].slug, PAGES[k].title, PAGES[k].canary]), HIDDEN_FACT];
+export const leaks = (text: string) => HIDDEN_MARKS.filter(m => text.toLowerCase().includes(m.toLowerCase()));
+
+export interface EnforcedMemberBrain {
+ /** The temp directory holding the brain, its GBRAIN_HOME and any scratch files a case writes. */
+ readonly root: string;
+ /** A read-scope token bound to OWNER, for reading back what a member wrote. */
+ readonly ownerToken: string;
+ cli(args: string[], opts?: { member?: string | null; stdin?: string }): Promise<{ stdout: string; stderr: string; exitCode: number }>;
+ withBrain<T>(run: (engine: BrainEngine) => Promise<T>): Promise<T>;
+}
+
+/** Registers the brain's beforeAll / afterAll in the calling describe and returns its handles. */
+export function enforcedMemberBrain(kind: TestBackend): EnforcedMemberBrain {
+ let root = '', home = '';
+ let config: Record<string, unknown>;
+ let closePg: (() => Promise<void>) | null = null;
+ let ownerToken = '';
+
+ function env(extra: Record<string, string | undefined>): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined) out[k] = v;
+ for (const k of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_BRAIN_ID', 'GBRAIN_SOURCE', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY', 'GEMINI_API_KEY', 'GBRAIN_ENFORCED_MEMBER']) delete out[k];
+ const merged: Record<string, string | undefined> = { ...out, HOME: home, GBRAIN_HOME: home, GBRAIN_SELF_UPGRADE_MODE: 'off', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SWEEP: '0', GBRAIN_CLI_SOCKET: '0', ...extra };
+ return Object.fromEntries(Object.entries(merged).filter(([, v]) => v !== undefined)) as Record<string, string>;
+ }
+ async function cli(args: string[], opts: { member?: string | null; stdin?: string } = {}) {
+ const member = opts.member === undefined ? MEMBER : opts.member;
+ const proc = Bun.spawn(['bun', 'run', CLI, ...args], { cwd: root, env: env({ GBRAIN_ENFORCED_MEMBER: member ?? undefined }),
+ stdin: opts.stdin === undefined ? 'ignore' : new Blob([opts.stdin]), stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { stdout, stderr, exitCode };
+ }
+ async function withBrain<T>(run: (engine: BrainEngine) => Promise<T>): Promise<T> {
+ const engine = await createEngine(config as never);
+ await engine.connect(config as never);
+ try { return await run(engine); } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ }
+
+ beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'gb-enforced-'));
+ home = join(root, 'home');
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ if (kind === 'postgres') {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ await pg.engine.disconnect();
+ config = { engine: 'postgres', database_url: pg.databaseUrl };
+ closePg = pg.close;
+ } else {
+ config = { engine: 'pglite', database_path: join(root, 'db') };
+ }
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(config));
+ await withBrain(async engine => {
+ if (kind === 'pglite') await engine.initSchema();
+ await engine.executeRaw("INSERT INTO sources (id, name, config) VALUES ('bob-dm', 'bob-dm', '{\"federated\": true}'::jsonb) ON CONFLICT (id) DO NOTHING");
+ for (const id of [MEMBER, 'bob-example', OWNER]) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);
+ await engine.executeRaw("INSERT INTO access_groups (id) VALUES ('team-a'), ('team-b') ON CONFLICT DO NOTHING");
+ await engine.executeRaw("INSERT INTO access_group_members (group_id, member_id) VALUES ('team-a', $1), ('team-b', 'bob-example')", [MEMBER]);
+ await engine.executeRaw("INSERT INTO access_member_sources (member_id, source_id) VALUES ('bob-example', 'bob-dm')");
+ await proposeRevision(engine, 'default', [
+ { id: 'team-a', prefix: 'team-a/', readable_by: ['group:team-a'] },
+ { id: 'team-b', prefix: 'team-b/', readable_by: ['group:team-b'] },
+ ] as never, { origin: 'cli', store: 'database' } as never);
+ for (const key of Object.keys(PAGES) as Key[]) {
+ const p = PAGES[key];
+ const fm = Object.entries(p.fm).map(([k, v]) => k + ': ' + JSON.stringify(v)).join('\n');
+ await importFromContent(engine, p.slug, '---\ntype: note\ntitle: ' + JSON.stringify(p.title) + '\n' + (fm ? fm + '\n' : '') + '---\n# ' + p.title + '\n\nHarbor ledger planning notes ' + p.canary + ' for the roadmap.\n', { sourceId: p.source, noEmbed: true });
+ }
+ await engine.addLink(PAGES.open.slug, PAGES.other.slug, 'see the secret plan', 'mentions');
+ await engine.addLink(PAGES.other.slug, PAGES.open.slug, 'back to open', 'mentions');
+ await engine.addTimelineEntry(PAGES.other.slug, { date: '2026-01-02', summary: 'Hidden event ' + HIDDEN_FACT } as never, { sourceId: 'default' });
+ await engine.insertFact({ fact: 'Harbor ledger fact ' + HIDDEN_FACT, entity_slug: PAGES.other.slug, visibility: 'world', source: 'test', embedding: null }, { source_id: 'default' });
+ await engine.insertFact({ fact: 'Harbor ledger fact ' + OPEN_FACT, entity_slug: PAGES.open.slug, visibility: 'world', source: 'test', embedding: null }, { source_id: 'default' });
+ const minted = await mintLegacyToken(engine, { name: 'owner-key', scopes: ['read'], takesHolders: ['world'] } as never);
+ ownerToken = minted.token;
+ await bindCredential(engine, { kind: 'token', id: minted.id }, { member: OWNER });
+ await setOwner(engine, OWNER);
+ });
+ }, 240_000);
+
+ afterAll(async () => {
+ rmSync(root, { recursive: true, force: true });
+ await closePg?.();
+ }, 60_000);
+
+ return { get root() { return root; }, get ownerToken() { return ownerToken; }, cli, withBrain };
+}
diff --git a/test/helpers/setup-serves-box.ts b/test/helpers/setup-serves-box.ts
new file mode 100644
index 0000000000..4fdc463627
--- /dev/null
+++ b/test/helpers/setup-serves-box.ts
@@ -0,0 +1,84 @@
+/**
+ * The spawned half of the gbrain setup --serves suites (GST-363): a temp HOME / GBRAIN_HOME box with a gbrain launcher
+ * that runs this checkout's src/cli.ts, and the readers those suites assert through. Used by
+ * test/setup-serves-several.test.ts, test/setup-serves-stdio-member.test.ts and test/setup-serves-upgrade.test.ts; each
+ * case builds its own box, so no case reads another's brain.
+ */
+import { expect } from 'bun:test';
+import { chmodSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { ownedEntryFingerprint } from '../../src/core/bootstrap/adopted-connections.ts';
+import { runCli, type CliResult } from './cli-spawn.ts';
+
+export const ROSTER = ['alice-example', 'bob-example'];
+export const PAGES: Record<string, string> = {
+ 'people/alice-example/plan': 'alicecanary',
+ 'people/bob-example/plan': 'bobcanary',
+ 'people/carol-public': 'carolcanary',
+ 'notes/world-topic': 'worldcanary',
+};
+export const pageText = (slug: string, canary: string) => `---\ntype: note\ntitle: ${slug}\n---\n# ${slug}\n\nHarbor ledger notes ${canary}.\n`;
+const roots: string[] = [];
+/** A temp directory removeTempDirs() deletes; register afterAll(removeTempDirs) in each file that makes one. */
+export const tempDir = (prefix: string) => { const d = mkdtempSync(join(tmpdir(), prefix)); roots.push(d); return d; };
+export const removeTempDirs = () => { for (const r of roots.splice(0)) rmSync(r, { recursive: true, force: true }); };
+
+export const CLI = resolve(import.meta.dir, '..', '..', 'src', 'cli.ts');
+export const CLEAN = { CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: undefined, GBRAIN_SOURCE: undefined, GBRAIN_SURFACE: undefined, GBRAIN_HOOKS: undefined, GBRAIN_SETUP_ABORT_AFTER: undefined };
+export interface Box { root: string; home: string; bin: string }
+
+export function box(): Box {
+ const root = tempDir('gbrain-setup-serves-');
+ const home = join(root, 'home');
+ mkdirSync(home, { recursive: true });
+ const bin = join(root, 'bin', 'gbrain');
+ mkdirSync(join(root, 'bin'));
+ writeFileSync(bin, `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${CLI}' "$@"\n`);
+ chmodSync(bin, 0o755);
+ return { root, home, bin };
+}
+export const gbrain = (b: Box, args: string[], env: Record<string, string | undefined> = {}) => runCli(args, { env: { ...CLEAN, HOME: b.home, GBRAIN_HOME: b.home, OPENCLAW_STATE_DIR: join(b.root, 'openclaw-state'), OPENCLAW_PROFILE: undefined, HERMES_HOME: join(b.root, 'hermes-home'), ...env }, timeoutMs: 120_000 });
+export async function setup(b: Box, args: string[]): Promise<CliResult & { doc: any }> {
+ const r = await gbrain(b, ['setup', ...args, '--gbrain-bin', b.bin]);
+ let doc: any = null;
+ if (args.includes('--json')) { try { doc = JSON.parse(r.stdout); } catch { doc = null; } }
+ return { ...r, doc };
+}
+export async function brainWithPages(b: Box): Promise<void> {
+ expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
+ for (const [slug, canary] of Object.entries(PAGES)) expect((await gbrain(b, ['put', slug, '--content', pageText(slug, canary)])).exitCode).toBe(0);
+}
+export const entry = (b: Box) => JSON.parse(readFileSync(join(b.home, '.claude.json'), 'utf8')).mcpServers.gbrain as { command: string; args: string[] };
+export const entryArgs = (b: Box) => entry(b).args;
+/** setup's claude-code entry as it was before the launcher (#8426), still owned by its receipt, so post-upgrade rewrites it. */
+export function staleEntry(b: Box): void {
+ const cfgPath = join(b.home, '.claude.json');
+ const cfg = JSON.parse(readFileSync(cfgPath, 'utf8'));
+ cfg.mcpServers.gbrain = { ...cfg.mcpServers.gbrain, command: b.bin };
+ writeFileSync(cfgPath, JSON.stringify(cfg, null, 2));
+ const receiptPath = join(b.home, '.gbrain-connection-claude-code-gbrain.json');
+ const receipt = JSON.parse(readFileSync(receiptPath, 'utf8'));
+ writeFileSync(receiptPath, JSON.stringify({ ...receipt, entry_hash: ownedEntryFingerprint(cfg.mcpServers.gbrain) }, null, 2));
+}
+export const stdioKey = async (b: Box) => { const r = await gbrain(b, ['config', 'get', 'mcp.stdio_member']); return r.exitCode === 0 ? r.stdout.trim() : ''; };
+export function fakeOpenclaw(b: Box): string {
+ const dir = join(b.root, 'oc-bin');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'openclaw'), '#!/bin/sh\nexit 0\n');
+ chmodSync(join(dir, 'openclaw'), 0o755);
+ return dir;
+}
+/** Every setup connection receipt under the box's HOME. */
+export function setupReceipts(b: Box): any[] {
+ const found: any[] = [];
+ const walk = (d: string) => { for (const e of readdirSync(d, { withFileTypes: true })) {
+ const p = join(d, e.name);
+ if (e.isDirectory()) walk(p);
+ else if (e.name.endsWith('.json')) { try { const j = JSON.parse(readFileSync(p, 'utf8')); if (j?.connection === 'local-stdio' && j?.setup_receipt_version) found.push(j); } catch { /* not JSON */ } }
+ } };
+ walk(b.home);
+ return found;
+}
+export const claudeMd = (b: Box) => readFileSync(join(b.home, '.claude', 'CLAUDE.md'), 'utf8');
+export const normalized = (doc: any) => JSON.parse(JSON.stringify(doc).replace(/\d{4}-\d\d-\d\dT[\d:.]+Z/g, 'T'));
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 6abb9ec96e..8641430c30 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -108,6 +108,8 @@ test/effect-commit-moved-head.test.ts
test/embed-once-per-content-version.serial.test.ts
test/embed-stale-images-managed-6529.test.ts
test/embedding-completion-atomic.serial.test.ts
+test/enforced-member-writes-setting.serial.test.ts
+test/enforced-member-writes.serial.test.ts
test/enforced-member.serial.test.ts
test/engine-sql-facts-keyset.test.ts
test/extract-all-stamp-intersection.serial.test.ts
diff --git a/test/setup-serves-several.test.ts b/test/setup-serves-several.test.ts
index a727ae1a88..91f33ff075 100644
--- a/test/setup-serves-several.test.ts
+++ b/test/setup-serves-several.test.ts
@@ -18,9 +18,8 @@
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
-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 { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
import type { AuthInfo } from '../src/core/ops/contract.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -32,30 +31,17 @@ import { dispatchToolCall } from '../src/mcp/dispatch.ts';
import { labelSeveral, receiptOk, servesStatus, type ServesReceipt } from '../src/commands/access-serves.ts';
import { setupRerunArgv } from '../src/core/setup/launcher-lanes.ts';
import { servesPreflight } from '../src/commands/setup-serves.ts';
-import { refreshHookLaunchers } from '../src/core/setup/hook-launcher-refresh.ts';
-import { ownedEntryFingerprint } from '../src/core/bootstrap/adopted-connections.ts';
-import { readdirSync } from 'node:fs';
import { addMember } from '../src/core/access/members.ts';
import { unlabeledPeopleFoldersEntry } from '../src/commands/doctor/checks/unlabeled-people-folders.ts';
import type { DoctorContext } from '../src/commands/doctor/context.ts';
import { addFolderRules } from '../src/commands/access-rules.ts';
import { renderBrainFirstBlock, renderBrainFirstTurnRule, SERVES_SEVERAL_LINE } from '../src/core/setup/brain-first.ts';
-import { runCli, type CliResult } from './helpers/cli-spawn.ts';
import { testBackends } from './helpers/test-backends.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { withEnv } from './helpers/with-env.ts';
+import { brainWithPages, box, claudeMd, CLI, entryArgs, gbrain, PAGES, pageText, removeTempDirs, ROSTER, setup, setupReceipts, stdioKey, tempDir } from './helpers/setup-serves-box.ts';
-const ROSTER = ['alice-example', 'bob-example'];
-const PAGES: Record<string, string> = {
- 'people/alice-example/plan': 'alicecanary',
- 'people/bob-example/plan': 'bobcanary',
- 'people/carol-public': 'carolcanary',
- 'notes/world-topic': 'worldcanary',
-};
-const pageText = (slug: string, canary: string) => `---\ntype: note\ntitle: ${slug}\n---\n# ${slug}\n\nHarbor ledger notes ${canary}.\n`;
-const roots: string[] = [];
-afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });
-const tempDir = (prefix: string) => { const d = mkdtempSync(join(tmpdir(), prefix)); roots.push(d); return d; };
+afterAll(removeTempDirs);
const mode = (path: string) => (statSync(path).mode & 0o777).toString(8);
describe('brain-first text for the two shapes', () => {
@@ -278,65 +264,6 @@ describe('labelling refuses or reports what it cannot make safe (pglite, repo-le
}, 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 }
-
-function box(): Box {
- const root = tempDir('gbrain-setup-serves-');
- const home = join(root, 'home');
- mkdirSync(home, { recursive: true });
- const bin = join(root, 'bin', 'gbrain');
- mkdirSync(join(root, 'bin'));
- writeFileSync(bin, `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${CLI}' "$@"\n`);
- chmodSync(bin, 0o755);
- return { root, home, bin };
-}
-const gbrain = (b: Box, args: string[], env: Record<string, string | undefined> = {}) => runCli(args, { env: { ...CLEAN, HOME: b.home, GBRAIN_HOME: b.home, OPENCLAW_STATE_DIR: join(b.root, 'openclaw-state'), OPENCLAW_PROFILE: undefined, HERMES_HOME: join(b.root, 'hermes-home'), ...env }, timeoutMs: 120_000 });
-async function setup(b: Box, args: string[]): Promise<CliResult & { doc: any }> {
- const r = await gbrain(b, ['setup', ...args, '--gbrain-bin', b.bin]);
- let doc: any = null;
- if (args.includes('--json')) { try { doc = JSON.parse(r.stdout); } catch { doc = null; } }
- return { ...r, doc };
-}
-async function brainWithPages(b: Box): Promise<void> {
- expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
- for (const [slug, canary] of Object.entries(PAGES)) expect((await gbrain(b, ['put', slug, '--content', pageText(slug, canary)])).exitCode).toBe(0);
-}
-const entry = (b: Box) => JSON.parse(readFileSync(join(b.home, '.claude.json'), 'utf8')).mcpServers.gbrain as { command: string; args: string[] };
-const entryArgs = (b: Box) => entry(b).args;
-/** setup's claude-code entry as it was before the launcher (#8426), still owned by its receipt, so post-upgrade rewrites it. */
-function staleEntry(b: Box): void {
- const cfgPath = join(b.home, '.claude.json');
- const cfg = JSON.parse(readFileSync(cfgPath, 'utf8'));
- cfg.mcpServers.gbrain = { ...cfg.mcpServers.gbrain, command: b.bin };
- writeFileSync(cfgPath, JSON.stringify(cfg, null, 2));
- const receiptPath = join(b.home, '.gbrain-connection-claude-code-gbrain.json');
- const receipt = JSON.parse(readFileSync(receiptPath, 'utf8'));
- writeFileSync(receiptPath, JSON.stringify({ ...receipt, entry_hash: ownedEntryFingerprint(cfg.mcpServers.gbrain) }, null, 2));
-}
-const stdioKey = async (b: Box) => { const r = await gbrain(b, ['config', 'get', 'mcp.stdio_member']); return r.exitCode === 0 ? r.stdout.trim() : ''; };
-function fakeOpenclaw(b: Box): string {
- const dir = join(b.root, 'oc-bin');
- mkdirSync(dir, { recursive: true });
- writeFileSync(join(dir, 'openclaw'), '#!/bin/sh\nexit 0\n');
- chmodSync(join(dir, 'openclaw'), 0o755);
- return dir;
-}
-/** Every setup connection receipt under the box's HOME. */
-function setupReceipts(b: Box): any[] {
- const found: any[] = [];
- const walk = (d: string) => { for (const e of readdirSync(d, { withFileTypes: true })) {
- const p = join(d, e.name);
- if (e.isDirectory()) walk(p);
- else if (e.name.endsWith('.json')) { try { const j = JSON.parse(readFileSync(p, 'utf8')); if (j?.connection === 'local-stdio' && j?.setup_receipt_version) found.push(j); } catch { /* not JSON */ } }
- } };
- walk(b.home);
- return found;
-}
-const claudeMd = (b: Box) => readFileSync(join(b.home, '.claude', 'CLAUDE.md'), 'utf8');
-const normalized = (doc: any) => JSON.parse(JSON.stringify(doc).replace(/\d{4}-\d\d-\d\dT[\d:.]+Z/g, 'T'));
-
describe('gbrain setup --serves (spawned, PGLite)', () => {
test('--serves several labels each person, proves it with bound reads, prints key paths never values; a re-run keeps it all', async () => {
const b = box();
@@ -395,78 +322,6 @@ describe('gbrain setup --serves (spawned, PGLite)', () => {
}
}, 480_000);
- test('--stdio-member refuses an unknown member, off claude-code and codex, with --instructions-only or --no-stdio-member, and on a host with OpenClaw or Hermes; nothing is written', async () => {
- const b = box();
- await brainWithPages(b);
- for (const m of ROSTER) expect((await gbrain(b, ['access', 'member', 'add', m])).exitCode).toBe(0);
- expect((await gbrain(b, ['access', 'owner', 'set', 'alice-example'])).exitCode).toBe(0);
- const workspace = join(b.root, 'oc-workspace');
- mkdirSync(workspace);
- expect(existsSync(join(b.root, 'openclaw-state'))).toBe(false);
- const refusals: Array<[string[], string, Record<string, string>]> = [
- [['openclaw', '--serves', 'several', '--members', ROSTER.join(','), '--workspace', workspace, '--stdio-member', 'alice-example'], 'claude-code or codex', {}],
- [['claude-code', '--instructions-only', '--serves', 'several', '--stdio-member', 'alice-example'], 'claude-code or codex', {}],
- [['claude-code', '--stdio-member', 'alice-example', '--no-stdio-member'], 'not both', {}],
- [['claude-code', '--stdio-member', 'Alice Example'], 'needs a member id', {}],
- [['claude-code', '--stdio-member', 'alice-example'], 'OpenClaw is installed on this host', { PATH: `${fakeOpenclaw(b)}:${process.env.PATH}` }],
- [['codex', '--serves', 'several', '--members', ROSTER.join(','), '--stdio-member', 'alice-example'], 'Hermes is installed on this host', { HERMES_HOME: b.root }],
- ];
- for (const [args, says, env] of refusals) {
- const r = await gbrain(b, ['setup', ...args, '--gbrain-bin', b.bin], env);
- expect(r.exitCode).toBe(2);
- expect(r.stderr).toContain(says);
- if (says.endsWith('on this host')) expect(r.stderr).toContain('gbrain auth create <name> --member <id>');
- expect(await stdioKey(b)).toBe('');
- expect(existsSync(join(b.home, '.claude.json'))).toBe(false);
- }
- const unknown = await setup(b, ['claude-code', '--stdio-member', 'carol-example', '--json']);
- expect(unknown.exitCode).not.toBe(0);
- expect(unknown.stdout).toContain('not an enabled member of this brain');
- expect(unknown.stdout).toContain('alice-example, bob-example');
- expect(existsSync(join(b.home, '.claude.json'))).toBe(false);
- const labelled = await setup(b, ['openclaw', '--serves', 'several', '--members', ROSTER.join(','), '--workspace', workspace]);
- expect(labelled.stdout + labelled.stderr).not.toContain('reads as alice-example');
- expect(await stdioKey(b)).toBe('');
- }, 360_000);
-
- test('codex keeps an entry member on a bare re-run and --no-stdio-member removes it on a several-person brain; a plugin-served harness and serve on a shared host refuse the flag', async () => {
- const b = box();
- await brainWithPages(b);
- for (const m of ROSTER) expect((await gbrain(b, ['access', 'member', 'add', m])).exitCode).toBe(0);
- const codexArgs = () => (Bun.TOML.parse(readFileSync(join(b.home, '.codex', 'config.toml'), 'utf8')) as any).mcp_servers.gbrain.args as string[];
- expect((await setup(b, ['codex', '--stdio-member', 'alice-example'])).exitCode).toBe(0);
- expect(codexArgs().slice(-2)).toEqual(['--stdio-member', 'alice-example']);
- const rerun = await setup(b, ['codex', '--json']);
- expect(rerun.exitCode).toBe(0);
- expect(rerun.doc.serves.stdio).toMatchObject({ member: 'alice-example', action: 'keep' });
- expect(codexArgs().slice(-2)).toEqual(['--stdio-member', 'alice-example']);
- const removed = await setup(b, ['codex', '--no-stdio-member', '--json']);
- expect(removed.exitCode).toBe(0);
- expect(removed.doc.serves.stdio).toMatchObject({ member: null, action: 'remove' });
- expect(codexArgs()).not.toContain('--stdio-member');
- expect(await stdioKey(b)).toBe('');
-
- mkdirSync(join(b.home, '.claude'), { recursive: true });
- writeFileSync(join(b.home, '.claude', 'settings.json'), JSON.stringify({ enabledPlugins: { 'gbrain@gbrain': true } }));
- const plugin = await gbrain(b, ['setup', 'claude-code', '--stdio-member', 'alice-example', '--gbrain-bin', b.bin]);
- expect(plugin.exitCode).toBe(2);
- expect(plugin.stderr).toContain("plugin serves this claude-code gbrain MCP server");
- expect(existsSync(join(b.home, '.claude.json'))).toBe(false);
-
- const serveRefusals: Array<[string[], string, Record<string, string>]> = [
- [['--stdio-member', 'alice-example', '--http'], 'binds a stdio serve only', {}],
- [['--stdio-member', 'Alice Example'], 'needs a member id', {}],
- [['--stdio-member', 'alice-example', '--stdio-member=bob-example'], 'was given 2 times', {}],
- [['--stdio-member', 'alice-example'], 'OpenClaw is installed on this host', { PATH: `${fakeOpenclaw(b)}:${process.env.PATH}` }],
- [['--stdio-member', 'alice-example'], 'Hermes is installed on this host', { HERMES_HOME: b.root }],
- ];
- for (const [args, says, env] of serveRefusals) {
- const r = await gbrain(b, ['serve', ...args], env);
- expect(r.exitCode).not.toBe(0);
- expect(r.stderr).toContain(says);
- }
- }, 360_000);
-
test('--stdio-member is checked against --members when this run labels them, and needs a brain otherwise; the engine no longer matters', () => {
const outside = servesPreflight({ serves: 'several', members: 'alice-example,bob-example', stdioMember: 'carol-example', dryRun: false }, '/nonexistent/gbrain', 'claude-code', false, false);
expect(outside).toMatchObject({ code: 'invalid_params' });
@@ -476,36 +331,6 @@ describe('gbrain setup --serves (spawned, PGLite)', () => {
expect(servesPreflight({ serves: 'several', members: 'alice-example,bob-example', stdioMember: 'alice-example', dryRun: true }, '/nonexistent/gbrain', 'claude-code', false, false)).toMatchObject({ roster: ROSTER, status: null });
});
- test('upgrade paths carry an entry\'s --stdio-member forward and never add one: post-upgrade rewrites, setup re-runs from the receipt, --no-stdio-member removes it', async () => {
- const b = box();
- await brainWithPages(b);
- expect((await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--stdio-member', 'alice-example'])).exitCode).toBe(0);
- const refresh = async () => { const lines: string[] = []; await withEnv({ ...CLEAN, HOME: b.home, GBRAIN_HOME: b.home }, () => refreshHookLaunchers((l) => lines.push(l))); return lines; };
- staleEntry(b);
- expect((await refresh()).join('\n')).toContain('now start gbrain from its own directory');
- expect(entryArgs(b).slice(-2)).toEqual(['--stdio-member', 'alice-example']);
- expect(entry(b).command).not.toBe(b.bin);
- for (const r of setupReceipts(b)) {
- const argv = setupRerunArgv('claude-code', r);
- expect(argv).not.toContain('--stdio-member');
- const rerun = await gbrain(b, [...argv.slice(1), '--json']);
- expect(rerun.exitCode).toBe(0);
- expect(entryArgs(b).slice(-2)).toEqual(['--stdio-member', 'alice-example']);
- }
- expect((await gbrain(b, ['apply-migrations', '--yes', '--no-autopilot-install'])).exitCode).toBe(0);
- expect(entryArgs(b).slice(-2)).toEqual(['--stdio-member', 'alice-example']);
- const removed = await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--no-stdio-member', '--json']);
- expect(removed.exitCode).toBe(0);
- expect(removed.doc.serves.stdio).toMatchObject({ member: null, action: 'remove' });
- expect(removed.doc.serves.stdio.detail).toContain('removed --stdio-member alice-example from this claude-code entry');
- expect(entryArgs(b)).not.toContain('--stdio-member');
- staleEntry(b);
- await refresh();
- expect(entryArgs(b)).not.toContain('--stdio-member');
- expect(entry(b).command).not.toBe(b.bin);
- expect(await stdioKey(b)).toBe('');
- }, 480_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);
@@ -540,45 +365,6 @@ exec '${process.execPath}' --no-env-file '${CLI}' "$@"
expect(existsSync(join(b.home, '.gbrain'))).toBe(false);
}, 120_000);
- test('--serves one on a one-person brain is the default install: the same document, no serves key, the one-person block', async () => {
- const plain = box();
- const explicit = box();
- for (const b of [plain, explicit]) expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
- const a = await setup(plain, ['claude-code', '--json']);
- const c = await setup(explicit, ['claude-code', '--serves', 'one', '--json']);
- expect(a.exitCode).toBe(0);
- expect(c.exitCode).toBe(0);
- expect(a.doc.serves).toBeUndefined();
- expect(normalized(c.doc).serves).toBeUndefined();
- const strip = (doc: any, b: Box) => JSON.parse(JSON.stringify(normalized(doc)).replaceAll(b.root, '<root>'));
- expect(strip(c.doc, explicit)).toEqual(strip(a.doc, plain));
- expect(claudeMd(plain)).toContain(renderBrainFirstBlock('claude-code', { kind: 'mcp', server: 'gbrain', surface: 'verbs' }).split('\n').slice(1).join('\n'));
- }, 240_000);
-
- test('a plain setup on a brain that serves several people refuses and writes nothing; once an owner is named it binds this harness to the owner', async () => {
- const b = box();
- expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
- for (const m of ROSTER) expect((await gbrain(b, ['access', 'member', 'add', m])).exitCode).toBe(0);
- const refused = await setup(b, ['claude-code', '--json']);
- expect(refused.exitCode).not.toBe(0);
- expect(refused.stdout).toContain('setup_serves_several');
- expect(refused.stdout).toContain('2 enabled members (alice-example, bob-example)');
- expect(refused.stdout).toContain('gbrain setup claude-code --serves several --members alice-example,bob-example');
- expect(existsSync(join(b.home, '.claude.json'))).toBe(false);
- expect((await gbrain(b, ['access', 'owner', 'set', 'alice-example'])).exitCode).toBe(0);
- const owner = await setup(b, ['claude-code', '--json']);
- expect(owner.exitCode).not.toBe(0);
- expect(owner.stdout).toContain('setup_serves_several');
- expect(await stdioKey(b)).toBe('');
- expect((await gbrain(b, ['apply-migrations', '--yes', '--no-autopilot-install'])).exitCode).toBe(0);
- expect(await stdioKey(b)).toBe('');
- expect((await gbrain(b, ['config', 'set', 'mcp.stdio_member', 'alice-example'])).exitCode).toBe(0);
- const bound = await setup(b, ['claude-code', '--json']);
- expect(bound.exitCode).toBe(0);
- expect(bound.doc.serves).toMatchObject({ mode: 'one', brain_serves: 'several', stdio: { member: 'alice-example', action: 'keep' } });
- expect(claudeMd(b)).toContain(`- ${SERVES_SEVERAL_LINE}`);
- }, 300_000);
-
test('a repo brain commits the folder rules to .gbrain/access.yml through the commit door, and the bound reads hold', async () => {
const b = box();
const repo = join(b.root, 'repo');
diff --git a/test/setup-serves-stdio-member.test.ts b/test/setup-serves-stdio-member.test.ts
new file mode 100644
index 0000000000..ae25743667
--- /dev/null
+++ b/test/setup-serves-stdio-member.test.ts
@@ -0,0 +1,91 @@
+/**
+ * GST-363: gbrain setup --stdio-member, spawned against a temp HOME / GBRAIN_HOME (PGLite). Split from
+ * test/setup-serves-several.test.ts; the box and readers are in test/helpers/setup-serves-box.ts.
+ *
+ * 1. Protects: --stdio-member refuses an unknown member, a harness other than claude-code and codex, --instructions-only,
+ * --no-stdio-member beside it, and a host with OpenClaw or Hermes, writing nothing; codex keeps an entry member on a
+ * bare re-run and --no-stdio-member removes it; a plugin-served harness and serve on a shared host refuse the flag.
+ * 2. Fails when: a refused run writes an entry or mcp.stdio_member, or a re-run drops or adds --stdio-member.
+ * 3. Existing coverage: test/setup-serves-several.test.ts (labelling), test/setup-serves-upgrade.test.ts (upgrade paths).
+ * 4. Real seams: `bun src/cli.ts setup` and `serve` spawned against a temp HOME / GBRAIN_HOME.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { brainWithPages, box, fakeOpenclaw, gbrain, removeTempDirs, ROSTER, setup, stdioKey } from './helpers/setup-serves-box.ts';
+
+afterAll(removeTempDirs);
+
+describe('gbrain setup --serves (spawned, PGLite)', () => {
+ test('--stdio-member refuses an unknown member, off claude-code and codex, with --instructions-only or --no-stdio-member, and on a host with OpenClaw or Hermes; nothing is written', async () => {
+ const b = box();
+ await brainWithPages(b);
+ for (const m of ROSTER) expect((await gbrain(b, ['access', 'member', 'add', m])).exitCode).toBe(0);
+ expect((await gbrain(b, ['access', 'owner', 'set', 'alice-example'])).exitCode).toBe(0);
+ const workspace = join(b.root, 'oc-workspace');
+ mkdirSync(workspace);
+ expect(existsSync(join(b.root, 'openclaw-state'))).toBe(false);
+ const refusals: Array<[string[], string, Record<string, string>]> = [
+ [['openclaw', '--serves', 'several', '--members', ROSTER.join(','), '--workspace', workspace, '--stdio-member', 'alice-example'], 'claude-code or codex', {}],
+ [['claude-code', '--instructions-only', '--serves', 'several', '--stdio-member', 'alice-example'], 'claude-code or codex', {}],
+ [['claude-code', '--stdio-member', 'alice-example', '--no-stdio-member'], 'not both', {}],
+ [['claude-code', '--stdio-member', 'Alice Example'], 'needs a member id', {}],
+ [['claude-code', '--stdio-member', 'alice-example'], 'OpenClaw is installed on this host', { PATH: `${fakeOpenclaw(b)}:${process.env.PATH}` }],
+ [['codex', '--serves', 'several', '--members', ROSTER.join(','), '--stdio-member', 'alice-example'], 'Hermes is installed on this host', { HERMES_HOME: b.root }],
+ ];
+ for (const [args, says, env] of refusals) {
+ const r = await gbrain(b, ['setup', ...args, '--gbrain-bin', b.bin], env);
+ expect(r.exitCode).toBe(2);
+ expect(r.stderr).toContain(says);
+ if (says.endsWith('on this host')) expect(r.stderr).toContain('gbrain auth create <name> --member <id>');
+ expect(await stdioKey(b)).toBe('');
+ expect(existsSync(join(b.home, '.claude.json'))).toBe(false);
+ }
+ const unknown = await setup(b, ['claude-code', '--stdio-member', 'carol-example', '--json']);
+ expect(unknown.exitCode).not.toBe(0);
+ expect(unknown.stdout).toContain('not an enabled member of this brain');
+ expect(unknown.stdout).toContain('alice-example, bob-example');
+ expect(existsSync(join(b.home, '.claude.json'))).toBe(false);
+ const labelled = await setup(b, ['openclaw', '--serves', 'several', '--members', ROSTER.join(','), '--workspace', workspace]);
+ expect(labelled.stdout + labelled.stderr).not.toContain('reads as alice-example');
+ expect(await stdioKey(b)).toBe('');
+ }, 360_000);
+
+ test('codex keeps an entry member on a bare re-run and --no-stdio-member removes it on a several-person brain; a plugin-served harness and serve on a shared host refuse the flag', async () => {
+ const b = box();
+ await brainWithPages(b);
+ for (const m of ROSTER) expect((await gbrain(b, ['access', 'member', 'add', m])).exitCode).toBe(0);
+ const codexArgs = () => (Bun.TOML.parse(readFileSync(join(b.home, '.codex', 'config.toml'), 'utf8')) as any).mcp_servers.gbrain.args as string[];
+ expect((await setup(b, ['codex', '--stdio-member', 'alice-example'])).exitCode).toBe(0);
+ expect(codexArgs().slice(-2)).toEqual(['--stdio-member', 'alice-example']);
+ const rerun = await setup(b, ['codex', '--json']);
+ expect(rerun.exitCode).toBe(0);
+ expect(rerun.doc.serves.stdio).toMatchObject({ member: 'alice-example', action: 'keep' });
+ expect(codexArgs().slice(-2)).toEqual(['--stdio-member', 'alice-example']);
+ const removed = await setup(b, ['codex', '--no-stdio-member', '--json']);
+ expect(removed.exitCode).toBe(0);
+ expect(removed.doc.serves.stdio).toMatchObject({ member: null, action: 'remove' });
+ expect(codexArgs()).not.toContain('--stdio-member');
+ expect(await stdioKey(b)).toBe('');
+
+ mkdirSync(join(b.home, '.claude'), { recursive: true });
+ writeFileSync(join(b.home, '.claude', 'settings.json'), JSON.stringify({ enabledPlugins: { 'gbrain@gbrain': true } }));
+ const plugin = await gbrain(b, ['setup', 'claude-code', '--stdio-member', 'alice-example', '--gbrain-bin', b.bin]);
+ expect(plugin.exitCode).toBe(2);
+ expect(plugin.stderr).toContain("plugin serves this claude-code gbrain MCP server");
+ expect(existsSync(join(b.home, '.claude.json'))).toBe(false);
+
+ const serveRefusals: Array<[string[], string, Record<string, string>]> = [
+ [['--stdio-member', 'alice-example', '--http'], 'binds a stdio serve only', {}],
+ [['--stdio-member', 'Alice Example'], 'needs a member id', {}],
+ [['--stdio-member', 'alice-example', '--stdio-member=bob-example'], 'was given 2 times', {}],
+ [['--stdio-member', 'alice-example'], 'OpenClaw is installed on this host', { PATH: `${fakeOpenclaw(b)}:${process.env.PATH}` }],
+ [['--stdio-member', 'alice-example'], 'Hermes is installed on this host', { HERMES_HOME: b.root }],
+ ];
+ for (const [args, says, env] of serveRefusals) {
+ const r = await gbrain(b, ['serve', ...args], env);
+ expect(r.exitCode).not.toBe(0);
+ expect(r.stderr).toContain(says);
+ }
+ }, 360_000);
+});
diff --git a/test/setup-serves-upgrade.test.ts b/test/setup-serves-upgrade.test.ts
new file mode 100644
index 0000000000..7867035032
--- /dev/null
+++ b/test/setup-serves-upgrade.test.ts
@@ -0,0 +1,93 @@
+/**
+ * GST-363: gbrain setup on upgrade paths and on a one-person brain, spawned against a temp HOME / GBRAIN_HOME (PGLite).
+ * Split from test/setup-serves-several.test.ts; the box and readers are in test/helpers/setup-serves-box.ts.
+ *
+ * 1. Protects: post-upgrade rewrites, setup re-runs from the receipt and apply-migrations carry an entry's
+ * --stdio-member forward and never add one; --serves one on a one-person brain is the default install; a plain
+ * setup on a brain that serves several people refuses and writes nothing until the stdio server is bound.
+ * 2. Fails when: an upgrade path adds or drops --stdio-member, --serves one changes the default document, or a plain
+ * setup writes an unbound connection on a several brain.
+ * 3. Existing coverage: test/setup-serves-several.test.ts (labelling), test/setup-serves-stdio-member.test.ts.
+ * 4. Real seams: `bun src/cli.ts setup` spawned against a temp HOME / GBRAIN_HOME, refreshHookLaunchers in process.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { setupRerunArgv } from '../src/core/setup/launcher-lanes.ts';
+import { refreshHookLaunchers } from '../src/core/setup/hook-launcher-refresh.ts';
+import { renderBrainFirstBlock, SERVES_SEVERAL_LINE } from '../src/core/setup/brain-first.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { brainWithPages, box, claudeMd, CLEAN, entry, entryArgs, gbrain, normalized, removeTempDirs, ROSTER, setup, setupReceipts, staleEntry, stdioKey, type Box } from './helpers/setup-serves-box.ts';
+
+afterAll(removeTempDirs);
+
+describe('gbrain setup --serves (spawned, PGLite)', () => {
+ test('upgrade paths carry an entry\'s --stdio-member forward and never add one: post-upgrade rewrites, setup re-runs from the receipt, --no-stdio-member removes it', async () => {
+ const b = box();
+ await brainWithPages(b);
+ expect((await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--stdio-member', 'alice-example'])).exitCode).toBe(0);
+ const refresh = async () => { const lines: string[] = []; await withEnv({ ...CLEAN, HOME: b.home, GBRAIN_HOME: b.home }, () => refreshHookLaunchers((l) => lines.push(l))); return lines; };
+ staleEntry(b);
+ expect((await refresh()).join('\n')).toContain('now start gbrain from its own directory');
+ expect(entryArgs(b).slice(-2)).toEqual(['--stdio-member', 'alice-example']);
+ expect(entry(b).command).not.toBe(b.bin);
+ for (const r of setupReceipts(b)) {
+ const argv = setupRerunArgv('claude-code', r);
+ expect(argv).not.toContain('--stdio-member');
+ const rerun = await gbrain(b, [...argv.slice(1), '--json']);
+ expect(rerun.exitCode).toBe(0);
+ expect(entryArgs(b).slice(-2)).toEqual(['--stdio-member', 'alice-example']);
+ }
+ expect((await gbrain(b, ['apply-migrations', '--yes', '--no-autopilot-install'])).exitCode).toBe(0);
+ expect(entryArgs(b).slice(-2)).toEqual(['--stdio-member', 'alice-example']);
+ const removed = await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--no-stdio-member', '--json']);
+ expect(removed.exitCode).toBe(0);
+ expect(removed.doc.serves.stdio).toMatchObject({ member: null, action: 'remove' });
+ expect(removed.doc.serves.stdio.detail).toContain('removed --stdio-member alice-example from this claude-code entry');
+ expect(entryArgs(b)).not.toContain('--stdio-member');
+ staleEntry(b);
+ await refresh();
+ expect(entryArgs(b)).not.toContain('--stdio-member');
+ expect(entry(b).command).not.toBe(b.bin);
+ expect(await stdioKey(b)).toBe('');
+ }, 480_000);
+
+ test('--serves one on a one-person brain is the default install: the same document, no serves key, the one-person block', async () => {
+ const plain = box();
+ const explicit = box();
+ for (const b of [plain, explicit]) expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
+ const a = await setup(plain, ['claude-code', '--json']);
+ const c = await setup(explicit, ['claude-code', '--serves', 'one', '--json']);
+ expect(a.exitCode).toBe(0);
+ expect(c.exitCode).toBe(0);
+ expect(a.doc.serves).toBeUndefined();
+ expect(normalized(c.doc).serves).toBeUndefined();
+ const strip = (doc: any, b: Box) => JSON.parse(JSON.stringify(normalized(doc)).replaceAll(b.root, '<root>'));
+ expect(strip(c.doc, explicit)).toEqual(strip(a.doc, plain));
+ expect(claudeMd(plain)).toContain(renderBrainFirstBlock('claude-code', { kind: 'mcp', server: 'gbrain', surface: 'verbs' }).split('\n').slice(1).join('\n'));
+ }, 240_000);
+
+ test('a plain setup on a brain that serves several people refuses and writes nothing; once an owner is named it binds this harness to the owner', async () => {
+ const b = box();
+ expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
+ for (const m of ROSTER) expect((await gbrain(b, ['access', 'member', 'add', m])).exitCode).toBe(0);
+ const refused = await setup(b, ['claude-code', '--json']);
+ expect(refused.exitCode).not.toBe(0);
+ expect(refused.stdout).toContain('setup_serves_several');
+ expect(refused.stdout).toContain('2 enabled members (alice-example, bob-example)');
+ expect(refused.stdout).toContain('gbrain setup claude-code --serves several --members alice-example,bob-example');
+ expect(existsSync(join(b.home, '.claude.json'))).toBe(false);
+ expect((await gbrain(b, ['access', 'owner', 'set', 'alice-example'])).exitCode).toBe(0);
+ const owner = await setup(b, ['claude-code', '--json']);
+ expect(owner.exitCode).not.toBe(0);
+ expect(owner.stdout).toContain('setup_serves_several');
+ expect(await stdioKey(b)).toBe('');
+ expect((await gbrain(b, ['apply-migrations', '--yes', '--no-autopilot-install'])).exitCode).toBe(0);
+ expect(await stdioKey(b)).toBe('');
+ expect((await gbrain(b, ['config', 'set', 'mcp.stdio_member', 'alice-example'])).exitCode).toBe(0);
+ const bound = await setup(b, ['claude-code', '--json']);
+ expect(bound.exitCode).toBe(0);
+ expect(bound.doc.serves).toMatchObject({ mode: 'one', brain_serves: 'several', stdio: { member: 'alice-example', action: 'keep' } });
+ expect(claudeMd(b)).toContain(`- ${SERVES_SEVERAL_LINE}`);
+ }, 300_000);
+});