Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: pre-landing review fixes (Git placement judges privacy alone; stdio writers resolve their bound member, closes #8396)

garrytanb8a1f679cdeb
diff --git a/src/core/access/caller.ts b/src/core/access/caller.ts
index de41afc305..69296025c0 100644
--- a/src/core/access/caller.ts
+++ b/src/core/access/caller.ts
@@ -42,13 +42,15 @@ async function liveIdentity(engine: Pick<BrainEngine, 'executeRaw'>, memberSql:
}
/**
- * The member identity bound to `auth`: the verifier's join when present, else a lookup from its principal; empty
- * when unbound, unknown or unreadable. A write's publication passes only its stored principal, so a member disabled
- * or a binding removed after submission takes effect.
+ * The member identity bound to `auth`: the verifier's join when present, else a lookup from its principal (a local
+ * stdio principal reads config mcp.stdio_member, as stdio reads do); empty when unbound, unknown or unreadable. A
+ * write's publication passes only its stored principal, so a member disabled or a binding removed after submission
+ * takes effect.
*/
export async function memberIdentityFor(engine: Pick<BrainEngine, 'executeRaw'>, auth: Pick<AuthInfo, 'member'> & { principal?: { kind: string; id: string } } | undefined): Promise<string[]> {
if (auth?.member !== undefined) return auth.member ? identityFor(auth.member.id, auth.member.groups) : [];
const principal = auth?.principal;
+ if (principal?.kind === 'local_stdio') return liveIdentity(engine, 'SELECT btrim(value) FROM config WHERE key = $1', STDIO_MEMBER_KEY);
if (!principal || (principal.kind !== 'legacy_token' && principal.kind !== 'oauth_client')) return [];
return liveIdentity(engine, principal.kind === 'legacy_token'
? 'SELECT member_id FROM access_tokens WHERE id::text = $1 AND revoked_at IS NULL'
diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.ts
index d38dbdfb02..7fb5c7075f 100644
--- a/src/core/persistence/connector-sync.ts
+++ b/src/core/persistence/connector-sync.ts
@@ -29,7 +29,7 @@ import { persistenceFileHash, type PreparedMutation } from './coordinator.ts';
import { isTerminal, type WriteRequest } from './model.ts';
import { databaseOnlyPublication, prepareFileTarget, preparePrivateTransition } from './page-prepare.ts';
import { sourceCanonicalGit } from './git-door.ts';
-import { isPrivatePage } from '../search/private-visibility.ts';
+import { isPrivacyPrivatePage } from '../search/private-visibility.ts';
import { assertPhysicalRoot } from './physical-root.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { LockStolenError, syncLockId, withRefreshingLock, type DbLockHandle } from '../db-lock.ts';
@@ -249,7 +249,7 @@ async function connectorFileTarget(engine: BrainEngine, row: Pick<WriteRequest,
async function strictPrivateImport(engine: BrainEngine, sourceId: string, content: string, sourcePath: string, snapshot: PageSnapshot | null): Promise<boolean> {
const parsed = parseMarkdown(content, sourcePath);
const frontmatter = snapshot?.page.frontmatter.visibility === 'private' ? { ...parsed.frontmatter, visibility: 'private' } : parsed.frontmatter;
- return isPrivatePage({ type: parsed.type, frontmatter }) && await sourceCanonicalGit(engine, sourceId);
+ return isPrivacyPrivatePage({ type: parsed.type, frontmatter }) && await sourceCanonicalGit(engine, sourceId);
}
/**
@@ -261,7 +261,7 @@ async function strictPrivateImport(engine: BrainEngine, sourceId: string, conten
async function strictPrivateFile(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'>, content: string, sourcePath: string,
snapshot: PageSnapshot | null): Promise<{ file: PreparedMutation['file'] } | null> {
if (!await strictPrivateImport(engine, row.source_id, content, sourcePath, snapshot)) return null;
- const turning = snapshot && !snapshot.page.deleted_at && !isPrivatePage({ type: snapshot.page.type, frontmatter: snapshot.page.frontmatter });
+ const turning = snapshot && !snapshot.page.deleted_at && !isPrivacyPrivatePage({ type: snapshot.page.type, frontmatter: snapshot.page.frontmatter });
return { file: turning ? await preparePrivateTransition(engine, row, snapshot) : undefined };
}
diff --git a/src/core/persistence/git-declared.ts b/src/core/persistence/git-declared.ts
index d061d3ea28..4c2faa0ad0 100644
--- a/src/core/persistence/git-declared.ts
+++ b/src/core/persistence/git-declared.ts
@@ -29,7 +29,7 @@ import { gitChildEnv } from '../git-env.ts';
import type { Action } from '../agent-output.ts';
import { opError, type OperationError } from '../ops/contract.ts';
import { execFile } from '../spawn.ts';
-import { isDerivationPrivate, isPrivatePage, privacyPartSql, readHonorAliases } from '../search/private-visibility.ts';
+import { isPrivacyDerivationPrivate, isPrivacyPrivatePage, privacyPartSql, readHonorAliases } from '../search/private-visibility.ts';
import { DERIVE_PHASE_DB_ONLY_DEFAULTS } from '../storage-config.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import type { PageMutationFile } from './coordinator.ts';
@@ -85,8 +85,8 @@ export function declaredPathClass(root: string, slug: string, page: RecordedFile
*/
export async function privacyClass(engine: BrainEngine, sourceId: string, page: { id?: number | null; slug: string; type?: string | null; frontmatter?: unknown }): Promise<PrivacyClass | null> {
await readHonorAliases(engine);
- if (isPrivatePage(page)) return 'private';
- if (isDerivationPrivate(page)) return 'alias_private';
+ if (isPrivacyPrivatePage(page)) return 'private';
+ if (isPrivacyDerivationPrivate(page)) return 'alias_private';
const frontmatter = typeof page.frontmatter === 'object' && page.frontmatter !== null ? page.frontmatter as Record<string, unknown> : {};
if (frontmatter.derived_from == null && !['atom', 'concept', 'event'].includes(page.type ?? '')) return null;
const [row] = await engine.executeRaw<{ lineage: boolean }>(`SELECT NOT ${privacyPartSql('p')} AS lineage
diff --git a/src/core/persistence/git-gap.ts b/src/core/persistence/git-gap.ts
index 7073d6d8e3..66ac64248d 100644
--- a/src/core/persistence/git-gap.ts
+++ b/src/core/persistence/git-gap.ts
@@ -14,7 +14,7 @@ import type { BrainEngine } from '../engine.ts';
import { hardenedGitStream, hardenedGitSync, NulRecordSplitter } from '../hardened-git.ts';
import { exportBodyLedger, segmentedExportHead, segmentedExportMarkdown, type ExportSnapshot, type ExportWithdrawal } from '../export-snapshot.ts';
import { parseMarkdown } from '../markdown.ts';
-import { isDerivationPrivate, isPrivatePage } from '../search/private-visibility.ts';
+import { isPrivacyDerivationPrivate, isPrivacyPrivatePage } from '../search/private-visibility.ts';
import { alignWithStored } from './align-stored.ts';
import { digest } from './digest.ts';
import { isDeclaredReason, isNeverFiledDerivedPage } from './git-declared.ts';
@@ -46,8 +46,8 @@ export function declaredDatabaseOnly(page: { slug: string; type?: string | null;
lineage_private?: boolean; source_path?: string | null; source_uri?: string | null; withheld_source_path?: string | null }, relativePath: string | null, policy: GitHomePolicy): DeclaredClass | null {
if (policy.mirror) return 'mirror_source';
if (policy.databaseOnlySource) return 'database_only_source';
- if (isPrivatePage(page)) return 'private';
- if (isDerivationPrivate(page)) return 'alias_private';
+ if (isPrivacyPrivatePage(page)) return 'private';
+ if (isPrivacyDerivationPrivate(page)) return 'alias_private';
if (page.lineage_private) return 'lineage_private';
// G7a (git-declared.ts): a strict publication stamps the class it declared; one whose cause is gone (an origin turned
// public, `visibility.honor_aliases` off, the ignore rule removed) keeps it until the page is written again.
diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.ts
index 659e55e55b..3dc719f114 100644
--- a/src/core/search/private-visibility.ts
+++ b/src/core/search/private-visibility.ts
@@ -510,7 +510,12 @@ export async function readHonorAliases(engine: BrainEngine): Promise<boolean> {
* folder rule or a pending folder prefix (`folder_restricted`, selected with folderRestrictedSql or looked up with folderRestricted).
*/
export function isDerivationPrivate(page: { type?: string | null; frontmatter?: unknown; folder_restricted?: boolean | null }): boolean {
- if (page.folder_restricted === true || isPrivatePage(page)) return true;
+ return page.folder_restricted === true || hasReaders(page.frontmatter) || isPrivacyDerivationPrivate(page);
+}
+
+/** isDerivationPrivate by privacy alone (visibility, aliases, pinned questions): what decides where a page lives in Git. */
+export function isPrivacyDerivationPrivate(page: { type?: string | null; frontmatter?: unknown }): boolean {
+ if (isPrivacyPrivatePage(page)) return true;
return typeof page.frontmatter === 'object' && page.frontmatter !== null && hasPrivacyAlias(page.frontmatter as Record<string, unknown>);
}
diff --git a/test/access-git-declared-class.test.ts b/test/access-git-declared-class.test.ts
index 9d5bf8a458..9d0fba5c5a 100644
--- a/test/access-git-declared-class.test.ts
+++ b/test/access-git-declared-class.test.ts
@@ -9,6 +9,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { importFromContent } from '../src/core/import-file.ts';
import { privacyClass } from '../src/core/persistence/git-declared.ts';
+import { declaredDatabaseOnly } from '../src/core/persistence/git-gap.ts';
const SRC = 'git-class';
let engine: PGLiteEngine;
@@ -29,4 +30,13 @@ describe('privacyClass ignores member access (pglite, repo-less)', () => {
expect(await privacyClass(engine, SRC, { slug: 'notes/summary', type: 'note', frontmatter: { derived_from: ['notes/secret-origin'] } })).toBe('lineage_private');
expect(await privacyClass(engine, SRC, { slug: 'notes/summary-2', type: 'note', frontmatter: { derived_from: ['notes/readers-origin'] } })).toBeNull();
}, 60_000);
+
+ test('a page that names readers is not private for placement: privacyClass and declaredDatabaseOnly ignore readers', async () => {
+ const readers = { slug: 'notes/team', type: 'note', frontmatter: { readable_by: ['alice-example'] } };
+ expect(await privacyClass(engine, SRC, readers)).toBeNull();
+ expect(await privacyClass(engine, SRC, { ...readers, frontmatter: { readable_by: ['alice-example'], visibility: 'private' } })).toBe('private');
+ const policy = { mirror: false, databaseOnlySource: false, dbOnly: () => false, ignored: new Set<string>() } as never;
+ expect(declaredDatabaseOnly(readers, 'notes/team.md', policy)).toBeNull();
+ expect(declaredDatabaseOnly({ ...readers, frontmatter: { visibility: 'private' } }, 'notes/team.md', policy)).toBe('private');
+ }, 60_000);
});
diff --git a/test/access-writes.test.ts b/test/access-writes.test.ts
index 83af127b3e..ccd787a094 100644
--- a/test/access-writes.test.ts
+++ b/test/access-writes.test.ts
@@ -19,6 +19,7 @@
* its member was disabled.
* A member who satisfies a folder rule writes the pages under it (the
* publication fast path must not read folder-ruled pages as unopenable).
+ * A stdio server bound through mcp.stdio_member writes as that member.
* 3. Existing coverage (member-read-access) pins reads 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
@@ -33,7 +34,7 @@ import { sqlQueryForEngine } from '../src/core/sql-query.ts';
import { mintLegacyToken } from '../src/core/token-mint.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
import { __resetPrivateVisibilityCacheForTests, withCallerAccess } from '../src/core/search/private-visibility.ts';
-import { remoteCallerAccess } from '../src/core/access/caller.ts';
+import { remoteCallerAccess, STDIO_MEMBER_KEY } from '../src/core/access/caller.ts';
import { submissionAuthority, authorizeStoredRequest } from '../src/core/persistence/authority.ts';
import { admitWrite } from '../src/core/persistence/journal.ts';
import { proposeRevision } from '../src/core/access/policy.ts';
@@ -288,6 +289,58 @@ for (const kind of testBackends()) {
}
}, 240_000);
+ test('a stdio server bound to a member through mcp.stdio_member writes that member\'s pages; unbound it is refused', async () => {
+ async function stdio(op: string, params: Record<string, unknown>) {
+ const out = await dispatchToolCall(engine, op, { ...params }, { remote: true, transport: 'stdio', sourceId: SRC, 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 };
+ }
+ const before = await state();
+ const unbound = await stdio('add_tag', { slug: ALICE_PAGE, tag: 'stdio-tag' });
+ expect({ code: unbound.json.code }).toEqual({ code: 'page_not_found' });
+ expect(await state()).toEqual(before);
+ await engine.setConfig(STDIO_MEMBER_KEY, 'alice-example');
+ try {
+ const appended = await stdio('append_page', { slug: ALICE_PAGE, text: 'Stdio wrote this.', request_id: randomUUID() });
+ expect({ op: 'append_page', isError: appended.isError, code: appended.json.code }).toEqual({ op: 'append_page', isError: false, code: undefined });
+ const tag = await stdio('add_tag', { slug: ALICE_PAGE, tag: 'stdio-tag' });
+ expect({ op: 'add_tag', isError: tag.isError, code: tag.json.code }).toEqual({ op: 'add_tag', isError: false, code: undefined });
+ const created = await stdio('put_page', { slug: 'notes/alice-stdio', content: alicePage('Stdio page.', '[alice-example]') });
+ expect({ op: 'put_page new', isError: created.isError, code: created.json.code }).toEqual({ op: 'put_page new', isError: false, code: undefined });
+ expect((await state()).tags).toBe(before.tags + 1);
+ expect((await state('notes/alice-stdio')).frontmatter.readable_by).toEqual(['alice-example']);
+ } finally {
+ await engine.setConfig(STDIO_MEMBER_KEY, '');
+ }
+ const after = await stdio('remove_tag', { slug: ALICE_PAGE, tag: 'stdio-tag' });
+ expect({ code: after.json.code }).toEqual({ code: 'page_not_found' });
+ }, 240_000);
+
+ test('under a privacy hatch the links effect resolves a stdio writer bound to a reader as that member: its mention edge is kept', async () => {
+ await engine.setConfig(STDIO_MEMBER_KEY, 'alice-example');
+ try {
+ await withEnv({ GBRAIN_REMOTE_PRIVATE_PAGES: '1' }, async () => {
+ const slug = 'notes/mentions-stdio';
+ const out = await dispatchToolCall(engine, 'put_page', { slug, content: '---\ntype: note\ntitle: Stdio mentions\n---\n# Stdio mentions\n\nSee [[' + ALICE_PAGE + ']].' },
+ { remote: true, transport: 'stdio', sourceId: SRC, takesHoldersAllowList: ['world'] });
+ expect(out.isError === true).toBe(false);
+ const settled = async () => (await engine.executeRaw<{ outcome: { added: number } | null }>(
+ "SELECT outcome FROM persistence_effects WHERE kind='links' AND source_id=$1 AND data->>'slug'=$2 ORDER BY id DESC LIMIT 1", [SRC, slug]))[0];
+ for (let i = 0; i < 20 && !(await settled())?.outcome; i++) {
+ await runPersistenceEffects(engine, { engine: 'pglite', embedding_disabled: true } as never, { hostId: localHostId() });
+ await new Promise(resolve => setTimeout(resolve, 50));
+ }
+ const edges = await engine.executeRaw<{ slug: string }>('SELECT t.slug FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id'
+ + ' WHERE f.source_id=$1 AND f.slug=$2', [SRC, slug]);
+ expect({ added: (await settled())?.outcome?.added, edges: edges.map(e => e.slug) }).toEqual({ added: 1, edges: [ALICE_PAGE] });
+ });
+ } finally {
+ await engine.setConfig(STDIO_MEMBER_KEY, '');
+ }
+ }, 120_000);
+
test('extract_facts treats a restricted source_slug exactly like a missing one', async () => {
const hidden = await call('bob', 'extract_facts', { turn_text: 'Bob likes tea.', source_slug: ALICE_PAGE, visibility: 'world' });
const missing = await call('bob', 'extract_facts', { turn_text: 'Bob likes tea.', source_slug: 'notes/never-written', visibility: 'world' });
diff --git a/test/git-canonical-declared-g7a.test.ts b/test/git-canonical-declared-g7a.test.ts
index 569d28b702..70381c1176 100644
--- a/test/git-canonical-declared-g7a.test.ts
+++ b/test/git-canonical-declared-g7a.test.ts
@@ -84,6 +84,20 @@ for (const backend of testBackends()) describe(`[${backend}] G7a: declared datab
expect(head(root)).toBe(before);
}, { databaseUrl, setup }), 120_000);
+ test('GBRA-218: a page that names readers (a member or a group) is not private, so it is committed to Git like any page', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strict(engine);
+ const before = head(root);
+ for (const [slug, content] of [['notes/team-plan', page('Team plan', 'Readers only.', 'readable_by: [alice-example]\n')],
+ ['notes/team-groups', page('Team groups', 'A group.', 'readable_by: [group:team-a]\n')]] as const) {
+ const requestId = randomUUID();
+ expect(await put(ctx, slug, content, requestId)).toMatchObject({ state: 'committed' });
+ await settleManagedGitEffects(engine);
+ expect({ slug, file: existsSync(join(root, `${slug}.md`)), atHead: atHead(root, `${slug}.md`) }).toEqual({ slug, file: true, atHead: `${slug}.md` });
+ expect(await row(engine, slug)).toMatchObject({ live: true, reason: null, source_path: `${slug}.md` });
+ }
+ expect(head(root)).not.toBe(before);
+ }, { databaseUrl, setup }), 120_000);
+
test('Q3: every strict writer is classified when it prepares; a managed import, which builds its own file target, is refused at publication', () => managedBrain(async ({ engine, ctx, root }) => {
writeFileSync(join(root, 'gbrain.yml'), 'storage:\n db_only:\n - cache/\n');
mkdirSync(join(root, 'cache'));