@ouro.bot/cli 0.1.0-alpha.1634 → 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.
@@ -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.1634",
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.1634</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,7 +3,9 @@ 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;
8
+ exports.butlerOnDisk = butlerOnDisk;
7
9
  /**
8
10
  * The Butler's agent names: `butler`, and `sanctuary` from before the rename (M2). Every check that picks Butler behaviour
9
11
  * asks this, so an install runs the same whichever name its bundle has.
@@ -19,6 +21,7 @@ function butlerContainerPaths(name) {
19
21
  const healthJobId = `${name}:sanctuary-health`;
20
22
  return {
21
23
  agentRoot,
24
+ trustRoot: `/etc/ouro/trust/${name}`,
22
25
  crontabPath: `/home/ouro/.ouro-cli/scheduler/${name}.crontab`,
23
26
  habitNamespace,
24
27
  healthJobId,
@@ -27,8 +30,25 @@ function butlerContainerPaths(name) {
27
30
  healthCronMarker: `# ouro:${habitNamespace}:${healthJobId}`,
28
31
  };
29
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
+ }
30
45
  /** The one Butler among the agents this daemon manages, or null when there is none or more than one. */
31
46
  function managedButlerAgent(managedAgents) {
32
47
  const butlers = managedAgents.filter(isButlerAgent);
33
48
  return butlers.length === 1 ? butlers[0] : null;
34
49
  }
50
+ /** The Butler named by the one bundle under `bundlesRoot`; null with both bundles there, or neither. */
51
+ function butlerOnDisk(bundlesRoot, exists) {
52
+ const present = exports.BUTLER_AGENT_NAMES.filter((name) => exists(`${bundlesRoot}/${name}.ouro`));
53
+ return present.length === 1 ? present[0] : null;
54
+ }
@@ -52,17 +52,12 @@ function fail(reason) {
52
52
  process.exitCode = 1;
53
53
  throw Object.assign(new Error(reason), { code: reason === "missing agent" ? "missing-agent" : "unhealthy" });
54
54
  }
55
- /** The Butler's name is the one its bundle on disk has; with both bundles, or neither, there is no Butler to check. */
56
- function butlerOnDisk(bundlesRoot) {
57
- const present = butler_agent_1.BUTLER_AGENT_NAMES.filter((name) => fs.existsSync(path.join(bundlesRoot, `${name}.ouro`)));
58
- return present.length === 1 ? present[0] : undefined;
59
- }
60
55
  function runContainerHealthcheck(options = {}) {
61
56
  const argv = options.argv ?? process.argv;
62
57
  const now = options.now ?? Date.now;
63
58
  const index = argv.indexOf("--agent");
64
59
  const given = index >= 0 ? argv[index + 1] : undefined;
65
- const agent = (0, butler_agent_1.isButlerAgent)(given) ? butlerOnDisk((0, identity_1.getAgentBundlesRoot)()) : given;
60
+ const agent = (0, butler_agent_1.isButlerAgent)(given) ? (0, butler_agent_1.butlerOnDisk)((0, identity_1.getAgentBundlesRoot)(), fs.existsSync) ?? undefined : given;
66
61
  if (!agent)
67
62
  fail("missing agent");
68
63
  const packageManagement = (0, sanctuary_package_management_1.resolveSanctuaryPackageManagementActivation)({ mode: "production", argv, managedAgents: [agent], repoRoot: (0, identity_1.getRepoRoot)(), bundlesRoot: (0, identity_1.getAgentBundlesRoot)(), runtimePackageVersion: (0, bundle_manifest_1.getPackageVersion)() });
@@ -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");
@@ -1783,7 +1783,8 @@ class OuroDaemon {
1783
1783
  try {
1784
1784
  const now = new Date().toISOString();
1785
1785
  if (fs.existsSync(this.privilegedEventSpoolRoot)) {
1786
- this.privilegedEventScanner({ spoolRoot: this.privilegedEventSpoolRoot, eventRoot: this.externalEventRootPath() });
1786
+ const butler = (0, butler_agent_1.managedButlerAgent)(this.processManager.listAgentSnapshots().map((snapshot) => snapshot.name));
1787
+ this.privilegedEventScanner({ spoolRoot: this.privilegedEventSpoolRoot, eventRoot: this.externalEventRootPath(), ...(butler ? { agent: butler } : {}) });
1787
1788
  }
1788
1789
  const scanned = this.externalEventScanCache.scan(this.externalEventRootPath());
1789
1790
  const readinessKeys = new Set();
@@ -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}`,