Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#6712 PR 4b: closure-memo writeback cases for the folded stamp; closure-universe replays one tree walk
garrytan87174e170c0c
diff --git a/src/core/persistence/sync-pass-episode.ts b/src/core/persistence/sync-pass-episode.tsindex b62eb96e72..3222e4d3be 100644--- a/src/core/persistence/sync-pass-episode.ts+++ b/src/core/persistence/sync-pass-episode.ts@@ -89,14 +89,16 @@ export function episodeClosure(input: ClosureInput & { treePaths: Iterable<strin* every path answers alike on both sides, so the closure is known without the walk.*/export async function passEpisodeClosure(input: { gitRoot: string; root: string; head: string; slugMode: 'git-root' | 'source-root'; episode: PassEpisode; pass: SyncSelection;- configuredSelection: SyncSelection; configured: boolean }): Promise<EpisodeClosure> {+ configuredSelection: SyncSelection; configured: boolean;+ /** The walk of `head`'s tree (default `walkTreeLevel`); a test replays one recorded listing instead of a `git` process per call. */+ walk?: (visit: (path: string) => void) => Promise<void> }): Promise<EpisodeClosure> {const scope = relative(realpathSync.native(input.gitRoot), realpathSync.native(input.root)).split(sep).join('/');const closure: ClosureInput = { episode: input.episode.selection, pass: input.pass, configuredSelection: input.configuredSelection, configured: input.configured, scope, slugMode: input.slugMode };const tally: ClosureTally = { included: true, covers: true, released: 0 };if (sameUniverse(closure.episode, input.configured ? closure.configuredSelection : closure.pass, scope)) return closureOf(input.configured, tally);let stretch: string[] = [];faultPointNow('sync:closure_walk', { path: input.head });- await walkTreeLevel(input.gitRoot, input.head, '', path => {+ await (input.walk ?? (visit => walkTreeLevel(input.gitRoot, input.head, '', visit)))(path => {stretch.push(path);if (stretch.length === CLOSURE_STRETCH) { tallyClosure(closure, stretch, tally); stretch = []; }});diff --git a/test/fold-hook-noop-6712.test.ts b/test/fold-hook-noop-6712.test.tsindex b76f2de982..9b47c1fce6 100644--- a/test/fold-hook-noop-6712.test.ts+++ b/test/fold-hook-noop-6712.test.ts@@ -9,6 +9,13 @@* trace), with whitespace collapsed and the per-call statement timeout masked. A hook that adds, drops or reorders a* statement for any other write fails here.*+ * PGLite runs `pipelined` branches one after another, so its sequence is compared exactly. Postgres sends them together+ * (page-state/transactions.ts `pipelined`): a branch's later statement goes out when its earlier one returns, so where+ * two branches interleave varies run to run (put_page's origin claim probe beside the takes projection). There the+ * publication is compared as its exact statement multiset plus its exact ordered tail from the effects insert (the+ * canonical import queues none: from its fold's `RELEASE SAVEPOINT`, the end of its apply) to the commit, the stretch the+ * hook runs in, which no pipelined call reaches.+ ** PGLite here; Postgres through test/e2e/fold-hook-noop-6712-postgres.test.ts.* CAPTURE_FOLD_NOOP=1 rewrites the fixture for the engine under test (only ever from the pre-hook commit).*/@@ -105,7 +112,11 @@ for (const backend of testBackends()) {if (process.env.CAPTURE_FOLD_NOOP === '1') { mkdirSync(join(import.meta.dir, 'fixtures'), { recursive: true }); writeFileSync(FIXTURE, `${JSON.stringify({ ...golden, [backend]: got }, null, 1)}\n`); }expect(got.put_page!.length).toBeGreaterThan(5);expect(got.canonical_import!.length).toBeGreaterThan(5);- expect(got).toEqual(process.env.CAPTURE_FOLD_NOOP === '1' ? got : golden[backend]!);+ const want = process.env.CAPTURE_FOLD_NOOP === '1' ? got : golden[backend]!;+ const tailFrom = (sequence: string[]) => { const at = sequence.findLastIndex(sql => sql.startsWith('INSERT INTO persistence_effects (') || sql === 'RELEASE SAVEPOINT gbrain_pass_stamp_fold'); expect(at).toBeGreaterThan(0); return at; };+ const shape = (sequences: Record<string, string[]>) => backend === 'pglite' ? sequences : Object.fromEntries(Object.entries(sequences).map(([write, sequence]) =>+ [write, { statements: [...sequence].sort(), tail: sequence.slice(tailFrom(sequence)) }]));+ expect(shape(got)).toEqual(shape(want));} finally { rmSync(home, { recursive: true, force: true }); }}, 180_000);});diff --git a/test/sync-pass-closure-memo-6712.test.ts b/test/sync-pass-closure-memo-6712.test.tsindex 6f1f8d27be..bd623c82c7 100644--- a/test/sync-pass-closure-memo-6712.test.ts+++ b/test/sync-pass-closure-memo-6712.test.ts@@ -1,11 +1,13 @@/*** #6712 PR 4b fix 1: one pass run computes the episode closure (design §6) once per key (sync-pass-episode.ts* `passClosureMemo`). A writeback round's fold offer and its checkpoint both stamp at the run's pinned head, so they share- * one `ls-tree` walk; any change to what the closure depends on walks again.+ * one `ls-tree` walk; any change to what the closure depends on walks again. Since GBRA-108 option A a writeback folds its+ * stamp into its import (one stamp per round, no checkpoint request), so its round computes the closure once.** Protects:- * - a writeback one-file commit (two stamps at the same head) walks the tree once (`sync:closure_walk`) when its episode's- * universe differs from the pass's, and not at all when they are equal (fix 2, test/sync-pass-closure-universe-6712.test.ts);+ * - a writeback one-file commit stamps exactly once, folded into its import (no separate stamp request), records the import+ * in `converged.writeback`, and walks the tree once (`sync:closure_walk`) when its episode's universe differs from the+ * pass's, and not at all when they are equal (fix 2, test/sync-pass-closure-universe-6712.test.ts);* - each closure input (head, slug mode, the episode's and the pass's selections, `configured`, the configured selection)* is part of the key: changing any one walks again and returns what a fresh walk returns.*@@ -72,32 +74,41 @@ test('each closure input is part of the key: a change walks again and matches afor (const backend of testBackends()) {const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;describe(`#6712 PR 4b episode closure memo (${backend})`, () => {- test('a writeback one-file commit under a carried wider episode stamps twice at one head and walks the tree once', () => managedBrain(async ({ engine, root }) => {+ test('a writeback one-file commit under a carried wider episode stamps once, folded, and walks the tree once', () => managedBrain(async ({ engine, root }) => {expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');const wider: PassEpisode = { opened_at: '2026-01-01T00:00:00Z', selection: { exclude: [], includeHidden: ['.hidden/**'], strategy: null, srcSubpath: null, mode: 'committed' },inherited: { noEmbed: true, noExtract: true, noSchemaPack: false, from: 'flag' } };await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_build_array(jsonb_set(completed_keys->0, '{obligations,episode}', $2::text::jsonb, true)) WHERE op=$1`,[MANAGED_SYNC_PASS_OP, JSON.stringify(wider)]);writeFileSync(join(root, 'notes/a.md'), '---\ntitle: notes/a\n---\nA committed change of notes/a.\n'); commit(root, 'change a, not canonical');- const seen = countWalks(), before = await committedStamps(engine);+ const seen = countWalks(), before = await lastSequence(engine);expect((await performManagedSync(engine, OPTS)).status).toBe('synced');- expect(await committedStamps(engine) - before).toBeGreaterThanOrEqual(2);+ await expectFoldedWriteback(engine, before);expect(seen.walks).toBe(1);expect((await engine.executeRaw<{ e: unknown }>("SELECT completed_keys->0->'obligations'->'episode' AS e FROM op_checkpoints WHERE op=$1", [MANAGED_SYNC_PASS_OP]))[0]?.e ?? null).toBeNull();}, { ...(databaseUrl ? { databaseUrl } : {}), setup }), 120_000);- test('a writeback one-file commit whose episode shares the pass\'s universe stamps twice and walks no tree (fix 2)', () => managedBrain(async ({ engine, root }) => {+ test('a writeback one-file commit whose episode shares the pass\'s universe stamps once, folded, and walks no tree (fix 2)', () => managedBrain(async ({ engine, root }) => {expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');writeFileSync(join(root, 'notes/a.md'), '---\ntitle: notes/a\n---\nA committed change of notes/a.\n'); commit(root, 'change a, not canonical');- const seen = countWalks(), before = await committedStamps(engine);+ const seen = countWalks(), before = await lastSequence(engine);expect((await performManagedSync(engine, OPTS)).status).toBe('synced');- expect(await committedStamps(engine) - before).toBeGreaterThanOrEqual(2);+ await expectFoldedWriteback(engine, before);expect(seen.walks).toBe(0);}, { ...(databaseUrl ? { databaseUrl } : {}), setup }), 120_000);});}-async function committedStamps(engine: BrainEngine): Promise<number> {- const [stamps] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE intent ? 'stamp' AND state='committed'");- return stamps!.n;+async function lastSequence(engine: BrainEngine): Promise<number> {+ return Number((await engine.executeRaw<{ s: number }>('SELECT COALESCE(max(sequence),0) AS s FROM persistence_requests'))[0]!.s);+}++/** The pass after `after` stamped exactly once, folded into the writeback's import, and its converged state lists that import. */+async function expectFoldedWriteback(engine: BrainEngine, after: number): Promise<void> {+ const stamped = await engine.executeRaw<{ id: string; kind: string; state: string; stamp: string | null; skipped: string | null; written: boolean | null }>(+ `SELECT id::text AS id, intent->>'kind' AS kind, state, outcome->>'pass_stamp' AS stamp, outcome->>'pass_stamp_skipped' AS skipped,+ (outcome->'persistence'->>'file_written')::boolean AS written FROM persistence_requests WHERE sequence > $1 AND intent ? 'stamp' ORDER BY sequence`, [after]);+ expect(stamped.map(({ id, ...row }) => row)).toEqual([{ kind: 'managed_sync_import', state: 'committed', stamp: 'folded', skipped: null, written: true }]);+ const [pass] = await engine.executeRaw<{ writeback: string[] | null }>("SELECT completed_keys->0->'obligations'->'converged'->'writeback' AS writeback FROM op_checkpoints WHERE op=$1", [MANAGED_SYNC_PASS_OP]);+ expect(pass!.writeback).toEqual([stamped[0]!.id]);}diff --git a/test/sync-pass-closure-universe-6712.test.ts b/test/sync-pass-closure-universe-6712.test.tsindex 43b99f1184..51061ab76b 100644--- a/test/sync-pass-closure-universe-6712.test.ts+++ b/test/sync-pass-closure-universe-6712.test.ts@@ -10,6 +10,10 @@* both values of `configured`;* - the walk is skipped exactly for the pairs whose universes are equal (equal spellings included) and taken for every* other pair, so a selection field the shortcut ignored would close an episode the walk keeps open.+ *+ * The fixture's tree is walked once (`walkTreeLevel`) and replayed into every closure that walks (`walk`), instead of a+ * `git ls-tree` process per pair; one episode variant's row also walks for real at every root, slug mode and `configured`,+ * and must equal the replay.*/import { expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';@@ -17,6 +21,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { walkTreeLevel } from '../src/core/persistence/sync-git-stream.ts';import { episodeClosure, passEpisodeClosure } from '../src/core/persistence/sync-pass-episode.ts';import type { PassEpisode, SyncSelection } from '../src/core/persistence/sync-pass-row.ts';@@ -43,7 +48,11 @@ test('an episode closes without the walk exactly when the universes are equal, agit(gitRoot, 'add', '-A'); git(gitRoot, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'tree');const head = git(gitRoot, 'rev-parse', 'HEAD'), treePaths = git(gitRoot, 'ls-tree', '-r', '--name-only', head).split('\n');expect(treePaths.length).toBe(FILES.length);- let walks = 0;+ const listing: string[] = [];+ await walkTreeLevel(gitRoot, head, '', path => { listing.push(path); });+ expect([...listing].sort()).toEqual([...treePaths].sort());+ const walk = async (visit: (path: string) => void) => { for (const path of listing) visit(path); };+ let walks = 0, real = 0;installFaultHook(point => { if (point === 'sync:closure_walk') walks++; });const misses: unknown[] = [], tally = { skipped: 0, walked: 0, closes: 0, open: 0 };for (const [root, scope] of [[gitRoot, ''], [join(gitRoot, 'docs'), 'docs']] as const)@@ -53,13 +62,20 @@ test('an episode closes without the walk exactly when the universes are equal, afor (const [oName, oGroup, other] of VARIANTS) {const pass = configured ? all : other, configuredSelection = configured ? other : all;const before = walks;- const got = await passEpisodeClosure({ gitRoot, root, head, slugMode, episode: episode(e), pass, configuredSelection, configured });+ const input = { gitRoot, root, head, slugMode, episode: episode(e), pass, configuredSelection, configured };+ const got = await passEpisodeClosure({ ...input, walk });const want = episodeClosure({ episode: e, pass, configuredSelection, configured, scope, slugMode, treePaths });const walked = walks - before, wantWalk = (scope ? groupIn(eGroup) !== groupIn(oGroup) : eGroup !== oGroup) ? 1 : 0;tally[walked ? 'walked' : 'skipped']++; tally[want.closes ? 'closes' : 'open']++;if (JSON.stringify(got) !== JSON.stringify(want) || walked !== wantWalk) misses.push({ scope, slugMode, configured, e: eName, other: oName, got, want, walked, wantWalk });+ if (eName === 'noDocsDrafts') {+ const fresh = await passEpisodeClosure(input);+ real += walks - before - walked;+ if (JSON.stringify(fresh) !== JSON.stringify(got)) misses.push({ scope, slugMode, configured, e: eName, other: oName, replayed: got, fresh });+ }}expect(misses).toEqual([]);+ expect(real).toBeGreaterThan(0);expect(tally.skipped).toBeGreaterThan(0); expect(tally.walked).toBeGreaterThan(0); expect(tally.closes).toBeGreaterThan(0); expect(tally.open).toBeGreaterThan(0);} finally { installFaultHook(undefined); rmSync(gitRoot, { recursive: true, force: true }); }});