@ouro.bot/cli 0.1.0-alpha.1444 → 0.1.0-alpha.1446

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/changelog.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "_note": "Each pull request writes its own change note under changes/; the release job on main gives each landed change its version and adds the notes here (scripts/release-version.cjs). On main this file stops at the last version set by hand; the published package has every release. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1446",
6
+ "changes": [
7
+ "Eval runs and Butler upgrades no longer run on the same host at once: they share a host lock.",
8
+ "**The lock.** `deploy/unraid/ouro-host-lock.mjs` takes `/var/lock/ouro-host.d` with `mkdir`, and writes `owner.json` inside it naming the holder, token, pid, host and expiry.",
9
+ "A lock is stale when its expiry has passed, when its process on this host is gone, or when it has had no readable owner for a minute. The next taker breaks a stale lock.",
10
+ "Taking, breaking and releasing all happen inside a short guard, so a breaker never removes a lock that someone took after it judged the old one stale.",
11
+ "**The eval.** `npm run eval -- ... --sandbox-ssh <host>:<folder> --host-lock <holder>` holds that host's lock over one ssh session (the holder is one word, such as `eval:c17-replay`) for the whole command, and frees it at the end. A dropped session frees it too.",
12
+ "The eval waits up to 30 minutes for a Butler ship that holds the lock.",
13
+ "Each job carries the lock's token. On the Butler's host the sandbox runs only while that token holds a live lock.",
14
+ "**butler:ship.** It takes the lock before it changes anything on the host. While someone else holds it, ship waits up to 30 minutes, then stops and says nothing was changed.",
15
+ "Ship passes the lock's token to the upgrade, and frees the lock at the end.",
16
+ "**The upgrade.** It takes the ship's lock over with its own pid and a fresh 4-hour expiry, so the lock lasts exactly as long as the upgrade does. When it exits it hands the lock back to the ship.",
17
+ "Run by hand without a token, it takes a lock of its own and frees it when it exits.",
18
+ "It waits while anyone else holds the lock, for up to `OURO_HOST_LOCK_WAIT_S` (30 minutes by default), and never starts past it.",
19
+ "Each rollback checks the lock again. A rollback the lock kept from running prints `ROLLBACK FAILED`, so ship reports the upgrade as failed. As with any failed rollback, the keeper retries it about 30 minutes later."
20
+ ]
21
+ },
22
+ {
23
+ "version": "0.1.0-alpha.1445",
24
+ "changes": [
25
+ "Update the Ouro UI files to Ouro UI v1.3.473."
26
+ ]
27
+ },
4
28
  {
5
29
  "version": "0.1.0-alpha.1444",
6
30
  "changes": [
@@ -3029,4 +3029,6 @@ Shipping a Butler release (one command)
3029
3029
 
3030
3030
  It resolves the release merge commit, waits for that commit's coverage-gate and for the GHCR image to resolve on the host, backs up the host's /tmp/butler-upgrade.mjs and /tmp/sanctuary-replay-gate.mjs to .bak-<previous>, stages the release's own copies, runs preflight, runs the release's gate against the live version (the baseline, log at /var/log/ouro-baseline-<version>.log), starts the gated upgrade detached with its log at /var/log/ouro-upgrade-<version>.log and OURO_REPLAY_BASELINE pointing at the baseline log, follows the case lines to a terminal line and runs verify. A candidate failure blocks the release only when that case did not fail on the live baseline; a case that fails on both is reported as failing-on-live-too and does not block. The safety checks (window-trusted, no-telegram, owner-policy-untouched) and a planted case always block. --no-baseline skips the live run, so every failure blocks. The last stdout line is one JSON result: {version, result: kept|rolled_back|refused|failed, running_image, cases, summary, baseline, comparison, verify, log}; comparison lists each case's live and candidate status and its verdict, and is also printed as a table above it. Exit 0 only when the result is kept and verify is green. --dry-run runs only the read-only steps. BUTLER_HOST overrides the default host alias.
3031
3031
 
3032
- Manual fallback (the script automates exactly these): wait for coverage-gate and `docker manifest inspect ghcr.io/ourostack/ouroboros-butler:<version>` on the host; copy deploy/unraid/sanctuary-butler-upgrade.mjs to /tmp/butler-upgrade.mjs and deploy/unraid/sanctuary-replay-gate.mjs to /tmp/sanctuary-replay-gate.mjs; run `node /tmp/butler-upgrade.mjs preflight <version>`; start `setsid nohup /usr/local/bin/node /tmp/butler-upgrade.mjs upgrade <version> > /var/log/ouro-upgrade-<version>.log 2>&1 < /dev/null &`; read the log for GATE PASS, GATE FAIL (rolled back), UPGRADE done, REFUSING or FAILED; then run `node /tmp/butler-upgrade.mjs verify`. Check for a live upgrade with pgrep -f "[b]utler-upgrade.mjs upgrade" so the check does not match its own shell.
3032
+ Host lock: before it changes anything, butler:ship copies deploy/unraid/ouro-host-lock.mjs to /tmp/ouro-host-lock.mjs and takes the host lock (/var/lock/ouro-host.d, with owner.json naming the holder, pid, host and expiry). While someone else holds it, the ship waits up to 30 minutes, then stops saying nothing was changed. The ship passes its token to the upgrade as OURO_HOST_LOCK_TOKEN, and the upgrade takes the lock over with its own pid and a fresh 4-hour expiry, so the lock lasts as long as the upgrade does; when the upgrade exits it hands the lock back to the ship (30-minute expiry), which frees it at the end. Run by hand without a token, the upgrade takes a lock of its own and frees it when it exits. The upgrade waits up to OURO_HOST_LOCK_WAIT_S seconds (default 1800) while anyone else holds the lock, and never starts past it. Each rollback checks the lock again; one that could not run prints ROLLBACK FAILED, and as with any failed rollback the keeper's authority boot retries it about 30 minutes later (that retry does not check the lock). A lock whose expiry has passed, whose process on this host is gone, or that has had no readable owner for a minute is stale and is broken by the next taker. To see who holds it: cat /var/lock/ouro-host.d/owner.json. Eval runs take it with `npm run eval -- ... --sandbox-ssh <host>:<folder> --host-lock <holder>` and hold it for the whole command (#1760).
3033
+
3034
+ Manual fallback (the script automates exactly these): wait for coverage-gate and `docker manifest inspect ghcr.io/ourostack/ouroboros-butler:<version>` on the host; copy deploy/unraid/sanctuary-butler-upgrade.mjs to /tmp/butler-upgrade.mjs, deploy/unraid/sanctuary-replay-gate.mjs to /tmp/sanctuary-replay-gate.mjs and deploy/unraid/ouro-host-lock.mjs to /tmp/ouro-host-lock.mjs; take the lock with `node /tmp/ouro-host-lock.mjs acquire --holder "<you>" --ttl 14400 --wait 1800` and pass the printed token to the upgrade as OURO_HOST_LOCK_TOKEN; run `node /tmp/butler-upgrade.mjs preflight <version>`; start `setsid nohup /usr/local/bin/node /tmp/butler-upgrade.mjs upgrade <version> > /var/log/ouro-upgrade-<version>.log 2>&1 < /dev/null &`; read the log for GATE PASS, GATE FAIL (rolled back), UPGRADE done, REFUSING or FAILED; then run `node /tmp/butler-upgrade.mjs verify` and free the lock with `node /tmp/ouro-host-lock.mjs release --token <token>`. Check for a live upgrade with pgrep -f "[b]utler-upgrade.mjs upgrade" so the check does not match its own shell.
@@ -0,0 +1,207 @@
1
+ #!/usr/bin/env node
2
+ // The host lock: one holder at a time on a Docker host that eval runs and the Butler's upgrade share (#1760).
3
+ //
4
+ // The lock is the directory /var/lock/ouro-host.d, made with mkdir (atomic), with owner.json inside naming its holder,
5
+ // token, pid, host and expiry. A lock is stale, and safe to break, when its expiry has passed, when its pid is gone
6
+ // on this host, or when it has had no readable owner.json for a minute. Taking, breaking and releasing all happen
7
+ // inside a short guard (the directory ouro-host.d.guard, also made with mkdir), so a breaker can never remove a lock
8
+ // that another process took after the breaker judged it stale. A guard older than 30 seconds belonged to a process
9
+ // that died inside it and is broken in turn.
10
+ //
11
+ // Holders: the eval runs `hold`, which keeps the lock with its own pid for as long as its stdin stays open (its ssh
12
+ // session), so a dropped session frees it. butler:ship runs `acquire` and later `release`, and passes the token to
13
+ // the upgrade (OURO_HOST_LOCK_TOKEN), which takes the lock over with its own pid (tryAcquire's `adopt`) for as long
14
+ // as it runs and hands it back when it exits.
15
+ //
16
+ // Usage: ouro-host-lock.mjs acquire --holder <name> --ttl <seconds> [--wait <seconds>]
17
+ // ouro-host-lock.mjs hold --holder <name> --ttl <seconds> [--wait <seconds>]
18
+ // ouro-host-lock.mjs release --token <token>
19
+ // ouro-host-lock.mjs check --token <token> (exit 0 only while that token holds a live lock)
20
+ // Output lines start with @@LOCK. Exit 3: the lock stayed held for all of --wait. Exit 2: bad usage.
21
+ import { randomBytes } from "node:crypto"
22
+ import { mkdirSync, readFileSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, writeFileSync } from "node:fs"
23
+ import { hostname } from "node:os"
24
+ import { join } from "node:path"
25
+ import { fileURLToPath } from "node:url"
26
+
27
+ export const LOCK_DIR = "/var/lock/ouro-host.d"
28
+ export const GUARD_STALE_MS = 30_000
29
+ export const UNWRITTEN_GRACE_MS = 60_000
30
+ const OWNER = "owner.json"
31
+
32
+ function processAlive(pid) {
33
+ try { process.kill(pid, 0); return true } catch (error) { return error.code === "EPERM" }
34
+ }
35
+
36
+ const defaults = (io = {}) => ({ now: () => Date.now(), host: hostname(), alive: processAlive, guardWaitMs: 5_000, ...io })
37
+ const sleepSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
38
+
39
+ /** The owner record, or { unreadable, ageMs } when the directory exists without a readable one, or null when free. */
40
+ export function readOwner(dir, io) {
41
+ let made
42
+ try { made = statSync(dir).mtimeMs } catch { return null }
43
+ try {
44
+ const owner = JSON.parse(readFileSync(join(dir, OWNER), "utf8"))
45
+ if (typeof owner.token === "string" && typeof owner.expiresAt === "string") return owner
46
+ } catch { /* below */ }
47
+ return { unreadable: true, ageMs: defaults(io).now() - made }
48
+ }
49
+
50
+ /** Why this owner no longer holds the lock, or null while it does. */
51
+ export function staleReason(owner, io) {
52
+ const { now, host, alive } = defaults(io)
53
+ if (owner.unreadable) return owner.ageMs > UNWRITTEN_GRACE_MS ? `it has had no readable owner for ${Math.round(owner.ageMs / 1000)}s` : null
54
+ if (Date.parse(owner.expiresAt) <= now()) return `it expired at ${owner.expiresAt}`
55
+ if (typeof owner.pid === "number" && owner.host === host && !alive(owner.pid)) return `its process ${owner.pid} on ${host} is gone`
56
+ return null
57
+ }
58
+
59
+ export function describeOwner(owner) {
60
+ if (owner.unreadable) return "an unknown holder (no readable owner yet)"
61
+ return `${owner.holder} (${typeof owner.pid === "number" ? `pid ${owner.pid} ` : ""}on ${owner.host}) until ${owner.expiresAt}`
62
+ }
63
+
64
+ // Moves the stale guard aside (only one rename can win) and removes it, unless what was moved is not the guard that
65
+ // was judged stale (another breaker already replaced it with a live one). Identity is inode and mtime together: a
66
+ // filesystem such as ext4 can give a guard made right after another was removed the same inode number.
67
+ function breakGuard(guard, seen, io) {
68
+ io?.beforeBreak?.()
69
+ const aside = `${guard}.broken-${randomBytes(4).toString("hex")}`
70
+ try { renameSync(guard, aside) } catch { return }
71
+ let moved
72
+ try { moved = statSync(aside) } catch { return }
73
+ if (moved.ino === seen.ino && moved.mtimeMs === seen.mtimeMs) { try { rmdirSync(aside) } catch { /* left */ } return }
74
+ // That was a live guard: stand a fresh one in its place for its holder (who removes it when done), then drop the
75
+ // moved copy. Never rename onto the guard path, which would replace a guard a third process just made.
76
+ try { mkdirSync(guard) } catch { /* someone made one already */ }
77
+ try { rmdirSync(aside) } catch { /* left */ }
78
+ }
79
+
80
+ function withGuard(dir, io, work) {
81
+ const guard = `${dir}.guard`
82
+ const { now, guardWaitMs } = defaults(io)
83
+ const deadline = Date.now() + guardWaitMs
84
+ for (;;) {
85
+ try { mkdirSync(guard); break } catch (error) {
86
+ if (error.code !== "EEXIST") throw error
87
+ }
88
+ let seen
89
+ try { seen = statSync(guard) } catch { continue }
90
+ if (now() - seen.mtimeMs > GUARD_STALE_MS) { breakGuard(guard, seen, io); continue }
91
+ if (Date.now() >= deadline) throw new Error(`the host lock's guard ${guard} is busy`)
92
+ sleepSync(10)
93
+ }
94
+ try { return work() } finally { try { rmdirSync(guard) } catch (error) { if (error.code !== "ENOENT") throw error } }
95
+ }
96
+
97
+ /**
98
+ * Takes the lock if it is free or stale. With `adopt`, a process that was handed a live lock's token takes it over
99
+ * with its own pid and a fresh expiry, keeping the token. { acquired: true, token, owner, adopted?, broke?,
100
+ * staleBecause? } or { acquired: false, owner }.
101
+ */
102
+ export function tryAcquire(dir, { holder, ttlMs, pid, adopt }, io) {
103
+ const { now, host } = defaults(io)
104
+ return withGuard(dir, io, () => {
105
+ let broke
106
+ let staleBecause
107
+ const current = readOwner(dir, io)
108
+ if (current) {
109
+ staleBecause = staleReason(current, io)
110
+ if (!staleBecause && adopt && current.token === adopt) {
111
+ const owner = { ...current, holder, pid: pid ?? null, host, expiresAt: new Date(now() + ttlMs).toISOString() }
112
+ writeFileSync(join(dir, OWNER), `${JSON.stringify(owner)}\n`, { mode: 0o644 })
113
+ return { acquired: true, token: adopt, owner, adopted: true }
114
+ }
115
+ if (!staleBecause) return { acquired: false, owner: current }
116
+ broke = current
117
+ rmSync(dir, { recursive: true, force: true })
118
+ }
119
+ mkdirSync(dir, { mode: 0o755 })
120
+ const token = randomBytes(16).toString("hex")
121
+ const owner = { holder, token, pid: pid ?? null, host, acquiredAt: new Date(now()).toISOString(), expiresAt: new Date(now() + ttlMs).toISOString() }
122
+ writeFileSync(join(dir, OWNER), `${JSON.stringify(owner)}\n`, { mode: 0o644 })
123
+ return { acquired: true, token, owner, ...(broke ? { broke, staleBecause } : {}) }
124
+ })
125
+ }
126
+
127
+ /** Gives a lock this token holds back with no pid and a fresh expiry; creates nothing when it no longer holds it. */
128
+ export function handBack(dir, token, { holder, ttlMs }, io) {
129
+ const { now } = defaults(io)
130
+ return withGuard(dir, io, () => {
131
+ const current = readOwner(dir, io)
132
+ if (!current || current.token !== token) return false
133
+ writeFileSync(join(dir, OWNER), `${JSON.stringify({ ...current, holder, pid: null, expiresAt: new Date(now() + ttlMs).toISOString() })}\n`, { mode: 0o644 })
134
+ return true
135
+ })
136
+ }
137
+
138
+ /** Frees the lock if this token holds it; true when it did. */
139
+ export function release(dir, token, io) {
140
+ return withGuard(dir, io, () => {
141
+ const current = readOwner(dir, io)
142
+ if (!current || current.token !== token) return false
143
+ rmSync(dir, { recursive: true, force: true })
144
+ return true
145
+ })
146
+ }
147
+
148
+ /** True while this token holds a lock that is not stale. */
149
+ export function heldBy(dir, token, io) {
150
+ const current = readOwner(dir, io)
151
+ return Boolean(current && current.token === token && !staleReason(current, io))
152
+ }
153
+
154
+ /** The live holder that is not this token, or null when the way is clear for it. */
155
+ export function blocker(dir, token, io) {
156
+ const current = readOwner(dir, io)
157
+ if (!current || (token && current.token === token) || staleReason(current, io)) return null
158
+ return current
159
+ }
160
+
161
+ function parse(argv) {
162
+ const [command, ...rest] = argv
163
+ const opts = {}
164
+ for (let i = 0; i < rest.length; i += 2) opts[String(rest[i]).replace(/^--/, "")] = rest[i + 1]
165
+ const needs = { acquire: ["holder", "ttl"], hold: ["holder", "ttl"], release: ["token"], check: ["token"] }[command]
166
+ if (!needs || needs.some((key) => !opts[key])) return null
167
+ return { command, ...opts }
168
+ }
169
+
170
+ async function takeWaiting(dir, args, pid, over = () => false) {
171
+ const pollMs = Number(process.env.OURO_HOST_LOCK_POLL_MS ?? 5_000)
172
+ const until = Date.now() + Number(args.wait ?? 0) * 1000
173
+ let said = false
174
+ for (;;) {
175
+ const got = tryAcquire(dir, { holder: args.holder, ttlMs: Number(args.ttl) * 1000, pid })
176
+ if (got.acquired) {
177
+ if (got.broke) console.log(`@@LOCK broke ${describeOwner(got.broke)}: ${got.staleBecause}`)
178
+ console.log(`@@LOCK acquired ${got.token}`)
179
+ return got.token
180
+ }
181
+ if (Date.now() >= until || over()) { console.log(`@@LOCK held ${describeOwner(got.owner)}`); return null }
182
+ if (!said) { console.log(`@@LOCK waiting ${describeOwner(got.owner)}`); said = true }
183
+ await new Promise((resolve) => setTimeout(resolve, pollMs))
184
+ }
185
+ }
186
+
187
+ export async function main(argv, dir = process.env.OURO_HOST_LOCK_DIR || LOCK_DIR) {
188
+ const args = parse(argv)
189
+ if (!args) { console.error("usage: ouro-host-lock.mjs acquire|hold --holder <name> --ttl <seconds> [--wait <seconds>] | release|check --token <token>"); return 2 }
190
+ if (args.command === "check") return heldBy(dir, args.token) ? 0 : 1
191
+ if (args.command === "release") { console.log(release(dir, args.token) ? "@@LOCK released" : "@@LOCK not-held"); return 0 }
192
+ if (args.command === "acquire") return (await takeWaiting(dir, args, null)) ? 0 : 3
193
+ // hold: keep it until the session that asked for it ends. Listen before taking it, so an early signal still releases.
194
+ const ended = new Promise((resolve) => {
195
+ process.stdin.on("end", resolve).on("close", resolve).on("error", resolve).resume()
196
+ for (const signal of ["SIGTERM", "SIGHUP", "SIGINT"]) process.on(signal, resolve)
197
+ })
198
+ let over = false
199
+ void ended.then(() => { over = true })
200
+ const token = await takeWaiting(dir, args, process.pid, () => over)
201
+ if (!token) return 3
202
+ await ended
203
+ console.log(release(dir, token) ? "@@LOCK released" : "@@LOCK not-held")
204
+ return 0
205
+ }
206
+
207
+ if (process.argv[1] && fileURLToPath(import.meta.url) === realpathSync(process.argv[1])) main(process.argv.slice(2)).then((code) => process.exit(code), (error) => { console.error(error); process.exit(1) })
@@ -1337,6 +1337,11 @@ export async function checkTelegramBeforePause({ journalExists, probe = telegram
1337
1337
 
1338
1338
  async function upgrade(version, rehearse, { noGate = false, plant } = {}) {
1339
1339
  say(`in-place upgrade to ${version}${rehearse ? ` — REHEARSAL: stop after "${rehearse}", then roll back` : ""}`)
1340
+ const hostLock = await loadHostLock()
1341
+ const taken = hostLockTake("the upgrade", { lockModule: hostLock, holder: `butler upgrade ${version}` })
1342
+ if (taken.refusal) fail(`${taken.refusal}; nothing was changed`)
1343
+ process.on("exit", () => hostLockLeave(taken, { lockModule: hostLock, holder: `butler:ship ${version}` }))
1344
+ const rollbackLock = () => { const held = hostLockWait("the rollback", { lockModule: hostLock, token: taken.token }); if (held) { console.error(`\n${ROLLBACK_LOCKED(held, lifecycle)}`); process.exit(1) } }
1340
1345
  if (rehearse && !UPGRADE_STEPS.includes(rehearse)) fail(`--rehearse takes one of: ${UPGRADE_STEPS.join(", ")}`)
1341
1346
  const gated = !rehearse && !noGate
1342
1347
  if (noGate && !rehearse) console.log("\n!! --no-gate: this upgrade will NOT be replay-gated or auto-rolled-back on a behavioural regression")
@@ -1385,6 +1390,7 @@ async function upgrade(version, rehearse, { noGate = false, plant } = {}) {
1385
1390
  const planned = Boolean(failure && rehearse && reason.includes(`rehearsal stopped after ${rehearse}`))
1386
1391
  if (failure) {
1387
1392
  console.log(`\n!! ${planned ? "rehearsal stopped as planned" : "upgrade FAILED"}: ${reason}\n!! rolling back to the predecessor`)
1393
+ rollbackLock()
1388
1394
  try { ok(`rollback: ${sh("/usr/local/bin/node", [lifecycle, "upgrade-rollback"], { stdio: ["ignore", "pipe", "pipe"] }).trim()}`) }
1389
1395
  catch (e) { fail(ROLLBACK_FAILED(e, lifecycle)) }
1390
1396
  } else if (!gated) { pinTemplate(version); pruneButlerImages() }
@@ -1424,6 +1430,7 @@ async function upgrade(version, rehearse, { noGate = false, plant } = {}) {
1424
1430
  },
1425
1431
  rollback: () => {
1426
1432
  pauseSupervision()
1433
+ rollbackLock()
1427
1434
  try { ok(`rollback: ${sh("/usr/local/bin/node", [lifecycle, "upgrade-rollback"], { stdio: ["ignore", "pipe", "pipe"] }).trim()}`) }
1428
1435
  catch (e) { fail(ROLLBACK_FAILED(e, lifecycle)) }
1429
1436
  resumeSupervision()
@@ -1483,6 +1490,80 @@ function verify(withGate = false) {
1483
1490
 
1484
1491
  function fail(m) { console.error(`\nREFUSING: ${m}`); process.exit(1) }
1485
1492
 
1493
+ // ---- host lock --------------------------------------------------------------
1494
+ // Eval runs hold the host lock (ouro-host-lock.mjs, staged beside this script by butler:ship) while they use this
1495
+ // host's Docker; butler:ship holds it for the whole ship and passes its token in OURO_HOST_LOCK_TOKEN. The upgrade
1496
+ // takes that lock over with its own pid (or takes its own when run by hand), waiting while anyone else holds it, and
1497
+ // each rollback checks it again: on 2026-11-23 an eval container vanishing mid-upgrade failed the upgrade and its
1498
+ // rollback and left the Butler down (#1760).
1499
+ export const HOST_LOCK_DIR = "/var/lock/ouro-host.d"
1500
+
1501
+ export const HOST_LOCK_TTL_MS = 4 * 60 * 60 * 1000
1502
+ const HAND_BACK_TTL_MS = 30 * 60 * 1000
1503
+
1504
+ export async function loadHostLock(url = new URL("./ouro-host-lock.mjs", import.meta.url)) {
1505
+ try { return await import(url.href) } catch (error) { if (error?.code === "ERR_MODULE_NOT_FOUND") return null; throw error }
1506
+ }
1507
+
1508
+ export const ROLLBACK_LOCKED = (held, lifecycle) => `ROLLBACK FAILED: ${held}. The Butler may be down or on the failed upgrade. Host supervision stays paused for about 30 minutes; after that the keeper's authority boot retries the rollback (that retry does not check the host lock). To roll back sooner once the lock is free: \`touch ${MAINTENANCE}; node ${lifecycle} upgrade-rollback\`.`
1509
+
1510
+ /**
1511
+ * Takes the host lock for this process before the upgrade changes anything, waiting up to waitMs while someone else
1512
+ * holds it. Handed butler:ship's token, it takes that lock over with this pid and a fresh expiry, so the lock lasts
1513
+ * exactly as long as the upgrade does. { token, adopted } or { refusal }; { token: undefined } on a host with neither
1514
+ * a lock nor the script to take one.
1515
+ */
1516
+ export function hostLockTake(what, {
1517
+ lockModule, dir = HOST_LOCK_DIR, token = process.env.OURO_HOST_LOCK_TOKEN, holder, pid = process.pid, ttlMs = HOST_LOCK_TTL_MS,
1518
+ waitMs = Number(process.env.OURO_HOST_LOCK_WAIT_S || 30 * 60) * 1000, pollMs = 15_000,
1519
+ now = Date.now, sleep = (ms) => sh("/bin/sleep", [String(ms / 1000)]), log = console.log,
1520
+ } = {}) {
1521
+ if (!lockModule) return existsSync(dir) ? { refusal: `the host lock ${dir} exists and ouro-host-lock.mjs is not beside this script to read it, so ${what} did not run` } : { token: undefined, adopted: false }
1522
+ const start = now()
1523
+ let said = false
1524
+ for (;;) {
1525
+ let got
1526
+ try { got = lockModule.tryAcquire(dir, { holder, ttlMs, pid, adopt: token }, { now }) } catch (error) {
1527
+ if (!/guard .* is busy/.test(String(error?.message))) return { refusal: `the host lock could not be taken (${error?.message ?? error}), so ${what} did not run` }
1528
+ got = { acquired: false, owner: { unreadable: true } }
1529
+ }
1530
+ if (got.acquired) return { token: got.token, adopted: Boolean(got.adopted) }
1531
+ const owner = lockModule.describeOwner(got.owner)
1532
+ if (now() - start >= waitMs) return { refusal: `the host lock is held by ${owner}, so ${what} did not run` }
1533
+ if (!said) { log(` waiting: the host lock is held by ${owner}; ${what} waits for it`); said = true }
1534
+ sleep(pollMs)
1535
+ }
1536
+ }
1537
+
1538
+ /** On exit: hands an adopted lock back to the ship that owns it (no pid, a short expiry), or frees one taken here. */
1539
+ export function hostLockLeave(taken, { lockModule, dir = HOST_LOCK_DIR, holder }) {
1540
+ if (!lockModule || !taken.token) return
1541
+ try {
1542
+ if (taken.adopted) lockModule.handBack(dir, taken.token, { holder, ttlMs: HAND_BACK_TTL_MS })
1543
+ else lockModule.release(dir, taken.token)
1544
+ } catch { /* the lock goes stale with this process */ }
1545
+ }
1546
+
1547
+ /** null when the way is clear; otherwise why `what` must not run. Waits up to waitMs while someone else holds the lock. */
1548
+ export function hostLockWait(what, {
1549
+ lockModule, dir = HOST_LOCK_DIR, token = process.env.OURO_HOST_LOCK_TOKEN,
1550
+ waitMs = Number(process.env.OURO_HOST_LOCK_WAIT_S || 30 * 60) * 1000, pollMs = 15_000,
1551
+ now = Date.now, sleep = (ms) => sh("/bin/sleep", [String(ms / 1000)]), log = console.log,
1552
+ } = {}) {
1553
+ if (!existsSync(dir)) return null
1554
+ if (!lockModule) return `the host lock ${dir} exists and ouro-host-lock.mjs is not beside this script to read it, so ${what} did not run`
1555
+ const start = now()
1556
+ let said = false
1557
+ for (;;) {
1558
+ const owner = lockModule.blocker(dir, token, { now })
1559
+ if (!owner) return null
1560
+ const holder = lockModule.describeOwner(owner)
1561
+ if (now() - start >= waitMs) return `the host lock is held by ${holder}, so ${what} did not run`
1562
+ if (!said) { log(` waiting: the host lock is held by ${holder}; ${what} waits for it`); said = true }
1563
+ sleep(pollMs)
1564
+ }
1565
+ }
1566
+
1486
1567
  // ---- entry ----------------------------------------------------------------
1487
1568
 
1488
1569
  export function parseUpgradeArgs(argv) {
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1444",
2
+ "runtimeVersion": "0.1.0-alpha.1446",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -1,7 +1,7 @@
1
1
  <?xml version="1.0"?>
2
2
  <Container version="2">
3
3
  <Name>ouro-butler</Name>
4
- <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1444</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1446</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -9,6 +9,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  const runtime_1 = require("../nerves/runtime");
10
10
  const case_1 = require("./domain/case");
11
11
  const docker_1 = require("./sandbox/docker");
12
+ const host_lock_1 = require("./sandbox/host-lock");
12
13
  const oracle_1 = require("./sandbox/oracle");
13
14
  const remote_1 = require("./sandbox/remote");
14
15
  void (0, remote_1.serveRemoteJob)({
@@ -21,6 +22,7 @@ void (0, remote_1.serveRemoteJob)({
21
22
  ...(job.workRoot ? { workRoot: job.workRoot } : {}),
22
23
  ...(job.guest ? { guest: job.guest } : {}),
23
24
  ...(job.images ? { images: job.images } : {}),
25
+ ...(job.hostLockToken ? { hostLock: (0, host_lock_1.localHostLock)(job.hostLockToken) } : {}),
24
26
  ...(job.oracleBooks ? { oracle: (0, oracle_1.dockerOracle)({ docker, image: job.images?.household ?? docker_1.HOUSEHOLD_IMAGE, booksLib: job.oracleBooks }) } : {}),
25
27
  });
26
28
  },
@@ -28,7 +28,7 @@ exports.CALLS_PER_RUN = core_1.MAX_PROVIDER_ITERATIONS_CEILING + 1;
28
28
  const STRING_FLAGS = {
29
29
  "--cases": "cases", "--bundle": "bundle", "--bundle-ref": "bundleRef", "--target": "target", "--credentials-agent": "credentialsAgent",
30
30
  "--copilot-account": "copilotAccount", "--output": "output", "--harness-ref": "harnessRef", "--seed-bundle": "seedBundle",
31
- "--oracle-books": "oracleBooks", "--sandbox-ssh": "sandboxSsh", "--sandbox-images": "sandboxImages",
31
+ "--oracle-books": "oracleBooks", "--sandbox-ssh": "sandboxSsh", "--sandbox-images": "sandboxImages", "--host-lock": "hostLock",
32
32
  };
33
33
  const NUMBER_FLAGS = {
34
34
  "--runs": "runs", "--budget-premium": "budgetPremium", "--budget-credits": "budgetCredits", "--price-in": "priceIn", "--price-out": "priceOut",
@@ -66,6 +66,10 @@ function parseEvalArgs(argv) {
66
66
  throw new Error("--sandbox-images must be <agent image>,<household image>");
67
67
  out.sandboxImages = { agent, household };
68
68
  }
69
+ if (out.hostLock !== undefined && out.sandboxSsh === undefined)
70
+ throw new Error("--host-lock needs --sandbox-ssh: it locks that host");
71
+ if (out.hostLock !== undefined && !/^[\w.:@+-]+$/.test(String(out.hostLock)))
72
+ throw new Error("--host-lock takes one word of letters, digits and . : @ + - _ (it is sent over ssh)");
69
73
  const missing = REQUIRED.find((flag) => !seen.has(flag));
70
74
  if (missing)
71
75
  throw new Error(`${missing} is required`);
@@ -9,8 +9,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  * harness checkout is synced to `<folder>/harness`; `--bundle`, `--seed-bundle` and `--oracle-books` are then paths
10
10
  * on that host. `--sandbox-images <agent>,<household>` names the image tags to run (on that host, when remote), built
11
11
  * beforehand with `docker build --file deploy/eval/Dockerfile --target agent|household --tag <tag> .`; the remote
12
- * checkout must be synced and built from this version for the books oracle to use them too. Model calls and
13
- * credentials stay on this machine.
12
+ * checkout must be synced and built from this version for the books oracle to use them too. `--host-lock <holder>`
13
+ * holds that host's lock (deploy/unraid/ouro-host-lock.mjs) for the whole command, so the Butler's upgrade and
14
+ * rollback wait for it, and the sandbox runs on the Butler's host only while it does. Model calls and credentials
15
+ * stay on this machine.
14
16
  */
15
17
  const node_fs_1 = __importDefault(require("node:fs"));
16
18
  const node_path_1 = __importDefault(require("node:path"));
@@ -19,22 +21,26 @@ const run_command_1 = require("./run-command");
19
21
  const report_1 = require("./report");
20
22
  const docker_1 = require("./sandbox/docker");
21
23
  const oracle_1 = require("./sandbox/oracle");
24
+ const host_lock_1 = require("./sandbox/host-lock");
22
25
  const remote_1 = require("./sandbox/remote");
23
26
  const targets_1 = require("./targets");
24
27
  const REPO = node_path_1.default.resolve(__dirname, "../..");
25
- function runCaseFor(args) {
28
+ function sshTarget(spec) {
29
+ const split = spec.indexOf(":");
30
+ if (split < 1)
31
+ throw new Error("--sandbox-ssh must be <host>:<folder>");
32
+ return { host: spec.slice(0, split), root: spec.slice(split + 1) };
33
+ }
34
+ function runCaseFor(args, hostLockToken) {
26
35
  if (args.sandboxSsh) {
27
- const split = args.sandboxSsh.indexOf(":");
28
- if (split < 1)
29
- throw new Error("--sandbox-ssh must be <host>:<folder>");
30
- const host = args.sandboxSsh.slice(0, split);
31
- const root = args.sandboxSsh.slice(split + 1);
36
+ const { host, root } = sshTarget(args.sandboxSsh);
32
37
  return (0, remote_1.remoteRunCase)({
33
38
  start: (0, remote_1.sshStart)(host, `${root}/harness/dist/eval/remote-entry.js`),
34
39
  paths: {
35
40
  bundleDir: args.bundle, seedBundleDir: args.seedBundle ?? `${root}/harness/deploy/unraid/sanctuary.ouro`, workRoot: `${root}/work`,
36
41
  ...(args.oracleBooks ? { oracleBooks: args.oracleBooks } : {}),
37
42
  ...(args.sandboxImages ? { images: args.sandboxImages } : {}),
43
+ ...(hostLockToken ? { hostLockToken } : {}),
38
44
  },
39
45
  });
40
46
  }
@@ -48,14 +54,24 @@ function runCaseFor(args) {
48
54
  }
49
55
  async function main() {
50
56
  const args = (0, run_command_1.parseEvalArgs)(process.argv.slice(2));
51
- const { exitCode } = await (0, run_command_1.runEvalCommand)(args, {
52
- resolveTarget: (spec, creds) => (0, targets_1.resolveTarget)(spec, creds),
53
- runCase: runCaseFor,
54
- outputExists: (file) => node_fs_1.default.existsSync(file),
55
- writeReport: report_1.writePrivateReport,
56
- print: (text) => { process.stdout.write(`${text}\n`); },
57
- });
58
- return exitCode;
57
+ let lock;
58
+ if (args.hostLock && args.sandboxSsh) {
59
+ const { host, root } = sshTarget(args.sandboxSsh);
60
+ lock = await (0, host_lock_1.holdHostLock)((0, remote_1.sshNode)(host, [`${root}/harness/deploy/unraid/ouro-host-lock.mjs`, "hold", "--holder", args.hostLock, "--ttl", String(host_lock_1.HOST_LOCK_TTL_S), "--wait", String(host_lock_1.HOST_LOCK_WAIT_S)]));
61
+ }
62
+ try {
63
+ const { exitCode } = await (0, run_command_1.runEvalCommand)(args, {
64
+ resolveTarget: (spec, creds) => (0, targets_1.resolveTarget)(spec, creds),
65
+ runCase: (parsed) => runCaseFor(parsed, lock?.token),
66
+ outputExists: (file) => node_fs_1.default.existsSync(file),
67
+ writeReport: report_1.writePrivateReport,
68
+ print: (text) => { process.stdout.write(`${text}\n`); },
69
+ });
70
+ return exitCode;
71
+ }
72
+ finally {
73
+ await lock?.release();
74
+ }
59
75
  }
60
76
  // stderr's last line names the failure its Ouro AX card lists (cli-commands/entry-points.ts): 2 a run the budget or
61
77
  // the provider stopped, 1 a refusal or a failure. process.exitCode, not process.exit, which can drop the line on a pipe.
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.HOST_LOCK_WAIT_S = exports.HOST_LOCK_TTL_S = exports.HOST_LOCK_SCRIPT = void 0;
7
+ exports.holdHostLock = holdHostLock;
8
+ exports.localHostLock = localHostLock;
9
+ /**
10
+ * The eval's side of the host lock (deploy/unraid/ouro-host-lock.mjs, #1760). With `--host-lock`, the command holds the
11
+ * remote host's lock for its whole run over one ssh session (`hold`), so a dropped session frees it, and sends the
12
+ * token with every job. On the host, `runSandboxed` checks that the token still holds a live lock before it creates
13
+ * anything; the Butler's upgrade and rollback wait while anyone else holds it.
14
+ */
15
+ const node_child_process_1 = require("node:child_process");
16
+ const node_path_1 = __importDefault(require("node:path"));
17
+ const runtime_1 = require("../../nerves/runtime");
18
+ /** The lock script, beside this file's package root, in a checkout and in the synced harness on the host alike. */
19
+ exports.HOST_LOCK_SCRIPT = node_path_1.default.resolve(__dirname, "../../../deploy/unraid/ouro-host-lock.mjs");
20
+ /** How long the lock lasts if the holder hangs without its session dropping: a whole replay fits well inside. */
21
+ exports.HOST_LOCK_TTL_S = 6 * 60 * 60;
22
+ /** How long to wait for a Butler ship that holds the lock before giving up. */
23
+ exports.HOST_LOCK_WAIT_S = 30 * 60;
24
+ /** Starts the remote `hold`, waits for its token, and returns it with a release that ends the session. */
25
+ async function holdHostLock(start) {
26
+ const proc = start();
27
+ let out = "";
28
+ const token = await new Promise((resolve) => {
29
+ proc.stdout.setEncoding("utf8");
30
+ proc.stdout.on("data", (chunk) => {
31
+ out += chunk;
32
+ const acquired = /^@@LOCK acquired ([0-9a-f]{32})$/m.exec(out);
33
+ if (acquired)
34
+ resolve(acquired[1]);
35
+ });
36
+ void proc.exited.then(() => resolve(undefined));
37
+ });
38
+ if (!token) {
39
+ const held = /^@@LOCK held (.+)$/m.exec(out);
40
+ const code = await proc.exited;
41
+ const error = held ? `the host lock is held by ${held[1]}` : `could not take the host lock: ${proc.stderr().trim().split("\n").at(-1) || `exit ${code}`}`;
42
+ (0, runtime_1.emitNervesEvent)({ component: "eval", level: "error", event: "eval.host_lock_refused", message: "the eval could not take the host lock", meta: { error } });
43
+ throw new Error(error);
44
+ }
45
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.host_lock_held", message: "the eval holds the host lock", meta: {} });
46
+ return {
47
+ token,
48
+ release: async () => {
49
+ proc.stdin.end();
50
+ await proc.exited;
51
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.host_lock_released", message: "the eval released the host lock", meta: {} });
52
+ },
53
+ };
54
+ }
55
+ /** On the host: held while this token holds a live lock there. */
56
+ function localHostLock(token, env = process.env) {
57
+ return {
58
+ held: () => new Promise((resolve) => {
59
+ (0, node_child_process_1.execFile)(process.execPath, [exports.HOST_LOCK_SCRIPT, "check", "--token", token], { env }, (error) => resolve(!error));
60
+ }),
61
+ };
62
+ }
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.serveRemoteJob = serveRemoteJob;
4
4
  exports.remoteRunCase = remoteRunCase;
5
5
  exports.sshStart = sshStart;
6
+ exports.sshNode = sshNode;
6
7
  /**
7
8
  * The sandbox on another Docker host, reached over ssh, with the model served from this side. The remote host runs
8
9
  * `remote-entry.js`, which reads one `job` (the case and the paths of its bundle, seed bundle, work folder and oracle
@@ -83,8 +84,12 @@ function remoteRunCase(options) {
83
84
  /* v8 ignore start -- process wiring: the channel and its lifecycle are tested above through in-memory pipes @preserve */
84
85
  /** `ssh -T <host> node <entry>`, with its stdin and stdout as the channel. */
85
86
  function sshStart(host, entry) {
87
+ return sshNode(host, [entry]);
88
+ }
89
+ /** `ssh -T <host> node <args...>`, with its stdin and stdout as the channel. */
90
+ function sshNode(host, args) {
86
91
  return () => {
87
- const child = (0, node_child_process_1.spawn)("ssh", ["-T", "-o", "BatchMode=yes", "-o", "ServerAliveInterval=30", host, "node", entry], { stdio: ["pipe", "pipe", "pipe"] });
92
+ const child = (0, node_child_process_1.spawn)("ssh", ["-T", "-o", "BatchMode=yes", "-o", "ServerAliveInterval=30", host, "node", ...args], { stdio: ["pipe", "pipe", "pipe"] });
88
93
  let err = "";
89
94
  child.stderr.setEncoding("utf8").on("data", (chunk) => { err = (err + chunk).slice(-4000); });
90
95
  const exited = new Promise((resolve) => {
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1444",
3
+ "version": "0.1.0-alpha.1446",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@ouro.bot/cli",
9
- "version": "0.1.0-alpha.1444",
9
+ "version": "0.1.0-alpha.1446",
10
10
  "bundleDependencies": [
11
11
  "@ouro.bot/friends"
12
12
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1444",
3
+ "version": "0.1.0-alpha.1446",
4
4
  "description": "Ouroboros, the agent harness: agents with durable memory that live where you talk (terminal, Teams, iMessage, mail, voice) and use real tools. Start with npx ouro.bot@latest.",
5
5
  "homepage": "https://ouroboros.bot/",
6
6
  "engines": {