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

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
@@ -2,12 +2,18 @@
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
4
  {
5
- "version": "0.1.0-alpha.1635",
5
+ "version": "0.1.0-alpha.1636",
6
6
  "changes": [
7
- "Update the Ouro UI files to Ouro UI v1.3.589.",
8
7
  "The Butler's Telegram front door runs under either of the Butler's names. This covers the root gateway's transport, the owner's and household's privileges, the Butler tools, the privileged failsafe, and the SABnzbd key it reads to verify a protective pause.",
9
8
  "The privileged event spool keeps its events and replay manifest under the name of the Butler the daemon runs. An envelope from the host's emitter that still names the Butler by its other name is filed there too, so usenet alerts survive the rename.",
10
- "The vault handoff, root-host approvals and the health sweep's acceptance marker each follow the Butler's bundle name. The vault's machine id stays `sanctuary`."
9
+ "The vault handoff, root-host approvals and the health sweep's acceptance marker each follow the Butler's bundle name. The vault's machine id stays `sanctuary`.",
10
+ "The Butler's host tools now read the Butler's name from the image they start (the name after `--package-managed-agent` in its entrypoint, else `sanctuary`). They use that name for every path inside the container: the bundle mount, the psyche mount, the trust mount `/etc/ouro/trust/<name>`, the vault and token containers, the bw profile, the replay gate, the sync cutover and the DockerMan template's bundle and trust Targets. The folders on the host never move: the bundle stays at `/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro` and trust stays at `trust/sanctuary`. Resident mounts now use `--mount`, so a missing host folder stops the start instead of mounting an empty one. Preflight also refuses a leftover credential handoff that names another Butler, and a DockerMan template that can't be moved to the image's name. Every image still says `sanctuary`, so nothing changes until a release renames it."
11
+ ]
12
+ },
13
+ {
14
+ "version": "0.1.0-alpha.1634",
15
+ "changes": [
16
+ "Update the Ouro UI files to Ouro UI v1.3.589."
11
17
  ]
12
18
  },
