Files
codegraph/__tests__/cli-unlock.test.ts
T
Colby MchenryandClaude Opus 5.5 3f58e34383 fix(cli): index no longer blocks on a daemon lock naming a process that isn't CodeGraph (#2819)
codegraph index told you to run `codegraph daemon stop`, which the CLI
rejects ("too many arguments"), whenever it could not verify the process
named in .codegraph/daemon.pid. In that state `codegraph daemon` lists
nothing, because it lists only daemons that answer their socket. And
`codegraph unlock` kept an old-format lock whose process was alive (the
rule from issue #1834), so nothing the CLI offered got past it. The
writer-lock message gave the same wrong advice.

Root cause: a live pid in the lock was the only evidence, and a pid
proves nothing once the OS gives it to another program. Every CodeGraph
daemon since the first one (v0.9.5) runs
`<runtime> ... codegraph.js serve --mcp --path <root>`, so the holder's
command line settles the question.

Fix:
- New src/mcp/process-identity.ts reads a process's command line and
  executable name from the OS: Win32_Process through PowerShell (tasklist
  as fallback) on Windows, /proc on Linux, ps elsewhere. Each lookup is
  capped at 5 s and never throws. A holder is a CodeGraph MCP server,
  provably something else, or unknown, and unknown is never evidence.
- stopDaemonAt treats an unverified live holder that is provably not a
  CodeGraph server like a dead one. Its lock is cleared, under the same
  writer-slot claim, and the process is never signalled.
  clearStaleDaemonArtifacts (codegraph unlock) does the same for an
  old-format lock. A holder that may be a daemon keeps its lock, as
  before (issues #1553 and #1834).
- daemonStopFailureMessage builds index's error from what remains: the
  pid, what it runs, and a command that clears it (taskkill /PID N /F or
  kill N), or which lock file to delete when only that will do.
- writerLockHeldMessage names `codegraph daemon` instead of the missing
  `codegraph daemon stop`.

Validation (Windows 11):
- New daemon-lock-holder.test.ts (11 tests) and a daemon-registry test.
  With main's daemon-registry.ts, writer-lock.ts and codegraph.ts put
  back, 11 tests fail, including all 8 CLI cases and the writer-lock
  wording; with the fix all pass. Four existing tests used generic
  processes to stand in for a daemon that doesn't answer. Those stand-ins
  now carry a CodeGraph server's command line, and pass on main and here.
- Real CLI with a private HOME, 4 cases: an old-format lock naming a live
  PING.EXE; an old-format lock naming a live Node process that isn't
  CodeGraph; a current-format lock naming that kind of Node process with
  a pipe nobody listens on; an old-format lock naming a Node process whose
  command line reads `codegraph.js serve --mcp`. On main all 4 index runs
  exit 1 with the old advice, `daemon stop` is rejected, `daemon` lists
  nothing, and unlock clears only the third. With the fix the first 3
  rebuild (exit 0), each holder stays alive, and unlock clears the first
  too. The 4th exits 1, naming the pid and `taskkill /PID <pid> /F`;
  after that command, index exits 0.

Contributor PR #2373 (@danusha2345) changes the two strings only; I read
it for guidance.

Fixes #2770

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 23:32:31 +00:00

142 lines
5.0 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { execFile, execFileSync, spawn } from 'child_process';
import * as fs from 'fs';
import * as net from 'net';
import * as os from 'os';
import * as path from 'path';
import { CodeGraph } from '../src';
import { getDaemonPidPath, getDaemonSocketPath } from '../src/mcp/daemon-paths';
import { CodeGraphPackageVersion } from '../src/mcp/version';
const BIN = path.resolve(__dirname, '../dist/bin/codegraph.js');
function runCodegraph(args: string[], cwd: string): string {
return execFileSync(process.execPath, [BIN, ...args], {
cwd,
encoding: 'utf8',
env: { ...process.env, CODEGRAPH_NO_DAEMON: '1' },
stdio: ['ignore', 'pipe', 'pipe'],
});
}
function runCodegraphAsync(args: string[], cwd: string): Promise<string> {
return new Promise((resolve, reject) => {
execFile(
process.execPath,
[BIN, ...args],
{ cwd, encoding: 'utf8', env: { ...process.env, CODEGRAPH_NO_DAEMON: '1' } },
(error, stdout, stderr) => {
if (error) reject(new Error(`${error.message}\n${stderr}`));
else resolve(stdout);
},
);
});
}
describe('codegraph unlock — daemon artifact recovery (#1553)', () => {
let tempDir: string;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-unlock-'));
const cg = CodeGraph.initSync(tempDir);
cg.close();
});
afterEach(() => {
fs.rmSync(tempDir, { recursive: true, force: true });
});
it('removes indexing and phantom-daemon artifacts, then permits indexing', () => {
const graphDir = path.join(tempDir, '.codegraph');
const pidPath = getDaemonPidPath(tempDir);
const socketPath = getDaemonSocketPath(tempDir);
fs.writeFileSync(path.join(graphDir, 'codegraph.lock'), 'stale\n');
fs.writeFileSync(pidPath, JSON.stringify({
pid: process.pid,
version: CodeGraphPackageVersion,
socketPath,
startedAt: Date.now() - 60_000,
}));
if (process.platform !== 'win32') fs.writeFileSync(socketPath, 'stale\n');
const output = runCodegraph(['unlock', tempDir], tempDir);
expect(output).toContain('Removed stale lock artifacts');
expect(fs.existsSync(path.join(graphDir, 'codegraph.lock'))).toBe(false);
expect(fs.existsSync(pidPath)).toBe(false);
if (process.platform !== 'win32') expect(fs.existsSync(socketPath)).toBe(false);
expect(() => process.kill(process.pid, 0)).not.toThrow();
expect(() => runCodegraph(['index', '--quiet', tempDir], tempDir)).not.toThrow();
});
it('preserves artifacts when the recorded live daemon answers the socket hello', async () => {
const pidPath = getDaemonPidPath(tempDir);
const socketPath = getDaemonSocketPath(tempDir);
const server = net.createServer((socket) => {
socket.end(JSON.stringify({
codegraph: CodeGraphPackageVersion,
pid: process.pid,
socketPath,
protocol: 1,
}) + '\n');
});
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(socketPath, resolve);
});
fs.writeFileSync(pidPath, JSON.stringify({
pid: process.pid,
version: CodeGraphPackageVersion,
socketPath,
startedAt: Date.now(),
}));
try {
const output = await runCodegraphAsync(['unlock', tempDir], tempDir);
expect(output).toContain('No stale lock files found');
expect(fs.existsSync(pidPath)).toBe(true);
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});
it('preserves a live legacy lock whose daemon identity cannot be probed', () => {
// The holder's command line reads like a CodeGraph MCP server's, so it may
// be the daemon. One that is plainly another program leaves a stale lock,
// which unlock clears (#2770).
const holder = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)', 'codegraph.js', 'serve', '--mcp'], { stdio: 'ignore' });
try {
const pidPath = getDaemonPidPath(tempDir);
fs.writeFileSync(pidPath, `${holder.pid}\n`);
const output = runCodegraph(['unlock', tempDir], tempDir);
expect(output).toContain('No stale lock files found');
expect(fs.readFileSync(pidPath, 'utf8')).toBe(`${holder.pid}\n`);
expect(() => process.kill(holder.pid!, 0)).not.toThrow();
} finally {
holder.kill('SIGKILL');
}
});
it('removes a legacy lock whose PID is dead', () => {
const pidPath = getDaemonPidPath(tempDir);
fs.writeFileSync(pidPath, '999999\n');
const output = runCodegraph(['unlock', tempDir], tempDir);
expect(output).toContain('Removed stale lock artifacts');
expect(fs.existsSync(pidPath)).toBe(false);
});
it('removes a malformed daemon lock', () => {
const pidPath = getDaemonPidPath(tempDir);
fs.writeFileSync(pidPath, 'not-a-lock\n');
const output = runCodegraph(['unlock', tempDir], tempDir);
expect(output).toContain('Removed stale lock artifacts');
expect(fs.existsSync(pidPath)).toBe(false);
});
});