Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
29.6 KB
Raw Blame
/**
 * gbrain waiting / gbrain loops CLI (src/commands/loops.ts) on a real PGLite
 * engine with a seeded google source + loops.
 *
 * SCOPING: runWaiting/runLoops pass `sourceId: '__all__'` to handleToolCall,
 * so trusted-local CLI reads span the whole brain — loops living in a real
 * google source are visible without any --source flag (the '--source <id>'
 * flag narrows explicitly). Pinned below as the cross-source-visibility test.
 * Most tests here still seed loops into 'default' for convenience; the brain
 * span includes it.
 *
 * Output capture swaps process.stdout.write / process.stderr.write and stubs
 * process.exit (restored in finally — same harness as
 * test/sync-working-tree-cli.test.ts). Exit verdicts are read through
 * currentExitCode() (the gbrain-owned channel) and reset per run.
 *
 * Synthetic data only.
 */

import { describe, expect, test, beforeAll, afterAll, beforeEach } from 'bun:test';

import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { runLoops, runWaiting } from '../src/commands/loops.ts';
import {
  currentExitCode,
  _resetCliExitVerdictForTests,
} from '../src/core/cli-force-exit.ts';
import {
  addSuppression,
  closeOpenLoop,
  listOpenLoops,
  loadSuppressions,
  upsertOpenLoop,
  type OpenLoopUpsert,
} from '../src/core/loops/loops-store.ts';

let engine: PGLiteEngine;

beforeAll(async () => {
  engine = new PGLiteEngine();
  await engine.connect({});
  await engine.initSchema();
});

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

beforeEach(async () => {
  await resetPgliteState(engine);
  // Make 'default' a fresh google source: freshness gating needs at least one
  // google source, and seeding loops into 'default' keeps fixtures short (the
  // CLI's __all__ span includes it).
  await engine.executeRaw(
    `UPDATE sources SET config = '{"kind":"google"}'::jsonb, last_sync_at = now() WHERE id = 'default'`,
  );
  _resetCliExitVerdictForTests();
});

function loop(over: Partial<OpenLoopUpsert> = {}): OpenLoopUpsert {
  return {
    sourceId: 'default',
    dedupKey: `thread:${over.threadId ?? '18c2f4a9b3d21e07'}:${over.loopType ?? 'unanswered_inbound'}`,
    loopType: 'unanswered_inbound',
    counterpartyEmail: '[email protected]',
    summary: 'Reply owed to [email protected]: "Quarterly plan" (2d)',
    evidence: [{ message_id: '18c2f4a9b3d21e07', quote: 'Can you review the plan?' }],
    threadId: '18c2f4a9b3d21e07',
    detector: 'deterministic_thread',
    ...over,
  };
}

async function makeStale(): Promise<void> {
  await engine.executeRaw(
    `UPDATE sources SET last_sync_at = now() - interval '3 days' WHERE id = 'default'`,
  );
}

interface Captured {
  out: string;
  err: string;
  /** gbrain's owned exit verdict after the run (0 when none was set). */
  verdict: number;
  /** Set only when the command hard-called process.exit(code). */
  exitCalled: number | undefined;
}

