Files
zhou.han 9e86a2c7b7 proc: a Linux zombie no longer holds a lock (#1198)
yetihan (#1198): a lock whose owner is a Linux zombie was held for
good. process.kill(pid, 0) succeeds on a zombie, so 15 packages' lock
and liveness checks counted an exited, unreaped owner as alive.

- scripts/proc.mjs: processStatus(pid) is dead on ESRCH, and on Linux
  also when /proc/<pid>/stat says Z or X; EPERM is "permission", any
  other error "unknown". processAlive / processExists keep each
  caller's old EPERM and unknown-error meaning.
- scripts/sync-proc.mjs copies it into each package (--check in the
  tests); every package's own check keeps its old semantics, now with
  zombies dead. agent-console's daemon bundle and window-warmup's dist
  are rebuilt.
- 15 packages bumped.

Review run at 28ef6622 (mote, HOME=$(mktemp -d)):
- node scripts/sync-proc.mjs --check: ok.
- bun test (whole repo): 8934 pass, 0 fail.
- bun scripts/check.mjs: every package ok.
- window-warmup's build reproduces its dist/plugin.js byte for byte.
  agent-console's bundle diff read line by line: the proc module plus
  esbuild's renumbered imports, nothing else (esbuild isn't installed
  on mote, so it wasn't rebuilt there).
- Real zombie on Linux (WSL, magpie-desktop): a bash child left
  unreaped by an exec'd sleep, /proc stat "Z": the old kill(0) check
  says alive, processStatus says dead; the running process says alive.

Not tried: each package's lock contention end to end.
2026-11-16 12:19:09 +08:00

129 lines
5.4 KiB
JavaScript

import fs from "node:fs"
import path from "node:path"
import { createHash, randomUUID } from "node:crypto"
import { pathsFor, reconcile, inspect } from "./bridge.mjs"
import { processExists } from "./proc.mjs"
function configFile(file) {
try {
const stat = fs.lstatSync(file)
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024) throw new Error("invalid-adapter-settings")
const value = JSON.parse(fs.readFileSync(file, "utf8"))
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid-adapter-settings")
return value
} catch (error) {
if (error.code === "ENOENT") return {}
throw new Error("invalid-adapter-settings")
}
}
export function resolvePaths(options = {}) {
const defaults = pathsFor()
const settings = { ...configFile(path.join(defaults.directory, "adapter.json")), ...options }
if (settings.configPath !== undefined && (typeof settings.configPath !== "string" || !path.isAbsolute(settings.configPath))) throw new Error("configPath-must-be-absolute")
return pathsFor({ configPath: settings.configPath })
}
function signature(p) {
const hash = createHash("sha256")
for (const file of [p.control, p.mcp]) {
try {
const stat = fs.lstatSync(file)
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024) throw new Error("invalid-control-file")
hash.update(fs.readFileSync(file))
} catch (error) {
if (error.code !== "ENOENT") throw error
hash.update("<missing>")
}
hash.update("\0")
}
return hash.digest("hex")
}
function claimRuntime(p) {
const file = path.join(p.directory, "runtime.lock")
fs.mkdirSync(p.directory, { recursive: true, mode: 0o700 })
const owner = { pid: process.pid, nonce: randomUUID() }
const readOwner = () => {
const stat = fs.lstatSync(file)
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024) throw new Error("invalid-runtime-lock")
const value = JSON.parse(fs.readFileSync(file, "utf8"))
if (!Number.isSafeInteger(value.pid) || value.pid <= 0 || typeof value.nonce !== "string") throw new Error("invalid-runtime-lock")
return value
}
try { fs.writeFileSync(file, JSON.stringify(owner), { mode: 0o600, flag: "wx" }) }
catch (error) {
if (error.code !== "EEXIST") throw error
const previous = readOwner()
if (processExists(previous.pid)) return null
// Serialize stale reclamation separately. Re-reading a nonce alone is not
// a compare-and-delete: another reclaimer could create a live lock between
// the read and unlink. A leftover guard fails closed for manual inspection.
const guard = file + ".reclaim"
try { fs.writeFileSync(guard, owner.nonce, { mode: 0o600, flag: "wx" }) }
catch (guardError) { if (guardError.code === "EEXIST") return null; throw guardError }
try {
let current
try { current = readOwner() } catch (probe) { if (probe.code !== "ENOENT") throw probe }
if (current) {
if (processExists(current.pid)) return null
fs.unlinkSync(file)
}
try { fs.writeFileSync(file, JSON.stringify(owner), { mode: 0o600, flag: "wx" }) }
catch (retry) { if (retry.code === "EEXIST") return null; throw retry }
} finally {
if (fs.readFileSync(guard, "utf8") === owner.nonce) fs.unlinkSync(guard)
}
}
const release = () => {
try { if (readOwner().nonce === owner.nonce) fs.unlinkSync(file) }
catch (error) { if (error.code !== "ENOENT") throw error }
}
release.owns = () => { try { return readOwner().nonce === owner.nonce } catch { return false } }
return release
}
// No backend request or nanobot process starts here. Each input must remain
// stable for one complete polling period before a target write is attempted.
export function startRuntime(p, { interval = 750, onStatus = () => {}, schedule = setInterval, cancel = clearInterval } = {}) {
if (!Number.isSafeInteger(interval) || interval < 100 || interval > 60000) throw new Error("invalid-poll-interval")
let previous = null, lastStatus = "", stopped = false, release = null
const report = (status) => {
const value = JSON.stringify(status)
if (value !== lastStatus) { lastStatus = value; onStatus(status) }
return status
}
const tick = () => {
if (stopped) return
try {
if (release && !release.owns()) release = null
if (!release) {
release = claimRuntime(p)
if (!release) return report({ state: "standby", recoveryPending: false, message: "Another Magpie host owns this adapter." })
}
const current = signature(p)
if (current !== previous) { previous = current; return }
return report(reconcile(p))
} catch {
return report({ state: "conflict", recoveryPending: true, message: "Adapter paused; inspect the control files and recovery status. Configuration contents are omitted." })
}
}
const timer = schedule(tick, interval)
timer.unref?.()
return {
tick,
status: () => inspect(p),
stop({ restore = false } = {}) {
if (stopped) return
stopped = true
cancel(timer)
// Flush the current intent synchronously before releasing ownership.
// Host exit alone is not a disconnect, but a control-file disconnect
// may still be waiting for the next polling tick. A standby never writes.
if (!release) return
try { return release.owns() ? report(reconcile(p, { restore })) : undefined }
finally { release(); release = null }
},
}
}