Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(import): a throwing onFileResult is that file's outcome, not a rejected import (GBRA-130 A-66)

garrytanaca0be66b6a6
diff --git a/src/commands/import.ts b/src/commands/import.ts
index 73d45717f5..91c9a2ad0c 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -705,6 +705,15 @@ export async function runImport(
// never plans against the empty tables it started with (O-CEO-17).
const analyzeEvery = await importAnalyzeEveryPages(engine);
+ // GBRA-130 A-66: a throwing caller callback is that file's outcome, never a rejection of the whole import.
+ async function reportFileResult(...args: Parameters<NonNullable<typeof opts.onFileResult>>): Promise<'held' | undefined> {
+ try { return await opts.onFileResult?.(...args); }
+ catch (e) {
+ console.error(` Warning: could not record the outcome of ${sanitizePathForDisplay(args[0])} (${e instanceof Error ? e.message : String(e)}); it is not held, the import continues.`);
+ return undefined;
+ }
+ }
+
async function processFile(eng: BrainEngine, filePath: string, settled?: PromiseSettledResult<ImportResult>) {
if (!settled && signal?.aborted) return;
const relativePath = singleFile ? basename(filePath) : relative(dir, filePath);
@@ -736,7 +745,7 @@ export async function runImport(
if (!settled && _fileMs > 5000) {
console.error(`[gbrain phase] import.process_file slow ${_fileMs}ms ${relativePath}`);
}
- if (await opts.onFileResult?.(importRelPath, filePath, result) === 'held') {
+ if (await reportFileResult(importRelPath, filePath, result) === 'held') {
skipped++;
completed.add(relativePath);
} else if (result.status === 'imported') {
@@ -781,7 +790,7 @@ export async function runImport(
}
// #5600: an accepted managed import still publishing is not a failure; the next run resumes its request.
if (acceptedPendingReceipt(e)) { skipped++; console.error(` Pending: ${relativePath} was accepted and is still publishing; rerun to confirm it.`); }
- else if (await opts.onFileResult?.(importRelPath, filePath, { status: 'error', error: e instanceof Error ? e.message : String(e) }) === 'held') { skipped++; completed.add(relativePath); } else {
+ else if (await reportFileResult(importRelPath, filePath, { status: 'error', error: e instanceof Error ? e.message : String(e) }) === 'held') { skipped++; completed.add(relativePath); } else {
const msg = e instanceof Error ? e.message : String(e);
const { count, sample } = recordImportFailure(errorCounts, errorSamples, msg);
if (count <= 5) {
diff --git a/test/import-file-result-callback-gbra130.test.ts b/test/import-file-result-callback-gbra130.test.ts
new file mode 100644
index 0000000000..cf5debb4cc
--- /dev/null
+++ b/test/import-file-result-callback-gbra130.test.ts
@@ -0,0 +1,68 @@
+/**
+ * GBRA-130 A-66 (#6712 PR 4b): `runImport` awaited the caller's `onFileResult` callback bare, both for a file's result
+ * and inside the catch that turns a thrown import into a per-file failure. A callback that threw (full sync's hold
+ * bookkeeping) escaped processFile and rejected the whole import, so one file's bookkeeping failure stopped every file.
+ *
+ * Protects (red before: runImport rejects with the callback's error): a throwing callback is logged and the file is
+ * counted by its own outcome (an imported page stays imported, a refused or thrown import is a failure ledger row);
+ * the other files import. Runs on PGLite and, with DATABASE_URL, on Postgres.
+ */
+import { afterAll, beforeAll, expect, spyOn, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runImport } from '../src/commands/import.ts';
+import * as importFileModule from '../src/core/import-file.ts';
+import { PAGE_MAX_BYTES } from '../src/core/page-size-policy.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+beforeAll(async () => {
+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }
+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) if (engine.kind === 'pglite') await engine.disconnect();
+ await closePostgres?.();
+});
+
+for (const backend of backends) test(`[${backend}] a throwing onFileResult counts that file by its own outcome; the import resolves and the other files import`, async () => {
+ const engine = engines[backends.indexOf(backend)]!;
+ const repo = mkdtempSync(join(tmpdir(), 'gbrain-a66-'));
+ execFileSync('git', ['-C', repo, 'init', '-q']);
+ writeFileSync(join(repo, 'alpha.md'), '---\ntype: note\n---\n# Alpha\n\nbody\n');
+ writeFileSync(join(repo, 'boom.md'), '---\ntype: note\n---\n# Boom\n\nbody\n');
+ writeFileSync(join(repo, 'huge.md'), '---\ntype: note\n---\n' + 'x'.repeat(PAGE_MAX_BYTES + 1));
+ writeFileSync(join(repo, 'zeta.md'), '---\ntype: note\n---\n# Zeta\n\nbody\n');
+ execFileSync('git', ['-C', repo, 'add', '-A']);
+ execFileSync('git', ['-C', repo, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'seed']);
+ const real = importFileModule.importFile;
+ const thrower = spyOn(importFileModule, 'importFile').mockImplementation((async (...args: Parameters<typeof real>) => {
+ if (String(args[2]).endsWith('boom.md')) throw new Error('simulated import failure');
+ return await real(...args);
+ }) as typeof real);
+ const logged: string[] = [];
+ const err = spyOn(console, 'error').mockImplementation((...parts: unknown[]) => { logged.push(parts.map(String).join(' ')); });
+ const seen: string[] = [];
+ try {
+ const result = await withEnv({ GBRAIN_HOME: mkdtempSync(join(tmpdir(), 'gbrain-a66-home-')) }, () => runImport(engine, [repo, '--no-embed', '--json'], {
+ managedBookmark: true,
+ onFileResult: async path => { seen.push(path); throw new Error('simulated hold bookkeeping failure'); },
+ }));
+ expect(seen.sort()).toEqual(['alpha.md', 'boom.md', 'huge.md', 'zeta.md']);
+ expect(result.imported).toBe(2);
+ expect(result.failures.map(f => f.path).sort()).toEqual(['boom.md', 'huge.md']);
+ expect(logged.some(line => line.includes('could not record the outcome of boom.md'))).toBe(true);
+ expect((await engine.getPage('zeta'))?.title).toBe('Zeta');
+ } finally {
+ thrower.mockRestore();
+ err.mockRestore();
+ }
+}, 120_000);
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index e3a97e5ef8..5035183285 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -79,6 +79,7 @@ test/grandfather-managed.test.ts
test/harness-skills-epoch.test.ts
test/held-read-signals.test.ts
test/hold-action-chain-6712.test.ts
+test/import-file-result-callback-gbra130.test.ts
test/import-frontmatter-key-order-5158.test.ts
test/import-inline-chunk-keep.test.ts
test/import-revision-concurrency.test.ts