13
19
  {
@@ -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("; ")}`)
@@ -35,7 +35,18 @@ export const DEFAULT_TRUST_DIR = "/mnt/user/appdata/ouro-butler/trust/sanctuary"
35
35
  // bundle: the Butler's user can neither write it nor move it, so nothing in it can be planted. Only this folder and the trust directory's replay
36
36
  // list may supply replay friend ids and DIDs; a file in the bundle never does.
37
37
  export const DEFAULT_CLIENT_DIR = "/mnt/user/appdata/ouro-butler/replay-client"
38
- export const CONTAINER_BUNDLE = "/home/ouro/AgentBundles/sanctuary.ouro"
38
+ // The host folder above never moves. Inside the container the bundle sits under the Butler name the image runs (its ENTRYPOINT's
39
+ // `--package-managed-agent <name>`, read from the live container by main), so every container path below is built from that name.
40
+ export const BUTLER_NAMES = ["butler", "sanctuary"]
41
+ /** The Butler name an image's ENTRYPOINT runs; anything else is sanctuary (as src/heart/butler-agent.ts butlerNameFromEntrypoint). */
42
+ export function butlerNameFromEntrypoint(entrypoint) {
43
+ if (!Array.isArray(entrypoint)) return "sanctuary"
44
+ const flag = entrypoint.indexOf("--package-managed-agent")
45
+ const name = flag >= 0 ? entrypoint[flag + 1] : undefined
46
+ return BUTLER_NAMES.includes(name) ? name : "sanctuary"
47
+ }
48
+ export const containerBundle = (name) => `/home/ouro/AgentBundles/${name}.ouro`
49
+ export const CONTAINER_BUNDLE = containerBundle("sanctuary")
39
50
  export const CONTAINER = "ouro-butler"
40
51
  // The uid the A2A sense runs as inside the container; the trust probe must see the window exactly as that process does.
41
52
  export const BUTLER_USER = "10001:10001"
@@ -169,7 +180,8 @@ export function findHedges(text, terms) {
169
180
  export const mentionsWord = (haystack, name) => new RegExp(`(?<![\\p{L}\\p{N}])${escapeRegExp(name)}(?![\\p{L}\\p{N}])`, "iu").test(String(haystack ?? ""))
170
181
  /** The release's own name finder (src/heart/source-grounding.ts, the one the runtime gates replies with), run inside the container. */
171
182
  // Loads the house's own names first, as every Butler turn does, so the gate and the runtime agree on what counts as a name.
172
- export const NAMES_SCRIPT = 'const [t,o]=JSON.parse(require("fs").readFileSync(0,"utf8"));const g=require("/opt/ouro/dist/heart/source-grounding.js");const h=require("/opt/ouro/dist/senses/sanctuary-house.js").readSanctuaryHouse("/home/ouro/AgentBundles/sanctuary.ouro");g.addHouseVocabulary([h.ownerName,h.butlerName,h.householdName]);console.log(JSON.stringify(g.namesIn(t,o)))'
183
+ export const namesScript = (agentRoot) => `const [t,o]=JSON.parse(require("fs").readFileSync(0,"utf8"));const g=require("/opt/ouro/dist/heart/source-grounding.js");const h=require("/opt/ouro/dist/senses/sanctuary-house.js").readSanctuaryHouse(${JSON.stringify(agentRoot)});g.addHouseVocabulary([h.ownerName,h.butlerName,h.householdName]);console.log(JSON.stringify(g.namesIn(t,o)))`
184
+ export const NAMES_SCRIPT = namesScript(CONTAINER_BUNDLE)
173
185
 
174
186
  /** HH:MM (UTC) of the whole minute `minutes` after the start of `now`'s minute. */
175
187
  export function utcMinuteAhead(now, minutes) {
@@ -1826,8 +1838,14 @@ export const RETIRE_RECORD_SCRIPT = [
1826
1838
  'fs.writeFileSync(file,JSON.stringify(rec,null,2)+"\\n");',
1827
1839
  ].join("")
1828
1840
 
1829
- function retireRecordInContainer(friendId, did) {
1830
- sh("docker", ["exec", "-u", BUTLER_USER, CONTAINER, "node", "-e", RETIRE_RECORD_SCRIPT, CONTAINER_BUNDLE, friendId, did ?? ""])
1841
+ export function retireRecordInContainer(friendId, did, agentRoot = CONTAINER_BUNDLE, run = sh) {
1842
+ run("docker", ["exec", "-u", BUTLER_USER, CONTAINER, "node", "-e", RETIRE_RECORD_SCRIPT, agentRoot, friendId, did ?? ""])
1843
+ }
1844
+
1845
+ /** The Butler name the live container's image runs. Throws when docker cannot say, so the gate never guesses a path. */
1846
+ export function liveButlerName(run = sh) {
1847
+ const imageId = String(run("docker", ["inspect", "--format", "{{.Image}}", CONTAINER])).trim()
1848
+ return butlerNameFromEntrypoint(JSON.parse(String(run("docker", ["image", "inspect", "--format", "{{json .Config.Entrypoint}}", imageId])).trim() || "null"))
1831
1849
  }
1832
1850
 
1833
1851
  /**
@@ -1836,9 +1854,9 @@ function retireRecordInContainer(friendId, did) {
1836
1854
  * that command must run with no more than the Butler's own rights. It runs no hooks and no fsmonitor, and takes no optional lock.
1837
1855
  * `env` adds `-e NAME=value` pairs (ls-remote's ssh). This is the gate's only git call.
1838
1856
  */
1839
- export function bundleGit(args, run = sh, { env = [], timeout = 120_000 } = {}) {
1857
+ export function bundleGit(args, run = sh, { env = [], timeout = 120_000, agentRoot = CONTAINER_BUNDLE } = {}) {
1840
1858
  const envArgs = ["GIT_OPTIONAL_LOCKS=0", ...env].flatMap((pair) => ["-e", pair])
1841
- return run("docker", ["exec", "-u", BUTLER_USER, ...envArgs, CONTAINER, "git", "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", "-C", CONTAINER_BUNDLE, ...args], { timeout, maxBuffer: 256 * 1024 * 1024 })
1859
+ return run("docker", ["exec", "-u", BUTLER_USER, ...envArgs, CONTAINER, "git", "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", "-C", agentRoot, ...args], { timeout, maxBuffer: 256 * 1024 * 1024 })
1842
1860
  }
1843
1861
 
1844
1862
  /** The untracked, unignored paths in the bundle and a hash of each (git's, with no filter run), read in the container. */
@@ -1857,10 +1875,9 @@ export function untrackedFiles(git) {
1857
1875
  * The host side of bundle sync for the gate: the cutover marker, sync's own pause marker, the lock, one `ouro sync` in the container,
1858
1876
  * and read-only git. `sleep` and `now` come from the host, so tests drive the clock.
1859
1877
  */
1860
- export function makeSyncHost({ bundle, backupDir = DEFAULT_BACKUP_DIR, exec = sh, git = (args) => bundleGit(args, exec), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), now = () => Date.now(), pollMs = SYNC_LOCK_POLL_MS }) {
1878
+ export function makeSyncHost({ bundle, backupDir = DEFAULT_BACKUP_DIR, exec = sh, agentName = path.basename(bundle, ".ouro"), git = (args) => bundleGit(args, exec, { agentRoot: containerBundle(agentName) }), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), now = () => Date.now(), pollMs = SYNC_LOCK_POLL_MS }) {
1861
1879
  const state = path.join(bundle, "state")
1862
1880
  const marker = path.join(state, "sync-paused")
1863
- const agentName = path.basename(bundle, ".ouro")
1864
1881
  const branch = () => {
1865
1882
  try { return readJsonNoFollow(path.join(bundle, "agent.json"))?.sync?.branch ?? "main" } catch { return "main" }
1866
1883
  }
@@ -1930,7 +1947,7 @@ export function makeSyncHost({ bundle, backupDir = DEFAULT_BACKUP_DIR, exec = sh
1930
1947
  * not move.
1931
1948
  */
1932
1949
  agentChanges(head) {
1933
- const listed = bundleGit(["ls-remote", "origin", `refs/heads/${branch()}`], exec, { env: [`GIT_SSH_COMMAND=${SYNC_SSH_COMMAND}`, "GIT_SSH_VARIANT=ssh"], timeout: 60_000 })
1950
+ const listed = bundleGit(["ls-remote", "origin", `refs/heads/${branch()}`], exec, { env: [`GIT_SSH_COMMAND=${SYNC_SSH_COMMAND}`, "GIT_SSH_VARIANT=ssh"], timeout: 60_000, agentRoot: containerBundle(agentName) })
1934
1951
  const remoteHead = /^([0-9a-f]{40})\s/u.exec(listed)?.[1]
1935
1952
  if (!remoteHead) throw new Error(`git ls-remote origin refs/heads/${branch()} listed no head`)
1936
1953
  const commits = lines(git(["log", "--no-merges", `--author=<${agentName}@ouro.local>`, "--format=%H", `${head}..${remoteHead}`]))
@@ -1960,7 +1977,7 @@ export function makeSyncHost({ bundle, backupDir = DEFAULT_BACKUP_DIR, exec = sh
1960
1977
  const entry = JSON.parse(line)
1961
1978
  const at = Date.parse(entry.ts)
1962
1979
  if (typeof entry.event !== "string" || !(at >= sinceMs)) continue
1963
- if (entry.meta?.agentRoot !== undefined && entry.meta.agentRoot !== CONTAINER_BUNDLE) continue
1980
+ if (entry.meta?.agentRoot !== undefined && entry.meta.agentRoot !== containerBundle(agentName)) continue
1964
1981
  out.push({ event: entry.event, at })
1965
1982
  } catch { /* a torn line */ }
1966
1983
  }
@@ -1970,7 +1987,8 @@ export function makeSyncHost({ bundle, backupDir = DEFAULT_BACKUP_DIR, exec = sh
1970
1987
  }
1971
1988
  }
1972
1989
 
1973
- export function makeHost({ bundle = DEFAULT_BUNDLE, trustDir = DEFAULT_TRUST_DIR, clientDir = DEFAULT_CLIENT_DIR, backupDir = DEFAULT_BACKUP_DIR, chainRoot, cardUrl, log = console.error, exec = sh, stage = dockerStage(exec), rootUid = 0, rootGid = 0 } = {}) {
1990
+ export function makeHost({ bundle = DEFAULT_BUNDLE, trustDir = DEFAULT_TRUST_DIR, clientDir = DEFAULT_CLIENT_DIR, backupDir = DEFAULT_BACKUP_DIR, chainRoot, cardUrl, log = console.error, exec = sh, stage = dockerStage(exec), rootUid = 0, rootGid = 0, agentName = "sanctuary" } = {}) {
1991
+ const agentRoot = containerBundle(agentName)
1974
1992
  const state = path.join(bundle, "state")
1975
1993
  const replayDir = path.join(state, "replay")
1976
1994
  const clientIssue = rootOwnedDirectoryIssue(clientDir, rootUid)
@@ -2005,7 +2023,7 @@ export function makeHost({ bundle = DEFAULT_BUNDLE, trustDir = DEFAULT_TRUST_DIR
2005
2023
  }
2006
2024
  return {
2007
2025
  friends: { principal: provisioned.principal.friendId, stranger: provisioned.stranger.friendId, escalation: provisioned.escalation.friendId },
2008
- sync: makeSyncHost({ bundle, backupDir, exec }),
2026
+ sync: makeSyncHost({ bundle, backupDir, exec, agentName }),
2009
2027
  now: () => Date.now(),
2010
2028
  sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
2011
2029
  /** The Butler's A2A card must answer before the window opens: a fresh container needs a moment after it turns healthy. */
@@ -2051,7 +2069,7 @@ export function makeHost({ bundle = DEFAULT_BUNDLE, trustDir = DEFAULT_TRUST_DIR
2051
2069
  /** Asks the Butler's own replay code, inside the container, whether it opens the window for both peers. */
2052
2070
  async windowTrusted() {
2053
2071
  const ids = replayPeers
2054
- const script = `const h=require("/opt/ouro/dist/a2a/replay-harness.js");const o={};for(const id of ${JSON.stringify(ids)})o[id]=h.isReplayWindowOpen(${JSON.stringify(CONTAINER_BUNDLE)},id);console.log(JSON.stringify(o))`
2072
+ const script = `const h=require("/opt/ouro/dist/a2a/replay-harness.js");const o={};for(const id of ${JSON.stringify(ids)})o[id]=h.isReplayWindowOpen(${JSON.stringify(agentRoot)},id);console.log(JSON.stringify(o))`
2055
2073
  try {
2056
2074
  const seen = JSON.parse(exec("docker", ["exec", "-u", BUTLER_USER, CONTAINER, "node", "-e", script], { timeout: 60_000 }).trim().split("\n").at(-1))
2057
2075
  const closed = ids.filter((id) => seen[id] !== true)
@@ -2096,7 +2114,7 @@ export function makeHost({ bundle = DEFAULT_BUNDLE, trustDir = DEFAULT_TRUST_DIR
2096
2114
  }
2097
2115
  },
2098
2116
  names(text, options) {
2099
- return JSON.parse(exec("docker", ["exec", "-i", "-u", BUTLER_USER, CONTAINER, "node", "-e", NAMES_SCRIPT], { input: JSON.stringify([text, options]), stdio: ["pipe", "pipe", "pipe"], timeout: 60_000 }).trim().split("\n").at(-1))
2117
+ return JSON.parse(exec("docker", ["exec", "-i", "-u", BUTLER_USER, CONTAINER, "node", "-e", namesScript(agentRoot)], { input: JSON.stringify([text, options]), stdio: ["pipe", "pipe", "pipe"], timeout: 60_000 }).trim().split("\n").at(-1))
2100
2118
  },
2101
2119
  async readSession(context) {
2102
2120
  const root = path.join(state, "sessions")
@@ -2604,7 +2622,7 @@ function trustedReplayList(trustDir) {
2604
2622
  * the record in the root-owned replay folder (`clientDir`). Nothing in the bundle's state/replay-client or state/replay supplies either, because
2605
2623
  * the Butler's user writes the bundle.
2606
2624
  */
2607
- export function provision({ bundle = DEFAULT_BUNDLE, trustDir = DEFAULT_TRUST_DIR, clientDir = DEFAULT_CLIENT_DIR, chainRoot, cardUrl, log = console.log, run = ctr, discover = discoverCardUrl, stage = dockerStage(), retireRecord = retireRecordInContainer, retire = [], rootUid = 0, rootGid = 0, rotate = false, now = new Date() } = {}) {
2625
+ export function provision({ bundle = DEFAULT_BUNDLE, trustDir = DEFAULT_TRUST_DIR, clientDir = DEFAULT_CLIENT_DIR, chainRoot, cardUrl, log = console.log, run = ctr, discover = discoverCardUrl, stage = dockerStage(), retireRecord = retireRecordInContainer, retire = [], rootUid = 0, rootGid = 0, rotate = false, now = new Date(), agentName = "sanctuary" } = {}) {
2608
2626
  const state = path.join(bundle, "state")
2609
2627
  const replayDir = path.join(state, "replay")
2610
2628
  refuseLinkOrWrongType(state, "directory")
@@ -2640,8 +2658,8 @@ export function provision({ bundle = DEFAULT_BUNDLE, trustDir = DEFAULT_TRUST_DI
2640
2658
  // The record lives in the Butler-writable bundle, so a missing or mangled one must not stop the rotation: the trust-dir revokes
2641
2659
  // above are what take authority away, and they have already happened.
2642
2660
  try {
2643
- run(["friend", "update", friendId, "--agent", "sanctuary", "--admission", "revoked", "--trust", "stranger"])
2644
- retireRecord(friendId, did)
2661
+ run(["friend", "update", friendId, "--agent", agentName, "--admission", "revoked", "--trust", "stranger"])
2662
+ retireRecord(friendId, did, containerBundle(agentName))
2645
2663
  log(`retired friend ${friendId}`)
2646
2664
  } catch (error) {
2647
2665
  log(`revoked friend ${friendId}'s grants, but could not demote its record: ${error instanceof Error ? error.message.split("\n")[0] : String(error)}`)
