import { stateRoot } from '../../lib/harness-context.js'; import { timeStartup } from '../../../bin/startup-trace.mjs'; import { createHash, randomUUID } from 'node:crypto'; import { mkdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import type { AuthData, AuthProfile } from '../../lib/auth.js'; import { getRuntimeAccountId, getWorkspaceDir } from '../../lib/init-command.js'; import { getRuntimeDir, getUserDataAuthFile } from '../../lib/user-data.js'; import { isDesktopMode } from '../../lib/desktop-mode.js'; import { tryAcquireWorkspaceRuntimeLock, type WorkspaceRuntimeLock } from '../../lib/workspace-runtime-lock.js'; import { readGameStartRuntime, sendOwnerControlRequestTo } from '../owner-control.js'; import { inspectProcessIdentity, sameProcessIdentity, terminateVerifiedProcess, type ProcessIdentity } from '../process-identity.js'; import { OwnerLockError, type OwnerBlocker } from './owner-lock-error.js'; export type OwnerPhase = 'starting' | 'ready' | 'stopping'; export interface OwnerLock extends WorkspaceRuntimeLock { instanceId: string; setPhase(phase: OwnerPhase): void; } export interface OwnerRecord { schema: 'clawclaw.workspace-owner.v1'; instance_id: string; pid: number; runtime_account_id: string; workspace_id: string; process_identity: ProcessIdentity | null; phase?: OwnerPhase; } export interface OwnerLockOperations { inspectProcess(pid: number): ProcessIdentity | null; requestStop(stateDir: string, owner: OwnerRecord): Promise; terminateProcess(pid: number, identity: ProcessIdentity, signal: NodeJS.Signals): void; } const defaultOperations: OwnerLockOperations = { inspectProcess: inspectProcessIdentity, async requestStop(stateDir, owner) { const pointer = readGameStartRuntime(stateDir); if (pointer?.owner_pid !== owner.pid || pointer?.instance_id !== owner.instance_id) return; await sendOwnerControlRequestTo(pointer, 'stop', { instance_id: owner.instance_id }); }, terminateProcess: terminateVerifiedProcess, }; const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); export function workspaceOwnerRecordPath(workspaceDir = getWorkspaceDir()): string { // Windows exclusive byte locks prevent reads, so metadata has its own file. return join(getRuntimeDir(workspaceDir), 'owner.json'); } export function workspaceOwnerIdentity(workspaceDir = getWorkspaceDir()): string { const real = realpathSync(stateRoot(workspaceDir)); return createHash('sha256').update(process.platform === 'win32' ? real.toLowerCase() : real).digest('hex'); } function readOwnerRecord(path: string): OwnerRecord | null { try { const value = JSON.parse(readFileSync(path, 'utf8')) as OwnerRecord; return value?.schema === 'clawclaw.workspace-owner.v1' && Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.instance_id === 'string' && value.instance_id.length > 0 && value.instance_id.length <= 64 && /^[a-f0-9]{64}$/.test(value.workspace_id) && /^acct_[a-f0-9]{32}$/.test(value.runtime_account_id) ? value : null; } catch { return null; } } export function readWorkspaceOwnerRecord(workspaceDir = getWorkspaceDir()): OwnerRecord | null { return readOwnerRecord(workspaceOwnerRecordPath(workspaceDir)); } function validIdentity(value: ProcessIdentity | null): value is ProcessIdentity { return !!value && typeof value.birth === 'string' && value.birth.length > 0 && typeof value.executable === 'string' && value.executable.length > 0 && Number.isFinite(value.startedAtMs); } function describeBlocker(record: OwnerRecord | null, operations: OwnerLockOperations): OwnerBlocker { if (!record) return { pid: null, pid_source: 'unknown', identity: 'not_recorded' }; const expected = validIdentity(record.process_identity) ? record.process_identity : null; const actual = expected ? operations.inspectProcess(record.pid) : null; return { pid: record.pid, pid_source: 'owner_record', instance_id: record.instance_id, phase: ['starting', 'ready', 'stopping'].includes(record.phase ?? '') ? record.phase : undefined, ...(expected ? { started_at_ms: expected.startedAtMs } : {}), identity: !expected ? 'not_recorded' : !actual ? 'unavailable' : sameProcessIdentity(expected, actual) ? 'matched' : 'mismatch', }; } function claimOwner( held: WorkspaceRuntimeLock, workspaceDir: string, profile: Pick, record: OwnerRecord, tempPath: string, ): OwnerLock { const recordPath = workspaceOwnerRecordPath(workspaceDir); try { // All expensive preparation and the complete write happened BEFORE locking. // The first operation after winning the system lock publishes our identity. renameSync(tempPath, recordPath); let auth: AuthData | undefined; try { auth = JSON.parse(readFileSync(getUserDataAuthFile(workspaceDir), 'utf8')) as AuthData; } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } if ((auth || isDesktopMode()) && auth?.profiles[auth.activeProfile]?.apiKey !== profile.apiKey) { throw new Error('The active ClawClaw account changed during startup. Retry with the current account.'); } let released = false; return { instanceId: record.instance_id, setPhase(phase) { if (released) throw new Error('ClawClaw workspace lock is already released.'); if (readOwnerRecord(recordPath)?.instance_id !== record.instance_id) { throw new Error('ClawClaw owner metadata changed while the workspace is locked.'); } record.phase = phase; try { writeFileSync(tempPath, JSON.stringify(record), { mode: 0o600 }); renameSync(tempPath, recordPath); } finally { try { unlinkSync(tempPath); } catch {} } }, release() { if (released) return; released = true; try { if (readOwnerRecord(recordPath)?.instance_id === record.instance_id) { try { unlinkSync(recordPath); } catch {} } } finally { held.release(); } }, }; } catch (error) { try { if (readOwnerRecord(recordPath)?.instance_id === record.instance_id) unlinkSync(recordPath); } catch {} held.release(); throw error; } } export async function acquireOwnerLock( profile: Pick, options: { force?: boolean; operations?: OwnerLockOperations } = {}, ): Promise { const workspaceDir = getWorkspaceDir(); const operations = options.operations ?? defaultOperations; const recordPath = workspaceOwnerRecordPath(workspaceDir); mkdirSync(dirname(recordPath), { recursive: true }); const prepared: OwnerRecord = { schema: 'clawclaw.workspace-owner.v1', instance_id: randomUUID(), pid: process.pid, runtime_account_id: getRuntimeAccountId(profile), process_identity: timeStartup('owner.process_identity', () => operations.inspectProcess(process.pid)), workspace_id: workspaceOwnerIdentity(workspaceDir), phase: 'starting', }; const tempPath = `${recordPath}.${prepared.instance_id}.tmp`; const claim = (held: WorkspaceRuntimeLock) => claimOwner(held, workspaceDir, profile, prepared, tempPath); const fail = (code: string, reason: string, record: OwnerRecord | null, osError?: string): never => { throw new OwnerLockError(code, reason, describeBlocker(record, operations), osError); }; try { writeFileSync(tempPath, JSON.stringify(prepared), { mode: 0o600, flag: 'wx' }); let record: OwnerRecord | null = null; for (let attempt = 0; attempt < 40; attempt++) { const held = timeStartup('owner.os_lock', () => tryAcquireWorkspaceRuntimeLock(workspaceDir)); if (held) return claim(held); record = readOwnerRecord(recordPath); if (record) break; await sleep(50); } if (!record) return fail('CCL_OWNER_UNKNOWN', 'Workspace locked; owner identity is missing, unreadable, or incomplete. No process was terminated.', null); if (record.workspace_id !== prepared.workspace_id) { return fail('CCL_OWNER_SCOPE_MISMATCH', 'Owner record belongs to a different workspace. No process was terminated.', record); } if (!options.force) { return fail('CCL_OWNER_BUSY', `A ClawClaw runtime is already running (pid ${record.pid}) in this workspace. Re-run with --force to replace it.`, record); } if (record.runtime_account_id !== prepared.runtime_account_id) { return fail('CCL_OWNER_OTHER_ACCOUNT', 'Another account owns this workspace. Stop it first or use a different workspace.', record); } if (record.pid === process.pid) return fail('CCL_OWNER_SELF', 'Refusing to replace the current ClawClaw runtime process.', record); const target = record; const checkGeneration = (requireRecord: boolean): void => { const current = readOwnerRecord(recordPath); if (current && current.instance_id !== target.instance_id) { fail('CCL_OWNER_CHANGED', 'The active ClawClaw runtime changed during replacement; no new instance was terminated.', current); } if (current && current.workspace_id !== prepared.workspace_id) { fail('CCL_OWNER_SCOPE_MISMATCH', 'Owner record changed to a different workspace. No process was terminated.', current); } if (!current && requireRecord) { fail('CCL_OWNER_UNKNOWN', 'Owner identity disappeared while the workspace remained locked. No process was terminated.', null); } }; const waitForLock = async (timeoutMs: number): Promise => { const deadline = Date.now() + timeoutMs; do { const held = tryAcquireWorkspaceRuntimeLock(workspaceDir); if (held) return held; // Normal teardown removes metadata just before releasing the system lock. checkGeneration(false); await sleep(50); } while (Date.now() < deadline); return null; }; checkGeneration(true); const stateDir = join(getRuntimeDir(workspaceDir), 'accounts', target.runtime_account_id); try { await operations.requestStop(stateDir, target); } catch {} let held = await waitForLock(1_500); if (held) return claim(held); for (const [signal, timeout] of [['SIGTERM', 1_500], ['SIGKILL', 2_000]] as const) { held = tryAcquireWorkspaceRuntimeLock(workspaceDir); if (held) return claim(held); checkGeneration(true); if (!validIdentity(target.process_identity) || !sameProcessIdentity(target.process_identity, operations.inspectProcess(target.pid))) { return fail('CCL_OWNER_UNVERIFIED', 'Unable to verify the recorded runtime identity; no process was terminated.', target); } try { operations.terminateProcess(target.pid, target.process_identity, signal); } catch (error) { // The target may have exited between verification and signalling. held = tryAcquireWorkspaceRuntimeLock(workspaceDir); if (held) return claim(held); checkGeneration(true); const osError = typeof (error as NodeJS.ErrnoException)?.code === 'string' ? (error as NodeJS.ErrnoException).code!.slice(0, 40) : 'termination_failed'; return fail('CCL_OWNER_STOP_FAILED', 'The OS did not terminate the old runtime; the workspace remains locked.', target, osError); } held = await waitForLock(timeout); if (held) return claim(held); } return fail('CCL_OWNER_STOP_FAILED', 'Unable to replace the old runtime; the workspace remains locked.', target); } finally { try { unlinkSync(tempPath); } catch {} } }