Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(maintain): one source whose cycle throws is blocked, later sources still cycle (GBRA-130 A-41)

garrytanfcc902a7e325
diff --git a/src/commands/maintain.ts b/src/commands/maintain.ts
index 96b8b84fb5..78b0f6243a 100644
--- a/src/commands/maintain.ts
+++ b/src/commands/maintain.ts
@@ -16,6 +16,8 @@ import type { BrainHealth } from '../core/types.ts';
import { buildChecks, computeDoctorReport, type DoctorReport, type Check } from './doctor.ts';
import { extractStaleFromDB } from './extract.ts';
import { runCycle, type CycleReport } from '../core/cycle.ts';
+import { ItemRun } from '../core/item-failure.ts';
+import { setCliExitVerdict } from '../core/cli-force-exit.ts';
type ActionStatus = 'ok' | 'would_apply' | 'applied' | 'blocked' | 'skipped';
@@ -136,17 +138,32 @@ async function runCycleFreshnessMaintenance(
const sources = await engine.listAllSources();
const actions: MaintenanceAction[] = [];
+ // One source's cycle throwing blocks that source only; a run-scoped error (abort, lost lock or connection) still stops maintain.
+ const run = new ItemRun('maintain.cycle_sources');
for (const sourceId of sourceIds) {
const source = sources.find((s) => s.id === sourceId);
const localPath = source?.local_path ?? null;
const brainDir = localPath && existsSync(localPath) ? localPath : null;
- const report: CycleReport = await runCycle(engine, {
- brainDir,
- dryRun: false,
- pull: false,
- sourceId,
- });
+ let report: CycleReport;
+ try {
+ report = await runCycle(engine, {
+ brainDir,
+ dryRun: false,
+ pull: false,
+ sourceId,
+ });
+ run.succeed();
+ } catch (error) {
+ const failure = run.fail(sourceId, error);
+ actions.push({
+ name: 'cycle_freshness',
+ status: 'blocked',
+ message: `Source-scoped dream cycle for ${sourceId} stopped with ${failure.code}: ${failure.message}`,
+ details: { source_id: sourceId, brain_dir: brainDir, code: failure.code, error: failure.message, fix: `gbrain dream --source ${sourceId}` },
+ });
+ continue;
+ }
actions.push({
name: 'cycle_freshness',
status: report.status === 'failed' ? 'blocked' : 'applied',
@@ -197,6 +214,7 @@ Not auto-applied:
actions,
after: { health: afterHealth, doctor: afterDoctor },
};
+ if (actions.some((action) => action.status === 'blocked')) setCliExitVerdict(1);
if (opts.json) {
console.log(JSON.stringify(report, null, 2));
diff --git a/src/core/item-failure.ts b/src/core/item-failure.ts
index d6c6afddac..639ecfed21 100644
--- a/src/core/item-failure.ts
+++ b/src/core/item-failure.ts
@@ -27,6 +27,7 @@ import { acceptedPendingReceipt } from './persistence/accepted-pending.ts';
/** Every per-item loop that isolates its items, with the inventory row it fixes (reports/GBRA-130-inventory.md). */
export const ISOLATE_SITES = {
+ 'maintain.cycle_sources': 'A-41',
} as const satisfies Record<string, string>;
export type IsolateSite = keyof typeof ISOLATE_SITES;
diff --git a/test/pathological/a41-maintain-sources.test.ts b/test/pathological/a41-maintain-sources.test.ts
new file mode 100644
index 0000000000..7e4295213e
--- /dev/null
+++ b/test/pathological/a41-maintain-sources.test.ts
@@ -0,0 +1,115 @@
+/**
+ * GBRA-130 A-41 (hardening): `gbrain maintain --safe` runs one dream cycle per
+ * stale source. A cycle that throws for one source used to end maintain and
+ * skip every later source; now that source is reported blocked with its code
+ * and the rest still cycle, while a run-scoped error still stops maintain.
+ *
+ * Authoring gate: (1) protects per-source isolation in runMaintain and its
+ * non-zero exit verdict; (2) fails when the per-source loop loses its catch or
+ * stops classifying run-scoped errors; (3) test/maintain.test.ts covers args
+ * and JSON output only; (4) no production seam: runCycle is spied on its module.
+ */
+import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import * as cycle from '../../src/core/cycle.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { runMaintain, type MaintainReport, type MaintenanceAction } from '../../src/commands/maintain.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../../src/core/cli-force-exit.ts';
+import { OperationError } from '../../src/core/ops/contract.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';
+
+const STALE = new Date(Date.now() - 48 * 3_600_000).toISOString();
+const SOURCES = ['src-a', 'src-b'];
+
+async function withStaleSources(databaseUrl: string | undefined, run: (engine: BrainEngine) => Promise<void>): Promise<void> {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-a41-'));
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ for (const id of SOURCES) {
+ const root = join(dir, id); mkdirSync(root);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::jsonb)', [id, root, JSON.stringify({ last_full_cycle_at: STALE })]);
+ await engine.putPage(`notes/${id}-note`, { type: 'note', title: `Note ${id}`, compiled_truth: `A note in ${id}.` }, { sourceId: id });
+ }
+ await run(engine);
+ } finally { await close(); }
+ });
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+}
+
+const cycleActions = (report: MaintainReport) => report.actions.filter(a => a.name === 'cycle_freshness');
+const bySource = (report: MaintainReport, id: string) => cycleActions(report).find(a => a.details?.source_id === id) as MaintenanceAction | undefined;
+const maintain = async (engine: BrainEngine) => {
+ const log = spyOn(console, 'log').mockImplementation(() => {});
+ try { return await runMaintain(engine, ['--safe', '--json']) as MaintainReport; } finally { log.mockRestore(); }
+};
+
+describe('A-41 maintain isolates one source whose cycle throws', () => {
+ beforeEach(() => { _resetCliExitVerdictForTests(); });
+ afterEach(() => { _resetCliExitVerdictForTests(); });
+
+ for (const { backend, databaseUrl } of pathologicalArms()) {
+ test(`[${backend}] a source whose cycle throws is blocked with its code and the next source still cycles`, async () => {
+ await withStaleSources(databaseUrl, async engine => {
+ const real = cycle.runCycle;
+ const cycled: string[] = [];
+ const spy = spyOn(cycle, 'runCycle').mockImplementation(async (e, opts) => {
+ if (opts.sourceId === 'src-a') throw new TypeError('listSourceChangedPages exploded on src-a');
+ cycled.push(opts.sourceId!);
+ return real(e, { ...opts, phases: ['orphans'] });
+ });
+ try {
+ const before = await snapshotItems(engine, 'src-a');
+ const report = await expectUnitNotAborted(() => maintain(engine));
+ expect(cycled).toEqual(['src-b']);
+ const blocked = bySource(report, 'src-a');
+ expect(blocked?.status).toBe('blocked');
+ expectItemFailure({ key: blocked?.details?.source_id as string, code: blocked?.details?.code as string, fix: blocked?.details?.fix },
+ { key: 'src-a', code: 'internal', fix: /^gbrain dream --source src-a$/ });
+ expect(bySource(report, 'src-b')?.status).toBe('applied');
+ expectOthersUnchanged(before, await snapshotItems(engine, 'src-a'));
+ const [b] = await engine.executeRaw<{ at: string | null }>(`SELECT config->>'last_full_cycle_at' AS at FROM sources WHERE id='src-b'`);
+ expect({ progressed: b!.at !== STALE }).toEqual({ progressed: true });
+ expect(currentExitCode()).toBe(1);
+ } finally { spy.mockRestore(); }
+ });
+ }, 120_000);
+
+ for (const { name, error } of runScopedErrors()) {
+ test(`[${backend}] a run-scoped error in one source's cycle still stops maintain (${name})`, async () => {
+ await withStaleSources(databaseUrl, async engine => {
+ const injected = error();
+ const cycled: string[] = [];
+ const spy = spyOn(cycle, 'runCycle').mockImplementation(async (_e, opts) => {
+ cycled.push(opts.sourceId!);
+ throw injected;
+ });
+ try {
+ await expect(maintain(engine)).rejects.toBe(injected);
+ expect(cycled).toEqual(['src-a']);
+ } finally { spy.mockRestore(); }
+ });
+ }, 120_000);
+ }
+
+ test(`[${backend}] most sources failing trips the breaker instead of blocking every source`, async () => {
+ await withStaleSources(databaseUrl, async engine => {
+ for (const id of ['src-c', 'src-d', 'src-e']) {
+ const root = join(String((await engine.executeRaw<{ p: string }>(`SELECT local_path AS p FROM sources WHERE id='src-a'`))[0]!.p), '..', id);
+ mkdirSync(root);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::jsonb)', [id, root, JSON.stringify({ last_full_cycle_at: STALE })]);
+ await engine.putPage(`notes/${id}-note`, { type: 'note', title: `Note ${id}`, compiled_truth: `A note in ${id}.` }, { sourceId: id });
+ }
+ const spy = spyOn(cycle, 'runCycle').mockImplementation(async () => { throw new OperationError('invalid_params', 'bad cycle input'); });
+ try {
+ await expect(maintain(engine)).rejects.toMatchObject({ code: 'item_failures_systemic' });
+ } finally { spy.mockRestore(); }
+ });
+ }, 120_000);
+ }
+});
diff --git a/test/pathological/catalogue.ts b/test/pathological/catalogue.ts
index 038e54eda2..5366abc0f2 100644
--- a/test/pathological/catalogue.ts
+++ b/test/pathological/catalogue.ts
@@ -18,4 +18,7 @@ export interface SiteCases {
}
export const CATALOGUE: Record<IsolateSite, SiteCases> = {
+ 'maintain.cycle_sources': { file: 'test/pathological/a41-maintain-sources.test.ts',
+ item: 'a source whose cycle throws is blocked with its code and the next source still cycles',
+ run: "a run-scoped error in one source's cycle still stops maintain" },
};
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 12e8291655..1e811693b6 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -218,6 +218,7 @@ test/page-prepare-shared-origin-6517.test.ts
test/page-purge-batch-sweep-6884.test.ts
test/page-purge-journal-timeout-6511.test.ts
test/page-state-engine.test.ts
+test/pathological/a41-maintain-sources.test.ts
test/persistence-background-pause.test.ts
test/persistence-bounded-read-session.test.ts
test/persistence-capacity-forecast.test.ts