@ouro.bot/cli 0.1.0-alpha.733 → 0.1.0-alpha.735

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.
Files changed (89) hide show
  1. package/changelog.json +34 -0
  2. package/deploy/unraid/Dockerfile +27 -0
  3. package/deploy/unraid/README.txt +1605 -0
  4. package/deploy/unraid/audit-container-spec.sh +4 -0
  5. package/deploy/unraid/container-runtime.json +1 -0
  6. package/deploy/unraid/sanctuary-acceptance-adapter.sh +37 -0
  7. package/deploy/unraid/sanctuary-acceptance-contract.json +200 -0
  8. package/deploy/unraid/sanctuary-acceptance-harness.sh +23 -0
  9. package/deploy/unraid/sanctuary-deployment-target.mjs +705 -0
  10. package/deploy/unraid/sanctuary-safe-rename.py +24 -0
  11. package/deploy/unraid/sanctuary-unit16-host-broker.mjs +1777 -0
  12. package/deploy/unraid/sanctuary-unit16-run.sh +502 -0
  13. package/deploy/unraid/sanctuary-unit18-target-audit.sh +27 -0
  14. package/deploy/unraid/sanctuary.ouro/agent.json +24 -0
  15. package/deploy/unraid/sanctuary.ouro/arc/README.md +3 -0
  16. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +5 -0
  17. package/deploy/unraid/sanctuary.ouro/habits/sanctuary-health.md +8 -0
  18. package/deploy/unraid/sanctuary.ouro/provider-readiness.json +18 -0
  19. package/deploy/unraid/sanctuary.ouro/psyche/ASPIRATIONS.md +3 -0
  20. package/deploy/unraid/sanctuary.ouro/psyche/IDENTITY.md +3 -0
  21. package/deploy/unraid/sanctuary.ouro/psyche/LORE.md +3 -0
  22. package/deploy/unraid/sanctuary.ouro/psyche/SOUL.md +5 -0
  23. package/deploy/unraid/sanctuary.ouro/psyche/TACIT.md +7 -0
  24. package/deploy/unraid/sanctuary.ouro/tool-profiles.json +21 -0
  25. package/deploy/unraid/sanctuary.xml +25 -0
  26. package/dist/heart/approval-files.js +113 -0
  27. package/dist/heart/approval-store.js +168 -9
  28. package/dist/heart/auth/auth-flow.js +17 -1
  29. package/dist/heart/autonomy-budget.js +44 -1
  30. package/dist/heart/awaiting/await-scheduler.js +6 -2
  31. package/dist/heart/config.js +8 -0
  32. package/dist/heart/core.js +117 -132
  33. package/dist/heart/daemon/cli-exec.js +73 -1
  34. package/dist/heart/daemon/cli-help.js +5 -0
  35. package/dist/heart/daemon/cli-parse.js +6 -4
  36. package/dist/heart/daemon/container-credential-bootstrap.js +208 -0
  37. package/dist/heart/daemon/container-healthcheck.js +94 -0
  38. package/dist/heart/daemon/container-runtime.js +84 -0
  39. package/dist/heart/daemon/container-spec-auditor-main.js +156 -0
  40. package/dist/heart/daemon/container-spec-auditor.js +156 -0
  41. package/dist/heart/daemon/daemon-bootstrap-startup.js +41 -0
  42. package/dist/heart/daemon/daemon-entry.js +116 -28
  43. package/dist/heart/daemon/daemon-health.js +10 -0
  44. package/dist/heart/daemon/daemon.js +92 -5
  45. package/dist/heart/daemon/runtime-logging.js +6 -0
  46. package/dist/heart/daemon/runtime-mode.js +13 -2
  47. package/dist/heart/daemon/sanctuary-acceptance-adapter.js +2365 -0
  48. package/dist/heart/daemon/sanctuary-acceptance-harness.js +1624 -0
  49. package/dist/heart/daemon/sanctuary-acceptance-marker.js +267 -0
  50. package/dist/heart/daemon/sanctuary-acceptance-scenarios.js +985 -0
  51. package/dist/heart/daemon/sanctuary-scheduler-liveness.js +227 -0
  52. package/dist/heart/daemon/sanctuary-scheduler-origin.js +126 -0
  53. package/dist/heart/daemon/sense-manager.js +25 -6
  54. package/dist/heart/daemon/supercronic-supervisor.js +267 -0
  55. package/dist/heart/habits/habit-scheduler.js +7 -3
  56. package/dist/heart/identity.js +13 -3
  57. package/dist/heart/provider-credentials.js +9 -1
  58. package/dist/heart/provider-models.js +8 -0
  59. package/dist/heart/provider-ping.js +5 -2
  60. package/dist/heart/providers/openai-compatible.js +177 -0
  61. package/dist/heart/runtime-credentials.js +217 -8
  62. package/dist/heart/sense-truth.js +2 -0
  63. package/dist/heart/tool-approval.js +1 -0
  64. package/dist/heart/turn-context.js +8 -0
  65. package/dist/mind/prompt.js +9 -0
  66. package/dist/nerves/coverage/source-scanner.js +4 -4
  67. package/dist/nerves/index.js +75 -9
  68. package/dist/nerves/runtime.js +12 -0
  69. package/dist/repertoire/tool-arguments.js +39 -0
  70. package/dist/repertoire/tools-unraid.js +353 -0
  71. package/dist/repertoire/tools.js +19 -1
  72. package/dist/repertoire/unraid-client.js +155 -0
  73. package/dist/repertoire/unraid-restart.js +130 -0
  74. package/dist/senses/private-runtime-worker.js +3 -2
  75. package/dist/senses/sanctuary-grounding.js +118 -0
  76. package/dist/senses/sanctuary-health-acceptance-probe-entry.js +12 -0
  77. package/dist/senses/sanctuary-health-acceptance-probe.js +772 -0
  78. package/dist/senses/sanctuary-health-runner.js +146 -0
  79. package/dist/senses/sanctuary-health.js +447 -0
  80. package/dist/senses/sanctuary-interactive-control.js +306 -0
  81. package/dist/senses/sanctuary-runtime.js +206 -0
  82. package/dist/senses/shared-turn.js +11 -3
  83. package/dist/senses/telegram-approval-runtime.js +526 -0
  84. package/dist/senses/telegram-audit-ledger.js +220 -0
  85. package/dist/senses/telegram-client.js +1471 -0
  86. package/dist/senses/telegram-entry.js +80 -0
  87. package/dist/senses/telegram.js +1232 -0
  88. package/npm-shrinkwrap.json +6558 -0
  89. package/package.json +4 -2
