Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
25.9 KB
Raw Blame
/**
 * v0.38 autopilot per-source fan-out unit tests.
 *
 * Pure-function coverage:
 *   - readLastFullCycleAt: JSONB roundtrip + nulls
 *   - isSourceStale: 60-min floor + never-cycled
 *   - selectSourcesForDispatch: gate + cap + deterministic ordering
 *   - resolveFanoutMax: PGLite=1, Postgres=4, operator override
 *   - dispatchPerSource: fallback path + per-source idempotency + cap
 *
 * No engine; queue + engine are stubbed.
 */
import { describe, test, expect } from 'bun:test';
import {
  readLastFullCycleAt,
  isSourceStale,
  selectSourcesForDispatch,
  resolveFanoutMax,
  dispatchPerSource,
} from '../src/commands/autopilot-fanout.ts';
import {
  autopilotRemediationIdempotencyKey,
  shouldRunAutopilotFullCycle,
  shouldSleepHealthyAutopilot,
} from '../src/commands/autopilot-remediation-policy.ts';
import type { SourceRow, BrainEngine } from '../src/core/engine.ts';
import { SOURCE_FRESHNESS_PHASES } from '../src/core/cycle.ts';

function src(id: string, last_full_cycle_at?: string | null, extra: Record<string, unknown> = {}): SourceRow {
  return {
    id,
    name: null,
    local_path: `/tmp/${id}`,
    last_sync_at: null,
    config: {
      ...(last_full_cycle_at !== undefined ? { last_full_cycle_at } : {}),
      ...extra,
    },
  };
}

describe('readLastFullCycleAt', () => {
  test('returns Date when ISO string present', () => {
    const d = readLastFullCycleAt(src('a', '2026-05-22T07:00:00.000Z'));
    expect(d).toBeInstanceOf(Date);
    expect(d!.toISOString()).toBe('2026-05-22T07:00:00.000Z');
  });
  test('returns null when missing', () => {
    expect(readLastFullCycleAt(src('a'))).toBeNull();
  });
  test('returns null when explicitly null', () => {
    expect(readLastFullCycleAt(src('a', null))).toBeNull();
  });
  test('returns null for unparseable string (codex P0-5 robustness)', () => {
    expect(readLastFullCycleAt(src('a', 'not-a-date'))).toBeNull();
  });
});

describe('isSourceStale', () => {
  const NOW = Date.parse('2026-05-22T12:00:00.000Z');
  test('never-cycled source is stale', () => {
    expect(isSourceStale(src('a'), NOW)).toBe(true);
  });
  test('source cycled 30min ago is fresh', () => {
    const past = new Date(NOW - 30 * 60_000).toISOString();
    expect(isSourceStale(src('a', past), NOW)).toBe(false);
  });
  test('source cycled exactly at floor (60min) is stale (>=)', () => {
    const past = new Date(NOW - 60 * 60_000).toISOString();
    expect(isSourceStale(src('a', past), NOW)).toBe(true);
  });
  test('source cycled 2h ago is stale', () => {
    const past = new Date(NOW - 2 * 60 * 60_000).toISOString();
    expect(isSourceStale(src('a', past), NOW)).toBe(true);
  });
  test('override floor (5 min) flips stale earlier', () => {
    const past = new Date(NOW - 6 * 60_000).toISOString();
    expect(isSourceStale(src('a', past), NOW, 5)).toBe(true);
    expect(isSourceStale(src('a', past), NOW, 60)).toBe(false);
  });
});

