Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

core writes share-lock the brain row before the worktree check (claims and topology hold it FOR UPDATE before sources); claim-shaped Postgres race; groupable excludes core-locked writes (unit); remember descriptions trimmed under the 25,000-char starter cap

garrytane8b5ce968e78
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index 8d5ce13565..70069cc14b 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -138,12 +138,12 @@ Every non-localOnly operation on the MCP surface: 139 tools across 23 areas. **S
| Tool | Description | Scope | Starter | Gate |
|---|---|---|---|---|
-| `context_pack` | MEMORY VERB (v1): core memory plus budget-packed cards, open threads and hot facts for up to 8 entities, zero LLM. | read | yes | |
+| `context_pack` | MEMORY VERB (v1): core memory, budget-packed cards, open threads and hot facts for up to 8 entities, zero LLM. | read | yes | |
| `delta` | MEMORY VERB (v1): what changed since a time (pages, facts, thread events), zero LLM. | read | yes | |
| `entity` | MEMORY VERB (v1): person/company/account card, zero LLM. | read | yes | |
| `forget` | MEMORY VERB (v1): expire a remembered fact by its fact_id (never a page slug). | write | yes | |
| `recall` | MEMORY VERB (v1): read saved facts by entity, since or session_id; `query` also searches pages. | read | yes | |
-| `remember` | MEMORY VERB (v1): save one fact; provenance required. | write | yes | |
+| `remember` | MEMORY VERB (v1): save facts with provenance. | write | yes | |
| `synthesize` | [EXPENSIVE / SLOW: LLM calls, costs money] MEMORY VERB (v1): answer a broad question across pages with citations. | read | yes | |
## ontology
diff --git a/docs/architecture/key-files/core-memory.md b/docs/architecture/key-files/core-memory.md
index e2e88106ee..52ade3c446 100644
--- a/docs/architecture/key-files/core-memory.md
+++ b/docs/architecture/key-files/core-memory.md
@@ -19,12 +19,18 @@ notice). User guide: [core memory](../../guides/core-memory.md).
the publish transaction), the remote-edit policy and `core_edit_notices`
rows, and `lockCoreSources`.
- Lock order for a core-touching publish (`coordinator.ts`): worktree native
- lock, then `guardOwnership` (`persistence_worktrees` FOR SHARE), then
- `lockCoreSources` (`sources` rows FOR UPDATE, `ORDER BY id`, own source plus
- `default`) in the source-exclusive slot, then `authorizeStoredRequest`
- (`sources` FOR SHARE), then `lockCounters`. Topology and deactivation take
- worktrees before sources and sources in id order, so the orders agree;
- `test/e2e/core-memory-locks-postgres.test.ts` races them on Postgres.
+ lock, then `lockCoreBrain` (`persistence_brain` FOR SHARE, the first lock
+ effects take in `guardEffectSource`), then `guardOwnership`
+ (`persistence_worktrees` FOR SHARE), then `lockCoreSources` (`sources` rows
+ FOR UPDATE, `ORDER BY id`, own source plus `default`) in the
+ source-exclusive slot, then `authorizeStoredRequest` (`sources` FOR SHARE),
+ then `lockCounters`. Worktree claims and topology changes hold the brain row
+ FOR UPDATE before worktrees and sources, and every publication share-locks
+ it later through the request and effect triggers, so taking it first keeps
+ the orders agreeing. `put_pages` batch groups skip the per-request source
+ lock, so `groupable()` excludes core-locked writes.
+ `test/e2e/core-memory-locks-postgres.test.ts` races core writes against
+ topology changes and a claim-shaped transaction on Postgres.
- `scripts/check-core-guard-coverage.mjs` (`bun run check:core-guard-coverage`,
in `verify`): every PreparedMutation builder routes through the guard or is
on its reviewed exemption list, and wrappers forward `exclusiveSources`.
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 8a68678f49..13e5221865 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -612,9 +612,9 @@ const context_pack: Operation = {
mutating: false,
idempotent: true,
outputRedaction: { retrieval: { localVerbatim: ['facts'] } },
- description: 'MEMORY VERB (v1): core memory plus budget-packed cards, open threads and hot facts for up to 8 entities, zero LLM. Call at session start and after compaction.',
+ description: 'MEMORY VERB (v1): core memory, budget-packed cards, open threads and hot facts for up to 8 entities, zero LLM. Call at session start and after compaction.',
params: {
- entities: { type: 'string', description: 'Comma-separated names or slugs (max 8); omit for core only.' },
+ entities: { type: 'string', description: 'Comma-separated names or slugs (max 8).' },
budget_tokens: { type: 'number', description: 'Token budget; cards pack first.' },
since: { type: 'string', description: 'Only open-thread events after this ISO time.' },
session_id: { type: 'string', description: 'Opaque session id.' },
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 9c8890c8aa..0584dd6bdf 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -17,7 +17,7 @@ import { clearResolvedRecovery, completeWrite, getWriteRequestById, lockCounters
import { isTerminal, principalKey, requestPrincipal, recoveryFiles, type FileRecoveryRecord, type RecoveryRecord, type WriteRequest } from './model.ts';
import type { NativeLockHandle } from './native-lock.ts';
import { withCoordinatedWrite } from './context.ts';
-import { lockCoreSources } from './core-guard.ts';
+import { lockCoreBrain, lockCoreSources } from './core-guard.ts';
import { requestAttribution } from './attribution.ts';
import { withFilesystemPublication } from './filesystem-guard.ts';
import { mayReprepare } from './semantic.ts';
@@ -274,6 +274,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
}
const done = await engine.transaction(async tx => {
await declareDurablePersistence(tx);
+ if (prepared.exclusiveSources?.length) await lockCoreBrain(tx);
const liveBinding = await guardOwnership(tx, row, hostId);
if (prepared.sourceExclusive && !prepared.exclusiveSources?.length) await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [row.source_id]);
if (prepared.exclusiveSources?.length) await lockCoreSources(tx, prepared.sourceExclusive ? [row.source_id, ...prepared.exclusiveSources] : prepared.exclusiveSources);
diff --git a/src/core/persistence/core-guard.ts b/src/core/persistence/core-guard.ts
index 5712c1e015..9d383cd10d 100644
--- a/src/core/persistence/core-guard.ts
+++ b/src/core/persistence/core-guard.ts
@@ -13,13 +13,16 @@
* after `lockCoreSources` serialized every core writer, so concurrent core
* writes can never pass the limit together.
*
- * Lock order (`lockCoreSources`): the coordinator calls it in its
- * source-exclusive slot, which runs after the worktree native lock and the
- * `persistence_worktrees` FOR SHARE ownership check, and before
- * `authorizeStoredRequest` (source FOR SHARE) and `lockCounters`. Rows are
- * locked FOR UPDATE in id order, the same order topology and deactivation
- * locks use, so every path takes worktree row → source rows (id order) →
- * counters, and no core write holds a counter while waiting on a source.
+ * Lock order: worktree native lock, then `lockCoreBrain` (the
+ * `persistence_brain` row FOR SHARE, the same first lock effects take in
+ * `guardEffectSource`), then the `persistence_worktrees` FOR SHARE ownership
+ * check, then `lockCoreSources` (source rows FOR UPDATE in id order) before
+ * `authorizeStoredRequest` (source FOR SHARE), then `lockCounters`. The brain
+ * row comes first because every publication share-locks it later through the
+ * request and effect protocol triggers, while worktree claims and topology
+ * changes hold it FOR UPDATE before they lock sources or worktrees: taking it
+ * after a source row would invert that order. So every path takes brain row →
+ * worktree row → source rows (id order) → counters.
*/
import type { BrainEngine } from '../engine.ts';
import type { Page } from '../types.ts';
@@ -42,6 +45,11 @@ export function coreLockSources(sourceId: string): string[] {
* FOR UPDATE in id order inside the publish transaction (transaction-scoped,
* PgBouncer-safe). See the module comment for the global order.
*/
+/** First lock of a core write's publish transaction; see the module comment for the global order. */
+export async function lockCoreBrain(tx: Pick<BrainEngine, 'executeRaw'>): Promise<void> {
+ await tx.executeRaw('SELECT singleton FROM persistence_brain WHERE singleton=1 FOR SHARE');
+}
+
export async function lockCoreSources(tx: Pick<BrainEngine, 'executeRaw'>, sourceIds: readonly string[]): Promise<void> {
const ids = [...new Set(sourceIds)].sort();
if (!ids.length) return;
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index cc663d1bd4..e3076c05ac 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -62,19 +62,19 @@ const remember: Operation = {
name: 'remember',
idempotent: true,
outputRedaction: 'no_stored_text',
- description: 'MEMORY VERB (v1): save one fact; provenance required. Set `entity` when the fact has a subject, or entity-scoped recall misses it. Branch on `status` (inserted|duplicate|superseded). write_pending carries a receipt: poll get_write_request.',
+ description: 'MEMORY VERB (v1): save facts with provenance. Set `entity` to the subject, or entity-scoped recall misses it. Branch on `status` (inserted|duplicate|superseded); write_pending: poll get_write_request.',
params: {
...PAGE_MUTATION_PARAMS,
fact: { type: 'string', description: 'One claim.' },
items: {
type: 'array',
- description: 'Up to 20 facts at once (e.g. before compaction): [{fact, entity?, kind?, ttl?, provenance?}]',
+ description: '≤20 facts: [{fact, provenance}]',
items: { type: 'object' },
},
provenance: {
type: 'string',
// Required for a single fact (the handler refuses with provenance_required); with items it may be given per item.
- description: 'Where the fact came from (max 500 chars); per item with items.',
+ description: 'Source of the fact (max 500 chars).',
},
ttl: {
type: 'string',
@@ -82,7 +82,7 @@ const remember: Operation = {
},
entity: {
type: 'string',
- description: 'Who or what it is about (name or slug).',
+ description: 'Subject (name or slug).',
},
infer_entity: {
type: 'boolean',
diff --git a/test/e2e/core-memory-locks-postgres.test.ts b/test/e2e/core-memory-locks-postgres.test.ts
index 91dc8d4728..f697ce8cb7 100644
--- a/test/e2e/core-memory-locks-postgres.test.ts
+++ b/test/e2e/core-memory-locks-postgres.test.ts
@@ -1,11 +1,12 @@
/**
- * 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).
+ * Always-loaded core writes on Postgres: the core lock order (core-guard.ts:
+ * `persistence_brain` FOR SHARE first, then the worktree ownership check,
+ * then `sources` rows FOR UPDATE in id order, own source plus `default`,
+ * then the authority FOR SHARE and the counter locks) never deadlocks with
+ * core writes in another source, non-core writes in `default`, a concurrent
+ * source topology change, or a worktree claim (brain row, then source row,
+ * both FOR UPDATE). 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';
@@ -18,6 +19,7 @@ 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';
+import { installFaultHook } from '../../src/core/persistence/fault-points.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`;
@@ -64,18 +66,27 @@ describeE2E('core memory ordered source lock (Postgres)', () => {
test('a core write and a worktree-claim-shaped transaction (brain row, then source row, both FOR UPDATE) never deadlock', () => managedBrain(async ({ engine }) => {
const put = await writer(engine);
await put('default', 'core/seed', page('Seed', 'seed core', true));
- let claimed = false;
- const claim = engine.transaction(async tx => {
- await tx.executeRaw('SELECT singleton FROM persistence_brain WHERE singleton=1 FOR UPDATE');
- await new Promise(r => setTimeout(r, 300));
- await tx.executeRaw("SELECT id FROM sources WHERE id='default' FOR UPDATE");
- claimed = true;
+ let claim: Promise<void> | null = null;
+ installFaultHook(async (point, detail) => {
+ if (point !== 'publication:prepared' || claim) return;
+ let brainHeld!: () => void;
+ const held = new Promise<void>(r => { brainHeld = r; });
+ claim = engine.transaction(async tx => {
+ await tx.executeRaw('SELECT singleton FROM persistence_brain WHERE singleton=1 FOR UPDATE');
+ brainHeld();
+ await new Promise(r => setTimeout(r, 300));
+ await tx.executeRaw("SELECT id FROM sources WHERE id='default' FOR UPDATE NOWAIT");
+ });
+ await held;
});
- await new Promise(r => setTimeout(r, 50));
- const write = put('default', 'core/during-claim', page('During', 'core during a claim', true));
- const [result] = await Promise.all([write, claim]);
- expect(claimed).toBe(true);
- expect(result.text).not.toMatch(/deadlock|40P01/i);
- expect(result.isError).toBe(false);
+ try {
+ const result = await put('default', 'core/during-claim', page('During', 'core during a claim', true));
+ expect(claim).not.toBeNull();
+ await claim;
+ expect(result.text).not.toMatch(/deadlock|40P01/i);
+ expect(result.isError).toBe(false);
+ } finally {
+ installFaultHook(undefined);
+ }
}, { databaseUrl: process.env.DATABASE_URL }), 120_000);
});
diff --git a/test/group-publish-core-exclusion.test.ts b/test/group-publish-core-exclusion.test.ts
new file mode 100644
index 0000000000..fca9c952de
--- /dev/null
+++ b/test/group-publish-core-exclusion.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, test } from 'bun:test';
+import { groupable } from '../src/core/persistence/group-publish.ts';
+import type { WriteRequest } from '../src/core/persistence/model.ts';
+import type { PreparedMutation } from '../src/core/persistence/coordinator.ts';
+
+const batchRow = { operation: 'put_page', target_kind: 'page', intent: { page_batch: { id: 'b1' } } } as unknown as WriteRequest;
+const syncRow = { operation: 'submit_job', target_kind: 'page', intent: { kind: 'managed_sync_import', group: 'g1' } } as unknown as WriteRequest;
+const prepared = (extra: Partial<PreparedMutation> = {}) => ({ observedRevision: null, validate: async () => {}, apply: async () => ({}), ...extra }) as unknown as PreparedMutation;
+
+describe('group publication never carries core-locked writes', () => {
+ test('a put_pages batch member groups unless it locks core sources', () => {
+ expect(groupable(batchRow, prepared())).toBe(true);
+ expect(groupable(batchRow, prepared({ exclusiveSources: ['default'] }))).toBe(false);
+ });
+ test('a managed sync member groups unless it locks core sources', () => {
+ expect(groupable(syncRow, prepared())).toBe(true);
+ expect(groupable(syncRow, prepared({ exclusiveSources: ['alpha', 'default'] }))).toBe(false);
+ });
+});
diff --git a/test/mcp-schema-budget.test.ts b/test/mcp-schema-budget.test.ts
index 0c0e0a93b7..1d0ceca90b 100644
--- a/test/mcp-schema-budget.test.ts
+++ b/test/mcp-schema-budget.test.ts
@@ -59,8 +59,9 @@ const PARAM_DESCRIPTION_HARD_CAP = 200;
/**
* Per-tool budget: JSON.stringify of the served tool definition. get_backlinks / traverse_graph carry the temporal status + as_of params (live relationships by default).
- * remember 1370 -> 1500: the additive `items` batch param (save up to 20 facts
- * before compaction), measured at 1,478; the served starter list stays under 25,000.
+ * remember 1330 -> 1370: the additive `items` batch param (save up to 20 facts
+ * before compaction), measured at 1,344 after its descriptions were shortened so the
+ * served starter list stays under 25,000 next to #6007's put_page growth.
*/
const TOOL_BUDGETS: Record<string, number> = {
add_timeline_entry: 680, cancel_job: 270, cancel_write_request: 350, capture: 1250, context_pack: 760,
@@ -68,7 +69,7 @@ const TOOL_BUDGETS: Record<string, number> = {
get_backlinks: 770, get_ingest_log: 280, get_page: 930, get_recent_salience: 660, get_skill: 910,
get_skill_asset: 790, get_write_request: 360, join_brain: 560, leave_brain: 540, list_brain_skillpack: 230,
list_link_sources: 220, list_pages: 1060, list_skills: 670, list_write_requests: 450, put_page: 1460,
- mute_notice: 460, put_skill: 1420, query: 3100, recall: 1540, remember: 1500, request_tools: 560, resolve_slugs: 410, search: 1670,
+ mute_notice: 460, put_skill: 1420, query: 3100, recall: 1540, remember: 1370, request_tools: 560, resolve_slugs: 410, search: 1670,
submit_agent: 750, sync_brain_skills: 770, synthesize: 550, traverse_graph: 810, whoami: 230,
};