nomad / scripts /lib /session-lock.js
LucioLiu's picture
Initial release - mirrors github.com/LucioLiu/nomad
0110783 verified
Raw
History Blame Contribute Delete
5.07 kB
#!/usr/bin/env node
'use strict';
/**
* session-lock.js — cross-harness soft session lock (Nomad scripts/ port).
*
* Purpose: the same agent home can get opened by more than one harness/session
* at once (a human borrowing the same agent from two tools, an automated check
* plus a manual window, etc). This is a SOFT lock — it never blocks anyone, it
* only turns "I don't know if someone else is in here" into a visible warning
* that a human or the calling agent can act on. It is deliberately not a real
* mutex: portable teams get borrowed across harnesses on purpose, and a hard
* lock would get in the way of that legitimate workflow.
*
* State file: `<memory-dir>/.session_lock.json` where memory-dir is whichever
* of the naming candidates (`记忆`, `memory`) exists under the agent home —
* see config.js firstExisting() and the "naming agnosticism" note in README.md.
* If neither exists yet, the lock file is written straight into the agent home
* root as a last resort so the feature degrades instead of throwing.
*
* Exposed both as a requirable module (used by session-start.js/session-stop.js
* directly — no subprocess needed since everything lives in the same package)
* and as a standalone CLI for manual diagnosis:
* node session-lock.js acquire <agent-home-abs-path> <harness-name>
* node session-lock.js release <agent-home-abs-path>
* node session-lock.js check <agent-home-abs-path>
*/
const fs = require('fs');
const path = require('path');
const cfg = require('./config');
const TTL_MS = 4 * 60 * 60 * 1000; // 4 hours
const MEMORY_DIR_CANDIDATES = ['记忆', 'memory'];
const LOCK_FILENAME = '.session_lock.json';
function lockFilePath(agentHome) {
const memDir = cfg.firstExisting(agentHome, MEMORY_DIR_CANDIDATES) || agentHome;
return path.join(memDir, LOCK_FILENAME);
}
function readLockFile(lp) {
if (!fs.existsSync(lp)) return null;
try {
return JSON.parse(cfg.readTextFileStripBOM(lp));
} catch (e) {
return null; // a corrupted lock file is treated as "no lock" — never let it wedge the flow
}
}
function isExpired(lockData, now) {
if (!lockData || !lockData.acquiredAt) return true;
const acquiredMs = Date.parse(lockData.acquiredAt);
if (Number.isNaN(acquiredMs)) return true;
const ttlMs = typeof lockData.ttlMs === 'number' ? lockData.ttlMs : TTL_MS;
return now - acquiredMs > ttlMs;
}
function acquire(agentHome, harness) {
if (!agentHome || !fs.existsSync(agentHome)) return { ok: false, error: 'agent home does not exist: ' + agentHome };
if (!harness) return { ok: false, error: 'missing harness name' };
const lp = lockFilePath(agentHome);
try {
fs.mkdirSync(path.dirname(lp), { recursive: true });
} catch (e) {
/* ignore — writeFileSync below will surface any real problem */
}
const now = Date.now();
const existing = readLockFile(lp);
let warned = false;
let priorHolder = null;
if (existing && !isExpired(existing, now)) {
warned = true;
priorHolder = existing;
}
const newLock = { harness: harness, pid: process.pid, acquiredAt: new Date(now).toISOString(), ttlMs: TTL_MS };
try {
fs.writeFileSync(lp, JSON.stringify(newLock, null, 2), 'utf8');
} catch (e) {
return { ok: false, error: 'failed to write lock file: ' + e.message };
}
return { ok: true, warned: warned, priorHolder: priorHolder, current: newLock, path: lp };
}
function release(agentHome) {
if (!agentHome || !fs.existsSync(agentHome)) return { ok: false, error: 'agent home does not exist: ' + agentHome };
const lp = lockFilePath(agentHome);
let existed = fs.existsSync(lp);
try {
fs.unlinkSync(lp);
} catch (e) {
existed = false; // missing or failed delete both read as "already released" — release is idempotent
}
return { ok: true, existed: existed, path: lp };
}
function check(agentHome) {
if (!agentHome || !fs.existsSync(agentHome)) return { ok: false, error: 'agent home does not exist: ' + agentHome };
const lp = lockFilePath(agentHome);
const existing = readLockFile(lp);
if (!existing) return { ok: true, hasLock: false, path: lp };
return { ok: true, hasLock: true, expired: isExpired(existing, Date.now()), lock: existing, path: lp };
}
function main() {
const argv = process.argv.slice(2);
const sub = argv[0];
const agentHome = argv[1] ? path.resolve(argv[1]) : null;
const harness = argv[2];
let result;
if (sub === 'acquire') result = acquire(agentHome, harness);
else if (sub === 'release') result = release(agentHome);
else if (sub === 'check') result = check(agentHome);
else result = { ok: false, error: 'unknown subcommand: ' + sub + ' (supported: acquire|release|check)' };
process.stdout.write(JSON.stringify(result) + '\n');
if (!result.ok) process.exitCode = 1;
}
if (require.main === module) {
main();
}
module.exports = { lockFilePath, isExpired, acquire, release, check, TTL_MS, MEMORY_DIR_CANDIDATES };