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

26.7 KB
Raw Blame
import { afterEach, describe, expect, it } from 'bun:test';
import { spawn, type ChildProcess } from 'child_process';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import path from 'path';
import { OBSERVER_SESSIONS_DIR } from '../../src/shared/paths.js';
import type { ProcessGroupMember } from '../../src/shared/kill-process-tree.js';
import {
  createProcessRegistry,
  isPidAlive,
  processGroupHasProcessesThatHaveNotExited,
  normalizeSpawnSdkArgs,
  normalizeSpawnSdkCwd,
  spawnSdkProcess,
  getProcessRegistry,
  waitForSlot,
  getParkedSlotWaiterCount,
  isSessionParkedForSlot,
  getReservedSlotCount,
  setRegistryDegradedReporter,
  type SlotReservation,
} from '../../src/supervisor/process-registry.js';
import { guardSharedProcessRegistrySingleton } from './process-registry-singleton-guard.js';

const TEST_SESSION_ID = process.pid;
const SDK_CWD_PROBE = 'console.log(process.cwd())';
const EXPECTED_SDK_CWD = path.join(OBSERVER_SESSIONS_DIR, String(TEST_SESSION_ID));
const PARENT_PATH = '..';
const DIRECTORY_COLLISION = 'directory collision';

function assertIsolatedObserverSessionsDir(): void {
  const relativePath = path.relative(tmpdir(), OBSERVER_SESSIONS_DIR);
  if (relativePath === PARENT_PATH || relativePath.startsWith(`${PARENT_PATH}${path.sep}`) || path.isAbsolute(relativePath)) {
    throw new Error(`Refusing to mutate non-test observer directory: ${OBSERVER_SESSIONS_DIR}`);
  }
}

// Registered at true file top level (outside every describe below), NOT
// nested inside describe('waitForSlot / parked waiters (#2756)', ...): bun
// (like Jest/Mocha) runs afterEach hooks inner-scope-first, outer-scope-last
// (LIFO), regardless of source order — so an outer-scope guard is
// guaranteed to run its "after" check only once that describe's own local
// `afterEach` cleanup (nested one level in) has already finished, no matter
// where within the describe that local afterEach is declared. Its
// beforeEach half runs outer-first (before any nested describe's own
// beforeEach or test body), which is exactly what a "before" check needs.
guardSharedProcessRegistrySingleton('process-registry.test.ts');

function makeTempDir(): string {
  return mkdtempSync(path.join(tmpdir(), 'claude-mem-supervisor-'));
}

const tempDirs: string[] = [];

function makeRegistry() {
  const tempDir = makeTempDir();
  tempDirs.push(tempDir);
  const registryPath = path.join(tempDir, 'supervisor.json');
  return { registry: createProcessRegistry(registryPath), registryPath };
}

