Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge origin/master (#6025 remote bulk writes); put_pages batch groups exclude core-locked writes
garrytan0946323288f7
diff --cc src/core/persistence/coordinator.tsindex 5697cc4ce8,a73c8eae4c..9c8890c8aa--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@@ -14,10 -14,9 +14,10 @@@ import { authorizeStoredRequest } fromimport { localHostId } from './identity.ts';import { acquireWorktree, getWorktreeBinding, guardOwnership, type WorktreeBinding } from './ownership.ts';import { clearResolvedRecovery, completeWrite, getWriteRequestById, lockCounters, markRecovering, prepareRecovery, releaseUnpublishedClaim } from './journal.ts';- import { isTerminal, principalKey, requestPrincipal, recoveryFiles, type RecoveryRecord, type WriteRequest } from './model.ts';+ 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 { requestAttribution } from './attribution.ts';import { withFilesystemPublication } from './filesystem-guard.ts';import { mayReprepare } from './semantic.ts';@@@ -265,11 -270,9 +273,10 @@@ export async function publishMutation(eawait hooks.boundary?.('prepared', row);}const done = await engine.transaction(async tx => {- await declarePersistenceProtocol(tx);- await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");+ await declareDurablePersistence(tx);const liveBinding = await guardOwnership(tx, row, hostId);- if (prepared.sourceExclusive) await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [row.source_id]);+ 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);if (binding && String(liveBinding?.owner_epoch) !== String(binding.owner_epoch)) throw opError('owner_unavailable', 'Owner epoch changed before publication.',`Source ${row.source_id}'s canonical owner changed (a transfer or re-claim) after request ${row.request_id} was prepared, so this host published nothing for it. Inspect the owner and the request before resubmitting; do not claim or transfer the source to push this write through.`,{ fix: ownerStatusFix(row.source_id) });diff --cc src/core/persistence/group-publish.tsindex 5e4ed7a7c1,9ffc56beb4..d84ac13f91--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@@ -39,21 -51,79 +51,79 @@@ import { pipelined } from '../page-statimport { jsonBytes } from './digest.ts';import { writerStamp } from './writer-versions.ts';+ /** A `put_pages` group publishes at most this many pages per transaction, so one commit stays a few seconds long. */+ export const PAGE_BATCH_GROUP_MAX = 8;++ function syncMember(row: WriteRequest): boolean {+ return row.operation === 'submit_job' && (row.intent?.kind === 'managed_sync_import' || row.intent?.kind === 'managed_sync_delete');+ }+/** Whether a prepared member can share a group transaction. */export function groupable(row: WriteRequest, prepared: PreparedMutation): boolean {- return row.operation === 'submit_job' && (row.intent?.kind === 'managed_sync_import' || row.intent?.kind === 'managed_sync_delete')- && (row.target_kind ?? 'page') === 'page' && prepared.target !== 'skill_bundle' && !prepared.file && !prepared.sourceExclusive && !prepared.exclusiveSources?.length && typeof prepared.validate === 'function';- if ((row.target_kind ?? 'page') !== 'page' || prepared.target === 'skill_bundle' || prepared.sourceExclusive) return false;++ if ((row.target_kind ?? 'page') !== 'page' || prepared.target === 'skill_bundle' || prepared.sourceExclusive || prepared.exclusiveSources?.length) return false;+ if (syncMember(row)) return !prepared.file && typeof prepared.validate === 'function';+ return publicationGroupKey(row)?.startsWith('batch:') === true;+ }++ const flat = (sql: string) => sql.replace(/\s+/g, ' ').trim();+ /**+ * Reads a group transaction repeats for every member and whose answer cannot+ * change before it commits: the source's local path (its source row is held+ * FOR SHARE by authorization, whose own reads `transactionMemo` answers) and+ * the owner's host binding (its worktree row is held FOR SHARE by the+ * ownership guard). Nothing in a page publication writes them.+ */+ const STABLE_IN_GROUP = new Set([+ 'SELECT local_path FROM sources WHERE id=$1 AND incarnation=$2::uuid',+ 'SELECT h.local_path FROM persistence_host_bindings h JOIN persistence_worktrees w ON w.id=h.worktree_id AND w.owner_host_id=h.host_id WHERE w.id=$1::uuid',+ ]);+ /**+ * #6007: the group transaction seen through a per-transaction read snapshot.+ * The stable reads above and config values (`getConfig`, one consistent value+ * per key for every member) are answered once; every other call reaches the+ * transaction unchanged. It lives only for one group transaction, so nothing+ * survives a rollback.+ */+ function groupReads(tx: BrainEngine): BrainEngine {+ const reads = new Map<string, Promise<unknown>>();+ const once = <T>(id: string, read: () => Promise<T>): Promise<T> => {+ let value = reads.get(id) as Promise<T> | undefined;+ if (!value) { value = read(); reads.set(id, value); value.catch(() => reads.delete(id)); }+ return value;+ };+ return new Proxy(tx, { get(target, key) {+ if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) =>+ STABLE_IN_GROUP.has(flat(sql)) ? once(JSON.stringify([flat(sql), params ?? null]), () => target.executeRaw(sql, params, opts)) : target.executeRaw(sql, params, opts);+ if (key === 'getConfig') return (name: string) => once(`config:${name}`, () => target.getConfig(name));+ const value = Reflect.get(target, key, target);+ return typeof value === 'function' ? value.bind(target) : value;+ } });+ }++ /** Test seams around a group's commit and its rollback. */+ export interface GroupHooks {+ beforeCommit?(rows: WriteRequest[]): Promise<void>;+ /** After a failed group transaction and the restoration of any file it published. */+ rolledBack?(rows: WriteRequest[]): Promise<void>;}- /** Publishes the whole group or nothing; null means the transaction did not commit and the claims are untouched. */- export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prepared: PreparedMutation[], hostId = localHostId()): Promise<WriteRequest[] | null> {+ /**+ * Publishes the whole group or nothing. `done` null means the transaction did+ * not commit; `requeued` lists members whose claims the file restoration+ * released, which the caller may claim again while it holds the worktree.+ */+ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prepared: PreparedMutation[], hostId = localHostId(),+ hooks: GroupHooks = {}): Promise<{ done: WriteRequest[] | null; requeued: string[] }> {const head = rows[0];- if (!head?.worktree_id || rows.some((row, i) => row.worktree_id !== head.worktree_id || !groupable(row, prepared[i]!))) return null;+ const none = { done: null, requeued: [] };+ if (!head?.worktree_id || rows.some((row, i) => row.worktree_id !== head.worktree_id || row.source_id !== head.source_id || !groupable(row, prepared[i]!))) return none;const binding = await getWorktreeBinding(engine, head.source_id, hostId);- if (!binding || binding.owner_host_id !== hostId || !binding.local_path) return null;+ if (!binding || binding.owner_host_id !== hostId || !binding.local_path) return none;const lock = await acquireWorktree(binding, 0, undefined, engine);- if (!lock) return null;+ if (!lock) return none;let releaseCapacity: (() => void) | null = null;+ const recorded = new Map<number, { row: WriteRequest; record: FileRecoveryRecord; bytes: number }>();+ let committed = false;try {const blocked = await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE worktree_id=$1::uuid AND NOT (id=ANY($2::uuid[])) AND recovery IS NOT NULLUNION ALL SELECT 1 FROM persistence_effects WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1`, [head.worktree_id, rows.map(row => row.id)]);diff --cc src/core/persistence/page-prepare.tsindex 336e5bbd2d,de0afac2a9..47dd3e068a--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@@ -407,14 -394,10 +407,14 @@@ export async function preparePageMutaticonst sourcePath = file && mintMode ? scannerSourcePath(file.root, file.path, mintMode) : undefined;// An inferred mode is pinned with the first origin it mints, so later pages cannot flip the inference (#5610).const pinMode = sourcePath && mintMode && scannerSourcePath(file!.root, file!.root) && !await readSlugRootMode(engine, row.source_id) ? mintMode : undefined;- return { observedRevision, noop, additionalPageKeys:links?.pageKeys, file, ...await pageDatabaseOnlyPublication(engine, row, file), validate: ready.validate, apply: async tx => {+ // Always-loaded core tier: owner-only marking, brain-wide budget, remote-edit policy (core-guard.ts).+ const core = noop ? null : await prepareCoreGuard(engine, { row, snapshot, incoming: targetDeleted ? null : ready.parsedPage });+ return { observedRevision, noop, additionalPageKeys:links?.pageKeys, file, ...await pageDatabaseOnlyPublication(engine, row, file),+ ...(core ? { exclusiveSources: core.exclusiveSources } : {}),+ validate: async tx => { await ready.validate(tx); await core?.validate(tx); }, apply: async tx => {let autoLinks: Awaited<ReturnType<NonNullable<typeof links>['apply']>> | undefined;if (!noop) {- await ready.apply(tx);+ const applied = await ready.apply(tx);// Mandatory metadata shares publication rollback; exact no-ops never heal it.if (sourcePath && !snapshot?.page.source_path) await tx.executeRaw(`UPDATE pages SET source_path = $1WHERE source_id=$2 AND slug=$3 AND source_path IS NULL`, [sourcePath, row.source_id, row.slug]);@@@ -432,15 -415,15 +432,17 @@@for (const tag of snapshot!.tags) if (!versionTags.includes(tag)) await tx.removeTag(row.slug, tag, source);for (const tag of versionTags) await tx.addTag(row.slug, tag, source);}- await project?.(tx);+ // #6007: the page the import just wrote live is the page the projections describe; no re-read.+ await project?.(tx, row.operation === 'restore_page' ? undefined : applied?.pageId);autoLinks = await links?.apply(tx);if (targetDeleted) await tx.softDeletePage(row.slug, source);- // Index installation and terminal receipt share this transaction.- await sealPageTextProjection(tx, row.slug, row.source_id);+ // Index installation and terminal receipt share this transaction. The import sealed the projection+ // as its last revision-changing step; only a later revision change (restore, tags, links, delete) reseals.+ if (!(applied?.sealed && row.operation !== 'restore_page' && !versionTags && !links && !targetDeleted)) await sealPageTextProjection(tx, row.slug, row.source_id);+ if (core) await core.record(tx, (await tx.readPageSnapshot(row.slug, source))?.revision ?? null);}- return { ...advisories, ...(autoLinks ? {auto_links:autoLinks} : {}),+ const coreUsage = core?.usage();+ return { ...advisories, ...(autoLinks ? {auto_links:autoLinks} : {}), ...(coreUsage ? { core: coreUsage } : {}),status: noop ? 'skipped' : row.operation === 'restore_page' ? 'restored' : row.operation === 'revert_version' ? 'reverted' : 'created_or_updated',slug: row.slug, source_id: row.source_id, chunks: ready.result.chunks, noop,...(ready.result.chunks === 0 ? {chunk_skip_reason: noop ? 'write_skipped'diff --cc test/e2e/core-memory-locks-postgres.test.tsindex c811522e81,0000000000..91dc8d4728mode 100644,000000..100644--- a/test/e2e/core-memory-locks-postgres.test.ts+++ b/test/e2e/core-memory-locks-postgres.test.ts@@@ -1,63 -1,0 +1,81 @@@+/**+ * 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);++++ 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;++ });++ 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);++ }, { databaseUrl: process.env.DATABASE_URL }), 120_000);+});diff --cc test/mcp-schema-budget.test.tsindex cab6417c22,77a917fb95..0c0e0a93b7--- a/test/mcp-schema-budget.test.ts+++ b/test/mcp-schema-budget.test.ts@@@ -53,18 -57,14 +57,18 @@@ const INSTRUCTIONS_MAX_CHARS = 4_868; /const DESCRIPTION_HARD_CAP = 1_200;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). */+/**+ * 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.+ */const TOOL_BUDGETS: Record<string, number> = {- add_timeline_entry: 640, cancel_job: 270, cancel_write_request: 350, capture: 1250, context_pack: 760,+ add_timeline_entry: 680, cancel_job: 270, cancel_write_request: 350, capture: 1250, context_pack: 760,delete_skill: 810, delta: 830, edit_page: 1090, entity: 470, find_anomalies: 520, forget: 560, get_agent_job: 270,get_backlinks: 770, get_ingest_log: 280, get_page: 930, get_recent_salience: 660, get_skill: 910,- get_skill_asset: 790, get_write_request: 330, 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: 1320,+ 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: 1330, request_tools: 560, resolve_slugs: 410, search: 1670,+ mute_notice: 460, put_skill: 1420, query: 3100, recall: 1540, remember: 1500, request_tools: 560, resolve_slugs: 410, search: 1670,submit_agent: 750, sync_brain_skills: 770, synthesize: 550, traverse_graph: 810, whoami: 230,};