Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: pre-landing review fixes (rows-behind honors sync eligibility; derived commit failures name their root; apply-guard, file-change re-screen and exit-code tests)

garrytan8ad7c6452fd8
diff --git a/src/core/cycle/derived-write-through.ts b/src/core/cycle/derived-write-through.ts
index 00d5200a4d..6cd9f3f8fa 100644
--- a/src/core/cycle/derived-write-through.ts
+++ b/src/core/cycle/derived-write-through.ts
@@ -89,7 +89,7 @@ export async function derivedFileTarget(engine: BrainEngine, slug: string, sourc
interface DerivedFileChange { slug: string; sourceId: string; filePath: string; writeRoot: string; prior: string | null; after: string | null; bound: string | null }
/** A batch commit the checkout refused: the door's code and message, the batch's files (root-relative) and those left as they were. */
-export interface DerivedCommitFailure { code: string; message: string; paths: string[]; kept: string[] }
+export interface DerivedCommitFailure { code: string; message: string; root: string; paths: string[]; kept: string[] }
/**
* Test seams. `beforeCommit` runs after a batch's files are written and before its commit; a throw stands in for a crash
@@ -252,7 +252,7 @@ async function rollBackDerived(engine: BrainEngine, root: string, batch: readonl
}
}
console.error(`[write-through] commit refused (${code}): ${pending.length - kept.length} generated file(s) rolled back, ${kept.length} left as they are`);
- return { code, message, paths: pending.map(c => relative(root, c.filePath)), kept };
+ return { code, message, root, paths: pending.map(c => relative(root, c.filePath)), kept };
}
/** Whether HEAD of `root`'s checkout already holds the change's resulting bytes (absent for a removal); false when HEAD is unreadable. */
@@ -271,7 +271,7 @@ export function reportFileHolds(result: PhaseResult, held: readonly string[] | u
if (!held?.length) return result;
return { ...result, status: result.status === 'fail' ? 'fail' : 'warn',
details: { ...result.details, file_holds: [...new Set([...((result.details.file_holds as string[] | undefined) ?? []), ...held])] },
- summary: `${result.summary} (${held.length} ${noun} file(s) left as they are: ${[...new Set(held.map(h => /^\S+ \((\w+)/.exec(h)?.[1] ?? 'file_database_drift'))].join(', ')})` };
+ summary: `${result.summary} (${held.length} ${noun} file(s) held: ${[...new Set(held.map(h => /^\S+ \((\w+)/.exec(h)?.[1] ?? 'file_database_drift'))].join(', ')})` };
}
/** `result` with the hook's held files (`reportFileHolds`) and refused commits reported: `details.write_through_failed` and a `warn` status unless it failed. */
@@ -368,10 +368,10 @@ async function dreamFileTarget(engine: BrainEngine, brainDir: string, slug: stri
* path instead of the classic door.
*/
export async function writeDreamPageFile(engine: BrainEngine, brainDir: string, slug: string, sourceId: string,
- opts: { nativeSourceId: string; markdown: string; label?: string }): Promise<DreamPageFileWrite> {
+ opts: { nativeSourceId: string; markdown: string }): Promise<DreamPageFileWrite> {
const file = await writeDreamFile(engine, brainDir, slug, sourceId, opts);
if (!file.change) return file.result;
- const [failure] = await commitDerivedChanges(engine, opts.label ?? 'dream', [file.change]);
+ const [failure] = await commitDerivedChanges(engine, 'dream', [file.change]);
return failure ? { written: false, held: dreamCommitFailedToken(slug, failure) } : file.result;
}
@@ -473,7 +473,7 @@ export async function reverseWriteDreamRefs<R extends { slug: string; source_id:
}
} finally {
for (const failure of await commitDerivedChanges(engine, opts.phase, changes)) {
- for (const change of changes.filter(c => failure.paths.includes(relative(c.writeRoot, c.filePath)))) {
+ for (const change of changes.filter(c => c.writeRoot === failure.root && failure.paths.includes(relative(c.writeRoot, c.filePath)))) {
opts.held?.push(dreamCommitFailedToken(change.slug, failure));
rolledBack++;
}
diff --git a/src/core/persistence/rows-behind.ts b/src/core/persistence/rows-behind.ts
index d12de42d23..439de1b4cc 100644
--- a/src/core/persistence/rows-behind.ts
+++ b/src/core/persistence/rows-behind.ts
@@ -38,6 +38,7 @@ import { compareInlineExportFile, compareSegmentedExportBlob, declaredDatabaseOn
import { prepareRepairPublication, repairScreenConfig } from './file-repair.ts';
import { SYNC_READ_BOUND } from './sync-blobs.ts';
import { heldGitPaths, readSyncImportProvenances } from './sync-holds.ts';
+import { loadSyncEligibility } from './sync-discovery.ts';
import { isSourceDbOnlySlug } from './source-storage.ts';
export const ROWS_BEHIND_BATCH = 256;
@@ -47,7 +48,7 @@ export const ROWS_BEHIND_DOCS = 'docs/guides/repair.md#rows-behind';
/** Why a row is not reported, counted per scan. */
export type RowsBehindSkip = 'held' | 'database_moved' | 'changed_after_checkpoint' | 'no_file_at_checkpoint' | 'not_markdown' | 'declared_database_only'
- | 'not_regular_file' | 'unsafe_path' | 'unconfirmed' | 'current';
+ | 'not_regular_file' | 'unsafe_path' | 'not_eligible' | 'unconfirmed' | 'current';
export interface RowBehind {
slug: string;
@@ -101,11 +102,11 @@ const empty = (sourceId: string, status: RowsBehindScan['status'], reason?: stri
const isMarkdown = (path: string) => /\.mdx?$/i.test(path);
export async function scanRowsBehind(engine: BrainEngine, sourceId: string,
- opts: { deadlineAt?: number; listLimit?: number; confirmUnproven?: boolean; now?: () => number } = {}): Promise<RowsBehindScan> {
+ opts: { deadlineAt?: number; confirmUnproven?: boolean; now?: () => number } = {}): Promise<RowsBehindScan> {
if (!(await managedPersistenceEnabled(engine))) return empty(sourceId, 'not_applicable', 'not_managed');
const context = await sourceContext(engine, sourceId);
if (!context.ok) return empty(sourceId, context.status, context.reason);
- const [source] = await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [sourceId]);
+ const [source] = await engine.executeRaw<{ last_commit: string | null; config: Record<string, unknown> | null }>('SELECT last_commit, config FROM sources WHERE id=$1', [sourceId]);
if (!source?.last_commit) return empty(sourceId, 'not_applicable', 'no_checkpoint');
const root = context.root;
try { isSourceDbOnlySlug(root, '', 'refuse'); } catch { return empty(sourceId, 'unknown', 'invalid_source_config'); }
@@ -117,9 +118,9 @@ export async function scanRowsBehind(engine: BrainEngine, sourceId: string,
await readHonorAliases(engine);
const scope = relative(checkpoint.gitRoot, realpathSync(root)).split(sep).join('/');
const gitPath = (rel: string) => scope ? `${scope}/${rel}` : rel;
+ const { eligible } = await loadSyncEligibility(engine, { root, gitRoot: checkpoint.gitRoot, sourceId, source: { last_commit: source.last_commit, config: source.config ?? {} } });
const policy = { mirror: false, databaseOnlySource: false, dbOnly: (slug: string) => isSourceDbOnlySlug(root, slug, 'refuse'), ignored: new Set<string>() };
const scan: RowsBehindScan = { ...empty(sourceId, 'known'), checkpoint: checkpoint.commit, head: head.commit };
- const limit = opts.listLimit ?? ROWS_BEHIND_LIST_LIMIT;
const count = (why: RowsBehindSkip) => { scan.counts[why] = (scan.counts[why] ?? 0) + 1; };
const now = opts.now ?? Date.now;
const late = () => opts.deadlineAt !== undefined && now() >= opts.deadlineAt;
@@ -148,6 +149,7 @@ export async function scanRowsBehind(engine: BrainEngine, sourceId: string,
const rel = relative(root, path).split(sep).join('/');
if (rel.startsWith('../') || rel === '..') { skip(key.id, 'unsafe_path'); continue; }
if (!isMarkdown(rel)) { skip(key.id, 'not_markdown'); continue; }
+ if (!eligible(gitPath(rel))) { skip(key.id, 'not_eligible'); continue; }
const frontmatter = typeof key.frontmatter === 'string' ? JSON.parse(key.frontmatter) : key.frontmatter;
if (declaredDatabaseOnly({ ...key, frontmatter }, rel, policy)) { skip(key.id, 'declared_database_only'); continue; }
const blob = checkpoint.blobs.get(gitPath(rel));
@@ -191,7 +193,7 @@ export async function scanRowsBehind(engine: BrainEngine, sourceId: string,
if (typeof row === 'string') { count(row); continue; }
const list = row.record === 'recorded' ? scan.behind : scan.unproven;
if (row.record === 'recorded') scan.behind_count++; else scan.unproven_count++;
- if (list.length < limit) list.push(row); else scan.truncated = true;
+ if (list.length < ROWS_BEHIND_LIST_LIMIT) list.push(row); else scan.truncated = true;
}
for (const [id, why] of skipped) if (stop === null || id < stop) count(why);
scan.pages += stop === null ? ids.length : ids.filter(id => id < stop!).length;
diff --git a/test/oversize-hold-rescreen-8072.test.ts b/test/oversize-hold-rescreen-8072.test.ts
index 66a77575d9..25d7fb044e 100644
--- a/test/oversize-hold-rescreen-8072.test.ts
+++ b/test/oversize-hold-rescreen-8072.test.ts
@@ -34,6 +34,8 @@ import { installFaultHook } from '../src/core/persistence/fault-points.ts';
import { localHostId } from '../src/core/persistence/identity.ts';
import { DEADLINE_PASS_GRACE_MS } from '../src/core/persistence/sync-drain.ts';
import { retryHeld } from '../src/commands/sources-retry-held.ts';
+import { printRefreshOutcome } from '../src/commands/sources-refresh.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
import { VERSION } from '../src/version.ts';
import { conversationPage } from './helpers/conversation-page.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
@@ -94,6 +96,14 @@ test('#8072: a held over-ceiling file the streamed import refused is not read ag
expect(streamedImportWork.bytes).toBeGreaterThan(0);
expect(await requestsFor(f, 'conv')).toBe(requests + 1);
expect(await holdsOf(f)).toMatchObject([{ path: 'conv.md', code: 'file_too_large', meta: { attempts: 2 } }]);
+
+ // New bytes for the held file re-screen it on the next tick, with no retry.
+ f.push('alpha/conv.md', fenced.replace('Example fact', 'An edited example fact'));
+ streamedImportWork.bytes = 0;
+ expect((await refreshWorktree(f.engine, f.alpha)).status).toBe('completed');
+ expect(streamedImportWork.bytes).toBeGreaterThan(0);
+ expect(await requestsFor(f, 'conv')).toBe(requests + 2);
+ expect(await holdsOf(f)).toMatchObject([{ path: 'conv.md', code: 'file_too_large' }]);
}), 600_000);
test('#8072: a streamed file_too_large hold re-screens on retry or another gbrain version; a size-only one on every sync', () => {
@@ -113,6 +123,10 @@ test('#8072: a refresh past its sync budget completes with its members deferred,
expect(f.head()).toBe(target);
expect(await f.lastCommit(f.alpha)).not.toBe(target);
expect((await f.refreshRows()).map(row => row.state)).toEqual(['completed']);
+ // Cron and wrappers read the exit code: a deferred refresh is not a clean 0.
+ const log = console.log;
+ console.log = () => {};
+ try { printRefreshOutcome({ result: deferred }, true); expect(currentExitCode()).toBe(1); } finally { console.log = log; _resetCliExitVerdictForTests(); process.exitCode = 0; }
const again = await refreshWorktree(f.engine, f.alpha);
expect(again).toMatchObject({ status: 'sync_deferred', next: `gbrain sources refresh ${f.alpha}` });
diff --git a/test/rows-behind-checkpoint-8071.test.ts b/test/rows-behind-checkpoint-8071.test.ts
index 5c350ed4ec..48f9fa2c0e 100644
--- a/test/rows-behind-checkpoint-8071.test.ts
+++ b/test/rows-behind-checkpoint-8071.test.ts
@@ -18,6 +18,8 @@
* - a checkpoint file the import refuses is held with the refusal's code instead of imported;
* - the scan checks its deadline inside a batch and reports how far it got; doctor counts unproven rows without the
* importer's confirmation; a hold row applies the refusal the apply computes;
+ * - a path sync does not read (`sync.exclude`) is not behind; an unreadable checkpoint commit is unknown, never clean;
+ * - the apply refuses a reimport row whose page moved since the preview and a hold row whose import is no longer refused;
* - repo-less: a brain with no checkout reports not_applicable (ok) and the preview lists nothing.
*
* PGLite always; Postgres too when DATABASE_URL is set (test/e2e wrapper).
@@ -280,6 +282,43 @@ for (const backend of testBackends()) describe(`[${backend}] #8071: rows behind
expect(hold?.message).not.toContain('saved with an older preview');
}, { databaseUrl, setup }), 240_000);
+ test('a path sync does not read (sync.exclude) is not behind; an unreadable checkpoint commit is unknown, never clean', () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await engine.setConfig('sync.exclude', 'notes/a.md');
+ await seedBehind(engine, root, { 'notes/a': { content: note('notes/a', 'The redacted body of notes/a.'), record: 'checkpoint' } });
+ const scan = await scanRowsBehind(engine, 'default');
+ expect(scan.behind).toEqual([]);
+ expect(scan.counts).toMatchObject({ not_eligible: 1 });
+ expect(await doctor(engine)).toMatchObject({ status: 'ok', details: { count: 0 } });
+ const preview = await repair(engine);
+ expect(listing(preview)).toEqual([]);
+ expect((await pageOf(engine, 'notes/a')).body).toContain('The committed body of notes/a.');
+
+ await unguarded(engine, () => engine.executeRaw("UPDATE sources SET last_commit=$1 WHERE id='default'", ['f'.repeat(40)]).then(() => {}));
+ expect(await scanRowsBehind(engine, 'default')).toMatchObject({ status: 'unknown', reason: 'checkpoint_unreadable', complete: false });
+ expect(await doctor(engine)).toMatchObject({ name: CHECK, status: 'ok', readiness_state: 'unknown' });
+ }, { databaseUrl, setup }), 240_000);
+
+ test('the apply refuses a reimport row whose page moved since the preview and a hold row whose import is no longer refused', () => managedBrain(async ({ engine, ctx, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await seedBehind(engine, root, {
+ 'notes/a': { content: note('notes/a', 'The redacted body of notes/a.'), record: 'checkpoint' },
+ 'notes/b': { content: note('notes/b', 'The redacted body of notes/b.'), record: 'checkpoint' },
+ });
+ const preview = await repair(engine);
+ expect(listing(preview)).toEqual([['default:notes/a', 'reimport'], ['default:notes/b', 'reimport']]);
+ await putDatabaseOnly(engine, ctx, 'notes/a', 'A database-only edit of notes/a.');
+ // The saved set names notes/b as a hold, as a preview taken while its import was refused would have.
+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys = jsonb_set(jsonb_set(completed_keys, '{0,items,1,action}', '"hold"'), '{0,items,1,refusal}', '{"code":"invalid_frontmatter","message":"saved with an older preview"}'::jsonb)
+ WHERE op=$1 AND completed_keys->0->>'hash'=$2 AND completed_keys->0->'items'->1->>'slug'='notes/b'`, [PREVIEW_APPROVAL_OP, preview.preview_hash]);
+ const applied = await repair(engine, { apply: true, expect: preview.preview_hash });
+ expect(applied.outcome_items?.map(item => [item.item, item.outcome, item.reason])).toEqual([
+ ['default:notes/a', 'changed_since_preview', 'page_moved'], ['default:notes/b', 'changed_since_preview', 'import_no_longer_refused']]);
+ expect((await pageOf(engine, 'notes/a')).body).toContain('A database-only edit of notes/a.');
+ expect((await pageOf(engine, 'notes/b')).body).toContain('The committed body of notes/b.');
+ expect(await readGitHold(engine, 'default', await incarnationOf(engine), 'notes/b.md')).toBeNull();
+ }, { databaseUrl, setup }), 240_000);
+
test('repo-less: a brain with no checkout is not applicable and the preview lists nothing', async () => {
const home = (await import('node:fs')).mkdtempSync(join((await import('node:os')).tmpdir(), 'gbrain-rows-behind-'));
await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {