Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
16.0 KB
Raw Blame
/**
 * #4730/#4731 — `gbrain dream --drain` surfaces the bounded per-item failure
 * records: the `--json` payload carries `failures` + `omitted_failure_count`
 * verbatim, and the human stderr summary names the record cap whenever
 * failures were omitted beyond it ("N beyond the record cap") — so a capped
 * list is visible, never silent.
 *
 * The drain loop itself (capping, sanitizing, reconciling failure_count) is
 * pinned in test/extract-atoms-drain*.test.ts. This file pins dream.ts's
 * rendering of the drain RESULT and its argv/exit-code wiring (#1678), so the shared drain helper is replaced by a
 * stub that returns a hand-built result. Serial: a top-level mock.module.
 */

import { afterAll, beforeAll, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
import type { ExtractAtomsDrainResult } from '../src/core/cycle/extract-atoms-drain.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { LockUnavailableError } from '../src/core/db-lock.ts';

let nextResult: ExtractAtomsDrainResult | Error;
let drainCalls: Array<{ sourceId: string | undefined; windowSeconds: number }> = [];

mock.module('../src/core/cycle/extract-atoms-drain.ts', () => ({
  MAX_DRAIN_FAILURE_RECORDS: 25,
  MAX_DRAIN_FAILURE_SOURCE_CHARS: 256,
  MAX_DRAIN_FAILURE_REASON_CHARS: 200,
  runExtractAtomsDrainForSource: async (_engine: unknown, opts: { sourceId: string | undefined; windowSeconds: number }) => {
    drainCalls.push({ sourceId: opts.sourceId, windowSeconds: opts.windowSeconds });
    if (nextResult instanceof Error) throw nextResult;
    return nextResult;
  },
}));

let runDream: typeof import('../src/commands/dream.ts').runDream;
let engine: PGLiteEngine;

beforeAll(async () => {
  engine = new PGLiteEngine();
  await engine.connect({});
  await engine.initSchema();
  ({ runDream } = await import('../src/commands/dream.ts'));
}, 120_000);

afterAll(async () => {
  await engine.disconnect();
});

beforeEach(() => {
  drainCalls = [];
});

function baseResult(overrides: Partial<ExtractAtomsDrainResult>): ExtractAtomsDrainResult {
  return {
    phase: 'extract_atoms',
    status: 'ok',
    extracted: 1,
    skipped: 0,
    remaining: 0, // fully drained → dream exits 0 (no process.exit call)
    batches: 1,
    stopped: 'drained',
    failure_count: 0,
    failures: [],
    omitted_failure_count: 0,
    last_error: null,
    ...overrides,
  };
}

/** Drive `dream --drain …` capturing stderr (progress/diagnostics) and stdout (data). */
async function runDrainCaptured(args: string[]): Promise<{ stderr: string; stdout: string[]; exitCode: number | undefined }> {
  const stderr: string[] = [];
  const stdout: string[] = [];
  let exitCode: number | undefined;
  const origWrite = process.stderr.write.bind(process.stderr);
  (process.stderr as unknown as { write: typeof origWrite }).write = ((chunk: unknown): boolean => {
    stderr.push(typeof chunk === 'string' ? chunk : String(chunk));
    return true;
  }) as typeof origWrite;
  const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { stderr.push(a.map(String).join(' ')); });
  const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { stdout.push(a.map(String).join(' ')); });
  const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => {
    exitCode = code;
    throw new Error('__exit__');
  }) as never);
  try {
    await runDream(engine, ['--drain', ...args]);
  } catch (e) {
    if ((e as Error).message !== '__exit__') throw e;
  } finally {
    exitSpy.mockRestore();
    logSpy.mockRestore();
    errSpy.mockRestore();
    (process.stderr as unknown as { write: typeof origWrite }).write = origWrite;
  }
  return { stderr: stderr.join(''), stdout, exitCode };
}

describe('dream --drain failure summary (#4730)', () => {
  test('stderr names the record cap when omitted_failure_count > 0', async () => {
    nextResult = baseResult({
      failure_count: 3,
      failures: [
        { batch: 1, source: 'writings/a', reason: 'provider timeout' },
        { batch: 1, source: 'writings/b', reason: 'bad json' },
      ],
      omitted_failure_count: 1,
      last_error: 'writings/b: bad json',
    });

    const r = await runDrainCaptured([]);
    expect(drainCalls).toHaveLength(1);
    expect(r.exitCode).toBeUndefined();
    expect(r.stderr).toContain('[drain] 3 item failure(s) (2 detailed, 1 beyond the record cap); last error: writings/b: bad json');
    expect(r.stderr).toContain('beyond the record cap');
    // Data stream stays clean of the diagnostic line.
    expect(r.stdout.join('\n')).not.toContain('beyond the record cap');
    expect(r.stdout.join('\n')).toContain('[drain] extracted 1 atom(s) across 1 batch(es); 0 remaining (stopped: drained)');
  });

  test('stderr omits the cap clause when every failure was recorded (omitted_failure_count = 0)', async () => {
    nextResult = baseResult({
      failure_count: 2,
      failures: [
        { batch: 1, source: 'writings/a', reason: 'provider timeout' },
        { batch: 2, source: 'writings/b', reason: 'bad json' },
      ],
      omitted_failure_count: 0,
      last_error: 'writings/b: bad json',
    });

    const r = await runDrainCaptured([]);
    expect(r.stderr).toContain('[drain] 2 item failure(s); last error: writings/b: bad json');
    expect(r.stderr).not.toContain('beyond the record cap');
    expect(r.stderr).not.toContain('detailed');
  });

  test('a clean run prints no failure line at all', async () => {
    nextResult = baseResult({});
    const r = await runDrainCaptured([]);
    expect(r.stderr).not.toContain('item failure');
    expect(r.stderr).not.toContain('beyond the record cap');
  });

  test('--json carries failures[] and omitted_failure_count verbatim; the cap clause still goes to stderr', async () => {
    nextResult = baseResult({
      failure_count: 27,
      failures: Array.from({ length: 25 }, (_, i) => ({ batch: 1, source: `writings/p${i}`, reason: 'provider timeout' })),
      omitted_failure_count: 2,
      last_error: 'writings/p24: provider timeout',
    });

    const r = await runDrainCaptured(['--json']);
    const payload = JSON.parse(r.stdout.find(l => l.trim().startsWith('{'))!);
    expect(payload.failure_count).toBe(27);
    expect(payload.failures).toHaveLength(25);
    expect(payload.failures[0]).toEqual({ batch: 1, source: 'writings/p0', reason: 'provider timeout' });
    expect(payload.omitted_failure_count).toBe(2);
    expect(payload.failure_count).toBe(payload.failures.length + payload.omitted_failure_count);
    // Stderr discipline: the summary (with the cap clause) never lands in the JSON stream.
    expect(r.stderr).toContain('(25 detailed, 2 beyond the record cap)');
    expect(r.stdout.join('\n')).not.toContain('beyond the record cap');
  });
});

describe('dream --drain wiring and exit codes (#1678)', () => {
  test('exits 11 (resumable stop; A3 reserves 3 for confirmation_required) while backlog remains or the final count is unknown', async () => {
    for (const remaining of [4, null]) {
      nextResult = baseResult({ remaining });
      expect((await runDrainCaptured([])).exitCode, String(remaining)).toBe(11);
    }
  });

  test('a held cycle lock reports cycle_already_running and exits 11', async () => {
    nextResult = new LockUnavailableError('gbrain-cycle');
    const r = await runDrainCaptured(['--json']);
    expect(JSON.parse(r.stdout.join('\n'))).toEqual({ phase: 'extract_atoms', status: 'skipped', reason: 'cycle_already_running', resume_command: 'gbrain dream --drain --window 300' });
    expect(r.exitCode).toBe(11);
  });

  test('--window sets the drain budget (default 300 s) and --source reaches the shared helper', async () => {
    await engine.executeRaw("INSERT INTO sources(id,name) VALUES ('drain-fixture','drain-fixture') ON CONFLICT DO NOTHING");
    nextResult = baseResult({});
    await runDrainCaptured([]);
    await runDrainCaptured(['--window', '42', '--source', 'drain-fixture']);
    expect(drainCalls.map(c => c.windowSeconds)).toEqual([300, 42]);
    expect(drainCalls[1].sourceId).toBe('drain-fixture');
  });

  test('rejects a bad --window and a non-drainable --phase with exit 2 before draining', async () => {
    const window = await runDrainCaptured(['--window', '0']);
    expect(window.exitCode).toBe(2);
    expect(window.stderr).toContain('--window must be a positive integer (seconds); got "0"');
    const phase = await runDrainCaptured(['--phase', 'lint']);
    expect(phase.exitCode).toBe(2);
    expect(phase.stderr).toContain('--drain currently supports only --phase extract_atoms (got "lint")');
    expect(drainCalls).toEqual([]);
  });
});

// #5809 / #5832 stop contract: every stop that is not `drained` exits 11 (was 3; A3),
// prints the drain JSON, and names the exact rerun command on stderr.
describe('dream --drain stop contract (#5809)', () => {
  test.each([
    { stopped: 'window' as const, remaining: 12 },
    { stopped: 'deadline' as const, remaining: 30 },
    { stopped: 'lock_lost' as const, remaining: 8 },
  ])('a $stopped stop prints the JSON, exits 11 and names the rerun command', async ({ stopped, remaining }) => {
    nextResult = baseResult({ stopped, remaining, extracted: 4, batches: 2 });
    const r = await runDrainCaptured(['--json', '--window', '90']);
    expect(JSON.parse(r.stdout.join('\n'))).toMatchObject({ stopped, remaining, extracted: 4, batches: 2, resume_command: 'gbrain dream --drain --window 90' });
    expect(r.exitCode).toBe(11);
    expect(r.stderr).toContain(`[drain] stopped: ${stopped}; ${remaining} page(s) remaining. Rerun: gbrain dream --drain --window 90`);
  });

  test('a provider_failure stop with an empty final recount still exits 11 (only drained exits 0)', async () => {
    nextResult = baseResult({ status: 'provider_failure', stopped: 'provider_failure', remaining: 0 });
    const r = await runDrainCaptured([]);
    expect(r.exitCode).toBe(11);
    expect(r.stderr).toContain('Rerun: gbrain dream --drain --window 300');
  });

  test('a drained run prints no rerun hint and exits 0', async () => {
    nextResult = baseResult({});
    const r = await runDrainCaptured([]);
    expect(r.exitCode).toBeUndefined();
    expect(r.stderr).not.toContain('Rerun:');
  });

  test('--help says the window is a hard deadline', async () => {
    const out: string[] = [];
    const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.map(String).join(' ')); });
    try {
      await runDream(engine, ['--help']);
    } finally {
      logSpy.mockRestore();
    }
    expect(out.join('\n')).toContain('Drain window, a hard deadline');
  });
});


describe('dream --drain budget stop (#6425)', () => {
  test('names the spend, the cap and the raise-cap command; --json carries a structured notice', async () => {
    nextResult = baseResult({ stopped: 'budget', remaining: 2, batches: 2, spent_usd: 0.0151, budget_usd: 0.03 });
    const human = await runDrainCaptured([]);
    expect(human.exitCode).toBe(11);
    expect(human.stderr).toContain('[drain] stopped: budget; spent $0.0151 of the $0.03 per-run cap (cycle.extract_atoms.budget_usd); 2 page(s) remaining. '
      + 'Rerun: gbrain dream --drain --window 300, or raise the cap: gbrain config set cycle.extract_atoms.budget_usd <usd>');
    const json = await runDrainCaptured(['--json']);
    const payload = JSON.parse(json.stdout.find(l => l.trim().startsWith('{'))!);
    expect(payload).toMatchObject({ stopped: 'budget', spent_usd: 0.0151, budget_usd: 0.03, resume_command: 'gbrain dream --drain --window 300' });
    expect(payload.notices).toEqual([expect.objectContaining({ code: 'atom_drain_budget', kind: 'info', contract_version: 1,
      fix: expect.objectContaining({ argv: ['gbrain', 'config', 'set', 'cycle.extract_atoms.budget_usd', '<USD>'], consent: ['paid'], next: 'ask_user',
        verify: { argv: ['gbrain', 'config', 'get', 'cycle.extract_atoms.budget_usd'] } }) })]);
    expect(payload.notices[0].why).toContain('$0.0151 of $0.03');
  });
});