describe('Autopilot remediation policy (#4046)', () => {
  test('targeted remediation keys reopen in each dispatch interval', () => {
    const recommendationKey = 'default:sync:deadbeef';
    const firstSlot = '2026-08-13T06:00:00.000Z';
    const nextSlot = '2026-08-13T06:05:00.000Z';

    expect(autopilotRemediationIdempotencyKey(recommendationKey, firstSlot)).toBe(
      'default:sync:deadbeef:autopilot:2026-08-13T06:00:00.000Z',
    );
    expect(autopilotRemediationIdempotencyKey(recommendationKey, nextSlot)).not.toBe(
      autopilotRemediationIdempotencyKey(recommendationKey, firstSlot),
    );
  });

  test('an overdue full cycle wins even while a small remediation plan exists', () => {
    expect(shouldRunAutopilotFullCycle({
      score: 94,
      planLength: 2,
      estimatedSeconds: 30,
      minutesSinceLastFull: 61,
    })).toBe(true);
  });

  test('a fresh small remediation plan stays targeted', () => {
    expect(shouldRunAutopilotFullCycle({
      score: 94,
      planLength: 2,
      estimatedSeconds: 30,
      minutesSinceLastFull: 10,
    })).toBe(false);
  });

  test('only a fresh healthy brain with no plan sleeps', () => {
    expect(shouldSleepHealthyAutopilot(95, 0, 59)).toBe(true);
    expect(shouldSleepHealthyAutopilot(95, 0, 60)).toBe(false);
    expect(shouldSleepHealthyAutopilot(95, 1, 10)).toBe(false);
  });

  test('large, slow, or severely degraded plans still use the full cycle', () => {
    expect(shouldRunAutopilotFullCycle({
      score: 90,
      planLength: 4,
      estimatedSeconds: 30,
      minutesSinceLastFull: 10,
    })).toBe(true);
    expect(shouldRunAutopilotFullCycle({
      score: 90,
      planLength: 2,
      estimatedSeconds: 300,
      minutesSinceLastFull: 10,
    })).toBe(true);
    expect(shouldRunAutopilotFullCycle({
      score: 69,
      planLength: 1,
      estimatedSeconds: 30,
      minutesSinceLastFull: 10,
    })).toBe(true);
  });
});

describe('selectSourcesForDispatch', () => {
  const NOW = Date.parse('2026-05-22T12:00:00.000Z');
  const fresh = (id: string, agoMin: number) =>
    src(id, new Date(NOW - agoMin * 60_000).toISOString());

  test('only stale sources dispatched', () => {
    const result = selectSourcesForDispatch(
      [fresh('a', 30), fresh('b', 90), src('c')],
      10,
      NOW,
    );
    expect(result.dispatch.map(s => s.id).sort()).toEqual(['b', 'c']);
    expect(result.skippedFresh.map(s => s.id)).toEqual(['a']);
    expect(result.skippedCap).toEqual([]);
  });

  test('never-cycled (NULL) sorts before timestamped', () => {
    const result = selectSourcesForDispatch(
      [fresh('b', 90), src('a'), fresh('c', 120)],
      10,
      NOW,
    );
    // 'a' has no last_full_cycle_at → -Infinity → sorts first
    // then 'c' (120min ago, older) before 'b' (90min ago, newer)
    expect(result.dispatch.map(s => s.id)).toEqual(['a', 'c', 'b']);
  });

  test('cap honored; overflow goes to skippedCap', () => {
    const result = selectSourcesForDispatch(
      [src('a'), src('b'), src('c'), src('d'), src('e')],
      2,
      NOW,
    );
    expect(result.dispatch.length).toBe(2);
    expect(result.skippedCap.length).toBe(3);
  });

  test('alphabetical tiebreaker when two NULL sources', () => {
    const result = selectSourcesForDispatch([src('zebra'), src('alpha')], 10, NOW);
    expect(result.dispatch.map(s => s.id)).toEqual(['alpha', 'zebra']);
  });

  test('all-fresh produces empty dispatch (the steady-state)', () => {
    const result = selectSourcesForDispatch([fresh('a', 5), fresh('b', 10)], 10, NOW);
    expect(result.dispatch).toEqual([]);
    expect(result.skippedFresh.length).toBe(2);
  });

  test('empty input is safe', () => {
    const result = selectSourcesForDispatch([], 4, NOW);
    expect(result.dispatch).toEqual([]);
    expect(result.skippedFresh).toEqual([]);
    expect(result.skippedCap).toEqual([]);
  });
});