async function captured(fn: () => Promise<void>): Promise<Captured> {
  const outOrig = process.stdout.write.bind(process.stdout);
  const errOrig = process.stderr.write.bind(process.stderr);
  const cerrOrig = console.error;
  const exitOrig = process.exit;
  const prevExitCode = process.exitCode;
  const outChunks: string[] = [];
  const errChunks: string[] = [];
  let exitCalled: number | undefined;
  _resetCliExitVerdictForTests();
  process.stdout.write = ((chunk: string | Uint8Array): boolean => {
    outChunks.push(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf-8'));
    return true;
  }) as typeof process.stdout.write;
  process.stderr.write = ((chunk: string | Uint8Array): boolean => {
    errChunks.push(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf-8'));
    return true;
  }) as typeof process.stderr.write;
  // Bun's console.error does NOT route through the process.stderr.write
  // swap; the usage / source-resolution refusals in loops.ts use it.
  console.error = (...a: unknown[]) => {
    errChunks.push(a.map(String).join(' ') + '\n');
  };
  process.exit = ((code?: number) => {
    exitCalled = code ?? 0;
    throw new Error('__exit__');
  }) as typeof process.exit;
  try {
    await fn();
  } catch (e) {
    if ((e as Error).message !== '__exit__') throw e;
  } finally {
    process.exit = exitOrig;
    console.error = cerrOrig;
    process.stdout.write = outOrig;
    process.stderr.write = errOrig;
  }
  const verdict = currentExitCode();
  // Never leak a verdict (or its process.exitCode mirror) into other tests.
  _resetCliExitVerdictForTests();
  process.exitCode = prevExitCode ?? 0;
  return { out: outChunks.join(''), err: errChunks.join(''), verdict, exitCalled };
}

// ── gbrain waiting ───────────────────────────────────────────────────────────

describe('runWaiting', () => {
  test('stale google source → refusal on stderr with the exact sync fix, verdict 1', async () => {
    await upsertOpenLoop(engine, loop());
    await makeStale();
    const r = await captured(() => runWaiting(engine, []));
    expect(r.err).toContain('Refusing to answer from stale data');
    expect(r.err).toContain('gbrain sync --source default'); // the exact fix
    expect(r.err).toContain('--stale-ok');
    // The digest is withheld: no loop content leaks past the refusal.
    expect(r.out).toBe('');
    expect(r.err).not.toContain('Can you review the plan?');
    expect(r.verdict).toBe(1);
    expect(r.exitCalled).toBeUndefined(); // verdict channel, not a hard exit
  });

  test('stale + --json → { ok:false, status:"stale", next_action.command } envelope, verdict 1', async () => {
    await upsertOpenLoop(engine, loop());
    await makeStale();
    const r = await captured(() => runWaiting(engine, ['--json']));
    const env = JSON.parse(r.out) as {
      ok: boolean;
      status: string;
      sources: Array<{ id: string; stale: boolean; last_sync_at: string | null }>;
      next_action: { command: string };
    };
    expect(env.ok).toBe(false);
    expect(env.status).toBe('stale');
    expect(env.sources).toHaveLength(1);
    expect(env.sources[0].id).toBe('default');
    expect(env.sources[0].stale).toBe(true);
    expect(env.next_action.command).toBe('gbrain sync --source default');
    expect(r.verdict).toBe(1);
  });

  test('--stale-ok bypasses the refusal and prints the loops (with the staleness banner)', async () => {
    await upsertOpenLoop(engine, loop());
    await makeStale();
    const r = await captured(() => runWaiting(engine, ['--stale-ok']));
    expect(r.out).toContain('waiting on you'); // "1 person is waiting on you"
    expect(r.out).toContain('may be out of date'); // the honesty banner survives
    expect(r.out).toContain('Can you review the plan?');
    expect(r.verdict).toBe(0);
  });

  test('fresh source → the digest prints with quote, close hint, verdict 0', async () => {
    await upsertOpenLoop(engine, loop());
    const r = await captured(() => runWaiting(engine, []));
    expect(r.out).toContain('1 person is waiting on you');
    expect(r.out).toContain('[email protected]');
    expect(r.out).toContain('Can you review the plan?');
    expect(r.out).toContain('gbrain loops done <id>'); // the management hint
    expect(r.verdict).toBe(0);
  });

  test('fresh source, zero loops → "You are clean", no management hint', async () => {
    const r = await captured(() => runWaiting(engine, []));
    expect(r.out).toContain('You are clean');
    expect(r.out).not.toContain('gbrain loops done');
    expect(r.verdict).toBe(0);
  });

  // #5871: no-counterparty loops are listed in their own section, never as a person.
  test('only no-counterparty loops → their section and the management hint, never "You are clean"', async () => {
    await upsertOpenLoop(engine, loop({ dedupKey: 'decision:solo', loopType: 'decision_pending', counterpartyEmail: null, threadId: null,
      summary: 'Decide on the offsite venue', detector: 'llm_extract' }));
    const r = await captured(() => runWaiting(engine, []));
    expect(r.out).toContain('## No counterparty (1 open: decision_pending 1)');
    expect(r.out).not.toContain('You are clean');
    expect(r.out).toContain('gbrain loops done <id>');
    const j = await captured(() => runWaiting(engine, ['--json']));
    expect(JSON.parse(j.out)).toMatchObject({ ok: true, groups: [], no_counterparty: { loop_count: 1, loops_omitted: 0 } });
  });

  test('partially stale google sources warn with source ids without refusing, including JSON', async () => {
    await engine.executeRaw(
      `INSERT INTO sources (id, name, config, last_sync_at)
       VALUES ('g-stale', 'g-stale', '{"kind":"google"}'::jsonb, NULL)`,
    );

    const text = await captured(() => runWaiting(engine, []));
    expect(text.out).toContain('⚠ some google sources have not synced recently');
    expect(text.out).toContain('g-stale');
    expect(text.out).toBe(
      '⚠ some google sources have not synced recently — this may be out of date: g-stale.\n' +
        'No open loops — no unanswered threads older than 24h and no tracked promises. You are clean.\n',
    );
    expect(text.err).toBe('');
    expect(text.verdict).toBe(0);

    const json = await captured(() => runWaiting(engine, ['--json']));
    const envelope = JSON.parse(json.out) as {
      ok: boolean;
      status: string;
      stale: boolean;
      stale_sources?: string[];
      sources: Array<{ id: string; stale: boolean }>;
      text: string;
    };
    expect(envelope.ok).toBe(true);
    expect(envelope.status).toBe('ok');
    expect(envelope.stale).toBe(false);
    expect(envelope.stale_sources).toEqual(['g-stale']);
    expect(envelope.sources).toHaveLength(2);
    expect(envelope.text).toContain('g-stale');
    expect(json.verdict).toBe(0);
  });

  test('fresh --json → { ok:true, status:"ok" } envelope carrying groups + text', async () => {
    await upsertOpenLoop(engine, loop());
    const r = await captured(() => runWaiting(engine, ['--json']));
    const env = JSON.parse(r.out) as {
      ok: boolean;
      status: string;
      count: number;
      groups: Array<{ counterparty: string }>;
      text: string;
    };
    expect(env.ok).toBe(true);
    expect(env.status).toBe('ok');
    expect(env.count).toBe(1);
    expect(env.groups[0].counterparty).toBe('[email protected]');
    expect(env.text).toContain('waiting on you');
    expect(r.verdict).toBe(0);
  });

  test('no google source in the brain → the honest connect hint prints (NOT "You are clean"), verdict 0; --json carries no_google_sources', async () => {
    // Flip 'default' back to a plain (non-google) source: the open-loop
    // engine now has nothing to read, and "You are clean" would be a
    // confident lie on a brain whose email arrives some other way.
    await engine.executeRaw(`UPDATE sources SET config = '{}'::jsonb WHERE id = 'default'`);
    const r = await captured(() => runWaiting(engine, []));
    expect(r.out).toContain('No google source is connected');
    expect(r.out).not.toContain('You are clean');
    expect(r.out).toContain('gbrain google setup'); // the connect fix rides along
    expect(r.verdict).toBe(0); // an unconnected brain is not an error state

    const j = await captured(() => runWaiting(engine, ['--json']));
    const env = JSON.parse(j.out) as {
      ok: boolean;
      status: string;
      count: number;
      no_google_sources: boolean;
      stale: boolean;
    };
    expect(env.ok).toBe(true);
    expect(env.status).toBe('ok');
    expect(env.no_google_sources).toBe(true);
    expect(env.count).toBe(0);
    expect(env.stale).toBe(false); // empty freshness set must not read stale
    expect(j.verdict).toBe(0);
  });

  test('loops in a NON-default google source are visible to the CLI (brain-wide __all__ scope)', async () => {
    // runWaiting passes sourceId '__all__' → trusted-local span of every
    // source — a loop detected by a real google sync (living in that source's
    // id, not 'default') shows up with no --source flag. This is the killer
    // output's correctness bar: "You are clean" while g1 holds a loop would
    // be a silent lie.
    await engine.executeRaw(
      `INSERT INTO sources (id, name, config, last_sync_at)
       VALUES ('g1', 'g1', '{"kind":"google"}'::jsonb, now())
       ON CONFLICT (id) DO NOTHING`,
    );
    await upsertOpenLoop(engine, loop({ sourceId: 'g1' }));
    const r = await captured(() => runWaiting(engine, []));
    expect(r.out).toContain('waiting on you');
    expect(r.out).toContain('[email protected]');
    expect(r.verdict).toBe(0);

    // --source narrows explicitly: scoping to 'default' hides g1's loop.
    const scoped = await captured(() => runWaiting(engine, ['--source', 'default']));
    expect(scoped.out).toContain('You are clean');
  });
});

// ── gbrain loops ─────────────────────────────────────────────────────────────

describe('runLoops', () => {
  test('list prints one line per loop; --json envelope carries ok/status/count', async () => {
    await upsertOpenLoop(engine, loop({ threadId: '18c2f4a9b3d21e01', counterpartyEmail: '[email protected]' }));
    await upsertOpenLoop(engine, loop({ threadId: '18c2f4a9b3d21e02', counterpartyEmail: '[email protected]' }));
    const human = await captured(() => runLoops(engine, ['list']));
    expect(human.out).toContain('#1');
    expect(human.out).toContain('#2');
    expect(human.out).toContain('[unanswered_inbound]');
    expect(human.verdict).toBe(0);

    const json = await captured(() => runLoops(engine, ['list', '--json']));
    const env = JSON.parse(json.out) as { ok: boolean; status: string; count: number; loops: unknown[] };
    expect(env.ok).toBe(true);
    expect(env.status).toBe('ok');
    expect(env.count).toBe(2);
    expect(env.loops).toHaveLength(2);
  });

  test('list with zero matches says so', async () => {
    const r = await captured(() => runLoops(engine, ['list']));
    expect(r.out).toContain('No loops match.');
    expect(r.verdict).toBe(0);
  });

  test('show <id> prints the loop with quote; --json wraps it in ok/status', async () => {
    await upsertOpenLoop(engine, loop());
    const human = await captured(() => runLoops(engine, ['show', '1']));
    expect(human.out).toContain('#1 [unanswered_inbound] open');
    expect(human.out).toContain('Reply owed to [email protected]');
    expect(human.out).toContain('> "Can you review the plan?"');
    expect(human.verdict).toBe(0);

    const json = await captured(() => runLoops(engine, ['show', '1', '--json']));
    const env = JSON.parse(json.out) as { ok: boolean; status: string; loop: { id: number } };
    expect(env.ok).toBe(true);
    expect(env.status).toBe('ok');
    expect(env.loop.id).toBe(1);
  });

  test('show with an unknown id sets verdict 1', async () => {
    const r = await captured(() => runLoops(engine, ['show', '999']));
    expect(r.verdict).toBe(1);
  });

  test('done closes the loop; the --json envelope reports ok/status; re-close fails honestly', async () => {
    await upsertOpenLoop(engine, loop());
    const r = await captured(() => runLoops(engine, ['done', '1']));
    expect(r.out).toContain('Loop 1 done.');
    expect(r.verdict).toBe(0);
    const rows = await engine.executeRaw<{ status: string; closed_by: string }>(
      `SELECT status, closed_by FROM open_loops WHERE id = 1`,
    );
    expect(rows[0].status).toBe('done');
    expect(rows[0].closed_by).toBe('manual');

    // Second close: not_closed envelope + verdict 1.
    const again = await captured(() => runLoops(engine, ['done', '1', '--json']));
    const env = JSON.parse(again.out) as { ok: boolean; status: string; reason?: string };
    expect(env.ok).toBe(false);
    expect(env.status).toBe('not_closed');
    expect(env.reason).toBe('not_found_or_already_closed');
    expect(again.verdict).toBe(1);
  });

  test('drop marks the loop dropped; --json envelope carries ok + the loop status', async () => {
    await upsertOpenLoop(engine, loop());
    const r = await captured(() => runLoops(engine, ['drop', '1', '--json']));
    const env = JSON.parse(r.out) as { ok: boolean; status: string; loop_status: string; id: number };
    expect(env.ok).toBe(true);
    // Envelope status is the outcome; the row's terminal state rides as
    // loop_status (a spread-last op result must not clobber the envelope).
    expect(env.status).toBe('closed');
    expect(env.loop_status).toBe('dropped');
    expect(env.id).toBe(1);
    expect(r.verdict).toBe(0);
    const rows = await engine.executeRaw<{ status: string }>(`SELECT status FROM open_loops WHERE id = 1`);
    expect(rows[0].status).toBe('dropped');
  });

  test('--note records a closed_by note instead of "manual" (#5446)', async () => {
    await upsertOpenLoop(engine, loop());
    const r = await captured(() => runLoops(engine, ['done', '1', '--note', 'handled in person']));
    expect(r.out).toContain('Loop 1 done.');
    const rows = await engine.executeRaw<{ closed_by: string }>(
      `SELECT closed_by FROM open_loops WHERE id = 1`,
    );
    expect(rows[0].closed_by).toBe('handled in person');
  });

  test('done without a numeric id hard-exits with usage code 2', async () => {
    const r = await captured(() => runLoops(engine, ['done']));
    expect(r.exitCalled).toBe(2);
  });

  test('mute sender writes the suppression row (lowercased) and prints the semantics', async () => {
    const r = await captured(() => runLoops(engine, ['mute', 'sender', '[email protected]']));
    expect(r.out).toContain('Muted sender [email protected]');
    // #5012: a mute now closes the sender's open reply-owed loops and prints the count and the undo.
    expect(r.out).toContain('closed 0 open reply-owed loop(s)');
    expect(r.out).toContain('Undo: gbrain loops unmute sender [email protected] --source default');
    expect(r.verdict).toBe(0);
    const set = await loadSuppressions(engine, 'default');
    expect(set.senders.has('[email protected]')).toBe(true);
  });

  test('mute thread --json envelope carries ok/status "muted"', async () => {
    const r = await captured(() => runLoops(engine, ['mute', 'thread', '18C2F4A9B3D21E07', '--json']));
    const env = JSON.parse(r.out) as { ok: boolean; status: string; value: string };
    expect(env.ok).toBe(true);
    expect(env.status).toBe('muted');
    expect(env.value).toBe('18c2f4a9b3d21e07');
    const set = await loadSuppressions(engine, 'default');
    expect(set.threads.has('18c2f4a9b3d21e07')).toBe(true);
  });

  test('mute without kind/value hard-exits with usage code 2', async () => {
    const r = await captured(() => runLoops(engine, ['mute', 'sender']));
    expect(r.exitCalled).toBe(2);
  });

  test('unmute removes the row the mute wrote, matching case-insensitively', async () => {
    await captured(() => runLoops(engine, ['mute', 'sender', '[email protected]']));
    const r = await captured(() => runLoops(engine, ['unmute', 'sender', '[email protected]']));
    expect(r.out).toContain('Unmuted sender [email protected]');
    expect(r.verdict).toBe(0);
    expect((await loadSuppressions(engine, 'default')).senders.has('[email protected]')).toBe(false);
  });

  test('a repeated unmute is a no-op that still exits 0', async () => {
    await captured(() => runLoops(engine, ['mute', 'sender', '[email protected]']));
    const first = await captured(() => runLoops(engine, ['unmute', 'sender', '[email protected]']));
    const second = await captured(() => runLoops(engine, ['unmute', 'sender', '[email protected]']));
    expect(first.out).toContain('Unmuted');
    expect(second.out).toContain('had no suppression');
    // The idempotency contract: a retried unmute must not look like a failure.
    expect(second.verdict).toBe(0);
  });

  test('unmute --json envelope reports ok:true with removed true then false', async () => {
    await captured(() => runLoops(engine, ['mute', 'thread', '18C2F4A9B3D21E07']));
    const hit = await captured(() => runLoops(engine, ['unmute', 'thread', '18C2F4A9B3D21E07', '--json']));
    const a = JSON.parse(hit.out) as { ok: boolean; status: string; removed: boolean; value: string };
    expect(a.ok).toBe(true);
    expect(a.status).toBe('unmuted');
    expect(a.removed).toBe(true);
    expect(a.value).toBe('18c2f4a9b3d21e07');
    const miss = await captured(() => runLoops(engine, ['unmute', 'thread', '18C2F4A9B3D21E07', '--json']));
    const b = JSON.parse(miss.out) as { ok: boolean; status: string; removed: boolean };
    expect(b.ok).toBe(true);
    expect(b.status).toBe('not_muted');
    expect(b.removed).toBe(false);
  });

  test('unmute leaves existing loops exactly as they were', async () => {
    await upsertOpenLoop(engine, loop({ counterpartyEmail: '[email protected]' }));
    await addSuppression(engine, 'default', 'sender', '[email protected]');
    const before = await listOpenLoops(engine, { sourceIds: ['default'], status: 'open' });
    await captured(() => runLoops(engine, ['unmute', 'sender', '[email protected]']));
    const after = await listOpenLoops(engine, { sourceIds: ['default'], status: 'open' });
    expect(after.length).toBe(before.length);
    expect(after[0].id).toBe(before[0].id);
    expect(after[0].status).toBe('open');
  });

  test('unmute without kind/value hard-exits with usage code 2', async () => {
    const r = await captured(() => runLoops(engine, ['unmute', 'sender']));
    expect(r.exitCalled).toBe(2);
  });

  test('unmute with ZERO google sources exits 2 naming the unmute (not the mute) as the thing to scope', async () => {
    // Flip 'default' back to a plain source: no google source anywhere.
    await engine.executeRaw(`UPDATE sources SET config = '{}'::jsonb WHERE id = 'default'`);
    const r = await captured(() => runLoops(engine, ['unmute', 'sender', '[email protected]']));
    expect(r.exitCalled).toBe(2);
    expect(r.err).toContain('No google source found');
    expect(r.err).toContain('scope the unmute');
    expect(r.err).not.toContain('scope the mute');
    expect(r.out).toBe('');
  });

  test('unmute with TWO google sources exits 2 listing both ids', async () => {
    await engine.executeRaw(
      `INSERT INTO sources (id, name, config, last_sync_at)
       VALUES ('g1', 'g1', '{"kind":"google"}'::jsonb, now())
       ON CONFLICT (id) DO NOTHING`,
    );
    const r = await captured(() => runLoops(engine, ['unmute', 'sender', '[email protected]']));
    expect(r.exitCalled).toBe(2);
    expect(r.err).toContain('Multiple google sources');
    expect(r.err).toContain('default');
    expect(r.err).toContain('g1');
    expect(r.out).toBe('');
  });

  test('--source g2 lands the mute AND the unmute in g2 only (never the default google source)', async () => {
    await engine.executeRaw(
      `INSERT INTO sources (id, name, config, last_sync_at)
       VALUES ('g2', 'g2', '{"kind":"google"}'::jsonb, now())
       ON CONFLICT (id) DO NOTHING`,
    );
    // With two google sources an unqualified mute would refuse; --source
    // resolves it and the row must land in g2 and nowhere else.
    const muted = await captured(() => runLoops(engine, ['mute', 'sender', '[email protected]', '--source', 'g2']));
    expect(muted.exitCalled).toBeUndefined();
    expect(muted.verdict).toBe(0);
    expect((await loadSuppressions(engine, 'g2')).senders.has('[email protected]')).toBe(true);
    expect((await loadSuppressions(engine, 'default')).senders.has('[email protected]')).toBe(false);

    // Unmute scoped the same way removes the g2 row; a stray default row is untouched.
    await addSuppression(engine, 'default', 'sender', '[email protected]');
    const unmuted = await captured(() => runLoops(engine, ['unmute', 'sender', '[email protected]', '--source', 'g2']));
    expect(unmuted.exitCalled).toBeUndefined();
    expect(unmuted.out).toContain('Unmuted sender [email protected]');
    expect((await loadSuppressions(engine, 'g2')).senders.has('[email protected]')).toBe(false);
    expect((await loadSuppressions(engine, 'default')).senders.has('[email protected]')).toBe(true);
  });

  test('--help paths answer without touching loops', async () => {
    const w = await captured(() => runWaiting(engine, ['--help']));
    expect(w.out).toContain('gbrain waiting');
    expect(w.out).toContain('--stale-ok');
    const l = await captured(() => runLoops(engine, ['--help']));
    expect(l.out).toContain('gbrain loops');
    expect(l.out).toContain('mute');
    expect(l.out).toContain('unmute');
    expect(w.verdict).toBe(0);
    expect(l.verdict).toBe(0);
  });
});

// ── gbrain loops show <id> looks the id up directly (#5870) ─────────────────

describe('loops show by id', () => {
  /**
   * One aged loop (last activity in 2019), then 230 newer fillers, so the aged
   * loop sits below the 200-row page `loops list` prints. A second google
   * source holds one foreign loop.
   */
  async function seedShowFixture(): Promise<{ aged: number; foreign: number }> {
    const { id: aged } = await upsertOpenLoop(engine, loop({
      threadId: 'aaaa000000000001',
      counterpartyEmail: '[email protected]',
      summary: 'Reply owed to [email protected]: "Aged thread"',
    }));
    await engine.executeRaw(
      `UPDATE open_loops SET last_activity_at = '2019-06-01T00:00:00Z' WHERE id = $1`,
      [aged],
    );
    await engine.executeRaw(
      `INSERT INTO open_loops (source_id, detector, loop_type, dedup_key, summary, counterparty_email, last_activity_at)
       SELECT 'default', 'deterministic_thread', 'unanswered_inbound', 'thread:filler-' || n || ':unanswered_inbound',
              'Filler loop ' || n, 'filler' || n || '@example.com',
              now() - (n || ' minutes')::interval
       FROM generate_series(1, 230) AS n`,
    );
    const googleConfig = { kind: 'google' };
    await engine.executeRaw(
      `INSERT INTO sources (id, name, config, last_sync_at) VALUES ($1, $1, $2::jsonb, now()) ON CONFLICT (id) DO NOTHING`,
      ['gx', googleConfig],
    );
    const { id: foreign } = await upsertOpenLoop(engine, loop({
      sourceId: 'gx',
      threadId: 'bbbb000000000002',
      counterpartyEmail: '[email protected]',
      summary: 'Reply owed to [email protected]: "Foreign source"',
    }));
    return { aged, foreign };
  }

  test('an open loop below the 200 most recent is shown, verdict 0', async () => {
    const { aged } = await seedShowFixture();
    const r = await captured(() => runLoops(engine, ['show', String(aged)]));
    expect(r.err).toBe('');
    expect(r.out).toContain(`#${aged} [unanswered_inbound] open`);
    expect(r.out).toContain('"Aged thread"');
    expect(r.verdict).toBe(0);
    expect(r.exitCalled).toBeUndefined();
  });

  test('a dropped loop is shown without --status, in human and --json output', async () => {
    const { aged } = await seedShowFixture();
    await closeOpenLoop(engine, 'default', aged, 'dropped', 'manual');
    const human = await captured(() => runLoops(engine, ['show', String(aged)]));
    expect(human.out).toContain(`#${aged} [unanswered_inbound] dropped`);
    expect(human.verdict).toBe(0);
    const machine = await captured(() => runLoops(engine, ['show', String(aged), '--json']));
    const doc = JSON.parse(machine.out) as { ok: boolean; status: string; loop: { id: number; status: string } };
    expect(doc.ok).toBe(true);
    expect(doc.loop.id).toBe(aged);
    expect(doc.loop.status).toBe('dropped');
  });

  test('--status and --type still narrow a lookup: a mismatch is not_found, verdict 1', async () => {
    const { aged } = await seedShowFixture();
    await closeOpenLoop(engine, 'default', aged, 'done', 'manual');
    const wrongStatus = await captured(() => runLoops(engine, ['show', String(aged), '--status', 'open']));
    expect(wrongStatus.err).toContain(`Error [not_found]: No loop ${aged} in the sources this command reads.`);
    expect(wrongStatus.out).toBe('');
    expect(wrongStatus.verdict).toBe(1);
    const wrongType = await captured(() => runLoops(engine, ['show', String(aged), '--type', 'decision_pending']));
    expect(wrongType.err).toContain('Error [not_found]');
    expect(wrongType.verdict).toBe(1);
    const matching = await captured(() => runLoops(engine, ['show', String(aged), '--status', 'done']));
    expect(matching.out).toContain(`#${aged} [unanswered_inbound] done`);
    expect(matching.verdict).toBe(0);
  });

  test('--source narrows the lookup: a loop in another source is not_found there', async () => {
    const { foreign } = await seedShowFixture();
    const narrowed = await captured(() => runLoops(engine, ['show', String(foreign), '--source', 'default']));
    expect(narrowed.err).toContain(`No loop ${foreign} in the sources this command reads.`);
    expect(narrowed.verdict).toBe(1);
    const home = await captured(() => runLoops(engine, ['show', String(foreign), '--source', 'gx']));
    expect(home.out).toContain(`#${foreign} [unanswered_inbound] open`);
    expect(home.verdict).toBe(0);
  });

  test('a missing id renders not_found with the list fix and no --status advice', async () => {
    await seedShowFixture();
    const r = await captured(() => runLoops(engine, ['show', '424242']));
    expect(r.err).toContain('Error [not_found]: No loop 424242 in the sources this command reads.');
    expect(r.err).toContain('Fix: gbrain loops list');
    expect(r.err).not.toContain('closed loops need --status');
    expect(r.out).toBe('');
    expect(r.verdict).toBe(1);
  });

  test.each([
    ['no id at all', ['show']],
    ['id 0', ['show', '0']],
    ['a negative id', ['show', '-5']],
    ['a fractional id', ['show', '2.5']],
    ['a non-numeric id', ['show', 'abc']],
  ])('%s is a usage error: exit 2, invalid_params, nothing on stdout', async (_label, args) => {
    const r = await captured(() => runLoops(engine, args));
    expect(r.exitCalled).toBe(2);
    expect(r.err).toContain('Error [invalid_params]: gbrain loops show needs a loop id of 1 or more.');
    expect(r.err).toContain('Usage: gbrain loops show <id> [--json]');
    expect(r.out).toBe('');
  });
});