Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
core guard coverage check, facts-prepare forwards the core source lock, Postgres ordered-lock E2E
garrytan9bd7abaa13c7
diff --git a/package.json b/package.jsonindex a91018fb95..f9dc7768e0 100644--- a/package.json+++ b/package.json@@ -137,6 +137,7 @@"check:agent-contract": "bun scripts/check-agent-contract.ts","check:no-legacy-getconnection": "bash scripts/check-no-legacy-getconnection.sh","check:module-size": "bash scripts/check-module-size.sh",+ "check:core-guard-coverage": "node scripts/check-core-guard-coverage.mjs","check:function-size": "bun scripts/check-function-size.ts","check:layering": "bun scripts/check-layering.ts","check:durable-flush": "bun scripts/check-durable-flush.ts",diff --git a/scripts/check-core-guard-coverage.mjs b/scripts/check-core-guard-coverage.mjsnew file mode 100644index 0000000000..332f0e49a8--- /dev/null+++ b/scripts/check-core-guard-coverage.mjs@@ -0,0 +1,78 @@+#!/usr/bin/env node+/**+ * Core memory write-path guard coverage (docs/guides/core-memory.md).+ *+ * Always-loaded core pages are guarded in preparePageMutation+ * (src/core/persistence/page-prepare.ts -> core-guard.ts): owner-only+ * marking, the brain-wide budget, the remote-edit policy, and the ordered+ * source lock the coordinator takes from `exclusiveSources`. This check+ * fails when:+ * 1. a module that builds a PreparedMutation neither routes through+ * preparePageMutation / prepareMemoryMutation nor sits on the reviewed+ * exemption list below (with its reason), or+ * 2. a module wraps preparePageMutation but drops `exclusiveSources`+ * (neither spreads the prepared result nor forwards the field), which+ * would publish a core write without the ordered source lock.+ */+import { readFileSync, readdirSync, statSync } from 'node:fs';+import { join, relative } from 'node:path';++const ROOT = new URL('..', import.meta.url).pathname;++/** Reviewed: preparers that publish without the core guard, and why that is safe. */+const EXEMPT = {+ 'src/core/persistence/sync-prepare.ts': 'owner git edits (managed sync) pass by design; doctor core_memory reports any overage',+ 'src/core/persistence/group-publish.ts': 'bulk managed sync of owner git edits; groupable() excludes core-locked members',+ 'src/core/persistence/reconcile-prepare.ts': 'reconciles the owner checkout into the database (owner edit)',+ 'src/core/persistence/file-repair.ts': 'publishes bytes the owner approved with gbrain repair frontmatter --apply',+ 'src/core/persistence/grandfather.ts': 'adopts pages that already exist at activation; no content change',+ 'src/core/persistence/import-prepare.ts': 'owner-run local import (gbrain import); doctor reports any overage',+ 'src/core/persistence/connector-sync.ts': 'connector-owned pages; core marking is owner-written frontmatter the connector never sets',+ 'src/core/persistence/connector-google-receipts.ts': 'connector receipt rows, not page text',+ 'src/core/persistence/projection-reindex.ts': 'rebuilds derived projections; page text is unchanged',+ 'src/core/persistence/noop-kernel.ts': 'decides that nothing would change; publishes nothing',+ 'src/core/persistence/consumer.ts': 'dispatches to preparers; no page content of its own',+ 'src/core/persistence/coordinator.ts': 'takes the ordered source lock from exclusiveSources; prepares nothing itself',+ 'src/core/persistence/effect-journal.ts': 'post-publication effects; no page text',+ 'src/core/repair/captured-facts.ts': 'owner-run repair that expires fact rows (shrinks only)',+ 'src/core/repair/extractor-facts.ts': 'owner-run repair restoring expired fact rows',+ 'src/core/shared-skills/publication.ts': 'skill bundles, not pages',+ 'src/commands/extract-timeline-db.ts': 'writes timeline rows; timeline never enters core',+};++const GUARDED = /\b(preparePageMutation|prepareMemoryMutation|prepareCoreGuard)\b/;++function walk(dir, out = []) {+ for (const name of readdirSync(dir)) {+ const path = join(dir, name);+ if (statSync(path).isDirectory()) walk(path, out);+ else if (path.endsWith('.ts') && !path.endsWith('.d.ts') && !path.includes('.generated.')) out.push(path);+ }+ return out;+}++const problems = [];+for (const file of walk(join(ROOT, 'src'))) {+ const rel = relative(ROOT, file);+ const text = readFileSync(file, 'utf8');+ if (!/\bPreparedMutation\b/.test(text)) continue;+ if (rel === 'src/core/persistence/page-prepare.ts' || rel === 'src/core/persistence/core-guard.ts') continue;+ if (!GUARDED.test(text)) {+ if (!EXEMPT[rel]) problems.push(`${rel}: builds a PreparedMutation without the core guard. Route page writes through preparePageMutation, or add it to EXEMPT in scripts/check-core-guard-coverage.mjs with the reason core pages are safe.`);+ continue;+ }+ const names = [...text.matchAll(/(?:const|let)\s+(\w+)\s*(?::[^=]+)?=\s*(?:await\s+)?[^;\n]*?\b(?:preparePageMutation|prepareMemoryMutation)\s*\(/g)].map(m => m[1]);+ const reassigned = [...text.matchAll(/\b(\w+)\s*=\s*await\s+[^;\n]*?\b(?:preparePageMutation|prepareMemoryMutation)\s*\(/g)].map(m => m[1]);+ const vars = [...new Set([...names, ...reassigned])];+ const returnsDirect = /return\s+(?:await\s+)?(?:preparePageMutation|prepareMemoryMutation)\s*\(/.test(text);+ const forwards = text.includes('exclusiveSources') || vars.some(v => new RegExp(`\\.\\.\\.${v}\\b`).test(text));+ if (!returnsDirect && !forwards) problems.push(`${rel}: wraps preparePageMutation but drops exclusiveSources, so a core write would publish without the ordered source lock. Spread the prepared result or forward exclusiveSources.`);+}++if (problems.length) {+ console.error('check-core-guard-coverage: FAIL');+ for (const p of problems) console.error(` ${p}`);+ console.error('See docs/guides/core-memory.md (write-path guard) and src/core/persistence/core-guard.ts.');+ process.exit(1);+}+console.log('check-core-guard-coverage: OK');diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.shindex ef451d1f6d..8a8cd80706 100755--- a/scripts/run-verify-parallel.sh+++ b/scripts/run-verify-parallel.sh@@ -129,6 +129,7 @@ CHECKS=("check:pg-url-redaction"# Containment sprint: module-size ratchet + structural-suite freshness."check:module-size"+ "check:core-guard-coverage"# W5 (refactor wave 1): per-function line ratchet over src/**/*.ts (TS AST,# ~1.5s); baseline scripts/function-size-baseline.tsv."check:function-size"diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex cef73d31d3..510298bfc2 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -163,7 +163,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writif (page.observedRevision !== snapshot.revision) throw factsRefusal('revision_conflict', 'The fact entity changed during preparation.', row,`Entity page ${row.slug} changed while its ## Facts table was being prepared, so none of these facts were published.`);}- return { observedRevision: snapshot?.revision ?? null, file: page?.file, noop: entries.every(entry => entry.duplicateId !== null || entry.duplicateOf !== undefined),+ return { observedRevision: snapshot?.revision ?? null, file: page?.file, ...(page?.exclusiveSources ? { exclusiveSources: page.exclusiveSources } : {}), noop: entries.every(entry => entry.duplicateId !== null || entry.duplicateOf !== undefined),additionalPageKeys, validate: async tx => {await validate(tx, true);await page?.validate?.(tx);diff --git a/test/e2e/core-memory-locks-postgres.test.ts b/test/e2e/core-memory-locks-postgres.test.tsnew file mode 100644index 0000000000..c811522e81--- /dev/null+++ b/test/e2e/core-memory-locks-postgres.test.ts@@ -0,0 +1,63 @@+/**+ * Always-loaded core writes on Postgres: the ordered source lock+ * (core-guard.ts lockCoreSources: `sources` rows FOR UPDATE in id order,+ * own source plus `default`, taken after the worktree ownership check and+ * before the authority FOR SHARE and the counter locks) never deadlocks+ * with core writes in another source, non-core writes in `default`, or a+ * concurrent source topology change. Every write commits or is refused by+ * a business rule; none fails with a deadlock (40P01).+ */+import { describe, expect, test } from 'bun:test';+import { mkdirSync } from 'node:fs';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { hasDatabase } from './helpers.ts';+import { managedBrain } from '../helpers/managed-brain.ts';+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../../src/core/persistence/identity.ts';+import { runManagedSourceLifecycle } from '../../src/core/persistence/source-lifecycle.ts';+import { listCorePages } from '../../src/core/core-memory.ts';++const describeE2E = hasDatabase() ? describe : describe.skip;+const page = (title: string, body: string, core: boolean) => `---\ntitle: ${title}\ntype: note\n${core ? 'always_load: true\n' : ''}---\n\n${body}\n`;++async function writer(engine: BrainEngine) {+ const reg = await registerLocalWriter(engine, 'cli');+ return async (sourceId: string, slug: string, content: string) => {+ const response = await withVerifiedLocalRegistration(engine, reg, () => dispatchToolCall(engine, 'put_page', { slug, content, request_id: randomUUID(), source_id: sourceId }, {+ remote: false, config: { engine: 'postgres' }, sourceId, logger: { info() {}, warn() {}, error() {} },+ }));+ const text = (response.content[0] as { text: string }).text;+ return { isError: response.isError === true, text };+ };+}++describeE2E('core memory ordered source lock (Postgres)', () => {+ test('core writes in two sources, non-core writes in default and a topology change interleave without deadlock', () => managedBrain(async ({ engine, root }) => {+ const alphaPath = join(root, '..', 'alpha'); mkdirSync(alphaPath);+ await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: 'alpha', path: alphaPath });+ const put = await writer(engine);+ const writes: Array<Promise<{ isError: boolean; text: string }>> = [];+ for (let i = 0; i < 6; i++) {+ writes.push(put('default', `core/d${i}`, page(`D${i}`, `default core ${i}`, true)));+ writes.push(put('alpha', `core/a${i}`, page(`A${i}`, `alpha core ${i}`, true)));+ writes.push(put('default', `notes/n${i}`, page(`N${i}`, `plain ${i}`, false)));+ }+ const probe = join(root, '..', 'probe'); mkdirSync(probe);+ const topology = (async () => {+ await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: 'probe', path: probe });+ return runManagedSourceLifecycle(engine, { operation: 'remove', sourceId: 'probe', confirmDestructive: true });+ })();+ const results = await Promise.all(writes);+ await topology;+ const deadlocks = results.filter(r => /deadlock|40P01/i.test(r.text));+ expect(deadlocks).toEqual([]);+ const failed = results.filter(r => r.isError);+ // Retryable lock-timeout refusals are allowed under contention; every other outcome is a commit.+ for (const f of failed) expect(f.text).toMatch(/lock_timeout|lock timeout|write_pending|owner_unavailable|source_changed/i);+ const core = (await listCorePages(engine)).map(p => `${p.source_id}:${p.slug}`);+ const committedCore = results.filter((r, i) => !r.isError && i % 3 !== 2).length;+ expect(core.length).toBe(committedCore);+ }, { databaseUrl: process.env.DATABASE_URL }), 240_000);+});