describe('resolveFanoutMax', () => {
  function stubEngine(kind: 'postgres' | 'pglite', configValue?: string): BrainEngine {
    return {
      kind,
      getConfig: async (_key: string) => configValue ?? null,
    } as unknown as BrainEngine;
  }
  test('PGLite default is 1 (codex P1-3)', async () => {
    expect(await resolveFanoutMax(stubEngine('pglite'))).toBe(1);
  });
  test('Postgres default is 4', async () => {
    expect(await resolveFanoutMax(stubEngine('postgres'))).toBe(4);
  });
  test('operator override honored', async () => {
    expect(await resolveFanoutMax(stubEngine('postgres', '8'))).toBe(8);
    expect(await resolveFanoutMax(stubEngine('pglite', '3'))).toBe(3);
  });
  test('invalid override falls back to default', async () => {
    expect(await resolveFanoutMax(stubEngine('postgres', 'not-a-number'))).toBe(4);
    expect(await resolveFanoutMax(stubEngine('postgres', '0'))).toBe(4);
    expect(await resolveFanoutMax(stubEngine('postgres', '-5'))).toBe(4);
    expect(await resolveFanoutMax(stubEngine('pglite', ''))).toBe(1);
  });
});

describe('dispatchPerSource — integration with stubbed engine + queue', () => {
  type AddedJob = { name: string; data: unknown; opts: Record<string, unknown> };

  function makeStubs(sources: SourceRow[], opts?: { listThrows?: boolean; listError?: unknown }) {
    const added: AddedJob[] = [];
    let nextId = 100;
    const engine = {
      kind: 'postgres' as const,
      // An unmanaged brain with no worktree bindings: automatic pull follows remote_url (#5463).
      executeRaw: async (sql: string) => (sql.includes('FROM persistence_brain') ? [{ enabled: false }] : []),
      listAllSources: async () => {
        if (opts?.listError) throw opts.listError;
        if (opts?.listThrows) throw new Error('sources table missing');
        return sources;
      },
    } as unknown as BrainEngine;
    const queue = {
      add: async (name: string, data: unknown, addOpts: Record<string, unknown>) => {
        added.push({ name, data, opts: addOpts });
        return { id: nextId++ };
      },
    } as unknown as Parameters<typeof dispatchPerSource>[1];
    const events: string[] = [];
    const logs: string[] = [];
    const fanoutOpts = {
      repoPath: '/tmp/brain',
      slot: '2026-05-22T12:00:00.000Z',
      timeoutMs: 600_000,
      fanoutMax: 4,
      jsonMode: true,
      emit: (line: string) => events.push(line),
      log: (line: string) => logs.push(line),
      pathExists: (_path: string) => true,
    };
    return { engine, queue, added, events, logs, fanoutOpts };
  }

  test('empty sources list falls back to legacy single-job dispatch', async () => {
    const { engine, queue, added, fanoutOpts } = makeStubs([]);
    const result = await dispatchPerSource(engine, queue, fanoutOpts);
    expect(result.legacy_fallback).toBe(true);
    expect(added.length).toBe(1);
    expect(added[0].name).toBe('autopilot-cycle');
    expect((added[0].data as Record<string, unknown>).source_id).toBeUndefined();
    expect(added[0].opts.idempotency_key).toBe('autopilot-cycle:2026-05-22T12:00:00.000Z');
  });

  test('listAllSources throwing also falls back to legacy', async () => {
    const { engine, queue, added, fanoutOpts } = makeStubs([], { listThrows: true });
    const result = await dispatchPerSource(engine, queue, fanoutOpts);
    expect(result.legacy_fallback).toBe(true);
    expect(added.length).toBe(1);
  });

  test('missing sources table (Postgres 42P01) falls back to legacy', async () => {
    const err = Object.assign(new Error('relation "sources" does not exist'), { code: '42P01' });
    const { engine, queue, added, fanoutOpts } = makeStubs([], { listError: err });
    const result = await dispatchPerSource(engine, queue, fanoutOpts);
    expect(result.legacy_fallback).toBe(true);
    expect(added.length).toBe(1);
  });

  test('transient connection error skips the tick instead of the legacy repo-root cycle', async () => {
    const err = Object.assign(new Error('write CONNECT_TIMEOUT aws-0-us-west-1.pooler.supabase.com:5432'), { code: 'CONNECT_TIMEOUT' });
    const { engine, queue, added, events, fanoutOpts } = makeStubs([], { listError: err });
    const result = await dispatchPerSource(engine, queue, fanoutOpts);
    expect(result.legacy_fallback).toBe(false);
    expect(result.dispatched).toEqual([]);
    expect(added.length).toBe(0);
    expect(events.some((e) => e.includes('"fanout_skipped"'))).toBe(true);
  });

  test('per-source fan-out: 2 stale sources, both dispatched with distinct keys', async () => {
    const { engine, queue, added, fanoutOpts } = makeStubs([src('alpha'), src('beta')]);
    const result = await dispatchPerSource(engine, queue, fanoutOpts);
    expect(result.legacy_fallback).toBe(false);
    expect(result.dispatched.sort()).toEqual(['alpha', 'beta']);
    expect(added.length).toBe(2);
    // Per-source idempotency keys
    const keys = added.map(j => j.opts.idempotency_key as string).sort();
    expect(keys).toEqual([
      'autopilot-cycle:alpha:2026-05-22T12:00:00.000Z',
      'autopilot-cycle:beta:2026-05-22T12:00:00.000Z',
    ]);
    // source_id threaded through job data
    const sourceIds = added.map(j => (j.data as Record<string, unknown>).source_id).sort();
    expect(sourceIds).toEqual(['alpha', 'beta']);
  });

  test('sources whose local_path is missing on this machine are skipped before dispatch', async () => {
    const present = src('present');
    present.local_path = '/present/brain';
    const missing = src('foreign');
    missing.local_path = '/foreign/brain';
    const { engine, queue, added, events, fanoutOpts } = makeStubs([present, missing]);
    fanoutOpts.pathExists = (p) => p === '/present/brain';

    const result = await dispatchPerSource(engine, queue, fanoutOpts);

    expect(result.dispatched).toEqual(['present']);
    expect(result.skipped_unavailable_path).toEqual(['foreign']);
    expect(added.length).toBe(1);
    expect((added[0].data as Record<string, unknown>).source_id).toBe('present');
    const skipped = events.find(e => e.includes('fanout_source_path_skipped'));
    expect(skipped).toBeDefined();
    expect(JSON.parse(skipped!).source_id).toBe('foreign');
  });

  test('missing managed remote clones still dispatch so sync can re-clone them', async () => {
    const managed = src('managed', undefined, {
      remote_url: 'https://github.com/example/repo',
      managed_clone: true,
    });
    managed.local_path = '/missing/managed';
    const { engine, queue, added, fanoutOpts } = makeStubs([managed]);
    fanoutOpts.pathExists = () => false;

    const result = await dispatchPerSource(engine, queue, fanoutOpts);

    expect(result.dispatched).toEqual(['managed']);
    expect(result.skipped_unavailable_path).toEqual([]);
    expect(added.length).toBe(1);
  });

  test('all unavailable non-managed sources are handled but not called fresh', async () => {
    const missing = src('foreign');
    missing.local_path = '/foreign/brain';
    const { engine, queue, added, fanoutOpts } = makeStubs([missing]);
    fanoutOpts.pathExists = () => false;

    const result = await dispatchPerSource(engine, queue, fanoutOpts);

    expect(result.dispatched).toEqual([]);
    expect(result.skipped_unavailable_path).toEqual(['foreign']);
    expect(result.all_sources_fresh).toBe(false);
    expect(result.all_sources_handled).toBe(true);
    expect(added.length).toBe(0);
  });

  test('fresh plus unavailable sources are handled without implying every source is fresh', async () => {
    const NOW = Date.now();
    const fresh = src('fresh', new Date(NOW - 5 * 60_000).toISOString());
    const missing = src('foreign');
    missing.local_path = '/foreign/brain';
    const { engine, queue, added, fanoutOpts } = makeStubs([fresh, missing]);
    fanoutOpts.pathExists = (p) => p === fresh.local_path;

    const result = await dispatchPerSource(engine, queue, fanoutOpts);

    expect(result.skipped_fresh).toEqual(['fresh']);
    expect(result.skipped_unavailable_path).toEqual(['foreign']);
    expect(result.all_sources_fresh).toBe(false);
    expect(result.all_sources_handled).toBe(true);
    expect(added.length).toBe(0);
  });

  test('relative local_path rows are skipped by the same fan-out guard', () => {
    const relative = src('legacy');
    relative.local_path = 'notes/brain';
    const result = selectSourcesForDispatch(
      [src('present'), relative],
      10,
      Date.parse('2026-05-22T12:00:00.000Z'),
      60,
      new Map(),
      { baseMin: 0, capMin: 120 },
      () => true,
    );

    expect(result.dispatch.map(s => s.id)).toEqual(['present']);
    expect(result.skippedUnavailablePath.map(s => s.id)).toEqual(['legacy']);
    // The row carries the warning that excluded it (dispatchPerSource logs it
    // directly rather than recomputing it with a second path probe).
    expect(result.skippedUnavailablePath[0].skip_warning).toContain('legacy');
    expect(result.skippedUnavailablePath[0].skip_warning).toContain('notes/brain');
  });

  test('pull: true only when source.config.remote_url is set', async () => {
    const remote = src('remote', undefined, { remote_url: 'https://github.com/x/y' });
    const local = src('local');
    const { engine, queue, added, fanoutOpts } = makeStubs([remote, local]);
    await dispatchPerSource(engine, queue, fanoutOpts);
    const byId = new Map<string, AddedJob>(
      added.map(j => [(j.data as Record<string, unknown>).source_id as string, j]),
    );
    expect((byId.get('remote')!.data as Record<string, unknown>).pull).toBe(true);
    expect((byId.get('local')!.data as Record<string, unknown>).pull).toBe(false);
  });

  test('pull: true when PGLite returns source.config as a JSON string', async () => {
    const remote = src('remote');
    remote.config = '{"remote_url":"https://github.com/x/y"}' as unknown as SourceRow['config'];
    const { engine, queue, added, fanoutOpts } = makeStubs([remote]);
    await dispatchPerSource(engine, queue, fanoutOpts);
    expect((added[0].data as Record<string, unknown>).pull).toBe(true);
  });

  test('#4399: a syncEnabled:false source keeps its freshness cycle but is never pulled or synced', async () => {
    // The full-cycle fan-out is autopilot's SECOND automatic sync path (the
    // freshness dispatcher in autopilot.ts is the first). A source the operator
    // excluded from automatic sync must still get lint/backlinks/extract and its
    // last_full_cycle_at stamp — only the sync phase (and the pull that feeds
    // it) is dropped. normalizeQueuedSourcePhases passes a subset through.
    const disabled = src('disabled', undefined, { syncEnabled: false, remote_url: 'https://github.com/x/y' });
    const normal = src('normal', undefined, { remote_url: 'https://github.com/x/y' });
    const { engine, queue, added, fanoutOpts } = makeStubs([disabled, normal]);
    await dispatchPerSource(engine, queue, fanoutOpts);
    const byId = new Map<string, AddedJob>(
      added.map(j => [(j.data as Record<string, unknown>).source_id as string, j]),
    );
    const disabledData = byId.get('disabled')!.data as Record<string, unknown>;
    expect(disabledData.phases).toEqual(SOURCE_FRESHNESS_PHASES.filter((p) => p !== 'sync'));
    expect(disabledData.phases).toContain('extract');
    expect(disabledData.pull).toBe(false);
    const normalData = byId.get('normal')!.data as Record<string, unknown>;
    expect(normalData.phases).toEqual(SOURCE_FRESHNESS_PHASES);
    expect(normalData.pull).toBe(true);
  });

  test('#5198: a claimed source awaiting activation keeps its freshness cycle but is never pulled or synced', async () => {
    // performSync refuses a claimed-but-not-activated source by contract, so
    // the fan-out drops its sync phase (and pull) instead of dispatching a
    // cycle that fails the same way every tick. The reason is reported once.
    const claimed = src('claimed-5198', undefined, { remote_url: 'https://github.com/x/y' });
    const normal = src('normal-5198', undefined, { remote_url: 'https://github.com/x/y' });
    const { engine, queue, added, events, fanoutOpts } = makeStubs([claimed, normal]);
    // Unmanaged brain; claimed-5198 is bound (activation pending), normal-5198 is not.
    (engine as unknown as { executeRaw: (sql: string, params?: unknown[]) => Promise<unknown[]> }).executeRaw = async (sql, params) =>
      sql.startsWith('SELECT enabled FROM persistence_brain') ? [{ enabled: false }]
        : sql.includes('WHERE s.source_id=$1') && params?.[0] !== 'claimed-5198' ? [] : [{ source_id: 'claimed-5198' }];
    await dispatchPerSource(engine, queue, fanoutOpts);
    const byId = new Map<string, AddedJob>(
      added.map(j => [(j.data as Record<string, unknown>).source_id as string, j]),
    );
    const claimedData = byId.get('claimed-5198')!.data as Record<string, unknown>;
    expect(claimedData.phases).toEqual(SOURCE_FRESHNESS_PHASES.filter((p) => p !== 'sync'));
    expect(claimedData.pull).toBe(false);
    const normalData = byId.get('normal-5198')!.data as Record<string, unknown>;
    expect(normalData.phases).toEqual(SOURCE_FRESHNESS_PHASES);
    expect(normalData.pull).toBe(true);
    const skipped = () => events.filter(e => e.includes('"fanout_sync_skipped"'));
    expect(skipped().map(e => JSON.parse(e))).toEqual([
      { event: 'fanout_sync_skipped', source_id: 'claimed-5198', reason: 'activation_pending' },
    ]);
    await dispatchPerSource(engine, queue, fanoutOpts);
    expect(skipped()).toHaveLength(1);
  });

  test('fanoutMax cap: 3 sources, fanoutMax=1, 1 dispatched + 2 in skippedCap', async () => {
    const { engine, queue, added, fanoutOpts } = makeStubs([src('a'), src('b'), src('c')]);
    fanoutOpts.fanoutMax = 1;
    const result = await dispatchPerSource(engine, queue, fanoutOpts);
    expect(result.dispatched.length).toBe(1);
    expect(result.skipped_cap.length).toBe(2);
    expect(added.length).toBe(1);
  });

  test('per-submit error does NOT abort the tick', async () => {
    const sources = [src('alpha'), src('boom'), src('charlie')];
    const added: AddedJob[] = [];
    const events: string[] = [];
    let nextId = 100;
    const engine = {
      kind: 'postgres' as const,
      listAllSources: async () => sources,
    } as unknown as BrainEngine;
    const queue = {
      add: async (name: string, data: unknown, opts: Record<string, unknown>) => {
        const id = (data as Record<string, unknown>).source_id;
        if (id === 'boom') throw new Error('queue full');
        added.push({ name, data, opts });
        return { id: nextId++ };
      },
    } as unknown as Parameters<typeof dispatchPerSource>[1];
    const result = await dispatchPerSource(engine, queue, {
      repoPath: '/tmp', slot: 's', timeoutMs: 1, fanoutMax: 4, jsonMode: true,
      emit: (l) => events.push(l), log: () => {}, pathExists: () => true,
    });
    // 2 of 3 dispatched (alpha + charlie); boom failed but didn't abort
    expect(result.dispatched.sort()).toEqual(['alpha', 'charlie']);
    expect(added.length).toBe(2);
    expect(events.some(e => e.includes('fanout_submit_failed') && e.includes('boom'))).toBe(true);
  });

  test('cap-reached event fires when skippedCap is non-empty', async () => {
    const { engine, queue, events, fanoutOpts } = makeStubs([src('a'), src('b'), src('c')]);
    fanoutOpts.fanoutMax = 1;
    await dispatchPerSource(engine, queue, fanoutOpts);
    const capEvent = events.find(e => e.includes('fanout_cap_reached'));
    expect(capEvent).toBeDefined();
    const parsed = JSON.parse(capEvent!);
    expect(parsed.cap).toBe(1);
    expect(parsed.pending.length).toBe(2);
  });

  test('per-source submit MUST NOT pass maxWaiting, MUST pass maxPending: 1 (fan-out preserved + single-flight)', async () => {
    // Direct unit-stub queues can't enforce backpressure semantics (the
    // production MinionQueue implementation does), so this catches the
    // regression by inspecting the submit opts at the dispatch boundary.
    // maxWaiting's NULL-as-wildcard source scope would coalesce N per-source
    // jobs sharing name='autopilot-cycle' down to ONE waiting job — killing
    // the fan-out. maxPending is required instead: its EXACT source scope
    // keeps N independent per-source caps while suppressing cross-slot
    // re-dispatch when a source's cycle is still in flight (upstream
    // issue #2). The e2e test also pins both against a real queue.
    const { engine, queue, added, fanoutOpts } = makeStubs([src('a'), src('b'), src('c')]);
    await dispatchPerSource(engine, queue, fanoutOpts);
    expect(added.length).toBe(3);
    for (const job of added) {
      expect(job.opts.maxWaiting).toBeUndefined();
      expect(job.opts.maxPending).toBe(1);
    }
  });

  test('legacy fallback submit passes maxPending: 1 (cross-slot single-flight) and no maxWaiting', async () => {
    const { engine, queue, added, fanoutOpts } = makeStubs([]);
    await dispatchPerSource(engine, queue, fanoutOpts);
    expect(added.length).toBe(1);
    expect(added[0].opts.maxPending).toBe(1);
    expect(added[0].opts.maxWaiting).toBeUndefined();
  });

  test('coalesced submissions are reported separately and emit dispatch_coalesced', async () => {
    // Stub queue marks the second source's job as coalesced (already in
    // flight) — the fanout must not claim it as a dispatch.
    const added: Array<{ name: string; data: Record<string, unknown>; opts: Record<string, unknown> }> = [];
    const events: string[] = [];
    let nextId = 200;
    const engine = {
      kind: 'postgres' as const,
      listAllSources: async () => [src('a'), src('b')],
      getConfig: async () => null,
      executeRaw: async () => [],
    } as unknown as BrainEngine;
    const queue = {
      add: async (name: string, data: Record<string, unknown>, addOpts: Record<string, unknown>) => {
        added.push({ name, data, opts: addOpts });
        const coalesce = data.source_id === 'b';
        return { id: nextId++, ...(coalesce ? { coalesced: true } : {}) };
      },
    } as unknown as Parameters<typeof dispatchPerSource>[1];
    const result = await dispatchPerSource(engine, queue, {
      repoPath: '/tmp/brain', slot: 's', timeoutMs: 1, fanoutMax: 4, jsonMode: true,
      emit: (l: string) => events.push(l), log: () => {}, pathExists: () => true,
    });
    expect(result.dispatched).toEqual(['a']);
    expect(result.coalesced).toEqual(['b']);
    const kinds = events.map(e => JSON.parse(e).event);
    expect(kinds).toContain('dispatched');
    expect(kinds).toContain('dispatch_coalesced');
  });

  test('all-fresh tick dispatches nothing (no jobs added)', async () => {
    const NOW = Date.now();
    const recent = (id: string) =>
      src(id, new Date(NOW - 5 * 60_000).toISOString());
    const { engine, queue, added, fanoutOpts } = makeStubs([recent('a'), recent('b')]);
    const result = await dispatchPerSource(engine, queue, fanoutOpts);
    expect(result.dispatched.length).toBe(0);
    expect(result.skipped_fresh.length).toBe(2);
    expect(result.all_sources_fresh).toBe(true);
    expect(result.all_sources_handled).toBe(true);
    expect(added.length).toBe(0);
  });

  test('a failed stale-source submission is not misclassified as all fresh', async () => {
    const { engine, fanoutOpts } = makeStubs([src('stale')]);
    const queue = {
      add: async () => { throw new Error('queue unavailable'); },
    } as unknown as Parameters<typeof dispatchPerSource>[1];

    const result = await dispatchPerSource(engine, queue, fanoutOpts);

    expect(result.dispatched).toEqual([]);
    expect(result.all_sources_fresh).toBe(false);
    expect(result.all_sources_handled).toBe(false);
  });
});