@ouro.bot/cli 0.1.0-alpha.1635 → 0.1.0-alpha.1637

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.
@@ -55,13 +55,13 @@ import { tmpdir } from "node:os"
55
55
  import { join } from "node:path"
56
56
 
57
57
  const ROOT = "/mnt/user/appdata/ouro-authority"
58
- const BUNDLE = "/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro"
58
+ // The host folder that holds the Butler's bundle. The live host's bundle stays sanctuary.ouro through the rename; only
59
+ // where it is mounted inside the container follows the Butler name the image runs (butlerNameFromEntrypoint).
60
+ const AGENT_DIR = "/mnt/user/appdata/ouro-butler/agent"
59
61
  const RUNTIME = "/mnt/user/appdata/ouro-butler/runtime/.ouro-cli"
60
62
  const CONTAINER = "ouro-butler"
61
63
  const TEMPLATE = "/boot/config/plugins/dockerMan/templates-user/my-ouro-butler.xml"
62
- const PSYCHE_TARGET = "/home/ouro/AgentBundles/sanctuary.ouro/psyche"
63
64
  const JOURNAL = "/boot/config/custom/ouro-butler/docker-man-template-transaction.json"
64
- const POLICY = `${BUNDLE}/state/policy/steward.json`
65
65
  const PRIMITIVES = ["/usr/local/bin/node", "/bin/sh", "/usr/bin/prlimit", "/usr/bin/setsid"]
