Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(#5984): gate findings on the integration branch
garrytanb5f0a67f5af4
diff --git a/scripts/e2e-backend-matrix.txt b/scripts/e2e-backend-matrix.txtindex 515f295a91..536772a53f 100644--- a/scripts/e2e-backend-matrix.txt+++ b/scripts/e2e-backend-matrix.txt@@ -55,3 +55,4 @@ test/e2e/mentions-parity.test.tstest/e2e/persistence-publish-lock-order-postgres.test.tstest/e2e/p8-memory-writes-postgres.test.tstest/e2e/delta-cursor-integrity-postgres.test.ts+test/e2e/single-write-group-parity-postgres.test.tsdiff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 4cfab52f72..76b6e2fbd6 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -340,7 +340,7 @@ export interface SyncOpts {/** #5984: wall-clock ms the current drain started; managed cursors measure their rate from it. */drainStartedAt?: number;/** #5984: `--no-bulk`; and the drain's resolved bulk settings (internal; absent = one request per pass step). */ noBulk?: boolean; bulk?: import('../core/persistence/sync-group.ts').BulkSettings;- /** #5984 lanes: `--lanes N` (1..8) or `--no-lanes` (1). */ lanes?: number;+ /** #5984 lanes: `--lanes N` (1..16) or `--no-lanes` (1). */ lanes?: number;}// The git-plumbing cluster (git(), discoverGitRoot, createSyncBaselineCommit,diff --git a/src/core/link-semantics-pack.ts b/src/core/link-semantics-pack.tsindex f5f6590fda..263e9125cd 100644--- a/src/core/link-semantics-pack.ts+++ b/src/core/link-semantics-pack.ts@@ -41,8 +41,9 @@ export async function primeRelationSemantics(engine: Partial<Pick<BrainEngine, 'if (!engine.getConfig || !engine.listConfigKeys) return;const configured = engine as Pick<BrainEngine, 'getConfig' | 'listConfigKeys'>;try {- const { loadActivePackForLocalEngine } = await import('./schema-pack/best-effort.ts');- const sourceKeys = await configured.listConfigKeys(SOURCE_PACK_PREFIX).catch(() => [] as string[]);+ // The key read is issued at once (not after the module load), so a caller pipelining this keeps its statement order.+ const [{ loadActivePackForLocalEngine }, sourceKeys] = await Promise.all([import('./schema-pack/best-effort.ts'),+ configured.listConfigKeys(SOURCE_PACK_PREFIX).catch(() => [] as string[])]);const sourceIds = [...new Set(sourceKeys.map(k => k.slice(SOURCE_PACK_PREFIX.length)).filter(Boolean))];const packs = await Promise.all([loadActivePackForLocalEngine(configured),diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex d1f37e6f91..9a1819a03e 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -343,7 +343,7 @@ export function lanesLimit(lanes: Pick<LanesReport, 'maximum' | 'configured' | 'if (cap === 'pool') return { kind: 'pool', message: `the connection pool allowed ${lanes.configured} of ${lanes.maximum} lanes.`,raise: `Set GBRAIN_POOL_SIZE=${lanes.maximum + 4} for ${lanes.maximum} lanes, if the database has the connections to spare.` };return { kind: 'maximum', message: `the configured maximum of ${lanes.maximum} lanes was in use.`,- raise: lanes.maximum < 16 ? 'Run gbrain config set sync.lanes 16 (or pass --lanes 16) to allow more.' : null };+ raise: lanes.maximum < 16 ? 'Pass gbrain sync --lanes 16, or run gbrain config set sync.lanes 16, to allow more.' : null };}export interface DrainNext {diff --git a/test/e2e/single-write-fast-path-postgres.test.ts b/test/e2e/single-write-fast-path-postgres.test.tsindex 8534c6df43..ec39293b31 100644--- a/test/e2e/single-write-fast-path-postgres.test.ts+++ b/test/e2e/single-write-fast-path-postgres.test.ts@@ -13,11 +13,12 @@ import { withEnv } from '../helpers/with-env.ts';import type { BrainEngine } from '../../src/core/engine.ts';import type { OperationContext } from '../../src/core/ops/contract.ts';import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';-import { revokeLocalWriter } from '../../src/core/persistence/identity.ts';+import { persistenceHome, revokeLocalWriter } from '../../src/core/persistence/identity.ts';import { installFaultHook } from '../../src/core/persistence/fault-points.ts';import { resetWriteSwitches } from '../../src/core/persistence/switches.ts';import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';import { getWorktreeBinding } from '../../src/core/persistence/ownership.ts';+import { tryAcquireNativeLock, type NativeLockHandle } from '../../src/core/persistence/native-lock.ts';const d = hasDatabase() ? describe : describe.skip;const url = () => process.env.DATABASE_URL!;@@ -107,12 +108,17 @@ d('single page writes on Postgres (Phase 4.1-4.4)', () => {});if (caseName === 'archived source') await administered("UPDATE sources SET archived=true WHERE id='default'");if (caseName === 'moved binding') await administered("UPDATE persistence_source_bindings SET topology_generation=topology_generation+1 WHERE source_id='default'");+ let refreshLock: NativeLockHandle | null = null;if (caseName === 'refreshing worktree') {const binding = (await getWorktreeBinding(engine, 'default'))!;+ // A live refresh holds its lock, so the consumer's recovery scan leaves its fenced row alone (as for a real refresh).+ refreshLock = await tryAcquireNativeLock(join(persistenceHome(), 'locks', `refresh-${binding.worktree_id}.lock`));+ expect(refreshLock).not.toBeNull();await engine.executeRaw(`INSERT INTO persistence_worktree_refreshes (worktree_id,source_ids,principal_id,owner_epoch,topology_generation,state,old_head,target_head,upstream_ref)VALUES ($1::uuid,ARRAY['default'],gen_random_uuid(),$2,$3,'fenced','a','b','origin/main')`, [binding.worktree_id, binding.owner_epoch, binding.topology_generation]);}- refused = await failure(put(ctx, 'notes/next', 'Next write.'));+ try { refused = await failure(put(ctx, 'notes/next', 'Next write.')); }+ finally { await refreshLock?.release(); }const [admitted] = await engine.executeRaw<{ n: number; generation: string | null }>("SELECT count(*)::int AS n,max(topology_generation)::text AS generation FROM persistence_requests WHERE slug='notes/next'");// A moved binding is not a refusal: the write is admitted under the current binding, as without the cache.@@ -127,6 +133,7 @@ d('single page writes on Postgres (Phase 4.1-4.4)', () => {const uncached = await outcome('0');const cached = await outcome('1');if (caseName !== 'moved binding') expect(uncached).not.toBeNull();+ if (caseName === 'refreshing worktree') expect(uncached?.code).toBe('worktree_refreshing');expect(cached).toEqual(uncached);}, 180_000);}diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 5685886a74..6585ad06e1 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -4450,7 +4450,7 @@"kind": "function","name": "importFromContent","signature": [- "(engine: BrainEngine, slug: string, content: string, opts?: { prepare?: (prepared: PreparedContentImport) => Promise<ImportResult>; coordinated?: boolean; prepareFrontmatter?: (page: ParsedPage) => void; noEmbed?: boolean; sourceId?: string; filename?: string; sourcePath?: string; sourceRoot?: string; fileTimes?: { birthtime?: Date; mtime?: Date; firstCommit?: Date; }; forceRechunk?: boolean; activePack?: ParseOpts[\"activePack\"]; source_kind?: string | null; source_uri?: string | null; ingested_via?: string | null; remote?: boolean; allowEmptyOverwrite?: boolean; beforeCommit?: (tx: BrainEngine, slug: string) => Promise<void>; onPostCommitEmbedding?: (complete: () => Promise<ImportEmbeddingResult>) => void; } & ImportFenceOptions) => Promise<ImportResult>"+ "(engine: BrainEngine, slug: string, content: string, opts?: { prepare?: (prepared: PreparedContentImport) => Promise<ImportResult>; coordinated?: boolean; existingSnapshot?: PageSnapshot | null; prepareFrontmatter?: (page: ParsedPage) => void; noEmbed?: boolean; sourceId?: string; filename?: string; sourcePath?: string; sourceRoot?: string; fileTimes?: { birthtime?: Date; mtime?: Date; firstCommit?: Date; }; forceRechunk?: boolean; activePack?: ParseOpts[\"activePack\"]; source_kind?: string | null; source_uri?: string | null; ingested_via?: string | null; remote?: boolean; allowEmptyOverwrite?: boolean; beforeCommit?: (tx: BrainEngine, slug: string) => Promise<void>; onPostCommitEmbedding?: (complete: () => Promise<ImportEmbeddingResult>) => void; } & ImportFenceOptions) => Promise<ImportResult>"]},{diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.jsonindex f1b84060a3..91d0ccf8f8 100644--- a/test/fixtures/goldens/sql-text/_driver.json+++ b/test/fixtures/goldens/sql-text/_driver.json@@ -2054,6 +2054,10 @@},"replaceDerivedLinks": {"default": [+ {+ "paramCount": 1,+ "via": "tagged"+ },{"paramCount": 1,"unsafeOptions": {@@ -2094,10 +2098,6 @@"paramCount": 1,"via": "tagged"},- {- "paramCount": 1,- "via": "tagged"- },{"paramCount": 3,"unsafeOptions": {diff --git a/test/fixtures/goldens/sql-text/links.json b/test/fixtures/goldens/sql-text/links.jsonindex b624900146..1cee75161e 100644--- a/test/fixtures/goldens/sql-text/links.json+++ b/test/fixtures/goldens/sql-text/links.json@@ -281,6 +281,14 @@"event": "begin","lane": "tx"},+ {+ "lane": "tx",+ "params": [+ "string"+ ],+ "sql": "SELECT key FROM config WHERE key LIKE $1 ESCAPE '\\' ORDER BY key",+ "textSha256": "3b7f63477b863dc13bb07fe9cd6980979bd0f7e84196810c1f74ea994df43e79"+ },{"lane": "tx","params": [@@ -316,14 +324,6 @@"sql": "SELECT p.id FROM unnest($1::text[],$2::text[]) WITH ORDINALITY AS k(src,s,n) JOIN pages p ON p.source_id=k.src AND p.slug=k.s ORDER BY k.n FOR UPDATE OF p","textSha256": "d2598c8eb0d051b3f8d25208513a7494b6db488c95574a3781e6db376d945b56"},- {- "lane": "tx",- "params": [- "string"- ],- "sql": "SELECT key FROM config WHERE key LIKE $1 ESCAPE '\\' ORDER BY key",- "textSha256": "3b7f63477b863dc13bb07fe9cd6980979bd0f7e84196810c1f74ea994df43e79"- },{"lane": "tx","params": [diff --git a/test/write-verify-guard.test.ts b/test/write-verify-guard.test.tsindex 019fabe52e..8e95930896 100644--- a/test/write-verify-guard.test.ts+++ b/test/write-verify-guard.test.ts@@ -23,7 +23,7 @@ afterEach(() => { rmSync(root, { recursive: true, force: true }); });/** Preserve the dynamic receiver, including every transaction/savepoint clone. */async function withBrokenReadback(slug: string, fault: 'missing' | 'stale', run: () => Promise<void>) {- const originalPut = engine.putPage; const originalGet = engine.getPage;+ const originalPut = engine.putPage; const originalGet = engine.getPage; const originalSnapshot = engine.readPageSnapshot;let written = false; let injected = false;engine.putPage = async function(this: PGLiteEngine, target, input, opts) {const page = await originalPut.call(this, target, input, opts);@@ -36,8 +36,15 @@ async function withBrokenReadback(slug: string, fault: 'missing' | 'stale', run:injected = true;return fault === 'missing' ? null : { ...page!, content_hash: 'synthetic-stale-hash' } as Page;};+ // A coordinated put_page apply reads the page once after its last write (a snapshot) for the read-back check.+ engine.readPageSnapshot = async function(this: PGLiteEngine, target, opts) {+ const snapshot = await originalSnapshot.call(this, target, opts);+ if (target !== slug || !written || !snapshot) return snapshot;+ injected = true;+ return fault === 'missing' ? null : { ...snapshot, page: { ...snapshot.page, content_hash: 'synthetic-stale-hash' } };+ };try { await run(); expect(injected).toBe(true); }- finally { engine.putPage = originalPut; engine.getPage = originalGet; }+ finally { engine.putPage = originalPut; engine.getPage = originalGet; engine.readPageSnapshot = originalSnapshot; }}describe('post-write read-back verification', () => {