akm-cli
Version:
akm (Agent Knowledge Manager) — a portable, local-first capability library for AI agents. Discover, load, share, and improve reusable skills, scripts, workflows, and knowledge across any shell-capable coding agent, including Claude Code, OpenCode, and Cur
329 lines (328 loc) • 12.4 kB
JavaScript
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
/**
* PID-stamped exclusive lock files.
*
* A lock is one file created with `O_EXCL` (`wx`), which the filesystem
* makes atomic: exactly one creator wins, so no further mutex or barrier is
* needed around acquisition. The payload records the holder's PID (and the
* launcher PID under a scheduler) so a probe can tell a live holder from a
* dead one; only a verifiably dead holder is ever reclaimed. A live PID is not
* proof of a live holder (a container entrypoint is PID 1 on every start, PIDs
* are reused after a reboot), so where the OS exposes it the payload also
* records the holder's boot id and process start time; a live PID with a
* different identity is a reused PID and the lock is stale. Reclaim moves the
* stale file aside, re-verifies it is the very file that was probed, and only
* then unlinks it, so two reclaimers cannot both "win" the same stale lock.
*
* Publication is a hard link of a fully written temp file. On filesystems
* without hard links (Azure Files SMB) it falls back to an `O_EXCL` create plus
* write; reclaim then leaves a freshly created empty lock alone for a short
* grace period.
*/
import { randomUUID } from "node:crypto";
import fs from "node:fs";
import { isProcessAlive, MAX_LOCK_METADATA_BYTES, readTextFileDescriptorWithLimit } from "./common.js";
/** Locks this process acquired and has not released, by path, so a lock naming our own PID that we do not hold is known to be left over. */
const acquiredByThisProcess = new Map();
function readLockSnapshot(lockPath) {
let fd;
try {
fd = fs.openSync(lockPath, "r");
}
catch (err) {
if (err.code === "ENOENT")
return undefined;
throw err;
}
try {
const rawContent = readTextFileDescriptorWithLimit(fd, MAX_LOCK_METADATA_BYTES, "Lock metadata", lockPath);
const stat = fs.fstatSync(fd);
return {
rawContent,
identity: { dev: stat.dev, ino: stat.ino, size: stat.size, mtimeMs: stat.mtimeMs },
};
}
finally {
fs.closeSync(fd);
}
}
function sameIdentity(left, right) {
return left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs;
}
/**
* A just-created lock file on a filesystem without hard links is briefly empty
* (see `createLockFileExclusive`). A probe younger than this reads that as
* "initialising", not stale, so a live acquirer is never reclaimed.
*/
const UNINITIALISED_LOCK_GRACE_MS = 2000;
/** `link()` errnos that mean "this filesystem has no hard links" (SMB/CIFS, some FUSE mounts). */
function isHardLinkUnsupported(error) {
const code = error?.code;
return code === "ENOTSUP" || code === "EOPNOTSUPP" || code === "EPERM" || code === "EINVAL";
}
/**
* Hard-link-free exclusive publish: `O_EXCL` create, then write the payload.
* The file exists empty for an instant; `reclaimStaleLock` refuses to reclaim
* an empty lock younger than `UNINITIALISED_LOCK_GRACE_MS`. Returns false when
* another holder already has the path.
*/
function createLockFileExclusive(lockPath, payload) {
let fd;
try {
fd = fs.openSync(lockPath, "wx");
}
catch (err) {
if (err.code === "EEXIST")
return false;
throw err;
}
try {
fs.writeSync(fd, payload);
}
catch (error) {
fs.closeSync(fd);
releaseLockRaw(lockPath);
throw error;
}
fs.closeSync(fd);
return true;
}
function releaseLockRaw(lockPath) {
try {
fs.unlinkSync(lockPath);
}
catch {
// Already gone.
}
}
/** Create the lock file atomically; `undefined` when another holder already has it. */
export function tryAcquireLockSync(lockPath, payload) {
// Write the payload under a private name, then hard-link it into place: the
// link is the exclusive step and the lock never exists without its payload.
// A `wx` write creates the file empty and fills it in afterwards; a contender
// probing in that gap reads no pid, calls the live lock stale and reclaims it.
const tmpPath = `${lockPath}.tmp-${process.pid}-${randomUUID()}`;
fs.writeFileSync(tmpPath, payload, { flag: "wx" });
try {
fs.linkSync(tmpPath, lockPath);
}
catch (err) {
if (err.code === "EEXIST")
return undefined;
if (!isHardLinkUnsupported(err))
throw err;
if (!createLockFileExclusive(lockPath, payload))
return undefined;
}
finally {
releaseLockRaw(tmpPath);
}
let snapshot;
try {
snapshot = readLockSnapshot(lockPath);
}
catch (error) {
releaseLockRaw(lockPath);
throw error;
}
if (!snapshot) {
releaseLockRaw(lockPath);
throw new Error(`Could not read newly acquired lock at ${lockPath}.`);
}
// Another process reclaimed our still-empty lock and took the path: we lost the race.
if (snapshot.rawContent !== payload)
return undefined;
acquiredByThisProcess.set(lockPath, payload);
return { lockPath, ...snapshot };
}
/**
* What a reused PID cannot fake: the kernel boot id and the process start time
* (`/proc/<pid>/stat` field 22, in ticks since boot). Linux only; `undefined`
* elsewhere or when `/proc` is unreadable, which leaves the PID as the only evidence.
*/
export function processIdentity(pid) {
try {
const bootId = fs.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
// The command name (field 2) may contain spaces and parens; fields resume after the last ")".
const startTime = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
return bootId && startTime ? { bootId, startTime } : undefined;
}
catch {
return undefined;
}
}
/** True when the lock records an identity and the live holder PID now has a different one. */
function holderPidReused(holderPid, recorded) {
if (typeof recorded.bootId !== "string" || typeof recorded.startTime !== "string")
return false;
const current = processIdentity(holderPid);
if (!current)
return false;
return current.bootId !== recorded.bootId || current.startTime !== recorded.startTime;
}
function launcherPidFromEnv() {
const raw = process.env.AKM_LAUNCHER_PID;
if (!raw)
return undefined;
const pid = Number.parseInt(raw, 10);
return Number.isInteger(pid) && pid > 0 ? pid : undefined;
}
export function createLockPayload(metadata = {}) {
const launcherPid = launcherPidFromEnv();
return JSON.stringify({
...metadata,
pid: process.pid,
...processIdentity(process.pid),
...(launcherPid !== undefined ? { launcherPid } : {}),
lockId: randomUUID(),
});
}
export function probeLock(lockPath) {
let snapshot;
try {
snapshot = readLockSnapshot(lockPath);
}
catch (error) {
const code = error?.code;
if (code === "EACCES" || code === "EPERM")
return { state: "inaccessible", code };
return { state: "stale", reason: "unreadable" };
}
if (!snapshot)
return { state: "absent" };
const { rawContent, identity } = snapshot;
const ageMs = Date.now() - identity.mtimeMs;
const { holderPid, launcherPid } = extractLockIdentity(rawContent);
if (holderPid === undefined) {
return { state: "stale", reason: "invalid_pid", ageMs, rawContent, identity };
}
if (!isProcessAlive(holderPid)) {
return { state: "stale", reason: "pid_dead", holderPid, launcherPid, ageMs, rawContent, identity };
}
// A lock naming this process that it did not acquire is left over from an earlier process with the same PID; so is
// one whose recorded identity no longer matches the live holder.
const ownLeftover = holderPid === process.pid && acquiredByThisProcess.get(lockPath) !== rawContent;
if (ownLeftover || holderPidReused(holderPid, parseLockJson(rawContent))) {
return { state: "stale", reason: "pid_reused", holderPid, launcherPid, ageMs, rawContent, identity };
}
return { state: "held", holderPid, launcherPid, ageMs, rawContent, identity };
}
/**
* Remove a lock that `probeLock` reported stale. Returns `false` when the file
* changed since the probe (someone else reclaimed or re-acquired it) so the
* caller re-probes instead of assuming the path is free.
*/
export function reclaimStaleLock(lockPath, probe, options) {
if (probe.rawContent === undefined || probe.identity === undefined)
return false;
// An empty lock this young may be mid-initialisation on a filesystem without hard links.
if (probe.rawContent.trim() === "" && (probe.ageMs ?? 0) < UNINITIALISED_LOCK_GRACE_MS)
return false;
const expectedContent = probe.rawContent;
const expectedIdentity = probe.identity;
let current;
try {
current = readLockSnapshot(lockPath);
}
catch {
return false;
}
if (!current || current.rawContent !== expectedContent || !sameIdentity(current.identity, expectedIdentity)) {
return false;
}
const quarantinePath = `${lockPath}.stale-${process.pid}-${randomUUID()}`;
try {
fs.renameSync(lockPath, quarantinePath);
}
catch (err) {
if (err.code === "ENOENT")
return false;
throw err;
}
let quarantined;
try {
quarantined = readLockSnapshot(quarantinePath);
}
catch {
quarantined = undefined;
}
if (!quarantined ||
quarantined.rawContent !== expectedContent ||
!sameIdentity(quarantined.identity, expectedIdentity)) {
// The file we moved aside is not the one we probed: a fresh holder took
// the path in between. Put it back and report no reclaim.
try {
fs.linkSync(quarantinePath, lockPath);
}
catch (err) {
if (isHardLinkUnsupported(err)) {
// Rename keeps the inode, so the owner's identity-checked release still matches.
if (!fs.existsSync(lockPath))
fs.renameSync(quarantinePath, lockPath);
}
else if (err.code !== "EEXIST")
throw err;
}
releaseLockRaw(quarantinePath);
return false;
}
options?.afterQuarantineVerified?.();
try {
fs.unlinkSync(quarantinePath);
return true;
}
catch (err) {
if (err.code === "ENOENT")
return false;
throw err;
}
}
/** Unlink the lock only while it is still the exact file this owner created. */
export function releaseLock(ownership) {
const { lockPath } = ownership;
if (acquiredByThisProcess.get(lockPath) === ownership.rawContent)
acquiredByThisProcess.delete(lockPath);
let current;
try {
current = readLockSnapshot(lockPath);
}
catch {
return;
}
if (current && current.rawContent === ownership.rawContent && sameIdentity(current.identity, ownership.identity)) {
releaseLockRaw(lockPath);
}
}
function parseLockJson(content) {
try {
const parsed = JSON.parse(content);
return typeof parsed === "object" && parsed !== null ? parsed : {};
}
catch {
return {};
}
}
function extractLockIdentity(content) {
const trimmed = content.trim();
if (!trimmed)
return {};
if (trimmed.startsWith("{")) {
try {
const parsed = JSON.parse(trimmed);
const pid = typeof parsed.pid === "number" ? parsed.pid : Number.NaN;
const rawLauncherPid = typeof parsed.launcherPid === "number" ? parsed.launcherPid : Number.NaN;
return {
holderPid: Number.isInteger(pid) && pid > 0 ? pid : undefined,
launcherPid: Number.isInteger(rawLauncherPid) && rawLauncherPid > 0 ? rawLauncherPid : undefined,
};
}
catch {
return {};
}
}
const pid = Number.parseInt(trimmed, 10);
return { holderPid: Number.isInteger(pid) && pid > 0 ? pid : undefined };
}