Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

25.6 KB
Raw Blame
import { type ChildProcess, execFileSync, spawn, spawnSync } from 'node:child_process';
import {
  chmodSync,
  existsSync,
  mkdirSync,
  mkdtempSync,
  readFileSync,
  realpathSync,
  rmSync,
  writeFileSync,
} from 'node:fs';
import { connect } from 'node:net';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { getMachineId } from '@inkeep/open-knowledge-server';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { afterAll, beforeAll, describe, expect, onTestFinished, test } from 'vitest';
import {
  legacyServerLock,
  lockWrittenBeforeProcessStarted,
  ownedProcessHasExited,
  startOwnedProcess,
  stopOwnedProcess,
} from '../../../../test-support/owned-process.test-helper.ts';
import {
  type CommandResult,
  spawnUnderOwnerLifeline,
} from '../../../../test-support/owner-lifeline.ts';
import { installPackedCli } from './packed-install.test-helper';

const HERE = dirname(fileURLToPath(import.meta.url));
const CLI_PKG_DIR = resolve(HERE, '..', '..');
const WORKSPACE_DIST_CLI = join(CLI_PKG_DIR, 'dist', 'cli.mjs');
const NODE = process.execPath.includes('bun') ? 'node' : process.execPath;
const SUT_MODE = process.env.OK_E2E_SUT === 'workspace' ? 'workspace' : 'packed';
const LOCKED_PACKED_INSTALL =
  SUT_MODE === 'packed' && (process.env.OK_CLI_E2E_INSTALL_MODE ?? 'locked') === 'locked';
const HERMETIC_ENV = { OK_BUNDLE_PROXY: '0' } as const;
const START_PORT = Number(process.env.OK_E2E_PORT ?? 13581);

type Acquisition = Awaited<ReturnType<typeof installPackedCli>>['acquisition'];

interface Harness {
  cliPath: string;
  binShim: string | null;
  installPrefix: string | null;
  packDest: string | null;
  acquisition: Acquisition;
  contentDir: string;
  lockPath: string;
  server: ChildProcess | null;
}

const H: Harness = {
  cliPath: '',
  binShim: null,
  installPrefix: null,
  packDest: null,
  acquisition: null,
  contentDir: '',
  lockPath: '',
  server: null,
};

function progressOf(acquisition: Acquisition, status: string) {
  return acquisition?.progress.get(status) ?? new Set<string>();
}

interface CliRunResult {
  status: number | null;
  signal: NodeJS.Signals | null;
  stdout: string;
  stderr: string;
}

function runOk(
  args: string[],
  opts: { cwd?: string; timeoutMs?: number; env?: NodeJS.ProcessEnv } = {},
): CliRunResult {
  const r = spawnSync(NODE, [H.cliPath, ...args], {
    cwd: opts.cwd ?? H.contentDir,
    timeout: opts.timeoutMs ?? 30_000,
    encoding: 'utf8',
    env: { ...process.env, ...HERMETIC_ENV, ...opts.env },
  });
  return {
    status: r.status,
    signal: r.signal,
    stdout: r.stdout ?? '',
    stderr: r.stderr ?? '',
  };
}

async function waitFor(
  predicate: () => boolean | Promise<boolean>,
  { timeoutMs = 30_000, intervalMs = 250 } = {},
): Promise<boolean> {
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    if (await predicate()) return true;
    await new Promise((r) => setTimeout(r, intervalMs));
  }
  return false;
}

function tcpConnect(host: string, port: number, timeoutMs: number): Promise<boolean> {
  return new Promise((res) => {
    const sock = connect({ host, port });
    const done = (ok: boolean) => {
      sock.destroy();
      res(ok);
    };
    sock.setTimeout(timeoutMs);
    sock.once('connect', () => done(true));
    sock.once('timeout', () => done(false));
    sock.once('error', () => done(false));
  });
}

async function tcpReachable(port: number, timeoutMs = 2000): Promise<boolean> {
  const [v4, v6] = await Promise.all([
    tcpConnect('127.0.0.1', port, timeoutMs),
    tcpConnect('::1', port, timeoutMs),
  ]);
  return v4 || v6;
}

