repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
pi/agent/extensions/llmiterate/lock.ts
RawFile outline
- LOCK_DIR line 6
- OWNER_FILE line 7
- LockHandle line 9
- dir line 10
- token line 11
- LockOwner line 14
- pid line 15
- hostname line 16
- token line 17
- findProjectRoot line 20
- realPath line 30
- acquireLock line 34
- releaseLock line 53
- createOwner line 59
- tryCreateLock line 63
- readLockOwner line 74
- parseLockOwner line 82
- reclaimStaleLock line 94
- isStaleOwner line 112
- isProjectBoundary line 122
- parentDir line 128
- isDirectory line 133
- nodeErrorCode line 137
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { randomUUID } from "node:crypto";
const LOCK_DIR = "lock";
const OWNER_FILE = "owner.json";
export interface LockHandle {
dir: string;
token: string;
}
interface LockOwner {
pid: number;
hostname: string;
token: string;
}
export function findProjectRoot(cwd: string): string {
const start = realPath(cwd);
for (let dir: string | undefined = start; dir; dir = parentDir(dir)) {
if (isProjectBoundary(dir)) return realPath(dir);
}
return start;
}
export function realPath(file: string): string {
try { return fs.realpathSync(file); } catch { return path.resolve(file); }
}
export function acquireLock(storeDir: string): LockHandle | string {
const lockDir = path.join(storeDir, LOCK_DIR);
fs.mkdirSync(storeDir, { recursive: true });
const token = randomUUID();
const owner = createOwner(token);
const created = tryCreateLock(lockDir, owner);
if (created) return created;
const existing = readLockOwner(lockDir);
if (existing && isStaleOwner(existing)) {
const recovered = reclaimStaleLock(lockDir, existing, owner);
if (recovered) return recovered;
}
const by = existing ? `pid ${existing.pid} on ${existing.hostname}` : "another pi";
return `singleton lock held by ${by}`;
}
export function releaseLock(lock: LockHandle): void {
const owner = readLockOwner(lock.dir);
if (!owner || owner.token !== lock.token) return;
fs.rmSync(lock.dir, { recursive: true, force: true });
}
function createOwner(token: string): LockOwner {
return { pid: process.pid, hostname: os.hostname(), token };
}
function tryCreateLock(lockDir: string, owner: LockOwner): LockHandle | undefined {
try {
fs.mkdirSync(lockDir);
fs.writeFileSync(path.join(lockDir, OWNER_FILE), JSON.stringify(owner, null, 2) + "\n", "utf-8");
return { dir: lockDir, token: owner.token };
} catch (error) {
if (nodeErrorCode(error) !== "EEXIST") throw error;
return undefined;
}
}
function readLockOwner(lockDir: string): LockOwner | undefined {
try {
return parseLockOwner(JSON.parse(fs.readFileSync(path.join(lockDir, OWNER_FILE), "utf-8")));
} catch {
return undefined;
}
}
function parseLockOwner(value: unknown): LockOwner | undefined {
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
const keys = Object.keys(value).sort();
if (keys.join("\0") !== "hostname\0pid\0token") return undefined;
const owner = value as Partial<LockOwner>;
if (typeof owner.pid !== "number") return undefined;
if (typeof owner.hostname !== "string") return undefined;
if (typeof owner.token !== "string") return undefined;
return { pid: owner.pid, hostname: owner.hostname, token: owner.token };
}
function reclaimStaleLock(lockDir: string, staleOwner: LockOwner, newOwner: LockOwner): LockHandle | undefined {
const reclaimedDir = `${lockDir}.stale.${newOwner.token}`;
try {
fs.renameSync(lockDir, reclaimedDir);
} catch {
return undefined;
}
const movedOwner = readLockOwner(reclaimedDir);
if (movedOwner?.token !== staleOwner.token) {
try { fs.renameSync(reclaimedDir, lockDir); } catch {}
return undefined;
}
fs.rmSync(reclaimedDir, { recursive: true, force: true });
return tryCreateLock(lockDir, newOwner);
}
function isStaleOwner(owner: LockOwner): boolean {
if (owner.hostname !== os.hostname()) return false;
try {
process.kill(owner.pid, 0);
return false;
} catch (error) {
return nodeErrorCode(error) === "ESRCH";
}
}
function isProjectBoundary(dir: string): boolean {
return isDirectory(path.join(dir, ".pi"))
|| fs.existsSync(path.join(dir, "AGENTS.md"))
|| fs.existsSync(path.join(dir, ".git"));
}
function parentDir(dir: string): string | undefined {
const parent = path.dirname(dir);
return parent === dir ? undefined : parent;
}
function isDirectory(file: string): boolean {
try { return fs.statSync(file).isDirectory(); } catch { return false; }
}
function nodeErrorCode(error: unknown): string | undefined {
return error instanceof Error && "code" in error ? String((error as NodeJS.ErrnoException).code) : undefined;
}