Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(g6): an unmanaged brain refuses a direct import into a git-canonical source; census pins no importFromContent outside the door (GBRA-60)
garrytan25536db30775
diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex f81d0b306a..ea85f30720 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -369,7 +369,7 @@ export async function importFromContent(return { slug, status: screen.refusal.code === 'file_too_large' ? 'skipped' : 'error', chunks: 0, error: screen.refusal.message, refusal: screen.refusal, skip_reason: screen.refusal.code };}const parsed = (screen as { parsed: ParsedMarkdown }).parsed;- if (!opts.prepare) await assertUnmanagedCanonicalWriter(engine, 'direct content import');+ if (!opts.prepare) await assertUnmanagedCanonicalWriter(engine, 'direct content import', { sourceId: sourceId ?? 'default' });// Canonicalize only free-prose fields before protected-fence parsing, hidden// row merging, hashing and indexing. Frontmatter identities stay untouched.parsed.title = sanitizeText(parsed.title);@@ -1230,7 +1230,7 @@ export async function importCodeFile(opts: { noEmbed?: boolean; force?: boolean; sourceId?: string;prepare?: (prepared: import('./persistence/prepared-import.ts').PreparedContentImport) => Promise<ImportResult> } = {},): Promise<ImportResult> {- if (!opts.prepare) await assertUnmanagedCanonicalWriter(engine, 'direct file import');+ if (!opts.prepare) await assertUnmanagedCanonicalWriter(engine, 'direct file import', { sourceId: opts.sourceId ?? 'default' });if (opts.prepare && !opts.noEmbed) throw new Error('Coordinated code import requires provider-free preparation.');const slug = slugifyCodePath(relativePath);const lang = detectCodeLanguage(relativePath) || 'unknown';diff --git a/src/core/persistence/maintenance.ts b/src/core/persistence/maintenance.tsindex c8e01f99ec..27348d2d1f 100644--- a/src/core/persistence/maintenance.ts+++ b/src/core/persistence/maintenance.ts@@ -53,8 +53,11 @@ function engineMigrationFix(m: EngineMigrationSide, why: string): Action {}/** Refuse unsupported multi-stage writers before providers, files or git change. */-export async function assertUnmanagedCanonicalWriter(engine: SqlEngine, operation: string, opts: { migration?: EngineMigrationSide } = {}): Promise<void> {- if (!await readManagedMode(engine)) return;+export async function assertUnmanagedCanonicalWriter(engine: SqlEngine, operation: string, opts: { migration?: EngineMigrationSide; sourceId?: string } = {}): Promise<void> {+ if (!await readManagedMode(engine)) {+ if (opts.sourceId !== undefined) await assertNotStrictSource(engine, opts.sourceId, operation);+ return;+ }const message = `${operation} cannot mutate a managed brain through the legacy writer.`;const why = 'This brain is managed: every write goes through its writer coordinator, which the legacy writer bypasses.';if (opts.migration) {@@ -69,6 +72,21 @@ export async function assertUnmanagedCanonicalWriter(engine: SqlEngine, operatiouser_message: `gbrain stopped ${operation} because your brain switched to managed writes while it ran. Nothing was written; running the same command again uses the managed path.` } });}+/**+ * G6 (git-canonical memory): a strict source (`config.canonical = "git"`) is written only through the door, which+ * commits each file before its row and runs in managed persistence. The legacy writer of an unmanaged brain writes the+ * row first, so it refuses such a source instead of putting content in the database that git does not have.+ */+async function assertNotStrictSource(engine: SqlEngine, sourceId: string, operation: string): Promise<void> {+ const [row] = await engine.executeRaw<{ strict: boolean }>(`SELECT COALESCE(config->>'canonical','')='git' AS strict FROM sources WHERE id=$1`, [sourceId]);+ if (row?.strict !== true) return;+ const why = `Source ${sourceId} is git-canonical: its pages are committed to Git before the database indexes them, and only managed persistence (the writer coordinator) does that. This brain is not managed, so ${operation} would write the database first.`;+ throw opError('writer_coordinator_required', `${operation} cannot write git-canonical source ${sourceId} on an unmanaged brain.`,+ `Nothing was written. Ask the user whether to turn on managed persistence for this brain (the supported way to make a source git-canonical), or to remove canonical: git from source ${sourceId}.`,+ { why, reason: 'strict_source_unmanaged', docs: 'docs/designs/GIT_CANONICAL_MEMORY.md', fix: { consent: [], actor: 'user', requires_exclusive: false, verify: DOCTOR_VERIFY, why,+ user_message: `Source ${sourceId} is set to git-canonical, which only a managed brain can serve, so gbrain wrote nothing. Should this brain move to managed writes, or should ${sourceId} stop being git-canonical?` } });+}+/** The legacy engine copier cannot transfer permanent IDs, withdrawals, ownership or the belief ledger. */export async function assertLegacyEngineMigration(engine: SqlEngine, migration: EngineMigrationSide = { side: 'source', from: 'pglite', to: 'postgres' }): Promise<void> {const tables = ['belief_events', 'persistence_requests', 'fact_withdrawals', 'persistence_worktrees'] as const;diff --git a/test/e2e/strict-source-unmanaged-import-postgres.test.ts b/test/e2e/strict-source-unmanaged-import-postgres.test.tsnew file mode 100644index 0000000000..06255f9460--- /dev/null+++ b/test/e2e/strict-source-unmanaged-import-postgres.test.ts@@ -0,0 +1,2 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';+await registerPostgresTests(() => import('../strict-source-unmanaged-import.test.ts'));diff --git a/test/strict-source-unmanaged-import.test.ts b/test/strict-source-unmanaged-import.test.tsnew file mode 100644index 0000000000..62badb1aa9--- /dev/null+++ b/test/strict-source-unmanaged-import.test.ts@@ -0,0 +1,77 @@+/**+ * G6 (git-canonical memory, docs/designs/GIT_CANONICAL_MEMORY.md): a strict source (`config.canonical = "git"`) is+ * written only through the door, which runs in managed persistence. The legacy writer of an unmanaged brain writes the+ * database row first, so `importFromContent` and `importCodeFile` without the coordinator's `prepare` seam refuse a+ * strict source (`writer_coordinator_required`, reason `strict_source_unmanaged`) and write nothing; other sources+ * import as before. The census pins the rule "no importFromContent outside the door": the only direct paths into the+ * page tables are these two functions' unprepared branches, and each one checks the target source. Red before: the+ * strict-source import committed the row. Runs on PGLite and, with DATABASE_URL, on Postgres.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import ts from 'typescript';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importCodeFile, importFromContent } from '../src/core/import-file.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+beforeAll(async () => {+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) if (engine.kind === 'pglite') await engine.disconnect();+ await closePostgres?.();+});++const page = (title: string) => `---\ntype: note\ntitle: ${title}\n---\n\n${title} body.\n`;+const pageCount = async (engine: BrainEngine, sourceId: string, slug: string) => Number((await engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0]!.n);+const refusal = (promise: Promise<unknown>) => promise.then(() => null, (error: { code?: string; reason?: string; details?: { reason?: string } }) =>+ ({ code: error.code, reason: error.reason ?? error.details?.reason }));++for (const backend of backends) test(`[${backend}] an unmanaged brain refuses a direct import into a strict source and writes nothing; other sources import`, async () => {+ const engine = engines[backends.indexOf(backend)]!;+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('source-a', 'source-a', '{"canonical":"git"}'::jsonb) ON CONFLICT (id) DO UPDATE SET config = EXCLUDED.config`);+ expect(await refusal(importFromContent(engine, 'notes/alice-example', page('Alice'), { noEmbed: true, sourceId: 'source-a' })))+ .toEqual({ code: 'writer_coordinator_required', reason: 'strict_source_unmanaged' });+ expect(await refusal(importCodeFile(engine, 'src/acme-example.ts', 'export const acme = 1;\n', { noEmbed: true, sourceId: 'source-a' })))+ .toEqual({ code: 'writer_coordinator_required', reason: 'strict_source_unmanaged' });+ expect(await pageCount(engine, 'source-a', 'notes/alice-example')).toBe(0);+ expect(await pageCount(engine, 'source-a', 'acme-example-ts')).toBe(0);+ expect((await importFromContent(engine, 'notes/alice-example', page('Alice'), { noEmbed: true })).status).toBe('imported');+ expect(await pageCount(engine, 'default', 'notes/alice-example')).toBe(1);+ await engine.executeRaw("UPDATE sources SET config = config - 'canonical' WHERE id='source-a'");+ expect((await importFromContent(engine, 'notes/alice-example', page('Alice'), { noEmbed: true, sourceId: 'source-a' })).status).toBe('imported');+}, 60_000);++// test-reads-source-ok[structural]: the census is a source-text tripwire by design; the planted copies prove it flags a bypass.+const root = join(import.meta.dir, '..');+/** Each exported import-file function whose unprepared branch writes the page tables, with whether that branch checks the target source. */+function unpreparedGuards(text: string): Record<string, boolean> {+ const file = ts.createSourceFile('import-file.ts', text, ts.ScriptTarget.Latest, true);+ const out: Record<string, boolean> = {};+ file.forEachChild(node => {+ if (!ts.isFunctionDeclaration(node) || !node.name || !['importFromContent', 'importCodeFile'].includes(node.name.text) || !node.body) return;+ out[node.name.text] = node.body.statements.some(statement => {+ if (!ts.isIfStatement(statement) || statement.expression.getText() !== '!opts.prepare') return false;+ const call = statement.thenStatement.getText();+ return call.startsWith('await assertUnmanagedCanonicalWriter(') && /sourceId:/.test(call);+ });+ });+ return out;+}++test('census: every direct importFromContent / importCodeFile write checks its source before writing (no import outside the door on a strict source)', () => {+ const text = readFileSync(join(root, 'src/core/import-file.ts'), 'utf8');+ expect(unpreparedGuards(text)).toEqual({ importFromContent: true, importCodeFile: true });+ expect(unpreparedGuards(text.replace("'direct content import', { sourceId: sourceId ?? 'default' })", "'direct content import')")))+ .toEqual({ importFromContent: false, importCodeFile: true });+ expect(unpreparedGuards(text.replace("if (!opts.prepare) await assertUnmanagedCanonicalWriter(engine, 'direct file import', { sourceId: opts.sourceId ?? 'default' });", '')))+ .toEqual({ importFromContent: true, importCodeFile: false });+});