Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(sync): #6712 PR 4b fix 2, close an episode without walking T when the universes are equal

garrytan2a094485025b
diff --git a/src/core/persistence/sync-pass-episode.ts b/src/core/persistence/sync-pass-episode.ts
index 0d5b8b0f0e..b62eb96e72 100644
--- a/src/core/persistence/sync-pass-episode.ts
+++ b/src/core/persistence/sync-pass-episode.ts
@@ -28,15 +28,21 @@ import { SYNC_PASS_COST_OP, type PassEpisode, type SyncSelection } from './sync-
type Exec = Pick<BrainEngine, 'executeRaw'>;
+/** What `selectionEligible` reads of a selection: equal universes (`sameUniverse`) admit exactly the same paths. */
+function universeOf(selection: SyncSelection, scope: string) {
+ return { sub: selection.srcSubpath ? selection.srcSubpath.replace(/^\/+|\/+$/g, '') : scope, includeHidden: selection.includeHidden.map(v => v.endsWith('/') ? `${v}**` : v),
+ exclude: selection.exclude, strategy: selection.strategy ?? 'markdown' };
+}
+const sameUniverse = (a: SyncSelection, b: SyncSelection, scope: string) => JSON.stringify(universeOf(a, scope)) === JSON.stringify(universeOf(b, scope));
+
/** Whether a Git-root path is in the universe of `selection` (the eligibility of sync-pass.ts `readShadowLevel`). */
export function selectionEligible(selection: SyncSelection, scope: string, slugMode: 'git-root' | 'source-root'): (gitPath: string) => boolean {
- const sub = selection.srcSubpath ? selection.srcSubpath.replace(/^\/+|\/+$/g, '') : scope;
- const includeHidden = selection.includeHidden.map(v => v.endsWith('/') ? `${v}**` : v);
+ const { sub, includeHidden, strategy } = universeOf(selection, scope);
return gitPath => {
if (sub && !gitPath.startsWith(`${sub}/`)) return false;
const sourceRelative = sub ? gitPath.slice(sub.length + 1) : gitPath;
return !matchesAnyGlob(sourceRelative, selection.exclude) && !isReservedSkillBundlePath(slugMode === 'source-root' ? sourceRelative : gitPath)
- && isSyncable(gitPath, { strategy: (selection.strategy ?? 'markdown') as 'markdown', includeHidden });
+ && isSyncable(gitPath, { strategy: strategy as 'markdown', includeHidden });
};
}
@@ -79,12 +85,15 @@ export function episodeClosure(input: ClosureInput & { treePaths: Iterable<strin
/**
* The closure of an open episode at the pinned target `head` (one `ls-tree` of the whole commit), tallied in stretches as the
* paths stream in: the pass still holds its level, so a 600k-path commit is never held a second time as a map or a path list.
+ * When the episode's universe equals the one the test compares it with (the pass's, or the configured one when `configured`),
+ * 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> {
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 => {
diff --git a/test/sync-pass-closure-memo-6712.test.ts b/test/sync-pass-closure-memo-6712.test.ts
index 38899aa384..6f1f8d27be 100644
--- a/test/sync-pass-closure-memo-6712.test.ts
+++ b/test/sync-pass-closure-memo-6712.test.ts
@@ -4,7 +4,8 @@
* one `ls-tree` walk; any change to what the closure depends on walks again.
*
* Protects:
- * - a writeback one-file commit (two stamps at the same head) walks the tree once (`sync:closure_walk`);
+ * - 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);
* - 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.
*
@@ -15,9 +16,10 @@ import { execFileSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
import { installFaultHook } from '../src/core/persistence/fault-points.ts';
import { passClosureMemo, passEpisodeClosure } from '../src/core/persistence/sync-pass-episode.ts';
-import type { PassEpisode, SyncSelection } from '../src/core/persistence/sync-pass-row.ts';
+import { MANAGED_SYNC_PASS_OP, type PassEpisode, type SyncSelection } from '../src/core/persistence/sync-pass-row.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
import { managedBrain } from './helpers/managed-brain.ts';
import { testBackends } from './helpers/test-backends.ts';
@@ -43,17 +45,18 @@ test('each closure input is part of the key: a change walks again and matches a
writeFileSync(join(root, 'drafts/c.md'), 'c\n'); commit(root, 'two');
const second = git(root, 'rev-parse', 'HEAD');
const all: SyncSelection = { exclude: [], includeHidden: [], strategy: null, srcSubpath: null, mode: 'committed' };
- const noDrafts: SyncSelection = { ...all, exclude: ['drafts/**'] };
+ const noDrafts: SyncSelection = { ...all, exclude: ['drafts/**'] }, noNotes: SyncSelection = { ...all, exclude: ['notes/**'] };
const episode = (selection: SyncSelection): PassEpisode => ({ opened_at: '2026-01-01T00:00:00Z', selection, inherited: { noEmbed: true, noExtract: true, noSchemaPack: false, from: 'flag' } });
- const base = { gitRoot: root, root, head: first, slugMode: 'git-root' as 'git-root' | 'source-root', episode: episode(all), pass: all, configuredSelection: all, configured: false };
+ // Every step keeps the episode's universe apart from the one it is compared with, so each closure walks (fix 2 skips equal ones).
+ const base = { gitRoot: root, root, head: first, slugMode: 'git-root' as 'git-root' | 'source-root', episode: episode(noDrafts), pass: all, configuredSelection: all, configured: false };
const steps: Array<[string, typeof base]> = [
['same key', base], ['same key again', base],
['head', { ...base, head: second }],
- ['episode selection', { ...base, head: second, episode: episode(noDrafts) }],
- ['pass selection', { ...base, head: second, episode: episode(noDrafts), pass: noDrafts }],
- ['configured selection', { ...base, head: second, episode: episode(noDrafts), pass: noDrafts, configuredSelection: noDrafts }],
- ['configured', { ...base, head: second, episode: episode(noDrafts), pass: noDrafts, configuredSelection: noDrafts, configured: true }],
- ['slug mode', { ...base, head: second, episode: episode(noDrafts), pass: noDrafts, configuredSelection: noDrafts, configured: true, slugMode: 'source-root' }],
+ ['episode selection', { ...base, head: second, episode: episode(noNotes) }],
+ ['pass selection', { ...base, head: second, episode: episode(noNotes), pass: noDrafts }],
+ ['configured selection', { ...base, head: second, episode: episode(noNotes), pass: noDrafts, configuredSelection: noDrafts }],
+ ['configured', { ...base, head: second, episode: episode(noNotes), pass: noDrafts, configuredSelection: noDrafts, configured: true }],
+ ['slug mode', { ...base, head: second, episode: episode(noNotes), pass: noDrafts, configuredSelection: noDrafts, configured: true, slugMode: 'source-root' }],
];
const memo = passClosureMemo(), seen = countWalks(), walks: Record<string, number> = {};
for (const [label, input] of steps) {
@@ -69,14 +72,32 @@ test('each closure input is part of the key: a change walks again and matches a
for (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 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 twice at one head 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();
+ const seen = countWalks(), before = await committedStamps(engine);
expect((await performManagedSync(engine, OPTS)).status).toBe('synced');
- const [stamps] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE intent ? 'stamp' AND state='committed'");
- expect(stamps!.n).toBeGreaterThanOrEqual(3);
+ expect(await committedStamps(engine) - before).toBeGreaterThanOrEqual(2);
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 }) => {
+ 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);
+ expect((await performManagedSync(engine, OPTS)).status).toBe('synced');
+ expect(await committedStamps(engine) - before).toBeGreaterThanOrEqual(2);
+ 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;
+}
diff --git a/test/sync-pass-closure-universe-6712.test.ts b/test/sync-pass-closure-universe-6712.test.ts
new file mode 100644
index 0000000000..43b99f1184
--- /dev/null
+++ b/test/sync-pass-closure-universe-6712.test.ts
@@ -0,0 +1,68 @@
+/**
+ * #6712 PR 4b fix 2: an episode whose universe equals the one design §6's closure test compares it with (the pass's, or
+ * the configured one when the pass is at the configured selection) closes without walking `T` (sync-pass-episode.ts
+ * `passEpisodeClosure`): every path of `T` answers alike on both sides, so the walk could only find inclusion and cover.
+ *
+ * Protects:
+ * - the shortcut returns exactly what the walk returns, over a tree of tracked, excluded, hidden, unsyncable (image, code),
+ * reserved skill-bundle and sub-path files, for every pair of selections (exclude, include-hidden spellings, strategy,
+ * --src-subpath spellings, working mode), both slug modes, a source at the Git root and one in a subdirectory, and
+ * 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.
+ */
+import { expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+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 { episodeClosure, passEpisodeClosure } from '../src/core/persistence/sync-pass-episode.ts';
+import type { PassEpisode, SyncSelection } from '../src/core/persistence/sync-pass-row.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const FILES = ['notes/a.md', 'notes/b.mdx', 'drafts/c.md', '.private/d.md', '.private/deep/e.md', 'img/f.png', 'src/g.ts', 'src/h.py', 'skills/i/SKILL.md',
+ 'docs/j.md', 'docs/drafts/k.md', 'docs/.private/l.md', 'docs/src/m.ts', 'docs/skills/n/SKILL.md', 'README.md'];
+
+const all: SyncSelection = { exclude: [], includeHidden: [], strategy: null, srcSubpath: null, mode: 'committed' };
+/** Each variant with its universe group: variants in one group must skip the walk against each other, all others walk. */
+const VARIANTS: Array<[string, string, SyncSelection]> = [
+ ['all', 'all', all], ['working', 'all', { ...all, mode: 'working' }], ['markdown', 'all', { ...all, strategy: 'markdown' }],
+ ['noDrafts', 'noDrafts', { ...all, exclude: ['drafts/**'] }], ['noDocsDrafts', 'noDocsDrafts', { ...all, exclude: ['drafts/**', 'docs/drafts/**'] }],
+ ['hidden', 'hidden', { ...all, includeHidden: ['.private/'] }], ['hiddenGlob', 'hidden', { ...all, includeHidden: ['.private/**'] }],
+ ['code', 'code', { ...all, strategy: 'code' }], ['auto', 'auto', { ...all, strategy: 'auto' }],
+ ['docs', 'docs', { ...all, srcSubpath: 'docs' }], ['docsSlash', 'docs', { ...all, srcSubpath: '/docs/' }],
+];
+const episode = (selection: SyncSelection): PassEpisode => ({ opened_at: '2026-01-01T00:00:00Z', selection, inherited: { noEmbed: true, noExtract: true, noSchemaPack: false, from: 'flag' } });
+
+test('an episode closes without the walk exactly when the universes are equal, and always as the walk says', async () => {
+ const gitRoot = mkdtempSync(join(tmpdir(), 'gbrain-closure-universe-'));
+ try {
+ git(gitRoot, 'init', '-q');
+ for (const file of FILES) { mkdirSync(join(gitRoot, dirname(file)), { recursive: true }); writeFileSync(join(gitRoot, file), `${file}\n`); }
+ git(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;
+ 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)
+ for (const slugMode of ['git-root', 'source-root'] as const)
+ for (const configured of [false, true])
+ for (const [eName, eGroup, e] of VARIANTS)
+ for (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 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 });
+ }
+ expect(misses).toEqual([]);
+ 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 }); }
+});
+
+/** A source rooted at `docs/`: a selection with no --src-subpath already reads `docs/`, so `all` and `docs` share a universe. */
+function groupIn(group: string): string { return group === 'docs' ? 'all' : group; }