Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(access): keep pages a member-bound no-grant credential creates to its member

garrytan9c476239fb41
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8cadb056cf..4dc32c85b9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,18 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**A page written by a member-bound credential with no source grant is now readable only by that member.** A token or OAuth client bound with `gbrain auth rescope --member <id>` and no `--sources` has no write source of its own, so its writes land in `default`, the source every credential without a source grant reads. Its `put_page` (and every page write through the same path) used to create an ordinary page there, which another member and an unbound token read through `get_page`, `search`, `query`, `recall` and `list_pages`; its `remember` facts were already kept on the member's own page. A page such a credential creates is now written with `readable_by: [member:<id>]`, in the database row on a repo-less brain and in the file on a repo brain; rewriting it without `readable_by` keeps the stored readers, and the member widens it by naming readers. An edit to an existing page that names no readers leaves it shared, and `POST /ingest`, which cannot keep a page to a member, refuses such a credential with `permission_denied`. Credentials granted sources (the documented `--sources private-<member>,default` shape) and unbound credentials write exactly as before. Pages written before this release keep whatever readers they have: `gbrain access who-can-read <slug>` shows who reads one.
+
+### Itemized changes
+
+- `src/core/persistence/page-visibility.ts`: `ungrantedMemberWriter` reads, live from the stored principal, whether a remote write's token or OAuth client is bound to an enabled member and holds the no-grant `default` floor (never for a local, unbound, attested or audience write); `ungrantedWriterReaders` gives a page such a writer sends without `readable_by` the stored page's readers, or the writer alone when the write creates the page.
+- `src/core/persistence/page-prepare.ts`: page preparation applies it to the frontmatter before the content hash, the rendered file and the stored row are made (restores and reverts excluded).
+- `src/commands/serve-http-webhooks.ts`: `POST /ingest` refuses a member-bound credential with no source grant before anything is queued.
+- Docs: `docs/guides/multi-source-brains.md`, `docs/tutorials/company-brain.md` (Model C), `docs/mcp/ADMIN.md`.
+- Tests: `test/access-ungranted-member-writes.test.ts` (repo-less PGLite and Postgres, plus a repo brain: another member and an unbound token read nothing of a new page over `get_page`, `search`, `query`, `recall` and `list_pages`; the writer reads, rewrites and widens it; a shared page stays shared; `remember` unchanged; the documented shape unchanged and unstamped; `POST /ingest` refused with nothing queued).
+
## [0.60.620.0] - 2026-11-09
**A diverged managed checkout now publishes its local commits on refresh by default when Git durability is on, after a secret scan of those commits.** Commits a script made with plain `git commit` in a managed checkout used to strand there whenever the remote moved: every `gbrain sources refresh` refused `refresh_diverged` and asked the user, unless `sources.refresh_publish_diverged` was set to `true`. With the setting unset, a worktree whose Git durability is on (`gbrain sources writer git-durability <source> --enable`, or the legacy hook) now publishes them itself: the local commits merged with the upstream in memory, never a rebase or force-push, then the fast-forward. The publish child scans, under its publish lock and for the exact commits it pushes, what they add: commit messages, added lines (including a value a later commit removed) and merge-commit conflict resolutions. A value that looks like a secret, added text too large to scan, or a commit that changes `.gbrain-scan-allow` or a `.gitattributes` refuses the new `publish_secret_found` naming the file, line, rule and commit, never the value, with nothing pushed; commits the scan cannot read in full refuse `publish_scan_unreadable` instead. The rewritten-upstream refusal and the `--expect-remote` bound are unchanged. `false` turns it off; `true` still publishes with durability off.
diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.md
index 4e0a19a4e9..82726016f3 100644
--- a/docs/guides/multi-source-brains.md
+++ b/docs/guides/multi-source-brains.md
@@ -245,6 +245,18 @@ who may read it, before any member's bot connects:
The first id is the token's write source, so a member's saved memories land
in their own private source.
+
+ A credential bound to a member (`--member`) with no `--sources` has no write
+ source of its own and writes to `default`, which every credential without a
+ source grant reads. A page such a credential creates is therefore written
+ with `readable_by: [member:<id>]`, readable only by that member (and the
+ local CLI); rewriting it without `readable_by` keeps those readers, and the
+ member shares it by naming readers (`readable_by: [alice-example,
+ group:team-a]`). An edit to an existing page that names no readers leaves it
+ shared. `POST /ingest` refuses such a credential. Before this release those
+ pages named no readers, so other members and unbound tokens read them:
+ check pages a member wrote with `gbrain access who-can-read <slug>` and add
+ `readable_by` on the brain host to any that should stay private.
- **Let each member read their own private pages (optional).** Remote
reads hide every `visibility: private` page by default, even in a granted
source. To let a member's agent read the private pages in the sources its
diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.md
index 664f96c23f..fb08d91532 100644
--- a/docs/mcp/ADMIN.md
+++ b/docs/mcp/ADMIN.md
@@ -239,6 +239,9 @@ Inside one source, bind each member's credential with `gbrain auth rescope
--token <name> --member <id>` (or `--client`) and put `readable_by` on the pages
only some members may read, or keep a whole folder to them with `gbrain access
rule add --prefix <folder>/ --readers <members> --source <id>`.
+A member-bound credential with no `--sources` writes to `default`, so a page it
+creates names only that member as reader until the member names more
+([details](../tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape)).
One agent serving several people in a shared channel holds `--may-act-for
<members>` instead, and its harness names each request's audience
(`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`); it reads only
diff --git a/docs/tutorials/company-brain.md b/docs/tutorials/company-brain.md
index 749782ca4d..d24fcb310c 100644
--- a/docs/tutorials/company-brain.md
+++ b/docs/tutorials/company-brain.md
@@ -130,6 +130,8 @@ gbrain access check --token alice-laptop # what this credential can rea
gbrain access who-can-read notes/renewal-notes # the members and groups a page admits
```
+A credential bound with `--member` and no `--sources` writes to `default`, a source every credential without a source grant reads, so a page it creates is written with `readable_by: [member:<id>]` and only that member reads it; it keeps those readers when the member rewrites it without the field, and the member shares it by naming readers (`readable_by: [alice-example, group:team-a]`). An edit to an existing page that names no readers leaves it shared, `remember` facts go on the member's own page as before, and `POST /ingest` refuses such a credential. A credential granted sources (`--sources private-alice-example,default`, first id the write source) keeps writing exactly what it sends. Earlier releases wrote these pages with no readers, so other members and unbound tokens read them; run `gbrain access who-can-read <slug>` on pages your members wrote and add `readable_by` on the host where needed.
+
A remote caller whose credential is bound to a listed member (directly or through a group) reads the page on every read path; every other remote caller, including an unbound token, an unbound stdio server, a bot with `--private-pages granted-sources` and an operator escape hatch (`GBRAIN_REMOTE_PRIVATE_PAGES=1`, `search.remote_private_pages=visible`), gets the same `not_found` as for a page that does not exist. `readable_by` only narrows: a `visibility: private` page stays private to a listed member unless the member's credential also has `--private-pages granted-sources`. A malformed `readable_by` reads as nobody. A page derived from a restricted page (an extracted atom, a synthesized concept, a chronicle event) is readable by no remote caller. The local CLI is unchanged; `--as <member>` previews one member's view. Pages that already carried `readable_by` before you upgraded read as nobody until `gbrain repair access` (preview, then `--apply`) derives their readers. This works the same on a repo-less brain: members, groups and bindings live in the database.
**Folder rules: keep a whole folder to some members.** Instead of tagging every page, give a prefix its readers. On a repo-less brain (the default install) the rules live in the database:
diff --git a/src/commands/serve-http-webhooks.ts b/src/commands/serve-http-webhooks.ts
index ac8b47d050..26b3d6e67f 100644
--- a/src/commands/serve-http-webhooks.ts
+++ b/src/commands/serve-http-webhooks.ts
@@ -31,6 +31,8 @@ import { NO_SOURCES } from '../core/source-id.ts';
import { noSourceGrantError } from '../core/ops/context.ts';
import { renderAction } from '../core/agent-output.ts';
import { assertWebhookWriterMayReplace } from '../core/minions/handlers/ingest-capture.ts';
+import { ungrantedMemberWriter } from '../core/persistence/page-visibility.ts';
+import type { WriteAuthority } from '../core/persistence/model.ts';
import { validateSlug } from '../core/utils.ts';
/**
@@ -392,6 +394,17 @@ async function handleIngest(
fix: renderAction(refusal.fix!, { transport: 'http', isCallable: () => false, preapproved: () => false }) });
return;
}
+ // GST-2051: a member-bound credential with no source grant would publish to default, which every no-grant credential
+ // reads; the capture job cannot keep the page to the member, so the route refuses and put_page (which does) stays open.
+ if (authInfo.principal && await ungrantedMemberWriter(engine, { remote: true, principal: authInfo.principal } as WriteAuthority)) {
+ res.status(403).json({
+ error: 'permission_denied',
+ message: 'POST /ingest is unavailable to a credential bound to a member with no source grant: its pages would land in the default source, ' +
+ 'which other members and unbound credentials read. Write through the MCP put_page op, which keeps a new page to its member, ' +
+ 'or ask the brain operator to grant this credential its own write source (gbrain auth rescope --sources <private-source>,default).',
+ });
+ return;
+ }
if (authInfo.allowedOperations != null || authInfo.grantProjectionDegraded) {
res.status(403).json({
error: 'permission_denied',
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 2e82668a4c..c1a117070d 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1489,6 +1489,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.618.0', id: 'refresh_replan_own_commits_8828', text: 'A `gbrain sources refresh` whose checkout HEAD moved while it waited for writes admitted before its fence no longer refuses `refresh_source_changed` when every commit since its start is one of gbrain\'s own (in the commit ledger) and the upstream branch holds them: it takes HEAD as its start and fast-forwards to the upstream. A HEAD move that includes a commit gbrain did not make, or gbrain\'s commits the upstream does not hold yet, still refuses as before.' },
{ since: '0.60.619.0', id: 'managed_commit_push_unpublished_gst1923', text: 'On a managed checkout, `gbrain git commit-push -m <msg> -- <paths>` now reports how many commits the upstream lacks as last fetched (`unpublished` in `--json`, `null` when there is no upstream) and says nothing was pushed, instead of answering `nothing to commit; <remote>/<branch> at -` and logging `[push] ok-already-on-remote` for a commit that already existed. It writes no push-log line on a managed checkout. It still never pushes there; `gbrain git commit-push --push-only --keep-checkout --path <checkout>` publishes.' },
{ since: '0.60.620.0', id: 'refresh_publish_diverged_default_gbra386', text: 'A diverged managed checkout now publishes its local commits on `gbrain sources refresh` by default when the worktree\'s Git durability is on: `sources.refresh_publish_diverged` unset now means on there (it used to mean off), merged with the upstream in memory, never rebased or forced. The refresh publish first scans what the local commits add (messages, added lines, merge resolutions) and refuses the new `publish_secret_found` naming the file, line and rule, never the value, when one looks like a secret; `gbrain git commit-push --push-only --scan-secrets` runs the same gate. Unset with durability not on still refuses, naming `gbrain sources writer git-durability <source> --enable`; `false` turns it off.' },
+ { since: 'TBD', id: 'ungranted_member_writes_gst2051', text: 'A token or OAuth client bound to a member (`gbrain auth rescope --member <id>`) with no `--sources` writes to `default`, which every credential without a source grant reads. A page it creates there is now written with `readable_by: [member:<id>]`, so other members and unbound tokens no longer read it; rewriting it without `readable_by` keeps those readers, naming readers widens it, an edit to an existing page with no readers leaves it shared, and `POST /ingest` refuses such a credential. Credentials granted sources and unbound credentials are unchanged, and pages written before the upgrade keep their readers (`gbrain access who-can-read <slug>`).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index b9b67a1939..b336d416f2 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -37,7 +37,7 @@ import { recordedPathFromFileUri, scannerSlugRootMode, scannerSourcePath } from
import { engineMutationPrecondition, parseMutationPrecondition } from './preconditions.ts';
import { assertPurgeParams } from './purge-params.ts';
import { authorizeWrite, slugDisclosable } from './authority.ts';
-import { remoteReadersChecked } from './page-visibility.ts';
+import { remoteReadersChecked, ungrantedMemberWriter, ungrantedWriterReaders } from './page-visibility.ts';
import { findLiveFileClaimants, type FileClaimant, type FileClaimTarget } from './file-claims.ts';
import { digest, sha256 } from './digest.ts';
import { replaceableFile } from '../facts/file-body-guard.ts';
@@ -976,6 +976,8 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
// #5575: the page's tier, computed once before import so the write gate sees exactly it (ENG-18).
const trust = provenanceWriteTrust(row, typeof content === 'string' && !isFenceEditWrite(row) ? parseMarkdown(content, row.slug, { activePack }).frontmatter : null, snapshot?.page.frontmatter);
const gateTrust = pageGateTrust(row, trust, storedTier);
+ // GST-2051: a member-bound credential with no source grant keeps the pages it creates to itself.
+ const ungrantedWriter = row.operation === 'restore_page' || row.operation === 'revert_version' ? null : await ungrantedMemberWriter(engine, row.authority);
// The apply diet: the publisher's locked read of row.slug is the import base, and one read after the
// last page write serves the read-back check, the seal, the core notice and the receipt (as sync does).
const lean = options.coordinated === true && !targetDeleted && row.operation !== 'restore_page' && !versionTags;
@@ -997,6 +999,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
provenance = putProvenance(row, snapshot, page);
suppliedTrustMarker = page.frontmatter.trust_tier;
stampPageTrustMarker(row, page.frontmatter, trust, storedTier, snapshot?.page.frontmatter);
+ ungrantedWriterReaders(ungrantedWriter, page.frontmatter, snapshot?.page);
if (privateRequest) assertPrivateRequestKept(row, page.frontmatter);
},
prepare: async value => { prepared = value; return value.result; },
diff --git a/src/core/persistence/page-visibility.ts b/src/core/persistence/page-visibility.ts
index 0b7b2c4b67..8ceadd40f0 100644
--- a/src/core/persistence/page-visibility.ts
+++ b/src/core/persistence/page-visibility.ts
@@ -6,6 +6,7 @@ import type { AudiencePrincipal } from '../access/audience.ts';
import { parseStoredActor, storedActorIdentity } from '../access/actor.ts';
import { hasReaders, normalizePrincipal, normalizeReaders, readersAllow, NOBODY } from '../access/principals.ts';
import { catalogueError } from '../error-catalogue.ts';
+import { grantFromClient, grantFromRow, grantFromTokenRow } from '../grants/model.ts';
import type { SqlEngine, WriteAuthority } from './model.ts';
/** Publication uses fresh policy, independent of the read-side telemetry cache (read through the resolver). */
@@ -141,6 +142,37 @@ export async function remoteReadersChecked<T extends { parsedPage: { frontmatter
return prepared;
}
+/**
+ * GST-2051: the member a remote write's credential is bound to, as `member:<id>`, when that credential holds no source
+ * grant (it writes to `default`, a source no operator chose for it and every no-grant credential reads); null for a
+ * local, unbound, attested or audience write, or a credential an operator granted sources. Read live from the stored
+ * principal, so a binding or grant changed after submission takes effect at preparation.
+ */
+export async function ungrantedMemberWriter(engine: SqlEngine, authority: WriteAuthority): Promise<string | null> {
+ const { principal } = authority;
+ if (!authority.remote || authority.actingFor || (principal.kind !== 'legacy_token' && principal.kind !== 'oauth_client')) return null;
+ const member = (await memberIdentityFor(engine, authority)).find(p => p.startsWith('member:'));
+ if (!member) return null;
+ const [row] = principal.kind === 'legacy_token'
+ ? await engine.executeRaw<Record<string, unknown>>('SELECT * FROM access_tokens WHERE id::text = $1 AND revoked_at IS NULL', [principal.id])
+ : await engine.executeRaw<Record<string, unknown>>('SELECT * FROM oauth_clients WHERE client_id = $1 AND deleted_at IS NULL', [principal.id]);
+ if (!row) return null;
+ const grant = principal.kind === 'legacy_token' ? grantFromTokenRow(row) : grantFromClient(grantFromRow(row));
+ return grant.sources.kind === 'default' ? member : null;
+}
+
+/**
+ * GST-2051: the readers a page written by an ungranted member writer (ungrantedMemberWriter) keeps when its content
+ * names none: the stored page's readers when it has them, else the writer alone for a page this write creates. An
+ * existing page with no readers stays as it is. Only ever narrows: a page naming readers is left to the caller.
+ */
+export function ungrantedWriterReaders(writer: string | null, frontmatter: Record<string, unknown>, stored: { frontmatter?: unknown; deleted_at?: unknown } | null | undefined): void {
+ if (!writer || hasReaders(frontmatter)) return;
+ const live = stored && stored.deleted_at == null ? stored : null;
+ if (live && hasReaders(live.frontmatter)) frontmatter.readable_by = (live.frontmatter as Record<string, unknown>).readable_by;
+ else if (!live) frontmatter.readable_by = [writer];
+}
+
/** The one refusal a remote writer gets for a target it may not see; other visibility refusals reuse it verbatim. */
export function pageNotVisibleError() {
return opError('page_not_found', 'Page not found.', 'This page does not exist or is not visible to this connection, so nothing was written. Do not retry this slug as a create; ask the user whether the page exists and who can read it, or write to a different slug.');
diff --git a/test/access-ungranted-member-writes.test.ts b/test/access-ungranted-member-writes.test.ts
new file mode 100644
index 0000000000..d60199b580
--- /dev/null
+++ b/test/access-ungranted-member-writes.test.ts
@@ -0,0 +1,232 @@
+/**
+ * GST-2051 (HARN-64): a credential bound to a member with no source grant writes to the `default` source, which every
+ * no-grant credential reads. Before the fix a page it created there was readable by any other member and by an unbound
+ * token on get_page, search, query, recall and list_pages.
+ * 1. Protects: a page such a credential creates names its member as its only reader (readable_by), so another member
+ * and an unbound token get the canonical page_not_found and no search, query, recall or list_pages hit; the writer
+ * still reads it, rewrites it without readable_by (the stored readers carry), and widens it by naming readers. An
+ * existing shared page it edits stays shared. POST /ingest, which cannot keep a page to its member, refuses it.
+ * The documented shape (--sources private-<member>,default) is unchanged: its pages carry no stamped readers and
+ * stay out of other members' and unbound reads through the source grant.
+ * 2. Fails when: a member-bound no-grant put_page lands without readers, or the documented shape is stamped or leaks.
+ * 3. Existing coverage (access-writes, member-read-access) uses granted credentials only.
+ * 4. Real seams: tokens minted by the token service and bound with SQL, verified by the serve --http verifier,
+ * dispatched through MCP dispatch; the durable write path of a repo-less brain (no git checkout).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import express from 'express';
+import type { Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { mountWebhooks } from '../src/commands/serve-http-webhooks.ts';
+import type { ServeHttpContext } from '../src/commands/serve-http.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.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 { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const PRIVATE_SRC = 'private-alice-example';
+const SHARED_PAGE = 'notes/team-shared';
+const marker = (tag: string) => 'ungranted' + tag + randomUUID().slice(0, 8);
+const note = (title: string, body: string, readers = '') =>
+ ['---', 'type: note', 'title: ' + title, ...(readers ? ['readable_by: ' + readers] : []), '---', '# ' + title, '', body].join('\n');
+
+for (const kind of testBackends()) {
+ describe('writes from a member-bound credential with no source grant (' + kind + ', repo-less)', () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ const tokens: Record<string, string> = {};
+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+
+ async function call(who: string, op: string, params: Record<string, unknown>) {
+ const auth = await provider().verifyAccessToken(tokens[who]) as unknown as AuthInfo;
+ const out = await dispatchToolCall(engine, op, { ...params }, { remote: true, transport: 'http', auth, sourceId: auth.sourceId ?? 'default', takesHoldersAllowList: ['world'] });
+ const text = out.content.map(c => c.text).join('\n');
+ let json: Record<string, unknown> = {};
+ try { json = JSON.parse(text); } catch { /* prose */ }
+ return { isError: out.isError === true, text, json };
+ }
+ async function revision(slug: string): Promise<string> {
+ const out = await dispatchToolCall(engine, 'get_page', { slug, include_content: true }, { remote: false, sourceId: 'default' });
+ return (JSON.parse(out.content.map(c => c.text).join('\n')) as { revision: string }).revision;
+ }
+ async function stored(slug: string, source = 'default') {
+ const [row] = await engine.executeRaw<{ frontmatter: Record<string, unknown>; page_readers: string[] | null; body: string }>(
+ 'SELECT frontmatter, page_readers, compiled_truth AS body FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [source, slug]);
+ return row;
+ }
+ /** What each read op shows `who` of a page whose body carries `canary`: true where the canary leaks. */
+ async function reads(who: string, slug: string, canary: string, source?: string) {
+ const scoped = source ? { source_id: source } : {};
+ const seen: Record<string, boolean> = {};
+ for (const [op, params] of [['get_page', { slug, ...scoped }], ['search', { query: canary }], ['query', { query: 'note ' + canary }],
+ ['recall', { query: canary }], ['list_pages', {}]] as const) {
+ const out = await call(who, op, params as Record<string, unknown>);
+ seen[op] = op === 'list_pages' ? out.text.includes(slug) : out.text.includes(canary + '.');
+ }
+ return seen;
+ }
+ const none = { get_page: false, search: false, query: false, recall: false, list_pages: false };
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }
+ __resetPrivateVisibilityCacheForTests();
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [PRIVATE_SRC]);
+ await importFromContent(engine, SHARED_PAGE, note('Team shared', 'Shared agenda.'), { sourceId: 'default', noEmbed: true });
+ for (const id of ['alice-example', 'bob-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);
+ for (const [name, member, sourceGrant] of [['alice', 'alice-example', undefined], ['bob', 'bob-example', undefined], ['public', null, undefined],
+ ['alice-documented', 'alice-example', [PRIVATE_SRC, 'default']]] as const) {
+ const minted = await mintLegacyToken(engine, { name, scopes: ['read', 'write'], takesHolders: ['world'], ...(sourceGrant ? { sourceGrant: [...sourceGrant] } : {}) });
+ tokens[name] = minted.token;
+ if (member) await engine.executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id = $1::uuid', [minted.id, member]);
+ }
+ }, 240_000);
+ afterAll(async () => { await close?.(); }, 60_000);
+
+ test('a page it creates in default names only its member: another member and an unbound token read nothing of it', async () => {
+ const canary = marker('new');
+ const slug = 'notes/alice-dock-' + canary;
+ const put = await call('alice', 'put_page', { slug, content: note('Alice dock', 'Alice dock code ' + canary + '.'), request_id: randomUUID() });
+ expect({ isError: put.isError, source: put.json.source_id ?? put.json.source }).toEqual({ isError: false, source: 'default' });
+ expect(await stored(slug)).toMatchObject({ frontmatter: { readable_by: ['member:alice-example'] }, page_readers: ['member:alice-example'] });
+ expect(await reads('bob', slug, canary)).toEqual(none);
+ expect(await reads('public', slug, canary)).toEqual(none);
+ expect((await call('bob', 'get_page', { slug })).json.code).toBe('page_not_found');
+ expect((await reads('alice', slug, canary)).get_page).toBe(true);
+ }, 240_000);
+
+ test('the writer rewrites its page without readable_by and the readers carry; naming readers widens it', async () => {
+ const canary = marker('carry');
+ const slug = 'notes/alice-carry-' + canary;
+ expect((await call('alice', 'put_page', { slug, content: note('Alice carry', 'First ' + canary + '.') })).isError).toBe(false);
+ const rewrite = await call('alice', 'put_page', { slug, content: note('Alice carry', 'Second ' + canary + '.'), expected_revision: await revision(slug) });
+ expect({ isError: rewrite.isError, code: rewrite.json.code }).toEqual({ isError: false, code: undefined });
+ expect(await stored(slug)).toMatchObject({ body: expect.stringContaining('Second'), page_readers: ['member:alice-example'] });
+ expect(await reads('bob', slug, canary)).toEqual(none);
+ const widen = await call('alice', 'put_page', { slug, content: note('Alice carry', 'Third ' + canary + '.', '[alice-example, bob-example]'), expected_revision: await revision(slug) });
+ expect(widen.isError).toBe(false);
+ expect((await reads('bob', slug, canary)).get_page).toBe(true);
+ expect((await reads('public', slug, canary)).get_page).toBe(false);
+ }, 240_000);
+
+ test('an existing shared page it edits stays shared', async () => {
+ const canary = marker('shared');
+ const out = await call('alice', 'put_page', { slug: SHARED_PAGE, content: note('Team shared', 'Shared agenda ' + canary + '.'), expected_revision: await revision(SHARED_PAGE) });
+ expect(out.isError).toBe(false);
+ expect((await stored(SHARED_PAGE)).page_readers).toBeNull();
+ expect((await reads('bob', SHARED_PAGE, canary)).get_page).toBe(true);
+ }, 240_000);
+
+ test('a remember fact stays on the member page, as before', async () => {
+ const canary = marker('fact');
+ const out = await call('alice', 'remember', { fact: 'Alice escalation code ' + canary + '.', entity: 'alice-example', provenance: 'test', request_id: randomUUID() });
+ expect(out.isError).toBe(false);
+ for (const who of ['bob', 'public']) expect((await call(who, 'recall', { query: canary })).text).not.toContain(canary + '.');
+ }, 240_000);
+
+ test('the documented shape (--sources private-<member>,default) is unchanged: no stamped readers, nothing leaks', async () => {
+ const canary = marker('doc');
+ const slug = 'notes/alice-doc-' + canary;
+ const put = await call('alice-documented', 'put_page', { slug, content: note('Alice doc', 'Alice doc code ' + canary + '.') });
+ expect(put.isError).toBe(false);
+ expect(await stored(slug, PRIVATE_SRC)).toMatchObject({ page_readers: null });
+ expect((await stored(slug, PRIVATE_SRC)).frontmatter.readable_by).toBeUndefined();
+ expect(await reads('bob', slug, canary, PRIVATE_SRC)).toEqual(none);
+ expect(await reads('public', slug, canary, PRIVATE_SRC)).toEqual(none);
+ expect((await reads('alice-documented', slug, canary, PRIVATE_SRC)).get_page).toBe(true);
+ }, 240_000);
+
+ test('POST /ingest refuses it and queues nothing; a granted member credential still reaches the route', async () => {
+ const app = express();
+ const pass: express.RequestHandler = (_req, _res, next) => next();
+ mountWebhooks(app, { engine, resourceVerifier: provider(), resourceMetadataUrl: 'http://127.0.0.1/.well-known/oauth-protected-resource',
+ ingestRateLimiter: pass, githubWebhookLimiter: pass, broadcastEvent: () => {} } as unknown as ServeHttpContext);
+ const server = await new Promise<Server>(resolve => { const s = app.listen(0, '127.0.0.1', () => resolve(s)); });
+ try {
+ const base = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
+ const ingest = (who: string, body: string) => fetch(base + '/ingest', { method: 'POST', body,
+ headers: { authorization: 'Bearer ' + tokens[who], 'content-type': 'text/markdown' } });
+ const [before] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM minion_jobs WHERE name = 'ingest_capture'");
+ const refused = await ingest('alice', note('Alice ingest', 'Ingest ' + marker('ingest') + '.'));
+ expect(refused.status).toBe(403);
+ expect(await refused.json()).toMatchObject({ error: 'permission_denied', message: expect.stringContaining('no source grant') });
+ const [after] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM minion_jobs WHERE name = 'ingest_capture'");
+ expect(after.n).toBe(before.n);
+ const granted = await ingest('alice-documented', note('Alice doc ingest', 'Ingest ' + marker('ingestdoc') + '.'));
+ expect(granted.status).toBe(202);
+ } finally {
+ await new Promise<void>(resolve => server.close(() => resolve()));
+ }
+ }, 240_000);
+ });
+}
+
+for (const kind of testBackends()) {
+ describe('writes from a member-bound credential with no source grant (' + kind + ', repo brain)', () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-gst2051-' + kind + '-'));
+ const root = join(home, 'default-repo');
+ const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+ const tokens: Record<string, string> = {};
+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+
+ async function call(who: string, op: string, params: Record<string, unknown>) {
+ const auth = await provider().verifyAccessToken(tokens[who]) as unknown as AuthInfo;
+ const out = await withEnv(env, () => dispatchToolCall(engine, op, { ...params }, { remote: true, transport: 'http', auth, sourceId: auth.sourceId ?? 'default', takesHoldersAllowList: ['world'] }));
+ return { isError: out.isError === true, text: out.content.map(c => c.text).join('\n') };
+ }
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }
+ __resetPrivateVisibilityCacheForTests();
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ git('init', '-q');
+ writeFileSync(join(root, 'notes', 'team-shared.md'), note('Team shared', 'Shared agenda.'));
+ git('add', '-A'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'synthetic content');
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('UPDATE sources SET local_path=$1 WHERE id=$2', [root, 'default']);
+ await withEnv(env, () => claimWorktree(engine, 'default', root));
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ expect((await withEnv(env, () => performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true }))).status).toBe('first_sync');
+ for (const id of ['alice-example', 'bob-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);
+ for (const [name, member] of [['alice', 'alice-example'], ['bob', 'bob-example']] as const) {
+ const minted = await mintLegacyToken(engine, { name, scopes: ['read', 'write'], takesHolders: ['world'] });
+ tokens[name] = minted.token;
+ await engine.executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id = $1::uuid', [minted.id, member]);
+ }
+ }, 240_000);
+ afterAll(async () => { await disposePersistenceConsumer(engine); await close?.(); rmSync(home, { recursive: true, force: true }); }, 60_000);
+
+ test('the git file carries the readers, so a sync of the checkout keeps the page to its member', async () => {
+ const canary = marker('repo');
+ const slug = 'notes/alice-repo-' + canary;
+ const put = await call('alice', 'put_page', { slug, content: note('Alice repo', 'Alice repo code ' + canary + '.'), request_id: randomUUID() });
+ expect(put.isError).toBe(false);
+ const file = readFileSync(join(root, slug + '.md'), 'utf8');
+ expect(file).toContain(canary);
+ expect(file).toMatch(/readable_by:\s*\n\s*- member:alice-example/);
+ expect((await call('bob', 'get_page', { slug })).text).not.toContain(canary + '.');
+ expect((await call('alice', 'get_page', { slug })).text).toContain(canary + '.');
+ }, 240_000);
+ });
+}