Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

29.0 KB
Raw Blame
import { describe, expect, it, jest, spyOn } from 'bun:test';
import { EventEmitter } from 'events';
import type { spawn } from 'child_process';
import { join, resolve } from 'node:path';
import {
  detectUsableAgent,
  detectUsableAgents,
  GEMINI_NO_MCP_SERVERS,
  MAX_STREAM_CHARS,
  runCommand,
  type AgentDetectionDependencies,
  type UsableAgent,
  type UsableAgentId,
} from '../../../src/services/agent-runner/detect.js';
import type { OAuthTokenResult } from '../../../src/shared/oauth-token.js';
import { logger } from '../../../src/utils/logger.js';

type ScriptedOutcome =
  | { exitCode: number; stdout?: string; stderr?: string }
  | { exitCode: number; stdout?: string; stderr?: string; delayMs: number }
  | { spawnError: string };

class FakeStream extends EventEmitter {
  setEncoding(): this {
    return this;
  }
}

class FakeChild extends EventEmitter {
  stdout = new FakeStream();
  stderr = new FakeStream();
}

/** A fake `spawn` that answers from a script keyed by "command arg arg". */
function fakeSpawn(script: Record<string, ScriptedOutcome>, calls: string[] = []): typeof spawn {
  return ((command: string, args: string[]) => {
    const key = [command, ...args].join(' ');
    calls.push(key);
    const child = new FakeChild();
    const outcome = script[key] ?? { exitCode: 1, stderr: '' };
    const answer = () => {
      if ('spawnError' in outcome) {
        child.emit('error', Object.assign(new Error(outcome.spawnError), { code: 'ENOENT' }));
        return;
      }
      if (outcome.stdout) child.stdout.emit('data', outcome.stdout);
      if (outcome.stderr) child.stderr.emit('data', outcome.stderr);
      child.emit('close', outcome.exitCode);
    };
    if ('delayMs' in outcome) setTimeout(answer, outcome.delayMs);
    else queueMicrotask(answer);
    return child;
  }) as unknown as typeof spawn;
}

async function afterFakeDelay<T>(start: () => Promise<T>): Promise<T> {
  jest.useFakeTimers();
  try {
    const pending = start();
    await new Promise<void>(resolve => setImmediate(resolve));
    jest.advanceTimersByTime(3_500);
    return await pending;
  } finally {
    jest.useRealTimers();
  }
}

const HOME = '/home/tester';
const CLAUDE_PATH = '/usr/local/bin/claude';
const CODEX_PATH = '/usr/local/bin/codex';
const GEMINI_PATH = '/usr/local/bin/gemini';
const OPENCODE_PATH = '/usr/local/bin/opencode';

const WHICH_CODEX = { 'which codex': { exitCode: 0, stdout: `${CODEX_PATH}\n` } };
const WHICH_GEMINI = { 'which gemini': { exitCode: 0, stdout: `${GEMINI_PATH}\n` } };
const WHICH_OPENCODE = { 'which opencode': { exitCode: 0, stdout: `${OPENCODE_PATH}\n` } };

function dependencies(overrides: Partial<AgentDetectionDependencies>): Partial<AgentDetectionDependencies> {
  return {
    spawn: fakeSpawn({}),
    findClaudeExecutable: () => {
      throw new Error('Claude executable not found.');
    },
    readClaudeOAuthToken: async (): Promise<OAuthTokenResult> => ({ kind: 'absent', reason: 'no credential' }),
    hasAnthropicApiKey: () => false,
    hasAnthropicAuthToken: () => false,
    hasConfiguredClaudeOAuthToken: () => false,
    fileExists: () => false,
    readTextFile: () => {
      throw new Error('ENOENT');
    },
    environment: {},
    homeDirectory: () => HOME,
    platform: () => 'darwin',
    now: () => 1_000_000,
    geminiAccountChecks: new Map(),
    ...overrides,
  };
}