function readLockPort(): number | null {
  if (!existsSync(H.lockPath)) return null;
  try {
    const meta = JSON.parse(readFileSync(H.lockPath, 'utf8')) as { port?: number };
    return typeof meta.port === 'number' ? meta.port : null;
  } catch {
    return null;
  }
}

const SERVER_INFO_RECORD = /^\[\d{2}:\d{2}:\d{2}\] INFO \((?:project-git|skills)\): /m;

function outputOf(result: CliRunResult): string {
  return `stdout:\n${result.stdout}\nstderr:\n${result.stderr}`;
}

function isolatedCliRunner(prefix: string) {
  const root = realpathSync(mkdtempSync(join(tmpdir(), prefix)));
  const fakeHome = join(root, 'home');
  const gitHome = join(root, 'git-home');
  let ownedRun: ReturnType<typeof spawnUnderOwnerLifeline> | undefined;
  let outputClosed: Promise<void> = Promise.resolve();
  let commandResult: Promise<CommandResult | null> = Promise.resolve(null);
  onTestFinished(async () => {
    if (
      ownedRun !== undefined &&
      ownedRun.child.exitCode === null &&
      ownedRun.child.signalCode === null &&
      !ownedRun.child.stdin.destroyed
    ) {
      ownedRun.child.stdin.end();
    }
    await outputClosed;
    await commandResult;
    rmSync(root, { recursive: true, force: true });
  });
  mkdirSync(fakeHome, { recursive: true });
  mkdirSync(gitHome, { recursive: true });
  const fixtureGitEnv: NodeJS.ProcessEnv = {
    ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_'))),
    HOME: gitHome,
    GIT_CONFIG_GLOBAL: '/dev/null',
    GIT_CONFIG_SYSTEM: '/dev/null',
    GIT_CONFIG_NOSYSTEM: '1',
  };
  const fixtureGit = (args: string[], cwd = root) => {
    execFileSync('git', args, { cwd, env: fixtureGitEnv, stdio: 'ignore' });
  };
  const ghShim = join(root, 'gh');
  writeFileSync(ghShim, '#!/bin/sh\nprintf token-for-e2e\n', 'utf8');
  chmodSync(ghShim, 0o755);
  mkdirSync(join(fakeHome, '.ok'), { recursive: true });
  writeFileSync(
    join(fakeHome, '.ok', 'skill-state.yml'),
    'schema: 1\nbundles:\n  open-knowledge-discovery:\n    enabled: true\n    decidedAt: 2026-01-01T00:00:00.000Z\n',
    'utf8',
  );

  const runCli = async (
    args: string[],
    cwd: string,
    scenarioEnv: NodeJS.ProcessEnv = {},
  ): Promise<CliRunResult> => {
    const owned = spawnUnderOwnerLifeline(NODE, [H.cliPath, '--log-level', 'info', ...args], {
      cwd,
      env: {
        ...Object.fromEntries(
          Object.entries(fixtureGitEnv).filter(([key]) => !key.startsWith('GIT_')),
        ),
        HOME: fakeHome,
        XDG_CONFIG_HOME: join(fakeHome, '.config'),
        PATH: `${root}:${fixtureGitEnv.PATH ?? ''}`,
        DBUS_SESSION_BUS_ADDRESS: '',
        XDG_RUNTIME_DIR: '',
        DO_NOT_TRACK: '1',
        LOG_LEVEL: 'info',
        OK_CONSOLE_LEVEL: 'info',
        GIT_CONFIG_NOSYSTEM: '1',
        ...scenarioEnv,
      },
    });
    ownedRun = owned;
    let stdout = '';
    let stderr = '';
    owned.child.stdout.setEncoding('utf8').on('data', (chunk) => {
      stdout += chunk;
    });
    owned.child.stderr.setEncoding('utf8').on('data', (chunk) => {
      stderr += chunk;
    });
    outputClosed = new Promise<void>((resolve, reject) => {
      owned.child.once('error', reject);
      owned.child.once('close', () => resolve());
    });
    commandResult = owned.commandResult;
    await outputClosed;
    const command = await commandResult;
    const result: CliRunResult = {
      status: command?.code ?? null,
      signal: command?.signal ?? null,
      stdout,
      stderr,
    };
    expect(result.status, `signal=${result.signal}\n${outputOf(result)}`).toBe(0);
    return result;
  };

  return { root, fixtureGit, runCli };
}