66
66
  const REQUIRED_PROGRAMS = [
67
67
  "dist/heart/daemon/sanctuary-telegram-authority-entry.js",
@@ -91,6 +91,34 @@ const sh = (file, args, opts = {}) => execFileSync(file, args, { encoding: "utf8
91
91
  const docker = (args, opts = {}) => sh("/usr/bin/docker", args, opts)
92
92
  const image = (version) => `ghcr.io/ourostack/ouroboros-butler:${version}`
93
93
 
94
+ // ---- the Butler's name --------------------------------------------------------
95
+ // The Butler's names, as src/heart/butler-agent.ts has them. This script is staged on its own, so it carries the rule itself.
96
+ export const BUTLER_NAMES = ["butler", "sanctuary"]
97
+ /** The Butler an image runs, from its ENTRYPOINT: the argument after --package-managed-agent when it is a Butler name, otherwise sanctuary. */
98
+ export function butlerNameFromEntrypoint(entrypoint) {
99
+ if (!Array.isArray(entrypoint)) return "sanctuary"
100
+ const flag = entrypoint.indexOf("--package-managed-agent")
101
+ return flag >= 0 && BUTLER_NAMES.includes(entrypoint[flag + 1]) ? entrypoint[flag + 1] : "sanctuary"
102
+ }
103
+ /** The host bundle folder, by the name it has on disk, worked out at each use; sanctuary.ouro when neither or both are there. It never moves. */
104
+ export function hostBundle(exists = existsSync) {
105
+ const present = BUTLER_NAMES.filter((name) => exists(`${AGENT_DIR}/${name}.ouro`))
106
+ return `${AGENT_DIR}/${present.length === 1 ? present[0] : "sanctuary"}.ouro`
107
+ }
108
+ const policyFile = () => `${hostBundle()}/state/policy/steward.json`
109
+ /** Where a Butler of this name finds its bundle, its psyche and the operator trust inside its container. */
110
+ export const containerBundle = (name) => `/home/ouro/AgentBundles/${name}.ouro`
111
+ export const psycheTarget = (name) => `${containerBundle(name)}/psyche`
112
+ export const trustTarget = (name) => `/etc/ouro/trust/${name}`
113
+ /** The Butler name an image (a reference or an id) runs, read from its own config. */
114
+ function imageButlerName(reference) {
115
+ return butlerNameFromEntrypoint(JSON.parse(docker(["image", "inspect", "--format", "{{json .Config.Entrypoint}}", reference], { stdio: ["ignore", "pipe", "pipe"] })))
116
+ }
117
+ /** The Butler name the running resident's image runs. */
118
+ function liveButlerName() {
119
+ return imageButlerName(docker(["inspect", CONTAINER, "--format", "{{.Image}}"], { stdio: ["ignore", "pipe", "pipe"] }).trim())
120
+ }
121
+
94
122
  // Unraid's cgroup2-unraid daemon watches /sys/fs/cgroup via inotify and rmdir's any
95
123
  // cgroup that reports `populated 0`. The authority install creates its cgroup empty and
96
124
  // keeps it empty through staging/verification (which asserts cgroup.procs === ""), so the
@@ -180,8 +208,9 @@ function preflight(version, { fresh = false } = {}) {
180
208
  {
181
209
  const friendRecords = {}
182
210
  try {
183
- for (const file of readdirSync(`${BUNDLE}/friends`).filter((name) => name.endsWith(".json"))) {
184
- try { friendRecords[file.replace(/\.json$/u, "")] = JSON.parse(readFileSync(`${BUNDLE}/friends/${file}`, "utf8")) } catch { /* unreadable record: not a grant source */ }
211
+ const friends = `${hostBundle()}/friends`
212
+ for (const file of readdirSync(friends).filter((name) => name.endsWith(".json"))) {
213
+ try { friendRecords[file.replace(/\.json$/u, "")] = JSON.parse(readFileSync(`${friends}/${file}`, "utf8")) } catch { /* unreadable record: not a grant source */ }
185
214
  }
186
215
  } catch { /* no friends folder yet */ }
187
216
  let trustedGrants = {}
@@ -192,10 +221,21 @@ function preflight(version, { fresh = false } = {}) {
192
221
 
193
222
  say("escalation holders the upgrade would drop")
194
223
  {
195
- const dropped = escalationGrantProblems()
224
+ // The grant command is run against the Butler that is running now, under its name.
225
+ let name = "sanctuary"
226
+ try { if (runningImage) name = imageButlerName(runningImage) } catch { /* reported with the default name */ }
227
+ const dropped = escalationGrantProblems(name)
196
228
  dropped.length === 0 ? ok("every escalation holder in the bundle is already in the trusted file") : dropped.forEach((line) => bad(line))
197
229
  }
198
230
 
231
+ say("no credential handoff left for another Butler name")
232
+ if (id) {
233
+ try {
234
+ const issue = credentialHandoffIssue(imageButlerName(image(version)))
235
+ issue ? bad(issue) : ok("no container-credentials handoff names another agent")
236
+ } catch (e) { bad(`could not check the credential handoff: ${String(e.message).split("\n")[0]}`) }
237
+ } else bad("skipped (no image)")
238
+
199
239
  say("required programs in the target image")
200
240
  try {
201
241
  const missing = REQUIRED_PROGRAMS.filter((p) => {
@@ -232,7 +272,16 @@ function preflight(version, { fresh = false } = {}) {
232
272
  } catch { bad("could not read disk free space") }
233
273
 
234
274
  say("preservation baselines readable")
235
- existsSync(POLICY) ? ok(`steward policy present (${sha12(POLICY)})`) : fresh ? ok("no steward policy yet (fresh install)") : bad(`steward policy missing at ${POLICY}`)
275
+ const policy = policyFile()
276
+ existsSync(policy) ? ok(`steward policy present (${sha12(policy)})`) : fresh ? ok("no steward policy yet (fresh install)") : bad(`steward policy missing at ${policy}`)
277
+
278
+ say("the DockerMan template can follow this image's Butler name")
279
+ if (id) {
280
+ try {
281
+ const problem = templatePinProblem(version)
282
+ problem ? bad(problem) : ok(`the DockerMan template can pin ${image(version)}`)
283
+ } catch (e) { bad(`could not check the DockerMan template: ${String(e.message).split("\n")[0]}`) }
284
+ } else bad("skipped (no image)")
236
285
  try { ok(jellyfinState() ? "jellyfin inspectable for the unchanged-check" : "no jellyfin container; it must stay absent") }
237
286
  catch { bad("docker could not list or inspect the jellyfin container") }
238
287
 
@@ -255,20 +304,21 @@ function targetHasVaultFix(version) {
255
304
  const CLI = "/opt/ouro/dist/heart/daemon/sanctuary-authority-root-lifecycle.js"
256
305
  // The fenced vault read, replicating the target version's own #vault fencing.
257
306
  function fencedVaultRead(version, hasFix) {
307
+ const bundleMount = `type=bind,src=${hostBundle()},dst=${containerBundle(imageButlerName(image(version)))},readonly`
258
308
  const base = ["run", "--rm", "-i", "--pull=never", "--network", "host", "--user", "0:0", "--read-only",
259
309
  "--cap-drop=ALL", "--security-opt=no-new-privileges"]
260
310
  const args = hasFix
261
311
  ? [...base, "--cap-add=DAC_OVERRIDE", "--entrypoint", "/bin/sh",
262
312
  "--mount", `type=bind,src=${RUNTIME},dst=/home/ouro/.ouro-cli,readonly`,
263
313
  "--mount", `type=bind,src=${RUNTIME}/bitwarden,dst=/home/ouro/.bw-src,readonly`,
264
- "--mount", `type=bind,src=${BUNDLE},dst=/home/ouro/AgentBundles/sanctuary.ouro,readonly`,
314
+ "--mount", bundleMount,
265
315
  "--tmpfs", "/home/ouro/.ouro-cli/bitwarden:rw,nosuid,nodev,noexec,mode=0700",
266
316
  "--tmpfs", "/home/ouro/.config:rw,nosuid,nodev,noexec,mode=0700",
267
317
  "--tmpfs", "/tmp:rw,nosuid,nodev,noexec,mode=0700",
268
318
  image(version), "-c", `cp -r /home/ouro/.bw-src/. /home/ouro/.ouro-cli/bitwarden/ && exec /usr/local/bin/node ${CLI} vault presence`]
269
319
  : [...base, "--entrypoint", "/usr/local/bin/node",
270
320
  "--mount", `type=bind,src=${RUNTIME},dst=/home/ouro/.ouro-cli,readonly`,
271
- "--mount", `type=bind,src=${BUNDLE},dst=/home/ouro/AgentBundles/sanctuary.ouro,readonly`,
321
+ "--mount", bundleMount,
272
322
  "--tmpfs", "/home/ouro/.ouro-cli/bitwarden:rw,nosuid,nodev,noexec,mode=0700",
273
323
  "--tmpfs", "/tmp:rw,nosuid,nodev,noexec,mode=0700",
274
324
  image(version), CLI, "vault", "presence"]
@@ -306,7 +356,7 @@ function containerExists(name) { return docker(["container", "ls", "--all", "--q
306
356
  function jellyfinState() {
307
357
  return containerExists("jellyfin") ? docker(["inspect", "jellyfin", "--format", "{{.Id}}|{{.Image}}|{{.RestartCount}}|{{.State.StartedAt}}"]).trim() : null
308
358
  }
309
- function policyState() { return existsSync(POLICY) ? sha12(POLICY) : null }
359
+ function policyState() { const policy = policyFile(); return existsSync(policy) ? sha12(policy) : null }
310
360
  function installedRequest() { try { return JSON.parse(readFileSync(`${ROOT}/request.json`, "utf8")) } catch { return null } }
311
361
 
312
362
  // ---- prepare (idempotent staging; running Butler untouched) ---------------
@@ -474,9 +524,10 @@ function enableResidentAutostart() {
474
524
  // stopped; start-resident starts it. #target asserts: target image, user 10001:10001, no
475
525
  // token env, exactly one read-only /run/ouro-authority mount, no docker.sock/${ROOT} mounts.
476
526
  // Operator-set grants (delegated commands, escalation) live outside the bundle, in a root-owned host directory mounted
477
- // read-only at /etc/ouro/trust/sanctuary. The bundle's recursive chown cannot reach it, and the resident cannot write it.
527
+ // read-only at /etc/ouro/trust/<the image's Butler name>. The bundle's recursive chown cannot reach it, and the resident cannot write it.
528
+ // The host directory keeps its name whatever the Butler is called.
478
529
  export const TRUST_HOST_DIR = "/mnt/user/appdata/ouro-butler/trust/sanctuary"
479
- export const TRUST_MOUNT = `${TRUST_HOST_DIR}:/etc/ouro/trust/sanctuary:ro`
530
+ export const trustMount = (name) => `type=bind,src=${TRUST_HOST_DIR},dst=${trustTarget(name)},readonly`
480
531
  // The bundle sync deploy key: root places it on the host, and the Butler reads it through a read-only mount. The key can
481
532
  // push to the owner's repo, so nothing inside the Butler can write the mount.
482
533
  export const SYNC_HOST_DIR = "/mnt/user/appdata/ouro-butler/sync"
@@ -504,8 +555,8 @@ function ensureTrustHostDir() {
504
555
  }
505
556
 
506
557
  /** What is wrong with the resident's trust mount, from `docker inspect` Mounts, or null when it is the read-only host directory. */
507
- export function trustMountIssue(mounts) {
508
- const mount = (Array.isArray(mounts) ? mounts : []).find((entry) => entry?.Destination === "/etc/ouro/trust/sanctuary")
558
+ export function trustMountIssue(mounts, name = "sanctuary") {
559
+ const mount = (Array.isArray(mounts) ? mounts : []).find((entry) => entry?.Destination === trustTarget(name))
509
560
  if (!mount) return "the operator trust directory is not mounted in the resident, so no grant would be honoured"
510
561
  if (mount.Source !== TRUST_HOST_DIR) return `the operator trust directory is mounted from ${mount.Source}, not the root-owned host directory`
511
562
  return mount.RW === false ? null : "the operator trust directory is mounted read-write in the resident"
@@ -522,16 +573,33 @@ export function legacyDelegationGrantWarnings(friendRecords, trustedGrants) {
522
573
  * Escalation holders the old harness honoured (the bundle's state/a2a/escalation-grants.json) that the trusted file does not list. The
523
574
  * upgrade never copies a grant out of the bundle, so each of these loses the escalation grant until the operator re-grants it.
524
575
  */
525
- export function legacyEscalationGrantProblems(legacyGrants, trustedGrants) {
576
+ export function legacyEscalationGrantProblems(legacyGrants, trustedGrants, name = "sanctuary") {
526
577
  return Object.entries(legacyGrants ?? {})
527
578
  .filter(([id]) => !(id in (trustedGrants ?? {})))
528
- .map(([id, grant]) => `escalation holder ${id} is in the bundle's state/a2a/escalation-grants.json but not in ${TRUST_HOST_DIR}/escalation-grants.json, so the upgrade would drop it; grant it as root first with \`ouro a2a escalation grant --agent sanctuary --friend ${id} --did ${typeof grant?.did === "string" ? grant.did : "<did:key>"}\` (the one-off container form is in deploy/unraid/README.txt)`)
579
+ .map(([id, grant]) => `escalation holder ${id} is in the bundle's state/a2a/escalation-grants.json but not in ${TRUST_HOST_DIR}/escalation-grants.json, so the upgrade would drop it; grant it as root first with \`ouro a2a escalation grant --agent ${name} --friend ${id} --did ${typeof grant?.did === "string" ? grant.did : "<did:key>"}\` (the one-off container form is in deploy/unraid/README.txt)`)
529
580
  }
530
581
 
531
582
  /** Reads the legacy bundle file and the trusted file from the host and returns the holders the upgrade would drop. */
532
- function escalationGrantProblems() {
583
+ function escalationGrantProblems(name) {
533
584
  const read = (file) => { try { return JSON.parse(readFileSync(file, "utf8")).grants ?? {} } catch { return {} } }
534
- return legacyEscalationGrantProblems(read(`${BUNDLE}/state/a2a/escalation-grants.json`), read(`${TRUST_HOST_DIR}/escalation-grants.json`))
585
+ return legacyEscalationGrantProblems(read(`${hostBundle()}/state/a2a/escalation-grants.json`), read(`${TRUST_HOST_DIR}/escalation-grants.json`), name)
586
+ }
587
+
588
+ /**
589
+ * What is wrong with a leftover container-credentials handoff (the file, or its `.consuming` claim) for a Butler of this
590
+ * name: one naming any other agent makes the daemon refuse to start (container-credential-bootstrap.ts). Null when there is
591
+ * none or every one names this Butler. `read` returns a file's text, or null when it is absent.
592
+ */
593
+ export function credentialHandoffIssue(name, read = (file) => (existsSync(file) ? readFileSync(file, "utf8") : null)) {
594
+ for (const file of [`${RUNTIME}/container-credentials.json`, `${RUNTIME}/container-credentials.json.consuming`]) {
595
+ const text = read(file)
596
+ if (text === null) continue
597
+ let agents
598
+ try { agents = JSON.parse(text).credentials.map((message) => message?.agentName) } catch { return `${file} cannot be read as a credential handoff; quarantine it before the upgrade` }
599
+ const other = agents.find((agent) => agent !== name)
600
+ if (other !== undefined) return `${file} names ${JSON.stringify(other)}, not ${name}, so the new Butler would refuse to start; quarantine it before the upgrade`
601
+ }
602
+ return null
535
603
  }
536
604
 
537
605
  function recreateResident(version) {
@@ -539,16 +607,20 @@ function recreateResident(version) {
539
607
  disableResidentAutostart()
540
608
  ensureTrustHostDir()
541
609
  const icon = "https://raw.githubusercontent.com/ourostack/ouroboros/main/assets/ouroboros.png"
610
+ // The image names where the bundle and trust are mounted; the host folders stay. --mount refuses a missing source,
611
+ // where -v would have Docker create an empty folder in its place. Read the name before the resident goes, so a failed
612
+ // inspect leaves it standing.
613
+ const name = imageButlerName(image(version))
542
614
  docker(["rm", "-f", CONTAINER], { stdio: "ignore" })
543
615
  docker(["create", "--name", CONTAINER, "--network", "host", "--restart", "unless-stopped", "--user", "10001:10001",
544
616
  "-l", "net.unraid.docker.managed=dockerman",
545
617
  "-l", `net.unraid.docker.icon=${icon}`,
546
618
  "-l", "org.opencontainers.image.source=https://github.com/ourostack/ouroboros",
547
619
  "-v", "/mnt/user/appdata/ouro-butler/runtime/.ouro-cli:/home/ouro/.ouro-cli:rw",
548
- "-v", "/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro:/home/ouro/AgentBundles/sanctuary.ouro:rw",
620
+ "--mount", `type=bind,src=${hostBundle()},dst=${containerBundle(name)}`,
549
621
  "-v", "/boot/config/custom/ouro-events/spool:/run/ouro-events:ro",
550
622
  "-v", "/run/ouro-authority:/run/ouro-authority:ro",
551
- "-v", TRUST_MOUNT,
623
+ "--mount", trustMount(name),
552
624
  "-v", SYNC_MOUNT,
553
625
  image(version)])
554
626
  const ref = docker(["inspect", CONTAINER, "--format", "{{.Config.Image}}"]).trim()
@@ -578,7 +650,7 @@ export function trustedStateChild(bundle, name, { lstat = lstatSync, realpath =
578
650
  if (!resolved || resolved !== expected) return refuse("it resolves outside the bundle's own state directory")
579
651
  return dir
580
652
  }
581
- export function restoreReplayRoot(bundle = BUNDLE, { lstat = lstatSync, realpath = realpathSync, chmod = chmodSync, rm = rmSync, run = sh, log = warn } = {}) {
653
+ export function restoreReplayRoot(bundle = hostBundle(), { lstat = lstatSync, realpath = realpathSync, chmod = chmodSync, rm = rmSync, run = sh, log = warn } = {}) {
582
654
  const dir = trustedStateChild(bundle, "replay", { lstat, realpath, log })
583
655
  if (!dir) return
584
656
  run("/bin/chown", ["-h", "0:0", dir])
@@ -600,7 +672,7 @@ export function restorePsycheModes(dir, { lstat = lstatSync, readdir = readdirSy
600
672
  walk(dir)
601
673
  }
602
674
  function restorePsycheRoot() {
603
- const dir = `${BUNDLE}/psyche`
675
+ const dir = `${hostBundle()}/psyche`
604
676
  if (existsSync(dir)) restorePsycheModes(dir)
605
677
  }
606
678
 
@@ -730,8 +802,8 @@ export function reportPsycheSurvival(id, dir, planted, log = console.log, option
730
802
  * What is wrong with the resident's psyche mount, from `docker inspect` Mounts, or null for a supported shape: no separate psyche
731
803
  * mount (current releases), or a read-only one (alpha.978 and earlier, which a rollback recreates).
732
804
  */
733
- export function psycheMountIssue(mounts) {
734
- const mount = (Array.isArray(mounts) ? mounts : []).find((entry) => entry?.Destination === PSYCHE_TARGET)
805
+ export function psycheMountIssue(mounts, name = "sanctuary") {
806
+ const mount = (Array.isArray(mounts) ? mounts : []).find((entry) => entry?.Destination === psycheTarget(name))
735
807
  return !mount || mount.RW === false ? null : "psyche is mounted read-write as a separate mount in the resident"
736
808
  }
737
809
 
@@ -740,19 +812,20 @@ function migrateBundle(version, rollbackImage) {
740
812
  const pkgBundle = `${ROOT}/incoming-package/deploy/unraid/sanctuary.ouro`
741
813
  const migrate = `${ROOT}/incoming-package/deploy/unraid/migrate-sanctuary-bundle.mjs`
742
814
  if (!existsSync(`${pkgBundle}/provider-readiness.json`)) fail(`packaged bundle template missing provider-readiness.json at ${pkgBundle}`)
815
+ const bundle = hostBundle()
743
816
  if (rollbackImage === null) {
744
817
  // A fresh install has no earlier image to roll back to: write the packaged files with no rollback record.
745
- sh("/usr/local/bin/node", [migrate, "--package-root", pkgBundle, "--agent-root", BUNDLE, "--operation", "seed"])
818
+ sh("/usr/local/bin/node", [migrate, "--package-root", pkgBundle, "--agent-root", bundle, "--operation", "seed"])
746
819
  ok("bundle seeded from the package (fresh install)")
747
820
  } else {
748
- sh("/usr/local/bin/node", [migrate, "--package-root", pkgBundle, "--agent-root", BUNDLE, "--operation", "migrate",
821
+ sh("/usr/local/bin/node", [migrate, "--package-root", pkgBundle, "--agent-root", bundle, "--operation", "migrate",
749
822
  "--rollback-image-id", rollbackImage, "--target-image-id", imageId(version)])
750
823
  ok("bundle migrated (rollback retained)")
751
- sh("/usr/local/bin/node", [migrate, "--package-root", pkgBundle, "--agent-root", BUNDLE, "--operation", "commit"])
824
+ sh("/usr/local/bin/node", [migrate, "--package-root", pkgBundle, "--agent-root", bundle, "--operation", "commit"])
752
825
  }
753
826
  // migrate/commit ran as root; the resident owns its bundle as uid 10001, so restore ownership
754
- sh("/bin/chown", ["-R", "10001:10001", BUNDLE])
755
- restoreReplayRoot()
827
+ sh("/bin/chown", ["-R", "10001:10001", bundle])
828
+ restoreReplayRoot(bundle)
756
829
  restorePsycheRoot()
757
830
  ok("bundle committed (ownership restored to resident)")
758
831
  }
@@ -1051,20 +1124,26 @@ function autoRollback(rollbackImage, version) {
1051
1124
  // `bw edit` fails ("The client copy of this cipher is out of date"). The store's
1052
1125
  // own sync-on-login skips when its freshness marker is <60s old, so we sync
1053
1126
  // directly (unlock -> sync) and let the write proceed against a reconciled cache.
1054
- function forceBwSync(name) {
1055
- const script = [
1127
+ export function forceBwSyncScript(butler) {
1128
+ return [
1056
1129
  'const cp=require("node:child_process"),fs=require("node:fs");',
1057
- 'const {readVaultUnlockSecret}=require("/opt/ouro/dist/repertoire/vault-unlock.js");',
1058
- 'const cfg=JSON.parse(fs.readFileSync("/home/ouro/AgentBundles/sanctuary.ouro/agent.json","utf8")).vault||{};',
1130
+ 'const {readVaultUnlockSecret,bitwardenAppDataDir}=require("/opt/ouro/dist/repertoire/vault-unlock.js");',
1131
+ `const NAME=${JSON.stringify(butler)};`,
1132
+ `const cfg=JSON.parse(fs.readFileSync(${JSON.stringify(`${containerBundle(butler)}/agent.json`)},"utf8")).vault||{};`,
1059
1133
  'const email=cfg.email, url=cfg.serverUrl;',
1060
- 'const base="/home/ouro/.ouro-cli/bitwarden";',
1061
- 'const APP=base+"/"+fs.readdirSync(base).find(d=>/^[0-9a-f]{16,}$/.test(d));',
1062
- 'const u=readVaultUnlockSecret({agentName:"sanctuary",email,serverUrl:url});',
1134
+ // The bw folder is keyed by the agent's name, so the other name's folder may be there too: take this Butler's.
1135
+ // Hash the folder from the vault config the daemon resolves (normalised URL, legacy hosts mapped), or it misses.
1136
+ 'const {resolveVaultConfig}=require("/opt/ouro/dist/heart/identity.js");',
1137
+ 'const APP=bitwardenAppDataDir(NAME,resolveVaultConfig(NAME,cfg),"/home/ouro");',
1138
+ 'const u=readVaultUnlockSecret({agentName:NAME,email,serverUrl:url});',
1063
1139
  'const env={...process.env,BITWARDENCLI_APPDATA_DIR:APP,OURO_BW_MASTER_PASSWORD:u.secret};',
1064
1140
  'const sess=cp.execFileSync("bw",["unlock","--passwordenv","OURO_BW_MASTER_PASSWORD","--raw"],{env,encoding:"utf8"}).trim();',
1065
1141
  'cp.execFileSync("bw",["sync"],{env:{...env,BW_SESSION:sess},encoding:"utf8"});',
1066
1142
  'process.stdout.write("bw-synced");',
1067
1143
  ].join("")
1144
+ }
1145
+ function forceBwSync(name, butler) {
1146
+ const script = forceBwSyncScript(butler)
1068
1147
  try { docker(["exec", "-u", "0:0", name, "node", "-e", script], { stdio: ["ignore", "pipe", "pipe"] }); ok("forced bw sync before token restore") }
1069
1148
  catch (e) { console.log(` forceBwSync: ${String(e.message).split("\n")[0]} (continuing; restore may still succeed)`) }
1070
1149
  }
@@ -1074,9 +1153,10 @@ function rematerialiseToken(version) {
1074
1153
  const incoming = `${ROOT}/incoming-token`
1075
1154
  const fromIncoming = existsSync(incoming) && statSync(incoming).size > 0
1076
1155
  const name = `ouro-vault-fix-${process.pid}`
1156
+ const butler = imageButlerName(image(version))
1077
1157
  docker(["rm", "-f", name], { stdio: "ignore" })
1078
1158
  docker(["run", "-d", "--name", name, "--network", "host", "--user", "0:0",
1079
- "-v", `${RUNTIME}:/home/ouro/.ouro-cli`, "-v", `${BUNDLE}:/home/ouro/AgentBundles/sanctuary.ouro`,
1159
+ "-v", `${RUNTIME}:/home/ouro/.ouro-cli`, "--mount", `type=bind,src=${hostBundle()},dst=${containerBundle(butler)}`,
1080
1160
  "--entrypoint", "sleep", image(version), "infinity"])
1081
1161
  try {
1082
1162
  sh("/bin/sleep", ["3"])
@@ -1090,7 +1170,7 @@ function rematerialiseToken(version) {
1090
1170
  const rc = resident.credentials[0].runtimeConfig
1091
1171
  const restore = JSON.stringify({ token: tok, botId: tok.split(":")[0],
1092
1172
  ownerUserId: String(rc.telegramAuthorizedUserId), ownerChatId: String(rc.telegramAuthorizedChatId) })
1093
- forceBwSync(name)
1173
+ forceBwSync(name, butler)
1094
1174
  docker(["exec", "-i", "-u", "0:0", name, "node", CLI, "vault", "restore"], { input: restore, stdio: ["pipe", "pipe", "pipe"] })
1095
1175
  // Fail loudly if the restored token is not actually live at Telegram, rather
1096
1176
  // than leaving a "healthy" container polling a revoked token (a deaf bot).
@@ -1128,7 +1208,7 @@ function buildFinalProof(version, out) {
1128
1208
  readFileSync("/var/lib/docker/unraid-autostart", "utf8").split("\n").some((l) => l.split(" ")[0] === "ouro-butler")
1129
1209
  const text = (tag2) => (readFileSync(TEMPLATE, "utf8").match(new RegExp(`<${tag2}>([^<]*)</${tag2}>`)) || [])[1]
1130
1210
  const bundle = JSON.parse(sh("/usr/local/bin/node", [`${ROOT}/incoming-package/deploy/unraid/migrate-sanctuary-bundle.mjs`,
1131
- "--package-root", `${ROOT}/package`, "--agent-root", BUNDLE, "--operation", "status"]))
1211
+ "--package-root", `${ROOT}/package`, "--agent-root", hostBundle(), "--operation", "status"]))
1132
1212
  const jf = JSON.parse(docker(["container", "inspect", "jellyfin", "--format",
1133
1213
  '{"containerId":{{json .Id}},"imageId":{{json .Image}},"state":{{json .State.Status}},"restartCount":{{json .RestartCount}}}']))
1134
1214
  const proof = {
@@ -1187,16 +1267,18 @@ function resumeSupervision() {
1187
1267
  }
1188
1268
 
1189
1269
  /**
1190
- * The template text without its psyche `<Config>` (Target exactly PSYCHE_TARGET), so a DockerMan Apply cannot put the old read-only
1270
+ * The template text without its psyche `<Config>` (Target exactly the psyche under either Butler name), so a DockerMan Apply cannot put the old read-only
1191
1271
  * psyche mount back. The element is removed with the whitespace that starts its line and the newline that ends it; every other byte
1192
1272
  * is kept. `parse` is docker-man-template-xml.cjs's parseDockerManTemplateXml: a template it cannot read, or one without exactly one
1193
1273
  * such Config, comes back unchanged, as does one where the textual match does not remove exactly that element.
1194
1274
  */
1195
1275
  export function withoutPsycheConfig(text, parse) {
1196
- const psycheConfigs = (document) => document?.children.filter((child) => child.name === "Config" && child.attributes.Target === PSYCHE_TARGET).length
1276
+ const targets = BUTLER_NAMES.map(psycheTarget)
1277
+ const psycheConfigs = (document) => document?.children.filter((child) => child.name === "Config" && targets.includes(child.attributes.Target)).length
1197
1278
  const before = parse(text)
1198
1279
  if (psycheConfigs(before) !== 1) return text
1199
- const next = text.replace(new RegExp(`[ \\t]*<Config\\b[^<>]*\\sTarget="${PSYCHE_TARGET.replace(/[.]/gu, "\\.")}"[^<>]*(?:/>|>[^<]*</Config>)[ \\t]*\\r?\\n?`, "u"), "")
1280
+ const target = before.children.find((child) => child.name === "Config" && targets.includes(child.attributes.Target)).attributes.Target
1281
+ const next = text.replace(new RegExp(`[ \\t]*<Config\\b[^<>]*\\sTarget="${target.replace(/[.]/gu, "\\.")}"[^<>]*(?:/>|>[^<]*</Config>)[ \\t]*\\r?\\n?`, "u"), "")
1200
1282
  const after = parse(next)
1201
1283
  return after && psycheConfigs(after) === 0 && after.children.length === before.children.length - 1 ? next : text
1202
1284
  }
@@ -1218,21 +1300,104 @@ export function withSyncConfig(text, parse) {
1218
1300
  return after && syncConfigs(after) === 1 && after.children.length === before.children.length + 1 ? next : text
1219
1301
  }
1220
1302
 
1221
- // Keep Unraid's DockerMan template (what the UI's Apply/Update uses) on the live image, without the old psyche mount.
1222
- // Runs after the commit, so the parser comes from the installed package (this script is staged on its own, without siblings).
1303
+ // Keep Unraid's DockerMan template (what the UI's Apply/Update uses) on the live image, without the old psyche mount, and
1304
+ // mounting the bundle and trust where that image's Butler expects them. Runs after the commit, so the parser comes from the
1305
+ // installed package (this script is staged on its own, without siblings). The upgrade checks it can pin before it changes
1306
+ // anything (templatePinProblem), so a template it cannot move to a new Butler name stops the upgrade instead of the pin.
1223
1307
  function pinTemplate(version) {
1224
- if (!existsSync(TEMPLATE)) { console.log(" note: no DockerMan template to update"); return }
1225
- const text = readFileSync(TEMPLATE, "utf8")
1226
- let next = text.replace(/<Repository>ghcr\.io\/ourostack\/ouroboros-butler:[^<]+<\/Repository>/u, `<Repository>${image(version)}</Repository>`)
1227
- if (!next.includes(`<Repository>${image(version)}</Repository>`)) { console.log(" WARN: DockerMan template Repository not recognised; left unchanged"); return }
1308
+ const pin = templatePin(version)
1309
+ if (pin.absent) { console.log(" note: no DockerMan template to update"); return }
1310
+ if (pin.problem) fail(`${pin.problem}; a DockerMan Apply would mount the bundle and trust where ${image(version)} does not look for them, so fix the template by hand first`)
1311
+ for (const warning of pin.warnings) console.log(` WARN: ${warning}`)
1312
+ if (pin.text !== pin.original) { writeFileSync(`${TEMPLATE}.prev`, pin.original); writeFileSync(TEMPLATE, pin.text) }
1313
+ if (!pin.skipped) ok(`DockerMan template pins ${image(version)}`)
1314
+ }
1315
+
1316
+ /** The installed template, pinned for this version and the Butler name its image runs, without writing it. */
1317
+ function templatePin(version) {
1318
+ if (!existsSync(TEMPLATE)) return { absent: true }
1319
+ const original = readFileSync(TEMPLATE, "utf8")
1320
+ let parse = null
1321
+ let parserError = null
1228
1322
  try {
1229
- const { parseDockerManTemplateXml } = createRequire(import.meta.url)(`${ROOT}/package/deploy/unraid/docker-man-template-xml.cjs`)
1230
- next = withSyncConfig(withoutPsycheConfig(next, parseDockerManTemplateXml), parseDockerManTemplateXml)
1231
- } catch (error) { console.log(` WARN: could not load the DockerMan template parser (${error.message}); psyche Config left in place, sync key Config not added`) }
1232
- if (next.includes(`Target="${PSYCHE_TARGET}"`)) console.log(" WARN: DockerMan template still has a psyche Config; remove it before the next DockerMan Apply")
1233
- if (!next.includes(`Target="${SYNC_TARGET}"`)) console.log(` WARN: DockerMan template has no ${SYNC_TARGET} Config; add it before the next DockerMan Apply`)
1234
- if (next !== text) { writeFileSync(`${TEMPLATE}.prev`, text); writeFileSync(TEMPLATE, next) }
1235
- ok(`DockerMan template pins ${image(version)}`)
1323
+ // Load the parser fresh each time: preflight reads the predecessor package's copy, and the pin after the switch must
1324
+ // read the new one at the same path, which require's cache would otherwise hand back.
1325
+ const load = createRequire(import.meta.url)
1326
+ const parserPath = `${ROOT}/package/deploy/unraid/docker-man-template-xml.cjs`
1327
+ delete load.cache[load.resolve(parserPath)]
1328
+ parse = load(parserPath).parseDockerManTemplateXml
1329
+ } catch (error) { parserError = error.message }
1330
+ return { original, ...pinTemplateText(original, image(version), imageButlerName(image(version)), parse, parserError) }
1331
+ }
1332
+
1333
+ /** Why the installed template cannot be pinned for this version, or null (also when there is no template). */
1334
+ function templatePinProblem(version) { return templatePin(version).problem ?? null }
1335
+
1336
+ /**
1337
+ * Whether the template must have its bundle and trust Targets moved to this Butler name: it lacks either one under the name,
1338
+ * and the name is butler or the template already says butler somewhere. A sanctuary image never moves a sanctuary template,
1339
+ * so every sanctuary pin does exactly what it did before the rename.
1340
+ */
1341
+ export function templateNeedsButlerName(text, name) {
1342
+ const has = (target) => text.includes(`Target="${target}"`)
1343
+ if (has(containerBundle(name)) && has(trustTarget(name))) return false
1344
+ return name !== "sanctuary" || has(containerBundle("butler")) || has(trustTarget("butler"))
1345
+ }
1346
+
1347
+ /**
1348
+ * The template with its bundle Config's Target and its trust Config's Target moved to this Butler name. Their Defaults and
1349
+ * values, the host folders, stay. `{ problem }` when the parser cannot read it, it lacks exactly one bundle Config and one
1350
+ * trust Config, a Target appears more than once in the text, or the result does not parse with exactly those two moved.
1351
+ */
1352
+ export function withButlerTargets(text, name, parse) {
1353
+ const configs = (document, targets) => document.children.filter((child) => child.name === "Config" && targets.includes(child.attributes.Target))
1354
+ const before = parse(text)
1355
+ if (!before) return { problem: "the DockerMan template cannot be parsed" }
1356
+ const bundles = configs(before, BUTLER_NAMES.map(containerBundle))
1357
+ const trusts = configs(before, BUTLER_NAMES.map(trustTarget))
1358
+ if (bundles.length !== 1 || trusts.length !== 1) return { problem: "the DockerMan template does not have exactly one bundle Config and one trust Config" }
1359
+ let next = text
1360
+ for (const [config, target] of [[bundles[0], containerBundle(name)], [trusts[0], trustTarget(name)]]) {
1361
+ const from = `Target="${config.attributes.Target}"`
1362
+ if (config.attributes.Target === target) continue
1363
+ if (next.split(from).length !== 2) return { problem: `the DockerMan template has ${from} more than once` }
1364
+ next = next.replace(from, `Target="${target}"`)
1365
+ }
1366
+ const after = parse(next)
1367
+ if (!after || after.children.length !== before.children.length || configs(after, [containerBundle(name)]).length !== 1 || configs(after, [trustTarget(name)]).length !== 1) {
1368
+ return { problem: "moving the DockerMan template's bundle and trust Targets did not leave exactly those two moved" }
1369
+ }
1370
+ return { text: next }
1371
+ }
1372
+
1373
+ /**
1374
+ * The template text pinned to `reference` for the Butler `name`: the Repository, no psyche Config, the sync key Config, and
1375
+ * the bundle and trust Targets under `name`. `parse` is null when the parser could not be loaded (`parserError` says why).
1376
+ * `{ problem }` when the Targets must move to a new name and cannot; otherwise `{ text, warnings, skipped }`, where the parts
1377
+ * a sanctuary pin has always only warned about stay warnings.
1378
+ */
1379
+ export function pinTemplateText(text, reference, name, parse, parserError) {
1380
+ const needsName = templateNeedsButlerName(text, name)
1381
+ const repository = `<Repository>${reference}</Repository>`
1382
+ let next = text.replace(/<Repository>ghcr\.io\/ourostack\/ouroboros-butler:[^<]+<\/Repository>/u, repository)
1383
+ if (!next.includes(repository)) {
1384
+ return needsName ? { problem: "the DockerMan template's Repository is not recognised" } : { text, warnings: ["DockerMan template Repository not recognised; left unchanged"], skipped: true }
1385
+ }
1386
+ const warnings = []
1387
+ if (!parse) {
1388
+ if (needsName) return { problem: `the DockerMan template parser could not be loaded (${parserError})` }
1389
+ warnings.push(`could not load the DockerMan template parser (${parserError}); psyche Config left in place, sync key Config not added`)
1390
+ } else {
1391
+ next = withSyncConfig(withoutPsycheConfig(next, parse), parse)
1392
+ if (needsName) {
1393
+ const moved = withButlerTargets(next, name, parse)
1394
+ if (moved.problem) return { problem: moved.problem }
1395
+ next = moved.text
1396
+ }
1397
+ }
1398
+ if (BUTLER_NAMES.some((butler) => next.includes(`Target="${psycheTarget(butler)}"`))) warnings.push("DockerMan template still has a psyche Config; remove it before the next DockerMan Apply")
1399
+ if (!next.includes(`Target="${SYNC_TARGET}"`)) warnings.push(`DockerMan template has no ${SYNC_TARGET} Config; add it before the next DockerMan Apply`)
1400
+ return { text: next, warnings, skipped: false }
1236
1401
  }
1237
1402
 
1238
1403
  // Every release pulls a ~1 GB Butler image, and Unraid's docker.img filled to 88% with
@@ -1372,10 +1537,13 @@ async function upgrade(version, rehearse, { noGate = false, plant } = {}) {
1372
1537
  if (!telegram.ok) fail(`api.telegram.org is not reachable from this host (${telegram.detail}); the new gateway could not pass its Telegram identity check. Nothing was paused or changed; fix the network and re-run.`)
1373
1538
  if (telegram.skipped) console.log(" note: resuming a pending upgrade; Telegram reachability not re-checked")
1374
1539
  else ok(`api.telegram.org reachable (${telegram.detail})`)
1375
- const psycheDir = `${BUNDLE}/psyche`
1540
+ const pinProblem = templatePinProblem(version)
1541
+ if (pinProblem) fail(`${pinProblem}, so the DockerMan template could not follow ${image(version)}; nothing was paused or changed`)
1542
+ // The host bundle is found on disk at each use; it never moves, so every check below reads the same psyche.
1543
+ const psycheDir = () => `${hostBundle()}/psyche`
1376
1544
  let planted = null
1377
1545
  if (gated) {
1378
- try { planted = plantPsycheMarker(psycheDir, { uid: 10001, gid: 10001 }) } catch (e) { fail(`could not plant the psyche marker before the gated upgrade; nothing was paused or changed: ${e.message}`) }
1546
+ try { planted = plantPsycheMarker(psycheDir(), { uid: 10001, gid: 10001 }) } catch (e) { fail(`could not plant the psyche marker before the gated upgrade; nothing was paused or changed: ${e.message}`) }
1379
1547
  ok("psyche marker planted and the four identity files hashed")
1380
1548
  }
1381
1549
  pauseSupervision()
@@ -1413,7 +1581,7 @@ async function upgrade(version, rehearse, { noGate = false, plant } = {}) {
1413
1581
  runGate: () => {
1414
1582
  if (preserved.length) return { ok: false, detail: preserved.join("; ") }
1415
1583
  if (!waitForButler(image(version), 300)) return { ok: false, detail: `the new Butler did not become healthy on ${image(version)}` }
1416
- const lost = reportPsycheSurvival("psyche-survives-release", psycheDir, planted)
1584
+ const lost = reportPsycheSurvival("psyche-survives-release", psycheDir(), planted)
1417
1585
  if (lost) return { ok: false, detail: `the psyche did not survive the release: ${lost}` }
1418
1586
  const result = runReplayGate(plant)
1419
1587
  if (!result.ok) return result
@@ -1437,14 +1605,14 @@ async function upgrade(version, rehearse, { noGate = false, plant } = {}) {
1437
1605
  },
1438
1606
  confirmRollback: () => {
1439
1607
  if (!waitForButler(priorImage, 300)) fail(`rolled back, but ${priorImage} is not running healthy; inspect \`docker logs ${CONTAINER}\``)
1440
- reportPsycheSurvival("psyche-survives-rollback", psycheDir, planted)
1608
+ reportPsycheSurvival("psyche-survives-rollback", psycheDir(), planted)
1441
1609
  return priorImage
1442
1610
  },
1443
1611
  pin: () => pinTemplate(version),
1444
1612
  prune: () => pruneButlerImages(),
1445
1613
  })
1446
1614
  } finally {
1447
- const left = removePsycheMarker(psycheDir, planted.token)
1615
+ const left = removePsycheMarker(psycheDir(), planted.token)
1448
1616
  if (left) warn(`the psyche marker was left in place: ${left}`)
1449
1617
  }
1450
1618
  if (!outcome.passed) process.exit(1)
@@ -1462,19 +1630,22 @@ function verify(withGate = false) {
1462
1630
  ok(`butler: ${st}`)
1463
1631
  const auth = docker(["logs", CONTAINER, "--since", "2m"], { stdio: ["ignore","pipe","pipe"] }).split("\n").filter((l) => l.includes("401")).length
1464
1632
  auth === 0 ? ok("no Telegram auth failures in the last 2m") : bad(`${auth} 401s in the last 2m`)
1465
- existsSync(POLICY) ? ok(`steward policy ${sha12(POLICY)}`) : installedRequest()?.predecessorContract === "none" ? ok("no steward policy yet") : bad("steward policy missing")
1633
+ const policy = policyFile()
1634
+ existsSync(policy) ? ok(`steward policy ${sha12(policy)}`) : installedRequest()?.predecessorContract === "none" ? ok("no steward policy yet") : bad("steward policy missing")
1635
+ // The paths inside the resident follow the Butler name its image runs.
1636
+ const name = liveButlerName()
1466
1637
  const psycheMount = JSON.parse(docker(["inspect", CONTAINER, "--format", "{{json .Mounts}}"]) || "[]")
1467
- psycheMountIssue(psycheMount) === null ? ok("psyche mount is in a supported shape") : bad(psycheMountIssue(psycheMount))
1468
- existsSync(TEMPLATE) && readFileSync(TEMPLATE, "utf8").includes(`Target="${PSYCHE_TARGET}"`)
1638
+ psycheMountIssue(psycheMount, name) === null ? ok("psyche mount is in a supported shape") : bad(psycheMountIssue(psycheMount, name))
1639
+ existsSync(TEMPLATE) && BUTLER_NAMES.some((butler) => readFileSync(TEMPLATE, "utf8").includes(`Target="${psycheTarget(butler)}"`))
1469
1640
  ? bad("installed DockerMan template still mounts the psyche read-only; a DockerMan Apply would restore it")
1470
1641
  : ok("installed DockerMan template has no separate psyche mount")
1471
1642
  const trustMount = JSON.parse(docker(["inspect", CONTAINER, "--format", "{{json .Mounts}}"]) || "[]")
1472
- trustMountIssue(trustMount) === null ? ok("the operator trust directory is mounted read-only in the resident") : bad(trustMountIssue(trustMount))
1643
+ trustMountIssue(trustMount, name) === null ? ok("the operator trust directory is mounted read-only in the resident") : bad(trustMountIssue(trustMount, name))
1473
1644
  const trustIssue = existsSync(TRUST_HOST_DIR) ? trustDirIssue(lstatSync(TRUST_HOST_DIR)) : `${TRUST_HOST_DIR} is missing`
1474
1645
  trustIssue === null ? ok("the host trust directory is root-owned and closed to group and other writes") : bad(trustIssue)
1475
- const droppedHolders = escalationGrantProblems()
1646
+ const droppedHolders = escalationGrantProblems(name)
1476
1647
  droppedHolders.length === 0 ? ok("every escalation holder is in the trusted file") : droppedHolders.forEach((line) => bad(line))
1477
- const psycheDir = `${BUNDLE}/psyche`
1648
+ const psycheDir = `${hostBundle()}/psyche`
1478
1649
  if (existsSync(psycheDir)) {
1479
1650
  const psycheIssues = psycheProblems(psycheDir)
1480
1651
  psycheIssues.length === 0 ? ok("psyche files are resident-owned and writable") : bad(`psyche files must be owned by the resident (uid 10001), not writable by group or others, and not symlinks: ${psycheIssues.slice(0, 3).join("; ")}`)