async function detectOne(id: UsableAgent['id'], overrides: Partial<AgentDetectionDependencies>): Promise<UsableAgent> {
  const agents = await detectUsableAgents(dependencies(overrides));
  const agent = agents.find(candidate => candidate.id === id);
  if (!agent) throw new Error(`no ${id} result`);
  return agent;
}

describe('detectUsableAgents', () => {
  it('reports all four agents in priority order and never throws', async () => {
    const agents = await detectUsableAgents(dependencies({}));
    expect(agents.map(agent => agent.id)).toEqual(['claude-code', 'codex', 'gemini', 'opencode']);
    expect(agents.every(agent => agent.authenticated === false && agent.path === null)).toBe(true);
  });

  describe('Claude Code', () => {
    const installed = { findClaudeExecutable: () => CLAUDE_PATH };

    it('not installed', async () => {
      const agent = await detectOne('claude-code', {});
      expect(agent).toMatchObject({ path: null, authenticated: false });
      expect(agent.reason).toContain('not installed');
    });

    it('installed but logged out', async () => {
      const calls: string[] = [];
      const agent = await detectOne('claude-code', {
        ...installed,
        spawn: fakeSpawn(
          { [`${CLAUDE_PATH} auth status --json`]: { exitCode: 1, stdout: '{"loggedIn": false, "authMethod": "none"}' } },
          calls,
        ),
      });
      expect(agent).toMatchObject({ path: CLAUDE_PATH, authenticated: false });
      expect(agent.reason).toContain('logged out');
      expect(calls).toContain(`${CLAUDE_PATH} auth status --json`);
    });

    it('logged in through a stored OAuth token, without spawning the CLI', async () => {
      const calls: string[] = [];
      const agent = await detectOne('claude-code', {
        ...installed,
        spawn: fakeSpawn({}, calls),
        readClaudeOAuthToken: async () => ({ kind: 'present', token: 'secret', source: 'keychain', expiresAt: 2_000_000 }),
      });
      expect(agent).toMatchObject({ path: CLAUDE_PATH, authenticated: true });
      expect(agent.reason).not.toContain('secret');
      expect(calls.some(call => call.startsWith(CLAUDE_PATH))).toBe(false);
    });

    it('logged in through an API key', async () => {
      const agent = await detectOne('claude-code', { ...installed, hasAnthropicApiKey: () => true });
      expect(agent).toMatchObject({ authenticated: true });
    });

    it('logged in through a long-lived CLAUDE_CODE_OAUTH_TOKEN in ~/.claude-mem/.env, without reading the stored login', async () => {
      const calls: string[] = [];
      let storeRead = false;
      const agent = await detectOne('claude-code', {
        ...installed,
        spawn: fakeSpawn({}, calls),
        hasConfiguredClaudeOAuthToken: () => true,
        readClaudeOAuthToken: async () => {
          storeRead = true;
          return { kind: 'expired', reason: 'stored login expired', expiresAt: 1 };
        },
      });
      expect(agent).toMatchObject({ path: CLAUDE_PATH, authenticated: true });
      expect(agent.reason).toContain('CLAUDE_CODE_OAUTH_TOKEN');
      expect(storeRead).toBe(false);
      expect(calls.some(call => call.startsWith(CLAUDE_PATH))).toBe(false);
    });

    it('falls back to `claude auth status` when the stored token is expired', async () => {
      const agent = await detectOne('claude-code', {
        ...installed,
        readClaudeOAuthToken: async () => ({ kind: 'expired', reason: 'expired', expiresAt: 10 }),
        spawn: fakeSpawn({
          [`${CLAUDE_PATH} auth status --json`]: { exitCode: 0, stdout: '{"loggedIn": true, "authMethod": "claude.ai"}' },
        }),
      });
      expect(agent).toMatchObject({ authenticated: true });
      expect(agent.reason).toContain('claude.ai');
    });

    it('a slow `claude auth status` is waited for and still reports logged in', async () => {
      const agent = await afterFakeDelay(() => detectOne('claude-code', {
        ...installed,
        readClaudeOAuthToken: async () => ({ kind: 'absent', reason: 'no keychain access' }),
        spawn: fakeSpawn({
          [`${CLAUDE_PATH} auth status --json`]: { exitCode: 0, stdout: '{"loggedIn": true, "authMethod": "claude.ai"}', delayMs: 3_500 },
        }),
      }));
      expect(agent).toMatchObject({ authenticated: true });
      expect(agent.reason).toContain('claude.ai');
    });
  });

  describe('Codex', () => {
    it('not installed', async () => {
      const agent = await detectOne('codex', { spawn: fakeSpawn({ 'which codex': { exitCode: 1 } }) });
      expect(agent).toMatchObject({ path: null, authenticated: false });
      expect(agent.reason).toContain('not installed');
    });

    it('installed but logged out', async () => {
      const agent = await detectOne('codex', {
        spawn: fakeSpawn({ ...WHICH_CODEX, [`${CODEX_PATH} login status`]: { exitCode: 1, stderr: 'Not logged in\n' } }),
      });
      expect(agent).toMatchObject({ path: CODEX_PATH, authenticated: false });
      expect(agent.reason).toContain('Not logged in');
    });

    it('logged in (status line on stderr, as codex-cli prints it)', async () => {
      const agent = await detectOne('codex', {
        spawn: fakeSpawn({ ...WHICH_CODEX, [`${CODEX_PATH} login status`]: { exitCode: 0, stderr: 'Logged in using ChatGPT\n' } }),
      });
      expect(agent).toMatchObject({ path: CODEX_PATH, authenticated: true, reason: 'Logged in using ChatGPT' });
    });

    it('a slow `codex login status` is waited for and still reports logged in', async () => {
      const agent = await afterFakeDelay(() => detectOne('codex', {
        spawn: fakeSpawn({
          ...WHICH_CODEX,
          [`${CODEX_PATH} login status`]: { exitCode: 0, stderr: 'Logged in using ChatGPT\n', delayMs: 3_500 },
        }),
      }));
      expect(agent).toMatchObject({ path: CODEX_PATH, authenticated: true, reason: 'Logged in using ChatGPT' });
    });

    it('uses where.exe on Windows', async () => {
      const calls: string[] = [];
      await detectOne('codex', { platform: () => 'win32', spawn: fakeSpawn({}, calls) });
      expect(calls).toContain(`${join('C:\\Windows', 'System32', 'where.exe')} codex`);
    });
  });

  describe('Gemini', () => {
    const settingsPath = join(HOME, '.gemini', 'settings.json');
    const credentialsPath = join(HOME, '.gemini', 'oauth_creds.json');
    const settings = JSON.stringify({ security: { auth: { selectedType: 'oauth-personal' } } });

    it('not installed', async () => {
      const agent = await detectOne('gemini', { spawn: fakeSpawn({ 'which gemini': { spawnError: 'spawn which ENOENT' } }) });
      expect(agent).toMatchObject({ path: null, authenticated: false });
      expect(agent.reason).toContain('not installed');
    });

    it('installed but logged out (auth type named, no OAuth credentials)', async () => {
      const agent = await detectOne('gemini', {
        spawn: fakeSpawn(WHICH_GEMINI),
        fileExists: path => path === settingsPath,
        readTextFile: () => settings,
      });
      expect(agent).toMatchObject({ path: GEMINI_PATH, authenticated: false });
      expect(agent.reason).toContain('oauth_creds.json');
    });

    const PROBE = [GEMINI_PATH, '--skip-trust', '-e', 'none', '--allowed-mcp-server-names', GEMINI_NO_MCP_SERVERS, '-o', 'json'].join(' ');
    const NO_INPUT = 'No input provided via stdin. Input can be provided by piping data into gemini or using the --prompt option.\n';
    const INELIGIBLE = 'Error authenticating: IneligibleTierError: This client is no longer supported for Gemini Code Assist for individuals. To continue using Gemini, please migrate to the Antigravity suite of products: https://antigravity.google\n'
      + '    at throwIneligibleOrProjectIdError (file:///gemini/bundle/chunk.js:300912:11)\n  ineligibleTiers: [ { reasonCode: \'UNSUPPORTED_CLIENT\' } ]\n' + NO_INPUT;
    const signedIn = (probe: ScriptedOutcome, credentials = () => JSON.stringify({ refresh_token: 'refresh-1', access_token: 'a' }), calls: string[] = []) => ({
      spawn: fakeSpawn({ ...WHICH_GEMINI, [PROBE]: probe }, calls),
      fileExists: (path: string) => path === settingsPath || path === credentialsPath,
      readTextFile: (path: string) => (path === settingsPath ? settings : credentials()),
    });

    it('usable: the account probe signs in and stops for lack of a prompt (exit 42, no generation)', async () => {
      const calls: string[] = [];
      const agent = await detectOne('gemini', signedIn({ exitCode: 42, stderr: NO_INPUT }, undefined, calls));
      expect(agent).toMatchObject({ path: GEMINI_PATH, authenticated: true });
      expect(agent.reason).toContain('oauth-personal');
      expect(calls).toContain(PROBE);
      expect(calls.join(' ')).not.toMatch(/ -p |--prompt|yolo|bypass/);
    });

    it('ineligible tier: installed, credentials on disk, but Google refuses the account', async () => {
      const agent = await detectOne('gemini', signedIn({ exitCode: 42, stderr: INELIGIBLE }));
      expect(agent).toMatchObject({ path: GEMINI_PATH, authenticated: false });
      expect(agent.reason).toBe("Gemini is installed, but this Google account can't use it: This client is no longer supported for Gemini Code Assist for individuals. To continue using Gemini, please migrate to the Antigravity suite of products: https://antigravity.google");
    });

    it('not logged in: stale credentials whose sign-in fails are reported, not trusted', async () => {
      const agent = await detectOne('gemini', signedIn({ exitCode: 41, stderr: 'Error authenticating: Error: invalid_grant\n' }));
      expect(agent).toMatchObject({ path: GEMINI_PATH, authenticated: false, reason: 'Gemini is installed, but its Google sign-in failed: invalid_grant' });
    });

    it('a probe that exits with another error is not usable', async () => {
      const agent = await detectOne('gemini', signedIn({ exitCode: 1, stderr: 'boom\n' }));
      expect(agent).toMatchObject({ authenticated: false, reason: '`gemini (account check)` exited 1: boom' });
    });

    it('caches the probe per login and probes again when the refresh token changes', async () => {
      const calls: string[] = [];
      let refreshToken = 'refresh-1';
      const geminiAccountChecks = new Map();
      const overrides = { ...signedIn({ exitCode: 42, stderr: NO_INPUT }, () => JSON.stringify({ refresh_token: refreshToken }), calls), geminiAccountChecks };
      const [first, second] = await Promise.all([detectOne('gemini', overrides), detectOne('gemini', overrides)]);
      expect(await detectOne('gemini', overrides)).toEqual(first);
      expect(second).toEqual(first);
      expect(calls.filter(call => call === PROBE)).toHaveLength(1);
      refreshToken = 'refresh-2';
      const relogged = await detectOne('gemini', { ...overrides, spawn: fakeSpawn({ ...WHICH_GEMINI, [PROBE]: { exitCode: 42, stderr: NO_INPUT } }, calls) });
      expect(relogged.authenticated).toBe(true);
      expect(calls.filter(call => call === PROBE)).toHaveLength(2);
      expect([...geminiAccountChecks.keys()].join(' ')).not.toContain('refresh-');
    });

    it('retries a transient failed account probe without requiring a new login', async () => {
      const geminiAccountChecks = new Map();
      const failed = await detectOne('gemini', { ...signedIn({ exitCode: 1, stderr: 'network unavailable' }), geminiAccountChecks });
      expect(failed.authenticated).toBe(false);
      const retry = await detectOne('gemini', { ...signedIn({ exitCode: 42, stderr: NO_INPUT }), geminiAccountChecks });
      expect(retry.authenticated).toBe(true);
    });

    it('logged in through GEMINI_API_KEY', async () => {
      const agent = await detectOne('gemini', { spawn: fakeSpawn(WHICH_GEMINI), environment: { GEMINI_API_KEY: 'key' } });
      expect(agent).toMatchObject({ authenticated: true, reason: 'GEMINI_API_KEY is set' });
    });

    it('uses the selected Gemini home and keeps a relative profile stable when the probe changes cwd', async () => {
      const selected = resolve('owned-gemini-profile');
      const launches: any[] = [];
      const scripted = fakeSpawn({ ...WHICH_GEMINI, [PROBE]: { exitCode: 42, stderr: NO_INPUT } });
      const agent = await detectOne('gemini', {
        environment: { GEMINI_CLI_HOME: 'owned-gemini-profile' },
        fileExists: path => [join(selected, '.gemini', 'settings.json'), join(selected, '.gemini', 'oauth_creds.json')].includes(path),
        readTextFile: path => path.endsWith('settings.json') ? settings : JSON.stringify({ refresh_token: 'owned-token' }),
        spawn: ((command, args, options) => { launches.push({ command, options }); return scripted(command, args, options); }) as typeof spawn,
      });
      expect(agent.authenticated).toBe(true);
      expect(launches.find(call => call.command === GEMINI_PATH)?.options.env.GEMINI_CLI_HOME).toBe(selected);
    });

    it('does not borrow the default login when the selected Gemini profile has no credentials', async () => {
      const selected = resolve('owned-missing-profile');
      const agent = await detectOne('gemini', { ...signedIn({ exitCode: 42, stderr: NO_INPUT }),
        environment: { GEMINI_CLI_HOME: selected },
      });
      expect(agent.authenticated).toBe(false);
      expect(agent.reason).toContain(join(selected, '.gemini', 'settings.json'));
    });

    it('a slow `which gemini` is waited for and still reports logged in', async () => {
      const agent = await afterFakeDelay(() => detectOne('gemini', {
        spawn: fakeSpawn({ 'which gemini': { exitCode: 0, stdout: `${GEMINI_PATH}\n`, delayMs: 3_500 } }),
        environment: { GEMINI_API_KEY: 'key' },
      }));
      expect(agent).toMatchObject({ path: GEMINI_PATH, authenticated: true });
    });

    it('unreadable settings.json is reported, not thrown', async () => {
      const agent = await detectOne('gemini', {
        spawn: fakeSpawn(WHICH_GEMINI),
        fileExists: () => true,
        readTextFile: () => '{not json',
      });
      expect(agent.authenticated).toBe(false);
      expect(agent.reason).toContain('unreadable');
    });
  });
});

