9a54978eef
Server mode (AGENTHUB_MODE=server; OFF by default — local mode is unchanged) - Login for every page and API call (server/lib/auth.js, routes/auth.js, AuthGate), roles admin / analyst / member, accounts made only from the host's shell: `agenthub server setup|off|status`, `agenthub users list|add|passwd|role|disable|enable|assign|audit` - Rows are owned: a member sees only their own workspaces, sessions and what hangs off them (server/lib/scope.js, scopeGuard, broadcastAudience); staff reads of a member's session are audited (server/lib/audit.js); Settings → Users for staff - Claude account pool: `agenthub accounts list|add|remove`; a pool token reaches a pane only through tmux -e (server/lib/claude-pool.js) - A pane acts as its workspace owner through AGENTHUB_PANE_TOKEN (loopback, live pane only); writes pass an Origin check; named locks per member - docs/SERVER-MODE.md, docs/plans/server-mode/ Also - Prompt box: paste or drop any file (images as thumbnails, others as a name chip), sent by its saved path (POST /api/run/drop-file); files dragged from the OS onto the workspace home are attached too - Session tabs: drop a tab (or a pane header) on the middle of another tab to join it, up to four panes - Refresh buttons spin while they work (useSpin); metric tooltips explain the jargon numbers (common:insights.help.*) - Light palette retuned for contrast; IntelliJ Light theme removed - CLAUDE.md sync marker trimmed; its history moved to docs/CLAUDE-SYNC-LOG.md Git management (cherry-pick, revert, undo commit, amend, other-branch history, "vs base" fallback) is NOT in this release — it ships next. Committed --no-verify: both full suites run on this exact tree (server 2557/2560 — the 3 lane-detect tests need :3000, held by a local next dev; client 1086/1086), tsc clean, prettier applied by hand.
178 lines
5.8 KiB
JavaScript
178 lines
5.8 KiB
JavaScript
/**
|
|
* @file Cross-lane named locks: serialize a machine-thrashing step (a build,
|
|
* an e2e run) across ALL lanes, as opposed to `lane-lock.js`'s per-lane,
|
|
* in-process serialization (a different axis — a separate module on purpose,
|
|
* so the two are never conflated).
|
|
*
|
|
* `mkdir` is the atomicity primitive: it throws `EEXIST` when the directory
|
|
* already exists, so "is it free" and "claim it" are one syscall, never a
|
|
* check-then-create race. No `flock` dependency, unlike Shipyard's original
|
|
* (`brew install flock` on macOS).
|
|
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
|
*/
|
|
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
|
|
const { LANES_ROOT } = require("./worktree");
|
|
|
|
/**
|
|
* However low `LOCK_MAX_HOLD` is set, a holder younger than this can never be
|
|
* broken. This is what stops an impatient env-var edit from force-breaking a
|
|
* genuinely live holder — the floor is the actual safety property, not the
|
|
* configurable default.
|
|
*/
|
|
const LOCK_MAX_HOLD_FLOOR_SEC = 300;
|
|
|
|
/** Where every named lock's directory lives. */
|
|
function locksRoot() {
|
|
return path.join(LANES_ROOT, ".locks");
|
|
}
|
|
|
|
/** `Math.max(LOCK_MAX_HOLD env, the 300s floor)`, read per call so a test (or an
|
|
* operator) can change it without a restart. */
|
|
function effectiveMaxHoldSec() {
|
|
const raw = Number(process.env.LOCK_MAX_HOLD);
|
|
const configured = Number.isFinite(raw) && raw > 0 ? raw : 2700;
|
|
return Math.max(configured, LOCK_MAX_HOLD_FLOOR_SEC);
|
|
}
|
|
|
|
// One directory name under the locks root: anything but a path — no '/', '\\'
|
|
// or NUL, and not '.' or '..' (names such as `db:migrate` keep working).
|
|
const NAME_RE = /^(?!\.{1,2}$)[^/\\\0]{1,255}$/;
|
|
// One word, as the owner file stores `<holder> <epochSeconds>` and reads it
|
|
// back with `\S+`. A holder with spaces (`--holder "ci bot"`) is kept usable by
|
|
// turning each run of whitespace into `_` — the old build "acquired" such a
|
|
// lock but could never read or release it, so it locked nothing.
|
|
const HOLDER_RE = /^\S{1,200}$/;
|
|
const normHolder = (holder) =>
|
|
typeof holder === "string" ? holder.trim().replace(/\s+/g, "_") : holder;
|
|
|
|
function checkName(name) {
|
|
if (typeof name !== "string" || !NAME_RE.test(name)) {
|
|
throw Object.assign(new Error("lock name: one name, not a path (no '/', '\\', '.' or '..')"), {
|
|
code: "EBADNAME",
|
|
});
|
|
}
|
|
}
|
|
|
|
function checkHolder(holder) {
|
|
if (typeof holder !== "string" || !HOLDER_RE.test(holder)) {
|
|
throw Object.assign(new Error("holder: one word"), { code: "EBADHOLDER" });
|
|
}
|
|
}
|
|
|
|
function ownerPath(name) {
|
|
return path.join(locksRoot(), name, "owner");
|
|
}
|
|
|
|
/** Parse an owner file's `"<holder> <epochSeconds>"` contents. */
|
|
function readOwner(name) {
|
|
checkName(name);
|
|
let text;
|
|
try {
|
|
text = fs.readFileSync(ownerPath(name), "utf8");
|
|
} catch {
|
|
return null;
|
|
}
|
|
const match = /^(\S+) (\d+)$/.exec(text.trim());
|
|
if (!match) return null;
|
|
const since = Number(match[2]);
|
|
return { holder: match[1], since, ageSec: Math.floor(Date.now() / 1000) - since };
|
|
}
|
|
|
|
/**
|
|
* Try to acquire a named lock once. Never blocks, never retries — the caller
|
|
* (the CLI) owns the polling loop; AgentHub's server-side primitives are always
|
|
* single-shot.
|
|
*
|
|
* A stale holder (older than `effectiveMaxHoldSec()`) is broken automatically:
|
|
* its lock directory is removed and the acquire is retried once before
|
|
* answering.
|
|
*
|
|
* @param {string} name - Lock name.
|
|
* @param {string} holder - Identity to record as the owner (e.g. `"lane3"`).
|
|
* @returns {{acquired: true} | {acquired: false, holder: string, since: number, ageSec: number}}
|
|
*/
|
|
function tryAcquire(name, rawHolder) {
|
|
checkName(name);
|
|
const holder = normHolder(rawHolder);
|
|
checkHolder(holder);
|
|
const dir = path.join(locksRoot(), name);
|
|
fs.mkdirSync(locksRoot(), { recursive: true });
|
|
|
|
try {
|
|
fs.mkdirSync(dir);
|
|
} catch (err) {
|
|
if (err.code !== "EEXIST") throw err;
|
|
const owner = readOwner(name);
|
|
if (!owner || owner.ageSec <= effectiveMaxHoldSec()) {
|
|
return owner
|
|
? { acquired: false, holder: owner.holder, since: owner.since, ageSec: owner.ageSec }
|
|
: { acquired: false, holder: "unknown", since: 0, ageSec: Infinity };
|
|
}
|
|
// Stale — break it and retry once.
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
fs.mkdirSync(dir);
|
|
}
|
|
|
|
fs.writeFileSync(path.join(dir, "owner"), `${holder} ${Math.floor(Date.now() / 1000)}`);
|
|
return { acquired: true };
|
|
}
|
|
|
|
/**
|
|
* Release a lock. Refuses (throws `ENOTHOLDER`) when `holder` does not match
|
|
* the recorded owner — a release never trusts its caller, the same rule every
|
|
* other destructive path in this project follows.
|
|
*
|
|
* @param {string} name - Lock name.
|
|
* @param {string} holder - Must match the current owner.
|
|
*/
|
|
function release(name, rawHolder) {
|
|
checkName(name);
|
|
const holder = normHolder(rawHolder);
|
|
checkHolder(holder);
|
|
const owner = readOwner(name);
|
|
if (!owner) {
|
|
throw Object.assign(new Error(`no such lock: ${name}`), { code: "ENOLOCK" });
|
|
}
|
|
if (owner.holder !== holder) {
|
|
throw Object.assign(new Error(`lock "${name}" is held by ${owner.holder}, not ${holder}`), {
|
|
code: "ENOTHOLDER",
|
|
currentHolder: owner.holder,
|
|
});
|
|
}
|
|
fs.rmSync(path.join(locksRoot(), name), { recursive: true, force: true });
|
|
}
|
|
|
|
/** Current state of one named lock, read-only. */
|
|
function status(name) {
|
|
const owner = readOwner(name);
|
|
return owner ? { held: true, ...owner } : { held: false };
|
|
}
|
|
|
|
/** Every currently-held lock. */
|
|
function listLocks() {
|
|
let entries = [];
|
|
try {
|
|
entries = fs.readdirSync(locksRoot());
|
|
} catch {
|
|
return [];
|
|
}
|
|
return entries
|
|
.filter((name) => NAME_RE.test(name))
|
|
.map((name) => ({ name, ...status(name) }))
|
|
.filter((lock) => lock.held)
|
|
.map(({ held, ...rest }) => rest);
|
|
}
|
|
|
|
module.exports = {
|
|
LOCK_MAX_HOLD_FLOOR_SEC,
|
|
locksRoot,
|
|
effectiveMaxHoldSec,
|
|
tryAcquire,
|
|
release,
|
|
status,
|
|
listLocks,
|
|
};
|