// #6817: one mapping for every drain stop across exit code, JSON status/retryable/code and the human last line.
describe('dream --drain exit mapping (#6817)', () => {
  test('a permanent provider failure after a committed batch exits 1 with no rerun hint and names the fix', async () => {
    nextResult = baseResult({ status: 'provider_failure', stopped: 'provider_failure', provider_failure_class: 'auth', remaining: 9, extracted: 3, batches: 2,
      failure_count: 4, last_error: 'notes/a: Failed to authenticate: OAuth session expired' });
    const json = await runDrainCaptured(['--json']);
    expect(json.exitCode).toBe(1);
    const payload = JSON.parse(json.stdout.join('\n'));
    expect(payload).toMatchObject({ status: 'provider_failure', retryable: false, code: 'atom_drain_provider_failure', reason: 'auth', extracted: 3, remaining: 9 });
    expect(payload.resume_command).toBeUndefined();
    expect(payload.fix).toMatchObject({ argv: ['gbrain', 'models', '--json'] });
    const human = await runDrainCaptured([]);
    expect(human.exitCode).toBe(1);
    expect(human.stderr).toContain('[drain] stopped: provider_failure (auth); 9 page(s) remaining. Fix: ');
    expect(human.stderr).toContain('Read-only check: gbrain models --json');
    expect(human.stderr).not.toContain('Rerun:');
  });

  test('a rate-limited or transient provider failure stays retryable on exit 11', async () => {
    for (const cls of ['rate_limit', 'transient'] as const) {
      nextResult = baseResult({ status: 'provider_failure', stopped: 'provider_failure', provider_failure_class: cls, remaining: 5 });
      const json = await runDrainCaptured(['--json']);
      expect(json.exitCode, cls).toBe(11);
      expect(JSON.parse(json.stdout.join('\n'))).toMatchObject({ status: 'provider_failure', retryable: true, code: 'atom_drain_provider_failure', reason: cls,
        resume_command: 'gbrain dream --drain --window 300' });
    }
  });

  test('no_progress over a counted backlog exits 1, reports a non-ok status and says not to rerun unchanged', async () => {
    nextResult = baseResult({ stopped: 'no_progress', remaining: 7, extracted: 2, batches: 2 });
    const json = await runDrainCaptured(['--json']);
    expect(json.exitCode).toBe(1);
    const payload = JSON.parse(json.stdout.join('\n'));
    expect(payload).toMatchObject({ status: 'incomplete', retryable: false, code: 'atom_drain_no_progress', stopped: 'no_progress', extracted: 2 });
    expect(payload.resume_command).toBeUndefined();
    const human = await runDrainCaptured([]);
    expect(human.exitCode).toBe(1);
    expect(human.stderr).toContain('[drain] stopped: no_progress; 7 page(s) remaining. Fix: Do not rerun this drain unchanged. Run gbrain doctor --json on the brain host');
    expect(human.stderr).toContain('earlier successful batches remain committed');
  });

  test('a no_progress stop whose count failed stays retryable (count_unavailable)', async () => {
    nextResult = baseResult({ stopped: 'no_progress', remaining: null });
    const json = await runDrainCaptured(['--json']);
    expect(json.exitCode).toBe(11);
    expect(JSON.parse(json.stdout.join('\n'))).toMatchObject({ status: 'incomplete', retryable: true, code: 'atom_drain_incomplete', reason: 'count_unavailable' });
  });

  test('a resumable stop never reports status ok in JSON', async () => {
    nextResult = baseResult({ stopped: 'window', remaining: 12 });
    const json = await runDrainCaptured(['--json']);
    expect(json.exitCode).toBe(11);
    expect(JSON.parse(json.stdout.join('\n'))).toMatchObject({ status: 'incomplete', retryable: true, code: 'atom_drain_incomplete', reason: 'window' });
  });

  test('--help documents exits 0, 11 and 1, never 3', async () => {
    const out: string[] = [];
    const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.map(String).join(' ')); });
    try {
      await runDream(engine, ['--help']);
    } finally {
      logSpy.mockRestore();
    }
    const help = out.join('\n');
    expect(help).toContain('Exits 0 when the backlog drained;');
    expect(help).toContain('11 when running again can continue');
    expect(help).toContain('1 when it cannot until something');
    expect(help).not.toContain('exits 3');
  });
});