Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(g6): typed strict_requires_managed refusal; the streamed large-page import checks its source too (GBRA-60)
garrytanf71c0da63f53
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex a3ef6083a0..ebecae80a4 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -4035,6 +4035,16 @@ Reasons: `database_contention`.Override: reason `database_contention`: retryable, exit 1, retryable.+### strict_requires_managed++<a id="strict_requires_managed"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A git-canonical source (config canonical: git) was written on a brain without managed persistence; nothing was written. | A strict source is committed to Git before the database indexes it, and only managed persistence (the writer coordinator) does that; the legacy writer of an unmanaged brain writes the database first. | Ask the user whether to turn on managed persistence for this brain, or to remove canonical: git from the source. | user | `repeat the read that failed` | 1 | no |++More: [docs/designs/GIT_CANONICAL_MEMORY.md](../../docs/designs/GIT_CANONICAL_MEMORY.md)+### sync_admission_restricted<a id="sync_admission_restricted"></a>diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 5a7fc69010..768e6658b0 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -675,6 +675,7 @@ export const CODES = {reasons: ['database_contention'], reason_overrides: { database_contention: { class: 'retryable' } },why: "Usually a dropped connection or a failed statement; the same error after a rerun is not transient. `reason: database_contention`: a write admission that deadlocks, serialization failures, lock timeouts or statement timeouts kept refusing for its whole retry budget; no receipt was confirmed, so the same request_id is safe to retry once the contention clears. `detail: persistence_mode_unknown` (#6482): the persistence_brain singleton is missing, duplicated or carries a non-boolean `enabled`, so gbrain cannot tell whether the brain is managed and refuses every write, sync, connector run and activation step that depends on it rather than route a managed brain through the unmanaged writer; only a well-formed `enabled: false` row selects the unmanaged path.",suggestion: 'For persistence_mode_unknown: run gbrain sources writer status --probe --json on the brain host (it reports the malformed state instead of refusing), fix the persistence_brain row it names, then gbrain doctor --json.' },+ strict_requires_managed: { class: 'consent', actor: 'user', summary: "A git-canonical source (config canonical: git) was written on a brain without managed persistence; nothing was written.", why: 'A strict source is committed to Git before the database indexes it, and only managed persistence (the writer coordinator) does that; the legacy writer of an unmanaged brain writes the database first.', docs: 'docs/designs/GIT_CANONICAL_MEMORY.md', suggestion: 'Ask the user whether to turn on managed persistence for this brain, or to remove canonical: git from the source.' },sync_not_applicable: { class: 'caller', summary: "Sync does not apply to this source: its directory is not a Git checkout.", why: "Sync imports changes between Git commits. A gbrain-owned content directory (created by init) holds files gbrain manages itself and is not a Git repository, so there is nothing to sync; gbrain never initializes Git on its own.", reasons: ['content_directory'] },// #6712 PR 1: the drain lease (src/core/persistence/sync-lease.ts).sync_admission_restricted: { class: 'host_only', retryable: false, actor: 'user',diff --git a/src/core/page-body/streamed-import.ts b/src/core/page-body/streamed-import.tsindex 540308a2d3..92453e20a6 100644--- a/src/core/page-body/streamed-import.ts+++ b/src/core/page-body/streamed-import.ts@@ -310,7 +310,7 @@ export async function importStreamedMarkdownFile(engine: BrainEngine, filePath:return { slug: '', status: 'skipped', skip_reason: 'malformed_path', chunks: 0,error: `Path "${relativePath}" contains bracket or control characters and cannot be imported. Rename the file to import it.` };}- if (!opts.coordinated) await assertUnmanagedCanonicalWriter(engine, 'direct content import');+ if (!opts.coordinated) await assertUnmanagedCanonicalWriter(engine, 'direct content import', { sourceId: opts.sourceId ?? 'default' });const expectedSlug = slugifyPath(relativePath);const file = await open(assertSourceFilePath(filePath), constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));try {diff --git a/src/core/persistence/maintenance.ts b/src/core/persistence/maintenance.tsindex 27348d2d1f..5ef4b74108 100644--- a/src/core/persistence/maintenance.ts+++ b/src/core/persistence/maintenance.ts@@ -81,9 +81,9 @@ async function assertNotStrictSource(engine: SqlEngine, sourceId: string, operatconst [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.`,+ throw opError('strict_requires_managed', `${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,+ { why, 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?` } });}diff --git a/test/strict-source-unmanaged-import.test.ts b/test/strict-source-unmanaged-import.test.tsindex 8c4a6dbdff..994a95976c 100644--- a/test/strict-source-unmanaged-import.test.ts+++ b/test/strict-source-unmanaged-import.test.ts@@ -1,10 +1,11 @@/*** 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`, `importCodeFile` and `importImageFile` without the coordinator's `prepare` seam refuse a- * strict source (`writer_coordinator_required`, reason `strict_source_unmanaged`) and write nothing; other sources+ * database row first, so `importFromContent`, `importCodeFile`, `importImageFile` and the large-page+ * `importStreamedMarkdownFile` outside the coordinator's seam (`prepare` / `coordinated`) refuse a+ * strict source (`strict_requires_managed`) 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 three functions' unprepared branches, and each one checks the target source. Red before: the+ * page tables are these four 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';@@ -14,6 +15,8 @@ import ts from 'typescript';import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { importCodeFile, importFromContent, importImageFile } from '../src/core/import-file.ts';+import { importStreamedMarkdownFile } from '../src/core/page-body/streamed-import.ts';+import type { PageBodyPolicy } from '../src/core/page-body/limits.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';@@ -32,18 +35,22 @@ afterAll(async () => {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 }));+const refusal = (promise: Promise<unknown>) => promise.then(() => null, (error: { code?: string }) =>+ error.code);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' });+ .toEqual('strict_requires_managed');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' });+ .toEqual('strict_requires_managed');expect(await refusal(importImageFile(engine, join(import.meta.dir, 'no-such-dir', 'acme-example.png'), 'img/acme-example.png', { noEmbed: true, sourceId: 'source-a' })))- .toEqual({ code: 'writer_coordinator_required', reason: 'strict_source_unmanaged' });+ .toEqual('strict_requires_managed');+ const now = new Date();+ expect(await refusal(importStreamedMarkdownFile(engine, join(import.meta.dir, 'no-such-dir', 'large.md'), 'notes/large.md', { noEmbed: true, sourceId: 'source-a' },+ { size: 1, mtimeMs: 0, birthtime: now, mtime: now }, {} as PageBodyPolicy)))+ .toEqual('strict_requires_managed');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');@@ -54,14 +61,14 @@ for (const backend of backends) test(`[${backend}] an unmanaged brain refuses a// 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);+/** Each named function whose branch outside the coordinator's seam writes the page tables, with whether that branch checks the target source. */+function unpreparedGuards(text: string, names: string[]): Record<string, boolean> {+ const file = ts.createSourceFile('source.ts', text, ts.ScriptTarget.Latest, true);const out: Record<string, boolean> = {};file.forEachChild(node => {- if (!ts.isFunctionDeclaration(node) || !node.name || !['importFromContent', 'importCodeFile', 'importImageFile'].includes(node.name.text) || !node.body) return;+ if (!ts.isFunctionDeclaration(node) || !node.name || !names.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;+ if (!ts.isIfStatement(statement) || !['!opts.prepare', '!opts.coordinated'].includes(statement.expression.getText())) return false;const call = statement.thenStatement.getText();return call.startsWith('await assertUnmanagedCanonicalWriter(') && /sourceId:/.test(call);});@@ -69,15 +76,20 @@ function unpreparedGuards(text: string): Record<string, boolean> {return out;}-test('census: every direct importFromContent / importCodeFile / importImageFile write checks its source before writing (no import outside the door on a strict source)', () => {+test('census: every direct import write (importFromContent, importCodeFile, importImageFile, importStreamedMarkdownFile) checks its source before writing', () => {+ const names = ['importFromContent', 'importCodeFile', 'importImageFile'];const text = readFileSync(join(root, 'src/core/import-file.ts'), 'utf8');const fileGuard = "if (!opts.prepare) await assertUnmanagedCanonicalWriter(engine, 'direct file import', { sourceId: opts.sourceId ?? 'default' });";const lastFileGuard = text.lastIndexOf(fileGuard);- expect(unpreparedGuards(text)).toEqual({ importFromContent: true, importCodeFile: true, importImageFile: true });- expect(unpreparedGuards(text.replace("'direct content import', { sourceId: sourceId ?? 'default' })", "'direct content import')")))+ expect(unpreparedGuards(text, names)).toEqual({ importFromContent: true, importCodeFile: true, importImageFile: true });+ expect(unpreparedGuards(text.replace("'direct content import', { sourceId: sourceId ?? 'default' })", "'direct content import')"), names)).toEqual({ importFromContent: false, importCodeFile: true, importImageFile: true });- expect(unpreparedGuards(text.replace(fileGuard, '')))+ expect(unpreparedGuards(text.replace(fileGuard, ''), names)).toEqual({ importFromContent: true, importCodeFile: false, importImageFile: true });- expect(unpreparedGuards(text.slice(0, lastFileGuard) + text.slice(lastFileGuard + fileGuard.length)))+ expect(unpreparedGuards(text.slice(0, lastFileGuard) + text.slice(lastFileGuard + fileGuard.length), names)).toEqual({ importFromContent: true, importCodeFile: true, importImageFile: false });+ const streamed = readFileSync(join(root, 'src/core/page-body/streamed-import.ts'), 'utf8');+ expect(unpreparedGuards(streamed, ['importStreamedMarkdownFile'])).toEqual({ importStreamedMarkdownFile: true });+ expect(unpreparedGuards(streamed.replace("'direct content import', { sourceId: opts.sourceId ?? 'default' })", "'direct content import')"), ['importStreamedMarkdownFile']))+ .toEqual({ importStreamedMarkdownFile: false });});