beforeAll(async () => {
  if (!existsSync(WORKSPACE_DIST_CLI)) {
    throw new Error(
      `Missing ${WORKSPACE_DIST_CLI}. Run \`pnpm exec turbo run build --filter=@inkeep/open-knowledge\` before this smoke.`,
    );
  }

  if (SUT_MODE === 'packed') {
    const packDest = mkdtempSync(join(tmpdir(), 'ok-e2e-pack-'));
    H.packDest = packDest;
    H.installPrefix = mkdtempSync(join(tmpdir(), 'ok-e2e-install-'));
    const installed = await installPackedCli({
      packageDir: CLI_PKG_DIR,
      packDest,
      installPrefix: H.installPrefix,
    });
    H.cliPath = installed.cliPath;
    H.binShim = installed.binShim;
    H.acquisition = installed.acquisition;
  } else {
    H.cliPath = WORKSPACE_DIST_CLI;
  }

  H.contentDir = mkdtempSync(join(tmpdir(), 'ok-e2e-content-'));
  execFileSync('git', ['init', '-q'], { cwd: H.contentDir });
  execFileSync('git', ['config', 'user.email', '[email protected]'], { cwd: H.contentDir });
  execFileSync('git', ['config', 'user.name', 'OK E2E'], { cwd: H.contentDir });
  H.lockPath = join(H.contentDir, '.ok', 'local', 'server.lock');
}, 240_000);

afterAll(async () => {
  if (H.server && H.server.exitCode === null) {
    H.server.kill('SIGKILL');
  }
  for (const dir of [H.contentDir, H.installPrefix, H.packDest]) {
    if (dir) rmSync(dir, { recursive: true, force: true });
  }
});

