Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): read candidate working directories in one lsof query (#4517)
Nick Gomezfff5fd8cc2d1
diff --git a/.changeset/faster-running-process-inspection.md b/.changeset/faster-running-process-inspection.mdnew file mode 100644index 000000000..bb9d83cb0--- /dev/null+++ b/.changeset/faster-running-process-inspection.md@@ -0,0 +1,7 @@+---+"@inkeep/open-knowledge": patch+"@inkeep/open-knowledge-desktop": patch+"@inkeep/open-knowledge-server": patch+---++`ok ps`, `ok stop`, and `ok uninstall` no longer stall for seconds while inspecting running processes, and neither does the desktop uninstall flow. A process that stops responding is queried twice, each attempt bounded at two seconds, so it still adds to the inspection.diff --git a/packages/cli/src/commands/removal-plan.ts b/packages/cli/src/commands/removal-plan.tsindex e62a0dbb5..a3f5c3bc8 100644--- a/packages/cli/src/commands/removal-plan.ts+++ b/packages/cli/src/commands/removal-plan.ts@@ -3,7 +3,11 @@ import { basename, join, relative, resolve, sep } from 'node:path';import { PROJECT_SKILL_PROJECTION_PATHS } from '@inkeep/open-knowledge-core';import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';import { resolveShadowDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';-import { resolveLockDir, scanLockProcesses } from '@inkeep/open-knowledge-server';+import {+ type LockProcessScan,+ resolveLockDir,+ scanLockProcesses,+} from '@inkeep/open-knowledge-server';import { clearAllEmbeddingsKeys } from '../auth/embeddings-key-store.ts';import { clearTokenFromAllBackends } from '../auth/token-store.ts';import {@@ -366,23 +370,37 @@ export function applicationDataOps(return ops;}-export interface RunRemovalDeps {+interface RunRemovalSharedDeps {env?: NodeJS.ProcessEnv;clearToken?: (host: string,) => Promise<{ touched: Array<'keychain' | 'file'>; keychainError?: string }>;clearEmbeddingsKey?: () => Promise<{ touched: Array<'file'> }>;- stopServer?: (lockDir: string) => Promise<{- stopped: number;- failed: Array<{ pid: number; error: string }>;- skipped?: string;- }>;}+type RemovalStopServer = (lockDir: string) => Promise<{+ stopped: number;+ failed: Array<{ pid: number; error: string }>;+ skipped?: string;+}>;++export type RunRemovalDeps = RunRemovalSharedDeps &+ (+ | { stopServer?: RemovalStopServer; scanProcesses?: never }+ | { stopServer?: never; scanProcesses?: () => Promise<LockProcessScan> }+ );+export async function runRemoval(plan: RemovalPlan,deps: RunRemovalDeps = {},): Promise<RemovalOutcome> {+ if (deps.stopServer !== undefined && deps.scanProcesses !== undefined) {+ throw new Error(+ 'runRemoval received both stopServer and scanProcesses. scanProcesses only parameterizes the ' ++ 'default stopServer, so a supplied stopServer never reads it and the scan would never run. ' ++ 'Supply stopServer to replace shutdown entirely, or scanProcesses to parameterize the default one.',+ );+ }const clearToken = deps.clearToken ?? clearTokenFromAllBackends;const clearEmbeddingsKey = deps.clearEmbeddingsKey ?? clearAllEmbeddingsKeys;const deinitLockDirs = new Set(@@ -390,13 +408,14 @@ export async function runRemoval(op.kind === 'stop-server' && !op.preserveProjectState ? [resolve(op.lockDir)] : [],),);- let processScan: ReturnType<typeof scanLockProcesses> | undefined;+ const scan = deps.scanProcesses ?? scanLockProcesses;+ let processScan: Promise<LockProcessScan> | undefined;const stopServer =deps.stopServer ??((lockDir: string) =>stopServerForRemoval(lockDir, {preserveProjectState: plan.scope === 'uninstall' && !deinitLockDirs.has(resolve(lockDir)),- scanProcesses: () => (processScan ??= scanLockProcesses()),+ scanProcesses: () => (processScan ??= scan()),}));const resolvedDeps = { clearToken, clearEmbeddingsKey, stopServer, env: deps.env ?? {} };@@ -479,7 +498,7 @@ export async function describeAttachedClients(return lines;}-type ResolvedDeps = Required<RunRemovalDeps>;+type ResolvedDeps = Required<Omit<RunRemovalDeps, 'scanProcesses'>>;async function executeOp(op: RemovalOp, deps: ResolvedDeps): Promise<RemovalOpResult> {switch (op.kind) {diff --git a/packages/cli/src/commands/uninstall-lock-recovery.test.ts b/packages/cli/src/commands/uninstall-lock-recovery.test.tsindex 832a49a72..2cf074aed 100644--- a/packages/cli/src/commands/uninstall-lock-recovery.test.ts+++ b/packages/cli/src/commands/uninstall-lock-recovery.test.ts@@ -11,16 +11,29 @@ import {} from 'node:fs';import { hostname, tmpdir } from 'node:os';import { dirname, join } from 'node:path';-import { isProcessAlive } from '@inkeep/open-knowledge-server';+import {+ isProcessAlive,+ type LockProcessScan,+ scanLockProcesses,+} from '@inkeep/open-knowledge-server';import { afterEach, beforeEach, describe, expect, test } from 'vitest';-import { buildDeinitPlan, buildUninstallPlan, runRemoval } from './removal-plan.ts';+import {+ buildDeinitPlan,+ buildUninstallPlan,+ type RunRemovalDeps,+ runRemoval,+} from './removal-plan.ts';import { runUninstall } from './uninstall.ts';describe.skipIf(process.platform === 'win32')('uninstall lock recovery in an isolated home', () => {let root: string;const children: ChildProcess[] = [];+ let observedScan:+ | { candidates: LockProcessScan['candidates']; livePidsAtScanTime: number[] }+ | undefined;beforeEach(() => {root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-uninstall-recovery-')));+ observedScan = undefined;});afterEach(async () => {for (const child of children.splice(0)) {@@ -36,6 +49,16 @@ describe.skipIf(process.platform === 'win32')('uninstall lock recovery in an isomkdirSync(dirname(path), { recursive: true });writeFileSync(path, bytes);}+ async function scanCandidatesWithoutHostUncertainty(): Promise<LockProcessScan> {+ const { candidates } = await scanLockProcesses();+ observedScan = {+ candidates,+ livePidsAtScanTime: children.flatMap((child) =>+ child.pid !== undefined && isProcessAlive(child.pid) ? [child.pid] : [],+ ),+ };+ return { candidates, unavailable: [] };+ }async function childServer(project: string) {const child = spawn(process.execPath,@@ -111,6 +134,7 @@ describe.skipIf(process.platform === 'win32')('uninstall lock recovery in an isorunRemovalDeps: {clearToken: async () => ({ touched: [] }),clearEmbeddingsKey: async () => ({ touched: [] }),+ scanProcesses: scanCandidatesWithoutHostUncertainty,},},});@@ -154,6 +178,23 @@ describe.skipIf(process.platform === 'win32')('uninstall lock recovery in an isoexpect(readFileSync(join(project, 'notes.md'), 'utf8')).toBe('# Keep');});+ test('refuses a dep set that supplies both stopServer and scanProcesses', async () => {+ const project = join(root, 'project');+ const lockPath = join(project, '.ok', 'local', 'server.lock');+ write(lockPath, 'not json');+ write(join(project, 'notes.md'), '# Keep');+ const contradictory = {+ stopServer: async () => ({ stopped: 0, failed: [] }),+ scanProcesses: scanCandidatesWithoutHostUncertainty,+ } as unknown as RunRemovalDeps;+ await expect(+ runRemoval(buildDeinitPlan(project, join(root, 'home')), contradictory),+ ).rejects.toThrow(/scanProcesses only parameterizes the default stopServer/);+ expect(observedScan).toBeUndefined();+ expect(readFileSync(lockPath, 'utf8')).toBe('not json');+ expect(readFileSync(join(project, 'notes.md'), 'utf8')).toBe('# Keep');+ });+test.each(([@@ -192,6 +233,7 @@ describe.skipIf(process.platform === 'win32')('uninstall lock recovery in an isoconst outcome = await runRemoval(plan, {clearToken: async () => ({ touched: [] }),clearEmbeddingsKey: async () => ({ touched: [] }),+ scanProcesses: scanCandidatesWithoutHostUncertainty,});if (scope.startsWith('global')) {expect(outcome.failed).toEqual([]);@@ -243,7 +285,19 @@ describe.skipIf(process.platform === 'win32')('uninstall lock recovery in an isoconst outcome = await runRemoval(plan, {clearToken: async () => ({ touched: [] }),clearEmbeddingsKey: async () => ({ touched: [] }),+ scanProcesses: scanCandidatesWithoutHostUncertainty,});+ const scanned = observedScan;+ if (scanned === undefined)+ throw new Error('The injected process scan never ran, so lock discovery went unverified');+ expect(+ scanned.livePidsAtScanTime,+ 'no fixture server was alive at scan time, so discovery is unverifiable',+ ).not.toHaveLength(0);+ expect(+ scanned.candidates.map((candidate) => candidate.pid),+ 'process discovery missed the live fixture server',+ ).toEqual(expect.arrayContaining(scanned.livePidsAtScanTime));if (associated) {expect(outcome.failed.some((r) => r.detail?.includes('live process candidates'))).toBe(true,diff --git a/packages/server/src/local-ops/gh-login.test.ts b/packages/server/src/local-ops/gh-login.test.tsindex 04f761624..18633d130 100644--- a/packages/server/src/local-ops/gh-login.test.ts+++ b/packages/server/src/local-ops/gh-login.test.ts@@ -70,13 +70,15 @@ exec sleep 60 1>/dev/null 2>/dev/null);chmodSync(cancelGh, 0o755);const events: AuthEvent[] = [];- const ctl = runGhDeviceLoginSubprocess({+ const ctl: RunGhDeviceLoginController = runGhDeviceLoginSubprocess({host: 'ghes.test',ghPath: cancelGh,verificationDeadlineMs: 10_000,- onEvent: (e) => events.push(e),+ onEvent: (e) => {+ events.push(e);+ if (e.type === 'verification') ctl.cancel();+ },});- setTimeout(() => ctl.cancel(), 300);await ctl.done;expect(events).toEqual([{diff --git a/packages/server/src/process-scan.test.ts b/packages/server/src/process-scan.test.tsindex f82d93dc2..776e7f64f 100644--- a/packages/server/src/process-scan.test.ts+++ b/packages/server/src/process-scan.test.ts@@ -9,7 +9,7 @@ const lstatSyncMock = vi.fn();let scanLockProcesses: typeof import('./process-scan.ts').scanLockProcesses;let discoverLockDirs: typeof import('./process-scan.ts').discoverLockDirs;let findOkProcessPids: typeof import('./process-scan.ts').findOkProcessPids;-let pidCwd: typeof import('./process-scan.ts').pidCwd;+let readPidCwds: typeof import('./process-scan.ts').readPidCwds;let realCp: typeof import('node:child_process');let realFs: typeof import('node:fs');@@ -23,11 +23,15 @@ beforeAll(async () => {readdirSync: readdirSyncMock,lstatSync: lstatSyncMock,}));- ({ scanLockProcesses, discoverLockDirs, findOkProcessPids, pidCwd } = await import(+ ({ scanLockProcesses, discoverLockDirs, findOkProcessPids, readPidCwds } = await import('./process-scan.ts'));});+function refuseUnmockedSpawn(command: string, args: readonly string[] = []): never {+ throw new Error(`unmocked spawnSync escaped to the host: ${command} ${args.join(' ')}`);+}+function makeSpawnResult(overrides: Partial<SpawnSyncReturns<string>>): SpawnSyncReturns<string> {return {pid: 0,@@ -45,7 +49,7 @@ describe('findOkProcessPids', () => {let spawnSyncSpy: typeof spawnSyncMock;beforeEach(() => {- spawnSyncMock.mockReset().mockImplementation(realCp.spawnSync);+ spawnSyncMock.mockReset().mockImplementation(refuseUnmockedSpawn);spawnSyncSpy = spawnSyncMock;});@@ -191,11 +195,11 @@ describe('findOkProcessPids', () => {});});-describe('pidCwd', () => {+describe('readPidCwds', () => {let spawnSyncSpy: typeof spawnSyncMock;beforeEach(() => {- spawnSyncMock.mockReset().mockImplementation(realCp.spawnSync);+ spawnSyncMock.mockReset().mockImplementation(refuseUnmockedSpawn);spawnSyncSpy = spawnSyncMock;});@@ -203,7 +207,7 @@ describe('pidCwd', () => {spawnSyncMock.mockReset();});- it('returns the CWD from lsof -Fn output', async () => {+ it('maps each pid to its CWD from lsof -Fn output', async () => {spawnSyncSpy.mockReturnValue(makeSpawnResult({stdout: 'p12345\nfcwd\nn/Users/mike/my-notes\n',@@ -211,31 +215,82 @@ describe('pidCwd', () => {}),);- const cwd = await pidCwd(12345);- expect(cwd).toBe('/Users/mike/my-notes');+ expect(readPidCwds([12345]).get(12345)).toBe('/Users/mike/my-notes');});- it('returns null when lsof is unavailable (ENOENT) — no crash', async () => {+ it('reports a failed query when lsof is unavailable (ENOENT) — no crash', async () => {const enoent = Object.assign(new Error('lsof not found'), { code: 'ENOENT' });spawnSyncSpy.mockReturnValue(makeSpawnResult({ error: enoent as NodeJS.ErrnoException }));- const cwd = await pidCwd(12345);- expect(cwd).toBeNull();+ expect(readPidCwds([12345]).size).toBe(0);});- it('returns null when lsof output has no cwd line', async () => {+ it('reports no cwd for a pid whose lsof output has no cwd line', async () => {spawnSyncSpy.mockReturnValue(makeSpawnResult({ stdout: 'p12345\n', status: 0 }));- const cwd = await pidCwd(12345);- expect(cwd).toBeNull();+ expect(readPidCwds([12345]).has(12345)).toBe(false);+ });++ it('keeps the answers of the responsive pids when the batched query fails', async () => {+ const timeoutErr = Object.assign(new Error('ETIMEDOUT'), { code: 'ETIMEDOUT' });+ spawnSyncSpy+ .mockReturnValueOnce(makeSpawnResult({ error: timeoutErr as NodeJS.ErrnoException }))+ .mockReturnValueOnce(makeSpawnResult({ error: timeoutErr as NodeJS.ErrnoException }))+ .mockReturnValueOnce(makeSpawnResult({ stdout: 'p22\nfcwd\nn/b\n', status: 0 }))+ .mockReturnValueOnce(makeSpawnResult({ stdout: 'p33\nfcwd\nn/c\n', status: 0 }));++ const cwds = readPidCwds([11, 22, 33]);+ expect(cwds.has(11)).toBe(false);+ expect(cwds.get(22)).toBe('/b');+ expect(cwds.get(33)).toBe('/c');+ });++ it('attributes each cwd to its own pid when a batch answers for only some of them', async () => {+ spawnSyncSpy.mockReturnValue(+ makeSpawnResult({ stdout: 'p11\nfcwd\nn/a\np22\np33\nfcwd\nn/c\n', status: 0 }),+ );++ const cwds = readPidCwds([11, 22, 33]);+ expect(cwds.get(11)).toBe('/a');+ expect(cwds.has(22)).toBe(false);+ expect(cwds.get(33)).toBe('/c');+ });++ it('issues no second query when the failing batch already covered a single pid', async () => {+ const timeoutErr = Object.assign(new Error('ETIMEDOUT'), { code: 'ETIMEDOUT' });+ spawnSyncSpy.mockReturnValue(makeSpawnResult({ error: timeoutErr as NodeJS.ErrnoException }));++ expect(readPidCwds([688]).size).toBe(0);++ const cwdQueries = spawnSyncSpy.mock.calls.filter(+ (call) => call[0] === 'lsof' && (call[1] as string[]).includes('cwd'),+ );+ expect(cwdQueries).toHaveLength(1);+ });++ it('attributes a batch from Linux lsof output, which omits the fcwd line', async () => {+ spawnSyncSpy.mockReturnValue(+ makeSpawnResult({ stdout: 'p249\nn/srv/notes\np250\nn/home/mike/second-notes\n', status: 0 }),+ );++ const cwds = readPidCwds([249, 250]);+ expect(cwds.get(249)).toBe('/srv/notes');+ expect(cwds.get(250)).toBe('/home/mike/second-notes');+ });++ it('keeps the first cwd line for a pid (parity pin: real lsof emits one per pid)', async () => {+ spawnSyncSpy.mockReturnValue(+ makeSpawnResult({ stdout: 'p11\nfcwd\nn/first\nn/second\n', status: 0 }),+ );++ expect(readPidCwds([11]).get(11)).toBe('/first');});- it('returns null on timeout (error but not ENOENT)', async () => {+ it('reports a failed query on timeout (error but not ENOENT)', async () => {const timeoutErr = Object.assign(new Error('ETIMEDOUT'), { code: 'ETIMEDOUT' });spawnSyncSpy.mockReturnValue(makeSpawnResult({ error: timeoutErr as NodeJS.ErrnoException }));- const cwd = await pidCwd(99999);- expect(cwd).toBeNull();+ expect(readPidCwds([99999]).size).toBe(0);});});@@ -246,7 +301,7 @@ describe('discoverLockDirs', () => {let lstatSyncSpy: typeof lstatSyncMock;beforeEach(() => {- spawnSyncMock.mockReset().mockImplementation(realCp.spawnSync);+ spawnSyncMock.mockReset().mockImplementation(refuseUnmockedSpawn);existsSyncMock.mockReset().mockImplementation(realFs.existsSync);lstatSyncMock.mockReset().mockImplementation(realFs.lstatSync);readdirSyncMock@@ -494,8 +549,12 @@ describe('discoverLockDirs', () => {status: 0,}),)- .mockReturnValueOnce(makeSpawnResult({ stdout: `p11\nfcwd\nn${directProject}\n`, status: 0 }))- .mockReturnValueOnce(makeSpawnResult({ stdout: 'p22\nfcwd\nn/\n', status: 0 }))+ .mockReturnValueOnce(+ makeSpawnResult({+ stdout: `p11\nfcwd\nn${directProject}\np22\nfcwd\nn/\n`,+ status: 0,+ }),+ ).mockReturnValueOnce(makeSpawnResult({ stdout: 'COMMAND PID USER\n', status: 0 }));existsSyncSpy.mockImplementation((p: unknown) =>@@ -521,23 +580,28 @@ describe('discoverLockDirs', () => {}});- it('degrades gracefully when lsof is unavailable for pidCwd calls', async () => {+ it('degrades gracefully when lsof is unavailable for working-directory and listener reads', async () => {const enoent = Object.assign(new Error('lsof not found'), { code: 'ENOENT' });+ const cwdSpy = vi.spyOn(process, 'cwd');spawnSyncSpy+ .mockImplementation(() => makeSpawnResult({ error: enoent as NodeJS.ErrnoException })).mockReturnValueOnce(makeSpawnResult({stdout: '55 /usr/local/bin/ok start\n',status: 0,}),- )- .mockReturnValueOnce(makeSpawnResult({ error: enoent as NodeJS.ErrnoException }))- .mockReturnValueOnce(makeSpawnResult({ error: enoent as NodeJS.ErrnoException }));+ );- existsSyncSpy.mockReturnValue(false);+ existsSyncSpy.mockImplementation(realFs.existsSync);- const dirs = await discoverLockDirs();- expect(dirs).toHaveLength(0);+ try {+ cwdSpy.mockReturnValue('/nonexistent-open-knowledge-test-root');+ const dirs = await discoverLockDirs();+ expect(dirs).toHaveLength(0);+ } finally {+ cwdSpy.mockRestore();+ }});});@@ -586,8 +650,8 @@ describe('lock recovery process evidence', () => {.mockReturnValueOnce(makeSpawnResult({ stdout: `${process.pid} open-knowledge-server notes\n` }),)- .mockReturnValueOnce(makeSpawnResult({ stdout: 'p123\nfcwd\nn/notes\n' }))- .mockReturnValueOnce(makeSpawnResult({ status: 1 }));+ .mockReturnValueOnce(makeSpawnResult({ status: 1 }))+ .mockReturnValueOnce(makeSpawnResult({ stdout: `p${process.pid}\nfcwd\nn/notes\n` }));expect((await scanLockProcesses()).candidates).toContainEqual({lockDir: '/notes/.ok/local',pid: process.pid,@@ -605,13 +669,52 @@ describe('lock recovery process evidence', () => {`Could not read the working directory of process ${process.pid}`,]);});+ it('retains a live candidate the batched query could not answer for', async () => {+ spawnSyncMock+ .mockReturnValueOnce(+ makeSpawnResult({ stdout: `${process.pid} open-knowledge-server notes\n` }),+ )+ .mockReturnValueOnce(makeSpawnResult({ status: 1 }))+ .mockReturnValueOnce(makeSpawnResult({ stdout: 'p1\nfcwd\nn/other\n', status: 0 }));+ expect((await scanLockProcesses()).unavailable).toEqual([+ `Could not read the working directory of process ${process.pid}`,+ ]);+ });+ it('reads every candidate working directory in one lsof query, not one per process', async () => {+ const pids = [process.pid, process.pid + 1, process.pid + 2, process.pid + 3];+ spawnSyncMock+ .mockReturnValueOnce(+ makeSpawnResult({+ stdout: pids.map((pid) => `${pid} open-knowledge-server notes`).join('\n'),+ }),+ )+ .mockReturnValueOnce(makeSpawnResult({ status: 1 }))+ .mockReturnValueOnce(+ makeSpawnResult({+ stdout: pids.map((pid) => `p${pid}\nfcwd\nn/notes-${pid}`).join('\n'),+ }),+ );+ const scan = await scanLockProcesses();+ const cwdQueries = spawnSyncMock.mock.calls.filter(+ (call) => call[0] === 'lsof' && (call[1] as string[]).includes('cwd'),+ );+ expect(cwdQueries).toHaveLength(1);+ expect(cwdQueries[0]?.[1]).toContain(pids.join(','));+ for (const pid of pids) {+ expect(scan.candidates).toContainEqual({+ lockDir: `/notes-${pid}/.ok/local`,+ pid,+ source: 'process-cwd',+ });+ }+ });it('keeps listener provenance without asserting the process is an OpenKnowledge server', async () => {spawnSyncMock.mockReturnValueOnce(makeSpawnResult({ status: 1 })).mockReturnValueOnce(makeSpawnResult({ stdout: `COMMAND PID USER\nnode ${process.pid} user\n` }),)- .mockReturnValueOnce(makeSpawnResult({ stdout: 'p123\nfcwd\nn/notes\n' }));+ .mockReturnValueOnce(makeSpawnResult({ stdout: `p${process.pid}\nfcwd\nn/notes\n` }));expect((await scanLockProcesses()).candidates).toContainEqual({lockDir: '/notes/.ok/local',pid: process.pid,diff --git a/packages/server/src/process-scan.ts b/packages/server/src/process-scan.tsindex 134d4d617..053280ef1 100644--- a/packages/server/src/process-scan.ts+++ b/packages/server/src/process-scan.ts@@ -193,28 +193,51 @@ export function processUsage(pid: number): ProcessUsage | null {return { cpuPercent, memPercent };}-export async function pidCwd(pid: number): Promise<string | null> {+function parsePidCwds(stdout: string): Map<number, string> {+ const cwds = new Map<number, string>();+ let pid: number | null = null;+ for (const line of stdout.split('\n')) {+ if (line.startsWith('p')) {+ const parsed = Number.parseInt(line.slice(1), 10);+ pid = Number.isNaN(parsed) ? null : parsed;+ } else if (line.startsWith('n') && line.length > 1 && pid !== null && !cwds.has(pid)) {+ cwds.set(pid, line.slice(1));+ }+ }+ return cwds;+}++function queryPidCwds(pids: readonly number[]): {+ cwds: Map<number, string>;+ queryFailed: boolean;+} {const result = spawnSync('lsof',- ['-p', String(pid), '-a', '-d', 'cwd', '-Fn'],+ ['-p', pids.join(','), '-a', '-d', 'cwd', '-Fn'],withHiddenWindowsConsole({encoding: 'utf-8',timeout: SPAWN_TIMEOUT_MS,}),);-if (result.error != null) {- return null;+ return {+ cwds: new Map(),+ queryFailed: true,+ };}+ return { cwds: parsePidCwds(result.stdout ?? ''), queryFailed: false };+}- const output = result.stdout ?? '';- for (const line of output.split('\n')) {- if (line.startsWith('n') && line.length > 1) {- return line.slice(1);- }+export function readPidCwds(pids: readonly number[]): Map<number, string> {+ if (pids.length === 0) return new Map();+ const batched = queryPidCwds(pids);+ if (!batched.queryFailed || pids.length === 1) return batched.cwds;+ const cwds = new Map<number, string>();+ for (const pid of pids) {+ const cwd = queryPidCwds([pid]).cwds.get(pid);+ if (cwd !== undefined) cwds.set(pid, cwd);}-- return null;+ return cwds;}function parseListeningPids(output: string): number[] {@@ -285,8 +308,8 @@ export async function discoverLockDirs(): Promise<string[]> {const candidateDirs = new Set<string>();const okEntries = await findOkProcessEntries();- const cwdPromises = okEntries.map((e) => pidCwd(e.pid));- const cwds = await Promise.all(cwdPromises);+ const okCwds = readPidCwds(okEntries.map((entry) => entry.pid));+ const cwds = okEntries.map((entry) => okCwds.get(entry.pid) ?? null);for (const entry of okEntries) {const markedLockDir = extractMarkedLockDir(entry.command);@@ -318,8 +341,8 @@ export async function discoverLockDirs(): Promise<string[]> {const listeningPids = parseListeningPids(lsofResult.stdout);const knownPidSet = new Set(okEntries.map((e) => e.pid));const newPids = listeningPids.filter((p) => !knownPidSet.has(p));- const portCwdPromises = newPids.map((pid) => pidCwd(pid));- const portCwds = await Promise.all(portCwdPromises);+ const portCwdsByPid = readPidCwds(newPids);+ const portCwds = newPids.map((pid) => portCwdsByPid.get(pid) ?? null);for (const cwd of portCwds) {if (cwd == null) continue;@@ -378,19 +401,14 @@ export async function scanLockProcesses(): Promise<LockProcessScan> {await add(join(project, '.ok', 'local'), pid, source);await add(join(project, '.ok'), pid, source);};- const addCwd = async (pid: number, source: 'process-cwd' | 'listener-cwd') => {- const cwd = await pidCwd(pid);- if (cwd) await addProject(cwd, pid, source);- else if (isProcessAlive(pid))- scan.unavailable.push(`Could not read the working directory of process ${pid}`);- };+ const pendingCwd: Array<{ pid: number; source: 'process-cwd' | 'listener-cwd' }> = [];for (const entry of entries) {if (!isValidLockPid(entry.pid)) continue;const marked = extractMarkedLockDir(entry.command);const project = extractProjectPathArg(entry.command);if (marked) await add(marked, entry.pid, 'lock-dir-argument');else if (project) await addProject(project, entry.pid, 'project-argument');- else await addCwd(entry.pid, 'process-cwd');+ else pendingCwd.push({ pid: entry.pid, source: 'process-cwd' });}const listeners = spawnSync('lsof',@@ -400,16 +418,22 @@ export async function scanLockProcesses(): Promise<LockProcessScan> {timeout: SPAWN_TIMEOUT_MS,}),);- if (- listeners.error ||- (listeners.status !== 0 && !(listeners.status === 1 && !listeners.stdout && !listeners.stderr))- ) {- scan.unavailable.push('Could not enumerate TCP listeners with lsof');- return scan;+ const listenersUnavailable =+ listeners.error != null ||+ (listeners.status !== 0 && !(listeners.status === 1 && !listeners.stdout && !listeners.stderr));+ if (!listenersUnavailable) {+ const known = new Set(entries.map((entry) => entry.pid));+ for (const pid of parseListeningPids(listeners.stdout ?? '')) {+ if (isValidLockPid(pid) && !known.has(pid)) pendingCwd.push({ pid, source: 'listener-cwd' });+ }}- const known = new Set(entries.map((entry) => entry.pid));- for (const pid of parseListeningPids(listeners.stdout ?? '')) {- if (isValidLockPid(pid) && !known.has(pid)) await addCwd(pid, 'listener-cwd');+ const cwds = readPidCwds(pendingCwd.map(({ pid }) => pid));+ for (const { pid, source } of pendingCwd) {+ const cwd = cwds.get(pid);+ if (cwd) await addProject(cwd, pid, source);+ else if (isProcessAlive(pid))+ scan.unavailable.push(`Could not read the working directory of process ${pid}`);}+ if (listenersUnavailable) scan.unavailable.push('Could not enumerate TCP listeners with lsof');return scan;}