Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Make the grace boundary strict and mark unbound fixtures that pin pre-refusal reads

garrytane44efed6cb1a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ca838e8e26..617684e24a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,7 +27,7 @@ identifiers and attribution are available in the pre-removal Git revision
### Itemized changes
- `src/core/access/requester-scope.ts` (new): the gate, run in `dispatchToolCall` after access resolves and in every agent job tool call. Every read op and every read-scope op (`think` included) is gated unless it reads no page: `whoami`, `get_brain_identity`, `get_status_snapshot`, `search_modes`, `get_health`, the caller's own `join_brain` / `leave_brain` / `sync_brain_skills` / `request_tools`, and a non-admin credential's own `get_job` / `wait_job`. When the serves policy cannot be read it is read once more, and a second failure refuses retryably (`requester_scope_unknown`) rather than reading as one person; a bound credential is never refused that way. A connection whose reads are refused gets no `_meta.brain_hot_memory` on the calls the gate lets through (the exempt ops above and writes), so it cannot read recent facts through `whoami`.
-- `access.serves` is read without regard to case or surrounding spaces (`One` pins one person). `access.serves_since` is set once and never cleared, so a brain that served several people once and does again later gets no new grace.
+- `access.serves` is read without regard to case or surrounding spaces (`One` pins one person). `access.serves_since` is set once and never cleared, so a brain that served several people once and does again later gets no new grace. A connection counts as existing before that date only when it was created in an earlier second, so one created in the same second is refused like a later one.
- Migration v308 (number assigned at the merge slot): `reads_unscoped` on `access_tokens` and `oauth_clients`, and a trigger that keeps config `access.serves_derived` and sets `access.serves_since` once, the first time the brain serves several people, so a request reads both from its config snapshot. Disabling and re-enabling a member does not restart the grace. Nothing else is rewritten.
- `gbrain auth create`, `gbrain auth register-client` and the admin dashboard's key mint refuse an unbound credential on such a brain (`credential_scope_required`). `gbrain auth rescope ... --reads-unscoped --yes` (`none` removes it) is the explicit opt-out, written to the `access-reads-unscoped` audit file; `gbrain access check` reports it.
- The fix every refusal, notice, `whoami` note and `gbrain access owner` hint gives for stdio is the per-harness binding, `gbrain setup claude-code|codex --stdio-member <id>`, on PGLite and Postgres alike, or a per-person key over `gbrain serve --http` for a harness several people talk to. Nothing suggests `config set mcp.stdio_member`, and no upgrade, doctor or setup path writes it.
diff --git a/src/core/access/requester-scope.ts b/src/core/access/requester-scope.ts
index 7eeeaa1b59..b1e72c219f 100644
--- a/src/core/access/requester-scope.ts
+++ b/src/core/access/requester-scope.ts
@@ -120,7 +120,7 @@ export function requesterScopeGate(op: Pick<Operation, 'name' | 'mutating'> | un
return { state: 'not_enforced', connection: c.handle, refuses_at: null, fix: fixFor(c, transport),
message: `This brain serves several people (${why(serves)}) and ${c.handle} is bound to nobody, so it reads every page no rule restricts for whoever is asking. ${alternatives(c)}` };
}
- const old = since !== null && (created === null || created <= since);
+ const old = since !== null && (created === null || created < since);
if (old && refusesAt !== null && now < refusesAt) {
const date = new Date(refusesAt * 1000).toISOString();
return { state: 'grace', connection: c.handle, refuses_at: date, fix: fixFor(c, transport),
@@ -265,7 +265,7 @@ export async function unscopedConnections(engine: Pick<BrainEngine, 'executeRaw'
const now = Math.floor(nowMs / 1000);
const entry = (c: Connection, row: { created: unknown; reads_unscoped: unknown }): UnscopedConnection => {
const { readsUnscoped, createdAt } = credentialScopeFields(row.reads_unscoped, row.created);
- const old = serves.since !== null && (createdAt === null || createdAt <= serves.since);
+ const old = serves.since !== null && (createdAt === null || createdAt < serves.since);
const state = readsUnscoped ? 'reads_unscoped' : !serves.enforce ? 'not_enforced' : old && refusesAt !== null && now < refusesAt ? 'grace' : 'refused';
return { connection: c.handle, state, refuses_at: state === 'grace' ? new Date(refusesAt! * 1000).toISOString() : null, argv: c.argv };
};
diff --git a/src/core/access/serves.ts b/src/core/access/serves.ts
index a8d326155c..14f893308a 100644
--- a/src/core/access/serves.ts
+++ b/src/core/access/serves.ts
@@ -28,7 +28,7 @@ export interface ServesView {
export async function brainServes(engine: Pick<BrainEngine, 'getConfig' | 'executeRaw'>): Promise<ServesView> {
const members = (await engine.executeRaw<{ id: string }>(
'SELECT id FROM access_members WHERE disabled_at IS NULL AND tombstoned_at IS NULL ORDER BY id')).map(r => r.id);
- const [explicit, derived, since] = await Promise.all([SERVES_KEY, SERVES_DERIVED_KEY, SERVES_SINCE_KEY].map(k => engine.getConfig(k)));
+ const [explicit, derived, since] = await Promise.all([engine.getConfig(SERVES_KEY), engine.getConfig(SERVES_DERIVED_KEY), engine.getConfig(SERVES_SINCE_KEY)]);
const policy = servesPolicyFrom({ [SERVES_KEY]: explicit ?? undefined, [SERVES_DERIVED_KEY]: derived ?? undefined });
return { serves: policy.several ? 'several' : 'one', from: policy.from, enabled_members: members, since: since?.trim() || null };
}
diff --git a/test/access-hidden-page-writes.test.ts b/test/access-hidden-page-writes.test.ts
index 8a3dbbfa2a..636b3dc11e 100644
--- a/test/access-hidden-page-writes.test.ts
+++ b/test/access-hidden-page-writes.test.ts
@@ -29,6 +29,7 @@ import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../
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 { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
import { getBrainHotMemoryMeta, __resetHotMemoryCacheForTests } from '../src/core/facts/meta-hook.ts';
import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
@@ -119,6 +120,7 @@ for (const kind of testBackends()) {
const minted = await mintLegacyToken(engine, { name, scopes: [...scopes], takesHolders: ['world'], sourceGrant: [SRC] });
tokens[name] = minted.token;
if (member) await engine.executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id = $1::uuid', [minted.id, member]);
+ else await readsUnscopedOnPurpose(engine, minted.id);
}
}, 240_000);
afterAll(async () => { __setEmbedTransportForTests(null); resetGateway(); await close?.(); }, 60_000);
diff --git a/test/e2e/serve-http-ingest-webhook.test.ts b/test/e2e/serve-http-ingest-webhook.test.ts
index 2a3915fabc..730a5b6223 100644
--- a/test/e2e/serve-http-ingest-webhook.test.ts
+++ b/test/e2e/serve-http-ingest-webhook.test.ts
@@ -64,7 +64,7 @@ describeE2E('serve-http POST /ingest webhook (v0.38)', () => {
function registerClientForRescope(name: string, sourceId?: string): { clientId: string; clientSecret: string } {
const sourceArg = sourceId ? ` --source "${sourceId}"` : '';
const regOutput = execSync(
- `bun run src/cli.ts auth register-client "${name}" --grant-types client_credentials --scopes "read write"${sourceArg}`,
+ `bun run src/cli.ts auth register-client "${name}" --grant-types client_credentials --scopes "read write" --reads-unscoped --yes${sourceArg}`,
{ cwd: process.cwd(), encoding: 'utf8', env: { ...process.env } },
);
const idMatch = regOutput.match(/Client ID:\s+(gbrain_cl_\S+)/);
diff --git a/test/e2e/serve-http-member-sweep.test.ts b/test/e2e/serve-http-member-sweep.test.ts
index 08302705b2..4367df1434 100644
--- a/test/e2e/serve-http-member-sweep.test.ts
+++ b/test/e2e/serve-http-member-sweep.test.ts
@@ -55,8 +55,8 @@ for (const [index, backend] of backends.entries()) {
for (const id of ['alice-example', 'bob-example']) cli('access', 'member', 'add', id);
bearer.alice = token(cli('auth', 'create', 'c2-alice-key', '--member', 'alice-example', '--scopes', 'read,write'));
bearer.bob = token(cli('auth', 'create', 'c2-bob-key', '--member', 'bob-example', '--scopes', 'read,write'));
- bearer.plain = token(cli('auth', 'create', 'c2-plain-key', '--scopes', 'read,write'));
- const registered = cli('auth', 'register-client', 'c2-qm', '--grant-types', 'client_credentials', '--scopes', 'read write');
+ bearer.plain = token(cli('auth', 'create', 'c2-plain-key', '--scopes', 'read,write', '--reads-unscoped', '--yes'));
+ const registered = cli('auth', 'register-client', 'c2-qm', '--grant-types', 'client_credentials', '--scopes', 'read write', '--reads-unscoped', '--yes');
const clientId = registered.match(/Client ID:\s+(\S+)/)![1]!;
const clientSecret = registered.match(/Client Secret:\s+(\S+)/)![1]!;
expect(cli('auth', 'rescope', '--client', clientId, '--attest-actor', 'qm', '--attest-ops', ATTESTABLE.map(op => op.name).join(','))).toContain('attests actor: qm');
diff --git a/test/fact-reads-page-access.test.ts b/test/fact-reads-page-access.test.ts
index a5696dd839..11942d2780 100644
--- a/test/fact-reads-page-access.test.ts
+++ b/test/fact-reads-page-access.test.ts
@@ -24,6 +24,7 @@ import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../
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 { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';
import { parseRescopeTokenArgs, rescopeLegacyToken } from '../src/core/grants/legacy-token.ts';
import { noGrantFederatedScope } from '../src/core/source-resolver.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
@@ -80,6 +81,7 @@ function callers(engine: () => BrainEngine, source: string) {
const minted = await mintLegacyToken(engine(), { name, scopes: ['read'], takesHolders: ['world'], sourceGrant: [source] });
tokens[name] = minted.token;
if (member) await engine().executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id = $1::uuid', [minted.id, member]);
+ else await readsUnscopedOnPurpose(engine(), minted.id);
},
};
}
diff --git a/test/harness-verify-member-credential.test.ts b/test/harness-verify-member-credential.test.ts
index 3cbb8e3ad1..331c245fc3 100644
--- a/test/harness-verify-member-credential.test.ts
+++ b/test/harness-verify-member-credential.test.ts
@@ -14,6 +14,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.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 { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
import { setOwner } from '../src/core/access/owner.ts';
@@ -64,6 +65,7 @@ for (const kind of testBackends()) {
const minted = await mintLegacyToken(engine, { name, scopes: ['read', 'write'], takesHolders: ['world'] });
tokens[name] = minted.token;
if (member) await engine.executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id = $1::uuid', [minted.id, member]);
+ else await readsUnscopedOnPurpose(engine, minted.id);
}
}, 240_000);
afterAll(async () => { await close?.(); }, 60_000);
diff --git a/test/lower-tier-label-hold.test.ts b/test/lower-tier-label-hold.test.ts
index 547e6aeda4..73157b063c 100644
--- a/test/lower-tier-label-hold.test.ts
+++ b/test/lower-tier-label-hold.test.ts
@@ -35,6 +35,7 @@ import { setOwner } from '../src/core/access/owner.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 { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';
import { noGrantFederatedScope } from '../src/core/source-resolver.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
@@ -99,6 +100,7 @@ async function remoteReaders(engine: BrainEngine, sourceId: string) {
const minted = await mintLegacyToken(engine, { name: 'reader-' + who, scopes: ['read'], takesHolders: ['world'], sourceGrant: [sourceId] });
tokens[who] = minted.token;
if (member) await bindCredential(engine, { kind: 'token', id: minted.id }, { member });
+ else await readsUnscopedOnPurpose(engine, minted.id);
}
const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
return async (who: Reader, slug: string, canary: string): Promise<boolean> => {
diff --git a/test/owner-label-guard.test.ts b/test/owner-label-guard.test.ts
index 254df77c85..5eac6b63d1 100644
--- a/test/owner-label-guard.test.ts
+++ b/test/owner-label-guard.test.ts
@@ -30,6 +30,7 @@ import { setOwner, setOwnerReadsRestricted } from '../src/core/access/owner.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 { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';
import { noGrantFederatedScope } from '../src/core/source-resolver.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
@@ -80,6 +81,7 @@ async function remoteReaders(engine: BrainEngine, sourceId: string) {
const minted = await mintLegacyToken(engine, { name: 'reader-' + who, scopes: ['read'], takesHolders: ['world'], sourceGrant: [sourceId] });
tokens[who] = minted.token;
if (member) await bindCredential(engine, { kind: 'token', id: minted.id }, { member });
+ else await readsUnscopedOnPurpose(engine, minted.id);
}
const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
return async (who: Reader, slug: string, canary: string): Promise<boolean> => {
diff --git a/test/owner-reads-restricted.test.ts b/test/owner-reads-restricted.test.ts
index 1b916fe60d..a795570d3f 100644
--- a/test/owner-reads-restricted.test.ts
+++ b/test/owner-reads-restricted.test.ts
@@ -334,6 +334,7 @@ for (const kind of testBackends()) {
const minted = await mintLegacyToken(engine, { name, scopes: ['read'], takesHolders: ['world'], sourceGrant: [MSRC] });
tokens[name] = minted.token;
if (member) await bindCredential(engine, { kind: 'token', id: minted.id }, { member });
+ else await readsUnscopedOnPurpose(engine, minted.id);
}
await setOwner(engine, OWNER);
}, 300_000);
diff --git a/test/qm-personal-sources.test.ts b/test/qm-personal-sources.test.ts
index e3ee302988..4e8e166d94 100644
--- a/test/qm-personal-sources.test.ts
+++ b/test/qm-personal-sources.test.ts
@@ -117,7 +117,7 @@ for (const kind of testBackends()) {
const register = async (name: string, grant: string[], read?: 'person' | 'scope') => {
const c = await provider().registerClientManual('personal-' + name + '-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], grant[0]!);
await provider().rescopeClient(c.clientId, { federatedRead: grant });
- await bindCredential(engine, { kind: 'client', id: c.clientId }, { attestActor: 'qm', attestOps: OPS, ...(read ? { attestRead: read } : {}) });
+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { attestActor: 'qm', attestOps: OPS, ...(read ? { attestRead: read } : {}), readsUnscoped: true });
clients[name] = (await provider().exchangeClientCredentials(c.clientId, c.clientSecret ?? '')).access_token;
};
await register('narrow', [SRC]);
diff --git a/test/qm-scope-read.test.ts b/test/qm-scope-read.test.ts
index e654813e9b..9f1303bb0c 100644
--- a/test/qm-scope-read.test.ts
+++ b/test/qm-scope-read.test.ts
@@ -131,7 +131,7 @@ for (const kind of testBackends()) {
const register = async (name: string, read?: 'person' | 'scope') => {
const c = await provider().registerClientManual('scope-' + name + '-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], SRC);
await provider().rescopeClient(c.clientId, { federatedRead: [SRC, ROOM] });
- await bindCredential(engine, { kind: 'client', id: c.clientId }, { attestActor: 'qm', attestOps: SCOPE_OPS, ...(read ? { attestRead: read } : {}) });
+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { attestActor: 'qm', attestOps: SCOPE_OPS, ...(read ? { attestRead: read } : {}), readsUnscoped: true });
clients[name] = { id: c.clientId, secret: c.clientSecret ?? '', token: (await provider().exchangeClientCredentials(c.clientId, c.clientSecret ?? '')).access_token };
};
await register('unset');
diff --git a/test/remember-share-gst2243.test.ts b/test/remember-share-gst2243.test.ts
index 2ea632f9b5..ead421d470 100644
--- a/test/remember-share-gst2243.test.ts
+++ b/test/remember-share-gst2243.test.ts
@@ -91,12 +91,13 @@ for (const kind of testBackends()) {
return { id: c.clientId, secret: c.clientSecret ?? '' };
};
const qm = await register('qm');
- await bindCredential(engine, { kind: 'client', id: qm.id }, { attestActor: 'qm', attestOps: ATTEST_OPS });
+ await bindCredential(engine, { kind: 'client', id: qm.id }, { attestActor: 'qm', attestOps: ATTEST_OPS, readsUnscoped: true });
const alice = await register('alice');
await bindCredential(engine, { kind: 'client', id: alice.id }, { member: 'alice-example' });
const bob = await register('bob');
await bindCredential(engine, { kind: 'client', id: bob.id }, { member: 'bob-example' });
const plain = await register('plain');
+ await bindCredential(engine, { kind: 'client', id: plain.id }, { readsUnscoped: true });
for (const [name, c] of [['qm', qm], ['alice', alice], ['bob', bob], ['plain', plain]] as const) tokens[name] = (await provider().exchangeClientCredentials(c.id, c.secret)).access_token;
await linkMember(engine, 'alice-example', 'qm', ALICE_ID);
await linkMember(engine, 'bob-example', 'qm', BOB_ID);
diff --git a/test/requester-scope.test.ts b/test/requester-scope.test.ts
index d1ea5b61c6..8526ba7ec4 100644
--- a/test/requester-scope.test.ts
+++ b/test/requester-scope.test.ts
@@ -286,6 +286,8 @@ for (const kind of testBackends()) {
await setSince(1);
await mint('fresh-unbound');
refused(await search('fresh-unbound'), 'created_after');
+ await engine.executeRaw('UPDATE access_tokens SET created_at = $2::timestamptz WHERE id::text = $1', [keys['fresh-unbound']!.id, await engine.getConfig('access.serves_since')]);
+ refused(await search('fresh-unbound'), 'created_after');
const who = await http('fresh-unbound', 'whoami', {});
expect(who.isError).toBe(false);
expect(who.json.access.requester_scope).toEqual({ state: 'refused', reason: 'created_after', argv: ['gbrain', 'auth', 'rescope', '--token', 'fresh-unbound', '--member', '<MEMBER>'] });
diff --git a/test/trust-guarded-supersession.test.ts b/test/trust-guarded-supersession.test.ts
index 39933997cf..bb209c3636 100644
--- a/test/trust-guarded-supersession.test.ts
+++ b/test/trust-guarded-supersession.test.ts
@@ -19,6 +19,7 @@ import type { BrainEngine } from '../src/core/engine.ts';
import type { OperationContext } from '../src/core/ops/contract.ts';
import { operationsByName } from '../src/core/operations.ts';
import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';
import { registerLocalWriter, readLocalWriter } from '../src/core/persistence/identity.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import type { Principal } from '../src/core/persistence/model.ts';
@@ -66,6 +67,7 @@ async function brain(engine: BrainEngine): Promise<Brain> {
await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
await registerLocalWriter(engine, 'cli');
const minted = await mintLegacyToken(engine, { name: `token-${sourceId}`, scopes: ['read', 'write'], sourceGrant: [sourceId], takesHolders: ['world'] });
+ await readsUnscopedOnPurpose(engine, minted.id);
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
const base = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId, dryRun: false, logger: quiet };
await readLocalWriter(engine, 'cli');