describe(`CLI Linux e2e (${SUT_MODE} SUT)`, () => {
  test('1. install fidelity: the bin runs under Node and ships its UI + assets', () => {
    const v = runOk(['--version'], { cwd: CLI_PKG_DIR });
    expect(v.status).toBe(0);
    expect(v.stdout.trim()).toMatch(/\d+\.\d+\.\d+/);

    if (SUT_MODE === 'packed') {
      const installed = dirname(dirname(H.cliPath));
      expect(existsSync(join(installed, 'dist', 'public'))).toBe(true);
      expect(existsSync(join(installed, 'dist', 'assets', 'skills'))).toBe(true);
      expect(H.binShim && existsSync(H.binShim)).toBe(true);
    }
  });

  test.skipIf(!LOCKED_PACKED_INSTALL)(
    '1b. a second install of the same packed CLI takes the warm-store path and its bin runs',
    async () => {
      const installPrefix = mkdtempSync(join(tmpdir(), 'ok-e2e-warm-install-'));
      try {
        const installation = installPackedCli({
          packageDir: CLI_PKG_DIR,
          packDest: H.packDest as string,
          installPrefix,
        });
        await expect(installation).resolves.toMatchObject({ binShim: expect.any(String) });
        const { binShim, acquisition } = await installation;

        const version = spawnSync(binShim, ['--version'], {
          cwd: installPrefix,
          timeout: 30_000,
          encoding: 'utf8',
          env: { ...process.env, ...HERMETIC_ENV },
        });
        expect(version.status, version.stderr).toBe(0);
        expect(version.stdout.split('\n')[0]).toMatch(/^\d+\.\d+\.\d+\S*$/);

        const acquired = new Set([
          ...progressOf(H.acquisition, 'fetched'),
          ...progressOf(H.acquisition, 'found_in_store'),
        ]);
        expect(progressOf(acquisition, 'found_in_store')).toContain('file:cli.tgz');
        expect(progressOf(acquisition, 'found_in_store')).toEqual(acquired);
        expect(acquisition?.fetchStarts).toEqual(new Set());
        expect(progressOf(acquisition, 'fetched')).toEqual(new Set());
      } finally {
        rmSync(installPrefix, { recursive: true, force: true });
      }
    },
    240_000,
  );

  test('2. ok init scaffolds .ok/ in the content dir', () => {
    const r = runOk(['init', '--no-mcp'], { timeoutMs: 60_000 });
    expect(r.status).toBe(0);
    expect(existsSync(join(H.contentDir, '.ok'))).toBe(true);
  });

  test('2c. ok clone --json keeps fresh clone stdout parseable as JSONL', async () => {
    const isolated = isolatedCliRunner('ok-clone-jsonl-fresh-');
    const run = join(isolated.root, 'run');
    mkdirSync(run, { recursive: true });
    isolated.fixtureGit(['init', '-q']);
    isolated.fixtureGit(['config', 'maintenance.auto', 'false']);
    isolated.fixtureGit(['config', 'user.email', '[email protected]']);
    isolated.fixtureGit(['config', 'user.name', 'OK E2E']);

    const source = join(isolated.root, 'source');
    const bare = join(isolated.root, 'remote.git');
    const cloneUrl = 'https://127.0.0.1/owner/repo';
    mkdirSync(source, { recursive: true });
    isolated.fixtureGit(['init', '-q', '--initial-branch=main'], source);
    isolated.fixtureGit(['config', 'maintenance.auto', 'false'], source);
    isolated.fixtureGit(['config', 'user.email', '[email protected]'], source);
    isolated.fixtureGit(['config', 'user.name', 'OK E2E'], source);
    writeFileSync(join(source, 'README.md'), '# Clone fixture\n', 'utf8');
    isolated.fixtureGit(['add', 'README.md'], source);
    isolated.fixtureGit(['commit', '-q', '-m', 'fixture'], source);
    isolated.fixtureGit(['-c', 'maintenance.auto=false', 'clone', '-q', '--bare', source, bare]);
    isolated.fixtureGit(['config', 'maintenance.auto', 'false'], bare);

    const result = await isolated.runCli(['clone', cloneUrl, '../clone', '--json'], run, {
      GIT_CONFIG_COUNT: '1',
      GIT_CONFIG_KEY_0: `url.file://${bare}.insteadOf`,
      GIT_CONFIG_VALUE_0: cloneUrl,
    });

    expect(result.stderr, outputOf(result)).toMatch(SERVER_INFO_RECORD);
    const lines = result.stdout.endsWith('\n')
      ? result.stdout.slice(0, -1).split('\n')
      : result.stdout.split('\n');
    expect(lines.length).toBeGreaterThan(0);
    for (const [index, line] of lines.entries()) {
      expect(
        () => JSON.parse(line),
        `stdout line ${index + 1}: ${line}\n${outputOf(result)}`,
      ).not.toThrow();
    }
  });

  test('2d. ok init --no-mcp --json keeps stdout parseable as JSON', async () => {
    const isolated = isolatedCliRunner('ok-init-json-');

    const result = await isolated.runCli(['init', '--no-mcp', '--json'], isolated.root);

    expect(result.stderr, outputOf(result)).toMatch(SERVER_INFO_RECORD);
    let report: { projectRoot?: string } | undefined;
    expect(() => {
      report = JSON.parse(result.stdout) as { projectRoot?: string };
    }, outputOf(result)).not.toThrow();
    expect(report?.projectRoot).toBe(isolated.root);
  });

  test('3. ok start boots, writes server.lock with a port, and serves HTTP', async () => {
    H.server = spawn(NODE, [H.cliPath, 'start', '--port', String(START_PORT)], {
      cwd: H.contentDir,
      env: { ...process.env, ...HERMETIC_ENV },
      stdio: ['ignore', 'pipe', 'pipe'],
    });
    let serverLog = '';
    H.server.stdout?.on('data', (d) => {
      serverLog += d;
    });
    H.server.stderr?.on('data', (d) => {
      serverLog += d;
    });

    const lockReady = await waitFor(() => (readLockPort() ?? 0) > 0, { timeoutMs: 45_000 });
    const lockState = !existsSync(H.lockPath)
      ? 'lock file never appeared'
      : `lock file exists but unreadable: ${readFileSync(H.lockPath, 'utf8').slice(0, 200)}`;
    expect(lockReady, `${lockState}\nServer log:\n${serverLog}`).toBe(true);

    const port = readLockPort();
    expect(port).toBe(START_PORT);
    expect(H.server.exitCode, 'server exited during startup').toBeNull();

    const reachable = await waitFor(() => tcpReachable(port as number), { timeoutMs: 15_000 });
    expect(reachable, 'server port never accepted a TCP connection').toBe(true);
  }, 70_000);

  test('4. ok mcp answers a stdio round-trip: tools/list + exec + write + read-back', async () => {
    const transport = new StdioClientTransport({
      command: NODE,
      args: [H.cliPath, 'mcp'],
      cwd: H.contentDir,
      env: { ...process.env, ...HERMETIC_ENV } as Record<string, string>,
    });
    const client = new Client({ name: 'ok-e2e', version: '0.0.0' });
    try {
      await client.connect(transport);

      const tools = await client.listTools();
      const names = new Set(tools.tools.map((t) => t.name));
      for (const required of ['exec', 'search', 'write', 'edit']) {
        expect(names.has(required), `MCP tool "${required}" missing`).toBe(true);
      }

      const marker = `e2e-marker-${START_PORT}`;
      const writeRes = (await client.callTool({
        name: 'write',
        arguments: {
          cwd: H.contentDir,
          document: { path: 'e2e/smoke', content: `# Smoke\n\n${marker}\n` },
        },
      })) as { isError?: boolean };
      expect(writeRes.isError ?? false).toBe(false);

      const catRes = (await client.callTool({
        name: 'exec',
        arguments: { command: 'cat e2e/smoke.md', cwd: H.contentDir },
      })) as { isError?: boolean; content?: Array<{ type: string; text?: string }> };
      expect(catRes.isError ?? false).toBe(false);
      const catText = (catRes.content ?? []).map((c) => c.text ?? '').join('\n');
      expect(catText).toContain(marker);
    } finally {
      await client.close().catch(() => {});
    }
  }, 60_000);

  test('4b. bundled mermaid validator emits renderWarnings through the packed bin', async () => {
    const transport = new StdioClientTransport({
      command: NODE,
      args: [H.cliPath, 'mcp'],
      cwd: H.contentDir,
      env: { ...process.env, ...HERMETIC_ENV } as Record<string, string>,
    });
    const client = new Client({ name: 'ok-e2e-mermaid', version: '0.0.0' });
    try {
      await client.connect(transport);
      const writeRes = (await client.callTool({
        name: 'write',
        arguments: {
          cwd: H.contentDir,
          document: {
            path: 'e2e/mermaid-smoke',
            content: '# Smoke\n\n```mermaid\nsequenceDiagram\n  A->>B: hi; there\n```\n',
          },
        },
      })) as {
        isError?: boolean;
        content?: Array<{ type: string; text?: string }>;
        structuredContent?: {
          document?: {
            warnings?: Array<{ kind: string; fenceIndex: number; message: string }>;
          };
        };
      };
      expect(writeRes.isError ?? false).toBe(false);
      const warnings = writeRes.structuredContent?.document?.warnings;
      expect(warnings, 'warnings missing from packed-bin write response').toBeDefined();
      expect(warnings?.[0]?.kind).toBe('mermaid-parse-error');
      expect(warnings?.[0]?.message).toContain('Parse error');
      const text = (writeRes.content ?? []).map((c) => c.text ?? '').join('\n');
      expect(text).toContain('⚠');
      expect(text).toContain('will not render');

      const editRes = (await client.callTool({
        name: 'edit',
        arguments: {
          cwd: H.contentDir,
          document: { path: 'e2e/mermaid-smoke', find: '# Smoke', replace: '# Smoke (edited)' },
        },
      })) as {
        isError?: boolean;
        content?: Array<{ type: string; text?: string }>;
        structuredContent?: { document?: { warnings?: Array<{ kind: string }> } };
      };
      expect(editRes.isError ?? false).toBe(false);
      expect(editRes.structuredContent?.document?.warnings?.[0]?.kind).toBe('mermaid-parse-error');
      const editText = (editRes.content ?? []).map((c) => c.text ?? '').join('\n');
      expect(editText).toContain('will not render');

      const validRes = (await client.callTool({
        name: 'write',
        arguments: {
          cwd: H.contentDir,
          document: {
            path: 'e2e/mermaid-smoke-valid',
            content: '```mermaid\ngraph LR\n  A-->B\n```\n',
          },
        },
      })) as {
        isError?: boolean;
        structuredContent?: { document?: { warnings?: unknown } };
      };
      expect(validRes.isError ?? false).toBe(false);
      expect(validRes.structuredContent?.document?.warnings).toBeUndefined();

      const batchRes = (await client.callTool({
        name: 'write',
        arguments: {
          cwd: H.contentDir,
          documents: [
            { path: 'e2e/mermaid-batch-ok', content: '```mermaid\ngraph LR\n  A-->B\n```\n' },
            {
              path: 'e2e/mermaid-batch-bad',
              content: '```mermaid\nsequenceDiagram\n  A->>B: x; y\n```\n',
            },
          ],
        },
      })) as {
        isError?: boolean;
        structuredContent?: {
          documents?: Array<{ docName: string; warnings?: Array<{ kind: string }> }>;
        };
      };
      expect(batchRes.isError ?? false).toBe(false);
      const batchDocs = batchRes.structuredContent?.documents ?? [];
      expect(batchDocs).toHaveLength(2);
      expect(batchDocs[0]?.warnings).toBeUndefined();
      expect(batchDocs[1]?.warnings?.[0]?.kind).toBe('mermaid-parse-error');
    } finally {
      await client.close().catch(() => {});
    }
  }, 60_000);

  test('5. file-watcher ingests an external disk write (inotify on Linux)', async () => {
    const marker = `okwatchprobe${START_PORT}`;
    writeFileSync(
      join(H.contentDir, `${marker}.md`),
      `---\ntitle: Watcher Probe\n---\n\n# Watcher Probe\n\n${marker} body sentinel\n`,
    );

    const transport = new StdioClientTransport({
      command: NODE,
      args: [H.cliPath, 'mcp'],
      cwd: H.contentDir,
      env: { ...process.env, ...HERMETIC_ENV } as Record<string, string>,
    });
    const client = new Client({ name: 'ok-e2e-watch', version: '0.0.0' });
    try {
      await client.connect(transport);
      const found = await waitFor(
        async () => {
          const res = (await client.callTool({
            name: 'search',
            arguments: { query: marker, cwd: H.contentDir },
          })) as { isError?: boolean; content?: Array<{ type: string; text?: string }> };
          if (res.isError) return false;
          const text = (res.content ?? []).map((c) => c.text ?? '').join('\n');
          return text.includes(marker);
        },
        { timeoutMs: 20_000, intervalMs: 500 },
      );
      expect(found, 'file-watcher never surfaced the disk-dropped doc via search').toBe(true);
    } finally {
      await client.close().catch(() => {});
    }
  }, 40_000);

  test('6. keyring resolves without hanging and `ok auth status` names the backend', () => {
    const headlessEnv = { DBUS_SESSION_BUS_ADDRESS: '', XDG_RUNTIME_DIR: '' };
    const r = runOk(['auth', 'status', '--json'], { timeoutMs: 15_000, env: headlessEnv });

    expect(r.signal, `ok auth status hung (keyring D-Bus trap?). stderr:\n${r.stderr}`).toBeNull();

    const line = r.stdout.trim().split('\n').filter(Boolean).pop() ?? '{}';
    let payload: { backend?: string };
    try {
      payload = JSON.parse(line) as { backend?: string };
    } catch {
      throw new Error(
        `Failed to parse JSON from \`ok auth status --json\`.\nLast stdout line: ${line}\nFull stdout:\n${r.stdout}\nstderr:\n${r.stderr}`,
      );
    }
    expect(['keyring', 'file']).toContain(payload.backend);
  });

  test('7. shutdown releases the server lock', async () => {
    expect(H.server).not.toBeNull();
    const server = H.server as ChildProcess;
    const exited = new Promise<void>((res) => server.once('exit', () => res()));
    server.kill('SIGTERM');
    const cleanExit = await Promise.race([
      exited.then(() => true),
      new Promise<boolean>((r) => setTimeout(() => r(false), 10_000)),
    ]);
    expect(cleanExit, 'server did not exit within 10s of SIGTERM').toBe(true);

    const lockGone = await waitFor(() => !existsSync(H.lockPath), { timeoutMs: 5_000 });
    expect(lockGone, 'server.lock was not released on shutdown').toBe(true);
  }, 20_000);

  test('8. a lock whose pid now belongs to another process reads stale, is pruned, and is never signalled', async () => {
    const projectDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-e2e-reused-pid-')));
    const lockPath = join(projectDir, '.ok', 'local', 'server.lock');
    const standIn = await startOwnedProcess();
    let server: ChildProcess | null = null;
    let serverLog = '';
    try {
      execFileSync('git', ['init', '-q'], { cwd: projectDir });
      expect(runOk(['init', '--no-mcp'], { cwd: projectDir, timeoutMs: 60_000 }).status).toBe(0);
      mkdirSync(dirname(lockPath), { recursive: true });
      writeFileSync(
        lockPath,
        JSON.stringify(
          legacyServerLock({
            pid: standIn.pid,
            startedAt: lockWrittenBeforeProcessStarted(standIn),
            machineId: getMachineId(),
            worktreeRoot: projectDir,
          }),
        ),
        { mode: 0o600 },
      );

      const status = runOk(['status', '--json'], { cwd: projectDir });
      expect(status.status, status.stderr).toBe(0);
      const report = JSON.parse(status.stdout) as { server: { state: string; alive: boolean } };
      expect(report.server).toMatchObject({ state: 'reused-pid', alive: false });

      const stop = runOk(['stop', projectDir], { cwd: projectDir });
      expect(stop.status, stop.stderr).toBe(0);
      expect(
        await waitFor(() => ownedProcessHasExited(standIn), { timeoutMs: 2_000 }),
        'ok stop signalled the stand-in',
      ).toBe(false);

      const clean = runOk(['clean'], { cwd: projectDir });
      expect(clean.status, clean.stderr).toBe(0);
      expect(clean.stdout).toContain('Pruned 1 stale lock: server (reused-pid)');
      expect(existsSync(lockPath)).toBe(false);

      server = spawn(NODE, [H.cliPath, 'start'], {
        cwd: projectDir,
        env: { ...process.env, ...HERMETIC_ENV },
        stdio: ['ignore', 'pipe', 'pipe'],
      });
      server.stdout?.on('data', (d) => {
        serverLog += d;
      });
      server.stderr?.on('data', (d) => {
        serverLog += d;
      });
      const readLock = (): Record<string, unknown> | null => {
        try {
          return JSON.parse(readFileSync(lockPath, 'utf8')) as Record<string, unknown>;
        } catch {
          return null;
        }
      };
      const booted = await waitFor(
        () => serverLog.includes('Press Ctrl+C to stop') && readLock()?.pid === server?.pid,
        { timeoutMs: 45_000 },
      );
      expect(
        booted,
        `ok start never finished booting under its own lock\nServer log:\n${serverLog}`,
      ).toBe(true);
      expect(readLock()?.processStart).toEqual(expect.any(Object));

      const exited = new Promise<void>((res) => server?.once('exit', () => res()));
      const stopStarted = runOk(['stop', projectDir], { cwd: projectDir, timeoutMs: 30_000 });
      expect(stopStarted.status, stopStarted.stderr).toBe(0);
      await exited;
      expect(existsSync(lockPath)).toBe(false);
      expect(
        await waitFor(() => ownedProcessHasExited(standIn), { timeoutMs: 2_000 }),
        'ok stop signalled the stand-in',
      ).toBe(false);
    } finally {
      if (server && server.exitCode === null && server.signalCode === null) server.kill('SIGKILL');
      await stopOwnedProcess(standIn);
      rmSync(projectDir, { recursive: true, force: true });
    }
  }, 120_000);
});