describe('supervisor ProcessRegistry', () => {
  afterEach(() => {
    while (tempDirs.length > 0) {
      const dir = tempDirs.pop();
      if (dir) {
        rmSync(dir, { recursive: true, force: true });
      }
    }
  });

  describe('isPidAlive', () => {
    it.each([
      [process.pid, true],
      [2147483647, false],
      [-1, false],
      [3.14, false],
    ] as const)('reports liveness of PID %s as %s', (pid, expected) => {
      expect(isPidAlive(pid)).toBe(expected);
    });
  });

  describe('persistence', () => {
    it('persists entries to disk and reloads them on initialize', () => {
      const { registry: registry1, registryPath } = makeRegistry();
      registry1.register('worker:1', {
        pid: process.pid,
        type: 'worker',
        startedAt: '2026-03-15T00:00:00.000Z'
      });

      expect(existsSync(registryPath)).toBe(true);
      const diskData = JSON.parse(readFileSync(registryPath, 'utf-8'));
      expect(diskData.processes['worker:1']).toBeDefined();

      const registry2 = createProcessRegistry(registryPath);
      registry2.initialize();
      const records = registry2.getAll();
      expect(records).toHaveLength(1);
      expect(records[0]?.id).toBe('worker:1');
      expect(records[0]?.pid).toBe(process.pid);
    });

    it('prunes dead processes on initialize', () => {
      const { registry, registryPath } = makeRegistry();

      writeFileSync(registryPath, JSON.stringify({
        processes: {
          alive: {
            pid: process.pid,
            type: 'worker',
            startedAt: '2026-03-15T00:00:00.000Z'
          },
          dead: {
            pid: 2147483647,
            type: 'mcp',
            startedAt: '2026-03-15T00:00:01.000Z'
          }
        }
      }));

      registry.initialize();

      const records = registry.getAll();
      expect(records).toHaveLength(1);
      expect(records[0]?.id).toBe('alive');
      expect(existsSync(registryPath)).toBe(true);
    });

    it('degrades to in-memory state instead of throwing when the registry cannot be written', () => {
      const tempDir = makeTempDir();
      tempDirs.push(tempDir);
      mkdirSync(tempDir, { recursive: true });
      // A regular file where the registry's parent directory should be makes
      // every write fail (ENOTDIR), standing in for an unwritable data dir.
      const blocker = path.join(tempDir, 'blocker');
      writeFileSync(blocker, 'not a directory');
      const registryPath = path.join(blocker, 'supervisor.json');

      const registry = createProcessRegistry(registryPath);

      expect(() => registry.register('worker:1', {
        pid: process.pid,
        type: 'worker',
        startedAt: '2026-03-15T00:00:00.000Z'
      })).not.toThrow();

      expect(existsSync(registryPath)).toBe(false);
      const records = registry.getAll();
      expect(records).toHaveLength(1);
      expect(records[0]?.id).toBe('worker:1');
    });

    it('reports a degraded episode once across repeated failed writes', () => {
      const tempDir = makeTempDir();
      tempDirs.push(tempDir);
      mkdirSync(tempDir, { recursive: true });
      const blocker = path.join(tempDir, 'blocker');
      writeFileSync(blocker, 'not a directory');
      const registryPath = path.join(blocker, 'supervisor.json');

      const categories: string[] = [];
      setRegistryDegradedReporter(({ errorCategory }) => categories.push(errorCategory));
      try {
        const registry = createProcessRegistry(registryPath);
        registry.register('worker:1', {
          pid: process.pid,
          type: 'worker',
          startedAt: '2026-03-15T00:00:00.000Z'
        });
        registry.register('worker:2', {
          pid: process.pid,
          type: 'worker',
          startedAt: '2026-03-15T00:00:01.000Z'
        });

        expect(categories).toHaveLength(1);
        expect(categories[0]).toBe('ENOTDIR');
      } finally {
        setRegistryDegradedReporter(null);
      }
    });

    it('handles corrupted registry file gracefully', () => {
      const { registry, registryPath } = makeRegistry();

      writeFileSync(registryPath, '{ not valid json!!!');

      registry.initialize();

      expect(registry.getAll()).toHaveLength(0);
    });
  });

  describe('register and unregister', () => {
    it('unregister removes an entry', () => {
      const { registry } = makeRegistry();

      registry.register('sdk:1', {
        pid: process.pid,
        type: 'sdk',
        startedAt: '2026-03-15T00:00:00.000Z'
      });
      expect(registry.getAll()).toHaveLength(1);

      registry.unregister('sdk:1');
      expect(registry.getAll()).toHaveLength(0);
    });

    it('unregister is a no-op for unknown IDs', () => {
      const { registry } = makeRegistry();

      registry.register('sdk:1', {
        pid: process.pid,
        type: 'sdk',
        startedAt: '2026-03-15T00:00:00.000Z'
      });

      registry.unregister('nonexistent');
      expect(registry.getAll()).toHaveLength(1);
    });
  });

  describe('getAll', () => {
    it('returns records sorted by startedAt ascending', () => {
      const { registry } = makeRegistry();

      registry.register('newest', {
        pid: process.pid,
        type: 'sdk',
        startedAt: '2026-03-15T00:00:02.000Z'
      });
      registry.register('oldest', {
        pid: process.pid,
        type: 'worker',
        startedAt: '2026-03-15T00:00:00.000Z'
      });
      registry.register('middle', {
        pid: process.pid,
        type: 'mcp',
        startedAt: '2026-03-15T00:00:01.000Z'
      });

      const records = registry.getAll();
      expect(records).toHaveLength(3);
      expect(records[0]?.id).toBe('oldest');
      expect(records[1]?.id).toBe('middle');
      expect(records[2]?.id).toBe('newest');
    });
  });

  describe('getBySession', () => {
    it('filters records by session id', () => {
      const { registry } = makeRegistry();

      registry.register('sdk:1', {
        pid: process.pid,
        type: 'sdk',
        sessionId: 42,
        startedAt: '2026-03-15T00:00:00.000Z'
      });
      registry.register('sdk:2', {
        pid: process.pid,
        type: 'sdk',
        sessionId: 'other',
        startedAt: '2026-03-15T00:00:01.000Z'
      });

      const records = registry.getBySession(42);
      expect(records).toHaveLength(1);
      expect(records[0]?.id).toBe('sdk:1');
    });

    it('returns empty array when no processes match the session', () => {
      const { registry } = makeRegistry();

      registry.register('sdk:1', {
        pid: process.pid,
        type: 'sdk',
        sessionId: 42,
        startedAt: '2026-03-15T00:00:00.000Z'
      });

      expect(registry.getBySession(999)).toHaveLength(0);
    });

    it('matches string and numeric session IDs by string comparison', () => {
      const { registry } = makeRegistry();

      registry.register('sdk:1', {
        pid: process.pid,
        type: 'sdk',
        sessionId: '42',
        startedAt: '2026-03-15T00:00:00.000Z'
      });

      expect(registry.getBySession(42)).toHaveLength(1);
    });
  });

  describe('pruneDeadEntries', () => {
    it('removes entries with dead PIDs and preserves live ones', () => {
      const { registry } = makeRegistry();

      registry.register('alive', {
        pid: process.pid,
        type: 'worker',
        startedAt: '2026-03-15T00:00:00.000Z'
      });
      registry.register('dead', {
        pid: 2147483647,
        type: 'mcp',
        startedAt: '2026-03-15T00:00:01.000Z'
      });

      const removed = registry.pruneDeadEntries();
      expect(removed).toBe(1);
      expect(registry.getAll()).toHaveLength(1);
      expect(registry.getAll()[0]?.id).toBe('alive');
    });

    it('returns 0 when all entries are alive', () => {
      const { registry } = makeRegistry();

      registry.register('alive', {
        pid: process.pid,
        type: 'worker',
        startedAt: '2026-03-15T00:00:00.000Z'
      });

      const removed = registry.pruneDeadEntries();
      expect(removed).toBe(0);
      expect(registry.getAll()).toHaveLength(1);
    });

    it('persists changes to disk after pruning', () => {
      const { registry, registryPath } = makeRegistry();

      registry.register('dead', {
        pid: 2147483647,
        type: 'mcp',
        startedAt: '2026-03-15T00:00:01.000Z'
      });

      registry.pruneDeadEntries();

      const diskData = JSON.parse(readFileSync(registryPath, 'utf-8'));
      expect(Object.keys(diskData.processes)).toHaveLength(0);
    });
  });

  describe('clear', () => {
    it('removes all entries', () => {
      const { registry, registryPath } = makeRegistry();

      registry.register('sdk:1', {
        pid: process.pid,
        type: 'sdk',
        startedAt: '2026-03-15T00:00:00.000Z'
      });
      registry.register('sdk:2', {
        pid: process.pid,
        type: 'sdk',
        startedAt: '2026-03-15T00:00:01.000Z'
      });

      expect(registry.getAll()).toHaveLength(2);

      registry.clear();
      expect(registry.getAll()).toHaveLength(0);

      const diskData = JSON.parse(readFileSync(registryPath, 'utf-8'));
      expect(Object.keys(diskData.processes)).toHaveLength(0);
    });
  });

  describe('normalizeSpawnSdkArgs', () => {
    it('appends explicit extra args after SDK args', () => {
      expect(normalizeSpawnSdkArgs(['--print', 'json'], ['--no-session-persistence'])).toEqual([
        '--print',
        'json',
        '--no-session-persistence',
      ]);
    });

    it('folds an empty SDK value into a single --flag= token instead of dropping the flag', () => {
      // `tools: []` arrives as `--tools ''`. Dropping the pair would give the
      // CLI its default tool set; `--tools=` keeps the empty value and survives
      // cmd.exe, which drops empty arguments.
      expect(normalizeSpawnSdkArgs([
        '--tools',
        '',
        '--resume',
        'session-123',
      ], ['--no-session-persistence'])).toEqual([
        '--tools=',
        '--resume',
        'session-123',
        '--no-session-persistence',
      ]);
    });

    it('drops an empty positional argument and never re-folds a --flag=value token', () => {
      expect(normalizeSpawnSdkArgs(['--print', 'json', ''])).toEqual(['--print', 'json']);
      expect(normalizeSpawnSdkArgs(['--setting-sources=', ''])).toEqual(['--setting-sources=']);
    });
  });

  describe('normalizeSpawnSdkCwd', () => {
    it('jails SDK subprocess cwd to the observer sessions directory (#3357)', () => {
      expect(normalizeSpawnSdkCwd(TEST_SESSION_ID)).toBe(EXPECTED_SDK_CWD);
    });

    it('applies the observer sessions cwd to direct SDK spawns', async () => {
      assertIsolatedObserverSessionsDir();
      tempDirs.push(EXPECTED_SDK_CWD);
      const projectDir = makeTempDir();
      tempDirs.push(projectDir);
      mkdirSync(projectDir, { recursive: true });

      const result = spawnSdkProcess(TEST_SESSION_ID, {
        command: process.execPath,
        args: ['--eval', SDK_CWD_PROBE],
        cwd: projectDir,
      });

      expect(result).not.toBeNull();
      try {
        const output = await new Response(result!.process.stdout).text();
        expect(output.trim()).toBe(realpathSync(EXPECTED_SDK_CWD));
      } finally {
        try { result!.process.kill('SIGKILL'); } catch { /* already exited */ }
        await new Promise<void>((resolve) => {
          if (result!.process.exitCode !== null) {
            resolve();
            return;
          }
          result!.process.once('exit', () => resolve());
        });
      }
    });

    it('returns null when the observer session directory cannot be created', () => {
      assertIsolatedObserverSessionsDir();
      mkdirSync(OBSERVER_SESSIONS_DIR, { recursive: true });
      tempDirs.push(EXPECTED_SDK_CWD);
      writeFileSync(EXPECTED_SDK_CWD, DIRECTORY_COLLISION);

      expect(spawnSdkProcess(TEST_SESSION_ID, {
        command: process.execPath,
        args: ['--eval', SDK_CWD_PROBE],
      })).toBeNull();
    });
  });

  describe('reapSession', () => {
    it('unregisters dead processes for the given session', async () => {
      const { registry } = makeRegistry();

      registry.register('sdk:99:50001', {
        pid: 2147483640,
        type: 'sdk',
        sessionId: 99,
        startedAt: '2026-03-15T00:00:00.000Z'
      });
      registry.register('mcp:99:50002', {
        pid: 2147483641,
        type: 'mcp',
        sessionId: 99,
        startedAt: '2026-03-15T00:00:01.000Z'
      });

      registry.register('sdk:100:50003', {
        pid: process.pid,
        type: 'sdk',
        sessionId: 100,
        startedAt: '2026-03-15T00:00:02.000Z'
      });

      const reaped = await registry.reapSession(99);
      expect(reaped).toBe(2);

      expect(registry.getBySession(99)).toHaveLength(0);
      expect(registry.getBySession(100)).toHaveLength(1);
    });

    it('returns 0 when no processes match the session', async () => {
      const { registry } = makeRegistry();

      registry.register('sdk:1', {
        pid: process.pid,
        type: 'sdk',
        sessionId: 42,
        startedAt: '2026-03-15T00:00:00.000Z'
      });

      const reaped = await registry.reapSession(999);
      expect(reaped).toBe(0);

      expect(registry.getAll()).toHaveLength(1);
    });
  });
});