describe('OpenCode', () => {
  const jsonList = `${OPENCODE_PATH} auth list --format json`;
  const plainList = `${OPENCODE_PATH} auth list`;

  it.each([
    { connection: { type: 'credential', method: 'key', id: 'cred_test', label: 'default' }, row: 'Anthropic  default                     stored' },
    { connection: { type: 'env', name: 'ANTHROPIC_API_KEY' }, row: 'Anthropic  ANTHROPIC_API_KEY           environment' },
  ])('recognizes an OpenCode 2.x connection listed as "$row"', async ({ connection, row }) => {
    const calls: string[] = [];
    const stdout = JSON.stringify([{ id: 'anthropic', name: 'Anthropic', connections: [connection] }]);
    const agent = await detectUsableAgent('opencode', dependencies({
      spawn: fakeSpawn({
        ...WHICH_OPENCODE,
        [jsonList]: { exitCode: 0, stdout },
        [plainList]: { exitCode: 0, stdout: row + '\n' },
      }, calls),
    }));
    expect(agent).toEqual({
      id: 'opencode', path: OPENCODE_PATH, authenticated: true,
      reason: '`opencode auth list` reports a connected provider',
    });
    expect(calls).toEqual(['which opencode', jsonList]);
  });

  it.each(['[]', '[{"id":"anthropic","connections":[]}]'])('reports no login for %s', async stdout => {
    const agent = await detectOne('opencode', {
      spawn: fakeSpawn({ ...WHICH_OPENCODE, [jsonList]: { exitCode: 0, stdout } }),
    });
    expect(agent).toMatchObject({ authenticated: false, reason: '`opencode auth list` reports no credentials (run `opencode auth login`)' });
  });

  it('rejects malformed JSON without echoing provider data', async () => {
    const agent = await detectOne('opencode', {
      spawn: fakeSpawn({ ...WHICH_OPENCODE, [jsonList]: { exitCode: 0, stdout: '[{"name":"private provider"' } }),
    });
    expect(agent).toMatchObject({ authenticated: false, reason: '`opencode auth list --format json` returned invalid JSON' });
  });

  it('not installed', async () => {
    const agent = await detectOne('opencode', {});
    expect(agent).toEqual({ id: 'opencode', path: null, authenticated: false, reason: 'not installed: `opencode` is not on PATH' });
  });

  it('installed but no credential is stored', async () => {
    const agent = await detectOne('opencode', {
      spawn: fakeSpawn({ ...WHICH_OPENCODE, [`${OPENCODE_PATH} auth list`]: { exitCode: 0, stdout: '—  0 credentials\n' } }),
    });
    expect(agent).toEqual({
      id: 'opencode', path: OPENCODE_PATH, authenticated: false,
      reason: '`opencode auth list` reports no credentials (run `opencode auth login`)',
    });
  });

  it('reads the ANSI-styled credential count when the CLI rejects --format', async () => {
    const calls: string[] = [];
    const agent = await detectUsableAgent('opencode', dependencies({
      spawn: fakeSpawn({
        ...WHICH_OPENCODE,
        [jsonList]: { exitCode: 1, stdout: 'opencode auth list\n\nlist providers' },
        [plainList]: { exitCode: 0, stdout: '\u001b[90mCredentials\u001b[0m\n•  11 \u001b[90mapi\n—  1 credentials\n' },
      }, calls),
    }));
    expect(agent).toEqual({ id: 'opencode', path: OPENCODE_PATH, authenticated: true, reason: '`opencode auth list` reports 1 credential' });
    expect(calls).toEqual(['which opencode', jsonList, plainList]);
  });

  it('an unreadable auth list is not treated as logged in', async () => {
    const agent = await detectOne('opencode', {
      spawn: fakeSpawn({ ...WHICH_OPENCODE, [`${OPENCODE_PATH} auth list`]: { exitCode: 1, stderr: 'permission denied' } }),
    });
    expect(agent.authenticated).toBe(false);
    expect(agent.path).toBe(OPENCODE_PATH);
    expect(agent.reason).toContain('`opencode auth list` exited 1');
  });
});