@@ -2667,11 +2685,11 @@ export function provision({ bundle = DEFAULT_BUNDLE, trustDir = DEFAULT_TRUST_DI
2667
2685
  handOverFile(hostIdentity, { uid: rootUid, gid: rootGid, mode: 0o600 })
2668
2686
  let friendId = previous[who]?.did === did ? previous[who].friendId : null
2669
2687
  if (!friendId) {
2670
- const onboarded = run(["a2a", "onboard", "--agent", "sanctuary", "--did", did, "--name", name, "--trust", trust])
2688
+ const onboarded = run(["a2a", "onboard", "--agent", agentName, "--did", did, "--name", name, "--trust", trust])
2671
2689
  friendId = /friend id:\s*(\S+)/.exec(onboarded)?.[1]
2672
2690
  if (!friendId) throw new Error(`could not read the friend id from: ${onboarded}`)
2673
2691
  }
2674
- run(["friend", "update", friendId, "--agent", "sanctuary", "--admission", "active", "--initiative", "reactive_only", "--profile", PEER_PROFILE])
2692
+ run(["friend", "update", friendId, "--agent", agentName, "--admission", "active", "--initiative", "reactive_only", "--profile", PEER_PROFILE])
2675
2693
  const record = readJsonNoFollow(friendFile(bundle, friendId))
2676
2694
  // The record's own delegationGrant is only a hint the Butler ignores; nobody here may hold one.
2677
2695
  if (record.delegationGrant && !grant) throw new Error(`${name} must not hold a delegation grant`)
@@ -2749,12 +2767,15 @@ export async function main(argv, io = { out: (text) => console.log(text), err: (
2749
2767
  for (const file of statusProblems((deps.readStdin ?? (() => readFileSync(0, "utf8")))())) io.out(file)
2750
2768
  return 0
2751
2769
  }
2770
+ // The paths inside the container, and the agent its commands name, follow the Butler name the live container's image runs.
2771
+ let agentName
2772
+ if (options.command === "provision" || options.command === "run") try { agentName = (deps.butlerName ?? liveButlerName)() } catch (error) { io.err(`could not read the Butler's name from the ${CONTAINER} container's image: ${String(error.message).split("\n")[0]}`); return 1 }
2752
2773
  if (options.command === "provision") {
2753
- try { deps.provision({ ...(options.bundle ? { bundle: options.bundle } : {}), ...(options.trustDir ? { trustDir: options.trustDir } : {}), ...(options.cardUrl ? { cardUrl: options.cardUrl } : {}), ...(options.clientDir ? { clientDir: options.clientDir } : {}), ...(options.retire ? { retire: options.retire } : {}), ...(options.rotate ? { rotate: true } : {}), log: io.out }); return 0 } catch (error) { io.err(`provision failed: ${error.message}`); return 1 }
2774
+ try { deps.provision({ agentName, ...(options.bundle ? { bundle: options.bundle } : {}), ...(options.trustDir ? { trustDir: options.trustDir } : {}), ...(options.cardUrl ? { cardUrl: options.cardUrl } : {}), ...(options.clientDir ? { clientDir: options.clientDir } : {}), ...(options.retire ? { retire: options.retire } : {}), ...(options.rotate ? { rotate: true } : {}), log: io.out }); return 0 } catch (error) { io.err(`provision failed: ${error.message}`); return 1 }
2754
2775
  }
2755
2776
  if (options.command === "run") {
2756
2777
  let host
2757
- try { host = deps.makeHost({ ...(options.bundle ? { bundle: options.bundle } : {}), ...(options.backupDir ? { backupDir: options.backupDir } : {}), ...(options.trustDir ? { trustDir: options.trustDir } : {}), ...(options.clientDir ? { clientDir: options.clientDir } : {}), ...(options.cardUrl ? { cardUrl: options.cardUrl } : {}), log: io.err }) } catch (error) { io.err(error.message); return 1 }
2778
+ try { host = deps.makeHost({ agentName, ...(options.bundle ? { bundle: options.bundle } : {}), ...(options.backupDir ? { backupDir: options.backupDir } : {}), ...(options.trustDir ? { trustDir: options.trustDir } : {}), ...(options.clientDir ? { clientDir: options.clientDir } : {}), ...(options.cardUrl ? { cardUrl: options.cardUrl } : {}), log: io.err }) } catch (error) { io.err(error.message); return 1 }
2758
2779
  // butler-ship runs this gate against the live version first and hands the upgrade that log through the environment.
2759
2780
  const baselineFile = options.baseline ?? env.OURO_REPLAY_BASELINE
2760
2781
  let baseline
@@ -31,6 +31,8 @@ BUNDLE_REPO_OWNER=arimendelow
31
31
  BUNDLE_REPO_NAME=sanctuary.ouro
32
32
  BUNDLE_REMOTE="git@github.com:${BUNDLE_REPO_OWNER}/${BUNDLE_REPO_NAME}.git"
33
33
  BUNDLE_BRANCH=main
34
+ # The Butler's name inside the container, and the bundle's path there, follow the live container's image (use_image_agent_name).
35
+ # The host folder ($BUNDLE below) keeps its name whichever name the image runs.
34
36
  AGENT_NAME=sanctuary
35
37
  # backup.sh's commit identity and the fetch refspec the moved repository must have.
36
38
  BACKUP_COMMIT_NAME="Sanctuary backup"
@@ -148,6 +150,19 @@ before_value() {
148
150
  file_value "$BEFORE" "$1" || die "$(basename "$BEFORE") has no \"$1\" line"
149
151
  }
150
152
 
153
+ # Sets AGENT_NAME and CONTAINER_BUNDLE from the Butler name image $1 runs: its ENTRYPOINT's `--package-managed-agent <name>`.
154
+ # Any other entrypoint means sanctuary, as src/heart/butler-agent.ts butlerNameFromEntrypoint reads it.
155
+ use_image_agent_name() {
156
+ local entrypoint name
157
+ entrypoint=$(docker image inspect --format '{{json .Config.Entrypoint}}' "$1") || die "docker could not read the entrypoint of $1"
158
+ name=$(printf '%s' "$entrypoint" | sed -n 's/.*"--package-managed-agent","\([^"]*\)".*/\1/p')
159
+ case "$name" in
160
+ butler | sanctuary) AGENT_NAME=$name ;;
161
+ *) AGENT_NAME=sanctuary ;;
162
+ esac
163
+ CONTAINER_BUNDLE=/home/ouro/AgentBundles/$AGENT_NAME.ouro
164
+ }
165
+
151
166
  container_image() {
152
167
  local image
153
168
  image=$(docker inspect --format '{{.Image}}' "$CONTAINER")
@@ -309,6 +324,7 @@ preflight() {
309
324
  local image branch upstream remote merge stash tracked timings status_ms add_ms excluded secrets out
310
325
  local origin_url fetch bare worktree sshcmd ucache manyfiles agent_sync repo_stat repo_owner repo_mode key_state
311
326
  image=$(container_image)
327
+ use_image_agent_name "$image"
312
328
  print_exclude "$image" "$WORK/exclude"
313
329
  chmod 0644 "$WORK/exclude"
314
330
  timings=$(measure_git "$image" "$WORK/exclude")
@@ -910,9 +926,11 @@ butler_sync() { docker exec -u 10001 "$CONTAINER" timeout 60 node "$CLI_ENTRY" s
910
926
 
911
927
  verify_live() {
912
928
  [ -e "$MARKER" ] || die "the cutover is not done ($MARKER is missing)"
913
- local heads uid start elapsed status out leftover
929
+ local heads uid start elapsed status out leftover image
914
930
  trap 'trap "" INT TERM HUP; exit 130' INT TERM
915
931
  trap 'trap "" INT TERM HUP; exit 129' HUP
932
+ image=$(container_image)
933
+ use_image_agent_name "$image"
916
934
 
917
935
  say "the sync path reaches GitHub as ouro-sync"
918
936
  heads=$(docker exec -u 10001 -e "GIT_SSH_COMMAND=sudo -n -u ouro-sync $SYNC_SSH_WRAPPER" -e GIT_SSH_VARIANT=ssh "$CONTAINER" \
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1635",
2
+ "runtimeVersion": "0.1.0-alpha.1636",
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.1635</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1636</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BUTLER_AGENT_NAMES = void 0;
4
4
  exports.isButlerAgent = isButlerAgent;
5
5
  exports.butlerContainerPaths = butlerContainerPaths;
6
+ exports.butlerNameFromEntrypoint = butlerNameFromEntrypoint;
6
7
  exports.managedButlerAgent = managedButlerAgent;
7
8
  exports.butlerOnDisk = butlerOnDisk;
8
9
  /**
@@ -20,6 +21,7 @@ function butlerContainerPaths(name) {
20
21
  const healthJobId = `${name}:sanctuary-health`;
21
22
  return {
22
23
  agentRoot,
24
+ trustRoot: `/etc/ouro/trust/${name}`,
23
25
  crontabPath: `/home/ouro/.ouro-cli/scheduler/${name}.crontab`,
24
26
  habitNamespace,
25
27
  healthJobId,
@@ -28,6 +30,18 @@ function butlerContainerPaths(name) {
28
30
  healthCronMarker: `# ouro:${habitNamespace}:${healthJobId}`,
29
31
  };
30
32
  }
33
+ /**
34
+ * The Butler an image runs, from its ENTRYPOINT (`docker image inspect --format '{{json .Config.Entrypoint}}'`): the argument
35
+ * after `--package-managed-agent` when it is a Butler name. Anything else, including an image with no package activation,
36
+ * means `sanctuary`, the name every image had before the rename. The host mounts the bundle and trust where this name says.
37
+ */
38
+ function butlerNameFromEntrypoint(entrypoint) {
39
+ if (!Array.isArray(entrypoint))
40
+ return "sanctuary";
41
+ const flag = entrypoint.indexOf("--package-managed-agent");
42
+ const name = flag >= 0 ? entrypoint[flag + 1] : undefined;
43
+ return isButlerAgent(name) ? name : "sanctuary";
44
+ }
31
45
  /** The one Butler among the agents this daemon manages, or null when there is none or more than one. */
32
46
  function managedButlerAgent(managedAgents) {
33
47
  const butlers = managedAgents.filter(isButlerAgent);
@@ -4,50 +4,57 @@ exports.auditSanctuaryContainerSpec = auditSanctuaryContainerSpec;
4
4
  exports.auditSanctuaryStagedFiles = auditSanctuaryStagedFiles;
5
5
  exports.auditSanctuaryPersistentTemplate = auditSanctuaryPersistentTemplate;
6
6
  const runtime_1 = require("../../nerves/runtime");
7
+ const butler_agent_1 = require("../butler-agent");
7
8
  const { parseDockerManTemplateXml } = require("../../../deploy/unraid/docker-man-template-xml.cjs");
8
- const EXPECTED_BINDS = [
9
- "/mnt/user/appdata/ouro-butler/runtime/.ouro-cli:/home/ouro/.ouro-cli:rw",
10
- "/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro:/home/ouro/AgentBundles/sanctuary.ouro:rw",
11
- "/boot/config/custom/ouro-events/spool:/run/ouro-events:ro",
12
- "/run/ouro-authority:/run/ouro-authority:ro",
13
- // The psyche folder read-only over the bundle. Releases up to alpha.978 create it, and a rollback to one recreates it,
14
- // so canonical-gateway accepts these binds with or without this row (GATEWAY_*_WITHOUT_PSYCHE).
15
- "/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro/psyche:/home/ouro/AgentBundles/sanctuary.ouro/psyche:ro",
16
- // Operator-set grants, root-owned on the host and read-only inside the Butler (the Butler honours a grant only from here).
17
- "/mnt/user/appdata/ouro-butler/trust/sanctuary:/etc/ouro/trust/sanctuary:ro",
18
- // The bundle sync deploy key, root-owned on the host and read-only inside the Butler. The key can push to the owner's repo.
19
- "/mnt/user/appdata/ouro-butler/sync:/run/ouro-sync:ro",
20
- ];
21
- const EXPECTED_MOUNTS = [
22
- ["/mnt/user/appdata/ouro-butler/runtime/.ouro-cli", "/home/ouro/.ouro-cli", true, "rprivate"],
23
- ["/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro", "/home/ouro/AgentBundles/sanctuary.ouro", true, "rprivate"],
24
- ["/boot/config/custom/ouro-events/spool", "/run/ouro-events", false, "rprivate"],
25
- ["/run/ouro-authority", "/run/ouro-authority", false, "rprivate"],
26
- ["/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro/psyche", "/home/ouro/AgentBundles/sanctuary.ouro/psyche", false, "rprivate"],
27
- ["/mnt/user/appdata/ouro-butler/trust/sanctuary", "/etc/ouro/trust/sanctuary", false, "rprivate"],
28
- ["/mnt/user/appdata/ouro-butler/sync", "/run/ouro-sync", false, "rprivate"],
29
- ];
30
- const PSYCHE_TARGET = "/home/ouro/AgentBundles/sanctuary.ouro/psyche";
31
- /** The current resident shape: the canonical-gateway set without the separate read-only psyche mount. */
32
- const GATEWAY_BINDS_WITHOUT_PSYCHE = EXPECTED_BINDS.filter((bind) => !bind.includes(`:${PSYCHE_TARGET}:`));
33
- const GATEWAY_MOUNTS_WITHOUT_PSYCHE = EXPECTED_MOUNTS.filter((mount) => mount[1] !== PSYCHE_TARGET);
9
+ // The host folders never change with the Butler's name: the bundle stays in sanctuary.ouro on the live host. Only where the
10
+ // bundle, its psyche and the operator trust are mounted inside the container follows the name the image runs.
11
+ function expectedBinds(name) {
12
+ return [
13
+ "/mnt/user/appdata/ouro-butler/runtime/.ouro-cli:/home/ouro/.ouro-cli:rw",
14
+ `/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro:/home/ouro/AgentBundles/${name}.ouro:rw`,
15
+ "/boot/config/custom/ouro-events/spool:/run/ouro-events:ro",
16
+ "/run/ouro-authority:/run/ouro-authority:ro",
17
+ // The psyche folder read-only over the bundle. Releases up to alpha.978 create it, and a rollback to one recreates it,
18
+ // so canonical-gateway accepts these binds with or without this row (gatewayBinds).
19
+ `/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro/psyche:/home/ouro/AgentBundles/${name}.ouro/psyche:ro`,
20
+ // Operator-set grants, root-owned on the host and read-only inside the Butler (the Butler honours a grant only from here).
21
+ `/mnt/user/appdata/ouro-butler/trust/sanctuary:/etc/ouro/trust/${name}:ro`,
22
+ // The bundle sync deploy key, root-owned on the host and read-only inside the Butler. The key can push to the owner's repo.
23
+ "/mnt/user/appdata/ouro-butler/sync:/run/ouro-sync:ro",
24
+ ];
25
+ }
26
+ function expectedMounts(name) {
27
+ return [
28
+ ["/mnt/user/appdata/ouro-butler/runtime/.ouro-cli", "/home/ouro/.ouro-cli", true, "rprivate"],
29
+ ["/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro", `/home/ouro/AgentBundles/${name}.ouro`, true, "rprivate"],
30
+ ["/boot/config/custom/ouro-events/spool", "/run/ouro-events", false, "rprivate"],
31
+ ["/run/ouro-authority", "/run/ouro-authority", false, "rprivate"],
32
+ ["/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro/psyche", `/home/ouro/AgentBundles/${name}.ouro/psyche`, false, "rprivate"],
33
+ ["/mnt/user/appdata/ouro-butler/trust/sanctuary", `/etc/ouro/trust/${name}`, false, "rprivate"],
34
+ ["/mnt/user/appdata/ouro-butler/sync", "/run/ouro-sync", false, "rprivate"],
35
+ ];
36
+ }
37
+ const psycheTarget = (name) => `/home/ouro/AgentBundles/${name}.ouro/psyche`;
34
38
  const SYNC_TARGET = "/run/ouro-sync";
35
39
  /**
36
- * The canonical-gateway shapes. With sync on, the key mount is required. With sync off (the live Butler until the
37
- * cutover, and a rollback to a release without the mount) each shape is accepted with or without it.
40
+ * The canonical-gateway shapes for one Butler name: with and without the separate read-only psyche mount. With sync on,
41
+ * the key mount is required. With sync off (the live Butler until the cutover, and a rollback to a release without the
42
+ * mount) each shape is accepted with or without it.
38
43
  */
39
- function gatewayBinds(syncEnabled) {
40
- const shapes = [EXPECTED_BINDS, GATEWAY_BINDS_WITHOUT_PSYCHE];
44
+ function gatewayBinds(syncEnabled, name) {
45
+ const all = expectedBinds(name);
46
+ const shapes = [all, all.filter((bind) => !bind.includes(`:${psycheTarget(name)}:`))];
41
47
  return syncEnabled ? shapes : [...shapes, ...shapes.map((binds) => binds.filter((bind) => !bind.includes(`:${SYNC_TARGET}:`)))];
42
48
  }
43
- function gatewayMounts(syncEnabled) {
44
- const shapes = [EXPECTED_MOUNTS, GATEWAY_MOUNTS_WITHOUT_PSYCHE];
49
+ function gatewayMounts(syncEnabled, name) {
50
+ const all = expectedMounts(name);
51
+ const shapes = [all, all.filter((mount) => mount[1] !== psycheTarget(name))];
45
52
  return syncEnabled ? shapes : [...shapes, ...shapes.map((mounts) => mounts.filter((mount) => mount[1] !== SYNC_TARGET))];
46
53
  }
47
- const PRE_GATEWAY_BINDS = EXPECTED_BINDS.slice(0, 3);
48
- const PRE_GATEWAY_MOUNTS = EXPECTED_MOUNTS.slice(0, 3);
54
+ const preGatewayBinds = (name) => expectedBinds(name).slice(0, 3);
55
+ const preGatewayMounts = (name) => expectedMounts(name).slice(0, 3);
49
56
  const LEGACY_ALPHA742_IMAGE = "sha256:681449ad47a2621705cd339b481e6339236b31dc65e195b1cf5025d0f2191d7d";
50
- const LEGACY_ALPHA742_MOUNTS = EXPECTED_MOUNTS.slice(0, 2);
57
+ const LEGACY_ALPHA742_MOUNTS = expectedMounts("sanctuary").slice(0, 2);
51
58
  const EXPECTED_EXTRA_PARAMS = "--restart=unless-stopped --user=10001:10001";
52
59
  const EXPECTED_NAME = "ouro-butler";
53
60
  // The release's own template, then main's copy, which templates carried before releases moved off pull requests.
@@ -59,7 +66,7 @@ const EXPECTED_ICON = "https://raw.githubusercontent.com/ourostack/ouroboros/mai
59
66
  const EXACT_IMAGE = /^sha256:[a-f0-9]{64}$/u;
60
67
  const VERSION_REFERENCE = /^ghcr\.io\/ourostack\/ouroboros-butler:[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/u;
61
68
  // The image names the Butler `butler` from M2 on; images from before the rename name it `sanctuary`. Either runs its one bundle.
62
- const PACKAGE_DAEMON_ARGS_BY_NAME = ["butler", "sanctuary"].map((name) => ["/opt/ouro/dist/heart/daemon/daemon-entry.js", "--package-managed-agent", name]);
69
+ const packageDaemonArgs = (name) => ["/opt/ouro/dist/heart/daemon/daemon-entry.js", "--package-managed-agent", name];
63
70
  const LEGACY_DAEMON_ARGS = ["/opt/ouro/dist/heart/daemon/daemon-entry.js"];
64
71
  const LEGACY_ENTRYPOINT = ["node", ...LEGACY_DAEMON_ARGS];
65
72
  function record(value) {
@@ -91,8 +98,10 @@ function auditSanctuaryContainerSpec(value, options) {
91
98
  violations.push("unsupported mount contract");
92
99
  if (mountContract === "legacy-alpha742" && options.expectedImage !== LEGACY_ALPHA742_IMAGE)
93
100
  violations.push("legacy mount exception requires the pinned alpha.742 image ID");
94
- const acceptedMounts = mountContract === "legacy-alpha742" ? [LEGACY_ALPHA742_MOUNTS] : mountContract === "canonical-pre-gateway" ? [PRE_GATEWAY_MOUNTS] : gatewayMounts(options.syncEnabled === true);
95
- const packageArgs = PACKAGE_DAEMON_ARGS_BY_NAME.find((args) => JSON.stringify(root.Args) === JSON.stringify(args)) ?? PACKAGE_DAEMON_ARGS_BY_NAME[1];
101
+ // The Butler name the container runs, from its own arguments: its bundle, psyche and trust must be mounted under that name.
102
+ const name = butler_agent_1.BUTLER_AGENT_NAMES.find((candidate) => JSON.stringify(root.Args) === JSON.stringify(packageDaemonArgs(candidate))) ?? "sanctuary";
103
+ const packageArgs = packageDaemonArgs(name);
104
+ const acceptedMounts = mountContract === "legacy-alpha742" ? [LEGACY_ALPHA742_MOUNTS] : mountContract === "canonical-pre-gateway" ? [preGatewayMounts(name)] : gatewayMounts(options.syncEnabled === true, name);
96
105
  const expectedArgs = mountContract !== "legacy-alpha742" ? packageArgs : LEGACY_DAEMON_ARGS;
97
106
  const expectedEntrypoint = mountContract !== "legacy-alpha742" ? ["node", ...packageArgs] : LEGACY_ENTRYPOINT;
98
107
  if (root.Image !== options.expectedImage)
@@ -201,7 +210,8 @@ function auditTemplate(input, expectedRepository, repositoryIsValid, repositoryV
201
210
  const violations = [];
202
211
  if (input.mountContract !== "canonical-pre-gateway" && input.mountContract !== "canonical-gateway")
203
212
  violations.push("unsupported template mount contract");
204
- const acceptedBinds = input.mountContract === "canonical-pre-gateway" ? [PRE_GATEWAY_BINDS] : gatewayBinds(input.syncEnabled === true);
213
+ // A template names no image arguments, so its binds may use either Butler name, but all under the same one.
214
+ const acceptedBinds = butler_agent_1.BUTLER_AGENT_NAMES.flatMap((name) => input.mountContract === "canonical-pre-gateway" ? [preGatewayBinds(name)] : gatewayBinds(input.syncEnabled === true, name));
205
215
  const template = parseDockerManTemplateXml(input.templateXml);
206
216
  if (!template)
207
217
  violations.push("canonical DockerMan XML structure is invalid");
@@ -53,12 +53,15 @@ const sanctuary_authority_vault_migration_1 = require("./sanctuary-authority-vau
53
53
  const session_transaction_1 = require("../../mind/session-transaction");
54
54
  const runtime_1 = require("../../nerves/runtime");
55
55
  const failure_code_1 = require("./cli-commands/failure-code");
56
+ const butler_agent_1 = require("../butler-agent");
56
57
  const ROOT = "/mnt/user/appdata/ouro-authority";
57
- const BUNDLE = "/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro";
58
+ // The host folder that holds the Butler's bundle. The bundle in it keeps the name it has on disk (the live host's stays
59
+ // sanctuary.ouro through the rename); only where it is mounted inside the container follows the image's name.
60
+ const AGENT = "/mnt/user/appdata/ouro-butler/agent";
58
61
  const RUNTIME = "/mnt/user/appdata/ouro-butler/runtime/.ouro-cli";
59
- const OFFSET = `${BUNDLE}/state/senses/telegram/offset.json`;
62
+ const OFFSET = "state/senses/telegram/offset.json";
60
63
  const SOCKET = "/run/ouro-authority";
61
- // Operator-set grants, root-owned on the host and mounted read-only into the Butler at /etc/ouro/trust/sanctuary.
64
+ // Operator-set grants, root-owned on the host and mounted read-only into the Butler at /etc/ouro/trust/<the image's Butler name>.
62
65
  const TRUST = "/mnt/user/appdata/ouro-butler/trust/sanctuary";
63
66
  // The bundle sync deploy key's host folder, mounted read-only where the sync wrapper reads it (from alpha.991).
64
67
  const SYNC = "/mnt/user/appdata/ouro-butler/sync";
@@ -91,6 +94,8 @@ const GATEWAY_LOG_TAIL_CHARS = 2_000;
91
94
  // Read more than is shown, so masking sees whole tokens before the tail is cut.
92
95
  const GATEWAY_LOG_READ_BYTES = 4_096;
93
96
  const GATEWAY_LOG_MAX_BYTES = 5 * 1024 * 1024;
97
+ // A container mounting the host bundle under either name could poll Telegram directly.
98
+ const HOST_BUNDLES = butler_agent_1.BUTLER_AGENT_NAMES.map((name) => `${AGENT}/${name}.ouro`);
94
99
  const TEMPLATE_JOURNAL = "/boot/config/custom/ouro-butler/docker-man-template-transaction.json";
95
100
  // In-place upgrade of an installed authority: same epoch (token, issuer, cursor,
96
101
  // gateway state), new reviewed package and resident image. Every root record it
@@ -281,8 +286,8 @@ class SanctuaryAuthorityRootLifecycle {
281
286
  throw new Error("Sanctuary previous epoch handoff is incomplete");
282
287
  }
283
288
  // A missing cursor is not a fresh install: it is lost handoff evidence.
284
- fs.lstatSync(this.#p(OFFSET));
285
- const predecessorCursor = new telegram_client_1.FileTelegramOffsetStore(this.#p(OFFSET)).load();
289
+ fs.lstatSync(this.#p(this.#offset()));
290
+ const predecessorCursor = new telegram_client_1.FileTelegramOffsetStore(this.#p(this.#offset())).load();
286
291
  const snapshot = this.#vault("snapshot");
287
292
  if (["botId", "ownerUserId", "ownerChatId"].some((key) => snapshot[key] !== this.#request[key]))
288
293
  throw new Error("Sanctuary predecessor identity changed");
@@ -762,7 +767,7 @@ class SanctuaryAuthorityRootLifecycle {
762
767
  return false;
763
768
  this.#record(`${this.#epochRoot()}/restored.json`, { tokenDigest: this.#epoch().tokenDigest, cursor: this.#epoch().terminalCursor });
764
769
  const token = this.#vault("snapshot");
765
- return digest(token.token) === this.#epoch().tokenDigest && new telegram_client_1.FileTelegramOffsetStore(this.#p(OFFSET)).load() >= this.#epoch().terminalCursor;
770
+ return digest(token.token) === this.#epoch().tokenDigest && new telegram_client_1.FileTelegramOffsetStore(this.#p(this.#offset())).load() >= this.#epoch().terminalCursor;
766
771
  }
767
772
  #restoreToken() {
768
773
  this.#requireStopped();
@@ -776,12 +781,12 @@ class SanctuaryAuthorityRootLifecycle {
776
781
  if (digest(token) !== epoch.tokenDigest)
777
782
  throw new Error("Sanctuary current token handoff identity changed");
778
783
  this.#vault("restore", { token, botId: epoch.botId, ownerUserId: epoch.ownerUserId, ownerChatId: epoch.ownerChatId });
779
- new telegram_client_1.FileTelegramOffsetStore(this.#p(OFFSET)).save(epoch.terminalCursor);
784
+ new telegram_client_1.FileTelegramOffsetStore(this.#p(this.#offset())).save(epoch.terminalCursor);
780
785
  // Restore the original resident ownership; root must not strand a root-owned cursor.
781
- fs.chownSync(this.#p(OFFSET), this.#uid === 0 ? 10001 : this.#uid, this.#uid === 0 ? 10001 : this.#gid);
786
+ fs.chownSync(this.#p(this.#offset()), this.#uid === 0 ? 10001 : this.#uid, this.#uid === 0 ? 10001 : this.#gid);
782
787
  this.#write(`${this.#epochRoot()}/restored.json`, JSON.stringify({ tokenDigest: epoch.tokenDigest, cursor: epoch.terminalCursor }));
783
788
  const restored = this.#vault("snapshot");
784
- if (digest(restored.token) !== epoch.tokenDigest || new telegram_client_1.FileTelegramOffsetStore(this.#p(OFFSET)).load() !== epoch.terminalCursor)
789
+ if (digest(restored.token) !== epoch.tokenDigest || new telegram_client_1.FileTelegramOffsetStore(this.#p(this.#offset())).load() !== epoch.terminalCursor)
785
790
  throw new Error("Sanctuary token and cursor handoff readback failed");
786
791
  (0, sanctuary_authority_epoch_1.releaseSanctuaryAuthorityToken)(this.#p(this.#epochRoot()), { expectedUid: this.#uid, expectedGid: this.#gid, tokenDigest: epoch.tokenDigest, cursor: epoch.terminalCursor });
787
792
  if (fs.existsSync(this.#p(`${ROOT}/incoming-token`))) {
@@ -1038,14 +1043,19 @@ class SanctuaryAuthorityRootLifecycle {
1038
1043
  * release's audit refuses it.
1039
1044
  */
1040
1045
  #recreateResident(reference, imageId, { psycheMount, syncMount }) {
1046
+ // The image names where its bundle and trust are mounted; the host folders stay where they are. `--mount` refuses a
1047
+ // missing source, where `-v` would have Docker create an empty folder in its place. Both are read before the resident
1048
+ // goes, so a failed inspect leaves it standing.
1049
+ const bundle = this.#hostBundle();
1050
+ const { agentRoot, trustRoot } = (0, butler_agent_1.butlerContainerPaths)(this.#imageButler(imageId));
1041
1051
  if (this.#containers().some((container) => container.Name === "/ouro-butler"))
1042
1052
  this.#docker(["rm", "-f", "ouro-butler"]);
1043
1053
  this.#docker(["create", "--name", "ouro-butler", "--network", "host", "--restart", "unless-stopped", "--user", "10001:10001",
1044
1054
  "-l", "net.unraid.docker.managed=dockerman", "-l", `net.unraid.docker.icon=${ICON}`, "-l", "org.opencontainers.image.source=https://github.com/ourostack/ouroboros",
1045
- "-v", `${RUNTIME}:/home/ouro/.ouro-cli:rw`, "-v", `${BUNDLE}:/home/ouro/AgentBundles/sanctuary.ouro:rw`,
1055
+ "-v", `${RUNTIME}:/home/ouro/.ouro-cli:rw`, "--mount", `type=bind,src=${bundle},dst=${agentRoot}`,
1046
1056
  "-v", `${EVENTS}:/run/ouro-events:ro`, "-v", `${SOCKET}:${SOCKET}:ro`,
1047
- ...(psycheMount ? ["-v", `${BUNDLE}/psyche:/home/ouro/AgentBundles/sanctuary.ouro/psyche:ro`] : []),
1048
- "-v", `${TRUST}:/etc/ouro/trust/sanctuary:ro`,
1057
+ ...(psycheMount ? ["--mount", `type=bind,src=${bundle}/psyche,dst=${agentRoot}/psyche,readonly`] : []),
1058
+ "--mount", `type=bind,src=${TRUST},dst=${trustRoot},readonly`,
1049
1059
  ...(syncMount ? ["-v", `${SYNC}:/run/ouro-sync:ro`] : []), reference]);
1050
1060
  const resident = this.#containers().find((container) => container.Name === "/ouro-butler");
1051
1061
  if (resident?.Image !== imageId || resident.State.Running)
@@ -1054,10 +1064,10 @@ class SanctuaryAuthorityRootLifecycle {
1054
1064
  /** Run the installed package's bundle migration CLI, then return the bundle to the resident. */
1055
1065
  #bundle(operation) {
1056
1066
  (0, node_child_process_1.execFileSync)(this.#p("/usr/local/bin/node"), [this.#p(`${ROOT}/package/deploy/unraid/migrate-sanctuary-bundle.mjs`),
1057
- "--package-root", this.#p(`${ROOT}/package/deploy/unraid/sanctuary.ouro`), "--agent-root", this.#p(BUNDLE), ...operation], {
1067
+ "--package-root", this.#p(`${ROOT}/package/deploy/unraid/sanctuary.ouro`), "--agent-root", this.#p(this.#hostBundle()), ...operation], {
1058
1068
  encoding: "utf8", timeout: 300_000, stdio: ["ignore", "pipe", "pipe"], env: { PATH: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" }, cwd: "/",
1059
1069
  });
1060
- (0, node_child_process_1.execFileSync)("/bin/chown", ["-R", "10001:10001", this.#p(BUNDLE)], { stdio: "ignore" });
1070
+ (0, node_child_process_1.execFileSync)("/bin/chown", ["-R", "10001:10001", this.#p(this.#hostBundle())], { stdio: "ignore" });
1061
1071
  this.#restoreReplayRoot();
1062
1072
  }
1063
1073
  /**
@@ -1072,7 +1082,7 @@ class SanctuaryAuthorityRootLifecycle {
1072
1082
  * `state` itself may be a link too: compare realpaths before any chown or chmod ever runs.
1073
1083
  */
1074
1084
  #stateChild(name) {
1075
- const bundle = this.#p(BUNDLE);
1085
+ const bundle = this.#p(this.#hostBundle());
1076
1086
  const directory = path.join(bundle, "state", name);
1077
1087
  let stat;
1078
1088
  try {
@@ -1139,6 +1149,15 @@ class SanctuaryAuthorityRootLifecycle {
1139
1149
  return !fs.readFileSync(file, "utf8").split("\n").some((line) => /^ouro-butler(?:-rollback|-staging|-legacy-evidence)?(?:\s|$)/u.test(line));
1140
1150
  }
1141
1151
  #p(absolute) { return `${this.#prefix}${absolute}`; }
1152
+ /** The host bundle folder, by the name it has on disk; sanctuary.ouro when neither or both are there. */
1153
+ #hostBundle() {
1154
+ return `${AGENT}/${(0, butler_agent_1.butlerOnDisk)(this.#p(AGENT), fs.existsSync) ?? "sanctuary"}.ouro`;
1155
+ }
1156
+ #offset() { return `${this.#hostBundle()}/${OFFSET}`; }
1157
+ /** The Butler an image runs, from its own ENTRYPOINT. */
1158
+ #imageButler(imageId) {
1159
+ return (0, butler_agent_1.butlerNameFromEntrypoint)(JSON.parse(this.#docker(["image", "inspect", "--format", "{{json .Config.Entrypoint}}", imageId])));
1160
+ }
1142
1161
  #bootScript() {
1143
1162
  const mode = fs.lstatSync(this.#p("/boot/config/go")).mode & 0o7777;
1144
1163
  if (![0o600, 0o644, 0o700, 0o755].includes(mode))
@@ -1233,7 +1252,7 @@ class SanctuaryAuthorityRootLifecycle {
1233
1252
  (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.sanctuary_poller_scan_container_gone", message: "skipped a container that stopped during the direct-poller scan", meta: { name } });
1234
1253
  continue;
1235
1254
  }
1236
- if (containers.some((container) => container.Mounts.some((mount) => mount.Source === BUNDLE || mount.Source === RUNTIME)))
1255
+ if (containers.some((container) => container.Mounts.some((mount) => HOST_BUNDLES.includes(mount.Source) || mount.Source === RUNTIME)))
1237
1256
  throw new Error("Sanctuary has an unowned possible direct poller");
1238
1257
  }
1239
1258
  }
@@ -1268,7 +1287,7 @@ class SanctuaryAuthorityRootLifecycle {
1268
1287
  "--cap-drop=ALL", "--cap-add=DAC_OVERRIDE", "--security-opt=no-new-privileges", "--entrypoint", "/bin/sh",
1269
1288
  "--mount", `type=bind,src=${RUNTIME},dst=/home/ouro/.ouro-cli,readonly`,
1270
1289
  ...bitwarden,
1271
- "--mount", `type=bind,src=${BUNDLE},dst=/home/ouro/AgentBundles/sanctuary.ouro,readonly`,
1290
+ "--mount", `type=bind,src=${this.#hostBundle()},dst=${(0, butler_agent_1.butlerContainerPaths)(this.#imageButler(this.#transaction.targetImageId)).agentRoot},readonly`,
1272
1291
  "--tmpfs", "/home/ouro/.config:rw,nosuid,nodev,noexec,mode=0700",
1273
1292
  "--tmpfs", "/tmp:rw,nosuid,nodev,noexec,mode=0700",
1274
1293
  "--env", `OURO_AUTHORITY_REMOVE_INTERLOCK=${this.#request.epochId}`,
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1635",
3
+ "version": "0.1.0-alpha.1636",
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.1635",
9
+ "version": "0.1.0-alpha.1636",
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.1635",
3
+ "version": "0.1.0-alpha.1636",
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": {