/**
 * #2756 — these tests exercise waitForSlot/getParkedSlotWaiterCount/
 * isSessionParkedForSlot against the REAL module singleton (getProcessRegistry()),
 * because waitForSlot is hardcoded to that singleton rather than accepting an
 * injected registry. This is safe re: data isolation: tests/preload.ts pins
 * CLAUDE_MEM_DATA_DIR to a fresh temp dir for the whole `bun test` run before
 * any module loads. It is NOT the only file touching this singleton's
 * in-memory state, though — tests/worker/http/routes/
 * session-routes-provider-switch.test.ts and tests/worker/http/routes/
 * data-routes-processing-status.test.ts both register real 'sdk'-typed
 * entries and drive real waitForSlot/slotWaiters against this exact same
 * process-global module, so a leak here can affect those files (and vice
 * versa) within the same `bun test` process — see
 * process-registry-singleton-guard.ts for the mechanism and the isolation
 * guard installed above (at file top level, on purpose — see its comment).
 * Every fake 'sdk' entry registered below is still unregistered in
 * afterEach on top of that guard.
 */
describe('waitForSlot / parked waiters (#2756)', () => {
  const registry = getProcessRegistry();
  const registeredIds: string[] = [];
  // waitForSlot resolves to a SlotReservation (#3287, upstream since this
  // fork's base) rather than void — every reservation granted below is
  // captured here and released in afterEach so the reservedSlots counter it
  // holds doesn't leak into getActiveSdkCount() for a later test in this
  // file, or for another file sharing this singleton in the same `bun test`
  // process (the guard above only checks parked waiters and registry 'sdk'
  // entries, not reservedSlots).
  const grantedReservations: SlotReservation[] = [];

  function registerFakeSdk(sessionId: string | number): string {
    const id = `sdk:test-${sessionId}:${Math.random().toString(36).slice(2)}`;
    // pid=process.pid is always alive per isPidAlive, so pruneDeadEntries()
    // never removes these out from under a test.
    registry.register(id, {
      pid: process.pid,
      type: 'sdk',
      sessionId,
      startedAt: new Date().toISOString(),
    });
    registeredIds.push(id);
    return id;
  }

  afterEach(() => {
    while (grantedReservations.length > 0) {
      grantedReservations.pop()!.release();
    }
    while (registeredIds.length > 0) {
      const id = registeredIds.pop();
      if (id) registry.unregister(id);
    }
  });

  it('parked waiter is released by a settings raise, without waiting the real recheck interval', async () => {
    registerFakeSdk('occupant-1');
    registerFakeSdk('occupant-2');

    let currentMax = 2;
    const parkedPromise = waitForSlot(() => currentMax, undefined, 'sess-settings-raise');

    // The Promise executor runs synchronously before any await, so the push
    // onto slotWaiters is already visible here.
    expect(isSessionParkedForSlot('sess-settings-raise')).toBe(true);
    expect(getParkedSlotWaiterCount()).toBe(1);

    // Raise the limit — this alone must NOT release the waiter (nothing has
    // poked the queue yet); the (a) fix is that the NEXT recheck observes it.
    currentMax = 3;
    expect(isSessionParkedForSlot('sess-settings-raise')).toBe(true);

    // Poke a recheck deterministically, without waiting the real 5s
    // SLOT_RECHECK_INTERVAL_MS: register+unregister a throwaway 3rd 'sdk'
    // entry. unregister() calls notifySlotAvailable() synchronously, and by
    // then the throwaway is already removed, so the recheck sees count=2 < 3.
    const throwawayId = registerFakeSdk('throwaway');
    registry.unregister(throwawayId);

    grantedReservations.push(await parkedPromise);

    expect(isSessionParkedForSlot('sess-settings-raise')).toBe(false);
    expect(getParkedSlotWaiterCount()).toBe(0);
  });

  it('releases parked waiters in FIFO order as slots free up one at a time', async () => {
    const occupantA = registerFakeSdk('occ-a');
    const occupantB = registerFakeSdk('occ-b');
    const currentMax = 2;

    const resolvedOrder: string[] = [];
    const waiterFirst = waitForSlot(() => currentMax, undefined, 'sess-first').then((reservation) => {
      grantedReservations.push(reservation);
      resolvedOrder.push('first');
    });
    const waiterSecond = waitForSlot(() => currentMax, undefined, 'sess-second').then((reservation) => {
      grantedReservations.push(reservation);
      resolvedOrder.push('second');
    });

    expect(isSessionParkedForSlot('sess-first')).toBe(true);
    expect(isSessionParkedForSlot('sess-second')).toBe(true);
    expect(getParkedSlotWaiterCount()).toBe(2);

    // Free exactly one slot: only the FRONT waiter (first) should resolve —
    // the second waiter's own recheck hasn't been poked yet.
    registry.unregister(occupantA);
    await waiterFirst;

    expect(resolvedOrder).toEqual(['first']);
    expect(isSessionParkedForSlot('sess-first')).toBe(false);
    expect(isSessionParkedForSlot('sess-second')).toBe(true);
    expect(getParkedSlotWaiterCount()).toBe(1);

    // Free the second slot: the remaining waiter (second) resolves.
    registry.unregister(occupantB);
    await waiterSecond;

    expect(resolvedOrder).toEqual(['first', 'second']);
    expect(getParkedSlotWaiterCount()).toBe(0);
  });

  it('rejects immediately when the registry is already over the hard cap, without parking', async () => {
    for (let i = 0; i < 11; i++) {
      registerFakeSdk(`hardcap-${i}`);
    }

    await expect(waitForSlot(1, undefined, 'sess-hardcap')).rejects.toThrow(/Hard cap exceeded/);
    expect(isSessionParkedForSlot('sess-hardcap')).toBe(false);
    expect(getParkedSlotWaiterCount()).toBe(0);
  });

  // #5376: with CLAUDE_MEM_MAX_CONCURRENT_AGENTS=10 a full pool reached the
  // hard cap, so starts threw and the session discarded its queued messages.
  it('parks (does not throw) when a limit of 10 fills the pool to the hard cap', async () => {
    const occupants: string[] = [];
    for (let i = 0; i < 10; i++) {
      occupants.push(registerFakeSdk(`full-${i}`));
    }

    const parked = waitForSlot(10, undefined, 'sess-full-pool');
    expect(isSessionParkedForSlot('sess-full-pool')).toBe(true);
    expect(getParkedSlotWaiterCount()).toBe(1);

    registry.unregister(occupants[0]);
    grantedReservations.push(await parked);
    expect(isSessionParkedForSlot('sess-full-pool')).toBe(false);
    expect(getReservedSlotCount()).toBe(1);
  });

  it('treats a limit above the hard cap as the hard cap', async () => {
    for (let i = 0; i < 9; i++) {
      registerFakeSdk(`over-${i}`);
    }

    // 9 in use, limit 15: one slot left under the cap of 10.
    grantedReservations.push(await waitForSlot(15, undefined, 'sess-ninth'));
    expect(isSessionParkedForSlot('sess-ninth')).toBe(false);

    // Now 10 (9 + 1 reservation): the next caller waits instead of spawning an 11th.
    const parked = waitForSlot(15, undefined, 'sess-eleventh');
    expect(isSessionParkedForSlot('sess-eleventh')).toBe(true);

    grantedReservations.pop()!.release();
    grantedReservations.push(await parked);
    expect(getReservedSlotCount()).toBe(1);
  });

  it('resolves immediately (no parking) when the active count is already under the limit', async () => {
    registerFakeSdk('solo-occupant');

    grantedReservations.push(await waitForSlot(() => 5, undefined, 'sess-not-parked'));

    expect(isSessionParkedForSlot('sess-not-parked')).toBe(false);
    expect(getParkedSlotWaiterCount()).toBe(0);
  });
});