describe('detectUsableAgent', () => {
  const settingsPath = join(HOME, '.gemini', 'settings.json');
  const credentialsPath = join(HOME, '.gemini', 'oauth_creds.json');
  const GEMINI_ACCOUNT_PROBE = [GEMINI_PATH, '--skip-trust', '-e', 'none', '--allowed-mcp-server-names', GEMINI_NO_MCP_SERVERS, '-o', 'json'].join(' ');
  /** All four installed and logged in so that each check runs commands; Gemini with a Google login, so its check starts the Gemini CLI. */
  const everyAgentInstalled = (calls: string[]) => dependencies({
    findClaudeExecutable: () => CLAUDE_PATH,
    readClaudeOAuthToken: async () => ({ kind: 'expired', reason: 'expired', expiresAt: 10 }),
    spawn: fakeSpawn({
      [`${CLAUDE_PATH} auth status --json`]: { exitCode: 0, stdout: '{"loggedIn": true, "authMethod": "claude.ai"}' },
      ...WHICH_CODEX,
      [`${CODEX_PATH} login status`]: { exitCode: 0, stderr: 'Logged in using ChatGPT\n' },
      ...WHICH_GEMINI,
      [GEMINI_ACCOUNT_PROBE]: { exitCode: 42, stderr: 'No input provided via stdin.\n' },
      ...WHICH_OPENCODE,
      [`${OPENCODE_PATH} auth list --format json`]: { exitCode: 0, stdout: '[{"connections":[{"type":"env","name":"ANTHROPIC_API_KEY"}]}]' },
    }, calls),
    fileExists: path => path === settingsPath || path === credentialsPath,
    readTextFile: path => JSON.stringify(path === settingsPath ? { security: { auth: { selectedType: 'oauth-personal' } } } : { refresh_token: 'refresh-1' }),
  });

  it("runs that agent's own check alone, so no other CLI starts, and answers what detectUsableAgents answers for it", async () => {
    const everyCall: string[] = [];
    const everyAgent = await detectUsableAgents(everyAgentInstalled(everyCall));
    // Checking all four starts the Gemini CLI for Gemini's account check.
    expect(everyCall).toContain(GEMINI_ACCOUNT_PROBE);
    const ownCommands: Record<UsableAgentId, string[]> = {
      'claude-code': [`${CLAUDE_PATH} auth status --json`],
      codex: ['which codex', `${CODEX_PATH} login status`],
      gemini: ['which gemini', GEMINI_ACCOUNT_PROBE],
      opencode: ['which opencode', `${OPENCODE_PATH} auth list --format json`],
    };
    expect(everyAgent.map(agent => agent.id)).toEqual(['claude-code', 'codex', 'gemini', 'opencode']);
    for (const agent of everyAgent) {
      const calls: string[] = [];
      expect(await detectUsableAgent(agent.id, everyAgentInstalled(calls))).toEqual(agent);
      expect(calls).toEqual(ownCommands[agent.id]);
    }
  });

  it('never throws: a check that throws is reported in plain words, with no path', async () => {
    const agent = await detectUsableAgent('claude-code', dependencies({
      findClaudeExecutable: () => CLAUDE_PATH,
      readClaudeOAuthToken: async () => { throw new Error('the login keychain could not be read'); },
    }));
    expect(agent).toEqual({ id: 'claude-code', path: null, authenticated: false, reason: 'check failed: the login keychain could not be read' });
  });
});

