Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor: move the A-66 and A-59 wrappers out of runImport and runPersistenceAdministration (check:function-size)

garrytan20339d85934c
diff --git a/src/commands/import.ts b/src/commands/import.ts
index 91c9a2ad0c..dd69d8b0dd 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -247,6 +247,17 @@ async function keylessImportRefusal(engine: BrainEngine, args: string[], e: unkn
});
}
+type ImportFileResultCallback = (path: string, filePath: string, result: Pick<ImportResult, 'status' | 'error' | 'refusal' | 'frontmatter_recovery' | 'fences_normalized' | 'fence_issues'>) => Promise<'held' | undefined>;
+
+/** GBRA-130 A-66: a throwing caller callback is that file's outcome, never a rejection of the whole import. */
+async function reportFileResult(onFileResult: ImportFileResultCallback | undefined, ...args: Parameters<ImportFileResultCallback>): Promise<'held' | undefined> {
+ try { return await 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;
+ }
+}
+
export async function runImport(
engine: BrainEngine,
args: string[],
@@ -259,7 +270,7 @@ export async function runImport(
/** #5988: paths the caller already held this run; they are skipped without importing (not failures). */
heldPaths?: ReadonlySet<string>;
/** #5988: each file's outcome (a throw arrives as `{ status: 'error', error }`); `'held'` = the caller held it, not a failure. */
- onFileResult?: (path: string, filePath: string, result: Pick<ImportResult, 'status' | 'error' | 'refusal' | 'frontmatter_recovery' | 'fences_normalized' | 'fence_issues'>) => Promise<'held' | undefined>;
+ onFileResult?: ImportFileResultCallback;
/**
* #753/#774: glob patterns to exclude from the import (same semantics as
* `isSyncable`'s `exclude` — matched against the dir-relative path).
@@ -705,15 +716,6 @@ 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);
@@ -745,7 +747,7 @@ export async function runImport(
if (!settled && _fileMs > 5000) {
console.error(`[gbrain phase] import.process_file slow ${_fileMs}ms ${relativePath}`);
}
- if (await reportFileResult(importRelPath, filePath, result) === 'held') {
+ if (await reportFileResult(opts.onFileResult, importRelPath, filePath, result) === 'held') {
skipped++;
completed.add(relativePath);
} else if (result.status === 'imported') {
@@ -790,7 +792,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 reportFileResult(importRelPath, filePath, { status: 'error', error: e instanceof Error ? e.message : String(e) }) === 'held') { skipped++; completed.add(relativePath); } else {
+ else if (await reportFileResult(opts.onFileResult, 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/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index 14464b2b9a..c1e9dd79b5 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -125,6 +125,13 @@ function writerFailuresQuery(sourceId: string, params: Record<string, unknown>):
const transferStatusFix = (sourceId: string) =>
readFix(`Shows source ${sourceId}'s owner binding and prepared transfer, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', sourceId, '--json'] });
+/** GBRA-130 A-59: writer status's movement, or a `not_read` with its code and a read-only fix; a failed read never reads as no movement. */
+async function writerStatusMovement(engine: BrainEngine, sourceId: string | undefined) {
+ return (await import('./sync-movement.ts')).readSourceMovement(engine, sourceId === undefined ? {} : { sourceIds: [sourceId] })
+ .catch((error: unknown) => ({ status: 'not_read' as const, code: String((error as { code?: unknown } | null)?.code ?? 'storage_error'),
+ fix: readFix('Reads source movement on its own, read-only.', { argv: ['gbrain', 'sources', 'writer', 'movement', ...(sourceId === undefined ? [] : [sourceId]), '--json'] }) }));
+}
+
export async function runPersistenceAdministration(engine: BrainEngine, operation: PersistenceAdminOperation,
params: Record<string, unknown>, config?: GBrainConfig, embeddingRetryPolicy: 'owner' | 'mounted_database' = 'owner'): Promise<Record<string, unknown>> {
if (operation === 'writer_reconcile_preview') return (await import('./reconcile.ts')).runReconcilePreview(engine, params);
@@ -282,10 +289,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
host: { host_id: existingLocalHostId(), ...await (await import('./consumer-diagnostics.ts')).hostConsumersReport(engine, existingLocalHostId()) },
worktree_refreshes: await (await import('./worktree-refresh.ts')).activeWorktreeRefreshes(engine, params.source_id as string | undefined),
// #6317 (B4): per managed source, whether sync data moves (shares the reader of sources status, doctor and writer movement).
- // GBRA-130 A-59: a failed read says so (not_read with its code), never an empty list that reads as no movement.
- movement: await (await import('./sync-movement.ts')).readSourceMovement(engine, params.source_id === undefined ? {} : { sourceIds: [source(params.source_id)] })
- .catch((error: unknown) => ({ status: 'not_read' as const, code: String((error as { code?: unknown } | null)?.code ?? 'storage_error'),
- fix: readFix('Reads source movement on its own, read-only.', { argv: ['gbrain', 'sources', 'writer', 'movement', ...(params.source_id === undefined ? [] : [String(params.source_id)]), '--json'] }) })) };
+ movement: await writerStatusMovement(engine, params.source_id === undefined ? undefined : source(params.source_id)) };
}
if (operation === 'writer_claim') {
keys(params, ['source_id', 'path', 'dry_run', 'admin_intent', 'expected_state']);