Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(doctor): managed_guard_schema_drift and publication_refusals checks (#5983, #5974)
garrytan8cf2877af2cc
diff --git a/src/commands/doctor/checks/managed-guard.ts b/src/commands/doctor/checks/managed-guard.tsnew file mode 100644index 0000000000..31be987236--- /dev/null+++ b/src/commands/doctor/checks/managed-guard.ts@@ -0,0 +1,87 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { GUARDED_TABLES, PAGE_CHILD_TABLES } from '../../../core/persistence/writer-guard-schema.ts';++const RUNBOOK = 'docs/guides/write-refusals.md#managed-guard-page-children';++/**+ * Every column gbrain's own schema creates on a managed-writer-guarded table.+ * test/doctor-managed-guard.test.ts pins this list to the union of the+ * committed catalog goldens: a migration that adds a column to one of these+ * tables regenerates the goldens and then updates this list.+ */+export const GUARDED_TABLE_COLUMNS: Readonly<Record<string, readonly string[]>> = {+ pages: ['chunker_version', 'compiled_truth', 'content_hash', 'contextual_retrieval_mode', 'corpus_generation', 'created_at', 'database_only_reason',+ 'deleted_at', 'effective_date', 'effective_date_source', 'embedding_signature', 'emotional_weight', 'emotional_weight_recomputed_at', 'frontmatter',+ 'generation', 'id', 'import_filename', 'ingested_at', 'ingested_via', 'knowledge_revision', 'last_retrieved_at', 'links_attendance_blocked_at',+ 'links_attendance_blocked_revision', 'links_extracted_at', 'page_kind', 'revision_principal_id', 'revision_principal_kind', 'revision_write_request_id',+ 'salience_touched_at', 'search_vector', 'slug', 'source_id', 'source_kind', 'source_path', 'source_uri', 'text_projection_revision', 'timeline',+ 'title', 'type', 'updated_at'],+ tags: ['id', 'page_id', 'tag', 'tag_source'],+ slug_aliases: ['alias_slug', 'canonical_slug', 'created_at', 'id', 'notes', 'source_id'],+ page_aliases: ['alias_norm', 'created_at', 'id', 'slug', 'source_id'],+ facts: ['claim_metric', 'claim_period', 'claim_unit', 'claim_value', 'confidence', 'consolidated_at', 'consolidated_into', 'context', 'created_at',+ 'dim_status', 'dimension', 'embedded_at', 'embedded_text_hash', 'embedding', 'embedding_model', 'entity_slug', 'event_type', 'expired_at', 'fact',+ 'id', 'kind', 'last_write_principal_id', 'last_write_principal_kind', 'last_write_request_id', 'last_written_at', 'notability', 'row_num', 'source',+ 'source_id', 'source_markdown_slug', 'source_session', 'superseded_by', 'valid_from', 'valid_until', 'value', 'value_hash', 'visibility',+ 'write_principal_id', 'write_principal_kind', 'write_request_id'],+ takes: ['active', 'claim', 'created_at', 'embedded_at', 'embedded_text_hash', 'embedding', 'embedding_model', 'holder', 'id', 'kind',+ 'last_write_principal_id', 'last_write_principal_kind', 'last_write_request_id', 'last_written_at', 'page_id', 'resolved_at', 'resolved_by',+ 'resolved_outcome', 'resolved_quality', 'resolved_source', 'resolved_unit', 'resolved_value', 'row_num', 'since_date', 'source', 'superseded_by',+ 'until_date', 'updated_at', 'weight', 'write_principal_id', 'write_principal_kind', 'write_request_id'],+ timeline_entries: ['created_at', 'date', 'detail', 'event_page_id', 'id', 'last_write_principal_id', 'last_write_principal_kind', 'last_write_request_id',+ 'last_written_at', 'page_id', 'source', 'summary', 'write_principal_id', 'write_principal_kind', 'write_request_id'],+ sources: ['archive_expires_at', 'archived', 'archived_at', 'chunker_version', 'config', 'contextual_retrieval_mode', 'created_at', 'id', 'incarnation',+ 'last_commit', 'last_sync_at', 'local_path', 'name', 'newest_content_at', 'trust_frontmatter_overrides', 'upstream_behind', 'upstream_checked_at',+ 'upstream_commit'],+};++/**+ * #5983/#5974: a column gbrain never creates on a guarded table means another+ * tool or a manual migration changed the schema the managed-writer guard reads.+ * A `source_id` on tags, timeline_entries or takes made every coordinated write+ * to them fail before v0.60.38.0.+ */+export async function checkManagedGuardSchemaDrift(engine: BrainEngine): Promise<Check> {+ const name = 'managed_guard_schema_drift';+ try {+ const rows = await engine.executeRaw<{ table_name: string; column_name: string }>(+ `SELECT table_name,column_name FROM information_schema.columns WHERE table_schema=current_schema() AND table_name=ANY($1::text[])+ ORDER BY table_name,ordinal_position`, [[...GUARDED_TABLES]]);+ const extra = rows.filter(row => !GUARDED_TABLE_COLUMNS[row.table_name]?.includes(row.column_name)).map(row => `${row.table_name}.${row.column_name}`);+ const pageChildSource = extra.filter(column => PAGE_CHILD_TABLES.some(table => column === `${table}.source_id`));+ const details = { extra_columns: extra, page_child_source_columns: pageChildSource, runbook: RUNBOOK };+ if (!extra.length) return { name, status: 'ok', message: 'Guarded tables carry only the columns gbrain creates.', details };+ return { name, status: 'warn', details, message: `${extra.length} column(s) on managed-writer-guarded tables were not created by gbrain: ${extra.join(', ')}. `+ + (pageChildSource.length ? `${pageChildSource.join(', ')} made every coordinated tag, timeline or take write fail with writer_coordinator_required before v0.60.38.0; `+ + 'this release ignores it and resolves those rows through their page. ' : '')+ + 'Another tool or a manual migration changed this schema. Find out what added the columns before anything else writes there; '+ + `do not drop them without asking the user, because another tool may read them. Recovery after the fix: ${RUNBOOK}.` };+ } catch (error) {+ return { name, status: 'warn', message: `Guarded table columns could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { health: 'unknown', runbook: RUNBOOK } };+ }+}++/** #5974: recent writes the database refused during preparation or publication. */+export async function checkPublicationRefusals(engine: BrainEngine): Promise<Check> {+ const name = 'publication_refusals';+ try {+ const [row] = await engine.executeRaw<{ guard: number; trigger: number; opaque: number }>(+ `SELECT COUNT(*) FILTER (WHERE error_code='writer_coordinator_required' AND error_detail->>'origin'='database_guard')::int AS guard,+ COUNT(*) FILTER (WHERE error_detail->>'origin'='database_trigger')::int AS trigger,+ COUNT(*) FILTER (WHERE error_detail IS NULL AND error_message LIKE 'Publication failed (P0001)%')::int AS opaque+ FROM persistence_requests WHERE state IN ('failed','conflict','recovering') AND COALESCE(completed_at,updated_at) > now()-interval '7 days'`);+ const details = { guard_refusals: row.guard, trigger_refusals: row.trigger, unclassified_p0001: row.opaque, window_days: 7, runbook: RUNBOOK };+ const total = row.guard + row.trigger + row.opaque;+ if (!total) return { name, status: 'ok', message: 'No write was refused by a database guard in the last 7 days.', details };+ return { name, status: 'warn', details, message: `${total} write(s) in the last 7 days were refused by the database and not committed `+ + `(${row.guard} by the managed-writer guard, ${row.trigger} by another trigger, ${row.opaque} recorded before refusals were classified). `+ + 'This is a gbrain defect, a schema change by another tool, or a version mismatch between gbrain processes, not a content conflict. '+ + 'Run gbrain sources writer status --probe --json and read recent_failures[].error_detail (table, operation, guard branch, executing build), '+ + `check managed_guard_schema_drift above, then follow ${RUNBOOK}. Retry each refused write with a new request ID after the cause is fixed.` };+ } catch (error) {+ return { name, status: 'warn', message: `Publication refusals could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { health: 'unknown', runbook: RUNBOOK } };+ }+}diff --git a/src/commands/doctor/checks/schema-health.ts b/src/commands/doctor/checks/schema-health.tsindex 951cd48c20..cc3869c057 100644--- a/src/commands/doctor/checks/schema-health.ts+++ b/src/commands/doctor/checks/schema-health.ts@@ -14,6 +14,7 @@ import { schemaVersionHealth } from '../../../core/schema-version-health.ts';import { pgvectorCheck, pagesUpsertArbiterCheck, linkSourceCheckConstraintCheck } from './core-health.ts';import { pgliteScaleCheck } from './engine-fit.ts';import { checkParkedEffects } from './parked-effects.ts';+import { checkManagedGuardSchemaDrift, checkPublicationRefusals } from './managed-guard.ts';import { checkWorktreeRefreshStuck } from './worktree-refresh.ts';import { checkPersistenceCapacity } from './persistence-capacity.ts';import { checkPostgresCancellationDriver } from './postgres-cancellation.ts';@@ -41,6 +42,8 @@ async function runPgvector(ctx: DoctorContext): Promise<Check[]> {// 4a-bis. Managed write capacity (#5470) and parked postcommit effects (#5612).progress.heartbeat('persistence_capacity');checks.push(await checkPersistenceCapacity(engine), await checkParkedEffects(engine), await checkWorktreeRefreshStuck(engine));+ // #5983/#5974: schema drift on guarded tables and writes the database refused.+ checks.push(await checkManagedGuardSchemaDrift(engine), await checkPublicationRefusals(engine));// 4a-ter. #4613: links_link_source_check shape — a ledger-current brain// whose CHECK reverted to the pre-v114 allowlist rejects every kebab@@ -68,6 +71,8 @@ export const pgvectorEntry: DoctorEntry = {'persistence_capacity','parked_effects','worktree_refresh_stuck',+ 'managed_guard_schema_drift',+ 'publication_refusals','links_link_source_check','pglite_scale',],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex d1d979ea06..c7c2ec5e64 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -218,6 +218,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['orphan_clones','persistence_capacity','worktree_refresh_stuck',+ 'managed_guard_schema_drift',+ 'publication_refusals','persistence_request_growth','persistence_request_indexes','stale_embedding_effects',diff --git a/src/core/persistence/writer-guard-schema.ts b/src/core/persistence/writer-guard-schema.tsindex acb99c97ec..a780b7c77e 100644--- a/src/core/persistence/writer-guard-schema.ts+++ b/src/core/persistence/writer-guard-schema.ts@@ -1,4 +1,6 @@import { ROW_ATTRIBUTION_COLUMNS } from './attribution-schema.ts';+export const PAGE_CHILD_TABLES = ['tags', 'timeline_entries', 'takes'];+export const GUARDED_TABLES = ['pages', 'tags', 'slug_aliases', 'page_aliases', 'facts', 'takes', 'timeline_entries', 'sources'];const ROW_ATTRIBUTION_KEYS = `ARRAY[${ROW_ATTRIBUTION_COLUMNS.map(column => `'${column}'`).join(',')}]`;/** Defense in depth for inventoried legacy writers. Manual SQL is outside the protocol. */export const MANAGED_WRITER_GUARD_SQL = `diff --git a/test/doctor-managed-guard.test.ts b/test/doctor-managed-guard.test.tsnew file mode 100644index 0000000000..a9396c8d27--- /dev/null+++ b/test/doctor-managed-guard.test.ts@@ -0,0 +1,73 @@+/**+ * #5983/#5974 doctor checks: schema drift on managed-writer-guarded tables and+ * writes the database refused. PGLite, no DATABASE_URL.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { readdirSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { submissionAuthority } from '../src/core/persistence/authority.ts';+import { admitWrite, claimNextWrite } from '../src/core/persistence/journal.ts';+import { publishMutation } from '../src/core/persistence/coordinator.ts';+import { GUARDED_TABLES } from '../src/core/persistence/writer-guard-schema.ts';+import { checkManagedGuardSchemaDrift, checkPublicationRefusals, GUARDED_TABLE_COLUMNS } from '../src/commands/doctor/checks/managed-guard.ts';++let engine: PGLiteEngine;+beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ for (const id of ['doctor-owned', 'doctor-other']) await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [id]);+ await registerLocalWriter(engine, 'cli');+}, 120_000);+afterAll(async () => { await engine.disconnect(); });++describe('managed guard doctor checks', () => {+ test('the canonical column list matches every committed catalog golden', () => {+ const dir = join(import.meta.dir, 'fixtures/goldens/catalog');+ const union: Record<string, Set<string>> = Object.fromEntries(GUARDED_TABLES.map(t => [t, new Set<string>()]));+ for (const file of readdirSync(dir).filter(f => /-engine-init-.*\.json$/.test(f))) {+ const tables = JSON.parse(readFileSync(join(dir, file), 'utf8')).golden.tables as Record<string, { columns: string[] }>;+ for (const table of GUARDED_TABLES) for (const column of tables[table].columns) union[table].add(column.split(' ')[1]);+ }+ // A migration that adds a column to a guarded table updates GUARDED_TABLE_COLUMNS in src/commands/doctor/checks/managed-guard.ts.+ expect(Object.fromEntries(GUARDED_TABLES.map(t => [t, [...union[t]].sort()]))).toEqual(+ Object.fromEntries(GUARDED_TABLES.map(t => [t, [...GUARDED_TABLE_COLUMNS[t]].sort()])));+ });++ test('a fresh brain is clean; a source_id column on a page-child table is named', async () => {+ expect(await checkManagedGuardSchemaDrift(engine)).toMatchObject({ status: 'ok', details: { extra_columns: [] } });+ await engine.executeRaw('ALTER TABLE tags ADD COLUMN source_id text');+ await engine.executeRaw('ALTER TABLE facts ADD COLUMN external_note text');+ try {+ const check = await checkManagedGuardSchemaDrift(engine);+ expect(check).toMatchObject({ status: 'warn', details: { extra_columns: ['facts.external_note', 'tags.source_id'], page_child_source_columns: ['tags.source_id'] } });+ expect(check.message).toContain('docs/guides/write-refusals.md#managed-guard-page-children');+ } finally {+ await engine.executeRaw('ALTER TABLE tags DROP COLUMN source_id');+ await engine.executeRaw('ALTER TABLE facts DROP COLUMN external_note');+ }+ });++ test('a write the guard refused is counted with its next step', async () => {+ expect(await checkPublicationRefusals(engine)).toMatchObject({ status: 'ok', details: { guard_refusals: 0 } });+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='doctor-owned'");+ const ctx = { engine, config: { engine: 'pglite' }, sourceId: 'doctor-owned', remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } } as OperationContext;+ const authority = await submissionAuthority(ctx, 'put_page', 'doctor-owned', source.incarnation, 'refused');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ try {+ await admitWrite(engine, { principal: authority.principal, operation: 'put_page', sourceId: 'doctor-owned', sourceIncarnation: source.incarnation,+ slug: 'refused', pageId: null, requestId: randomUUID(), callerIntent: { content: 'x' }, intent: { content: 'x' }, authority });+ const row = (await claimNextWrite(engine, randomUUID()))!;+ const done = await publishMutation(engine, row, { observedRevision: null, apply: async tx => {+ await tx.putPage('leak', { type: 'note', title: 'x', compiled_truth: 'x', timeline: '', frontmatter: {} }, { sourceId: 'doctor-other' });+ return {};+ } });+ expect(done.error_code).toBe('writer_coordinator_required');+ } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); }+ const check = await checkPublicationRefusals(engine);+ expect(check).toMatchObject({ status: 'warn', details: { guard_refusals: 1, trigger_refusals: 0, unclassified_p0001: 0 } });+ expect(check.message).toContain('gbrain sources writer status --probe --json');+ });+});diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 450fd2f82d..ca5b4c45df 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -372,6 +372,30 @@"name": "worktree_refresh_stuck","status": "ok"},+ {+ "category": "ops",+ "details": {+ "extra_columns": [],+ "page_child_source_columns": [],+ "runbook": "docs/guides/write-refusals.md#managed-guard-page-children"+ },+ "message": "Guarded tables carry only the columns gbrain creates.",+ "name": "managed_guard_schema_drift",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "guard_refusals": 0,+ "runbook": "docs/guides/write-refusals.md#managed-guard-page-children",+ "trigger_refusals": 0,+ "unclassified_p0001": 0,+ "window_days": 7+ },+ "message": "No write was refused by a database guard in the last 7 days.",+ "name": "publication_refusals",+ "status": "ok"+ },{"category": "meta","message": "links_link_source_check has the v114 kebab-case gate",diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex fce5a69488..451b6f502d 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -372,6 +372,30 @@"name": "worktree_refresh_stuck","status": "ok"},+ {+ "category": "ops",+ "details": {+ "extra_columns": [],+ "page_child_source_columns": [],+ "runbook": "docs/guides/write-refusals.md#managed-guard-page-children"+ },+ "message": "Guarded tables carry only the columns gbrain creates.",+ "name": "managed_guard_schema_drift",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "guard_refusals": 0,+ "runbook": "docs/guides/write-refusals.md#managed-guard-page-children",+ "trigger_refusals": 0,+ "unclassified_p0001": 0,+ "window_days": 7+ },+ "message": "No write was refused by a database guard in the last 7 days.",+ "name": "publication_refusals",+ "status": "ok"+ },{"category": "meta","message": "links_link_source_check has the v114 kebab-case gate",diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex b9e8429c71..5891604283 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -253,6 +253,14 @@"category": "ops","name": "worktree_refresh_stuck"},+ {+ "category": "ops",+ "name": "managed_guard_schema_drift"+ },+ {+ "category": "ops",+ "name": "publication_refusals"+ },{"category": "meta","name": "links_link_source_check"