describe('runCommand', () => {
  it('waits for a slow command to finish instead of giving up', async () => {
    const result = await afterFakeDelay(() => runCommand(fakeSpawn({ 'codex login status': { exitCode: 0, stderr: 'Logged in', delayMs: 3_500 } }), 'codex', ['login', 'status']));
    expect(result).toMatchObject({ exitCode: 0, stderr: 'Logged in' });
  });

  it('reports a spawn error instead of rejecting', async () => {
    const result = await runCommand(fakeSpawn({ 'nope': { spawnError: 'spawn nope ENOENT' } }), 'nope', []);
    expect(result.spawnError?.message).toContain('ENOENT');
    expect(result.exitCode).toBeNull();
  });

  it('a spawn that throws synchronously is reported, not thrown', async () => {
    const throwingSpawn = (() => {
      throw new Error('EINVAL');
    }) as unknown as typeof spawn;
    const result = await runCommand(throwingSpawn, 'x', []);
    expect(result.spawnError?.message).toBe('EINVAL');
  });

  /** A child that prints `chunks` on stdout, then exits 0. */
  function printingSpawn(chunks: () => Iterable<string>): typeof spawn {
    return (() => {
      const child = new FakeChild();
      queueMicrotask(() => {
        for (const chunk of chunks()) child.stdout.emit('data', chunk);
        child.emit('close', 0);
      });
      return child;
    }) as unknown as typeof spawn;
  }

  it('bounds the accumulated stdout of a chatty child, keeps both ends, and marks and logs the cut', async () => {
    // A chatty or looping CLI would otherwise grow the retained string with
    // every chunk it prints, for as long as it runs (no time limit is an
    // owner rule). Past the cap the accumulation keeps the head and the tail
    // of the stream, says where the middle was dropped, and logs the cut once.
    const chunk = 'x'.repeat(1024 * 1024);
    const rounds = MAX_STREAM_CHARS / chunk.length + 8;
    const warn = spyOn(logger, 'warn').mockImplementation(() => {});
    try {
      const result = await runCommand(printingSpawn(function* () {
        yield 'HEAD-MARK' + chunk;
        for (let round = 0; round < rounds; round++) yield chunk;
        yield chunk + 'TAIL-MARK';
      }), 'chatty', ['run']);
      expect(result.exitCode).toBe(0);
      expect(result.stdoutTruncated).toBe(true);
      expect(result.stderrTruncated).toBe(false);
      expect(result.stdout.startsWith('HEAD-MARK')).toBe(true);
      expect(result.stdout.endsWith('TAIL-MARK')).toBe(true);
      const printed = (rounds + 2) * chunk.length + 'HEAD-MARK'.length + 'TAIL-MARK'.length;
      const marker = /\n\[([\d,]+) characters dropped here: stdout passed the [\d,]+ character capture cap\]\n/.exec(result.stdout);
      expect(marker).not.toBeNull();
      // Every character printed is either kept or counted as dropped.
      expect(result.stdout.length - marker![0].length + Number(marker![1].replace(/,/g, ''))).toBe(printed);
      // The kept text is at most the cap plus one chunk, plus the marker.
      expect(result.stdout.length - marker![0].length).toBeLessThanOrEqual(MAX_STREAM_CHARS + chunk.length + 'TAIL-MARK'.length);
      const cutWarnings = warn.mock.calls.filter(call => call[1] === 'Command output passed the capture cap; the middle is dropped');
      expect(cutWarnings.map(call => call[2])).toEqual([{ command: 'chatty', stream: 'stdout', capChars: MAX_STREAM_CHARS }]);
    } finally {
      warn.mockRestore();
    }
  });

  it('collects many small writes past the cap without re-copying the kept text on each one', async () => {
    // Re-slicing the kept text on every chunk costs the cap per chunk: about
    // 140,000 writes of 1 KiB here would copy terabytes and never finish
    // within the test timeout. The rolling tail costs one append per chunk.
    const chunk = 'y'.repeat(1024);
    const writes = MAX_STREAM_CHARS / chunk.length + 8192;
    const warn = spyOn(logger, 'warn').mockImplementation(() => {});
    try {
      const result = await runCommand(printingSpawn(function* () {
        for (let write = 0; write < writes; write++) yield chunk;
        yield 'LAST';
      }), 'chatty', ['run']);
      expect(result.stdoutTruncated).toBe(true);
      expect(result.stdout.endsWith(chunk + 'LAST')).toBe(true);
      // The tail keeps at least half the cap, so the end of the output is there to read.
      const tail = result.stdout.slice(result.stdout.indexOf('capture cap]\n') + 'capture cap]\n'.length);
      expect(tail.length).toBeGreaterThanOrEqual(MAX_STREAM_CHARS / 2);
    } finally {
      warn.mockRestore();
    }
  });

  it('never ends the kept head between the two halves of a surrogate pair', async () => {
    // The pair sits on the head's boundary: one code unit on each side.
    const warn = spyOn(logger, 'warn').mockImplementation(() => {});
    try {
      const result = await runCommand(printingSpawn(function* () {
        yield 'a'.repeat(MAX_STREAM_CHARS / 2 - 1) + '\u{1F642}';
        yield 'b'.repeat(MAX_STREAM_CHARS);
      }), 'chatty', ['run']);
      const head = result.stdout.slice(0, result.stdout.indexOf('\n['));
      expect(head).toBe('a'.repeat(MAX_STREAM_CHARS / 2 - 1));
    } finally {
      warn.mockRestore();
    }
  });

  it('leaves small output complete and unflagged', async () => {
    const result = await runCommand(fakeSpawn({ 'small tool': { exitCode: 0, stdout: 'ok' } }), 'small', ['tool']);
    expect(result.stdout).toBe('ok');
    expect(result.stdoutTruncated).toBe(false);
    expect(result.stderrTruncated).toBe(false);
  });
});