@@ -0,0 +1,1605 @@
1
+ Mendelow Cloud Butler operator runbook
2
+
3
+ The production container is ouro-butler. It runs as UID/GID 10001, publishes no
4
+ ports, uses host networking only so its loopback-only Unraid GraphQL client can
5
+ reach 127.0.0.1, mounts only the runtime and sanctuary.ouro bundle paths from
6
+ the Unraid template, and uses restart policy unless-stopped.
7
+
8
+ Start/stop:
9
+ docker start ouro-butler
10
+ docker stop ouro-butler
11
+
12
+ Status and health:
13
+ docker inspect --format '{{.State.Status}} {{.State.Health.Status}}' ouro-butler
14
+ docker logs --tail 200 ouro-butler
15
+
16
+ Effective-spec audit helper:
17
+ Run Update and Restore command sequences from a root shell with `set -eu`.
18
+ Before either sequence, define this helper. It captures one actual container
19
+ inspect and its reviewed image inspect without printing either, invokes the
20
+ packaged auditor from IMAGE_ID, and removes its mode-0600 inputs on success
21
+ or shell exit:
22
+ audit_effective() {
23
+ (
24
+ AUDIT_CONTAINER=$1
25
+ AUDIT_EXPECTED_IMAGE=$2
26
+ INSPECT_DIR=$(mktemp -d /mnt/user/appdata/ouro-butler/staging/inspect.XXXXXX) || return $?
27
+ trap 'rm -f -- "$INSPECT_DIR/container.json" "$INSPECT_DIR/image.json"; rmdir -- "$INSPECT_DIR"' EXIT || return $?
28
+ chmod 0700 "$INSPECT_DIR" || return $?
29
+ umask 077 || return $?
30
+ docker inspect "$AUDIT_CONTAINER" >"$INSPECT_DIR/container.json" || return $?
31
+ docker image inspect "$AUDIT_EXPECTED_IMAGE" >"$INSPECT_DIR/image.json" || return $?
32
+ chmod 0600 "$INSPECT_DIR/container.json" "$INSPECT_DIR/image.json" || return $?
33
+ docker run --rm --pull=never --network=none \
34
+ --entrypoint /opt/ouro/deploy/unraid/audit-container-spec.sh \
35
+ --mount "type=bind,src=$INSPECT_DIR/container.json,dst=/audit/container.json,readonly" \
36
+ --mount "type=bind,src=$INSPECT_DIR/image.json,dst=/audit/image.json,readonly" \
37
+ "$IMAGE_ID" --inspect /audit/container.json --image-inspect /audit/image.json --expected-image "$AUDIT_EXPECTED_IMAGE" || return $?
38
+ rm -f -- "$INSPECT_DIR/container.json" "$INSPECT_DIR/image.json" || return $?
39
+ rmdir -- "$INSPECT_DIR" || return $?
40
+ trap - EXIT || return $?
41
+ )
42
+ }
43
+ Define these helpers in the same root shell. Each autostart change uses
44
+ Unraid's authenticated loopback WebGUI endpoint with the live root-session
45
+ CSRF token supplied only on request stdin. Requests have hard connection and
46
+ total timeouts, discard response bodies, and read back the durable array
47
+ autostart state without writing its backing file directly:
48
+ set_butler_autostart() {
49
+ (
50
+ AUTOSTART_CONTAINER=$1
51
+ AUTOSTART_ENABLED=$2
52
+ case "$AUTOSTART_CONTAINER" in
53
+ ouro-butler|ouro-butler-staging|ouro-butler-rollback|ouro-butler-legacy-evidence) ;;
54
+ *) return 1 ;;
55
+ esac
56
+ case "$AUTOSTART_ENABLED" in true|false) ;; *) return 1 ;; esac
57
+ AUTOSTART_CSRF_FILE=/var/local/emhttp/var.ini
58
+ test -f "$AUTOSTART_CSRF_FILE" || return $?
59
+ AUTOSTART_CSRF_TOKEN=$(awk -F= '$1 == "csrf_token" {
60
+ value = $2
61
+ sub(/^"/, "", value)
62
+ sub(/"$/, "", value)
63
+ print value
64
+ }' "$AUTOSTART_CSRF_FILE") || return $?
65
+ test -n "$AUTOSTART_CSRF_TOKEN" || return $?
66
+ case "$AUTOSTART_CSRF_TOKEN" in *[!A-Za-z0-9._-]*) return 1 ;; esac
67
+ printf '%s' "action=autostart&container=$AUTOSTART_CONTAINER&auto=$AUTOSTART_ENABLED&wait=0&csrf_token=$AUTOSTART_CSRF_TOKEN" | \
68
+ curl --silent --show-error --fail --request POST \
69
+ --connect-timeout 5 --max-time 15 \
70
+ --header 'Content-Type: application/x-www-form-urlencoded' \
71
+ --data-binary @- --output /dev/null \
72
+ http://127.0.0.1/plugins/dynamix.docker.manager/include/UpdateConfig.php || return $?
73
+ )
74
+ }
75
+ verify_butler_autostart() {
76
+ (
77
+ EXPECTED_AUTOSTART_COUNTS=$1
78
+ AUTOSTART_FILE=/var/lib/docker/unraid-autostart
79
+ test -f "$AUTOSTART_FILE" || return $?
80
+ AUTOSTART_COUNTS=$(awk '
81
+ $1 == "ouro-butler" { production++ }
82
+ $1 == "ouro-butler-staging" { staging++ }
83
+ $1 == "ouro-butler-rollback" { rollback++ }
84
+ $1 == "ouro-butler-legacy-evidence" { legacy++ }
85
+ END { printf "%d %d %d %d", production + 0, staging + 0, rollback + 0, legacy + 0 }
86
+ ' "$AUTOSTART_FILE") || return $?
87
+ test "$AUTOSTART_COUNTS" = "$EXPECTED_AUTOSTART_COUNTS" || return $?
88
+ )
89
+ }
90
+ disable_butler_autostart() {
91
+ set_butler_autostart ouro-butler-staging false || return $?
92
+ set_butler_autostart ouro-butler-rollback false || return $?
93
+ set_butler_autostart ouro-butler-legacy-evidence false || return $?
94
+ set_butler_autostart ouro-butler false || return $?
95
+ verify_butler_autostart "0 0 0 0" || return $?
96
+ }
97
+ enable_butler_autostart() {
98
+ set_butler_autostart ouro-butler-staging false || return $?
99
+ set_butler_autostart ouro-butler-rollback false || return $?
100
+ set_butler_autostart ouro-butler-legacy-evidence false || return $?
101
+ set_butler_autostart ouro-butler true || return $?
102
+ verify_butler_autostart "1 0 0 0" || return $?
103
+ }
104
+ This bounded wait accepts only Docker's healthy state. The image healthcheck
105
+ verifies fresh daemon state plus exactly one managed Telegram process and one
106
+ managed scheduler process. It fails immediately on an exited, dead, or
107
+ unhealthy container and times out after four minutes:
108
+ wait_butler_ready() {
109
+ WAIT_CONTAINER=$1
110
+ WAIT_NOW=$(date +%s) || return $?
111
+ WAIT_DEADLINE=$(( WAIT_NOW + 240 ))
112
+ while :; do
113
+ WAIT_NOW=$(date +%s) || return $?
114
+ test "$WAIT_NOW" -lt "$WAIT_DEADLINE" || break
115
+ WAIT_STATE=$(docker inspect --format '{{.State.Status}} {{.State.Health.Status}}' "$WAIT_CONTAINER") || return $?
116
+ if test "$WAIT_STATE" = "running healthy"; then
117
+ return 0
118
+ fi
119
+ case "$WAIT_STATE" in
120
+ exited\ *|dead\ *|*\ unhealthy) return 1 ;;
121
+ esac
122
+ sleep 5 || return $?
123
+ done
124
+ return 1
125
+ }
126
+ Define these fail-closed image and topology helpers in the same shell. They use
127
+ exact Docker image IDs and exact container names; no mutation is performed:
128
+ validate_exact_image_id() {
129
+ VALIDATE_IMAGE_ID=$1
130
+ case "$VALIDATE_IMAGE_ID" in
131
+ sha256:*) VALIDATE_IMAGE_HEX=${VALIDATE_IMAGE_ID#sha256:} ;;
132
+ *) return 1 ;;
133
+ esac
134
+ test "${#VALIDATE_IMAGE_HEX}" -eq 64 || return $?
135
+ case "$VALIDATE_IMAGE_HEX" in
136
+ *[!0-9a-f]*) return 1 ;;
137
+ esac
138
+ docker image inspect "$VALIDATE_IMAGE_ID" >/dev/null || return $?
139
+ }
140
+ assert_only_running_butler() {
141
+ EXPECTED_RUNNING_BUTLER=$1
142
+ RUNNING_BUTLER_NAMES=$(docker container ls --format '{{.Names}}') || return $?
143
+ RUNNING_BUTLER_COUNTS=$(printf '%s\n' "$RUNNING_BUTLER_NAMES" | awk -v expected="$EXPECTED_RUNNING_BUTLER" '
144
+ {
145
+ if ($0 == "ouro-butler" || $0 == "ouro-butler-staging" || $0 == "ouro-butler-rollback" || $0 == "ouro-butler-legacy-evidence") {
146
+ butlers++
147
+ if ($0 == expected) matching++
148
+ }
149
+ }
150
+ END { printf "%d %d", butlers + 0, matching + 0 }
151
+ ') || return $?
152
+ test "$RUNNING_BUTLER_COUNTS" = "1 1" || return $?
153
+ }
154
+ assert_update_topology() {
155
+ EXPECTED_ROLLBACK_IMAGE_ID=$1
156
+ UPDATE_CONTAINER_NAMES=$(docker container ls -a --format '{{.Names}}') || return $?
157
+ UPDATE_NAME_COUNTS=$(printf '%s\n' "$UPDATE_CONTAINER_NAMES" | awk '
158
+ $0 == "ouro-butler" { production++ }
159
+ $0 == "ouro-butler-staging" { staging++ }
160
+ $0 == "ouro-butler-rollback" { rollback++ }
161
+ $0 == "ouro-butler-legacy-evidence" { legacy++ }
162
+ END {
163
+ printf "%d %d %d %d", production + 0, staging + 0, rollback + 0, legacy + 0
164
+ }
165
+ ') || return $?
166
+ case "$UPDATE_NAME_COUNTS" in
167
+ "1 0 0 0"|"1 0 1 0"|"1 0 0 1"|"1 0 1 1") ;;
168
+ *) return 1 ;;
169
+ esac
170
+ UPDATE_PRODUCTION_RUNNING=$(docker inspect --format '{{.State.Running}}' ouro-butler) || return $?
171
+ test "$UPDATE_PRODUCTION_RUNNING" = true || return $?
172
+ UPDATE_PRODUCTION_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler) || return $?
173
+ test "$UPDATE_PRODUCTION_IMAGE_ID" = "$EXPECTED_ROLLBACK_IMAGE_ID" || return $?
174
+ case "$UPDATE_NAME_COUNTS" in
175
+ "1 0 1 0"|"1 0 1 1")
176
+ UPDATE_ROLLBACK_RUNNING=$(docker inspect --format '{{.State.Running}}' ouro-butler-rollback) || return $?
177
+ test "$UPDATE_ROLLBACK_RUNNING" = false || return $?
178
+ UPDATE_ROLLBACK_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-rollback) || return $?
179
+ test "$UPDATE_ROLLBACK_IMAGE_ID" = "$EXPECTED_ROLLBACK_IMAGE_ID" || return $?
180
+ ;;
181
+ esac
182
+ case "$UPDATE_NAME_COUNTS" in
183
+ "1 0 0 1"|"1 0 1 1")
184
+ UPDATE_LEGACY_RUNNING=$(docker inspect --format '{{.State.Running}}' ouro-butler-legacy-evidence) || return $?
185
+ test "$UPDATE_LEGACY_RUNNING" = false || return $?
186
+ UPDATE_LEGACY_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-legacy-evidence) || return $?
187
+ validate_exact_image_id "$UPDATE_LEGACY_IMAGE_ID" || return $?
188
+ ;;
189
+ esac
190
+ assert_only_running_butler ouro-butler || return $?
191
+ }
192
+ validate_sanctuary_roots() {
193
+ (
194
+ VALIDATE_RUNTIME_ROOT=$1
195
+ VALIDATE_AGENT_ROOT=$2
196
+ test -d "$VALIDATE_RUNTIME_ROOT" || return $?
197
+ test -d "$VALIDATE_AGENT_ROOT" || return $?
198
+ VALIDATE_BAD_SHAPE=$(find "$VALIDATE_RUNTIME_ROOT" "$VALIDATE_AGENT_ROOT" -xdev \( -type l -o \( ! -type d -a ! -type f \) \) -print -quit) || return $?
199
+ test -z "$VALIDATE_BAD_SHAPE" || return $?
200
+ for VALIDATE_REQUIRED_FILE in \
201
+ agent.json bundle-meta.json provider-readiness.json tool-profiles.json \
202
+ psyche/SOUL.md habits/sanctuary-health.md; do
203
+ test -s "$VALIDATE_AGENT_ROOT/$VALIDATE_REQUIRED_FILE" || return $?
204
+ done
205
+ test -d "$VALIDATE_RUNTIME_ROOT/vault-unlock" || return $?
206
+ VALIDATE_UNLOCK_FILES=$(find "$VALIDATE_RUNTIME_ROOT/vault-unlock" -xdev -mindepth 1 -maxdepth 1 -type f -name '*.secret' -size +0c -print) || return $?
207
+ test "$(printf '%s\n' "$VALIDATE_UNLOCK_FILES" | awk 'NF { count++ } END { print count + 0 }')" = 1 || return $?
208
+ test ! -e "$VALIDATE_RUNTIME_ROOT/container-credentials.json" || return $?
209
+ test ! -e "$VALIDATE_RUNTIME_ROOT/container-credentials.json.consuming" || return $?
210
+ VALIDATE_WRONG_OWNER=$(find "$VALIDATE_RUNTIME_ROOT" "$VALIDATE_AGENT_ROOT" -xdev \( ! -user 10001 -o ! -group 10001 \) -print -quit) || return $?
211
+ test -z "$VALIDATE_WRONG_OWNER" || return $?
212
+ VALIDATE_WRONG_DIR_MODE=$(find "$VALIDATE_RUNTIME_ROOT" "$VALIDATE_AGENT_ROOT" -xdev -type d ! -perm 0700 -print -quit) || return $?
213
+ test -z "$VALIDATE_WRONG_DIR_MODE" || return $?
214
+ VALIDATE_WRONG_FILE_MODE=$(find "$VALIDATE_RUNTIME_ROOT" "$VALIDATE_AGENT_ROOT" -xdev -type f ! -perm 0600 -print -quit) || return $?
215
+ test -z "$VALIDATE_WRONG_FILE_MODE" || return $?
216
+ )
217
+ }
218
+ assert_restore_preflight() {
219
+ (
220
+ test -n "${BACKUP_ROOT-}" || return 1
221
+ test -n "${IMAGE_ID-}" || return 1
222
+ case "$BACKUP_ROOT" in
223
+ /*) ;;
224
+ *) return 1 ;;
225
+ esac
226
+ test "$BACKUP_ROOT" != / || return $?
227
+ RESTORE_BACKUP_ROOT=$(cd -- "$BACKUP_ROOT" && pwd -P) || return $?
228
+ test "$RESTORE_BACKUP_ROOT" = "$BACKUP_ROOT" || return $?
229
+ test -d "$BACKUP_ROOT/runtime/.ouro-cli" || return $?
230
+ test -d "$BACKUP_ROOT/agent/sanctuary.ouro" || return $?
231
+ validate_sanctuary_roots "$BACKUP_ROOT/runtime/.ouro-cli" "$BACKUP_ROOT/agent/sanctuary.ouro" || return $?
232
+ validate_exact_image_id "$IMAGE_ID" || return $?
233
+ RESTORE_CONTAINER_NAMES=$(docker container ls -a --format '{{.Names}}') || return $?
234
+ RESTORE_NAME_COUNTS=$(printf '%s\n' "$RESTORE_CONTAINER_NAMES" | awk '
235
+ $0 == "ouro-butler" { production++ }
236
+ $0 == "ouro-butler-staging" { staging++ }
237
+ $0 == "ouro-butler-rollback" { rollback++ }
238
+ $0 == "ouro-butler-legacy-evidence" { legacy++ }
239
+ END {
240
+ printf "%d %d %d %d", production + 0, staging + 0, rollback + 0, legacy + 0
241
+ }
242
+ ') || return $?
243
+ case "$RESTORE_NAME_COUNTS" in
244
+ "1 0 0 0"|"1 0 0 1") ;;
245
+ *) return 1 ;;
246
+ esac
247
+ RESTORE_PRODUCTION_RUNNING=$(docker inspect --format '{{.State.Running}}' ouro-butler) || return $?
248
+ test "$RESTORE_PRODUCTION_RUNNING" = true || return $?
249
+ RESTORE_PRODUCTION_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler) || return $?
250
+ validate_exact_image_id "$RESTORE_PRODUCTION_IMAGE_ID" || return $?
251
+ if test "$RESTORE_NAME_COUNTS" = "1 0 0 1"; then
252
+ RESTORE_LEGACY_RUNNING=$(docker inspect --format '{{.State.Running}}' ouro-butler-legacy-evidence) || return $?
253
+ test "$RESTORE_LEGACY_RUNNING" = false || return $?
254
+ RESTORE_LEGACY_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-legacy-evidence) || return $?
255
+ validate_exact_image_id "$RESTORE_LEGACY_IMAGE_ID" || return $?
256
+ fi
257
+ assert_only_running_butler ouro-butler || return $?
258
+ )
259
+ }
260
+ ensure_sanctuary_machine_identity() {
261
+ MACHINE_PATH=$1
262
+ test ! -L "$MACHINE_PATH" || return 1
263
+ /usr/local/bin/node -e '
264
+ const fs = require("node:fs");
265
+ const path = process.argv[1];
266
+ const valid = value => value && value.schemaVersion === 1 && value.machineId === "sanctuary"
267
+ && typeof value.createdAt === "string" && typeof value.updatedAt === "string"
268
+ && Array.isArray(value.hostnameAliases);
269
+ if (fs.existsSync(path)) {
270
+ if (!valid(JSON.parse(fs.readFileSync(path, "utf8")))) process.exit(1);
271
+ process.exit(0);
272
+ }
273
+ const now = new Date().toISOString();
274
+ const value = { schemaVersion: 1, machineId: "sanctuary", createdAt: now, updatedAt: now, hostnameAliases: [] };
275
+ const temporary = `${path}.tmp.${process.pid}`;
276
+ fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: "wx" });
277
+ fs.renameSync(temporary, path);
278
+ ' "$MACHINE_PATH" || return $?
279
+ chown 10001:10001 "$MACHINE_PATH" || return $?
280
+ chmod 0600 "$MACHINE_PATH" || return $?
281
+ sync -f "$MACHINE_PATH" || return $?
282
+ }
283
+ prepare_canonical_sanctuary_roots() {
284
+ PREPARE_IMAGE_ID=$1
285
+ validate_exact_image_id "$PREPARE_IMAGE_ID" || return $?
286
+ PREPARE_RUNTIME_ROOT=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli
287
+ PREPARE_AGENT_ROOT=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro
288
+ install -d -m 0700 -o 10001 -g 10001 "$PREPARE_RUNTIME_ROOT" || return $?
289
+ install -d -m 0700 -o 10001 -g 10001 "$PREPARE_AGENT_ROOT" || return $?
290
+ ensure_sanctuary_machine_identity "$PREPARE_RUNTIME_ROOT/machine.json" || return $?
291
+ if test ! -f "$PREPARE_AGENT_ROOT/agent.json"; then
292
+ PREPARE_EXISTING_ENTRY=$(find "$PREPARE_AGENT_ROOT" -mindepth 1 -print -quit) || return $?
293
+ test -z "$PREPARE_EXISTING_ENTRY" || return $?
294
+ ! docker container inspect ouro-butler-bundle-bootstrap >/dev/null 2>&1 || return 1
295
+ docker run --rm --pull=never --network=none --name ouro-butler-bundle-bootstrap --user 10001:10001 \
296
+ --mount "type=bind,src=$PREPARE_RUNTIME_ROOT,dst=/home/ouro/.ouro-cli" \
297
+ --mount "type=bind,src=$PREPARE_AGENT_ROOT,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
298
+ --entrypoint /bin/sh "$PREPARE_IMAGE_ID" -ceu '
299
+ cp -R /opt/ouro/deploy/unraid/sanctuary.ouro/. /home/ouro/AgentBundles/sanctuary.ouro/
300
+ find /home/ouro/AgentBundles/sanctuary.ouro -type d -exec chmod 0700 {} +
301
+ find /home/ouro/AgentBundles/sanctuary.ouro -type f -exec chmod 0600 {} +
302
+ ' || return $?
303
+ ! docker container inspect ouro-butler-bundle-bootstrap >/dev/null 2>&1 || return 1
304
+ fi
305
+ for PREPARE_REQUIRED_FILE in \
306
+ agent.json bundle-meta.json provider-readiness.json tool-profiles.json \
307
+ psyche/SOUL.md habits/sanctuary-health.md; do
308
+ test -f "$PREPARE_AGENT_ROOT/$PREPARE_REQUIRED_FILE" || return $?
309
+ done
310
+ PREPARE_WRONG_OWNER=$(find "$PREPARE_RUNTIME_ROOT" "$PREPARE_AGENT_ROOT" \( ! -user 10001 -o ! -group 10001 \) -print -quit) || return $?
311
+ test -z "$PREPARE_WRONG_OWNER" || return $?
312
+ PREPARE_WRONG_DIR_MODE=$(find "$PREPARE_RUNTIME_ROOT" "$PREPARE_AGENT_ROOT" -type d ! -perm 0700 -print -quit) || return $?
313
+ test -z "$PREPARE_WRONG_DIR_MODE" || return $?
314
+ PREPARE_WRONG_FILE_MODE=$(find "$PREPARE_RUNTIME_ROOT" "$PREPARE_AGENT_ROOT" -type f ! -perm 0600 -print -quit) || return $?
315
+ test -z "$PREPARE_WRONG_FILE_MODE" || return $?
316
+ }
317
+ validate_sanctuary_legacy_staging() {
318
+ EXPECTED_LEGACY_CONTAINER_ID=${1-}
319
+ EXPECTED_LEGACY_IMAGE_ID=${2-}
320
+ LEGACY_CONTAINER_NAMES=$(docker container ls -a --format '{{.Names}}') || return $?
321
+ LEGACY_NAME_COUNTS=$(printf '%s\n' "$LEGACY_CONTAINER_NAMES" | awk '
322
+ /butler/ { butlers++ }
323
+ $0 == "ouro-butler-staging" { staging++ }
324
+ END { printf "%d %d", butlers + 0, staging + 0 }
325
+ ') || return $?
326
+ test "$LEGACY_NAME_COUNTS" = "1 1" || return $?
327
+ assert_only_running_butler ouro-butler-staging || return $?
328
+ LEGACY_STAGING_RUNNING=$(docker inspect --format '{{.State.Running}}' ouro-butler-staging) || return $?
329
+ test "$LEGACY_STAGING_RUNNING" = true || return $?
330
+ LEGACY_STAGING_CONTAINER_ID=$(docker inspect --format '{{.Id}}' ouro-butler-staging) || return $?
331
+ case "$LEGACY_STAGING_CONTAINER_ID" in *[!0-9a-f]*|'') return 1 ;; esac
332
+ test "${#LEGACY_STAGING_CONTAINER_ID}" -eq 64 || return 1
333
+ LEGACY_STAGING_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-staging) || return $?
334
+ validate_exact_image_id "$LEGACY_STAGING_IMAGE_ID" || return $?
335
+ if test -n "$EXPECTED_LEGACY_CONTAINER_ID"; then
336
+ test "$LEGACY_STAGING_CONTAINER_ID" = "$EXPECTED_LEGACY_CONTAINER_ID" || return 1
337
+ test "$LEGACY_STAGING_IMAGE_ID" = "$EXPECTED_LEGACY_IMAGE_ID" || return 1
338
+ fi
339
+ }
340
+ prepare_sanctuary_legacy_adoption() {
341
+ IMAGE_ID=$1
342
+ validate_exact_image_id "$IMAGE_ID" || return $?
343
+ validate_sanctuary_legacy_staging || return $?
344
+ PREPARED_LEGACY_CONTAINER_ID=$LEGACY_STAGING_CONTAINER_ID
345
+ PREPARED_LEGACY_IMAGE_ID=$LEGACY_STAGING_IMAGE_ID
346
+ prepare_canonical_sanctuary_roots "$IMAGE_ID" || return $?
347
+ bootstrap_sanctuary_vault "$IMAGE_ID" \
348
+ /mnt/user/appdata/ouro-butler/runtime/container-credentials.json \
349
+ sanctuary-unraid sanctuary || return $?
350
+ validate_sanctuary_legacy_staging "$PREPARED_LEGACY_CONTAINER_ID" "$PREPARED_LEGACY_IMAGE_ID" || return $?
351
+ LEGACY_STAGING_CONTAINER_ID=$PREPARED_LEGACY_CONTAINER_ID
352
+ LEGACY_STAGING_IMAGE_ID=$PREPARED_LEGACY_IMAGE_ID
353
+ }
354
+ capture_sanctuary_legacy_evidence() {
355
+ CAPTURED_LEGACY_CONTAINER_ID=$1
356
+ CAPTURED_LEGACY_IMAGE_ID=$2
357
+ LEGACY_EVIDENCE_ROOT=$3
358
+ case "$CAPTURED_LEGACY_CONTAINER_ID" in *[!0-9a-f]*|'') return 1 ;; esac
359
+ test "${#CAPTURED_LEGACY_CONTAINER_ID}" -eq 64 || return 1
360
+ validate_exact_image_id "$CAPTURED_LEGACY_IMAGE_ID" || return $?
361
+ case "$LEGACY_EVIDENCE_ROOT" in /*) ;; *) return 1 ;; esac
362
+ if test -e "$LEGACY_EVIDENCE_ROOT" || test -L "$LEGACY_EVIDENCE_ROOT"; then
363
+ /usr/local/bin/node -e '
364
+ const fs = require("node:fs");
365
+ const root = fs.lstatSync(process.argv[1]);
366
+ if (!root.isDirectory() || root.isSymbolicLink() || (root.mode & 0o777) !== 0o700) process.exit(1);
367
+ if (root.uid !== process.geteuid() || root.gid !== process.getegid()) process.exit(1);
368
+ ' "$LEGACY_EVIDENCE_ROOT" || return $?
369
+ else
370
+ install -d -m 0700 -o 0 -g 0 "$LEGACY_EVIDENCE_ROOT" || return $?
371
+ fi
372
+ LEGACY_EVIDENCE_DIR="$LEGACY_EVIDENCE_ROOT/${CAPTURED_LEGACY_IMAGE_ID#sha256:}"
373
+ if test -e "$LEGACY_EVIDENCE_DIR" || test -L "$LEGACY_EVIDENCE_DIR"; then
374
+ test -d "$LEGACY_EVIDENCE_DIR" && test ! -L "$LEGACY_EVIDENCE_DIR" || return 1
375
+ else
376
+ mkdir -m 0700 "$LEGACY_EVIDENCE_DIR" || return $?
377
+ fi
378
+ /usr/local/bin/node -e '
379
+ const fs = require("node:fs");
380
+ const [rootPath, directoryPath] = process.argv.slice(1);
381
+ const root = fs.lstatSync(rootPath);
382
+ const directory = fs.lstatSync(directoryPath);
383
+ const privateDirectory = value => value.isDirectory() && !value.isSymbolicLink() && (value.mode & 0o777) === 0o700;
384
+ if (!privateDirectory(root) || !privateDirectory(directory)) process.exit(1);
385
+ if (root.uid !== process.geteuid() || root.gid !== process.getegid()) process.exit(1);
386
+ if (root.uid !== directory.uid || root.gid !== directory.gid) process.exit(1);
387
+ const allowed = new Set(["container.json", "image.json"]);
388
+ if (fs.readdirSync(directoryPath).some(name => !allowed.has(name))) process.exit(1);
389
+ ' "$LEGACY_EVIDENCE_ROOT" "$LEGACY_EVIDENCE_DIR" || return $?
390
+ validate_legacy_evidence_entry() {
391
+ VALIDATED_EVIDENCE_KIND=$1
392
+ VALIDATED_EVIDENCE_PATH=$2
393
+ /usr/local/bin/node -e '
394
+ const fs = require("node:fs");
395
+ const [kind, filePath, rootPath, containerId, imageId] = process.argv.slice(1);
396
+ const root = fs.lstatSync(rootPath);
397
+ const entry = fs.lstatSync(filePath);
398
+ if (!entry.isFile() || entry.isSymbolicLink() || entry.uid !== root.uid || entry.gid !== root.gid) process.exit(1);
399
+ const mode = entry.mode & 0o777;
400
+ if (mode !== 0o600 && mode !== 0o644) process.exit(1);
401
+ const value = JSON.parse(fs.readFileSync(filePath, "utf8"));
402
+ if (!Array.isArray(value) || value.length !== 1 || !value[0] || typeof value[0] !== "object") process.exit(1);
403
+ if (kind === "container" && (value[0].Id !== containerId || value[0].Image !== imageId)) process.exit(1);
404
+ if (kind === "image" && value[0].Id !== imageId) process.exit(1);
405
+ ' "$VALIDATED_EVIDENCE_KIND" "$VALIDATED_EVIDENCE_PATH" "$LEGACY_EVIDENCE_ROOT" "$CAPTURED_LEGACY_CONTAINER_ID" "$CAPTURED_LEGACY_IMAGE_ID"
406
+ }
407
+ capture_missing_legacy_evidence_entry() {
408
+ MISSING_EVIDENCE_KIND=$1
409
+ MISSING_EVIDENCE_PATH=$2
410
+ LEGACY_EVIDENCE_TMP=$(mktemp "$LEGACY_EVIDENCE_ROOT/.capture.XXXXXXXX") || return $?
411
+ if test "$MISSING_EVIDENCE_KIND" = container; then
412
+ docker container inspect "$CAPTURED_LEGACY_CONTAINER_ID" >"$LEGACY_EVIDENCE_TMP" || {
413
+ CAPTURE_STATUS=$?
414
+ rm -f "$LEGACY_EVIDENCE_TMP"
415
+ return "$CAPTURE_STATUS"
416
+ }
417
+ else
418
+ docker image inspect "$CAPTURED_LEGACY_IMAGE_ID" >"$LEGACY_EVIDENCE_TMP" || {
419
+ CAPTURE_STATUS=$?
420
+ rm -f "$LEGACY_EVIDENCE_TMP"
421
+ return "$CAPTURE_STATUS"
422
+ }
423
+ fi
424
+ chmod 0600 "$LEGACY_EVIDENCE_TMP" || {
425
+ CAPTURE_STATUS=$?
426
+ rm -f "$LEGACY_EVIDENCE_TMP"
427
+ return "$CAPTURE_STATUS"
428
+ }
429
+ validate_legacy_evidence_entry "$MISSING_EVIDENCE_KIND" "$LEGACY_EVIDENCE_TMP" || {
430
+ CAPTURE_STATUS=$?
431
+ rm -f "$LEGACY_EVIDENCE_TMP"
432
+ return "$CAPTURE_STATUS"
433
+ }
434
+ sync -f "$LEGACY_EVIDENCE_TMP" || {
435
+ CAPTURE_STATUS=$?
436
+ rm -f "$LEGACY_EVIDENCE_TMP"
437
+ return "$CAPTURE_STATUS"
438
+ }
439
+ if ln "$LEGACY_EVIDENCE_TMP" "$MISSING_EVIDENCE_PATH"; then
440
+ rm -f "$LEGACY_EVIDENCE_TMP" || return $?
441
+ else
442
+ rm -f "$LEGACY_EVIDENCE_TMP" || return $?
443
+ validate_legacy_evidence_entry "$MISSING_EVIDENCE_KIND" "$MISSING_EVIDENCE_PATH" || return $?
444
+ fi
445
+ }
446
+ for LEGACY_EVIDENCE_KIND in container image; do
447
+ LEGACY_EVIDENCE_PATH="$LEGACY_EVIDENCE_DIR/$LEGACY_EVIDENCE_KIND.json"
448
+ if test -e "$LEGACY_EVIDENCE_PATH" || test -L "$LEGACY_EVIDENCE_PATH"; then
449
+ validate_legacy_evidence_entry "$LEGACY_EVIDENCE_KIND" "$LEGACY_EVIDENCE_PATH" || return $?
450
+ else
451
+ capture_missing_legacy_evidence_entry "$LEGACY_EVIDENCE_KIND" "$LEGACY_EVIDENCE_PATH" || return $?
452
+ fi
453
+ chmod 0600 "$LEGACY_EVIDENCE_PATH" || return $?
454
+ validate_legacy_evidence_entry "$LEGACY_EVIDENCE_KIND" "$LEGACY_EVIDENCE_PATH" || return $?
455
+ done
456
+ sync -f "$LEGACY_EVIDENCE_DIR" || return $?
457
+ }
458
+ install_from_legacy_staging() {
459
+ prepare_sanctuary_legacy_adoption "$IMAGE_ID" || return $?
460
+ ADOPTION_PREPARED_CONTAINER_ID=$LEGACY_STAGING_CONTAINER_ID
461
+ ADOPTION_PREPARED_IMAGE_ID=$LEGACY_STAGING_IMAGE_ID
462
+ verify_sanctuary_provider_readiness "$IMAGE_ID" || return $?
463
+ ADOPTION_CONTAINER_NAMES=$(docker container ls -a --format '{{.Names}}') || return $?
464
+ ADOPTION_NAME_COUNTS=$(printf '%s\n' "$ADOPTION_CONTAINER_NAMES" | awk '
465
+ /butler/ { butlers++ }
466
+ $0 == "ouro-butler-staging" { staging++ }
467
+ END { printf "%d %d", butlers + 0, staging + 0 }
468
+ ') || return $?
469
+ test "$ADOPTION_NAME_COUNTS" = "1 1" || return $?
470
+ assert_only_running_butler ouro-butler-staging || return $?
471
+ test "$(docker inspect --format '{{.State.Running}}' ouro-butler-staging)" = true || return $?
472
+ test "$(docker inspect --format '{{.Id}}' ouro-butler-staging)" = "$ADOPTION_PREPARED_CONTAINER_ID" || return $?
473
+ test "$(docker inspect --format '{{.Image}}' ouro-butler-staging)" = "$ADOPTION_PREPARED_IMAGE_ID" || return $?
474
+ LEGACY_STAGING_CONTAINER_ID=$ADOPTION_PREPARED_CONTAINER_ID
475
+ LEGACY_STAGING_IMAGE_ID=$ADOPTION_PREPARED_IMAGE_ID
476
+ LEGACY_EVIDENCE_ROOT=/mnt/user/appdata/ouro-butler/legacy-evidence
477
+ capture_sanctuary_legacy_evidence "$LEGACY_STAGING_CONTAINER_ID" "$LEGACY_STAGING_IMAGE_ID" "$LEGACY_EVIDENCE_ROOT" || return $?
478
+ validate_sanctuary_legacy_staging "$ADOPTION_PREPARED_CONTAINER_ID" "$ADOPTION_PREPARED_IMAGE_ID" || return $?
479
+ LEGACY_STAGING_CONTAINER_ID=$ADOPTION_PREPARED_CONTAINER_ID
480
+ LEGACY_STAGING_IMAGE_ID=$ADOPTION_PREPARED_IMAGE_ID
481
+ disable_butler_autostart || return $?
482
+ if docker stop "$LEGACY_STAGING_CONTAINER_ID" \
483
+ && CURRENT_LEGACY_STAGING_IMAGE_ID=$(docker inspect --format '{{.Image}}' "$LEGACY_STAGING_CONTAINER_ID") \
484
+ && test "$CURRENT_LEGACY_STAGING_IMAGE_ID" = "$LEGACY_STAGING_IMAGE_ID" \
485
+ && test "$(docker inspect --format '{{.State.Running}}' "$LEGACY_STAGING_CONTAINER_ID")" = false \
486
+ && docker rename "$LEGACY_STAGING_CONTAINER_ID" ouro-butler-legacy-evidence \
487
+ && CURRENT_LEGACY_EVIDENCE_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-legacy-evidence) \
488
+ && test "$CURRENT_LEGACY_EVIDENCE_IMAGE_ID" = "$LEGACY_STAGING_IMAGE_ID" \
489
+ && test "$(docker inspect --format '{{.State.Running}}' ouro-butler-legacy-evidence)" = false \
490
+ && docker create --name ouro-butler-staging --network host --restart unless-stopped --user 10001:10001 \
491
+ --mount "type=bind,src=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli,dst=/home/ouro/.ouro-cli" \
492
+ --mount "type=bind,src=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
493
+ "$IMAGE_ID" \
494
+ && audit_effective ouro-butler-staging "$IMAGE_ID" \
495
+ && docker start ouro-butler-staging \
496
+ && assert_only_running_butler ouro-butler-staging \
497
+ && wait_butler_ready ouro-butler-staging \
498
+ && docker stop ouro-butler-staging \
499
+ && test "$(docker inspect --format '{{.Image}}' ouro-butler-staging)" = "$IMAGE_ID" \
500
+ && docker rm ouro-butler-staging \
501
+ && docker create --name ouro-butler --network host --restart unless-stopped --user 10001:10001 \
502
+ --mount "type=bind,src=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli,dst=/home/ouro/.ouro-cli" \
503
+ --mount "type=bind,src=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
504
+ "$IMAGE_ID" \
505
+ && audit_effective ouro-butler "$IMAGE_ID" \
506
+ && docker start ouro-butler \
507
+ && assert_only_running_butler ouro-butler \
508
+ && wait_butler_ready ouro-butler \
509
+ && enable_butler_autostart; then
510
+ return 0
511
+ else
512
+ ADOPTION_STATUS=$?
513
+ fi
514
+ ADOPTION_RECOVERY_NAMES=$(docker container ls -a --format '{{.Names}}') || return $?
515
+ case "
516
+ $ADOPTION_RECOVERY_NAMES
517
+ " in
518
+ *"
519
+ ouro-butler
520
+ "*)
521
+ ADOPTION_PARTIAL_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler) || return $?
522
+ test "$ADOPTION_PARTIAL_IMAGE_ID" = "$IMAGE_ID" || return $?
523
+ docker stop ouro-butler >/dev/null 2>&1 || true
524
+ docker rm --force ouro-butler || return $?
525
+ ;;
526
+ esac
527
+ ADOPTION_RECOVERY_NAMES=$(docker container ls -a --format '{{.Names}}') || return $?
528
+ case "
529
+ $ADOPTION_RECOVERY_NAMES
530
+ " in
531
+ *"
532
+ ouro-butler-staging
533
+ "*)
534
+ CURRENT_LEGACY_STAGING_CONTAINER_ID=$(docker inspect --format '{{.Id}}' ouro-butler-staging) || return $?
535
+ case "$CURRENT_LEGACY_STAGING_CONTAINER_ID" in *[!0-9a-f]*|'') return 1 ;; esac
536
+ test "${#CURRENT_LEGACY_STAGING_CONTAINER_ID}" -eq 64 || return 1
537
+ CURRENT_LEGACY_STAGING_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-staging) || return $?
538
+ case "$CURRENT_LEGACY_STAGING_IMAGE_ID" in
539
+ "$IMAGE_ID")
540
+ docker stop ouro-butler-staging >/dev/null 2>&1 || true
541
+ docker rm --force ouro-butler-staging || return $?
542
+ ;;
543
+ "$LEGACY_STAGING_IMAGE_ID")
544
+ test "$CURRENT_LEGACY_STAGING_CONTAINER_ID" = "$LEGACY_STAGING_CONTAINER_ID" || return 1
545
+ docker stop "$LEGACY_STAGING_CONTAINER_ID" >/dev/null 2>&1 || return $?
546
+ test "$(docker inspect --format '{{.State.Running}}' "$LEGACY_STAGING_CONTAINER_ID")" = false || return $?
547
+ docker rename "$LEGACY_STAGING_CONTAINER_ID" ouro-butler-legacy-evidence || return $?
548
+ ;;
549
+ *) return 1 ;;
550
+ esac
551
+ ;;
552
+ esac
553
+ CURRENT_LEGACY_EVIDENCE_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-legacy-evidence) || return $?
554
+ test "$CURRENT_LEGACY_EVIDENCE_IMAGE_ID" = "$LEGACY_STAGING_IMAGE_ID" || return $?
555
+ test "$(docker inspect --format '{{.State.Running}}' ouro-butler-legacy-evidence)" = false || return $?
556
+ return "$ADOPTION_STATUS"
557
+ }
558
+ validate_sanctuary_legacy_import_marker() {
559
+ IMPORT_MARKER=$1
560
+ IMPORT_SOURCE=$2
561
+ test -f "$IMPORT_MARKER" && test ! -L "$IMPORT_MARKER" || return 1
562
+ test "$(stat -c '%u:%g %a' "$IMPORT_MARKER")" = "10001:10001 600" || return 1
563
+ /usr/local/bin/node -e '
564
+ const crypto = require("node:crypto");
565
+ const fs = require("node:fs");
566
+ const marker = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
567
+ const sourceDigest = `sha256:${crypto.createHash("sha256").update(fs.readFileSync(process.argv[2])).digest("hex")}`;
568
+ if (JSON.stringify(Object.keys(marker).sort()) !== JSON.stringify(["importedAt", "machineId", "schemaVersion", "sourceDigest"])) process.exit(1);
569
+ if (marker.schemaVersion !== 1 || marker.machineId !== "sanctuary" || marker.sourceDigest !== sourceDigest) process.exit(1);
570
+ if (!Number.isFinite(Date.parse(marker.importedAt))) process.exit(1);
571
+ ' "$IMPORT_MARKER" "$IMPORT_SOURCE"
572
+ }
573
+ record_sanctuary_legacy_import_marker() {
574
+ IMPORT_MARKER=$1
575
+ IMPORT_SOURCE=$2
576
+ test ! -e "$IMPORT_MARKER" || return 1
577
+ IMPORT_MARKER_TMP=$(mktemp "${IMPORT_MARKER}.tmp.XXXXXX") || return $?
578
+ trap 'rm -f -- "$IMPORT_MARKER_TMP"' EXIT || return $?
579
+ /usr/local/bin/node -e '
580
+ const crypto = require("node:crypto");
581
+ const fs = require("node:fs");
582
+ const sourceDigest = `sha256:${crypto.createHash("sha256").update(fs.readFileSync(process.argv[2])).digest("hex")}`;
583
+ const marker = { schemaVersion: 1, machineId: "sanctuary", sourceDigest, importedAt: new Date().toISOString() };
584
+ fs.writeFileSync(process.argv[1], `${JSON.stringify(marker)}\n`, { mode: 0o600, flag: "w" });
585
+ ' "$IMPORT_MARKER_TMP" "$IMPORT_SOURCE" || return $?
586
+ chown 10001:10001 "$IMPORT_MARKER_TMP" || return $?
587
+ chmod 0600 "$IMPORT_MARKER_TMP" || return $?
588
+ mv -f -- "$IMPORT_MARKER_TMP" "$IMPORT_MARKER" || return $?
589
+ sync -f "$IMPORT_MARKER" || return $?
590
+ sync -f "$(dirname "$IMPORT_MARKER")" || return $?
591
+ trap - EXIT || return $?
592
+ }
593
+ bootstrap_sanctuary_vault() {
594
+ BOOTSTRAP_IMAGE_ID=$1
595
+ BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE=${2-}
596
+ BOOTSTRAP_SOURCE_MACHINE_ID=${3-}
597
+ BOOTSTRAP_TARGET_MACHINE_ID=${4-}
598
+ validate_exact_image_id "$BOOTSTRAP_IMAGE_ID" || return $?
599
+ case "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" in
600
+ "")
601
+ test -z "$BOOTSTRAP_SOURCE_MACHINE_ID" || return 1
602
+ test -z "$BOOTSTRAP_TARGET_MACHINE_ID" || return 1
603
+ ;;
604
+ /mnt/user/appdata/ouro-butler/runtime/container-credentials.json)
605
+ test "$BOOTSTRAP_SOURCE_MACHINE_ID" = sanctuary-unraid || return 1
606
+ test "$BOOTSTRAP_TARGET_MACHINE_ID" = sanctuary || return 1
607
+ ;;
608
+ *) return 1 ;;
609
+ esac
610
+ BOOTSTRAP_RUNTIME_ROOT=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli
611
+ BOOTSTRAP_AGENT_ROOT=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro
612
+ for BOOTSTRAP_CONTAINER in ouro-butler-vault-status ouro-butler-vault-bootstrap ouro-butler-credential-bootstrap ouro-butler-provider-readiness; do
613
+ ! docker container inspect "$BOOTSTRAP_CONTAINER" >/dev/null 2>&1 || return 1
614
+ done
615
+ VAULT_STATUS=$(docker run --rm --pull=never --network host --name ouro-butler-vault-status --user 10001:10001 \
616
+ --mount "type=bind,src=$BOOTSTRAP_RUNTIME_ROOT,dst=/home/ouro/.ouro-cli" \
617
+ --mount "type=bind,src=$BOOTSTRAP_AGENT_ROOT,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
618
+ --entrypoint node "$BOOTSTRAP_IMAGE_ID" /opt/ouro/dist/heart/daemon/ouro-entry.js \
619
+ vault status --agent sanctuary --store plaintext-file) || return $?
620
+ ! docker container inspect ouro-butler-vault-status >/dev/null 2>&1 || return 1
621
+ case "
622
+ $VAULT_STATUS
623
+ " in
624
+ *"
625
+ vault locator: not configured in agent.json
626
+ "*) VAULT_ACTION=create ;;
627
+ *"
628
+ vault locator: agent.json
629
+ "*)
630
+ case "
631
+ $VAULT_STATUS
632
+ " in
633
+ *"
634
+ local unlock: available
635
+ "*) VAULT_ACTION=none ;;
636
+ *"
637
+ local unlock: missing
638
+ "*) VAULT_ACTION=unlock ;;
639
+ *) return 1 ;;
640
+ esac
641
+ ;;
642
+ *) return 1 ;;
643
+ esac
644
+ if test "$VAULT_ACTION" != none; then
645
+ docker run --rm -it --pull=never --network host --name ouro-butler-vault-bootstrap --user 10001:10001 \
646
+ --mount "type=bind,src=$BOOTSTRAP_RUNTIME_ROOT,dst=/home/ouro/.ouro-cli" \
647
+ --mount "type=bind,src=$BOOTSTRAP_AGENT_ROOT,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
648
+ --entrypoint node "$BOOTSTRAP_IMAGE_ID" /opt/ouro/dist/heart/daemon/ouro-entry.js \
649
+ vault "$VAULT_ACTION" --agent sanctuary --store plaintext-file || return $?
650
+ ! docker container inspect ouro-butler-vault-bootstrap >/dev/null 2>&1 || return 1
651
+ fi
652
+ VERIFIED_VAULT_STATUS=$(docker run --rm --pull=never --network host --name ouro-butler-vault-status --user 10001:10001 \
653
+ --mount "type=bind,src=$BOOTSTRAP_RUNTIME_ROOT,dst=/home/ouro/.ouro-cli" \
654
+ --mount "type=bind,src=$BOOTSTRAP_AGENT_ROOT,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
655
+ --entrypoint node "$BOOTSTRAP_IMAGE_ID" /opt/ouro/dist/heart/daemon/ouro-entry.js \
656
+ vault status --agent sanctuary --store plaintext-file) || return $?
657
+ ! docker container inspect ouro-butler-vault-status >/dev/null 2>&1 || return 1
658
+ case "
659
+ $VERIFIED_VAULT_STATUS
660
+ " in
661
+ *"
662
+ vault locator: agent.json
663
+ "*) ;;
664
+ *) return 1 ;;
665
+ esac
666
+ case "
667
+ $VERIFIED_VAULT_STATUS
668
+ " in
669
+ *"
670
+ local unlock: available
671
+ "*) ;;
672
+ *) return 1 ;;
673
+ esac
674
+ if test -n "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE"; then
675
+ BOOTSTRAP_CREDENTIAL_SOURCE="$BOOTSTRAP_RUNTIME_ROOT/container-credentials.json"
676
+ BOOTSTRAP_CREDENTIAL_CLAIM="$BOOTSTRAP_CREDENTIAL_SOURCE.consuming"
677
+ test -f "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" || return $?
678
+ test ! -L "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" || return $?
679
+ BOOTSTRAP_LEGACY_METADATA=$(stat -c '%u:%g %a' "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE") || return $?
680
+ test "$BOOTSTRAP_LEGACY_METADATA" = "10001:10001 600" || return $?
681
+ BOOTSTRAP_IMPORT_MARKER="$BOOTSTRAP_RUNTIME_ROOT/legacy-credentials-imported.json"
682
+ if test -e "$BOOTSTRAP_IMPORT_MARKER"; then
683
+ validate_sanctuary_legacy_import_marker "$BOOTSTRAP_IMPORT_MARKER" "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" || return $?
684
+ test ! -e "$BOOTSTRAP_CREDENTIAL_SOURCE" || return 1
685
+ test ! -e "$BOOTSTRAP_CREDENTIAL_CLAIM" || return 1
686
+ else
687
+ if test -e "$BOOTSTRAP_CREDENTIAL_SOURCE"; then
688
+ test -f "$BOOTSTRAP_CREDENTIAL_SOURCE" || return $?
689
+ test ! -L "$BOOTSTRAP_CREDENTIAL_SOURCE" || return $?
690
+ test "$(stat -c '%u:%g %a' "$BOOTSTRAP_CREDENTIAL_SOURCE")" = "10001:10001 600" || return $?
691
+ cmp -s "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" "$BOOTSTRAP_CREDENTIAL_SOURCE" || return $?
692
+ elif test -e "$BOOTSTRAP_CREDENTIAL_CLAIM"; then
693
+ test -f "$BOOTSTRAP_CREDENTIAL_CLAIM" || return $?
694
+ test ! -L "$BOOTSTRAP_CREDENTIAL_CLAIM" || return $?
695
+ test "$(stat -c '%u:%g %a' "$BOOTSTRAP_CREDENTIAL_CLAIM")" = "10001:10001 600" || return $?
696
+ cmp -s "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" "$BOOTSTRAP_CREDENTIAL_CLAIM" || return $?
697
+ else
698
+ BOOTSTRAP_CREDENTIAL_TMP=$(mktemp "$BOOTSTRAP_RUNTIME_ROOT/container-credentials.json.tmp.XXXXXX") || return $?
699
+ trap 'rm -f -- "$BOOTSTRAP_CREDENTIAL_TMP"' EXIT || return $?
700
+ install -m 0600 -o 10001 -g 10001 "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" "$BOOTSTRAP_CREDENTIAL_TMP" || return $?
701
+ cmp -s "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" "$BOOTSTRAP_CREDENTIAL_TMP" || return $?
702
+ sync -f "$BOOTSTRAP_CREDENTIAL_TMP" || return $?
703
+ mv -f -- "$BOOTSTRAP_CREDENTIAL_TMP" "$BOOTSTRAP_CREDENTIAL_SOURCE" || return $?
704
+ sync -f "$BOOTSTRAP_RUNTIME_ROOT" || return $?
705
+ trap - EXIT || return $?
706
+ fi
707
+ docker run --rm --pull=never --network host --name ouro-butler-credential-bootstrap --user 10001:10001 \
708
+ --mount "type=bind,src=$BOOTSTRAP_RUNTIME_ROOT,dst=/home/ouro/.ouro-cli" \
709
+ --mount "type=bind,src=$BOOTSTRAP_AGENT_ROOT,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
710
+ --entrypoint node "$BOOTSTRAP_IMAGE_ID" -e '
711
+ const { loadContainerCredentialBootstrap } = require("/opt/ouro/dist/heart/daemon/container-credential-bootstrap.js")
712
+ loadContainerCredentialBootstrap(["sanctuary"], {
713
+ machineIdMigration: {
714
+ sourceMachineId: process.argv[1],
715
+ targetMachineId: process.argv[2],
716
+ },
717
+ }).then(
718
+ () => process.exit(0),
719
+ () => { process.stderr.write("credential bootstrap failed\n"); process.exit(1) },
720
+ )
721
+ ' "$BOOTSTRAP_SOURCE_MACHINE_ID" "$BOOTSTRAP_TARGET_MACHINE_ID" || return $?
722
+ ! docker container inspect ouro-butler-credential-bootstrap >/dev/null 2>&1 || return 1
723
+ test ! -e "$BOOTSTRAP_CREDENTIAL_SOURCE" || return $?
724
+ test ! -e "$BOOTSTRAP_CREDENTIAL_CLAIM" || return $?
725
+ record_sanctuary_legacy_import_marker "$BOOTSTRAP_IMPORT_MARKER" "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" || return $?
726
+ validate_sanctuary_legacy_import_marker "$BOOTSTRAP_IMPORT_MARKER" "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" || return $?
727
+ fi
728
+ test -f "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" || return $?
729
+ test ! -L "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" || return $?
730
+ test "$(stat -c '%u:%g %a' "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE")" = "$BOOTSTRAP_LEGACY_METADATA" || return $?
731
+ fi
732
+ validate_sanctuary_roots "$BOOTSTRAP_RUNTIME_ROOT" "$BOOTSTRAP_AGENT_ROOT" || return $?
733
+ }
734
+ authenticate_sanctuary_provider() {
735
+ AUTH_IMAGE_ID=$1
736
+ AUTH_PROVIDER=${2-}
737
+ validate_exact_image_id "$AUTH_IMAGE_ID" || return $?
738
+ case "$AUTH_PROVIDER" in
739
+ openai-compatible) AUTH_CONTAINER=ouro-butler-provider-auth-glm ;;
740
+ openai-compatible-gemini) AUTH_CONTAINER=ouro-butler-provider-auth-gemini ;;
741
+ *) return 1 ;;
742
+ esac
743
+ AUTH_RUNTIME_ROOT=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli
744
+ AUTH_AGENT_ROOT=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro
745
+ ! docker container inspect "$AUTH_CONTAINER" >/dev/null 2>&1 || return 1
746
+ docker run --rm -it --pull=never --network host --name "$AUTH_CONTAINER" --user 10001:10001 \
747
+ --mount "type=bind,src=$AUTH_RUNTIME_ROOT,dst=/home/ouro/.ouro-cli" \
748
+ --mount "type=bind,src=$AUTH_AGENT_ROOT,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
749
+ --entrypoint node "$AUTH_IMAGE_ID" /opt/ouro/dist/heart/daemon/ouro-entry.js \
750
+ auth --agent sanctuary --provider "$AUTH_PROVIDER" || return $?
751
+ ! docker container inspect "$AUTH_CONTAINER" >/dev/null 2>&1 || return 1
752
+ }
753
+ verify_sanctuary_provider_readiness() {
754
+ READINESS_IMAGE_ID=$1
755
+ validate_exact_image_id "$READINESS_IMAGE_ID" || return $?
756
+ READINESS_RUNTIME_ROOT=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli
757
+ READINESS_AGENT_ROOT=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro
758
+ ! docker container inspect ouro-butler-provider-readiness >/dev/null 2>&1 || return 1
759
+ docker run --rm --pull=never --network host --name ouro-butler-provider-readiness --user 10001:10001 \
760
+ --mount "type=bind,src=$READINESS_RUNTIME_ROOT,dst=/home/ouro/.ouro-cli" \
761
+ --mount "type=bind,src=$READINESS_AGENT_ROOT,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
762
+ --entrypoint /bin/sh "$READINESS_IMAGE_ID" -ceu '
763
+ umask 077
764
+ node /opt/ouro/dist/heart/daemon/ouro-entry.js check --agent sanctuary --lane outward
765
+ node /opt/ouro/dist/heart/daemon/ouro-entry.js check --agent sanctuary --lane inner
766
+ node - <<'"'"'NODE'"'"'
767
+ (async () => {
768
+ try {
769
+ const fs = require("node:fs");
770
+ const root = "/home/ouro/AgentBundles/sanctuary.ouro";
771
+ const agent = JSON.parse(fs.readFileSync(`${root}/agent.json`, "utf8"));
772
+ const policy = JSON.parse(fs.readFileSync(`${root}/provider-readiness.json`, "utf8"));
773
+ const expectedPolicy = { version: 1, selectionPolicy: "explicit-same-lane-only" };
774
+ const expected = new Map([
775
+ ["openai-compatible", { provider: "openai-compatible", model: "glm-5.2", vaultItem: "providers/openai-compatible", baseUrl: "https://api.z.ai/api/paas/v4/" }],
776
+ ["openai-compatible-gemini", { provider: "openai-compatible-gemini", model: "gemini-3.6-flash", vaultItem: "providers/openai-compatible-gemini", baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai/" }],
777
+ ]);
778
+ const exactLane = value => value && value.provider === "openai-compatible" && value.model === "glm-5.2";
779
+ if (!exactLane(agent.humanFacing) || !exactLane(agent.agentFacing)
780
+ || policy.version !== expectedPolicy.version || policy.selectionPolicy !== expectedPolicy.selectionPolicy
781
+ || !Array.isArray(policy.providers) || policy.providers.length !== expected.size) throw new Error();
782
+ for (const entry of policy.providers) {
783
+ const wanted = expected.get(entry.provider);
784
+ if (!wanted || entry.model !== wanted.model || entry.vaultItem !== wanted.vaultItem || entry.baseUrl !== wanted.baseUrl) throw new Error();
785
+ expected.delete(entry.provider);
786
+ }
787
+ if (expected.size !== 0) throw new Error();
788
+ const { refreshProviderCredentialPool } = require("/opt/ouro/dist/heart/provider-credentials.js");
789
+ const { pingProvider } = require("/opt/ouro/dist/heart/provider-ping.js");
790
+ const refreshed = await refreshProviderCredentialPool("sanctuary", {
791
+ providers: ["openai-compatible", "openai-compatible-gemini"],
792
+ skipCache: true,
793
+ });
794
+ if (!refreshed.ok) throw new Error();
795
+ const glm = refreshed.pool.providers["openai-compatible"];
796
+ const gemini = refreshed.pool.providers["openai-compatible-gemini"];
797
+ const exactRecord = (record, provider, baseUrl) => record && record.provider === provider
798
+ && typeof record.revision === "string" && record.revision.length > 0
799
+ && typeof record.credentials?.apiKey === "string" && record.credentials.apiKey.trim().length > 0
800
+ && record.config?.baseUrl === baseUrl;
801
+ if (!exactRecord(glm, "openai-compatible", "https://api.z.ai/api/paas/v4/")
802
+ || !exactRecord(gemini, "openai-compatible-gemini", "https://generativelanguage.googleapis.com/v1beta/openai/")
803
+ || glm.credentials.apiKey === gemini.credentials.apiKey
804
+ || new Set([glm.revision, gemini.revision]).size !== 2) throw new Error();
805
+ const probes = [
806
+ { provider: "openai-compatible", model: "glm-5.2", credentialRevision: glm.revision, record: glm },
807
+ { provider: "openai-compatible", model: "glm-5.2", credentialRevision: glm.revision, record: glm },
808
+ { provider: "openai-compatible-gemini", model: "gemini-3.6-flash", credentialRevision: gemini.revision, record: gemini },
809
+ ];
810
+ const results = await Promise.all(probes.map(({ provider, model, record }) => pingProvider(
811
+ provider,
812
+ { ...record.credentials, ...record.config },
813
+ { model, timeoutMs: 10000, attemptPolicy: { baseDelayMs: 0 } },
814
+ )));
815
+ for (let index = 0; index < results.length; index += 1) {
816
+ const result = results[index];
817
+ const probe = probes[index];
818
+ if (!result.ok || !Array.isArray(result.attempts) || result.attempts.length < 1 || result.attempts.length > 3
819
+ || !result.attempts.every(attempt => attempt.provider === probe.provider && attempt.model === probe.model
820
+ && attempt.operation === "ping" && typeof attempt.ok === "boolean")
821
+ || result.attempts.at(-1)?.ok !== true) throw new Error();
822
+ }
823
+ process.stdout.write("Sanctuary provider readiness verified.\n");
824
+ } catch {
825
+ process.stderr.write("Sanctuary provider readiness verification failed.\n");
826
+ process.exitCode = 1;
827
+ }
828
+ })();
829
+ NODE
830
+ ' || return $?
831
+ ! docker container inspect ouro-butler-provider-readiness >/dev/null 2>&1 || return 1
832
+ validate_sanctuary_roots "$READINESS_RUNTIME_ROOT" "$READINESS_AGENT_ROOT" || return $?
833
+ }
834
+ run_sanctuary_docker() {
835
+ /usr/bin/timeout -s KILL 20 /usr/bin/docker "$@"
836
+ }
837
+ run_sanctuary_unraid_api() {
838
+ /usr/bin/timeout -s KILL 20 /usr/local/sbin/unraid-api "$@"
839
+ }
840
+ run_sanctuary_node() {
841
+ /usr/local/bin/node "$@"
842
+ }
843
+ resolve_sanctuary_unraid_key() {
844
+ run_sanctuary_node -e '
845
+ const fs = require("node:fs");
846
+ const root = "/boot/config/plugins/dynamix.my.servers/keys";
847
+ const expected = process.argv[1];
848
+ const found = [];
849
+ for (const name of fs.readdirSync(root)) {
850
+ if (!/^[A-Za-z0-9._:-]+\.json$/.test(name)) process.exit(1);
851
+ const path = `${root}/${name}`;
852
+ const stat = fs.lstatSync(path);
853
+ if (!stat.isFile() || stat.isSymbolicLink()) process.exit(1);
854
+ const value = JSON.parse(fs.readFileSync(path, "utf8"));
855
+ if (value.id === expected) found.push({ path, name: value.name });
856
+ }
857
+ if (found.length !== 1 || typeof found[0].name !== "string" || !/^[A-Za-z0-9 ._:-]+$/.test(found[0].name)) process.exit(1);
858
+ process.stdout.write(`${found[0].path}\t${found[0].name}`);
859
+ ' "$1"
860
+ }
861
+ sanctuary_revoked_key_recovery_path() {
862
+ case "$1" in ''|*[!A-Za-z0-9._:-]*) return 1 ;; esac
863
+ printf '%s/%s.json' /mnt/user/appdata/ouro-butler/acceptance/revoked-key-proof "$1"
864
+ }
865
+ validate_sanctuary_revoked_key_recovery() {
866
+ test -f "$1" && test ! -L "$1" || return 1
867
+ test "$(stat -c '%u:%g %a' "$1")" = "0:0 600" || return 1
868
+ }
869
+ preserve_sanctuary_revoked_key() {
870
+ KEY_ID=$1
871
+ KEY_SOURCE=$2
872
+ RECOVERY_ROOT=/mnt/user/appdata/ouro-butler/acceptance/revoked-key-proof
873
+ test -f "$KEY_SOURCE" && test ! -L "$KEY_SOURCE" || return 1
874
+ if test ! -e "$RECOVERY_ROOT"; then
875
+ install -d -m 0700 -o root -g root "$RECOVERY_ROOT" || return $?
876
+ fi
877
+ test -d "$RECOVERY_ROOT" && test ! -L "$RECOVERY_ROOT" || return 1
878
+ test "$(stat -c '%u:%g %a' "$RECOVERY_ROOT")" = "0:0 700" || return 1
879
+ RECOVERY_PATH=$(sanctuary_revoked_key_recovery_path "$KEY_ID") || return $?
880
+ test ! -e "$RECOVERY_PATH" || return 1
881
+ RECOVERY_TMP=$(mktemp "$RECOVERY_ROOT/$KEY_ID.json.tmp.XXXXXX") || return $?
882
+ trap 'rm -f -- "$RECOVERY_TMP"' EXIT || return $?
883
+ install -m 0600 -o root -g root "$KEY_SOURCE" "$RECOVERY_TMP" || return $?
884
+ cmp -s "$KEY_SOURCE" "$RECOVERY_TMP" || return 1
885
+ mv -f -- "$RECOVERY_TMP" "$RECOVERY_PATH" || return $?
886
+ sync -f "$RECOVERY_ROOT" || return $?
887
+ trap - EXIT || return $?
888
+ }
889
+ clear_sanctuary_revoked_key() {
890
+ RECOVERY_PATH=$(sanctuary_revoked_key_recovery_path "$1") || return $?
891
+ test -f "$RECOVERY_PATH" && test ! -L "$RECOVERY_PATH" || return 1
892
+ test "$(stat -c '%u:%g %a' "$RECOVERY_PATH")" = "0:0 600" || return 1
893
+ rm -f -- "$RECOVERY_PATH" || return $?
894
+ sync -f "$(dirname "$RECOVERY_PATH")" || return $?
895
+ }
896
+ verify_vault_backed_unraid_key() {
897
+ KEY_ID=$1
898
+ CAPABILITY=$2
899
+ case "$KEY_ID" in ''|*[!A-Za-z0-9._:-]*) return 1 ;; esac
900
+ case "$CAPABILITY" in read-only|bounded-write) ;; *) return 1 ;; esac
901
+ IMAGE_DIGEST=${IMAGE_ID#sha256:}
902
+ test "$IMAGE_DIGEST" != "$IMAGE_ID" || return 1
903
+ test "${#IMAGE_DIGEST}" -eq 64 || return 1
904
+ case "$IMAGE_DIGEST" in *[!0-9a-f]*) return 1 ;; esac
905
+ test "$(run_sanctuary_docker image inspect --format '{{.Id}}' "$IMAGE_ID")" = "$IMAGE_ID" || return $?
906
+ KEY_TARGET=$(resolve_sanctuary_unraid_key "$KEY_ID") || return $?
907
+ KEY_PATH=${KEY_TARGET%% *}
908
+ test "$KEY_PATH" != "$KEY_TARGET" || return 1
909
+ test -f "$KEY_PATH" && test ! -L "$KEY_PATH" || return 1
910
+ VERIFY_RESULT=$(run_sanctuary_docker run --rm --pull=never --network host \
911
+ --user 0:0 \
912
+ --mount type=bind,src=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli,dst=/home/ouro/.ouro-cli,readonly \
913
+ --mount type=bind,src=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro,dst=/home/ouro/AgentBundles/sanctuary.ouro,readonly \
914
+ --mount type=bind,src="$KEY_PATH",dst=/run/ouro-acceptance/unraid-key.json,readonly \
915
+ --entrypoint /opt/ouro/deploy/unraid/sanctuary-acceptance-adapter.sh \
916
+ "$IMAGE_ID" vault-probe "$KEY_ID" "$CAPABILITY") || return $?
917
+ printf '%s' "$VERIFY_RESULT" | run_sanctuary_node -e '
918
+ let input = "";
919
+ process.stdin.setEncoding("utf8");
920
+ process.stdin.on("data", chunk => { input += chunk; });
921
+ process.stdin.on("end", () => {
922
+ const value = JSON.parse(input);
923
+ const expectedId = process.argv[1];
924
+ const expectedCapability = process.argv[2];
925
+ const expectedProof = expectedCapability === "read-only"
926
+ ? "read-authorized-write-denied"
927
+ : "read-authorized-write-reached-not-found";
928
+ if (JSON.stringify(Object.keys(value).sort()) !== JSON.stringify(["capability", "keyId", "proof", "valid"])) process.exit(1);
929
+ if (value.valid !== true || value.keyId !== expectedId || value.capability !== expectedCapability) process.exit(1);
930
+ if (value.proof !== expectedProof) process.exit(1);
931
+ });
932
+ ' "$KEY_ID" "$CAPABILITY" || return $?
933
+ }
934
+ inventory_unraid_key_ids() {
935
+ IMAGE_DIGEST=${IMAGE_ID#sha256:}
936
+ test "$IMAGE_DIGEST" != "$IMAGE_ID" || return 1
937
+ test "${#IMAGE_DIGEST}" -eq 64 || return 1
938
+ case "$IMAGE_DIGEST" in *[!0-9a-f]*) return 1 ;; esac
939
+ test "$(run_sanctuary_docker image inspect --format '{{.Id}}' "$IMAGE_ID")" = "$IMAGE_ID" || return $?
940
+ INVENTORY_RESULT=$(printf '%s' '{"operation":"closed-inventory"}' | \
941
+ run_sanctuary_docker run --rm -i --pull=never --network none \
942
+ --user 0:0 --read-only \
943
+ --mount type=bind,src=/boot/config/plugins/dynamix.my.servers/keys,dst=/boot/config/plugins/dynamix.my.servers/keys,readonly \
944
+ --entrypoint /opt/ouro/deploy/unraid/sanctuary-acceptance-adapter.sh "$IMAGE_ID") || return $?
945
+ printf '%s' "$INVENTORY_RESULT" | run_sanctuary_node -e '
946
+ let input = "";
947
+ process.stdin.setEncoding("utf8");
948
+ process.stdin.on("data", chunk => { input += chunk; });
949
+ process.stdin.on("end", () => {
950
+ const value = JSON.parse(input);
951
+ if (!value || JSON.stringify(Object.keys(value)) !== JSON.stringify(["keys"]) || !Array.isArray(value.keys)) process.exit(1);
952
+ for (const key of value.keys) {
953
+ if (!key || JSON.stringify(Object.keys(key).sort()) !== JSON.stringify(["id", "roles", "scope"])) process.exit(1);
954
+ if (!/^[A-Za-z0-9._:-]+$/.test(key.id)) process.exit(1);
955
+ if (!["read-only", "bounded-write", "legacy-write"].includes(key.scope) || key.roles !== "none") process.exit(1);
956
+ process.stdout.write(`${key.id}\t${key.scope}\t${key.roles}\n`);
957
+ }
958
+ });
959
+ ' || return $?
960
+ }
961
+ revoke_unraid_key_exact() {
962
+ KEY_ID=$1
963
+ case "$KEY_ID" in ''|*[!A-Za-z0-9._:-]*) return 1 ;; esac
964
+ test "${REVOKED_KEY_FD_OPEN:-no}" = no || return 1
965
+ KEY_TARGET=$(resolve_sanctuary_unraid_key "$KEY_ID") || return $?
966
+ KEY_PATH=${KEY_TARGET%% *}
967
+ KEY_NAME=${KEY_TARGET#* }
968
+ test "$KEY_PATH" != "$KEY_TARGET" || return 1
969
+ test -f "$KEY_PATH" && test ! -L "$KEY_PATH" || return $?
970
+ preserve_sanctuary_revoked_key "$KEY_ID" "$KEY_PATH" || return $?
971
+ if ! REVOKE_RESULT=$(run_sanctuary_unraid_api apikey --name "$KEY_NAME" --delete --json); then
972
+ return 1
973
+ fi
974
+ if ! printf '%s' "$REVOKE_RESULT" | run_sanctuary_node -e '
975
+ let input = "";
976
+ process.stdin.setEncoding("utf8");
977
+ process.stdin.on("data", chunk => { input += chunk; });
978
+ process.stdin.on("end", () => {
979
+ const value = JSON.parse(input);
980
+ const expectedId = process.argv[1];
981
+ const expectedName = process.argv[2];
982
+ if (value.deleted !== 1 || !Array.isArray(value.keys) || value.keys.length !== 1) process.exit(1);
983
+ if (value.keys[0].id !== expectedId || value.keys[0].name !== expectedName) process.exit(1);
984
+ });
985
+ ' "$KEY_ID" "$KEY_NAME"; then
986
+ return 1
987
+ fi
988
+ }
989
+ verify_revoked_unraid_key_rejected() {
990
+ KEY_ID=$1
991
+ case "$KEY_ID" in ''|*[!A-Za-z0-9._:-]*) return 1 ;; esac
992
+ REVOKED_KEY_RECOVERY_PATH=$(sanctuary_revoked_key_recovery_path "$KEY_ID") || return $?
993
+ validate_sanctuary_revoked_key_recovery "$REVOKED_KEY_RECOVERY_PATH" || return $?
994
+ IMAGE_DIGEST=${IMAGE_ID#sha256:}
995
+ test "$IMAGE_DIGEST" != "$IMAGE_ID" || return 1
996
+ test "${#IMAGE_DIGEST}" -eq 64 || return 1
997
+ case "$IMAGE_DIGEST" in *[!0-9a-f]*) return 1 ;; esac
998
+ test "$(run_sanctuary_docker image inspect --format '{{.Id}}' "$IMAGE_ID")" = "$IMAGE_ID" || return 1
999
+ REJECT_ATTEMPT=0
1000
+ while test "$REJECT_ATTEMPT" -lt 3; do
1001
+ REJECT_ATTEMPT=$((REJECT_ATTEMPT + 1))
1002
+ if REJECT_RESULT=$(run_sanctuary_docker run --rm -i --pull=never --network host \
1003
+ --user 10001:10001 --read-only \
1004
+ --entrypoint /bin/sh "$IMAGE_ID" -ceu \
1005
+ 'exec 3<&0; exec /opt/ouro/deploy/unraid/sanctuary-acceptance-adapter.sh revoked-probe "$1" "$2" 3<&3' \
1006
+ sanctuary-revoked-probe "$KEY_ID" http://127.0.0.1/graphql <"$REVOKED_KEY_RECOVERY_PATH") \
1007
+ && printf '%s' "$REJECT_RESULT" | run_sanctuary_node -e '
1008
+ let input = "";
1009
+ process.stdin.setEncoding("utf8");
1010
+ process.stdin.on("data", chunk => { input += chunk; });
1011
+ process.stdin.on("end", () => {
1012
+ const value = JSON.parse(input);
1013
+ if (JSON.stringify(Object.keys(value).sort()) !== JSON.stringify(["id", "rejected", "status"])) process.exit(1);
1014
+ if (value.rejected !== true || value.id !== process.argv[1] || ![401, 403].includes(value.status)) process.exit(1);
1015
+ });
1016
+ ' "$KEY_ID"; then
1017
+ clear_sanctuary_revoked_key "$KEY_ID" || return $?
1018
+ return 0
1019
+ fi
1020
+ test "$REJECT_ATTEMPT" -lt 3 || return 1
1021
+ sleep 2
1022
+ done
1023
+ return 1
1024
+ }
1025
+ Update:
1026
+ Build and verify a new ouro-butler:<version> image first. The tag is only a
1027
+ lookup handle and never authorizes container creation. Resolve and validate
1028
+ the exact local Docker image ID before staging:
1029
+ IMAGE_TAG=ouro-butler:<version>
1030
+ IMAGE_ID=$(docker image inspect --format '{{.Id}}' "$IMAGE_TAG")
1031
+ printf '%s\n' "$IMAGE_ID" | grep -Eq '^sha256:[0-9a-f]{64}$'
1032
+ docker image inspect "$IMAGE_ID" >/dev/null
1033
+ Initial install/adoption is a separate terminal path for the verified live
1034
+ legacy state: no production or rollback, exactly one running (possibly
1035
+ unhealthy) ouro-butler-staging, and no legacy-evidence container. After the
1036
+ helper definitions above are loaded and IMAGE_ID is resolved, run this exact
1037
+ sequence. The two authentication commands prompt through the runtime's hidden
1038
+ terminal input; do not place credentials in arguments, shell variables, or
1039
+ history.
1040
+ Sanctuary legacy adoption commands:
1041
+ prepare_sanctuary_legacy_adoption "$IMAGE_ID"
1042
+ authenticate_sanctuary_provider "$IMAGE_ID" openai-compatible
1043
+ authenticate_sanctuary_provider "$IMAGE_ID" openai-compatible-gemini
1044
+ verify_sanctuary_provider_readiness "$IMAGE_ID"
1045
+ install_from_legacy_staging
1046
+ These commands are one terminal path; after install succeeds, stop and do not
1047
+ continue into the normal update below. The final install is noninteractive:
1048
+ it reruns resumable preparation plus fresh readiness, but never authentication.
1049
+ That function never applies the canonical auditor to the known-noncanonical
1050
+ legacy container or restarts it. It verifies and pins the legacy image,
1051
+ provisions the absent canonical roots from the exact target image's packaged
1052
+ Sanctuary skeleton, proves required files plus exact ownership/modes, and runs
1053
+ same-image vault bootstrap and provider readiness before durably snapshotting
1054
+ both exact container and image inspect records. Any preparation, vault, or
1055
+ readiness failure returns while legacy remains running with autostart
1056
+ untouched. It then stops and rechecks the legacy container and renames it to
1057
+ stopped ouro-butler-legacy-evidence. A fresh canonical staging container is
1058
+ created from exact IMAGE_ID and canonical binds, audited, started, proven to
1059
+ be the only running Butler, readiness-checked, then stopped and removed only
1060
+ after its image is rechecked. Only then is fresh canonical production created,
1061
+ audited, started, readiness-checked, and placed in bare production autostart.
1062
+ Failure removes only partial target-image staging/production containers,
1063
+ quarantines the exact legacy container without deletion or restart, leaves
1064
+ autostart disabled, and propagates the original status.
1065
+ For a normal update, preflight the canonical topology before any autostart or
1066
+ container mutation. Production must be the only running Butler poller;
1067
+ staging must be absent; rollback may be absent or one stopped container with
1068
+ the exact production image. A stopped legacy-evidence container is preserved.
1069
+ Disable every Butler name in Unraid's array-autostart file and verify that
1070
+ result before stopping production. First resolve and validate the exact image
1071
+ ID of the known-good production container while it is still running, so a
1072
+ lookup failure cannot strand a renamed container:
1073
+ ROLLBACK_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler)
1074
+ validate_exact_image_id "$ROLLBACK_IMAGE_ID"
1075
+ if assert_update_topology "$ROLLBACK_IMAGE_ID"; then
1076
+ :
1077
+ else
1078
+ UPDATE_PREFLIGHT_STATUS=$?
1079
+ (exit "$UPDATE_PREFLIGHT_STATUS")
1080
+ fi
1081
+ audit_effective ouro-butler "$ROLLBACK_IMAGE_ID"
1082
+ Only after that topology gate, stage copies of the packaged template and
1083
+ runtime policy at these paths:
1084
+ STAGED_TEMPLATE=/mnt/user/appdata/ouro-butler/staging/sanctuary.xml
1085
+ STAGED_RUNTIME_POLICY=/mnt/user/appdata/ouro-butler/staging/container-runtime.json
1086
+ Replace sha256:REPLACE_WITH_EXACT_LOCAL_IMAGE_ID in the staged template at
1087
+ $STAGED_TEMPLATE with exactly $IMAGE_ID. Before docker create, run the
1088
+ packaged auditor from that exact image ID with both staged inputs mounted
1089
+ read-only:
1090
+ docker run --rm --pull=never --network=none \
1091
+ --entrypoint /opt/ouro/deploy/unraid/audit-container-spec.sh \
1092
+ --mount "type=bind,src=$STAGED_TEMPLATE,dst=/audit/sanctuary.xml,readonly" \
1093
+ --mount "type=bind,src=$STAGED_RUNTIME_POLICY,dst=/audit/container-runtime.json,readonly" \
1094
+ "$IMAGE_ID" --template /audit/sanctuary.xml --runtime-policy /audit/container-runtime.json --expected-image "$IMAGE_ID"
1095
+ Guard the atomic autostart disable separately. If it fails, production has not
1096
+ been touched and the captured status is propagated:
1097
+ if disable_butler_autostart; then
1098
+ :
1099
+ else
1100
+ AUTOSTART_DISABLE_STATUS=$?
1101
+ (exit "$AUTOSTART_DISABLE_STATUS")
1102
+ fi
1103
+ Define the stale-rollback cleanup used by the preparation guard:
1104
+ remove_stopped_rollback_if_present() {
1105
+ EXPECTED_STALE_ROLLBACK_IMAGE_ID=$1
1106
+ ROLLBACK_CONTAINER_NAMES=$(docker container ls -a --format '{{.Names}}') || return $?
1107
+ case "
1108
+ $ROLLBACK_CONTAINER_NAMES
1109
+ " in
1110
+ *"
1111
+ ouro-butler-rollback
1112
+ "*)
1113
+ ROLLBACK_RUNNING=$(docker inspect --format '{{.State.Running}}' ouro-butler-rollback) || return $?
1114
+ test "$ROLLBACK_RUNNING" = false || return $?
1115
+ CURRENT_STALE_ROLLBACK_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-rollback) || return $?
1116
+ test "$CURRENT_STALE_ROLLBACK_IMAGE_ID" = "$EXPECTED_STALE_ROLLBACK_IMAGE_ID" || return $?
1117
+ docker rm ouro-butler-rollback || return $?
1118
+ ;;
1119
+ esac
1120
+ }
1121
+ Stop production, remove only a stopped stale rollback, rename the known-good
1122
+ container, and verify it remains stopped in one explicit preparation guard:
1123
+ if docker stop ouro-butler \
1124
+ && remove_stopped_rollback_if_present "$ROLLBACK_IMAGE_ID" \
1125
+ && docker rename ouro-butler ouro-butler-rollback \
1126
+ && test "$(docker inspect --format '{{.State.Running}}' ouro-butler-rollback)" = false; then
1127
+ :
1128
+ else
1129
+ PRODUCTION_PREPARATION_STATUS=$?
1130
+ if docker container inspect ouro-butler >/dev/null 2>&1; then
1131
+ if docker container inspect ouro-butler-rollback >/dev/null 2>&1; then
1132
+ docker stop ouro-butler-rollback >/dev/null 2>&1 || true
1133
+ CURRENT_ROLLBACK_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-rollback)
1134
+ test "$CURRENT_ROLLBACK_IMAGE_ID" = "$ROLLBACK_IMAGE_ID"
1135
+ docker rm --force ouro-butler-rollback >/dev/null 2>&1 || true
1136
+ fi
1137
+ ! docker container inspect ouro-butler-rollback >/dev/null 2>&1
1138
+ audit_effective ouro-butler "$ROLLBACK_IMAGE_ID"
1139
+ docker start ouro-butler
1140
+ assert_only_running_butler ouro-butler
1141
+ wait_butler_ready ouro-butler
1142
+ enable_butler_autostart
1143
+ elif docker container inspect ouro-butler-rollback >/dev/null 2>&1; then
1144
+ docker stop ouro-butler-rollback >/dev/null 2>&1 || true
1145
+ test "$(docker inspect --format '{{.Image}}' ouro-butler-rollback)" = "$ROLLBACK_IMAGE_ID"
1146
+ docker rename ouro-butler-rollback ouro-butler
1147
+ audit_effective ouro-butler "$ROLLBACK_IMAGE_ID"
1148
+ docker start ouro-butler
1149
+ assert_only_running_butler ouro-butler
1150
+ wait_butler_ready ouro-butler
1151
+ enable_butler_autostart
1152
+ fi
1153
+ (exit "$PRODUCTION_PREPARATION_STATUS")
1154
+ fi
1155
+ Preparation failure therefore either restores the still-named exact production
1156
+ after removing any stale rollback, or renames the exact stopped rollback back;
1157
+ both recoveries re-audit, start, bounded-wait, atomically restore production-only
1158
+ autostart, and propagate the original failure. If neither exact container can
1159
+ be found, the failure propagates with Butler autostart disabled.
1160
+ Put the entire post-rename staging phase in one explicit conditional so
1161
+ `set -eu` cannot bypass rollback at the create, effective-audit, start, or
1162
+ bounded-readiness boundary. Staging uses the exact image ID with no command,
1163
+ environment, port, device, capability, privilege, or extra mount override.
1164
+ A passing staging container is stopped and removed inside the same condition,
1165
+ completing the poller handoff before production creation:
1166
+ if docker create --name ouro-butler-staging --network host --restart unless-stopped --user 10001:10001 \
1167
+ --mount "type=bind,src=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli,dst=/home/ouro/.ouro-cli" \
1168
+ --mount "type=bind,src=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
1169
+ "$IMAGE_ID" \
1170
+ && audit_effective ouro-butler-staging "$IMAGE_ID" \
1171
+ && docker start ouro-butler-staging \
1172
+ && assert_only_running_butler ouro-butler-staging \
1173
+ && wait_butler_ready ouro-butler-staging \
1174
+ && docker stop ouro-butler-staging \
1175
+ && docker rm ouro-butler-staging; then
1176
+ :
1177
+ else
1178
+ STAGING_ACTIVATION_STATUS=$?
1179
+ if docker container inspect ouro-butler-staging >/dev/null 2>&1; then
1180
+ docker stop ouro-butler-staging >/dev/null 2>&1 || true
1181
+ PARTIAL_STAGING_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-staging)
1182
+ test "$PARTIAL_STAGING_IMAGE_ID" = "$IMAGE_ID"
1183
+ docker rm --force ouro-butler-staging >/dev/null 2>&1 || true
1184
+ fi
1185
+ ! docker container inspect ouro-butler-staging >/dev/null 2>&1
1186
+ CURRENT_ROLLBACK_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-rollback)
1187
+ test "$CURRENT_ROLLBACK_IMAGE_ID" = "$ROLLBACK_IMAGE_ID"
1188
+ docker rename ouro-butler-rollback ouro-butler
1189
+ audit_effective ouro-butler "$ROLLBACK_IMAGE_ID"
1190
+ docker start ouro-butler
1191
+ assert_only_running_butler ouro-butler
1192
+ wait_butler_ready ouro-butler
1193
+ enable_butler_autostart
1194
+ (exit "$STAGING_ACTIVATION_STATUS")
1195
+ fi
1196
+ The failure arm safely handles staging that was never created, remains
1197
+ stopped, is running, or exited: it force-removes any partial staging state,
1198
+ verifies the name is absent, restores and re-audits the old production against
1199
+ its exact pre-recorded image ID, starts and bounded-waits it, atomically
1200
+ restores production-only autostart, and propagates the original failure.
1201
+ At no point may production and staging run together against the same Telegram token.
1202
+ Create and activate production from the same exact image ID and exact authority
1203
+ in one explicit conditional so `set -eu` cannot exit before rollback. Only a
1204
+ successful create, effective audit, start, stopped rollback assertion, and
1205
+ bounded readiness wait may enable production autostart. Any failure captures
1206
+ the activation status, safely removes a partially created new production if it
1207
+ exists, restores the stopped rollback container, audits it against its exact
1208
+ old image ID, proves it ready, atomically enables only production autostart,
1209
+ and then propagates the original activation failure:
1210
+ if docker create --name ouro-butler --network host --restart unless-stopped --user 10001:10001 \
1211
+ --mount "type=bind,src=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli,dst=/home/ouro/.ouro-cli" \
1212
+ --mount "type=bind,src=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
1213
+ "$IMAGE_ID" \
1214
+ && audit_effective ouro-butler "$IMAGE_ID" \
1215
+ && docker start ouro-butler \
1216
+ && assert_only_running_butler ouro-butler \
1217
+ && test "$(docker inspect --format '{{.State.Running}}' ouro-butler-rollback)" = false \
1218
+ && wait_butler_ready ouro-butler \
1219
+ && enable_butler_autostart; then
1220
+ :
1221
+ else
1222
+ PRODUCTION_ACTIVATION_STATUS=$?
1223
+ if docker container inspect ouro-butler >/dev/null 2>&1; then
1224
+ docker stop ouro-butler >/dev/null 2>&1 || true
1225
+ PARTIAL_PRODUCTION_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler)
1226
+ test "$PARTIAL_PRODUCTION_IMAGE_ID" = "$IMAGE_ID"
1227
+ docker rm --force ouro-butler >/dev/null 2>&1 || true
1228
+ fi
1229
+ ! docker container inspect ouro-butler >/dev/null 2>&1
1230
+ CURRENT_ROLLBACK_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-rollback)
1231
+ test "$CURRENT_ROLLBACK_IMAGE_ID" = "$ROLLBACK_IMAGE_ID"
1232
+ docker rename ouro-butler-rollback ouro-butler
1233
+ audit_effective ouro-butler "$ROLLBACK_IMAGE_ID"
1234
+ docker start ouro-butler
1235
+ assert_only_running_butler ouro-butler
1236
+ wait_butler_ready ouro-butler
1237
+ enable_butler_autostart
1238
+ (exit "$PRODUCTION_ACTIVATION_STATUS")
1239
+ fi
1240
+ Keep ouro-butler-rollback stopped until the new production container is proven
1241
+ or the explicit rollback arm restores it.
1242
+ Never create a container from the mutable lookup tag.
1243
+
1244
+ Backup:
1245
+ Stop ouro-butler, then snapshot both of these directories together:
1246
+ /mnt/user/appdata/ouro-butler/runtime/.ouro-cli
1247
+ /mnt/user/appdata/ouro-butler/agent/sanctuary.ouro
1248
+ A routine backup must not contain container-credentials.json or
1249
+ container-credentials.json.consuming. If either exists, credential migration
1250
+ is pending or failed and must be reconciled before taking the backup.
1251
+
1252
+ Restore:
1253
+ Set BACKUP_ROOT to the exact verified snapshot containing `runtime/.ouro-cli`
1254
+ and `agent/sanctuary.ouro`, and set IMAGE_ID to its recorded local image ID.
1255
+ Before any autostart, root, or container mutation, run the nounset-safe input,
1256
+ backup-root, image, and topology preflight. It requires a nonempty canonical
1257
+ absolute BACKUP_ROOT (not /), both exact required directories, an exact local
1258
+ sha256 image ID, canonical production as the only running Butler poller, no
1259
+ staging or rollback, and at most one exact stopped legacy-evidence container:
1260
+ if assert_restore_preflight; then
1261
+ :
1262
+ else
1263
+ RESTORE_PREFLIGHT_STATUS=$?
1264
+ (exit "$RESTORE_PREFLIGHT_STATUS")
1265
+ fi
1266
+ Guard the atomic autostart disable before stopping or removing any Butler
1267
+ container. Failure propagates while the existing production remains untouched:
1268
+ if disable_butler_autostart; then
1269
+ :
1270
+ else
1271
+ RESTORE_AUTOSTART_DISABLE_STATUS=$?
1272
+ (exit "$RESTORE_AUTOSTART_DISABLE_STATUS")
1273
+ fi
1274
+ Stop and remove only ouro-butler, restore both roots without stale files,
1275
+ restore exact ownership, validate the image, and create/audit/start/bounded-wait
1276
+ the restored production inside one explicit condition. The initial tolerant
1277
+ stop plus inspected force-removal safely handles an already absent or stopped
1278
+ container:
1279
+ if { docker stop ouro-butler >/dev/null 2>&1 || true; } \
1280
+ && {
1281
+ if docker container inspect ouro-butler >/dev/null 2>&1; then
1282
+ docker rm --force ouro-butler
1283
+ else
1284
+ :
1285
+ fi
1286
+ } \
1287
+ && ! docker container inspect ouro-butler >/dev/null 2>&1 \
1288
+ && rsync -a --delete "$BACKUP_ROOT/runtime/.ouro-cli/" /mnt/user/appdata/ouro-butler/runtime/.ouro-cli/ \
1289
+ && rsync -a --delete "$BACKUP_ROOT/agent/sanctuary.ouro/" /mnt/user/appdata/ouro-butler/agent/sanctuary.ouro/ \
1290
+ && chown -R 10001:10001 /mnt/user/appdata/ouro-butler/runtime/.ouro-cli /mnt/user/appdata/ouro-butler/agent/sanctuary.ouro \
1291
+ && validate_sanctuary_roots /mnt/user/appdata/ouro-butler/runtime/.ouro-cli /mnt/user/appdata/ouro-butler/agent/sanctuary.ouro \
1292
+ && docker image inspect "$IMAGE_ID" >/dev/null \
1293
+ && docker create --name ouro-butler --network host --restart unless-stopped --user 10001:10001 \
1294
+ --mount "type=bind,src=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli,dst=/home/ouro/.ouro-cli" \
1295
+ --mount "type=bind,src=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
1296
+ "$IMAGE_ID" \
1297
+ && audit_effective ouro-butler "$IMAGE_ID" \
1298
+ && docker start ouro-butler \
1299
+ && assert_only_running_butler ouro-butler \
1300
+ && wait_butler_ready ouro-butler \
1301
+ && enable_butler_autostart; then
1302
+ :
1303
+ else
1304
+ RESTORE_ACTIVATION_STATUS=$?
1305
+ if docker container inspect ouro-butler >/dev/null 2>&1; then
1306
+ docker stop ouro-butler >/dev/null 2>&1 || true
1307
+ PARTIAL_RESTORE_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler)
1308
+ test "$PARTIAL_RESTORE_IMAGE_ID" = "$IMAGE_ID"
1309
+ docker rm --force ouro-butler >/dev/null 2>&1 || true
1310
+ fi
1311
+ ! docker container inspect ouro-butler >/dev/null 2>&1
1312
+ (exit "$RESTORE_ACTIVATION_STATUS")
1313
+ fi
1314
+ A restore has no retained old container or pre-restore data root to roll back
1315
+ to. Any stop/remove, data replacement, ownership, image validation, create,
1316
+ audit, start, or readiness failure therefore reaches the same cleanup arm,
1317
+ leaves all Butler autostart entries disabled, and propagates the captured
1318
+ failure for operator repair or a verified restore retry.
1319
+
1320
+ Credential recovery:
1321
+ The one canonical Telegram identity is display name `Mendelow Cloud Butler`,
1322
+ username `MendelowCloudButlerBot`, numeric bot ID `8541786263`. Treat any
1323
+ different display name, username, numeric ID, or fallback handle as a hard
1324
+ preflight failure; do not start polling or send a test message.
1325
+ Run `bootstrap_sanctuary_vault "$IMAGE_ID"` interactively before installing
1326
+ credentials. It uses only fresh `--rm` containers from that exact image as
1327
+ UID/GID 10001 with the canonical two binds; create/unlock is the sole `-it`
1328
+ action so the master secret remains on the hidden terminal prompt.
1329
+ Its first read-only `vault status` is authoritative: it runs `vault create`
1330
+ only when the locator is absent, runs `vault unlock` only when the locator
1331
+ exists but local unlock is missing, and does not prompt when local unlock is
1332
+ already available. It then requires the configured locator, available local
1333
+ unlock, and successful auth verification. Never guess from a failed status
1334
+ command.
1335
+ Initial legacy adoption passes the exact legacy envelope path as the helper's
1336
+ second argument. After vault availability, the helper validates and atomically
1337
+ copies that envelope into the canonical runtime root, imports it with a fresh
1338
+ same-image one-shot container, and requires both canonical source and claim to
1339
+ be absent before provider readiness. The exact legacy source remains untouched
1340
+ as rollback evidence until canonical acceptance completes.
1341
+ Restore or unlock the Sanctuary agent vault, then run provider refresh.
1342
+ /mnt/user/appdata/ouro-butler/runtime/.ouro-cli/container-credentials.json
1343
+ exists only for a one-time migration: if
1344
+ used, install it atomically as root with ownership 10001:10001 and mode 0600.
1345
+ Startup atomically claims it as container-credentials.json.consuming and
1346
+ writes every credential class into the unlocked Sanctuary vault before deleting the claimed envelope.
1347
+ Only then does it refresh the daemon's in-memory credentials.
1348
+ If validation or any vault write fails, startup fails closed and preserves
1349
+ container-credentials.json.consuming for the next startup to reconcile.
1350
+ Restore or create/unlock the configured agent vault, then restart the same
1351
+ reviewed image and let it retry the preserved claim. If both the source and
1352
+ claimed envelope exist and they are safe regular 0600 files owned by the
1353
+ runtime user, startup resumes automatically only when they are byte-for-byte identical:
1354
+ it durably removes the redundant unclaimed source and continues the existing claim.
1355
+ If they differ, the repair is human-required: stop the Butler, securely compare and quarantine
1356
+ the two envelopes, then restore exactly one reviewed envelope at the source path.
1357
+ Never print either envelope's contents or place them in logs or command arguments.
1358
+ After successful import, both files
1359
+ are absent and the vault is the only credential source of truth.
1360
+ Never print or place credential values in logs, templates, command arguments,
1361
+ backups, or this runbook.
1362
+
1363
+ Packaged deployment-target containment gates:
1364
+ Unit 16 is fixed to the `staging` profile and therefore targets only
1365
+ `ouro-butler-staging`; it does not require `ouro-butler` to exist. Before the
1366
+ broker starts, the packaged deployment auditor captures all present canonical
1367
+ production/staging/rollback identities in one Docker inspect, verifies the
1368
+ target image, `unless-stopped`, host networking, matching GraphQL and durable
1369
+ file autostart identity/state for every present canonical container,
1370
+ and exactly one running Butler, then repeats the canonical snapshot to reject
1371
+ races. It binds the target PID and exact Docker cgroup-v2 path to the inspected
1372
+ container ID; Unit 16 carries that immutable ID into every launcher and broker
1373
+ Docker operation and binds it to the GraphQL PrefixedID suffix. It scans every
1374
+ cgroup process and requires stable before/after process, owned-socket, and
1375
+ listener inventories. Between the two canonical topology captures, it verifies
1376
+ the exact immutable-ID target is running and unpaused, pauses that ID without
1377
+ changing restart or autostart state, and performs every cgroup, all-thread
1378
+ descriptor, TCP, UDP, and Unix observation inside that one quiesced window,
1379
+ including two matching complete terminal snapshots; nonconvergence fails
1380
+ closed after eight attempts. It always makes bounded exact-ID unpause attempts,
1381
+ verifies the same ID and PID resumed their original running, unpaused state,
1382
+ and only then performs the final full-profile topology capture. It
1383
+ rejects every owned UDP listener and every externally reachable owned TCP listener. Only loopback
1384
+ Mailbox port 6876 plus stream-listening endpoints at the fixed daemon and
1385
+ acceptance Unix control paths are permitted; all other named Unix endpoint
1386
+ types (including datagrams) fail closed. Inherited descriptors for the same
1387
+ socket inode are deduplicated, while unknown loopback ports, wildcard/host-address
1388
+ listeners, process/socket/listener drift, or ambiguous ownership fail closed.
1389
+ Unit 18 uses the separately packaged fixed final command, after rollback has
1390
+ been retained stopped:
1391
+ UNIT18_TARGET_TMP=$(mktemp /run/sanctuary-unit18-target-audit.sh.XXXXXX)
1392
+ /usr/bin/timeout -s KILL 20 /usr/bin/docker run --rm --pull=never --network none \
1393
+ --entrypoint /bin/cat "$IMAGE_ID" /opt/ouro/deploy/unraid/sanctuary-unit18-target-audit.sh >"$UNIT18_TARGET_TMP"
1394
+ chmod 0500 "$UNIT18_TARGET_TMP"
1395
+ "$UNIT18_TARGET_TMP" "$IMAGE_ID"
1396
+ rm -f -- "$UNIT18_TARGET_TMP"
1397
+ Neither packaged command accepts a container name or an open-ended profile.
1398
+
1399
+ Packaged Unit 16 acceptance execution:
1400
+ Use only the launcher packaged in the exact reviewed image. Install it without
1401
+ network access, then create the two private roots with the runtime UID/GID:
1402
+ UNIT16_ROOT=/mnt/user/appdata/ouro-butler/acceptance
1403
+ install -d -m 0700 -o 10001 -g 10001 "$UNIT16_ROOT/configs" "$UNIT16_ROOT/evidence"
1404
+ UNIT16_LAUNCHER_TMP=$(mktemp "$UNIT16_ROOT/sanctuary-unit16-run.sh.tmp.XXXXXX")
1405
+ /usr/bin/timeout -s KILL 20 /usr/bin/docker run --rm --pull=never --network none \
1406
+ --entrypoint /bin/cat "$IMAGE_ID" /opt/ouro/deploy/unraid/sanctuary-unit16-run.sh >"$UNIT16_LAUNCHER_TMP"
1407
+ install -m 0755 -o root -g root "$UNIT16_LAUNCHER_TMP" "$UNIT16_ROOT/sanctuary-unit16-run.sh"
1408
+ rm -f -- "$UNIT16_LAUNCHER_TMP"
1409
+ Never hand-author a Unit 16 config. Materialize it from the exact image, then
1410
+ execute it in the order below. Before every execution the launcher regenerates
1411
+ the config from the packaged fixed contract and requires byte-for-byte equality.
1412
+ The cursor snapshot is deliberately materialized and executed twice around the
1413
+ live scenario. Telegram bootstrap reads the new bot token from host file
1414
+ descriptor 3; callback injection reads the reviewed saved callback-update JSON
1415
+ from the same descriptor. The launcher explicitly maps host fd 3 to Docker
1416
+ stdin and then to in-container fd 3 only for those two commands. Neither value
1417
+ belongs in argv, shell history, a config file, or an unrelated command's stdin.
1418
+ Define this Bash helper in the root shell. It disables terminal echo while
1419
+ reading the token, opens an anonymous descriptor for the launcher, and unsets
1420
+ the short-lived shell value on either launcher success or failure:
1421
+ run_unit16_telegram_bootstrap() {
1422
+ local UNIT16_BOT_TOKEN UNIT16_BOT_STATUS
1423
+ printf 'Telegram bot token: ' >&2
1424
+ IFS= read -r -s UNIT16_BOT_TOKEN || return $?
1425
+ printf '\n' >&2
1426
+ if "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" telegram-bootstrap telegram-bootstrap.json \
1427
+ 3< <(printf '%s\n' "$UNIT16_BOT_TOKEN"); then
1428
+ UNIT16_BOT_STATUS=0
1429
+ else
1430
+ UNIT16_BOT_STATUS=$?
1431
+ fi
1432
+ unset UNIT16_BOT_TOKEN
1433
+ return "$UNIT16_BOT_STATUS"
1434
+ }
1435
+ Stage the reviewed callback JSON at the fixed path below in the root-owned
1436
+ tmpfs inbox, then use this single fail-closed helper. It opens the input once,
1437
+ validates the opened descriptor and its original path refer to the same
1438
+ root-owned mode-0600 regular file, and invokes the launcher only afterward.
1439
+ Success overwrites, fsyncs, and unlinks the raw input. Any failure allocates a
1440
+ collision-free quarantine file atomically, copies and fsyncs the input into it,
1441
+ locks it to mode 000, then overwrites and removes the tmpfs source;
1442
+ no raw callback update remains loose in `/root` or the inbox.
1443
+ UNIT16_CALLBACK_INBOX=/run/ouro-unit16-callback-input
1444
+ UNIT16_CALLBACK_FILE=$UNIT16_CALLBACK_INBOX/callback-update.json
1445
+ UNIT16_CALLBACK_QUARANTINE_ROOT=$UNIT16_ROOT/callback-quarantine
1446
+ install -d -m 0700 -o root -g root "$UNIT16_CALLBACK_INBOX" "$UNIT16_CALLBACK_QUARANTINE_ROOT"
1447
+ run_unit16_callback_inject() {
1448
+ (
1449
+ UNIT16_CALLBACK_VALIDATED=no
1450
+ UNIT16_CALLBACK_STATUS=1
1451
+ unit16_callback_cleanup() {
1452
+ UNIT16_CALLBACK_STATUS=$?
1453
+ trap - EXIT HUP INT TERM
1454
+ if test -e "$UNIT16_CALLBACK_FILE" || test -L "$UNIT16_CALLBACK_FILE"; then
1455
+ if test "$UNIT16_CALLBACK_STATUS" -eq 0 && test "$UNIT16_CALLBACK_VALIDATED" = yes; then
1456
+ if ! truncate -s 0 /proc/self/fd/3 || ! sync -f /proc/self/fd/3 \
1457
+ || ! rm -f -- "$UNIT16_CALLBACK_FILE" || ! sync -f "$UNIT16_CALLBACK_INBOX"; then
1458
+ UNIT16_CALLBACK_STATUS=1
1459
+ fi
1460
+ elif test -f "$UNIT16_CALLBACK_FILE" && test ! -L "$UNIT16_CALLBACK_FILE"; then
1461
+ UNIT16_CALLBACK_QUARANTINE_FILE=$(mktemp "$UNIT16_CALLBACK_QUARANTINE_ROOT/failed.XXXXXX") || UNIT16_CALLBACK_QUARANTINE_FILE=
1462
+ if test -n "$UNIT16_CALLBACK_QUARANTINE_FILE" \
1463
+ && chmod 0600 "$UNIT16_CALLBACK_QUARANTINE_FILE" \
1464
+ && cp -- "$UNIT16_CALLBACK_FILE" "$UNIT16_CALLBACK_QUARANTINE_FILE" \
1465
+ && sync -f "$UNIT16_CALLBACK_QUARANTINE_FILE" \
1466
+ && chmod 000 "$UNIT16_CALLBACK_QUARANTINE_FILE" \
1467
+ && sync -f "$UNIT16_CALLBACK_QUARANTINE_ROOT"; then
1468
+ :
1469
+ else
1470
+ test -z "${UNIT16_CALLBACK_QUARANTINE_FILE-}" || rm -f -- "$UNIT16_CALLBACK_QUARANTINE_FILE"
1471
+ UNIT16_CALLBACK_STATUS=1
1472
+ fi
1473
+ if ! truncate -s 0 "$UNIT16_CALLBACK_FILE" || ! sync -f "$UNIT16_CALLBACK_FILE" \
1474
+ || ! rm -f -- "$UNIT16_CALLBACK_FILE" || ! sync -f "$UNIT16_CALLBACK_INBOX"; then
1475
+ UNIT16_CALLBACK_STATUS=1
1476
+ fi
1477
+ else
1478
+ rm -f -- "$UNIT16_CALLBACK_FILE" || UNIT16_CALLBACK_STATUS=1
1479
+ sync -f "$UNIT16_CALLBACK_INBOX" || UNIT16_CALLBACK_STATUS=1
1480
+ fi
1481
+ fi
1482
+ exec 3<&-
1483
+ exit "$UNIT16_CALLBACK_STATUS"
1484
+ }
1485
+ trap unit16_callback_cleanup EXIT
1486
+ trap 'exit 129' HUP
1487
+ trap 'exit 130' INT
1488
+ trap 'exit 143' TERM
1489
+ test -d "$UNIT16_CALLBACK_INBOX" && test ! -L "$UNIT16_CALLBACK_INBOX" || exit 1
1490
+ test "$(stat -c '%F %u:%g %a' "$UNIT16_CALLBACK_INBOX")" = "directory 0:0 700" || exit 1
1491
+ test -d "$UNIT16_CALLBACK_QUARANTINE_ROOT" && test ! -L "$UNIT16_CALLBACK_QUARANTINE_ROOT" || exit 1
1492
+ test "$(stat -c '%F %u:%g %a' "$UNIT16_CALLBACK_QUARANTINE_ROOT")" = "directory 0:0 700" || exit 1
1493
+ test -f "$UNIT16_CALLBACK_FILE" && test ! -L "$UNIT16_CALLBACK_FILE" || exit 1
1494
+ exec 3<"$UNIT16_CALLBACK_FILE"
1495
+ test "$(stat -Lc '%F' /proc/self/fd/3)" = "regular file" || exit 1
1496
+ test "$(stat -c '%d:%i' "$UNIT16_CALLBACK_FILE")" = "$(stat -Lc '%d:%i' /proc/self/fd/3)" || exit 1
1497
+ UNIT16_CALLBACK_VALIDATED=yes
1498
+ test "$(stat -Lc '%F %u:%g %a' /proc/self/fd/3)" = "regular file 0:0 600" || exit 1
1499
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" callback-inject callback-inject.json 3<&3
1500
+ )
1501
+ }
1502
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" materialize telegram-bootstrap
1503
+ run_unit16_telegram_bootstrap
1504
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" materialize cursor-snapshot before
1505
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" cursor-snapshot cursor-snapshot.json
1506
+ # Perform the live scenario whose cursor movement is being measured.
1507
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" materialize cursor-snapshot after
1508
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" cursor-snapshot cursor-snapshot.json
1509
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" materialize cursor-delta
1510
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" cursor-delta cursor-delta.json
1511
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" materialize callback-inject
1512
+ run_unit16_callback_inject
1513
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" materialize unraid-key-rotate
1514
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" unraid-key-rotate unraid-key-rotate.json
1515
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" materialize reboot-request
1516
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" reboot-request reboot-request.json
1517
+ # The preceding command captures and seals preflight evidence before it asks
1518
+ # the broker to stage the reboot, then seals the requested-phase evidence and
1519
+ # fsyncs the requested checkpoint before invoking the host reboot. Reconnect
1520
+ # only after Unraid and Docker are ready.
1521
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" materialize reboot-resume
1522
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" reboot-resume reboot-resume.json
1523
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" materialize evidence-snapshot
1524
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" evidence-snapshot evidence-snapshot.json
1525
+ # reboot-resume seals the changed boot identity and recovery milestones.
1526
+ # evidence-snapshot then runs the remaining scenarios sequentially with a
1527
+ # 72-minute aggregate bound; each completed scenario records provenance at
1528
+ # capture time and always clears its public gate, private marker, and receipt.
1529
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" materialize evidence-bundle-index
1530
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" evidence-bundle-index evidence-bundle-index.json
1531
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" materialize evidence-bundle-verify
1532
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" evidence-bundle-verify evidence-bundle-verify.json
1533
+ Each execution revalidates the immutable image and the production container's
1534
+ exact image ID. The main one-shot gets a read-only root filesystem, one writable
1535
+ evidence mount, narrowly selected runtime/bundle modes, and individual read-only
1536
+ image/container/health/boot fact files. Host-only operations cross an ephemeral
1537
+ root-owned private Unix socket (root:10001 mode 0660) to a root broker extracted
1538
+ from the same exact image. The broker accepts only fixed Unraid inventory/create/
1539
+ exact-revoke/rejection operations, exact fixed-target snapshots, and a
1540
+ two-phase reboot reservation/final commit. Reservation drains queued owner
1541
+ mutations and rejects new ones; after the requested checkpoint is fsynced, the
1542
+ broker repeats the array/parity/mover/durable-health preflight and invokes the
1543
+ fixed host reboot itself exactly once. The Unit 16 broker inspects only the
1544
+ deployment profile's attested immutable container ID (staging is
1545
+ `ouro-butler-staging`), requires its immutable image ID, writes that exact typed/redacted
1546
+ snapshot before accepting requests, and exposes a nonnegative Docker restart
1547
+ count. Both initial and refreshed snapshots share the same exact schema. The
1548
+ broker derives `autostartExact` from both the Unraid GraphQL `autoStart` value
1549
+ and exactly one staging entry in `/var/lib/docker/unraid-autostart`, derives
1550
+ `updaterDisabled` from `/opt/ouro/container-runtime.json` inside the exact image,
1551
+ and derives `vaultUnlocked`/`manualAuthRequired` from a bounded live Sanctuary
1552
+ vault-status command only when its non-secret summary proves the required
1553
+ Telegram runtime fields and both configured provider records were freshly read.
1554
+ Scenario handles remain private to the scenario adapter. The main one-shot
1555
+ never receives the Docker socket, Unraid key directory, or a host-root mount.
1556
+ Telegram bootstrap additionally brackets its one-shot with a host-controlled
1557
+ poller quiescence guard: it verifies the exact healthy staging container,
1558
+ assumes recovery responsibility before attempting the stop, stops it with a
1559
+ 30-second grace bound, proves it is stopped, and mounts a
1560
+ root-owned typed zero-poller fact. Its exit/signal trap restarts that same exact
1561
+ container and waits up to 120 seconds for healthy recovery on both success and
1562
+ failure. It never reads or changes Unraid autostart configuration. Every command
1563
+ also receives a freshly generated, redacted typed container-inspect snapshot;
1564
+ raw container environment or credential values are never captured.
1565
+ Evidence-snapshot keeps the bundle mount read-only and overlays only the exact
1566
+ canonical `state/acceptance` directory as writable. It first stops the exact
1567
+ healthy staging container under recovery responsibility, then opens the
1568
+ directory with `O_DIRECTORY|O_NOFOLLOW` and bind-mounts from the inherited fd
1569
+ while no Sanctuary UID process is running. The launcher bind-pins that inode
1570
+ behind a root-only alias and back onto the canonical path against rename swaps,
1571
+ restarts the same exact image healthy, and compares the alias, canonical path,
1572
+ and staging container's inode before and after capture. Cleanup unmounts the
1573
+ canonical pin and then the alias. The staging daemon therefore sees the same
1574
+ inode used by the one-shot for marker correlation.
1575
+
1576
+ Audit and safety verification:
1577
+ Inspect AgentBundles/sanctuary.ouro/state/approvals for durable approval and
1578
+ restart-attempt receipts. Confirm no Docker socket/device/host-root mounts and
1579
+ no published ports with docker inspect. Confirm Config.Image equals the exact
1580
+ reviewed local image ID, not the build tag. The read key must reject Docker
1581
+ stop and restart mutations; only the separate write key may perform the one
1582
+ typed approved restart action.
1583
+ The packaged `unraid-key-rotate` command is the only canonical key-rotation
1584
+ authority. It inventories the two occupied canonical names by exact immutable
1585
+ ID, creates collision-safe `Butler RO Rotation <suffix>` and
1586
+ `Butler RW Rotation <suffix>` keys, stores and capability-probes both through
1587
+ the Sanctuary machine vault, and requires an exact four-key inventory. It then
1588
+ revokes both old IDs and proves each old credential receives a 401 or 403.
1589
+ Only after an exact inventory contains the temporary pair alone does it create,
1590
+ store, and probe the canonical `Butler RO` and `Butler RW` pair. It requires an
1591
+ exact four-key temporary-plus-canonical inventory, revokes and rejection-probes
1592
+ both temporary IDs, and finally requires exactly the canonical pair. Every
1593
+ unexpected key, duplicate, malformed permission set, role, name, inventory
1594
+ delta, or probe response fails closed.
1595
+
1596
+ Record only IDs, names, and permission sets in evidence; never raw key values.
1597
+ Raw credentials must not appear in argv, shell history, stdout, logs, or
1598
+ acceptance evidence. They may cross only the ephemeral private Unit 16 Unix
1599
+ socket in process memory. The narrow revocation-retry recovery records under
1600
+ `/mnt/user/appdata/ouro-butler/acceptance/revoked-key-proof` are the sole file
1601
+ exception: they are root-owned mode 0600 beneath a root-owned mode 0700
1602
+ directory, excluded from backup/evidence, streamed only on standard input to
1603
+ the bounded rejection probe, retained across failed retries, and durably
1604
+ deleted only after the exact authentication rejection is validated. Never
1605
+ substitute names for IDs when revoking keys.