const describeOnMacOsAndLinux = process.platform === 'win32' ? describe.skip : describe;

describeOnMacOsAndLinux('processGroupHasProcessesThatHaveNotExited, with the reads of the process table passed in', () => {
  /** A real process group, so kill(2) finds it and the reads passed in decide. Ended after each test. */
  let groupLeader: ChildProcess | null = null;
  afterEach(() => {
    groupLeader?.kill('SIGKILL');
    groupLeader = null;
  });

  /** Starts a process in a group of its own (detached), and returns that group's id, which is the process's own. */
  function idOfARunningProcessGroup(): number {
    groupLeader = spawn('sleep', ['30'], { detached: true, stdio: 'ignore' });
    return groupLeader.pid!;
  }

  /** Reads of the process table that answer, in turn, each list given, and remember which group each was asked about. */
  function readsAnswering(...answers: ProcessGroupMember[][]) {
    const groupsAskedAbout: number[] = [];
    const read = async (processGroupId: number) => {
      groupsAskedAbout.push(processGroupId);
      const answer = answers[groupsAskedAbout.length - 1];
      if (!answer) throw new Error(`read ${groupsAskedAbout.length} was not expected`);
      return answer;
    };
    return { read, groupsAskedAbout };
  }

  const parentThatExited: ProcessGroupMember = { pid: 990001, hasExited: true };

  it('finds none left when a second read lists the same processes, all exited', async () => {
    const processGroupId = idOfARunningProcessGroup();
    const { read, groupsAskedAbout } = readsAnswering([parentThatExited], [parentThatExited]);

    expect(await processGroupHasProcessesThatHaveNotExited(processGroupId, read)).toBe(false);
    expect(groupsAskedAbout).toEqual([processGroupId, processGroupId]);
  });

  it('finds the child a first read missed, which its parent started before exiting between the list and its own line', async () => {
    const processGroupId = idOfARunningProcessGroup();
    const { read } = readsAnswering([parentThatExited], [parentThatExited, { pid: 990002, hasExited: false }]);

    expect(await processGroupHasProcessesThatHaveNotExited(processGroupId, read)).toBe(true);
  });

  it('counts a process the first read missed even when the second read shows it has exited too', async () => {
    const processGroupId = idOfARunningProcessGroup();
    const { read } = readsAnswering([parentThatExited], [parentThatExited, { pid: 990002, hasExited: true }]);

    expect(await processGroupHasProcessesThatHaveNotExited(processGroupId, read)).toBe(true);
  });

  it('does not believe a second read that lists nothing: the next look asks kill(2) again', async () => {
    const processGroupId = idOfARunningProcessGroup();
    const { read } = readsAnswering([parentThatExited], []);

    expect(await processGroupHasProcessesThatHaveNotExited(processGroupId, read)).toBe(true);
  });

  it('reads the table once when it lists a process that has not exited', async () => {
    const processGroupId = idOfARunningProcessGroup();
    const { read, groupsAskedAbout } = readsAnswering([parentThatExited, { pid: 990002, hasExited: false }]);

    expect(await processGroupHasProcessesThatHaveNotExited(processGroupId, read)).toBe(true);
    expect(groupsAskedAbout).toHaveLength(1);
  });

  it('reads no table when kill(2) finds no process left in the group', async () => {
    const processGroupId = idOfARunningProcessGroup();
    const leaderHasExited = new Promise(resolve => groupLeader!.once('exit', resolve));
    groupLeader!.kill('SIGKILL');
    await leaderHasExited;
    const { read, groupsAskedAbout } = readsAnswering();

    expect(await processGroupHasProcessesThatHaveNotExited(processGroupId, read)).toBe(false);
    expect(groupsAskedAbout).toHaveLength(0);
  });
});