@ouro.bot/cli 0.1.0-alpha.88 → 0.1.0-alpha.881

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 (671) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +154 -23
  3. package/RepairGuide.ouro/agent.json +5 -0
  4. package/RepairGuide.ouro/psyche/IDENTITY.md +19 -0
  5. package/RepairGuide.ouro/psyche/SOUL.md +55 -0
  6. package/RepairGuide.ouro/skills/diagnose-broken-remote.md +63 -0
  7. package/RepairGuide.ouro/skills/diagnose-stacked-typed-issues.md +35 -0
  8. package/RepairGuide.ouro/skills/diagnose-sync-blocked.md +54 -0
  9. package/RepairGuide.ouro/skills/diagnose-vault-expired.md +60 -0
  10. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +4 -2
  11. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +2 -2
  12. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
  13. package/assets/bluebubbles-host +264 -0
  14. package/assets/sanctuary-host-launcher.sh +16 -0
  15. package/changelog.json +5607 -16
  16. package/deploy/unraid/Dockerfile +58 -0
  17. package/deploy/unraid/README.txt +2995 -0
  18. package/deploy/unraid/audit-container-spec.sh +4 -0
  19. package/deploy/unraid/container-runtime.json +1 -0
  20. package/deploy/unraid/docker-man-template-transaction.mjs +711 -0
  21. package/deploy/unraid/docker-man-template-xml.cjs +105 -0
  22. package/deploy/unraid/migrate-sanctuary-bundle.mjs +60 -0
  23. package/deploy/unraid/ouro-events/bootstrap-spool.sh +92 -0
  24. package/deploy/unraid/ouro-events/emit-event.mjs +310 -0
  25. package/deploy/unraid/ouro-events/emit-usenet-event.sh +54 -0
  26. package/deploy/unraid/ouro-events/install-usenet-guard.sh +435 -0
  27. package/deploy/unraid/ouro-events/usenet-health.sh +176 -0
  28. package/deploy/unraid/sanctuary-acceptance-adapter.sh +43 -0
  29. package/deploy/unraid/sanctuary-acceptance-contract.json +198 -0
  30. package/deploy/unraid/sanctuary-acceptance-harness.sh +23 -0
  31. package/deploy/unraid/sanctuary-authority-installation.json +36 -0
  32. package/deploy/unraid/sanctuary-authority-service.sh +30 -0
  33. package/deploy/unraid/sanctuary-butler-upgrade.mjs +1197 -0
  34. package/deploy/unraid/sanctuary-deployment-target.mjs +710 -0
  35. package/deploy/unraid/sanctuary-replay-gate.mjs +1127 -0
  36. package/deploy/unraid/sanctuary-safe-rename.py +24 -0
  37. package/deploy/unraid/sanctuary-unit16-host-broker.mjs +2085 -0
  38. package/deploy/unraid/sanctuary-unit16-run.sh +560 -0
  39. package/deploy/unraid/sanctuary-unit18-target-audit.sh +27 -0
  40. package/deploy/unraid/sanctuary.ouro/agent.json +66 -0
  41. package/deploy/unraid/sanctuary.ouro/arc/README.md +3 -0
  42. package/deploy/unraid/sanctuary.ouro/awaiting/house-care-sweep.md +17 -0
  43. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +5 -0
  44. package/deploy/unraid/sanctuary.ouro/habits/sanctuary-health.md +8 -0
  45. package/deploy/unraid/sanctuary.ouro/mcp/media-mcp.mjs +2231 -0
  46. package/deploy/unraid/sanctuary.ouro/provider-readiness.json +11 -0
  47. package/deploy/unraid/sanctuary.ouro/psyche/ASPIRATIONS.md +5 -0
  48. package/deploy/unraid/sanctuary.ouro/psyche/IDENTITY.md +5 -0
  49. package/deploy/unraid/sanctuary.ouro/psyche/LORE.md +27 -0
  50. package/deploy/unraid/sanctuary.ouro/psyche/SOUL.md +27 -0
  51. package/deploy/unraid/sanctuary.ouro/psyche/TACIT.md +22 -0
  52. package/deploy/unraid/sanctuary.ouro/state/policy/steward.json +7 -0
  53. package/deploy/unraid/sanctuary.ouro/tool-profiles.json +232 -0
  54. package/deploy/unraid/sanctuary.xml +29 -0
  55. package/dist/a2a/card.js +57 -0
  56. package/dist/a2a/client.js +238 -0
  57. package/dist/a2a/config.js +50 -0
  58. package/dist/a2a/delegated-command.js +151 -0
  59. package/dist/a2a/delegation-stores.js +56 -0
  60. package/dist/a2a/did-resolution.js +93 -0
  61. package/dist/a2a/escalation-grants.js +122 -0
  62. package/dist/a2a/escalation-wiring.js +60 -0
  63. package/dist/a2a/identity.js +204 -0
  64. package/dist/a2a/inbound-share.js +110 -0
  65. package/dist/a2a/mission-result-wire.js +196 -0
  66. package/dist/a2a/onboarding.js +133 -0
  67. package/dist/a2a/outbox-client.js +57 -0
  68. package/dist/a2a/outbox-store.js +188 -0
  69. package/dist/a2a/outbox-wire.js +95 -0
  70. package/dist/a2a/pin-store.js +132 -0
  71. package/dist/a2a/replay-harness.js +175 -0
  72. package/dist/a2a/resolution-proof.js +53 -0
  73. package/dist/a2a/sealed-chat.js +113 -0
  74. package/dist/a2a/seen-ledger.js +120 -0
  75. package/dist/a2a/server.js +766 -0
  76. package/dist/a2a/task-store.js +69 -0
  77. package/dist/a2a/transport.js +45 -0
  78. package/dist/a2a/trusted-files.js +98 -0
  79. package/dist/a2a/types.js +3 -0
  80. package/dist/arc/attention-types.js +8 -0
  81. package/dist/arc/cares.js +360 -0
  82. package/dist/arc/episodes.js +118 -0
  83. package/dist/arc/evolution.js +490 -0
  84. package/dist/arc/flight-recorder.js +1034 -0
  85. package/dist/arc/intentions.js +134 -0
  86. package/dist/arc/json-store.js +117 -0
  87. package/dist/arc/obligations.js +386 -0
  88. package/dist/arc/packets.js +336 -0
  89. package/dist/arc/presence.js +185 -0
  90. package/dist/arc/task-lifecycle.js +57 -0
  91. package/dist/commerce/store.js +755 -0
  92. package/dist/commerce/types.js +3 -0
  93. package/dist/heart/active-work.js +798 -40
  94. package/dist/heart/agent-entry.js +252 -3
  95. package/dist/heart/approval-files.js +113 -0
  96. package/dist/heart/approval-store.js +960 -0
  97. package/dist/heart/attachments/image-normalize.js +194 -0
  98. package/dist/heart/attachments/materialize.js +97 -0
  99. package/dist/heart/attachments/originals.js +88 -0
  100. package/dist/heart/attachments/render.js +29 -0
  101. package/dist/heart/attachments/sources/bluebubbles.js +156 -0
  102. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  103. package/dist/heart/attachments/sources/index.js +18 -0
  104. package/dist/heart/attachments/sources/telegram.js +71 -0
  105. package/dist/heart/attachments/store.js +132 -0
  106. package/dist/heart/attachments/types.js +93 -0
  107. package/dist/heart/auth/auth-flow.js +495 -0
  108. package/dist/heart/autonomy-budget.js +478 -0
  109. package/dist/heart/awaiting/a2a-await-delivery.js +109 -0
  110. package/dist/heart/awaiting/await-alert.js +152 -0
  111. package/dist/heart/awaiting/await-expiry.js +143 -0
  112. package/dist/heart/awaiting/await-loader.js +91 -0
  113. package/dist/heart/awaiting/await-parser.js +152 -0
  114. package/dist/heart/awaiting/await-runtime-state.js +111 -0
  115. package/dist/heart/awaiting/await-scheduler.js +382 -0
  116. package/dist/heart/background-operations.js +281 -0
  117. package/dist/heart/bridges/manager.js +137 -17
  118. package/dist/heart/bridges/store.js +14 -2
  119. package/dist/heart/bundle-state.js +168 -0
  120. package/dist/heart/commitments.js +44 -18
  121. package/dist/heart/config-registry.js +331 -0
  122. package/dist/heart/config.js +174 -131
  123. package/dist/heart/context-loss-gauntlet.js +387 -0
  124. package/dist/heart/context-loss-sentinel.js +1157 -0
  125. package/dist/heart/core.js +2286 -580
  126. package/dist/heart/cross-chat-delivery.js +9 -22
  127. package/dist/heart/daemon/agent-config-check.js +451 -0
  128. package/dist/heart/daemon/agent-discovery.js +185 -3
  129. package/dist/heart/daemon/agent-service.js +542 -0
  130. package/dist/heart/daemon/agentic-repair.js +547 -0
  131. package/dist/heart/daemon/await-private-wake.js +59 -0
  132. package/dist/heart/daemon/bluebubbles-cli-integration.js +71 -0
  133. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  134. package/dist/heart/daemon/bluebubbles-host-protocol.js +433 -0
  135. package/dist/heart/daemon/bluebubbles-host.js +273 -0
  136. package/dist/heart/daemon/boot-sync-probe.js +197 -0
  137. package/dist/heart/daemon/cadence.js +180 -0
  138. package/dist/heart/daemon/cli-defaults.js +854 -0
  139. package/dist/heart/daemon/cli-desk.js +322 -0
  140. package/dist/heart/daemon/cli-exec.js +8951 -0
  141. package/dist/heart/daemon/cli-help.js +716 -0
  142. package/dist/heart/daemon/cli-parse.js +2941 -0
  143. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  144. package/dist/heart/daemon/cli-render.js +777 -0
  145. package/dist/heart/daemon/cli-types.js +8 -0
  146. package/dist/heart/daemon/connect-bay.js +323 -0
  147. package/dist/heart/daemon/container-credential-bootstrap.js +273 -0
  148. package/dist/heart/daemon/container-healthcheck.js +112 -0
  149. package/dist/heart/daemon/container-runtime.js +97 -0
  150. package/dist/heart/daemon/container-spec-auditor-main.js +171 -0
  151. package/dist/heart/daemon/container-spec-auditor.js +232 -0
  152. package/dist/heart/daemon/daemon-bootstrap-startup.js +115 -0
  153. package/dist/heart/daemon/daemon-cli.js +29 -2349
  154. package/dist/heart/daemon/daemon-entry.js +932 -11
  155. package/dist/heart/daemon/daemon-health.js +186 -0
  156. package/dist/heart/daemon/daemon-rollup.js +57 -0
  157. package/dist/heart/daemon/daemon-runtime-sync.js +88 -13
  158. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  159. package/dist/heart/daemon/daemon.js +2084 -105
  160. package/dist/heart/daemon/dns-workflow.js +394 -0
  161. package/dist/heart/daemon/doctor-types.js +8 -0
  162. package/dist/heart/daemon/doctor.js +1755 -0
  163. package/dist/heart/daemon/freshness.js +345 -0
  164. package/dist/heart/daemon/habit-private-wake.js +61 -0
  165. package/dist/heart/daemon/health-monitor.js +142 -11
  166. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  167. package/dist/heart/daemon/hooks/bundle-meta.js +135 -1
  168. package/dist/heart/daemon/http-health-probe.js +80 -0
  169. package/dist/heart/daemon/human-command-screens.js +234 -0
  170. package/dist/heart/daemon/human-readiness.js +114 -0
  171. package/dist/heart/daemon/inner-status.js +78 -0
  172. package/dist/heart/daemon/interactive-repair.js +394 -0
  173. package/dist/heart/daemon/launchd.js +37 -8
  174. package/dist/heart/daemon/log-tailer.js +79 -10
  175. package/dist/heart/daemon/logs-prune.js +132 -0
  176. package/dist/heart/daemon/mcp-canary.js +524 -0
  177. package/dist/heart/daemon/message-router.js +65 -5
  178. package/dist/heart/daemon/migrate-to-desk.js +848 -0
  179. package/dist/heart/daemon/os-cron-deps.js +135 -0
  180. package/dist/heart/daemon/os-cron.js +22 -14
  181. package/dist/heart/daemon/ouro-bot-entry.js +4 -2
  182. package/dist/heart/daemon/ouro-entry.js +3 -1
  183. package/dist/heart/daemon/plugin-cli.js +432 -0
  184. package/dist/heart/daemon/process-manager.js +733 -61
  185. package/dist/heart/daemon/provider-discovery.js +137 -0
  186. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  187. package/dist/heart/daemon/prunable-bundle.js +144 -0
  188. package/dist/heart/daemon/pulse.js +511 -0
  189. package/dist/heart/daemon/readiness-repair.js +365 -0
  190. package/dist/heart/daemon/run-hooks.js +2 -0
  191. package/dist/heart/daemon/runtime-logging.js +47 -14
  192. package/dist/heart/daemon/runtime-metadata.js +2 -30
  193. package/dist/heart/daemon/runtime-mode.js +13 -2
  194. package/dist/heart/daemon/safe-mode.js +161 -0
  195. package/dist/heart/daemon/sanctuary-acceptance-adapter.js +2654 -0
  196. package/dist/heart/daemon/sanctuary-acceptance-harness.js +1830 -0
  197. package/dist/heart/daemon/sanctuary-acceptance-marker.js +267 -0
  198. package/dist/heart/daemon/sanctuary-acceptance-scenarios.js +955 -0
  199. package/dist/heart/daemon/sanctuary-authority-codec.js +86 -0
  200. package/dist/heart/daemon/sanctuary-authority-epoch.js +281 -0
  201. package/dist/heart/daemon/sanctuary-authority-installation.js +161 -0
  202. package/dist/heart/daemon/sanctuary-authority-ledger.js +241 -0
  203. package/dist/heart/daemon/sanctuary-authority-root-lifecycle.js +1310 -0
  204. package/dist/heart/daemon/sanctuary-authority-vault-migration.js +79 -0
  205. package/dist/heart/daemon/sanctuary-bundle-migration.js +730 -0
  206. package/dist/heart/daemon/sanctuary-host-authority.js +1008 -0
  207. package/dist/heart/daemon/sanctuary-host-detached-supervisor.js +493 -0
  208. package/dist/heart/daemon/sanctuary-host-executor.js +670 -0
  209. package/dist/heart/daemon/sanctuary-host-linux-kernel.js +334 -0
  210. package/dist/heart/daemon/sanctuary-host-supervisor-entry.js +207 -0
  211. package/dist/heart/daemon/sanctuary-host-supervisor.js +95 -0
  212. package/dist/heart/daemon/sanctuary-package-management.js +103 -0
  213. package/dist/heart/daemon/sanctuary-scheduler-liveness.js +227 -0
  214. package/dist/heart/daemon/sanctuary-scheduler-origin.js +132 -0
  215. package/dist/heart/daemon/sanctuary-telegram-authority-entry.js +475 -0
  216. package/dist/heart/daemon/sanctuary-telegram-authority-gateway.js +585 -0
  217. package/dist/heart/daemon/sanctuary-telegram-authority-service.js +676 -0
  218. package/dist/heart/daemon/sense-manager.js +699 -48
  219. package/dist/heart/daemon/session-id-resolver.js +131 -0
  220. package/dist/heart/daemon/skill-management-installer.js +1 -1
  221. package/dist/heart/daemon/socket-client.js +180 -12
  222. package/dist/heart/daemon/stale-bundle-prune.js +113 -0
  223. package/dist/heart/daemon/startup-tui.js +339 -0
  224. package/dist/heart/daemon/supercronic-supervisor.js +282 -0
  225. package/dist/heart/daemon/task-scheduler.js +117 -39
  226. package/dist/heart/daemon/terminal-ui.js +499 -0
  227. package/dist/heart/daemon/thoughts.js +138 -54
  228. package/dist/heart/daemon/up-progress.js +366 -0
  229. package/dist/heart/daemon/vault-items.js +56 -0
  230. package/dist/heart/delegation.js +1 -4
  231. package/dist/heart/external-events/router.js +1516 -0
  232. package/dist/heart/failure-reports.js +335 -0
  233. package/dist/heart/file-lock.js +109 -0
  234. package/dist/heart/frontend-approval-runtime.js +506 -0
  235. package/dist/heart/frontend-journal.js +215 -0
  236. package/dist/heart/frontend-session-service.js +237 -0
  237. package/dist/heart/frontend-socket-client.js +164 -0
  238. package/dist/heart/frontend-socket.js +400 -0
  239. package/dist/heart/habits/habit-cancel.js +810 -0
  240. package/dist/heart/habits/habit-lifecycle.js +1327 -0
  241. package/dist/heart/habits/habit-migration.js +194 -0
  242. package/dist/heart/habits/habit-parser.js +278 -0
  243. package/dist/heart/habits/habit-runtime-state.js +93 -0
  244. package/dist/heart/habits/habit-scheduler.js +653 -0
  245. package/dist/heart/habits/habit-session-summary.js +318 -0
  246. package/dist/heart/habits/habit-session.js +636 -0
  247. package/dist/heart/{daemon → hatch}/hatch-flow.js +55 -62
  248. package/dist/heart/{daemon → hatch}/hatch-specialist.js +6 -8
  249. package/dist/heart/{daemon → hatch}/specialist-prompt.js +12 -9
  250. package/dist/heart/{daemon → hatch}/specialist-tools.js +53 -18
  251. package/dist/heart/identity.js +196 -59
  252. package/dist/heart/kept-notes.js +289 -0
  253. package/dist/heart/kicks.js +1 -1
  254. package/dist/heart/machine-identity.js +161 -0
  255. package/dist/heart/mail-import-discovery.js +356 -0
  256. package/dist/heart/mailbox/mailbox-http-hooks.js +98 -0
  257. package/dist/heart/mailbox/mailbox-http-response.js +7 -0
  258. package/dist/heart/mailbox/mailbox-http-routes.js +398 -0
  259. package/dist/heart/mailbox/mailbox-http-static.js +103 -0
  260. package/dist/heart/mailbox/mailbox-http-transport.js +272 -0
  261. package/dist/heart/mailbox/mailbox-http.js +99 -0
  262. package/dist/heart/mailbox/mailbox-read.js +39 -0
  263. package/dist/heart/mailbox/mailbox-types.js +27 -0
  264. package/dist/heart/mailbox/mailbox-view.js +197 -0
  265. package/dist/heart/mailbox/readers/agent-machine.js +428 -0
  266. package/dist/heart/mailbox/readers/continuity-readers.js +329 -0
  267. package/dist/heart/mailbox/readers/mail.js +375 -0
  268. package/dist/heart/mailbox/readers/runtime-readers.js +823 -0
  269. package/dist/heart/mailbox/readers/sessions.js +231 -0
  270. package/dist/heart/mailbox/readers/shared.js +111 -0
  271. package/dist/heart/mcp/mcp-server.js +696 -0
  272. package/dist/heart/migrate-config.js +100 -0
  273. package/dist/heart/model-capabilities.js +11 -0
  274. package/dist/heart/orientation-frame.js +345 -0
  275. package/dist/heart/platform.js +81 -0
  276. package/dist/heart/primitives.js +1 -1
  277. package/dist/heart/private-runtime/decision-renderer.js +158 -0
  278. package/dist/heart/private-runtime/index.js +18 -0
  279. package/dist/heart/private-runtime/ledger.js +221 -0
  280. package/dist/heart/private-runtime/policy.js +252 -0
  281. package/dist/heart/private-runtime/types.js +2 -0
  282. package/dist/heart/progress-story.js +1 -1
  283. package/dist/heart/provider-attempt.js +137 -0
  284. package/dist/heart/provider-binding-resolver.js +273 -0
  285. package/dist/heart/provider-credentials.js +449 -0
  286. package/dist/heart/provider-failover.js +311 -0
  287. package/dist/heart/provider-models.js +96 -0
  288. package/dist/heart/provider-ping.js +265 -0
  289. package/dist/heart/provider-readiness-cache.js +119 -0
  290. package/dist/heart/provider-visibility.js +188 -0
  291. package/dist/heart/providers/anthropic-token.js +131 -0
  292. package/dist/heart/providers/anthropic.js +173 -60
  293. package/dist/heart/providers/azure.js +23 -11
  294. package/dist/heart/providers/error-classification.js +127 -0
  295. package/dist/heart/providers/github-copilot.js +34 -38
  296. package/dist/heart/providers/minimax-vlm.js +189 -0
  297. package/dist/heart/providers/minimax.js +26 -8
  298. package/dist/heart/providers/openai-codex-token.js +349 -0
  299. package/dist/heart/providers/openai-codex.js +55 -40
  300. package/dist/heart/providers/openai-compatible.js +177 -0
  301. package/dist/heart/reply-style.js +56 -0
  302. package/dist/heart/run-ledger.js +247 -0
  303. package/dist/heart/runtime-capability-check.js +170 -0
  304. package/dist/heart/runtime-credentials.js +607 -0
  305. package/dist/heart/runtime-cwd.js +87 -0
  306. package/dist/heart/sense-truth.js +22 -4
  307. package/dist/heart/session-activity.js +92 -24
  308. package/dist/heart/session-events.js +1504 -0
  309. package/dist/heart/session-playback-cli-main.js +5 -0
  310. package/dist/heart/session-playback-cli.js +36 -0
  311. package/dist/heart/session-playback.js +231 -0
  312. package/dist/heart/session-redaction-repair-cli-main.js +31 -0
  313. package/dist/heart/session-redaction-repair.js +552 -0
  314. package/dist/heart/session-stats-cli-main.js +5 -0
  315. package/dist/heart/session-stats.js +183 -0
  316. package/dist/heart/session-transcript.js +133 -0
  317. package/dist/heart/source-grounding.js +194 -0
  318. package/dist/heart/start-of-turn-packet.js +372 -0
  319. package/dist/heart/steward-policy.js +656 -0
  320. package/dist/heart/streaming.js +604 -207
  321. package/dist/heart/structured-output.js +196 -0
  322. package/dist/heart/sync-classification.js +176 -0
  323. package/dist/heart/sync.js +505 -0
  324. package/dist/heart/target-resolution.js +11 -7
  325. package/dist/heart/tempo.js +93 -0
  326. package/dist/heart/temporal-view.js +41 -0
  327. package/dist/heart/timeouts.js +101 -0
  328. package/dist/heart/tool-activity-callbacks.js +59 -0
  329. package/dist/heart/tool-approval.js +382 -0
  330. package/dist/heart/tool-description.js +155 -0
  331. package/dist/heart/tool-friction.js +55 -0
  332. package/dist/heart/tool-loop.js +206 -0
  333. package/dist/heart/turn-context.js +487 -0
  334. package/dist/heart/turn-execution-lease.js +30 -0
  335. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +6 -5
  336. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  337. package/dist/heart/versioning/ouro-path-installer.js +432 -0
  338. package/dist/heart/versioning/ouro-recovery-launcher.js +76 -0
  339. package/dist/heart/versioning/ouro-version-manager.js +409 -0
  340. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  341. package/dist/heart/{daemon → versioning}/update-checker.js +6 -1
  342. package/dist/heart/versioning/update-hooks.js +154 -0
  343. package/dist/heart/versioning/version-intent.js +114 -0
  344. package/dist/heart/work-card.js +380 -0
  345. package/dist/mailbox-ui/assets/index-Cyv4mw3Y.js +1 -0
  346. package/dist/mailbox-ui/assets/index-Du_9G9WO.css +1 -0
  347. package/dist/mailbox-ui/assets/vendor-CcN1XpQ9.js +61 -0
  348. package/dist/mailbox-ui/index.html +16 -0
  349. package/dist/mailroom/attention.js +167 -0
  350. package/dist/mailroom/autonomy.js +209 -0
  351. package/dist/mailroom/blob-store.js +889 -0
  352. package/dist/mailroom/body-cache.js +61 -0
  353. package/dist/mailroom/cache-sync-cli.js +58 -0
  354. package/dist/mailroom/core.js +803 -0
  355. package/dist/mailroom/entry.js +160 -0
  356. package/dist/mailroom/file-store.js +568 -0
  357. package/dist/mailroom/hosted-cache-sync.js +384 -0
  358. package/dist/mailroom/mbox-import.js +393 -0
  359. package/dist/mailroom/migration.js +164 -0
  360. package/dist/mailroom/outbound.js +380 -0
  361. package/dist/mailroom/policy.js +263 -0
  362. package/dist/mailroom/reader.js +292 -0
  363. package/dist/mailroom/search-cache.js +513 -0
  364. package/dist/mailroom/search-relevance.js +319 -0
  365. package/dist/mailroom/smtp-ingress.js +176 -0
  366. package/dist/mailroom/source-state.js +176 -0
  367. package/dist/mailroom/thread.js +109 -0
  368. package/dist/mailroom/travel-extract.js +89 -0
  369. package/dist/mind/bundle-manifest.js +24 -2
  370. package/dist/mind/context.js +307 -139
  371. package/dist/mind/desk-section.js +362 -0
  372. package/dist/mind/diary-integrity.js +60 -0
  373. package/dist/mind/{memory.js → diary.js} +68 -77
  374. package/dist/mind/embedding-provider.js +60 -0
  375. package/dist/mind/file-state.js +179 -0
  376. package/dist/mind/{associative-recall.js → note-search.js} +47 -58
  377. package/dist/mind/obligation-steering.js +199 -3
  378. package/dist/mind/pending.js +36 -10
  379. package/dist/mind/prompt-budget.js +479 -0
  380. package/dist/mind/prompt-refresh.js +3 -2
  381. package/dist/mind/prompt.js +1048 -198
  382. package/dist/mind/provenance-trust.js +26 -0
  383. package/dist/mind/record-paths.js +312 -0
  384. package/dist/mind/scrutiny.js +173 -0
  385. package/dist/mind/session-transaction.js +564 -0
  386. package/dist/nerves/cli-logging.js +7 -1
  387. package/dist/nerves/coverage/audit-rules.js +15 -6
  388. package/dist/nerves/coverage/audit.js +28 -2
  389. package/dist/nerves/coverage/cli.js +1 -1
  390. package/dist/nerves/coverage/contract.js +5 -5
  391. package/dist/nerves/coverage/file-completeness.js +139 -5
  392. package/dist/nerves/coverage/run-artifacts.js +55 -35
  393. package/dist/nerves/coverage/source-scanner.js +4 -4
  394. package/dist/nerves/event-buffer.js +111 -0
  395. package/dist/nerves/index.js +293 -9
  396. package/dist/nerves/observation.js +20 -0
  397. package/dist/nerves/redact.js +79 -0
  398. package/dist/nerves/review/cli-main.js +5 -0
  399. package/dist/nerves/review/cli.js +156 -0
  400. package/dist/nerves/review/core.js +159 -0
  401. package/dist/nerves/runtime.js +17 -1
  402. package/dist/repertoire/ado-client.js +15 -56
  403. package/dist/repertoire/ado-semantic.js +16 -10
  404. package/dist/repertoire/api-client.js +97 -0
  405. package/dist/repertoire/bitwarden-store.js +1045 -0
  406. package/dist/repertoire/bundle-templates.js +71 -0
  407. package/dist/repertoire/bw-installer.js +180 -0
  408. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  409. package/dist/repertoire/coding/context-pack.js +331 -0
  410. package/dist/repertoire/coding/feedback.js +174 -32
  411. package/dist/repertoire/coding/index.js +15 -3
  412. package/dist/repertoire/coding/manager.js +159 -10
  413. package/dist/repertoire/coding/spawner.js +58 -11
  414. package/dist/repertoire/coding/tools.js +221 -15
  415. package/dist/repertoire/coding/workbench-client.js +272 -0
  416. package/dist/repertoire/coding/workbench-manager.js +346 -0
  417. package/dist/repertoire/commerce-errors.js +109 -0
  418. package/dist/repertoire/commerce-self-test.js +156 -0
  419. package/dist/repertoire/credential-access.js +178 -0
  420. package/dist/repertoire/desk/classifier.js +362 -0
  421. package/dist/repertoire/duffel-client.js +185 -0
  422. package/dist/repertoire/github-client.js +14 -55
  423. package/dist/repertoire/graph-client.js +11 -52
  424. package/dist/repertoire/guardrails.js +873 -19
  425. package/dist/repertoire/house-sweep.js +466 -0
  426. package/dist/repertoire/mcp-client.js +58 -5
  427. package/dist/repertoire/mcp-manager.js +427 -139
  428. package/dist/repertoire/mcp-tools.js +132 -0
  429. package/dist/repertoire/mcp-write-guard.js +46 -0
  430. package/dist/repertoire/plugin-mcp.js +175 -0
  431. package/dist/repertoire/plugins.js +253 -0
  432. package/dist/repertoire/relationship-authorization.js +322 -0
  433. package/dist/repertoire/shell-sessions.js +134 -0
  434. package/dist/repertoire/skills.js +48 -4
  435. package/dist/repertoire/stripe-client.js +131 -0
  436. package/dist/repertoire/tool-arguments.js +182 -0
  437. package/dist/repertoire/tool-results.js +29 -0
  438. package/dist/repertoire/tools-a2a.js +699 -0
  439. package/dist/repertoire/tools-attachments.js +322 -0
  440. package/dist/repertoire/tools-awaiting.js +870 -0
  441. package/dist/repertoire/tools-base.js +79 -1168
  442. package/dist/repertoire/tools-bluebubbles.js +2 -0
  443. package/dist/repertoire/tools-bridge.js +144 -0
  444. package/dist/repertoire/tools-bundle.js +993 -0
  445. package/dist/repertoire/tools-commerce.js +253 -0
  446. package/dist/repertoire/tools-config.js +186 -0
  447. package/dist/repertoire/tools-continuity.js +575 -0
  448. package/dist/repertoire/tools-credential.js +383 -0
  449. package/dist/repertoire/tools-escalation.js +84 -0
  450. package/dist/repertoire/tools-evolution.js +527 -0
  451. package/dist/repertoire/tools-files.js +344 -0
  452. package/dist/repertoire/tools-flight.js +290 -0
  453. package/dist/repertoire/tools-flow.js +119 -0
  454. package/dist/repertoire/tools-github.js +3 -8
  455. package/dist/repertoire/tools-habits.js +103 -0
  456. package/dist/repertoire/tools-house-care.js +138 -0
  457. package/dist/repertoire/tools-mail.js +1828 -0
  458. package/dist/repertoire/tools-notes.js +496 -0
  459. package/dist/repertoire/tools-obligations.js +182 -0
  460. package/dist/repertoire/tools-orientation.js +31 -0
  461. package/dist/repertoire/tools-record.js +482 -0
  462. package/dist/repertoire/tools-rsvp.js +139 -0
  463. package/dist/repertoire/tools-runtime.js +238 -0
  464. package/dist/repertoire/tools-sanctuary-host.js +202 -0
  465. package/dist/repertoire/tools-session.js +1133 -0
  466. package/dist/repertoire/tools-shell.js +149 -0
  467. package/dist/repertoire/tools-steward-policy.js +147 -0
  468. package/dist/repertoire/tools-stripe.js +224 -0
  469. package/dist/repertoire/tools-surface.js +369 -0
  470. package/dist/repertoire/tools-teams.js +12 -39
  471. package/dist/repertoire/tools-telegram-contacts.js +37 -0
  472. package/dist/repertoire/tools-travel.js +125 -0
  473. package/dist/repertoire/tools-trip.js +982 -0
  474. package/dist/repertoire/tools-unraid.js +556 -0
  475. package/dist/repertoire/tools-user-profile.js +146 -0
  476. package/dist/repertoire/tools-vault.js +40 -0
  477. package/dist/repertoire/tools-voice.js +145 -0
  478. package/dist/repertoire/tools.js +509 -156
  479. package/dist/repertoire/travel-api-client.js +360 -0
  480. package/dist/repertoire/unraid-client.js +155 -0
  481. package/dist/repertoire/unraid-restart.js +339 -0
  482. package/dist/repertoire/user-profile.js +131 -0
  483. package/dist/repertoire/vault-setup.js +246 -0
  484. package/dist/repertoire/vault-unlock.js +628 -0
  485. package/dist/rsvp/aisleplanner-client.js +354 -0
  486. package/dist/rsvp/cli.js +926 -0
  487. package/dist/rsvp/config.js +327 -0
  488. package/dist/rsvp/cutover.js +433 -0
  489. package/dist/rsvp/diagnostics.js +232 -0
  490. package/dist/rsvp/diff-renderer.js +176 -0
  491. package/dist/rsvp/habit-policy.js +110 -0
  492. package/dist/rsvp/habit-stage.js +123 -0
  493. package/dist/rsvp/incident-bundle.js +97 -0
  494. package/dist/rsvp/migration.js +204 -0
  495. package/dist/rsvp/native-habit-runner.js +630 -0
  496. package/dist/rsvp/outbound-state.js +628 -0
  497. package/dist/rsvp/query.js +118 -0
  498. package/dist/rsvp/replay.js +233 -0
  499. package/dist/rsvp/snapshot.js +232 -0
  500. package/dist/rsvp/spend-ledger.js +175 -0
  501. package/dist/scripts/claude-code-hook.js +41 -0
  502. package/dist/scripts/claude-code-stop-hook.js +47 -0
  503. package/dist/senses/a2a-entry.js +131 -0
  504. package/dist/senses/acp-server.js +386 -0
  505. package/dist/senses/attention-queue.js +186 -0
  506. package/dist/senses/await-turn-message.js +65 -0
  507. package/dist/senses/bluebubbles/active-turns.js +216 -0
  508. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  509. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  510. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +355 -40
  511. package/dist/senses/bluebubbles/context-packet.js +207 -0
  512. package/dist/senses/bluebubbles/context-smoke.js +144 -0
  513. package/dist/senses/bluebubbles/entry.js +90 -0
  514. package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +21 -3
  515. package/dist/senses/bluebubbles/index.js +3841 -0
  516. package/dist/senses/bluebubbles/latest-turn.js +311 -0
  517. package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +121 -71
  518. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +159 -28
  519. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +24 -13
  520. package/dist/senses/bluebubbles/outbound-state.js +308 -0
  521. package/dist/senses/bluebubbles/processed-log.js +133 -0
  522. package/dist/senses/bluebubbles/reaction-policy.js +47 -0
  523. package/dist/senses/bluebubbles/replay.js +284 -0
  524. package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +30 -2
  525. package/dist/senses/bluebubbles/semantic-receipts.js +1986 -0
  526. package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
  527. package/dist/senses/bluebubbles/webhook-registration.js +228 -0
  528. package/dist/senses/bluebubbles-meta-guard.js +39 -0
  529. package/dist/senses/cli/bracketed-paste.js +82 -0
  530. package/dist/senses/cli/image-paste.js +287 -0
  531. package/dist/senses/cli/image-ref-navigation.js +75 -0
  532. package/dist/senses/cli/ink-app.js +156 -0
  533. package/dist/senses/cli/inline-diff.js +64 -0
  534. package/dist/senses/cli/input-keys.js +174 -0
  535. package/dist/senses/cli/kill-ring.js +86 -0
  536. package/dist/senses/cli/message-list.js +51 -0
  537. package/dist/senses/cli/ouro-tui.js +607 -0
  538. package/dist/senses/cli/spinner-imperative.js +135 -0
  539. package/dist/senses/cli/spinner.js +101 -0
  540. package/dist/senses/cli/status-line.js +60 -0
  541. package/dist/senses/cli/streaming-markdown.js +526 -0
  542. package/dist/senses/cli/tool-display.js +85 -0
  543. package/dist/senses/cli/tool-render.js +85 -0
  544. package/dist/senses/cli/tui-store.js +241 -0
  545. package/dist/senses/cli/virtual-list.js +35 -0
  546. package/dist/senses/cli-entry.js +60 -8
  547. package/dist/senses/cli.js +601 -304
  548. package/dist/senses/commands.js +66 -3
  549. package/dist/senses/context-packet-ledger.js +371 -0
  550. package/dist/senses/context-packets.js +154 -0
  551. package/dist/senses/habit-lifecycle-guard.js +24 -0
  552. package/dist/senses/habit-turn-message.js +160 -0
  553. package/dist/senses/ingress-evidence.js +2 -0
  554. package/dist/senses/mail-entry.js +66 -0
  555. package/dist/senses/mail.js +524 -0
  556. package/dist/senses/pipeline.js +1115 -204
  557. package/dist/senses/private-runtime-worker.js +859 -0
  558. package/dist/senses/private-runtime.js +1619 -0
  559. package/dist/senses/proactive-content-guard.js +51 -0
  560. package/dist/senses/root-host-approval-port.js +345 -0
  561. package/dist/senses/root-host-approval-runtime.js +393 -0
  562. package/dist/senses/sanctuary-authority-resident.js +102 -0
  563. package/dist/senses/sanctuary-download-credit-presentation.js +31 -0
  564. package/dist/senses/sanctuary-full-visibility-contract.js +302 -0
  565. package/dist/senses/sanctuary-grounding.js +118 -0
  566. package/dist/senses/sanctuary-health-acceptance-probe-entry.js +12 -0
  567. package/dist/senses/sanctuary-health-acceptance-probe.js +774 -0
  568. package/dist/senses/sanctuary-health-runner.js +104 -0
  569. package/dist/senses/sanctuary-health.js +422 -0
  570. package/dist/senses/sanctuary-install-state-contract.js +169 -0
  571. package/dist/senses/sanctuary-interactive-control.js +410 -0
  572. package/dist/senses/sanctuary-media-catalog-contract.js +297 -0
  573. package/dist/senses/sanctuary-media-optimization.js +514 -0
  574. package/dist/senses/sanctuary-runtime.js +347 -0
  575. package/dist/senses/sanctuary-sab.js +85 -0
  576. package/dist/senses/sanctuary-storage-optimization-contract.js +32 -0
  577. package/dist/senses/shared-turn.js +789 -0
  578. package/dist/senses/surface-tool.js +109 -0
  579. package/dist/senses/teams-entry.js +60 -8
  580. package/dist/senses/teams.js +519 -218
  581. package/dist/senses/telegram-admission.js +718 -0
  582. package/dist/senses/telegram-approval-runtime.js +793 -0
  583. package/dist/senses/telegram-attachments.js +186 -0
  584. package/dist/senses/telegram-audit-ledger.js +220 -0
  585. package/dist/senses/telegram-authority-transport.js +231 -0
  586. package/dist/senses/telegram-client.js +1749 -0
  587. package/dist/senses/telegram-effect-adapter.js +900 -0
  588. package/dist/senses/telegram-entry.js +83 -0
  589. package/dist/senses/telegram.js +2349 -0
  590. package/dist/senses/trust-gate.js +104 -9
  591. package/dist/senses/voice/audio-playback.js +237 -0
  592. package/dist/senses/voice/audio-routing.js +119 -0
  593. package/dist/senses/voice/call-auth.js +248 -0
  594. package/dist/senses/voice/elevenlabs.js +202 -0
  595. package/dist/senses/voice/floor-control.js +431 -0
  596. package/dist/senses/voice/floor-controller.js +115 -0
  597. package/dist/senses/voice/golden-path.js +116 -0
  598. package/dist/senses/voice/index.js +29 -0
  599. package/dist/senses/voice/meeting.js +113 -0
  600. package/dist/senses/voice/outbound.js +190 -0
  601. package/dist/senses/voice/phone.js +33 -0
  602. package/dist/senses/voice/playback.js +139 -0
  603. package/dist/senses/voice/process-guards.js +51 -0
  604. package/dist/senses/voice/realtime-eval.js +496 -0
  605. package/dist/senses/voice/realtime-trace.js +531 -0
  606. package/dist/senses/voice/transcript.js +70 -0
  607. package/dist/senses/voice/turn.js +191 -0
  608. package/dist/senses/voice/twilio-phone-runtime.js +820 -0
  609. package/dist/senses/voice/twilio-phone.js +5324 -0
  610. package/dist/senses/voice/types.js +2 -0
  611. package/dist/senses/voice/whisper.js +161 -0
  612. package/dist/senses/voice-entry.js +83 -0
  613. package/dist/senses/voice-realtime-eval-command.js +99 -0
  614. package/dist/senses/voice-realtime-eval-entry.js +21 -0
  615. package/dist/senses/voice-twilio-entry.js +87 -0
  616. package/dist/trips/core.js +138 -0
  617. package/dist/trips/store.js +265 -0
  618. package/dist/util/frontmatter.js +69 -0
  619. package/npm-shrinkwrap.json +8100 -0
  620. package/package.json +73 -13
  621. package/skills/agent-commerce.md +113 -0
  622. package/skills/browser-navigation.md +117 -0
  623. package/skills/commerce-setup-guide.md +116 -0
  624. package/skills/commerce-setup.md +84 -0
  625. package/skills/configure-dev-tools.md +99 -0
  626. package/skills/travel-planning.md +138 -0
  627. package/dist/heart/daemon/auth-flow.js +0 -430
  628. package/dist/heart/daemon/ouro-path-installer.js +0 -260
  629. package/dist/heart/daemon/ouro-version-manager.js +0 -171
  630. package/dist/heart/daemon/update-hooks.js +0 -138
  631. package/dist/heart/obligations.js +0 -191
  632. package/dist/heart/safe-workspace.js +0 -362
  633. package/dist/heart/session-recall.js +0 -116
  634. package/dist/mind/friends/channel.js +0 -84
  635. package/dist/mind/friends/group-context.js +0 -144
  636. package/dist/mind/friends/resolver.js +0 -84
  637. package/dist/mind/friends/store-file.js +0 -190
  638. package/dist/mind/friends/store.js +0 -4
  639. package/dist/mind/friends/tokens.js +0 -26
  640. package/dist/mind/friends/trust-explanation.js +0 -74
  641. package/dist/mind/friends/types.js +0 -29
  642. package/dist/repertoire/tasks/board.js +0 -134
  643. package/dist/repertoire/tasks/index.js +0 -224
  644. package/dist/repertoire/tasks/lifecycle.js +0 -80
  645. package/dist/repertoire/tasks/middleware.js +0 -65
  646. package/dist/repertoire/tasks/parser.js +0 -173
  647. package/dist/repertoire/tasks/scanner.js +0 -132
  648. package/dist/repertoire/tasks/transitions.js +0 -144
  649. package/dist/senses/bluebubbles-entry.js +0 -13
  650. package/dist/senses/bluebubbles.js +0 -1181
  651. package/dist/senses/debug-activity.js +0 -154
  652. package/dist/senses/inner-dialog-worker.js +0 -90
  653. package/dist/senses/inner-dialog.js +0 -525
  654. package/subagents/README.md +0 -7
  655. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  656. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  657. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  658. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  659. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  660. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  661. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  662. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  663. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  664. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  665. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  666. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  667. /package/dist/{repertoire/tasks/types.js → heart/attachments/sources/adapter.js} +0 -0
  668. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  669. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  670. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  671. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
@@ -0,0 +1,2995 @@
1
+ Mendelow Cloud Butler operator runbook
2
+
3
+ The production container is ouro-butler. It runs as UID/GID 10001, publishes no ports, uses host networking only so its loopback-only Unraid GraphQL client can reach 127.0.0.1, mounts the runtime and sanctuary.ouro bundle read-write, the bundle psyche folder read-only over it so the Butler can neither edit nor replace its psyche, plus the privileged event spool read-only, and uses restart policy unless-stopped. The canonical-gateway image appends /run/ouro-authority -> /run/ouro-authority, readonly, rprivate, and the psyche mount (<bundle>/psyche -> /home/ouro/AgentBundles/sanctuary.ouro/psyche, readonly, rprivate). The pinned alpha.816 predecessor has only the first three mounts. Root token, issuer, package and authority state are never mounted into the resident.
4
+
5
+ Root authority lifecycle
6
+
7
+ The existing DockerMan transaction owns authority-install, authority-activate, authority-retire and authority-restore. A complete exact-image package, including dist and production dependencies, must remain at its package-relative paths; extracting only the old five deployment assets cannot execute this lifecycle. The reviewed root-only inputs are /mnt/user/appdata/ouro-authority/incoming-package, package-manifest.json, request.json and incoming-token. They are not a new resident credential policy. The human rotates the existing bot token directly into root custody; the root owner proves the previous token returns 401 and the fresh token belongs to the same numeric bot before continuing.
8
+
9
+ First rollout of the psyche mount: the live container before this release has four mounts, but the canonical-gateway contract now requires five (the psyche folder read-only over the bundle). assert_update_source audits the live source container against its image's contract, so on that first update it fails with "effective mounts do not match the selected Sanctuary mount contract". The failure is expected and changes nothing. Recreate the live resident once by hand with the five-mount create (the canonical-gateway line in create_sanctuary_container, including the psyche mount), leave it stopped, then rerun the update. Psyche files stay owned by uid 10001 at mode 0600 because the resident's boot check requires exactly that; the read-only mount, not ownership, keeps the resident from editing or replacing them.
10
+
11
+ During installation the resident is stopped, the root gateway is installed and proven, tokenless readiness runs, and authority-activate starts the exact five-mount target. On failure, authority-retire must finish before restoring bundle/config/mounts or starting the exact three-mount predecessor; authority-restore proves that rollback before the outer template journal is removed. An uncertain or interrupted handoff leaves autostart disabled and preserves both journals and root inputs for the same reviewed recovery, never a raw old-template start. Retired keys, policy, history and Jellyfin remain untouched. Re-enabling authority requires a new human token rotation and issuer epoch, not reuse of retired authority.
12
+
13
+ On installed cold boot, the original unless-stopped and DockerMan autostart remain unchanged: /boot/config/custom/ouro-authority/start.sh --boot waits for the array and responsive Docker, then starts the fenced root gateway. Docker may already have started the tokenless resident; it fails closed until the gateway is ready. There is no pre-Docker gate, whole-array gate, resident direct poller or resident token fallback.
14
+
15
+ Bounded Jellyfin stewardship
16
+
17
+ Do not start a weak predecessor after policy exists. Once live A-006 authority has been provisioned, repair by forward-fixing and installing another policy-aware image through the existing exact-image update procedure. Its transaction mechanics are unchanged; a stopped older image is not permission to resume weaker policy enforcement.
18
+
19
+ Packaged desired states and grants remain empty. Build and installation create no authority and do not restart Jellyfin. Package migration preserves the live policy, audit and action-receipt bytes, including on a repeated migration.
20
+
21
+ A standing restart requires the intersection of an applied owner-stated positive desired state, an applied owner-stated grant and a fresh authorized request or exact current health event. Values on, always_on and expected_on permit either request-driven or event-driven evaluation; on_demand permits current owner or household requests only. Active off, disabled, paused, intentionally_off or intentionally_paused states deny mutation and make an unchanged expected health condition quiet. Missing, expired, inferred, unaudited, conflicted or mismatched positive state cannot authorize a standing restart. Installation provenance is not owner-stated authority.
22
+
23
+ Provision only after the policy-aware image is healthy and its package and running-image identities agree. Ari must supply a fresh authenticated owner Telegram message after installation. This runbook, old messages, agent-written setup text and installation records are not that authorization. The approved setup terms are container:jellyfin=on with no desired-state expiry; grant key unraid.restart:jellyfin, action unraid.container.restart, target jellyfin, 2 attempts per 1800000 ms, verificationRequired=true, exclusions=[], provenance=stated, and grant expiry exactly 365 days after authorization.
24
+
25
+ Use the existing steward_policy_manage actions sequentially: set_desired_state -> read -> grant_routine_action -> read. Carry the current readback version into each write. The first write must be applied and read back before the grant; desired state alone cannot authorize action. The final read must show both exact keys and versions, the stated provenance, rate, verification requirement, exclusions and calculated expiry. The two writes must have two linked applied v2 rows in state/policy/policy-audit.ndjson. Do not edit policy files directly or fabricate the authorizing event.
26
+
27
+ Use steward_policy_manage read for current policy and state/policy/action-receipts.ndjson for reservation and outcome evidence. Durable reservations count toward the limit, not only successful restarts. A reservation or attempt is not proof of a successful effect: retain definite no-effect, failed, indeterminate and verified-success outcomes without replaying an uncertain attempt. Fresh relationship, request, policy, grant, reservation and exact target checks still apply immediately before mutation.
28
+
29
+ When an owner request has only a missing or expired grant and no active negative desired state, the existing one-time owner approval path remains available. A conflicting negative state requires clarification or a policy update, not an approval workaround. Household and event denials never create a self-approval card.
30
+
31
+ Never manufacture a Jellyfin outage to demonstrate the grant. Record a natural event or ordinary request if one occurs; otherwise report organic operation as unobserved, separately from installed and provisioned state.
32
+
33
+ Start/stop:
34
+ docker start ouro-butler
35
+ docker stop ouro-butler
36
+
37
+ Status and health:
38
+ docker inspect --format '{{.State.Status}} {{.State.Health.Status}}' ouro-butler
39
+ docker logs --tail 200 ouro-butler
40
+
41
+ Effective-spec audit helper:
42
+ Run Update, Backup, and Restore command sequences from a root shell with `set -eu`.
43
+ Before any sequence, define this helper. It captures one actual container
44
+ inspect and its reviewed image inspect without printing either, invokes the
45
+ packaged auditor from the explicit validated runner image argument, and
46
+ removes its mode-0600 inputs on success or shell exit:
47
+ audit_effective() {
48
+ (
49
+ AUDIT_CONTAINER=$1
50
+ AUDIT_EXPECTED_IMAGE=$2
51
+ AUDIT_RUNNER_IMAGE_ID=$3
52
+ AUDIT_MOUNT_CONTRACT=${4-}
53
+ AUDIT_EXPECTED_IMAGE_REFERENCE=${5-}
54
+ AUDIT_EXPECTED_ICON=${6-}
55
+ validate_exact_image_id "$AUDIT_EXPECTED_IMAGE" || return $?
56
+ validate_exact_image_id "$AUDIT_RUNNER_IMAGE_ID" || return $?
57
+ test "$AUDIT_RUNNER_IMAGE_ID" != sha256:681449ad47a2621705cd339b481e6339236b31dc65e195b1cf5025d0f2191d7d || return $?
58
+ case "$AUDIT_MOUNT_CONTRACT" in
59
+ canonical-pre-gateway|canonical-gateway)
60
+ test -n "$AUDIT_EXPECTED_IMAGE_REFERENCE" || return 1
61
+ test "$AUDIT_EXPECTED_ICON" = https://raw.githubusercontent.com/ourostack/ouroboros/main/assets/ouroboros.png || return 1
62
+ set -- --mount-contract "$AUDIT_MOUNT_CONTRACT" --expected-image-reference "$AUDIT_EXPECTED_IMAGE_REFERENCE" --expected-icon "$AUDIT_EXPECTED_ICON"
63
+ ;;
64
+ legacy-alpha742) set -- --mount-contract "$AUDIT_MOUNT_CONTRACT" ;;
65
+ *) return 1 ;;
66
+ esac
67
+ INSPECT_DIR=$(mktemp -d /mnt/user/appdata/ouro-butler/staging/inspect.XXXXXX) || return $?
68
+ trap 'rm -f -- "$INSPECT_DIR/container.json" "$INSPECT_DIR/image.json"; rmdir -- "$INSPECT_DIR"' EXIT || return $?
69
+ chmod 0700 "$INSPECT_DIR" || return $?
70
+ umask 077 || return $?
71
+ docker inspect "$AUDIT_CONTAINER" >"$INSPECT_DIR/container.json" || return $?
72
+ docker image inspect "$AUDIT_EXPECTED_IMAGE" >"$INSPECT_DIR/image.json" || return $?
73
+ chmod 0600 "$INSPECT_DIR/container.json" "$INSPECT_DIR/image.json" || return $?
74
+ docker run --rm --pull=never --network=none \
75
+ --user 0:0 --read-only --cap-drop=ALL --security-opt=no-new-privileges \
76
+ --entrypoint /opt/ouro/deploy/unraid/audit-container-spec.sh \
77
+ --mount "type=bind,src=$INSPECT_DIR/container.json,dst=/audit/container.json,readonly" \
78
+ --mount "type=bind,src=$INSPECT_DIR/image.json,dst=/audit/image.json,readonly" \
79
+ "$AUDIT_RUNNER_IMAGE_ID" --inspect /audit/container.json --image-inspect /audit/image.json --expected-image "$AUDIT_EXPECTED_IMAGE" "$@" || return $?
80
+ rm -f -- "$INSPECT_DIR/container.json" "$INSPECT_DIR/image.json" || return $?
81
+ rmdir -- "$INSPECT_DIR" || return $?
82
+ trap - EXIT || return $?
83
+ )
84
+ }
85
+ inspect_registry_manifest_digest() {
86
+ (
87
+ REGISTRY_MANIFEST_REFERENCE=$1
88
+ REGISTRY_MANIFEST_PATH=$(mktemp /tmp/ouro-registry-manifest.XXXXXX) || return $?
89
+ trap 'rm -f -- "$REGISTRY_MANIFEST_PATH"' EXIT || return $?
90
+ docker buildx imagetools inspect "$REGISTRY_MANIFEST_REFERENCE" --raw >"$REGISTRY_MANIFEST_PATH" || return $?
91
+ REGISTRY_MANIFEST_SHA256=$(sha256sum -- "$REGISTRY_MANIFEST_PATH") || return $?
92
+ REGISTRY_MANIFEST_SHA256=${REGISTRY_MANIFEST_SHA256%% *}
93
+ printf 'sha256:%s\n' "$REGISTRY_MANIFEST_SHA256"
94
+ )
95
+ }
96
+ Define these helpers in the same root shell. Each profile change calls Unraid's
97
+ own root-local Docker manager backend, after proving exact durable identities.
98
+ A missing Butler entry is a no-op when disabling; this avoids the backend's
99
+ false-to-index-zero behavior. The helper preserves every non-Butler row byte
100
+ for byte and restores the complete captured file atomically on any failure:
101
+ butler_autostart_counts() {
102
+ (
103
+ AUTOSTART_FILE=/var/lib/docker/unraid-autostart
104
+ test -f "$AUTOSTART_FILE" || return $?
105
+ awk '
106
+ $1 == "ouro-butler" { production++ }
107
+ $1 == "ouro-butler-staging" { staging++ }
108
+ $1 == "ouro-butler-rollback" { rollback++ }
109
+ $1 == "ouro-butler-legacy-evidence" { legacy++ }
110
+ END { printf "%d %d %d %d", production + 0, staging + 0, rollback + 0, legacy + 0 }
111
+ ' "$AUTOSTART_FILE"
112
+ )
113
+ }
114
+ snapshot_nonbutler_autostart() {
115
+ awk '
116
+ $1 != "ouro-butler" && $1 != "ouro-butler-staging" && $1 != "ouro-butler-rollback" && $1 != "ouro-butler-legacy-evidence" { print }
117
+ ' /var/lib/docker/unraid-autostart
118
+ }
119
+ run_unraid_autostart_backend() {
120
+ (
121
+ AUTOSTART_ACTION=$1
122
+ AUTOSTART_CONTAINER=$2
123
+ AUTOSTART_VALUE=$3
124
+ case "$AUTOSTART_ACTION:$AUTOSTART_VALUE" in wait:0|autostart:true|autostart:false) ;; *) return 1 ;; esac
125
+ case "$AUTOSTART_CONTAINER" in
126
+ ouro-butler|ouro-butler-staging|ouro-butler-rollback|ouro-butler-legacy-evidence) ;;
127
+ *) return 1 ;;
128
+ esac
129
+ timeout -s KILL 20 /usr/bin/php -r '
130
+ [$action, $container, $value] = array_slice($argv, 1);
131
+ $allowed = ["ouro-butler", "ouro-butler-staging", "ouro-butler-rollback", "ouro-butler-legacy-evidence"];
132
+ if (!in_array($container, $allowed, true)) exit(2);
133
+ if ($action === "wait" && $value === "0") {
134
+ $_POST = ["action" => "wait", "container" => $container, "wait" => "0"];
135
+ } elseif ($action === "autostart" && ($value === "true" || $value === "false")) {
136
+ $_POST = ["action" => "autostart", "container" => $container, "auto" => $value, "wait" => "0"];
137
+ } else exit(2);
138
+ $_SERVER["DOCUMENT_ROOT"] = "/usr/local/emhttp";
139
+ $_SERVER["REQUEST_URI"] = "docker";
140
+ require "/usr/local/emhttp/plugins/dynamix.docker.manager/include/UpdateConfig.php";
141
+ ' "$AUTOSTART_ACTION" "$AUTOSTART_CONTAINER" "$AUTOSTART_VALUE"
142
+ )
143
+ }
144
+ mutate_butler_autostart() {
145
+ (
146
+ AUTOSTART_CONTAINER=$1
147
+ AUTOSTART_ENABLED=$2
148
+ case "$AUTOSTART_CONTAINER" in
149
+ ouro-butler|ouro-butler-staging|ouro-butler-rollback|ouro-butler-legacy-evidence) ;;
150
+ *) return 1 ;;
151
+ esac
152
+ case "$AUTOSTART_ENABLED" in true|false) ;; *) return 1 ;; esac
153
+ AUTOSTART_COUNT=$(awk -v name="$AUTOSTART_CONTAINER" '$1 == name { count++ } END { print count + 0 }' /var/lib/docker/unraid-autostart) || return $?
154
+ case "$AUTOSTART_COUNT" in 0|1) ;; *) return 1 ;; esac
155
+ if test "$AUTOSTART_ENABLED" = false && test "$AUTOSTART_COUNT" -eq 0; then
156
+ return 0
157
+ fi
158
+ if test "$AUTOSTART_COUNT" -eq 1; then
159
+ run_unraid_autostart_backend wait "$AUTOSTART_CONTAINER" 0 || return $?
160
+ fi
161
+ if test "$AUTOSTART_ENABLED" = false; then
162
+ run_unraid_autostart_backend autostart "$AUTOSTART_CONTAINER" false || return $?
163
+ AUTOSTART_EXPECTED_COUNT=0
164
+ else
165
+ if test "$AUTOSTART_COUNT" -eq 0; then
166
+ run_unraid_autostart_backend autostart "$AUTOSTART_CONTAINER" true || return $?
167
+ fi
168
+ AUTOSTART_EXPECTED_COUNT=1
169
+ fi
170
+ AUTOSTART_COUNT=$(awk -v name="$AUTOSTART_CONTAINER" '$1 == name { count++ } END { print count + 0 }' /var/lib/docker/unraid-autostart) || return $?
171
+ test "$AUTOSTART_COUNT" -eq "$AUTOSTART_EXPECTED_COUNT" || return $?
172
+ )
173
+ }
174
+ set_butler_autostart() {
175
+ (
176
+ AUTOSTART_PROFILE=$1
177
+ case "$AUTOSTART_PROFILE" in disabled|production|staging) ;; *) return 1 ;; esac
178
+ test "$(id -u)" -eq 0 || return $?
179
+ AUTOSTART_FILE=/var/lib/docker/unraid-autostart
180
+ AUTOSTART_INCLUDE=/usr/local/emhttp/plugins/dynamix.docker.manager/include/UpdateConfig.php
181
+ test -f "$AUTOSTART_FILE" && test ! -L "$AUTOSTART_FILE" || return 1
182
+ test "$(stat -c '%u:%g:%a' "$AUTOSTART_FILE")" = 0:0:644 || return $?
183
+ test -f "$AUTOSTART_INCLUDE" && test ! -L "$AUTOSTART_INCLUDE" || return 1
184
+ test "$(stat -c '%u:%g:%a' "$AUTOSTART_INCLUDE")" = 0:0:644 || return $?
185
+ AUTOSTART_COUNTS=$(butler_autostart_counts) || return $?
186
+ set -- $AUTOSTART_COUNTS
187
+ test "$#" -eq 4 || return $?
188
+ for AUTOSTART_COUNT in "$@"; do case "$AUTOSTART_COUNT" in 0|1) ;; *) return 1 ;; esac; done
189
+ case "$AUTOSTART_PROFILE" in
190
+ production) docker container inspect ouro-butler >/dev/null 2>&1 || return $? ;;
191
+ staging) docker container inspect ouro-butler-staging >/dev/null 2>&1 || return $? ;;
192
+ esac
193
+ AUTOSTART_BACKUP=$(mktemp /var/lib/docker/.unraid-autostart.ouro.XXXXXX) || return $?
194
+ AUTOSTART_NONBUTLER_BEFORE=$(mktemp /run/unraid-autostart.nonbutler-before.XXXXXX) || { rm -f -- "$AUTOSTART_BACKUP"; return 1; }
195
+ AUTOSTART_NONBUTLER_AFTER=$(mktemp /run/unraid-autostart.nonbutler-after.XXXXXX) || { rm -f -- "$AUTOSTART_BACKUP" "$AUTOSTART_NONBUTLER_BEFORE"; return 1; }
196
+ AUTOSTART_COMMITTED=no
197
+ AUTOSTART_BACKUP_READY=no
198
+ AUTOSTART_RESTORE_TMP=
199
+ autostart_cleanup() {
200
+ AUTOSTART_STATUS=$?
201
+ trap - EXIT HUP INT TERM
202
+ if test "$AUTOSTART_COMMITTED" = yes; then
203
+ rm -f -- "$AUTOSTART_BACKUP" || AUTOSTART_STATUS=1
204
+ elif test "$AUTOSTART_BACKUP_READY" = yes; then
205
+ AUTOSTART_RESTORE_TMP=$(mktemp /var/lib/docker/.unraid-autostart.restore.XXXXXX) || AUTOSTART_RESTORE_TMP=
206
+ if test -n "$AUTOSTART_RESTORE_TMP" \
207
+ && cp -p -- "$AUTOSTART_BACKUP" "$AUTOSTART_RESTORE_TMP" \
208
+ && sync -f "$AUTOSTART_RESTORE_TMP" \
209
+ && mv -f -- "$AUTOSTART_RESTORE_TMP" "$AUTOSTART_FILE" \
210
+ && sync -f "$AUTOSTART_FILE" \
211
+ && sync -f /var/lib/docker; then
212
+ rm -f -- "$AUTOSTART_BACKUP" || AUTOSTART_STATUS=1
213
+ else
214
+ test -z "$AUTOSTART_RESTORE_TMP" || rm -f -- "$AUTOSTART_RESTORE_TMP"
215
+ printf 'CRITICAL: Butler autostart rollback failed; recovery copy preserved at %s\n' "$AUTOSTART_BACKUP" >&2
216
+ AUTOSTART_STATUS=1
217
+ fi
218
+ else
219
+ rm -f -- "$AUTOSTART_BACKUP" || AUTOSTART_STATUS=1
220
+ fi
221
+ rm -f -- "$AUTOSTART_NONBUTLER_BEFORE" "$AUTOSTART_NONBUTLER_AFTER" || AUTOSTART_STATUS=1
222
+ exit "$AUTOSTART_STATUS"
223
+ }
224
+ trap autostart_cleanup EXIT
225
+ trap 'exit 129' HUP
226
+ trap 'exit 130' INT
227
+ trap 'exit 143' TERM
228
+ cp -p -- "$AUTOSTART_FILE" "$AUTOSTART_BACKUP" || return $?
229
+ cmp -s -- "$AUTOSTART_FILE" "$AUTOSTART_BACKUP" || return 1
230
+ sync -f "$AUTOSTART_BACKUP" || return $?
231
+ sync -f /var/lib/docker || return $?
232
+ AUTOSTART_BACKUP_READY=yes
233
+ snapshot_nonbutler_autostart >"$AUTOSTART_NONBUTLER_BEFORE" || return $?
234
+ case "$AUTOSTART_PROFILE" in
235
+ production) AUTOSTART_TARGET=ouro-butler ;;
236
+ staging) AUTOSTART_TARGET=ouro-butler-staging ;;
237
+ disabled) AUTOSTART_TARGET=- ;;
238
+ esac
239
+ for AUTOSTART_CONTAINER in ouro-butler ouro-butler-staging ouro-butler-rollback ouro-butler-legacy-evidence; do
240
+ test "$AUTOSTART_CONTAINER" = "$AUTOSTART_TARGET" && continue
241
+ mutate_butler_autostart "$AUTOSTART_CONTAINER" false || return $?
242
+ done
243
+ test "$AUTOSTART_TARGET" = - || mutate_butler_autostart "$AUTOSTART_TARGET" true || return $?
244
+ case "$AUTOSTART_PROFILE" in
245
+ production) AUTOSTART_EXPECTED_COUNTS="1 0 0 0" ;;
246
+ staging) AUTOSTART_EXPECTED_COUNTS="0 1 0 0" ;;
247
+ disabled) AUTOSTART_EXPECTED_COUNTS="0 0 0 0" ;;
248
+ esac
249
+ verify_butler_autostart "$AUTOSTART_EXPECTED_COUNTS" || return $?
250
+ snapshot_nonbutler_autostart >"$AUTOSTART_NONBUTLER_AFTER" || return $?
251
+ cmp -s -- "$AUTOSTART_NONBUTLER_BEFORE" "$AUTOSTART_NONBUTLER_AFTER" || return 1
252
+ sync -f "$AUTOSTART_FILE" || return $?
253
+ sync -f /var/lib/docker || return $?
254
+ AUTOSTART_COMMITTED=yes
255
+ )
256
+ }
257
+ verify_butler_autostart() {
258
+ (
259
+ EXPECTED_AUTOSTART_COUNTS=$1
260
+ AUTOSTART_COUNTS=$(butler_autostart_counts) || return $?
261
+ test "$AUTOSTART_COUNTS" = "$EXPECTED_AUTOSTART_COUNTS" || return $?
262
+ )
263
+ }
264
+ disable_butler_autostart() {
265
+ set_butler_autostart disabled || return $?
266
+ verify_butler_autostart "0 0 0 0" || return $?
267
+ }
268
+ enable_butler_autostart() {
269
+ set_butler_autostart production || return $?
270
+ verify_butler_autostart "1 0 0 0" || return $?
271
+ }
272
+ This bounded wait accepts only Docker's healthy state. The image healthcheck
273
+ verifies fresh daemon state plus exactly one managed Telegram process and one
274
+ managed scheduler process. It fails immediately on an exited, dead, or
275
+ unhealthy container and times out after four minutes:
276
+ wait_butler_ready() {
277
+ WAIT_CONTAINER=$1
278
+ WAIT_NOW=$(date +%s) || return $?
279
+ WAIT_DEADLINE=$(( WAIT_NOW + 240 ))
280
+ while :; do
281
+ WAIT_NOW=$(date +%s) || return $?
282
+ test "$WAIT_NOW" -lt "$WAIT_DEADLINE" || break
283
+ WAIT_STATE=$(docker inspect --format '{{.State.Status}} {{.State.Health.Status}}' "$WAIT_CONTAINER") || return $?
284
+ if test "$WAIT_STATE" = "running healthy"; then
285
+ return 0
286
+ fi
287
+ case "$WAIT_STATE" in
288
+ exited\ *|dead\ *|*\ unhealthy) return 1 ;;
289
+ esac
290
+ sleep 5 || return $?
291
+ done
292
+ return 1
293
+ }
294
+ Define these fail-closed image and topology helpers in the same shell. They use
295
+ exact Docker image IDs and container identity, image provenance, and writable
296
+ root overlap; no mutation is performed:
297
+ validate_exact_image_id() {
298
+ VALIDATE_IMAGE_ID=$1
299
+ case "$VALIDATE_IMAGE_ID" in
300
+ sha256:*) VALIDATE_IMAGE_HEX=${VALIDATE_IMAGE_ID#sha256:} ;;
301
+ *) return 1 ;;
302
+ esac
303
+ test "${#VALIDATE_IMAGE_HEX}" -eq 64 || return $?
304
+ case "$VALIDATE_IMAGE_HEX" in
305
+ *[!0-9a-f]*) return 1 ;;
306
+ esac
307
+ docker image inspect "$VALIDATE_IMAGE_ID" >/dev/null || return $?
308
+ }
309
+ sanctuary_image_mount_contract() {
310
+ (
311
+ CONTRACT_IMAGE_ID=$1
312
+ validate_exact_image_id "$CONTRACT_IMAGE_ID" || return $?
313
+ CONTRACT_LABEL=$(docker image inspect --format '{{with .Config.Labels}}{{index . "bot.ouro.sanctuary.mount-contract"}}{{end}}' "$CONTRACT_IMAGE_ID") || return $?
314
+ case "$CONTRACT_IMAGE_ID:$CONTRACT_LABEL" in
315
+ sha256:589b7cf8f96d139ee9fd86204a183126aadcbd3fbfb406063709be303397b1b2:) printf '%s\n' canonical-pre-gateway ;;
316
+ sha256:681449ad47a2621705cd339b481e6339236b31dc65e195b1cf5025d0f2191d7d:) printf '%s\n' legacy-alpha742 ;;
317
+ sha256:589b7cf8f96d139ee9fd86204a183126aadcbd3fbfb406063709be303397b1b2:*|sha256:681449ad47a2621705cd339b481e6339236b31dc65e195b1cf5025d0f2191d7d:*) return 1 ;;
318
+ *:canonical-gateway) printf '%s\n' canonical-gateway ;;
319
+ *) printf '%s\n' 'Unreviewed image mount contract; refusing version-only classification.' >&2; return 1 ;;
320
+ esac
321
+ )
322
+ }
323
+ create_sanctuary_container() {
324
+ (
325
+ CREATE_IMAGE_ID=$1
326
+ CREATE_IMAGE_REFERENCE=$2
327
+ CREATE_MOUNT_CONTRACT=$3
328
+ test "$(sanctuary_image_mount_contract "$CREATE_IMAGE_ID")" = "$CREATE_MOUNT_CONTRACT" || return 1
329
+ test "$(docker image inspect --format '{{.Id}}' "$CREATE_IMAGE_REFERENCE")" = "$CREATE_IMAGE_ID" || return 1
330
+ case "$CREATE_MOUNT_CONTRACT" in
331
+ canonical-gateway) set -- --mount "type=bind,src=/run/ouro-authority,dst=/run/ouro-authority,readonly" --mount "type=bind,src=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro/psyche,dst=/home/ouro/AgentBundles/sanctuary.ouro/psyche,readonly" ;;
332
+ canonical-pre-gateway) set -- ;;
333
+ *) return 1 ;;
334
+ esac
335
+ docker create --pull=never --name ouro-butler --network host --restart unless-stopped --user 10001:10001 \
336
+ --label net.unraid.docker.managed=dockerman \
337
+ --label "net.unraid.docker.icon=https://raw.githubusercontent.com/ourostack/ouroboros/main/assets/ouroboros.png" \
338
+ --mount "type=bind,src=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli,dst=/home/ouro/.ouro-cli" \
339
+ --mount "type=bind,src=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
340
+ --mount "type=bind,src=/boot/config/custom/ouro-events/spool,dst=/run/ouro-events,readonly" \
341
+ "$@" "$CREATE_IMAGE_REFERENCE" || return $?
342
+ )
343
+ }
344
+ assert_only_running_butler() {
345
+ (
346
+ EXPECTED_RUNNING_BUTLER=$1
347
+ case "$EXPECTED_RUNNING_BUTLER" in
348
+ -) EXPECTED_RUNNING_BUTLER_COUNT=0 ;;
349
+ ouro-butler|ouro-butler-staging) EXPECTED_RUNNING_BUTLER_COUNT=1 ;;
350
+ *) return 1 ;;
351
+ esac
352
+ RUNNING_CONTAINER_IDS=$(docker container ls -q) || return $?
353
+ MATCHING_RUNNING_BUTLERS=0
354
+ for RUNNING_CONTAINER_ID in $RUNNING_CONTAINER_IDS; do
355
+ RUNNING_CONTAINER_NAME=$(docker container inspect --format '{{.Name}}' "$RUNNING_CONTAINER_ID") || return $?
356
+ RUNNING_CONTAINER_NAME=${RUNNING_CONTAINER_NAME#/}
357
+ if test "$RUNNING_CONTAINER_NAME" = "$EXPECTED_RUNNING_BUTLER"; then
358
+ MATCHING_RUNNING_BUTLERS=$(( MATCHING_RUNNING_BUTLERS + 1 ))
359
+ continue
360
+ fi
361
+ RUNNING_CONTAINER_IMAGE_ID=$(docker container inspect --format '{{.Image}}' "$RUNNING_CONTAINER_ID") || return $?
362
+ RUNNING_CONTAINER_IMAGE_REF=$(docker container inspect --format '{{.Config.Image}}' "$RUNNING_CONTAINER_ID") || return $?
363
+ RUNNING_CONTAINER_IMAGE_SOURCE=$(docker image inspect --format '{{with .Config.Labels}}{{index . "org.opencontainers.image.source"}}{{end}}' "$RUNNING_CONTAINER_IMAGE_ID") || return $?
364
+ test "$RUNNING_CONTAINER_IMAGE_SOURCE" != https://github.com/ourostack/ouroboros || return 1
365
+ test "$RUNNING_CONTAINER_IMAGE_ID" != sha256:681449ad47a2621705cd339b481e6339236b31dc65e195b1cf5025d0f2191d7d || return 1
366
+ case "$RUNNING_CONTAINER_IMAGE_REF" in
367
+ ouro-butler|ouro-butler:*|ouro-butler@sha256:*|ouroboros-butler|ouroboros-butler:*|ouroboros-butler@sha256:*|ghcr.io/ourostack/ouroboros-butler|ghcr.io/ourostack/ouroboros-butler:*|ghcr.io/ourostack/ouroboros-butler@sha256:*) return 1 ;;
368
+ esac
369
+ RUNNING_WRITABLE_MOUNT_SOURCES=$(docker container inspect --format '{{range .Mounts}}{{if .RW}}{{println .Source}}{{end}}{{end}}' "$RUNNING_CONTAINER_ID") || return $?
370
+ if printf '%s\n' "$RUNNING_WRITABLE_MOUNT_SOURCES" | awk '
371
+ function overlaps(path, root) {
372
+ return length(path) > 0 && (path == root || index(path, root "/") == 1 || index(root, path "/") == 1)
373
+ }
374
+ overlaps($0, "/mnt/user/appdata/ouro-butler/runtime") || overlaps($0, "/mnt/user/appdata/ouro-butler/runtime/.ouro-cli") || overlaps($0, "/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro") || overlaps($0, "/mnt/user/appdata/ouro-butler/AgentBundles") { found = 1 }
375
+ END { exit found ? 0 : 1 }
376
+ '; then
377
+ return 1
378
+ fi
379
+ done
380
+ test "$MATCHING_RUNNING_BUTLERS" -eq "$EXPECTED_RUNNING_BUTLER_COUNT" || return $?
381
+ )
382
+ }
383
+ assert_update_topology() {
384
+ EXPECTED_ROLLBACK_IMAGE_ID=$1
385
+ UPDATE_CONTAINER_NAMES=$(docker container ls -a --format '{{.Names}}') || return $?
386
+ UPDATE_NAME_COUNTS=$(printf '%s\n' "$UPDATE_CONTAINER_NAMES" | awk '
387
+ $0 == "ouro-butler" { production++ }
388
+ $0 == "ouro-butler-staging" { staging++ }
389
+ $0 == "ouro-butler-rollback" { rollback++ }
390
+ $0 == "ouro-butler-legacy-evidence" { legacy++ }
391
+ END {
392
+ printf "%d %d %d %d", production + 0, staging + 0, rollback + 0, legacy + 0
393
+ }
394
+ ') || return $?
395
+ case "$UPDATE_NAME_COUNTS" in
396
+ "1 0 0 0"|"1 0 1 0"|"1 0 0 1"|"1 0 1 1") ;;
397
+ *) return 1 ;;
398
+ esac
399
+ UPDATE_PRODUCTION_RUNNING=$(docker inspect --format '{{.State.Running}}' ouro-butler) || return $?
400
+ test "$UPDATE_PRODUCTION_RUNNING" = true || return $?
401
+ UPDATE_PRODUCTION_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler) || return $?
402
+ test "$UPDATE_PRODUCTION_IMAGE_ID" = "$EXPECTED_ROLLBACK_IMAGE_ID" || return $?
403
+ case "$UPDATE_NAME_COUNTS" in
404
+ "1 0 1 0"|"1 0 1 1")
405
+ UPDATE_ROLLBACK_RUNNING=$(docker inspect --format '{{.State.Running}}' ouro-butler-rollback) || return $?
406
+ test "$UPDATE_ROLLBACK_RUNNING" = false || return $?
407
+ UPDATE_ROLLBACK_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-rollback) || return $?
408
+ test "$UPDATE_ROLLBACK_IMAGE_ID" = "$EXPECTED_ROLLBACK_IMAGE_ID" || return $?
409
+ ;;
410
+ esac
411
+ case "$UPDATE_NAME_COUNTS" in
412
+ "1 0 0 1"|"1 0 1 1")
413
+ UPDATE_LEGACY_RUNNING=$(docker inspect --format '{{.State.Running}}' ouro-butler-legacy-evidence) || return $?
414
+ test "$UPDATE_LEGACY_RUNNING" = false || return $?
415
+ UPDATE_LEGACY_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-legacy-evidence) || return $?
416
+ validate_exact_image_id "$UPDATE_LEGACY_IMAGE_ID" || return $?
417
+ ;;
418
+ esac
419
+ assert_only_running_butler ouro-butler || return $?
420
+ }
421
+ assert_sanctuary_update_source_pin() {
422
+ (
423
+ PIN_SOURCE_CONTAINER=$1
424
+ PIN_SOURCE_IMAGE_ID=$2
425
+ validate_exact_image_id "$PIN_SOURCE_IMAGE_ID" || return $?
426
+ test "$(docker inspect --format '{{.Image}}' "$PIN_SOURCE_CONTAINER")" = "$PIN_SOURCE_IMAGE_ID" || return $?
427
+ case "$PIN_SOURCE_CONTAINER $PIN_SOURCE_IMAGE_ID" in
428
+ "ouro-butler sha256:681449ad47a2621705cd339b481e6339236b31dc65e195b1cf5025d0f2191d7d") return 0 ;;
429
+ "ouro-butler "*) ;;
430
+ *) return 1 ;;
431
+ esac
432
+ PIN_SOURCE_IMAGE_REFERENCE=$(docker inspect --format '{{.Config.Image}}' "$PIN_SOURCE_CONTAINER") || return $?
433
+ printf '%s\n' "$PIN_SOURCE_IMAGE_REFERENCE" | grep -Eq '^ghcr\.io/ourostack/ouroboros-butler:[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$' || return $?
434
+ test "$(docker image inspect --format '{{.Id}}' "$PIN_SOURCE_IMAGE_REFERENCE")" = "$PIN_SOURCE_IMAGE_ID" || return $?
435
+ PIN_SOURCE_IMAGE_ORIGIN=$(docker image inspect --format '{{with .Config.Labels}}{{index . "org.opencontainers.image.source"}}{{end}}' "$PIN_SOURCE_IMAGE_ID") || return $?
436
+ test "$PIN_SOURCE_IMAGE_ORIGIN" = https://github.com/ourostack/ouroboros || return $?
437
+ test "$(docker inspect --format '{{with .Config.Labels}}{{index . "net.unraid.docker.managed"}}{{end}}' "$PIN_SOURCE_CONTAINER")" = dockerman || return $?
438
+ test "$(docker inspect --format '{{with .Config.Labels}}{{index . "net.unraid.docker.icon"}}{{end}}' "$PIN_SOURCE_CONTAINER")" = https://raw.githubusercontent.com/ourostack/ouroboros/main/assets/ouroboros.png
439
+ )
440
+ }
441
+ assert_legacy_alpha742_source() {
442
+ EXPECTED_SOURCE_IMAGE_ID=$1
443
+ AUDIT_RUNNER_IMAGE_ID=$2
444
+ assert_sanctuary_update_source_pin ouro-butler "$EXPECTED_SOURCE_IMAGE_ID" || return $?
445
+ audit_effective ouro-butler "$EXPECTED_SOURCE_IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID" legacy-alpha742
446
+ }
447
+ assert_update_source() {
448
+ EXPECTED_SOURCE_IMAGE_ID=$1
449
+ AUDIT_RUNNER_IMAGE_ID=$2
450
+ if test "$EXPECTED_SOURCE_IMAGE_ID" = sha256:681449ad47a2621705cd339b481e6339236b31dc65e195b1cf5025d0f2191d7d; then
451
+ assert_legacy_alpha742_source "$EXPECTED_SOURCE_IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID"
452
+ else
453
+ assert_sanctuary_update_source_pin ouro-butler "$EXPECTED_SOURCE_IMAGE_ID" || return $?
454
+ EXPECTED_SOURCE_IMAGE_REFERENCE=$(docker inspect --format '{{.Config.Image}}' ouro-butler) || return $?
455
+ EXPECTED_SOURCE_MOUNT_CONTRACT=$(sanctuary_image_mount_contract "$EXPECTED_SOURCE_IMAGE_ID") || return $?
456
+ audit_effective ouro-butler "$EXPECTED_SOURCE_IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID" "$EXPECTED_SOURCE_MOUNT_CONTRACT" "$EXPECTED_SOURCE_IMAGE_REFERENCE" https://raw.githubusercontent.com/ourostack/ouroboros/main/assets/ouroboros.png
457
+ fi
458
+ }
459
+ validate_sanctuary_roots() {
460
+ (
461
+ VALIDATE_RUNTIME_ROOT=$1
462
+ VALIDATE_AGENT_ROOT=$2
463
+ VALIDATE_CONTEXT=${3:-strict}
464
+ case "$VALIDATE_CONTEXT" in strict|live-precutover) ;; *) return 1 ;; esac
465
+ test -d "$VALIDATE_RUNTIME_ROOT" || return $?
466
+ test -d "$VALIDATE_AGENT_ROOT" || return $?
467
+ VALIDATE_CONTROL_SOCKET=$VALIDATE_AGENT_ROOT/state/acceptance/telegram-control.sock
468
+ if test "$VALIDATE_CONTEXT" = live-precutover; then
469
+ test ! -L "$VALIDATE_CONTROL_SOCKET" || return 1
470
+ test -S "$VALIDATE_CONTROL_SOCKET" || return 1
471
+ test "$(stat -c '%u:%g:%a' "$VALIDATE_CONTROL_SOCKET")" = 10001:10001:600 || return $?
472
+ VALIDATE_BAD_SHAPE=$(find "$VALIDATE_RUNTIME_ROOT" "$VALIDATE_AGENT_ROOT" -xdev \( -type l -o \( ! -type d -a ! -type f -a ! \( -type s -a -path "$VALIDATE_CONTROL_SOCKET" \) \) \) -print -quit) || return $?
473
+ VALIDATE_UNEXPECTED_SOCKET=$(find "$VALIDATE_RUNTIME_ROOT" "$VALIDATE_AGENT_ROOT" -xdev -type s ! -path "$VALIDATE_CONTROL_SOCKET" -print -quit) || return $?
474
+ else
475
+ test ! -S "$VALIDATE_AGENT_ROOT/state/acceptance/telegram-control.sock" || return $?
476
+ test ! -e "$VALIDATE_CONTROL_SOCKET" || return $?
477
+ VALIDATE_BAD_SHAPE=$(find "$VALIDATE_RUNTIME_ROOT" "$VALIDATE_AGENT_ROOT" -xdev \( -type l -o \( ! -type d -a ! -type f \) \) -print -quit) || return $?
478
+ VALIDATE_UNEXPECTED_SOCKET=$(find "$VALIDATE_RUNTIME_ROOT" "$VALIDATE_AGENT_ROOT" -xdev -type s -print -quit) || return $?
479
+ fi
480
+ test -z "$VALIDATE_BAD_SHAPE" || return $?
481
+ test -z "$VALIDATE_UNEXPECTED_SOCKET" || return $?
482
+ for VALIDATE_REQUIRED_FILE in \
483
+ agent.json bundle-meta.json provider-readiness.json tool-profiles.json \
484
+ psyche/SOUL.md habits/sanctuary-health.md; do
485
+ test -s "$VALIDATE_AGENT_ROOT/$VALIDATE_REQUIRED_FILE" || return $?
486
+ done
487
+ test -d "$VALIDATE_RUNTIME_ROOT/vault-unlock" || return $?
488
+ VALIDATE_UNLOCK_FILES=$(find "$VALIDATE_RUNTIME_ROOT/vault-unlock" -xdev -mindepth 1 -maxdepth 1 -type f -name '*.secret' -size +0c -print) || return $?
489
+ test "$(printf '%s\n' "$VALIDATE_UNLOCK_FILES" | awk 'NF { count++ } END { print count + 0 }')" = 1 || return $?
490
+ test ! -e "$VALIDATE_RUNTIME_ROOT/container-credentials.json" || return $?
491
+ test ! -e "$VALIDATE_RUNTIME_ROOT/container-credentials.json.consuming" || return $?
492
+ VALIDATE_WRONG_OWNER=$(find "$VALIDATE_RUNTIME_ROOT" "$VALIDATE_AGENT_ROOT" -xdev \( ! -user 10001 -o ! -group 10001 \) -print -quit) || return $?
493
+ test -z "$VALIDATE_WRONG_OWNER" || return $?
494
+ VALIDATE_WRONG_RUNTIME_DIR_MODE=$(find "$VALIDATE_RUNTIME_ROOT" -xdev -type d ! -perm 0700 \
495
+ ! \( -perm 0755 \( \
496
+ -path "$VALIDATE_RUNTIME_ROOT/scheduler" -o -path "$VALIDATE_RUNTIME_ROOT/scheduler/*" -o \
497
+ -path "$VALIDATE_RUNTIME_ROOT/daemon/logs" -o -path "$VALIDATE_RUNTIME_ROOT/daemon/logs/*" -o \
498
+ -path "$VALIDATE_RUNTIME_ROOT/daemon/external-events" -o -path "$VALIDATE_RUNTIME_ROOT/daemon/external-events/*" \
499
+ \) \) -print -quit) || return $?
500
+ test -z "$VALIDATE_WRONG_RUNTIME_DIR_MODE" || return $?
501
+ VALIDATE_WRONG_AGENT_DIR_MODE=$(find "$VALIDATE_AGENT_ROOT" -xdev -type d ! -perm 0700 \
502
+ ! \( -perm 0755 \( \
503
+ -path "$VALIDATE_AGENT_ROOT/arc/flight-recorder" -o -path "$VALIDATE_AGENT_ROOT/arc/flight-recorder/*" -o \
504
+ -path "$VALIDATE_AGENT_ROOT/state/health" -o -path "$VALIDATE_AGENT_ROOT/state/health/*" -o \
505
+ -path "$VALIDATE_AGENT_ROOT/state/logs" -o -path "$VALIDATE_AGENT_ROOT/state/logs/*" -o \
506
+ -path "$VALIDATE_AGENT_ROOT/state/habits" -o -path "$VALIDATE_AGENT_ROOT/state/habits/*" \
507
+ \) \) -print -quit) || return $?
508
+ test -z "$VALIDATE_WRONG_AGENT_DIR_MODE" || return $?
509
+ VALIDATE_WRONG_RUNTIME_FILE_MODE=$(find "$VALIDATE_RUNTIME_ROOT" -xdev -type f ! -perm 0600 \
510
+ ! \( -perm 0644 \( \
511
+ -path "$VALIDATE_RUNTIME_ROOT/daemon/logs/*" -o \
512
+ -path "$VALIDATE_RUNTIME_ROOT/scheduler/*" -o \
513
+ -path "$VALIDATE_RUNTIME_ROOT/pulse.json" -o \
514
+ -path "$VALIDATE_RUNTIME_ROOT/pulse-delivered.json" -o \
515
+ -path "$VALIDATE_RUNTIME_ROOT/daemon.pids" -o \
516
+ -path "$VALIDATE_RUNTIME_ROOT/daemon-health.json" \
517
+ \) \) -print -quit) || return $?
518
+ test -z "$VALIDATE_WRONG_RUNTIME_FILE_MODE" || return $?
519
+ # Alpha.753 and earlier wrote content-free autonomy receipts as 0644 below a 0700 tree.
520
+ # Preserve those audit records; current writers create and normalize this exact format to 0600.
521
+ VALIDATE_WRONG_AGENT_FILE_MODE=$(find "$VALIDATE_AGENT_ROOT" -xdev -type f ! -perm 0600 \
522
+ ! \( -perm 0644 \( \
523
+ -path "$VALIDATE_AGENT_ROOT/arc/flight-recorder/*" -o \
524
+ -path "$VALIDATE_AGENT_ROOT/state/health/*" -o \
525
+ -path "$VALIDATE_AGENT_ROOT/state/logs/*" -o \
526
+ -path "$VALIDATE_AGENT_ROOT/state/habits/*" -o \
527
+ -path "$VALIDATE_AGENT_ROOT/state/arc/context-loss-sentinel-watermark.json" -o \
528
+ -exec /bin/sh -c '
529
+ VALIDATE_AUTONOMY_RECEIPT=$1
530
+ VALIDATE_AUTONOMY_RECEIPTS_ROOT=$2
531
+ test "${VALIDATE_AUTONOMY_RECEIPT%/*}" = "$VALIDATE_AUTONOMY_RECEIPTS_ROOT" || exit 1
532
+ VALIDATE_AUTONOMY_RECEIPT_NAME=${VALIDATE_AUTONOMY_RECEIPT##*/}
533
+ case "$VALIDATE_AUTONOMY_RECEIPT_NAME" in
534
+ autr_????????????????????????????????.json) ;;
535
+ *) exit 1 ;;
536
+ esac
537
+ VALIDATE_AUTONOMY_RECEIPT_ID=${VALIDATE_AUTONOMY_RECEIPT_NAME#autr_}
538
+ VALIDATE_AUTONOMY_RECEIPT_ID=${VALIDATE_AUTONOMY_RECEIPT_ID%.json}
539
+ case "$VALIDATE_AUTONOMY_RECEIPT_ID" in *[!0-9a-f]*) exit 1 ;; esac
540
+ ' sanctuary-autonomy-receipt-validator {} "$VALIDATE_AGENT_ROOT/state/autonomy/receipts" \; \
541
+ \) \) -print -quit) || return $?
542
+ test -z "$VALIDATE_WRONG_AGENT_FILE_MODE" || return $?
543
+ )
544
+ }
545
+ normalize_sanctuary_private_permissions() {
546
+ (
547
+ NORMALIZE_RUNTIME_ROOT=$1
548
+ NORMALIZE_AGENT_ROOT=$2
549
+ NORMALIZE_IMAGE_ID=$3
550
+ test -d "$NORMALIZE_RUNTIME_ROOT" || return $?
551
+ test -d "$NORMALIZE_AGENT_ROOT" || return $?
552
+ validate_exact_image_id "$NORMALIZE_IMAGE_ID" || return $?
553
+ docker run --rm --pull=never --network none --user 10001:10001 \
554
+ --read-only --cap-drop ALL --security-opt no-new-privileges \
555
+ --mount "type=bind,src=$NORMALIZE_RUNTIME_ROOT,dst=/normalize/runtime" \
556
+ --mount "type=bind,src=$NORMALIZE_AGENT_ROOT,dst=/normalize/agent" \
557
+ --entrypoint /bin/sh "$NORMALIZE_IMAGE_ID" -eu -c '
558
+ find /normalize/runtime /normalize/agent -xdev -type d -user 10001 -group 10001 -perm 0755 \
559
+ ! -path "/normalize/runtime/scheduler" ! -path "/normalize/runtime/scheduler/*" \
560
+ ! -path "/normalize/runtime/daemon/logs" ! -path "/normalize/runtime/daemon/logs/*" \
561
+ ! -path "/normalize/runtime/daemon/external-events" ! -path "/normalize/runtime/daemon/external-events/*" \
562
+ ! -path "/normalize/agent/arc/flight-recorder" ! -path "/normalize/agent/arc/flight-recorder/*" \
563
+ ! -path "/normalize/agent/state/health" ! -path "/normalize/agent/state/health/*" \
564
+ ! -path "/normalize/agent/state/logs" ! -path "/normalize/agent/state/logs/*" \
565
+ ! -path "/normalize/agent/state/habits" ! -path "/normalize/agent/state/habits/*" \
566
+ -exec chmod 0700 {} +
567
+ find /normalize/runtime /normalize/agent -xdev -type f -links 1 -user 10001 -group 10001 -perm 0644 \
568
+ ! -path "/normalize/runtime/daemon/logs/*" \
569
+ ! -path "/normalize/runtime/scheduler/*" \
570
+ ! -path "/normalize/runtime/pulse.json" \
571
+ ! -path "/normalize/runtime/pulse-delivered.json" \
572
+ ! -path "/normalize/runtime/daemon.pids" \
573
+ ! -path "/normalize/runtime/daemon-health.json" \
574
+ ! -path "/normalize/agent/arc/flight-recorder/*" \
575
+ ! -path "/normalize/agent/state/health/*" \
576
+ ! -path "/normalize/agent/state/logs/*" \
577
+ ! -path "/normalize/agent/state/habits/*" \
578
+ ! -path "/normalize/agent/state/arc/context-loss-sentinel-watermark.json" \
579
+ -exec chmod 0600 {} +
580
+ ' || return $?
581
+ )
582
+ }
583
+ verify_sanctuary_snapshot_provenance() {
584
+ (
585
+ SNAPSHOT_ROOT=$1
586
+ EXPECTED_SNAPSHOT_IMAGE_ID=$2
587
+ SNAPSHOT_PROVENANCE_ROOT=$SNAPSHOT_ROOT/provenance
588
+ for SNAPSHOT_TOP_LEVEL_DIRECTORY in runtime agent host provenance; do
589
+ test -d "$SNAPSHOT_ROOT/$SNAPSHOT_TOP_LEVEL_DIRECTORY" || return $?
590
+ test ! -L "$SNAPSHOT_ROOT/$SNAPSHOT_TOP_LEVEL_DIRECTORY" || return 1
591
+ done
592
+ test "$(find "$SNAPSHOT_ROOT" -xdev -mindepth 1 -maxdepth 1 -print | wc -l)" -eq 4 || return $?
593
+ test -d "$SNAPSHOT_PROVENANCE_ROOT" || return $?
594
+ test ! -L "$SNAPSHOT_PROVENANCE_ROOT" || return 1
595
+ test "$(stat -c '%u:%g:%a' "$SNAPSHOT_PROVENANCE_ROOT")" = 0:0:700 || return $?
596
+ SNAPSHOT_BAD_PROVENANCE_ENTRY=$(find "$SNAPSHOT_PROVENANCE_ROOT" -xdev -mindepth 1 ! -type f -print -quit) || return $?
597
+ test -z "$SNAPSHOT_BAD_PROVENANCE_ENTRY" || return $?
598
+ for SNAPSHOT_PROVENANCE_FILE in image-id container-inspect.json image-inspect.json package-version manifest.sha256; do
599
+ test -f "$SNAPSHOT_PROVENANCE_ROOT/$SNAPSHOT_PROVENANCE_FILE" || return $?
600
+ test ! -L "$SNAPSHOT_PROVENANCE_ROOT/$SNAPSHOT_PROVENANCE_FILE" || return 1
601
+ test "$(stat -c '%u:%g:%a' "$SNAPSHOT_PROVENANCE_ROOT/$SNAPSHOT_PROVENANCE_FILE")" = 0:0:600 || return $?
602
+ done
603
+ test "$(find "$SNAPSHOT_PROVENANCE_ROOT" -xdev -mindepth 1 -maxdepth 1 -type f | wc -l)" -eq 5 || return $?
604
+ test "$(wc -l <"$SNAPSHOT_PROVENANCE_ROOT/image-id")" -eq 1 || return $?
605
+ IFS= read -r SNAPSHOT_IMAGE_ID <"$SNAPSHOT_PROVENANCE_ROOT/image-id" || return $?
606
+ test "$SNAPSHOT_IMAGE_ID" = "$EXPECTED_SNAPSHOT_IMAGE_ID" || return $?
607
+ case "$SNAPSHOT_IMAGE_ID" in sha256:????????????????????????????????????????????????????????????????) ;; *) return 1 ;; esac
608
+ case "${SNAPSHOT_IMAGE_ID#sha256:}" in *[!0-9a-f]*) return 1 ;; esac
609
+ /usr/local/bin/node -e '
610
+ const fs = require("node:fs");
611
+ const [containerPath, imagePath, imageId, hostPath] = process.argv.slice(1);
612
+ const container = JSON.parse(fs.readFileSync(containerPath, "utf8"));
613
+ const image = JSON.parse(fs.readFileSync(imagePath, "utf8"));
614
+ if (!Array.isArray(container) || container.length !== 1 || !container[0] || container[0].Image !== imageId) process.exit(1);
615
+ if (!Array.isArray(image) || image.length !== 1 || !image[0] || image[0].Id !== imageId) process.exit(1);
616
+ const source = image[0].Config?.Labels?.["org.opencontainers.image.source"];
617
+ const legacyAlpha742 = "sha256:681449ad47a2621705cd339b481e6339236b31dc65e195b1cf5025d0f2191d7d";
618
+ if (source !== "https://github.com/ourostack/ouroboros" && !(source === undefined && imageId === legacyAlpha742)) process.exit(1);
619
+ const expected = ["custom/usenet_health.sh", "custom/ouro-events/bootstrap-spool.sh", "custom/ouro-events/emit-event.mjs", "custom/ouro-events/emit-usenet-event.sh", "custom/ouro-events/install-usenet-guard.sh", "go.butler-lines", "crontab.butler-lines", "global-state"];
620
+ const expectedUid = 0;
621
+ const expectedGid = 0;
622
+ const hostRoot = fs.lstatSync(hostPath);
623
+ if (!hostRoot.isDirectory() || hostRoot.isSymbolicLink() || hostRoot.uid !== expectedUid || hostRoot.gid !== expectedGid || (hostRoot.mode & 0o777) !== 0o700) process.exit(1);
624
+ const rows = fs.readFileSync(`${hostPath}/inventory`, "utf8").trim().split("\n").map(line => line.split("\t"));
625
+ if (rows.length !== expected.length || rows.some((row, index) => row.length !== 2 || row[1] !== expected[index] || !["present", "absent"].includes(row[0]))) process.exit(1);
626
+ const present = rows.filter(row => row[0] === "present").map(row => row[1]);
627
+ if (!["go.butler-lines", "crontab.butler-lines", "global-state"].every(relative => present.includes(relative))) process.exit(1);
628
+ const globalRows = fs.readFileSync(`${hostPath}/global-state`, "utf8").trim().split("\n").map(line => line.split("\t"));
629
+ if (globalRows.length !== 2 || globalRows[0][0] !== "go" || globalRows[1][0] !== "crontab") process.exit(1);
630
+ for (const [name, state, digest, count] of globalRows) {
631
+ if (!["go", "crontab"].includes(name) || !["present", "absent"].includes(state) || !/^(?:[0-9a-f]{64}|-)$/.test(digest) || !/^(?:0|[1-9][0-9]*)$/.test(count)) process.exit(1);
632
+ if ((state === "absent") !== (digest === "-")) process.exit(1);
633
+ const fragmentLines = fs.readFileSync(`${hostPath}/${name}.butler-lines`, "utf8").split("\n").filter(Boolean);
634
+ if (fragmentLines.length !== Number(count)) process.exit(1);
635
+ }
636
+ for (const [state, relative] of rows) {
637
+ if (fs.existsSync(`${hostPath}/${relative}`) !== (state === "present")) process.exit(1);
638
+ }
639
+ const files = [];
640
+ const directories = [];
641
+ const walk = (directory, prefix = "") => {
642
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
643
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
644
+ const metadata = fs.lstatSync(`${directory}/${entry.name}`);
645
+ if (metadata.uid !== expectedUid || metadata.gid !== expectedGid) process.exit(1);
646
+ if (entry.isDirectory() && (metadata.mode & 0o777) === 0o700) { directories.push(relative); walk(`${directory}/${entry.name}`, relative); }
647
+ else if (entry.isFile() && (metadata.mode & 0o777) === 0o600) files.push(relative);
648
+ else process.exit(1);
649
+ }
650
+ };
651
+ walk(hostPath);
652
+ if (JSON.stringify(directories.sort()) !== JSON.stringify(["custom", "custom/ouro-events"])) process.exit(1);
653
+ if (JSON.stringify(files.sort()) !== JSON.stringify(["inventory", ...present].sort())) process.exit(1);
654
+ ' "$SNAPSHOT_PROVENANCE_ROOT/container-inspect.json" "$SNAPSHOT_PROVENANCE_ROOT/image-inspect.json" "$SNAPSHOT_IMAGE_ID" "$SNAPSHOT_ROOT/host" || return $?
655
+ test "$(wc -l <"$SNAPSHOT_PROVENANCE_ROOT/package-version")" -eq 1 || return $?
656
+ grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$' "$SNAPSHOT_PROVENANCE_ROOT/package-version" || return $?
657
+ test "$(stat -c '%u:%g:%a' "$SNAPSHOT_ROOT/host")" = 0:0:700 || return $?
658
+ SNAPSHOT_BAD_HOST_ENTRY=$(find "$SNAPSHOT_ROOT/host" -xdev \( \( -type d ! -perm 0700 \) -o \( -type f ! -perm 0600 \) -o \( ! -type d -a ! -type f \) \) -print -quit) || return $?
659
+ test -z "$SNAPSHOT_BAD_HOST_ENTRY" || return $?
660
+ test -f "$SNAPSHOT_ROOT/host/inventory" || return $?
661
+ test ! -e "$SNAPSHOT_ROOT/host/notify.conf" || return 1
662
+ test ! -e "$SNAPSHOT_ROOT/host/sabnzbd.ini" || return 1
663
+ SNAPSHOT_VERIFY_ROOT=$(mktemp -d /tmp/ouro-snapshot-verify.XXXXXX) || return $?
664
+ trap 'rm -f -- "$SNAPSHOT_VERIFY_ROOT/current-files" "$SNAPSHOT_VERIFY_ROOT/manifest-files"; rmdir -- "$SNAPSHOT_VERIFY_ROOT"' EXIT || return $?
665
+ (
666
+ cd "$SNAPSHOT_ROOT" || return $?
667
+ find runtime agent host provenance -xdev -type f ! -path provenance/manifest.sha256 -print | LC_ALL=C sort >"$SNAPSHOT_VERIFY_ROOT/current-files" || return $?
668
+ grep -E '^[0-9a-f]{64} [^/].+$' provenance/manifest.sha256 >/dev/null || return $?
669
+ ! grep -Ev '^[0-9a-f]{64} [^/].+$' provenance/manifest.sha256 >/dev/null || return 1
670
+ sed 's/^[0-9a-f]\{64\} //' provenance/manifest.sha256 | LC_ALL=C sort >"$SNAPSHOT_VERIFY_ROOT/manifest-files" || return $?
671
+ cmp -s "$SNAPSHOT_VERIFY_ROOT/current-files" "$SNAPSHOT_VERIFY_ROOT/manifest-files" || return $?
672
+ sha256sum -c -- provenance/manifest.sha256 >/dev/null || return $?
673
+ ) || return $?
674
+ rm -f -- "$SNAPSHOT_VERIFY_ROOT/current-files" "$SNAPSHOT_VERIFY_ROOT/manifest-files" || return $?
675
+ rmdir -- "$SNAPSHOT_VERIFY_ROOT" || return $?
676
+ trap - EXIT || return $?
677
+ )
678
+ }
679
+ assert_restore_preflight() {
680
+ (
681
+ test -n "${BACKUP_ROOT-}" || return 1
682
+ test -n "${IMAGE_ID-}" || return 1
683
+ test -n "${AUDIT_RUNNER_IMAGE_ID-}" || return 1
684
+ test -n "${RESTORE_VERSION_IMAGE-}" || return 1
685
+ case "$BACKUP_ROOT" in
686
+ /*) ;;
687
+ *) return 1 ;;
688
+ esac
689
+ test "$BACKUP_ROOT" != / || return $?
690
+ RESTORE_BACKUP_ROOT=$(cd -- "$BACKUP_ROOT" && pwd -P) || return $?
691
+ test "$RESTORE_BACKUP_ROOT" = "$BACKUP_ROOT" || return $?
692
+ test -d "$BACKUP_ROOT/runtime/.ouro-cli" || return $?
693
+ test -d "$BACKUP_ROOT/agent/sanctuary.ouro" || return $?
694
+ verify_sanctuary_snapshot_provenance "$BACKUP_ROOT" "$IMAGE_ID" || return $?
695
+ validate_sanctuary_roots "$BACKUP_ROOT/runtime/.ouro-cli" "$BACKUP_ROOT/agent/sanctuary.ouro" || return $?
696
+ validate_exact_image_id "$IMAGE_ID" || return $?
697
+ validate_exact_image_id "$AUDIT_RUNNER_IMAGE_ID" || return $?
698
+ test "$IMAGE_ID" != sha256:681449ad47a2621705cd339b481e6339236b31dc65e195b1cf5025d0f2191d7d || return $?
699
+ test "$IMAGE_ID" != sha256:e337dff04c92d116b269052f473b26a47eea933d017d1befc73af50dd37bb08d || return $?
700
+ test "$AUDIT_RUNNER_IMAGE_ID" != sha256:681449ad47a2621705cd339b481e6339236b31dc65e195b1cf5025d0f2191d7d || return $?
701
+ test "$AUDIT_RUNNER_IMAGE_ID" != sha256:e337dff04c92d116b269052f473b26a47eea933d017d1befc73af50dd37bb08d || return $?
702
+ printf '%s\n' "$RESTORE_VERSION_IMAGE" | grep -Eq '^ghcr\.io/ourostack/ouroboros-butler:[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$' || return $?
703
+ test "$(docker image inspect --format '{{.Id}}' "$RESTORE_VERSION_IMAGE")" = "$IMAGE_ID" || return $?
704
+ RESTORE_CONTAINER_NAMES=$(docker container ls -a --format '{{.Names}}') || return $?
705
+ RESTORE_NAME_COUNTS=$(printf '%s\n' "$RESTORE_CONTAINER_NAMES" | awk '
706
+ $0 == "ouro-butler" { production++ }
707
+ $0 == "ouro-butler-staging" { staging++ }
708
+ $0 == "ouro-butler-rollback" { rollback++ }
709
+ $0 == "ouro-butler-legacy-evidence" { legacy++ }
710
+ END {
711
+ printf "%d %d %d %d", production + 0, staging + 0, rollback + 0, legacy + 0
712
+ }
713
+ ') || return $?
714
+ case "$RESTORE_NAME_COUNTS" in
715
+ "1 0 0 0"|"1 0 0 1") ;;
716
+ *) return 1 ;;
717
+ esac
718
+ RESTORE_PRODUCTION_RUNNING=$(docker inspect --format '{{.State.Running}}' ouro-butler) || return $?
719
+ test "$RESTORE_PRODUCTION_RUNNING" = true || return $?
720
+ RESTORE_PRODUCTION_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler) || return $?
721
+ validate_exact_image_id "$RESTORE_PRODUCTION_IMAGE_ID" || return $?
722
+ if test "$RESTORE_NAME_COUNTS" = "1 0 0 1"; then
723
+ RESTORE_LEGACY_RUNNING=$(docker inspect --format '{{.State.Running}}' ouro-butler-legacy-evidence) || return $?
724
+ test "$RESTORE_LEGACY_RUNNING" = false || return $?
725
+ RESTORE_LEGACY_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-legacy-evidence) || return $?
726
+ validate_exact_image_id "$RESTORE_LEGACY_IMAGE_ID" || return $?
727
+ fi
728
+ assert_only_running_butler ouro-butler || return $?
729
+ assert_update_source "$RESTORE_PRODUCTION_IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID" || return $?
730
+ )
731
+ }
732
+ ensure_sanctuary_machine_identity() {
733
+ MACHINE_PATH=$1
734
+ test ! -L "$MACHINE_PATH" || return 1
735
+ /usr/local/bin/node -e '
736
+ const fs = require("node:fs");
737
+ const path = process.argv[1];
738
+ const valid = value => value && value.schemaVersion === 1 && value.machineId === "sanctuary"
739
+ && typeof value.createdAt === "string" && typeof value.updatedAt === "string"
740
+ && Array.isArray(value.hostnameAliases);
741
+ if (fs.existsSync(path)) {
742
+ if (!valid(JSON.parse(fs.readFileSync(path, "utf8")))) process.exit(1);
743
+ process.exit(0);
744
+ }
745
+ const now = new Date().toISOString();
746
+ const value = { schemaVersion: 1, machineId: "sanctuary", createdAt: now, updatedAt: now, hostnameAliases: [] };
747
+ const temporary = `${path}.tmp.${process.pid}`;
748
+ fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: "wx" });
749
+ fs.renameSync(temporary, path);
750
+ ' "$MACHINE_PATH" || return $?
751
+ chown 10001:10001 "$MACHINE_PATH" || return $?
752
+ chmod 0600 "$MACHINE_PATH" || return $?
753
+ sync -f "$MACHINE_PATH" || return $?
754
+ }
755
+ migrate_sanctuary_package_managed_bundle() {
756
+ MIGRATE_IMAGE_ID=$1
757
+ MIGRATE_OPERATION=$2
758
+ MIGRATE_ROLLBACK_IMAGE_ID=${3-}
759
+ validate_exact_image_id "$MIGRATE_IMAGE_ID" || return $?
760
+ case "$MIGRATE_OPERATION" in migrate|rollback|finalize-rollback|commit|status|inspect) ;; *) return 1 ;; esac
761
+ if test "$MIGRATE_OPERATION" = migrate; then
762
+ validate_exact_image_id "$MIGRATE_ROLLBACK_IMAGE_ID" || return $?
763
+ test "$MIGRATE_IMAGE_ID" != "$MIGRATE_ROLLBACK_IMAGE_ID" || return 1
764
+ set -- --rollback-image-id "$MIGRATE_ROLLBACK_IMAGE_ID" --target-image-id "$MIGRATE_IMAGE_ID"
765
+ else
766
+ set --
767
+ fi
768
+ docker run --rm --pull=never --network=none --read-only --user 10001:10001 \
769
+ --entrypoint /usr/local/bin/node \
770
+ --mount "type=bind,src=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
771
+ "$MIGRATE_IMAGE_ID" /opt/ouro/deploy/unraid/migrate-sanctuary-bundle.mjs \
772
+ --package-root /opt/ouro/deploy/unraid/sanctuary.ouro \
773
+ --agent-root /home/ouro/AgentBundles/sanctuary.ouro \
774
+ --operation "$MIGRATE_OPERATION" "$@" || return $?
775
+ }
776
+ read_sanctuary_bundle_transaction_status() {
777
+ READ_BUNDLE_IMAGE_ID=$1
778
+ READ_BUNDLE_AGENT_ROOT=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro
779
+ READ_BUNDLE_EXPECTED_UID=10001
780
+ READ_BUNDLE_EXPECTED_GID=10001
781
+ READ_BUNDLE_ROLLBACK_RECORD=$READ_BUNDLE_AGENT_ROOT/.sanctuary-package-managed-rollback.json
782
+ READ_BUNDLE_COMMITTING_RECORD=$READ_BUNDLE_ROLLBACK_RECORD.committing
783
+ validate_exact_image_id "$READ_BUNDLE_IMAGE_ID" || return $?
784
+ READ_BUNDLE_ROOT_STATE=$(/usr/local/bin/node -e '
785
+ const fs = require("node:fs");
786
+ const path = require("node:path");
787
+ const [rootPath, expectedUid, expectedGid] = process.argv.slice(1);
788
+ if (!path.isAbsolute(rootPath) || path.normalize(rootPath) !== rootPath) process.exit(1);
789
+ let current = path.parse(rootPath).root;
790
+ let rootStat;
791
+ for (const segment of rootPath.slice(current.length).split(path.sep)) {
792
+ current = path.join(current, segment);
793
+ let stat;
794
+ try { stat = fs.lstatSync(current); } catch (error) {
795
+ if (error?.code === "ENOENT") { process.stdout.write("missing"); process.exit(0); }
796
+ process.exit(1);
797
+ }
798
+ if (!stat.isDirectory() || stat.isSymbolicLink() || fs.realpathSync(current) !== current) process.exit(1);
799
+ rootStat = stat;
800
+ }
801
+ if (!rootStat || rootStat.uid !== Number(expectedUid) || rootStat.gid !== Number(expectedGid) || (rootStat.mode & 0o777) !== 0o700) process.exit(1);
802
+ process.stdout.write("present");
803
+ ' "$READ_BUNDLE_AGENT_ROOT" "$READ_BUNDLE_EXPECTED_UID" "$READ_BUNDLE_EXPECTED_GID") || return $?
804
+ if test "$READ_BUNDLE_ROOT_STATE" = missing; then
805
+ printf 'null\n'
806
+ return 0
807
+ fi
808
+ test "$READ_BUNDLE_ROOT_STATE" = present || return 1
809
+ READ_BUNDLE_STAGING_RESIDUE=$(find "$READ_BUNDLE_AGENT_ROOT" -mindepth 1 -maxdepth 1 \( \
810
+ -name '.sanctuary-package-managed-rollback.json.package-migration.*' -o \
811
+ -name '.sanctuary-package-managed-rollback.json.committing.package-migration.*' \
812
+ \) -print -quit) || return $?
813
+ test -z "$READ_BUNDLE_STAGING_RESIDUE" || return 1
814
+ READ_BUNDLE_RECORD_COUNT=0
815
+ for READ_BUNDLE_CANDIDATE in "$READ_BUNDLE_ROLLBACK_RECORD" "$READ_BUNDLE_COMMITTING_RECORD"; do
816
+ test ! -L "$READ_BUNDLE_CANDIDATE" || return 1
817
+ if test -e "$READ_BUNDLE_CANDIDATE"; then
818
+ test -f "$READ_BUNDLE_CANDIDATE" || return 1
819
+ READ_BUNDLE_RECORD_COUNT=$((READ_BUNDLE_RECORD_COUNT + 1))
820
+ fi
821
+ done
822
+ test "$READ_BUNDLE_RECORD_COUNT" -le 1 || return 1
823
+ if test "$READ_BUNDLE_RECORD_COUNT" -eq 0; then
824
+ printf 'null\n'
825
+ return 0
826
+ fi
827
+ migrate_sanctuary_package_managed_bundle "$READ_BUNDLE_IMAGE_ID" status || return $?
828
+ }
829
+ verify_dockerman_and_community_apps() {
830
+ VERIFY_VERSION_IMAGE=$1
831
+ VERIFY_INSTALL_PROOF_PATH=$2
832
+ VERIFY_TEMPLATE_PATH=/boot/config/plugins/dockerMan/templates-user/my-ouro-butler.xml
833
+ test "$(stat -c '%u:%g:%a' "$VERIFY_TEMPLATE_PATH")" = 0:0:600 || return $?
834
+ test ! -e "$VERIFY_INSTALL_PROOF_PATH" || return 1
835
+ timeout -s KILL 20 /usr/bin/php -r '
836
+ [$expectedImage, $outputPath] = array_slice($argv, 1);
837
+ $expectedPath = "/boot/config/plugins/dockerMan/templates-user/my-ouro-butler.xml";
838
+ $expectedUrl = "https://raw.githubusercontent.com/ourostack/ouroboros/main/deploy/unraid/sanctuary.xml";
839
+ $expectedIcon = "https://raw.githubusercontent.com/ourostack/ouroboros/main/assets/ouroboros.png";
840
+ $communityAppsEntryPath = "/usr/local/emhttp/plugins/community.applications/include/exec.php";
841
+ $communityAppsHelperPath = "/usr/local/emhttp/plugins/community.applications/include/previous_apps_helpers.php";
842
+ $communityAppsDependencies = ["/usr/local/emhttp/plugins/community.applications/include/paths.php", "/usr/local/emhttp/plugins/community.applications/include/plugin_identity.php", "/usr/local/emhttp/plugins/community.applications/include/helpers.php"];
843
+ if (!preg_match("#^ghcr\\.io/ourostack/ouroboros-butler:[0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z.-]+)?$#", $expectedImage)) exit(2);
844
+ $readActivePhp = static function($path) {
845
+ if (!is_file($path) || is_link($path) || fileowner($path) !== 0 || (fileperms($path) & 0022) !== 0 || realpath($path) !== $path) exit(3);
846
+ $lint = proc_open(["/usr/bin/php", "-l", $path], [0 => ["file", "/dev/null", "r"], 1 => ["file", "/dev/null", "w"], 2 => ["file", "/dev/null", "w"]], $pipes);
847
+ if (!is_resource($lint) || proc_close($lint) !== 0) exit(4);
848
+ $source = php_strip_whitespace($path);
849
+ if (!is_string($source) || $source === "") exit(4);
850
+ return $source;
851
+ };
852
+ $functionSlice = static function($source, $start, $next) {
853
+ if (substr_count($source, $start) !== 1 || substr_count($source, $next) !== 1) return false;
854
+ $startAt = strpos($source, $start);
855
+ $nextAt = strpos($source, $next, $startAt + strlen($start));
856
+ return $nextAt !== false && $nextAt > $startAt ? substr($source, $startAt, $nextAt - $startAt) : false;
857
+ };
858
+ $entrySource = $readActivePhp($communityAppsEntryPath);
859
+ $inlineBody = $functionSlice($entrySource, "function previous_apps(", "function remove_application(");
860
+ $delegatedBody = $functionSlice($entrySource, "function previous_apps(", "function installedAndPreviousCounts(");
861
+ $isInline = $inlineBody !== false && hash("sha256", $inlineBody) === "1914b9c6b8910b7bb116dad48fe76d4790a069becbf0d68b3822ee3df7f22b1c";
862
+ $isDelegated = $delegatedBody !== false && hash("sha256", $delegatedBody) === "16b52cd87cc3f74915bf172f8a6eb46f981529208766916d4aeedf4b3344a3a4";
863
+ if (($isInline ? 1 : 0) + ($isDelegated ? 1 : 0) !== 1) exit(4);
864
+ $_SERVER["DOCUMENT_ROOT"] = "/usr/local/emhttp";
865
+ $docroot = $_SERVER["DOCUMENT_ROOT"];
866
+ require_once "$docroot/plugins/dynamix/include/Wrappers.php";
867
+ require_once "$docroot/plugins/dynamix.docker.manager/include/DockerClient.php";
868
+ $driver = DockerUtil::driver();
869
+ $client = new DockerClient();
870
+ $templates = new DockerTemplates();
871
+ $resolved = $templates->getUserTemplate("ouro-butler");
872
+ if ($resolved !== $expectedPath) exit(5);
873
+ $xml = @simplexml_load_file($resolved);
874
+ if (!$xml || (string)$xml->Name !== "ouro-butler" || (string)$xml->Repository !== $expectedImage || (string)$xml->TemplateURL !== $expectedUrl || (string)$xml->Icon !== $expectedIcon || trim((string)$xml->WebUI) !== "") exit(6);
875
+ $containers = $client->getDockerContainers();
876
+ $matches = array_values(array_filter($containers, fn($container) => $container["Name"] === "ouro-butler"));
877
+ if (count($matches) !== 1) exit(7);
878
+ $container = $matches[0];
879
+ if ($container["Image"] !== $expectedImage || $container["Manager"] !== "dockerman" || $container["Icon"] !== $expectedIcon || !empty($container["Url"])) exit(8);
880
+ $communityAppsInstalled = $container["Name"] === (string)$xml->Name && (str_starts_with(str_replace("library/", "", $container["Image"]), (string)$xml->Repository) || str_starts_with($container["Image"], (string)$xml->Repository));
881
+ if (!$communityAppsInstalled) exit(9);
882
+ if ($isDelegated) {
883
+ $readActivePhp($communityAppsHelperPath);
884
+ foreach ($communityAppsDependencies as $dependencyPath) $readActivePhp($dependencyPath);
885
+ require_once "$docroot/plugins/community.applications/include/helpers.php";
886
+ require_once $communityAppsHelperPath;
887
+ if (!is_callable(["PreviousAppsHelpers", "collectDockerApplications"])) exit(4);
888
+ $helperUpdateCount = 0;
889
+ $helperRows = PreviousAppsHelpers::collectDockerApplications(true, "true", "docker", $containers, $helperUpdateCount, [], [], [], []);
890
+ if (!is_array($helperRows)) exit(9);
891
+ $helperMatches = array_values(array_filter($helperRows, fn($row) => is_array($row) && ($row["InstallPath"] ?? null) === $expectedPath && ($row["Name"] ?? null) === "ouro-butler" && ($row["Repository"] ?? null) === $expectedImage && ($row["TemplateURL"] ?? null) === $expectedUrl && ($row["Icon"] ?? null) === $expectedIcon));
892
+ if (count($helperMatches) !== 1) exit(9);
893
+ $communityAppsStateModel = "previous-apps-helper-v1";
894
+ $communityAppsImplementationPath = $communityAppsHelperPath;
895
+ $communityAppsImplementationSymbol = "PreviousAppsHelpers::collectDockerApplications";
896
+ } else {
897
+ $communityAppsStateModel = "previous-apps-inline-v1";
898
+ $communityAppsImplementationPath = $communityAppsEntryPath;
899
+ $communityAppsImplementationSymbol = "previous_apps";
900
+ }
901
+ $proof = [
902
+ "dockerMan" => ["templatePath" => $resolved, "name" => (string)$xml->Name, "repository" => (string)$xml->Repository, "templateUrl" => (string)$xml->TemplateURL, "icon" => (string)$xml->Icon],
903
+ "communityApps" => ["installed" => true, "name" => (string)$xml->Name, "repository" => (string)$xml->Repository, "templateUrl" => (string)$xml->TemplateURL, "stateModel" => $communityAppsStateModel, "entryPath" => $communityAppsEntryPath, "entryFunction" => "previous_apps", "implementationPath" => $communityAppsImplementationPath, "implementationSymbol" => $communityAppsImplementationSymbol],
904
+ ];
905
+ $temporary = $outputPath . ".tmp";
906
+ if (file_exists($temporary) || is_link($temporary) || file_exists($outputPath) || is_link($outputPath)) exit(10);
907
+ $payload = json_encode($proof, JSON_UNESCAPED_SLASHES) . "\n";
908
+ $handle = @fopen($temporary, "x");
909
+ if ($handle === false || fwrite($handle, $payload) !== strlen($payload) || !fflush($handle) || !fsync($handle) || !fclose($handle) || !chmod($temporary, 0600) || !chown($temporary, 0) || !chgrp($temporary, 0) || !rename($temporary, $outputPath)) exit(11);
910
+ ' "$VERIFY_VERSION_IMAGE" "$VERIFY_INSTALL_PROOF_PATH" || return $?
911
+ test "$(stat -c '%u:%g:%a' "$VERIFY_INSTALL_PROOF_PATH")" = 0:0:600 || return $?
912
+ }
913
+ audit_registered_dockerman_template() {
914
+ REGISTERED_TEMPLATE_RUNNER_IMAGE_ID=$1
915
+ REGISTERED_TEMPLATE_VERSION_IMAGE=$2
916
+ REGISTERED_TEMPLATE_MOUNT_CONTRACT=$3
917
+ REGISTERED_TEMPLATE_PATH=/boot/config/plugins/dockerMan/templates-user/my-ouro-butler.xml
918
+ validate_exact_image_id "$REGISTERED_TEMPLATE_RUNNER_IMAGE_ID" || return $?
919
+ printf '%s\n' "$REGISTERED_TEMPLATE_VERSION_IMAGE" | grep -Eq '^ghcr\.io/ourostack/ouroboros-butler:[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$' || return $?
920
+ test -f "$REGISTERED_TEMPLATE_PATH" && test ! -L "$REGISTERED_TEMPLATE_PATH" || return 1
921
+ docker run --rm --pull=never --network=none --user 0:0 --read-only --cap-drop=ALL --security-opt=no-new-privileges --entrypoint /opt/ouro/deploy/unraid/audit-container-spec.sh --mount "type=bind,src=$REGISTERED_TEMPLATE_PATH,dst=/audit/sanctuary.xml,readonly" "$REGISTERED_TEMPLATE_RUNNER_IMAGE_ID" --persistent-template /audit/sanctuary.xml --runtime-policy /opt/ouro/deploy/unraid/container-runtime.json --expected-image-reference "$REGISTERED_TEMPLATE_VERSION_IMAGE" --mount-contract "$REGISTERED_TEMPLATE_MOUNT_CONTRACT" || return $?
922
+ }
923
+ verify_known_good_rollback_artifact() {
924
+ EXPECTED_KNOWN_GOOD_IMAGE_ID=$1
925
+ validate_exact_image_id "$EXPECTED_KNOWN_GOOD_IMAGE_ID" || return $?
926
+ MATCHING_KNOWN_GOOD_COUNT=0
927
+ for KNOWN_GOOD_NAME in ouro-butler-rollback ouro-butler-legacy-evidence; do
928
+ if docker container inspect "$KNOWN_GOOD_NAME" >/dev/null 2>&1; then
929
+ KNOWN_GOOD_IMAGE_ID=$(docker inspect --format '{{.Image}}' "$KNOWN_GOOD_NAME") || return $?
930
+ if test "$KNOWN_GOOD_IMAGE_ID" = "$EXPECTED_KNOWN_GOOD_IMAGE_ID"; then
931
+ test "$(docker inspect --format '{{.State.Running}}' "$KNOWN_GOOD_NAME")" = false || return 1
932
+ MATCHING_KNOWN_GOOD_COUNT=$((MATCHING_KNOWN_GOOD_COUNT + 1))
933
+ fi
934
+ fi
935
+ done
936
+ test "$MATCHING_KNOWN_GOOD_COUNT" -eq 1 || return 1
937
+ }
938
+ write_dockerman_final_proof() {
939
+ FINAL_PROOF_IMAGE_ID=$1
940
+ FINAL_PROOF_VERSION_IMAGE=$2
941
+ FINAL_PROOF_ICON=$3
942
+ FINAL_PROOF_ROOT=$4
943
+ validate_exact_image_id "$FINAL_PROOF_IMAGE_ID" || return $?
944
+ test "$FINAL_PROOF_VERSION_IMAGE" = "ghcr.io/ourostack/ouroboros-butler:$PACKAGE_VERSION" || return 1
945
+ install -d -m 0700 -o 0 -g 0 "$FINAL_PROOF_ROOT" || return $?
946
+ FINAL_CONTAINER_PATH=$FINAL_PROOF_ROOT/container.json
947
+ FINAL_BUNDLE_PATH=$FINAL_PROOF_ROOT/bundle.json
948
+ FINAL_INSTALL_PATH=$FINAL_PROOF_ROOT/install.json
949
+ FINAL_JELLYFIN_PATH=$FINAL_PROOF_ROOT/jellyfin.json
950
+ FINAL_PROOF_PATH=$FINAL_PROOF_ROOT/final-proof.json
951
+ test ! -e "$FINAL_CONTAINER_PATH" && test ! -e "$FINAL_BUNDLE_PATH" && test ! -e "$FINAL_INSTALL_PATH" && test ! -e "$FINAL_JELLYFIN_PATH" && test ! -e "$FINAL_PROOF_PATH" || return 1
952
+ docker inspect ouro-butler >"$FINAL_CONTAINER_PATH" || return $?
953
+ migrate_sanctuary_package_managed_bundle "$FINAL_PROOF_IMAGE_ID" inspect >"$FINAL_BUNDLE_PATH" || return $?
954
+ verify_dockerman_and_community_apps "$FINAL_PROOF_VERSION_IMAGE" "$FINAL_INSTALL_PATH" || return $?
955
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" jellyfin-status >"$FINAL_JELLYFIN_PATH" || return $?
956
+ chown 0:0 "$FINAL_CONTAINER_PATH" "$FINAL_BUNDLE_PATH" "$FINAL_JELLYFIN_PATH" || return $?
957
+ chmod 0600 "$FINAL_CONTAINER_PATH" "$FINAL_BUNDLE_PATH" "$FINAL_JELLYFIN_PATH" || return $?
958
+ FINAL_AUTOSTART_COUNT=$(awk '$1 == "ouro-butler" { count++ } END { print count + 0 }' /var/lib/docker/unraid-autostart) || return $?
959
+ /usr/local/bin/node -e '
960
+ const fs = require("node:fs");
961
+ const [containerPath, bundlePath, installPath, jellyfinPath, outputPath, imageId, imageReference, icon, autostartCount] = process.argv.slice(1);
962
+ const containers = JSON.parse(fs.readFileSync(containerPath, "utf8"));
963
+ const bundle = JSON.parse(fs.readFileSync(bundlePath, "utf8"));
964
+ const install = JSON.parse(fs.readFileSync(installPath, "utf8"));
965
+ const jellyfin = JSON.parse(fs.readFileSync(jellyfinPath, "utf8"));
966
+ if (!Array.isArray(containers) || containers.length !== 1) process.exit(1);
967
+ const source = containers[0];
968
+ const labels = source.Config?.Labels;
969
+ const health = source.State?.Health?.Status;
970
+ if (source.Name !== "/ouro-butler" || source.Image !== imageId || source.Config?.Image !== imageReference || source.State?.Running !== true || health !== "healthy" || autostartCount !== "1" || labels?.["net.unraid.docker.managed"] !== "dockerman" || labels?.["net.unraid.docker.icon"] !== icon || Object.prototype.hasOwnProperty.call(labels ?? {}, "net.unraid.docker.webui")) process.exit(1);
971
+ if (bundle?.ok !== true || bundle?.data?.parity !== "exact" || bundle?.data?.journalState !== "absent" || bundle?.data?.ready !== true) process.exit(1);
972
+ const proof = { container: { name: source.Name, imageId: source.Image, imageReference: source.Config.Image, running: source.State.Running, healthy: health === "healthy", autostart: true, labels: { "net.unraid.docker.managed": labels["net.unraid.docker.managed"], "net.unraid.docker.icon": labels["net.unraid.docker.icon"] } }, bundle, ...install, jellyfin };
973
+ fs.writeFileSync(outputPath, `${JSON.stringify(proof)}\n`, { mode: 0o600, flag: "wx" });
974
+ ' "$FINAL_CONTAINER_PATH" "$FINAL_BUNDLE_PATH" "$FINAL_INSTALL_PATH" "$FINAL_JELLYFIN_PATH" "$FINAL_PROOF_PATH" "$FINAL_PROOF_IMAGE_ID" "$FINAL_PROOF_VERSION_IMAGE" "$FINAL_PROOF_ICON" "$FINAL_AUTOSTART_COUNT" || return $?
975
+ chown 0:0 "$FINAL_PROOF_PATH" || return $?
976
+ chmod 0600 "$FINAL_PROOF_PATH" || return $?
977
+ printf '%s\n' "$FINAL_PROOF_PATH"
978
+ }
979
+ start_only_butler_for_recovery() {
980
+ RECOVERY_AUTHORITY_STATE=$(read_sanctuary_authority_state) || return $?
981
+ if test "$RECOVERY_AUTHORITY_STATE" != none; then
982
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" authority-restore >/dev/null || return $?
983
+ assert_only_running_butler ouro-butler || return $?
984
+ return 0
985
+ fi
986
+ RECOVERY_START_STATE=$(docker inspect --format '{{.State.Running}}' ouro-butler) || return $?
987
+ case "$RECOVERY_START_STATE" in
988
+ true)
989
+ assert_only_running_butler ouro-butler || return $?
990
+ ;;
991
+ false)
992
+ assert_only_running_butler - || return $?
993
+ docker start ouro-butler || return $?
994
+ assert_only_running_butler ouro-butler || return $?
995
+ ;;
996
+ *) return 1 ;;
997
+ esac
998
+ }
999
+ recover_pending_sanctuary_bundle_migration() {
1000
+ RECOVERY_IMAGE_ID=$1
1001
+ RECOVERY_STATUS=$(read_sanctuary_bundle_transaction_status "$RECOVERY_IMAGE_ID") || return $?
1002
+ test "$RECOVERY_STATUS" != null || return 0
1003
+ RECOVERY_IDENTITIES=$(printf '%s' "$RECOVERY_STATUS" | /usr/local/bin/node -e '
1004
+ let input = "";
1005
+ process.stdin.setEncoding("utf8");
1006
+ process.stdin.on("data", chunk => { input += chunk; });
1007
+ process.stdin.on("end", () => {
1008
+ const value = JSON.parse(input);
1009
+ if (!value || !["rollback", "committing"].includes(value.state)
1010
+ || typeof value.rollbackImageId !== "string" || typeof value.targetImageId !== "string") process.exit(1);
1011
+ process.stdout.write(`${value.state} ${value.rollbackImageId} ${value.targetImageId}`);
1012
+ });
1013
+ ') || return $?
1014
+ set -- $RECOVERY_IDENTITIES
1015
+ test "$#" -eq 3 || return 1
1016
+ RECOVERY_STATE=$1
1017
+ RECOVERY_ROLLBACK_IMAGE_ID=$2
1018
+ RECOVERY_TARGET_IMAGE_ID=$3
1019
+ validate_exact_image_id "$RECOVERY_ROLLBACK_IMAGE_ID" || return $?
1020
+ validate_exact_image_id "$RECOVERY_TARGET_IMAGE_ID" || return $?
1021
+ test "$RECOVERY_TARGET_IMAGE_ID" != "$RECOVERY_ROLLBACK_IMAGE_ID" || return 1
1022
+ disable_butler_autostart || return $?
1023
+ if test "$RECOVERY_STATE" = committing; then
1024
+ ! docker container inspect ouro-butler-staging >/dev/null 2>&1 || return 1
1025
+ RECOVERY_PRODUCTION_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler) || return $?
1026
+ test "$(docker inspect --format '{{.State.Running}}' ouro-butler)" = true || return 1
1027
+ test "$RECOVERY_PRODUCTION_IMAGE_ID" = "$RECOVERY_TARGET_IMAGE_ID" || return 1
1028
+ RECOVERY_CURRENT_ROLLBACK_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-rollback) || return $?
1029
+ test "$RECOVERY_CURRENT_ROLLBACK_IMAGE_ID" = "$RECOVERY_ROLLBACK_IMAGE_ID" || return 1
1030
+ test "$(docker inspect --format '{{.State.Running}}' ouro-butler-rollback)" = false || return 1
1031
+ assert_only_running_butler ouro-butler || return $?
1032
+ assert_update_source "$RECOVERY_PRODUCTION_IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID" || return $?
1033
+ wait_butler_ready ouro-butler || return $?
1034
+ enable_butler_autostart || return $?
1035
+ migrate_sanctuary_package_managed_bundle "$RECOVERY_IMAGE_ID" commit || return $?
1036
+ return 0
1037
+ fi
1038
+ retire_sanctuary_authority_if_pending || return $?
1039
+ if docker container inspect ouro-butler-rollback >/dev/null 2>&1; then
1040
+ RECOVERY_CURRENT_ROLLBACK_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-rollback) || return $?
1041
+ test "$RECOVERY_CURRENT_ROLLBACK_IMAGE_ID" = "$RECOVERY_ROLLBACK_IMAGE_ID" || return 1
1042
+ test "$(docker inspect --format '{{.State.Running}}' ouro-butler-rollback)" = false || return 1
1043
+ if docker container inspect ouro-butler-staging >/dev/null 2>&1; then
1044
+ RECOVERY_STAGING_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-staging) || return $?
1045
+ test "$RECOVERY_STAGING_IMAGE_ID" = "$RECOVERY_TARGET_IMAGE_ID" || return 1
1046
+ docker stop ouro-butler-staging >/dev/null 2>&1 || true
1047
+ docker rm --force ouro-butler-staging || return $?
1048
+ fi
1049
+ if docker container inspect ouro-butler >/dev/null 2>&1; then
1050
+ RECOVERY_PRODUCTION_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler) || return $?
1051
+ test "$RECOVERY_PRODUCTION_IMAGE_ID" = "$RECOVERY_TARGET_IMAGE_ID" || return 1
1052
+ docker stop ouro-butler >/dev/null 2>&1 || true
1053
+ docker rm --force ouro-butler || return $?
1054
+ fi
1055
+ migrate_sanctuary_package_managed_bundle "$RECOVERY_IMAGE_ID" rollback || return $?
1056
+ docker rename ouro-butler-rollback ouro-butler || return $?
1057
+ elif docker container inspect ouro-butler >/dev/null 2>&1; then
1058
+ ! docker container inspect ouro-butler-staging >/dev/null 2>&1 || return 1
1059
+ RECOVERY_PRODUCTION_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler) || return $?
1060
+ test "$RECOVERY_PRODUCTION_IMAGE_ID" = "$RECOVERY_ROLLBACK_IMAGE_ID" || return 1
1061
+ ! docker container inspect ouro-butler-rollback >/dev/null 2>&1 || return 1
1062
+ migrate_sanctuary_package_managed_bundle "$RECOVERY_IMAGE_ID" rollback || return $?
1063
+ else
1064
+ return 1
1065
+ fi
1066
+ RECOVERY_PRODUCTION_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler) || return $?
1067
+ test "$RECOVERY_PRODUCTION_IMAGE_ID" = "$RECOVERY_ROLLBACK_IMAGE_ID" || return 1
1068
+ assert_update_source "$RECOVERY_ROLLBACK_IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID" || return $?
1069
+ start_only_butler_for_recovery || return $?
1070
+ wait_butler_ready ouro-butler || return $?
1071
+ enable_butler_autostart || return $?
1072
+ migrate_sanctuary_package_managed_bundle "$RECOVERY_IMAGE_ID" finalize-rollback || return $?
1073
+ }
1074
+ rollback_sanctuary_bundle_if_pending() {
1075
+ OPTIONAL_ROLLBACK_IMAGE_ID=$1
1076
+ OPTIONAL_ROLLBACK_RECORD=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro/.sanctuary-package-managed-rollback.json
1077
+ OPTIONAL_COMMITTING_RECORD=$OPTIONAL_ROLLBACK_RECORD.committing
1078
+ test ! -L "$OPTIONAL_ROLLBACK_RECORD" || return 1
1079
+ test ! -L "$OPTIONAL_COMMITTING_RECORD" || return 1
1080
+ test ! -e "$OPTIONAL_COMMITTING_RECORD" || return 1
1081
+ if test -e "$OPTIONAL_ROLLBACK_RECORD"; then
1082
+ test -f "$OPTIONAL_ROLLBACK_RECORD" || return 1
1083
+ migrate_sanctuary_package_managed_bundle "$OPTIONAL_ROLLBACK_IMAGE_ID" rollback || return $?
1084
+ fi
1085
+ }
1086
+ finalize_sanctuary_bundle_rollback_if_retained() {
1087
+ FINALIZE_ROLLBACK_IMAGE_ID=$1
1088
+ FINALIZE_ROLLBACK_STATUS=$(read_sanctuary_bundle_transaction_status "$FINALIZE_ROLLBACK_IMAGE_ID") || return $?
1089
+ test "$FINALIZE_ROLLBACK_STATUS" != null || return 0
1090
+ FINALIZE_ROLLBACK_STATE=$(printf '%s' "$FINALIZE_ROLLBACK_STATUS" | /usr/local/bin/node -e '
1091
+ let input = "";
1092
+ process.stdin.setEncoding("utf8");
1093
+ process.stdin.on("data", chunk => { input += chunk; });
1094
+ process.stdin.on("end", () => {
1095
+ const value = JSON.parse(input);
1096
+ if (!value || !["rollback", "committing"].includes(value.state)) process.exit(1);
1097
+ process.stdout.write(value.state);
1098
+ });
1099
+ ') || return $?
1100
+ test "$FINALIZE_ROLLBACK_STATE" = rollback || return 1
1101
+ migrate_sanctuary_package_managed_bundle "$FINALIZE_ROLLBACK_IMAGE_ID" finalize-rollback || return $?
1102
+ }
1103
+ write_dockerman_recovery_evidence() {
1104
+ RECOVERY_EVIDENCE_BUNDLE_STATE=$1
1105
+ RECOVERY_EVIDENCE_PRODUCTION=$2
1106
+ RECOVERY_EVIDENCE_INSPECTION_PATH=$3
1107
+ RECOVERY_EVIDENCE_PATH=$4
1108
+ test ! -e "$RECOVERY_EVIDENCE_PATH" || return 1
1109
+ /usr/local/bin/node -e '
1110
+ const fs = require("node:fs");
1111
+ const [bundleJournalState, production, inspectionPath, outputPath] = process.argv.slice(1);
1112
+ const evidence = { bundleJournalState, production };
1113
+ if (inspectionPath !== "-") evidence.inspection = JSON.parse(fs.readFileSync(inspectionPath, "utf8"));
1114
+ fs.writeFileSync(outputPath, `${JSON.stringify(evidence)}\n`, { mode: 0o600, flag: "wx" });
1115
+ ' "$RECOVERY_EVIDENCE_BUNDLE_STATE" "$RECOVERY_EVIDENCE_PRODUCTION" "$RECOVERY_EVIDENCE_INSPECTION_PATH" "$RECOVERY_EVIDENCE_PATH" || return $?
1116
+ chown 0:0 "$RECOVERY_EVIDENCE_PATH" || return $?
1117
+ chmod 0600 "$RECOVERY_EVIDENCE_PATH" || return $?
1118
+ }
1119
+ recover_dockerman_template_transaction() {
1120
+ TEMPLATE_RECOVERY_IDENTITY=$(/usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" recovery-identity) || return $?
1121
+ if test "$TEMPLATE_RECOVERY_IDENTITY" = null; then
1122
+ test "$(/usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" recover-status)" = null || return 1
1123
+ return 0
1124
+ fi
1125
+ TEMPLATE_RECOVERY_IDENTITIES=$(printf '%s' "$TEMPLATE_RECOVERY_IDENTITY" | /usr/local/bin/node -e '
1126
+ let input = "";
1127
+ process.stdin.setEncoding("utf8");
1128
+ process.stdin.on("data", chunk => { input += chunk; });
1129
+ process.stdin.on("end", () => {
1130
+ const value = JSON.parse(input);
1131
+ if (!value || !["rollback", "committing"].includes(value.state)) process.exit(1);
1132
+ process.stdout.write([value.state, value.rollbackImageId, value.targetImageId, value.canonicalVersionTag, value.reviewedManifestDigest].join(" "));
1133
+ });
1134
+ ') || return $?
1135
+ set -- $TEMPLATE_RECOVERY_IDENTITIES
1136
+ test "$#" -eq 5 || return 1
1137
+ TEMPLATE_RECOVERY_STATE=$1
1138
+ TEMPLATE_RECOVERY_ROLLBACK_IMAGE_ID=$2
1139
+ TEMPLATE_RECOVERY_TARGET_IMAGE_ID=$3
1140
+ TEMPLATE_RECOVERY_VERSION_IMAGE=$4
1141
+ TEMPLATE_RECOVERY_MANIFEST_DIGEST=$5
1142
+ test "$TEMPLATE_RECOVERY_TARGET_IMAGE_ID" = "$IMAGE_ID" || return 1
1143
+ test "$TEMPLATE_RECOVERY_VERSION_IMAGE" = "$VERSION_IMAGE" || return 1
1144
+ test "$TEMPLATE_RECOVERY_MANIFEST_DIGEST" = "$MANIFEST_DIGEST" || return 1
1145
+ validate_exact_image_id "$TEMPLATE_RECOVERY_ROLLBACK_IMAGE_ID" || return $?
1146
+ TEMPLATE_RECOVERY_BUNDLE_STATUS=$(read_sanctuary_bundle_transaction_status "$IMAGE_ID") || return $?
1147
+ TEMPLATE_RECOVERY_BUNDLE_IDENTITIES=$(printf '%s' "$TEMPLATE_RECOVERY_BUNDLE_STATUS" | /usr/local/bin/node -e '
1148
+ let input = "";
1149
+ process.stdin.setEncoding("utf8");
1150
+ process.stdin.on("data", chunk => { input += chunk; });
1151
+ process.stdin.on("end", () => {
1152
+ const value = JSON.parse(input);
1153
+ if (value === null) process.stdout.write("absent - -");
1154
+ else if (value && ["rollback", "committing"].includes(value.state) && typeof value.rollbackImageId === "string" && typeof value.targetImageId === "string") process.stdout.write([value.state, value.rollbackImageId, value.targetImageId].join(" "));
1155
+ else process.exit(1);
1156
+ });
1157
+ ') || return $?
1158
+ set -- $TEMPLATE_RECOVERY_BUNDLE_IDENTITIES
1159
+ test "$#" -eq 3 || return 1
1160
+ TEMPLATE_RECOVERY_BUNDLE_STATE=$1
1161
+ TEMPLATE_RECOVERY_BUNDLE_ROLLBACK_IMAGE_ID=$2
1162
+ TEMPLATE_RECOVERY_BUNDLE_TARGET_IMAGE_ID=$3
1163
+ if test "$TEMPLATE_RECOVERY_BUNDLE_STATE" = absent; then
1164
+ test "$TEMPLATE_RECOVERY_BUNDLE_ROLLBACK_IMAGE_ID" = - && test "$TEMPLATE_RECOVERY_BUNDLE_TARGET_IMAGE_ID" = - || return 1
1165
+ else
1166
+ validate_exact_image_id "$TEMPLATE_RECOVERY_BUNDLE_ROLLBACK_IMAGE_ID" || return $?
1167
+ validate_exact_image_id "$TEMPLATE_RECOVERY_BUNDLE_TARGET_IMAGE_ID" || return $?
1168
+ test "$TEMPLATE_RECOVERY_BUNDLE_ROLLBACK_IMAGE_ID" != "$TEMPLATE_RECOVERY_BUNDLE_TARGET_IMAGE_ID" || return 1
1169
+ test "$TEMPLATE_RECOVERY_BUNDLE_ROLLBACK_IMAGE_ID" = "$TEMPLATE_RECOVERY_ROLLBACK_IMAGE_ID" || return 1
1170
+ test "$TEMPLATE_RECOVERY_BUNDLE_TARGET_IMAGE_ID" = "$TEMPLATE_RECOVERY_TARGET_IMAGE_ID" || return 1
1171
+ fi
1172
+ TEMPLATE_RECOVERY_STATUS=$(/usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" recover-status) || return $?
1173
+ test "$TEMPLATE_RECOVERY_STATUS" = "$TEMPLATE_RECOVERY_IDENTITY" || return 1
1174
+ TEMPLATE_RECOVERY_EVIDENCE=$EVENT_ASSET_STAGE/template-recovery-evidence.json
1175
+ TEMPLATE_RECOVERY_INSPECTION=$EVENT_ASSET_STAGE/template-recovery-inspection.json
1176
+ TEMPLATE_RECOVERY_FINAL_ROOT=$EVENT_ASSET_STAGE/template-recovery-final
1177
+ if test "$TEMPLATE_RECOVERY_STATE" = rollback; then
1178
+ disable_butler_autostart || return $?
1179
+ retire_sanctuary_authority_if_pending || return $?
1180
+ fi
1181
+ if test "$TEMPLATE_RECOVERY_BUNDLE_STATE" = rollback; then
1182
+ recover_pending_sanctuary_bundle_migration "$IMAGE_ID" || return $?
1183
+ TEMPLATE_RECOVERY_POST_BUNDLE_STATUS=$(read_sanctuary_bundle_transaction_status "$IMAGE_ID") || return $?
1184
+ test "$TEMPLATE_RECOVERY_POST_BUNDLE_STATUS" = null || return 1
1185
+ test "$(docker inspect --format '{{.Image}}' ouro-butler)" = "$TEMPLATE_RECOVERY_ROLLBACK_IMAGE_ID" || return 1
1186
+ write_dockerman_recovery_evidence absent rollback-exact - "$TEMPLATE_RECOVERY_EVIDENCE" || return $?
1187
+ test "$(/usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" recovery-action --evidence "$TEMPLATE_RECOVERY_EVIDENCE")" = '{"action":"restore-prior-template"}' || return 1
1188
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" rollback >/dev/null || return $?
1189
+ return 0
1190
+ fi
1191
+ TEMPLATE_RECOVERY_PRODUCTION_PRESENT=false
1192
+ TEMPLATE_RECOVERY_PRODUCTION_IMAGE_ID=
1193
+ if docker container inspect ouro-butler >/dev/null 2>&1; then
1194
+ TEMPLATE_RECOVERY_PRODUCTION_PRESENT=true
1195
+ TEMPLATE_RECOVERY_PRODUCTION_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler) || return $?
1196
+ fi
1197
+ if test "$TEMPLATE_RECOVERY_BUNDLE_STATE" = committing; then
1198
+ test "$TEMPLATE_RECOVERY_PRODUCTION_PRESENT" = true || return 1
1199
+ test "$TEMPLATE_RECOVERY_STATE" = committing || return 1
1200
+ test "$TEMPLATE_RECOVERY_PRODUCTION_IMAGE_ID" = "$IMAGE_ID" || return 1
1201
+ test "$(docker inspect --format '{{.Image}}' ouro-butler-rollback)" = "$TEMPLATE_RECOVERY_ROLLBACK_IMAGE_ID" || return 1
1202
+ test "$(docker inspect --format '{{.State.Running}}' ouro-butler-rollback)" = false || return 1
1203
+ assert_only_running_butler ouro-butler || return $?
1204
+ audit_effective ouro-butler "$IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID" "$TARGET_MOUNT_CONTRACT" "$VERSION_IMAGE" "$TEMPLATE_ICON" || return $?
1205
+ migrate_sanctuary_package_managed_bundle "$IMAGE_ID" inspect >"$TEMPLATE_RECOVERY_INSPECTION" || return $?
1206
+ chown 0:0 "$TEMPLATE_RECOVERY_INSPECTION" && chmod 0600 "$TEMPLATE_RECOVERY_INSPECTION" || return $?
1207
+ write_dockerman_recovery_evidence committing target-exact-committing "$TEMPLATE_RECOVERY_INSPECTION" "$TEMPLATE_RECOVERY_EVIDENCE" || return $?
1208
+ test "$(/usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" recovery-action --evidence "$TEMPLATE_RECOVERY_EVIDENCE")" = '{"action":"finish-bundle-commit"}' || return 1
1209
+ migrate_sanctuary_package_managed_bundle "$IMAGE_ID" commit || return $?
1210
+ wait_butler_ready ouro-butler || return $?
1211
+ test "$(docker inspect --format '{{.Image}}' ouro-butler)" = "$IMAGE_ID" || return 1
1212
+ verify_butler_autostart "1 0 0 0" || return $?
1213
+ elif test "$TEMPLATE_RECOVERY_BUNDLE_STATE" = absent && test "$TEMPLATE_RECOVERY_PRODUCTION_PRESENT" = false; then
1214
+ test "$TEMPLATE_RECOVERY_STATE" = rollback || return 1
1215
+ ! docker container inspect ouro-butler-staging >/dev/null 2>&1 || return 1
1216
+ assert_only_running_butler - || return $?
1217
+ if docker container inspect ouro-butler-rollback >/dev/null 2>&1; then
1218
+ TEMPLATE_RECOVERY_CURRENT_ROLLBACK_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-rollback) || return $?
1219
+ test "$TEMPLATE_RECOVERY_CURRENT_ROLLBACK_IMAGE_ID" = "$TEMPLATE_RECOVERY_ROLLBACK_IMAGE_ID" || return 1
1220
+ test "$(docker inspect --format '{{.State.Running}}' ouro-butler-rollback)" = false || return 1
1221
+ docker rename ouro-butler-rollback ouro-butler || return $?
1222
+ assert_update_source "$TEMPLATE_RECOVERY_ROLLBACK_IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID" || return $?
1223
+ start_only_butler_for_recovery || return $?
1224
+ wait_butler_ready ouro-butler || return $?
1225
+ enable_butler_autostart || return $?
1226
+ write_dockerman_recovery_evidence absent rollback-exact - "$TEMPLATE_RECOVERY_EVIDENCE" || return $?
1227
+ test "$(/usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" recovery-action --evidence "$TEMPLATE_RECOVERY_EVIDENCE")" = '{"action":"restore-prior-template"}' || return 1
1228
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" rollback >/dev/null || return $?
1229
+ return 0
1230
+ fi
1231
+ TEMPLATE_RECOVERY_LEGACY_EVIDENCE_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-legacy-evidence) || return $?
1232
+ test "$TEMPLATE_RECOVERY_LEGACY_EVIDENCE_IMAGE_ID" = "$TEMPLATE_RECOVERY_ROLLBACK_IMAGE_ID" || return 1
1233
+ test "$(docker inspect --format '{{.State.Running}}' ouro-butler-legacy-evidence)" = false || return 1
1234
+ write_dockerman_recovery_evidence absent adoption-evidence-exact-stopped - "$TEMPLATE_RECOVERY_EVIDENCE" || return $?
1235
+ test "$(/usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" recovery-action --evidence "$TEMPLATE_RECOVERY_EVIDENCE")" = '{"action":"quarantine-adoption"}' || return 1
1236
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" rollback >/dev/null || return $?
1237
+ printf '%s\n' 'Legacy adoption recovery requires a reviewed retry; exact legacy evidence remains quarantined and stopped.' >&2
1238
+ return 1
1239
+ elif test "$TEMPLATE_RECOVERY_BUNDLE_STATE" = absent && test "$TEMPLATE_RECOVERY_STATE" = rollback && test "$TEMPLATE_RECOVERY_PRODUCTION_IMAGE_ID" = "$TEMPLATE_RECOVERY_ROLLBACK_IMAGE_ID"; then
1240
+ ! docker container inspect ouro-butler-staging >/dev/null 2>&1 || return 1
1241
+ ! docker container inspect ouro-butler-rollback >/dev/null 2>&1 || return 1
1242
+ assert_update_source "$TEMPLATE_RECOVERY_ROLLBACK_IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID" || return $?
1243
+ start_only_butler_for_recovery || return $?
1244
+ wait_butler_ready ouro-butler || return $?
1245
+ enable_butler_autostart || return $?
1246
+ write_dockerman_recovery_evidence absent rollback-exact - "$TEMPLATE_RECOVERY_EVIDENCE" || return $?
1247
+ test "$(/usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" recovery-action --evidence "$TEMPLATE_RECOVERY_EVIDENCE")" = '{"action":"restore-prior-template"}' || return 1
1248
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" rollback >/dev/null || return $?
1249
+ return 0
1250
+ elif test "$TEMPLATE_RECOVERY_BUNDLE_STATE" = absent && test "$TEMPLATE_RECOVERY_STATE" = rollback && test "$TEMPLATE_RECOVERY_PRODUCTION_IMAGE_ID" = "$IMAGE_ID"; then
1251
+ ! docker container inspect ouro-butler-staging >/dev/null 2>&1 || return 1
1252
+ ! docker container inspect ouro-butler-rollback >/dev/null 2>&1 || return 1
1253
+ TEMPLATE_RECOVERY_LEGACY_EVIDENCE_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-legacy-evidence) || return $?
1254
+ test "$TEMPLATE_RECOVERY_LEGACY_EVIDENCE_IMAGE_ID" = "$TEMPLATE_RECOVERY_ROLLBACK_IMAGE_ID" || return 1
1255
+ test "$(docker inspect --format '{{.State.Running}}' ouro-butler-legacy-evidence)" = false || return 1
1256
+ audit_effective ouro-butler "$IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID" "$TARGET_MOUNT_CONTRACT" "$VERSION_IMAGE" "$TEMPLATE_ICON" || return $?
1257
+ start_only_butler_for_recovery || return $?
1258
+ wait_butler_ready ouro-butler || return $?
1259
+ migrate_sanctuary_package_managed_bundle "$IMAGE_ID" inspect >"$TEMPLATE_RECOVERY_INSPECTION" || return $?
1260
+ chown 0:0 "$TEMPLATE_RECOVERY_INSPECTION" && chmod 0600 "$TEMPLATE_RECOVERY_INSPECTION" || return $?
1261
+ write_dockerman_recovery_evidence absent adoption-target-exact-ready "$TEMPLATE_RECOVERY_INSPECTION" "$TEMPLATE_RECOVERY_EVIDENCE" || return $?
1262
+ test "$(/usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" recovery-action --evidence "$TEMPLATE_RECOVERY_EVIDENCE")" = '{"action":"roll-forward-adoption"}' || return 1
1263
+ enable_butler_autostart || return $?
1264
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" mark-committing >/dev/null || return $?
1265
+ elif test "$TEMPLATE_RECOVERY_BUNDLE_STATE" = absent && test "$TEMPLATE_RECOVERY_STATE" = committing && test "$TEMPLATE_RECOVERY_PRODUCTION_IMAGE_ID" = "$IMAGE_ID"; then
1266
+ audit_effective ouro-butler "$IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID" "$TARGET_MOUNT_CONTRACT" "$VERSION_IMAGE" "$TEMPLATE_ICON" || return $?
1267
+ wait_butler_ready ouro-butler || return $?
1268
+ verify_butler_autostart "1 0 0 0" || return $?
1269
+ migrate_sanctuary_package_managed_bundle "$IMAGE_ID" inspect >"$TEMPLATE_RECOVERY_INSPECTION" || return $?
1270
+ chown 0:0 "$TEMPLATE_RECOVERY_INSPECTION" && chmod 0600 "$TEMPLATE_RECOVERY_INSPECTION" || return $?
1271
+ write_dockerman_recovery_evidence absent target-exact-ready "$TEMPLATE_RECOVERY_INSPECTION" "$TEMPLATE_RECOVERY_EVIDENCE" || return $?
1272
+ test "$(/usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" recovery-action --evidence "$TEMPLATE_RECOVERY_EVIDENCE")" = '{"action":"finish-template-commit"}' || return 1
1273
+ else
1274
+ return 1
1275
+ fi
1276
+ TEMPLATE_RECOVERY_FINAL_PROOF=$(write_dockerman_final_proof "$IMAGE_ID" "$VERSION_IMAGE" "$TEMPLATE_ICON" "$TEMPLATE_RECOVERY_FINAL_ROOT") || return $?
1277
+ verify_known_good_rollback_artifact "$TEMPLATE_RECOVERY_ROLLBACK_IMAGE_ID" || return $?
1278
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" commit --proof "$TEMPLATE_RECOVERY_FINAL_PROOF" >/dev/null || return $?
1279
+ }
1280
+ # Package installation and migration never grant restart authority. The
1281
+ # migration is the pre-activation assertion: it fails before live mutation
1282
+ # if packaged steward.json carries any routine grant. It preserves an
1283
+ # existing live steward policy and its audit receipts byte for byte. On a
1284
+ # new installation, start the healthy private runtime, then use
1285
+ # an authenticated owner Telegram turn to grant each exact restart target
1286
+ # through steward_policy_manage. That existing tool binds the grant to the
1287
+ # verified owner relationship and durable session event. Do not seed grants
1288
+ # in the packaged steward.json, copy an old session-event ID, or edit the
1289
+ # live policy/audit files directly. A missing grant remains fail-closed until
1290
+ # that explicit owner ceremony succeeds.
1291
+ prepare_canonical_sanctuary_roots() {
1292
+ PREPARE_IMAGE_ID=$1
1293
+ validate_exact_image_id "$PREPARE_IMAGE_ID" || return $?
1294
+ PREPARE_RUNTIME_ROOT=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli
1295
+ PREPARE_AGENT_ROOT=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro
1296
+ install -d -m 0700 -o 10001 -g 10001 "$PREPARE_RUNTIME_ROOT" || return $?
1297
+ install -d -m 0700 -o 10001 -g 10001 "$PREPARE_AGENT_ROOT" || return $?
1298
+ ensure_sanctuary_machine_identity "$PREPARE_RUNTIME_ROOT/machine.json" || return $?
1299
+ if test ! -f "$PREPARE_AGENT_ROOT/agent.json"; then
1300
+ PREPARE_EXISTING_ENTRY=$(find "$PREPARE_AGENT_ROOT" -mindepth 1 -print -quit) || return $?
1301
+ test -z "$PREPARE_EXISTING_ENTRY" || return $?
1302
+ ! docker container inspect ouro-butler-bundle-bootstrap >/dev/null 2>&1 || return 1
1303
+ docker run --rm --pull=never --network=none --name ouro-butler-bundle-bootstrap --user 10001:10001 \
1304
+ --mount "type=bind,src=$PREPARE_RUNTIME_ROOT,dst=/home/ouro/.ouro-cli" \
1305
+ --mount "type=bind,src=$PREPARE_AGENT_ROOT,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
1306
+ --entrypoint /bin/sh "$PREPARE_IMAGE_ID" -ceu '
1307
+ cp -R /opt/ouro/deploy/unraid/sanctuary.ouro/. /home/ouro/AgentBundles/sanctuary.ouro/
1308
+ find /home/ouro/AgentBundles/sanctuary.ouro -type d -exec chmod 0700 {} +
1309
+ find /home/ouro/AgentBundles/sanctuary.ouro -type f -exec chmod 0600 {} +
1310
+ ' || return $?
1311
+ ! docker container inspect ouro-butler-bundle-bootstrap >/dev/null 2>&1 || return 1
1312
+ fi
1313
+ for PREPARE_REQUIRED_FILE in \
1314
+ agent.json bundle-meta.json provider-readiness.json tool-profiles.json \
1315
+ psyche/SOUL.md habits/sanctuary-health.md; do
1316
+ test -f "$PREPARE_AGENT_ROOT/$PREPARE_REQUIRED_FILE" || return $?
1317
+ done
1318
+ PREPARE_WRONG_OWNER=$(find "$PREPARE_RUNTIME_ROOT" "$PREPARE_AGENT_ROOT" \( ! -user 10001 -o ! -group 10001 \) -print -quit) || return $?
1319
+ test -z "$PREPARE_WRONG_OWNER" || return $?
1320
+ PREPARE_WRONG_DIR_MODE=$(find "$PREPARE_RUNTIME_ROOT" "$PREPARE_AGENT_ROOT" -type d ! -perm 0700 -print -quit) || return $?
1321
+ test -z "$PREPARE_WRONG_DIR_MODE" || return $?
1322
+ PREPARE_WRONG_FILE_MODE=$(find "$PREPARE_RUNTIME_ROOT" "$PREPARE_AGENT_ROOT" -type f ! -perm 0600 -print -quit) || return $?
1323
+ test -z "$PREPARE_WRONG_FILE_MODE" || return $?
1324
+ }
1325
+ classify_sanctuary_update_source() {
1326
+ UPDATE_ENTRY_CONTAINER_NAMES=$(docker container ls -a --format '{{.Names}}') || return $?
1327
+ if printf '%s\n' "$UPDATE_ENTRY_CONTAINER_NAMES" | grep -Fxq ouro-butler-staging; then
1328
+ return 1
1329
+ else
1330
+ UPDATE_ENTRY_SOURCE_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler) || return $?
1331
+ assert_update_topology "$UPDATE_ENTRY_SOURCE_IMAGE_ID" || return $?
1332
+ assert_sanctuary_update_source_pin ouro-butler "$UPDATE_ENTRY_SOURCE_IMAGE_ID"
1333
+ fi
1334
+ }
1335
+ admit_sanctuary_update_entry() {
1336
+ UPDATE_ENTRY_RECOVERY_JOURNAL=/boot/config/custom/ouro-butler/docker-man-template-transaction.json
1337
+ if test -e "$UPDATE_ENTRY_RECOVERY_JOURNAL" || test -L "$UPDATE_ENTRY_RECOVERY_JOURNAL"; then
1338
+ test -f "$UPDATE_ENTRY_RECOVERY_JOURNAL" && test ! -L "$UPDATE_ENTRY_RECOVERY_JOURNAL" || return 1
1339
+ test "$(stat -c '%u:%g:%a' "$UPDATE_ENTRY_RECOVERY_JOURNAL")" = 0:0:600
1340
+ else
1341
+ classify_sanctuary_update_source
1342
+ fi
1343
+ }
1344
+ validate_sanctuary_legacy_import_marker() {
1345
+ IMPORT_MARKER=$1
1346
+ IMPORT_SOURCE=$2
1347
+ test -f "$IMPORT_MARKER" && test ! -L "$IMPORT_MARKER" || return 1
1348
+ test "$(stat -c '%u:%g %a' "$IMPORT_MARKER")" = "10001:10001 600" || return 1
1349
+ /usr/local/bin/node -e '
1350
+ const crypto = require("node:crypto");
1351
+ const fs = require("node:fs");
1352
+ const marker = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
1353
+ const sourceDigest = `sha256:${crypto.createHash("sha256").update(fs.readFileSync(process.argv[2])).digest("hex")}`;
1354
+ if (JSON.stringify(Object.keys(marker).sort()) !== JSON.stringify(["importedAt", "machineId", "schemaVersion", "sourceDigest"])) process.exit(1);
1355
+ if (marker.schemaVersion !== 1 || marker.machineId !== "sanctuary" || marker.sourceDigest !== sourceDigest) process.exit(1);
1356
+ if (!Number.isFinite(Date.parse(marker.importedAt))) process.exit(1);
1357
+ ' "$IMPORT_MARKER" "$IMPORT_SOURCE"
1358
+ }
1359
+ record_sanctuary_legacy_import_marker() {
1360
+ IMPORT_MARKER=$1
1361
+ IMPORT_SOURCE=$2
1362
+ test ! -e "$IMPORT_MARKER" || return 1
1363
+ IMPORT_MARKER_TMP=$(mktemp "${IMPORT_MARKER}.tmp.XXXXXX") || return $?
1364
+ trap 'rm -f -- "$IMPORT_MARKER_TMP"' EXIT || return $?
1365
+ /usr/local/bin/node -e '
1366
+ const crypto = require("node:crypto");
1367
+ const fs = require("node:fs");
1368
+ const sourceDigest = `sha256:${crypto.createHash("sha256").update(fs.readFileSync(process.argv[2])).digest("hex")}`;
1369
+ const marker = { schemaVersion: 1, machineId: "sanctuary", sourceDigest, importedAt: new Date().toISOString() };
1370
+ fs.writeFileSync(process.argv[1], `${JSON.stringify(marker)}\n`, { mode: 0o600, flag: "w" });
1371
+ ' "$IMPORT_MARKER_TMP" "$IMPORT_SOURCE" || return $?
1372
+ chown 10001:10001 "$IMPORT_MARKER_TMP" || return $?
1373
+ chmod 0600 "$IMPORT_MARKER_TMP" || return $?
1374
+ mv -f -- "$IMPORT_MARKER_TMP" "$IMPORT_MARKER" || return $?
1375
+ sync -f "$IMPORT_MARKER" || return $?
1376
+ sync -f "$(dirname "$IMPORT_MARKER")" || return $?
1377
+ trap - EXIT || return $?
1378
+ }
1379
+ bootstrap_sanctuary_vault() {
1380
+ BOOTSTRAP_IMAGE_ID=$1
1381
+ BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE=${2-}
1382
+ BOOTSTRAP_SOURCE_MACHINE_ID=${3-}
1383
+ BOOTSTRAP_TARGET_MACHINE_ID=${4-}
1384
+ validate_exact_image_id "$BOOTSTRAP_IMAGE_ID" || return $?
1385
+ case "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" in
1386
+ "")
1387
+ test -z "$BOOTSTRAP_SOURCE_MACHINE_ID" || return 1
1388
+ test -z "$BOOTSTRAP_TARGET_MACHINE_ID" || return 1
1389
+ ;;
1390
+ /mnt/user/appdata/ouro-butler/runtime/container-credentials.json)
1391
+ test "$BOOTSTRAP_SOURCE_MACHINE_ID" = sanctuary-unraid || return 1
1392
+ test "$BOOTSTRAP_TARGET_MACHINE_ID" = sanctuary || return 1
1393
+ ;;
1394
+ *) return 1 ;;
1395
+ esac
1396
+ BOOTSTRAP_RUNTIME_ROOT=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli
1397
+ BOOTSTRAP_AGENT_ROOT=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro
1398
+ for BOOTSTRAP_CONTAINER in ouro-butler-vault-status ouro-butler-vault-bootstrap ouro-butler-credential-bootstrap ouro-butler-provider-readiness; do
1399
+ ! docker container inspect "$BOOTSTRAP_CONTAINER" >/dev/null 2>&1 || return 1
1400
+ done
1401
+ VAULT_STATUS=$(docker run --rm --pull=never --network host --name ouro-butler-vault-status --user 10001:10001 \
1402
+ --mount "type=bind,src=$BOOTSTRAP_RUNTIME_ROOT,dst=/home/ouro/.ouro-cli" \
1403
+ --mount "type=bind,src=$BOOTSTRAP_AGENT_ROOT,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
1404
+ --entrypoint node "$BOOTSTRAP_IMAGE_ID" /opt/ouro/dist/heart/daemon/ouro-entry.js \
1405
+ vault status --agent sanctuary --store plaintext-file) || return $?
1406
+ ! docker container inspect ouro-butler-vault-status >/dev/null 2>&1 || return 1
1407
+ case "
1408
+ $VAULT_STATUS
1409
+ " in
1410
+ *"
1411
+ vault locator: not configured in agent.json
1412
+ "*) VAULT_ACTION=create ;;
1413
+ *"
1414
+ vault locator: agent.json
1415
+ "*)
1416
+ case "
1417
+ $VAULT_STATUS
1418
+ " in
1419
+ *"
1420
+ local unlock: available
1421
+ "*) VAULT_ACTION=none ;;
1422
+ *"
1423
+ local unlock: missing
1424
+ "*) VAULT_ACTION=unlock ;;
1425
+ *) return 1 ;;
1426
+ esac
1427
+ ;;
1428
+ *) return 1 ;;
1429
+ esac
1430
+ if test "$VAULT_ACTION" != none; then
1431
+ docker run --rm -it --pull=never --network host --name ouro-butler-vault-bootstrap --user 10001:10001 \
1432
+ --mount "type=bind,src=$BOOTSTRAP_RUNTIME_ROOT,dst=/home/ouro/.ouro-cli" \
1433
+ --mount "type=bind,src=$BOOTSTRAP_AGENT_ROOT,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
1434
+ --entrypoint node "$BOOTSTRAP_IMAGE_ID" /opt/ouro/dist/heart/daemon/ouro-entry.js \
1435
+ vault "$VAULT_ACTION" --agent sanctuary --store plaintext-file || return $?
1436
+ ! docker container inspect ouro-butler-vault-bootstrap >/dev/null 2>&1 || return 1
1437
+ fi
1438
+ VERIFIED_VAULT_STATUS=$(docker run --rm --pull=never --network host --name ouro-butler-vault-status --user 10001:10001 \
1439
+ --mount "type=bind,src=$BOOTSTRAP_RUNTIME_ROOT,dst=/home/ouro/.ouro-cli" \
1440
+ --mount "type=bind,src=$BOOTSTRAP_AGENT_ROOT,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
1441
+ --entrypoint node "$BOOTSTRAP_IMAGE_ID" /opt/ouro/dist/heart/daemon/ouro-entry.js \
1442
+ vault status --agent sanctuary --store plaintext-file) || return $?
1443
+ ! docker container inspect ouro-butler-vault-status >/dev/null 2>&1 || return 1
1444
+ case "
1445
+ $VERIFIED_VAULT_STATUS
1446
+ " in
1447
+ *"
1448
+ vault locator: agent.json
1449
+ "*) ;;
1450
+ *) return 1 ;;
1451
+ esac
1452
+ case "
1453
+ $VERIFIED_VAULT_STATUS
1454
+ " in
1455
+ *"
1456
+ local unlock: available
1457
+ "*) ;;
1458
+ *) return 1 ;;
1459
+ esac
1460
+ if test -n "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE"; then
1461
+ BOOTSTRAP_CREDENTIAL_SOURCE="$BOOTSTRAP_RUNTIME_ROOT/container-credentials.json"
1462
+ BOOTSTRAP_CREDENTIAL_CLAIM="$BOOTSTRAP_CREDENTIAL_SOURCE.consuming"
1463
+ test -f "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" || return $?
1464
+ test ! -L "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" || return $?
1465
+ BOOTSTRAP_LEGACY_METADATA=$(stat -c '%u:%g %a' "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE") || return $?
1466
+ test "$BOOTSTRAP_LEGACY_METADATA" = "10001:10001 600" || return $?
1467
+ BOOTSTRAP_IMPORT_MARKER="$BOOTSTRAP_RUNTIME_ROOT/legacy-credentials-imported.json"
1468
+ if test -e "$BOOTSTRAP_IMPORT_MARKER"; then
1469
+ validate_sanctuary_legacy_import_marker "$BOOTSTRAP_IMPORT_MARKER" "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" || return $?
1470
+ test ! -e "$BOOTSTRAP_CREDENTIAL_SOURCE" || return 1
1471
+ test ! -e "$BOOTSTRAP_CREDENTIAL_CLAIM" || return 1
1472
+ else
1473
+ if test -e "$BOOTSTRAP_CREDENTIAL_SOURCE"; then
1474
+ test -f "$BOOTSTRAP_CREDENTIAL_SOURCE" || return $?
1475
+ test ! -L "$BOOTSTRAP_CREDENTIAL_SOURCE" || return $?
1476
+ test "$(stat -c '%u:%g %a' "$BOOTSTRAP_CREDENTIAL_SOURCE")" = "10001:10001 600" || return $?
1477
+ cmp -s "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" "$BOOTSTRAP_CREDENTIAL_SOURCE" || return $?
1478
+ elif test -e "$BOOTSTRAP_CREDENTIAL_CLAIM"; then
1479
+ test -f "$BOOTSTRAP_CREDENTIAL_CLAIM" || return $?
1480
+ test ! -L "$BOOTSTRAP_CREDENTIAL_CLAIM" || return $?
1481
+ test "$(stat -c '%u:%g %a' "$BOOTSTRAP_CREDENTIAL_CLAIM")" = "10001:10001 600" || return $?
1482
+ cmp -s "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" "$BOOTSTRAP_CREDENTIAL_CLAIM" || return $?
1483
+ else
1484
+ BOOTSTRAP_CREDENTIAL_TMP=$(mktemp "$BOOTSTRAP_RUNTIME_ROOT/container-credentials.json.tmp.XXXXXX") || return $?
1485
+ trap 'rm -f -- "$BOOTSTRAP_CREDENTIAL_TMP"' EXIT || return $?
1486
+ install -m 0600 -o 10001 -g 10001 "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" "$BOOTSTRAP_CREDENTIAL_TMP" || return $?
1487
+ cmp -s "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" "$BOOTSTRAP_CREDENTIAL_TMP" || return $?
1488
+ sync -f "$BOOTSTRAP_CREDENTIAL_TMP" || return $?
1489
+ mv -f -- "$BOOTSTRAP_CREDENTIAL_TMP" "$BOOTSTRAP_CREDENTIAL_SOURCE" || return $?
1490
+ sync -f "$BOOTSTRAP_RUNTIME_ROOT" || return $?
1491
+ trap - EXIT || return $?
1492
+ fi
1493
+ docker run --rm --pull=never --network host --name ouro-butler-credential-bootstrap --user 10001:10001 \
1494
+ --mount "type=bind,src=$BOOTSTRAP_RUNTIME_ROOT,dst=/home/ouro/.ouro-cli" \
1495
+ --mount "type=bind,src=$BOOTSTRAP_AGENT_ROOT,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
1496
+ --entrypoint node "$BOOTSTRAP_IMAGE_ID" -e '
1497
+ const { loadContainerCredentialBootstrap } = require("/opt/ouro/dist/heart/daemon/container-credential-bootstrap.js")
1498
+ loadContainerCredentialBootstrap(["sanctuary"], {
1499
+ machineIdMigration: {
1500
+ sourceMachineId: process.argv[1],
1501
+ targetMachineId: process.argv[2],
1502
+ },
1503
+ }).then(
1504
+ () => process.exit(0),
1505
+ () => { process.stderr.write("credential bootstrap failed\n"); process.exit(1) },
1506
+ )
1507
+ ' "$BOOTSTRAP_SOURCE_MACHINE_ID" "$BOOTSTRAP_TARGET_MACHINE_ID" || return $?
1508
+ # The path-locked Sanctuary migration imports the legacy MiniMax provider
1509
+ # record into the agent vault before strict validation and persistence.
1510
+ # The original legacy envelope remains byte-for-byte unchanged and is the
1511
+ # sole digest authority.
1512
+ ! docker container inspect ouro-butler-credential-bootstrap >/dev/null 2>&1 || return 1
1513
+ test ! -e "$BOOTSTRAP_CREDENTIAL_SOURCE" || return $?
1514
+ test ! -e "$BOOTSTRAP_CREDENTIAL_CLAIM" || return $?
1515
+ record_sanctuary_legacy_import_marker "$BOOTSTRAP_IMPORT_MARKER" "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" || return $?
1516
+ validate_sanctuary_legacy_import_marker "$BOOTSTRAP_IMPORT_MARKER" "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" || return $?
1517
+ fi
1518
+ test -f "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" || return $?
1519
+ test ! -L "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE" || return $?
1520
+ test "$(stat -c '%u:%g %a' "$BOOTSTRAP_LEGACY_CREDENTIAL_SOURCE")" = "$BOOTSTRAP_LEGACY_METADATA" || return $?
1521
+ fi
1522
+ validate_sanctuary_roots "$BOOTSTRAP_RUNTIME_ROOT" "$BOOTSTRAP_AGENT_ROOT" || return $?
1523
+ }
1524
+ provision_sanctuary_sab_credential() {
1525
+ SAB_BOOTSTRAP_IMAGE_ID=$1
1526
+ validate_exact_image_id "$SAB_BOOTSTRAP_IMAGE_ID" || return $?
1527
+ SAB_BOOTSTRAP_SOURCE=/mnt/user/appdata/sabnzbd/sabnzbd.ini
1528
+ SAB_BOOTSTRAP_RUNTIME_ROOT=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli
1529
+ SAB_BOOTSTRAP_AGENT_ROOT=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro
1530
+ SAB_BOOTSTRAP_ENVELOPE="$SAB_BOOTSTRAP_RUNTIME_ROOT/container-credentials.json"
1531
+ SAB_BOOTSTRAP_CLAIM="$SAB_BOOTSTRAP_ENVELOPE.consuming"
1532
+ test -f "$SAB_BOOTSTRAP_SOURCE" || return $?
1533
+ test ! -L "$SAB_BOOTSTRAP_SOURCE" || return 1
1534
+ test ! -e "$SAB_BOOTSTRAP_ENVELOPE" || return 1
1535
+ test ! -e "$SAB_BOOTSTRAP_CLAIM" || return 1
1536
+ ! docker container inspect ouro-butler-sab-credential-bootstrap >/dev/null 2>&1 || return 1
1537
+ SAB_BOOTSTRAP_TMP=$(mktemp "$SAB_BOOTSTRAP_RUNTIME_ROOT/container-credentials.json.tmp.XXXXXX") || return $?
1538
+ trap 'rm -f -- "$SAB_BOOTSTRAP_TMP"' EXIT || return $?
1539
+ /usr/local/bin/node -e '
1540
+ const fs = require("node:fs");
1541
+ const [source, destination] = process.argv.slice(1);
1542
+ const match = fs.readFileSync(source, "utf8").match(/^\s*api_key\s*=\s*(\S+)\s*$/mu);
1543
+ if (!match || !match[1]) process.exit(1);
1544
+ const credential = { type: "ouro.runtimeCredentialBootstrap", agentName: "sanctuary", machineId: "sanctuary", machineRuntimeConfig: { sabnzbdApiKey: match[1] } };
1545
+ const envelope = { schemaVersion: 1, credentials: [credential] };
1546
+ fs.writeFileSync(destination, `${JSON.stringify(envelope)}\n`, { mode: 0o600, flag: "w" });
1547
+ ' "$SAB_BOOTSTRAP_SOURCE" "$SAB_BOOTSTRAP_TMP" || return $?
1548
+ chown 10001:10001 "$SAB_BOOTSTRAP_TMP" || return $?
1549
+ chmod 0600 "$SAB_BOOTSTRAP_TMP" || return $?
1550
+ sync -f "$SAB_BOOTSTRAP_TMP" || return $?
1551
+ mv -f -- "$SAB_BOOTSTRAP_TMP" "$SAB_BOOTSTRAP_ENVELOPE" || return $?
1552
+ sync -f "$SAB_BOOTSTRAP_RUNTIME_ROOT" || return $?
1553
+ trap - EXIT || return $?
1554
+ docker run --rm --pull=never --network host --name ouro-butler-sab-credential-bootstrap --user 10001:10001 \
1555
+ --mount "type=bind,src=$SAB_BOOTSTRAP_RUNTIME_ROOT,dst=/home/ouro/.ouro-cli" \
1556
+ --mount "type=bind,src=$SAB_BOOTSTRAP_AGENT_ROOT,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
1557
+ --entrypoint node "$SAB_BOOTSTRAP_IMAGE_ID" -e '
1558
+ const { loadContainerCredentialBootstrap } = require("/opt/ouro/dist/heart/daemon/container-credential-bootstrap.js");
1559
+ loadContainerCredentialBootstrap(["sanctuary"]).then(
1560
+ () => process.exit(0),
1561
+ () => { process.stderr.write("SAB credential bootstrap failed\n"); process.exit(1); },
1562
+ );
1563
+ ' || return $?
1564
+ ! docker container inspect ouro-butler-sab-credential-bootstrap >/dev/null 2>&1 || return 1
1565
+ test ! -e "$SAB_BOOTSTRAP_ENVELOPE" || return 1
1566
+ test ! -e "$SAB_BOOTSTRAP_CLAIM" || return 1
1567
+ }
1568
+ verify_sanctuary_sab_readiness() {
1569
+ SAB_READINESS_IMAGE_ID=$1
1570
+ validate_exact_image_id "$SAB_READINESS_IMAGE_ID" || return $?
1571
+ ! docker container inspect ouro-butler-sab-readiness >/dev/null 2>&1 || return 1
1572
+ docker run --rm --pull=never --network host --name ouro-butler-sab-readiness --user 10001:10001 \
1573
+ --mount "type=bind,src=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli,dst=/home/ouro/.ouro-cli" \
1574
+ --mount "type=bind,src=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
1575
+ --entrypoint node "$SAB_READINESS_IMAGE_ID" -e '
1576
+ (async () => {
1577
+ try {
1578
+ const { refreshMachineRuntimeCredentialConfig } = require("/opt/ouro/dist/heart/runtime-credentials.js");
1579
+ const { createSanctuarySabClient } = require("/opt/ouro/dist/senses/sanctuary-sab.js");
1580
+ const current = await refreshMachineRuntimeCredentialConfig("sanctuary", "sanctuary");
1581
+ if (!current.ok || typeof current.config.sabnzbdApiKey !== "string" || !current.config.sabnzbdApiKey.trim()) throw new Error();
1582
+ const snapshot = await createSanctuarySabClient({ loadApiKey: async () => current.config.sabnzbdApiKey }).readQueue();
1583
+ if (typeof snapshot.paused !== "boolean" || !Number.isSafeInteger(snapshot.queuedJobs) || !snapshot.observedAt) throw new Error();
1584
+ process.stdout.write("Sanctuary SAB queue readiness verified.\n");
1585
+ } catch {
1586
+ process.stderr.write("Sanctuary SAB queue readiness verification failed.\n");
1587
+ process.exitCode = 1;
1588
+ }
1589
+ })();
1590
+ ' || return $?
1591
+ ! docker container inspect ouro-butler-sab-readiness >/dev/null 2>&1 || return 1
1592
+ }
1593
+ authenticate_sanctuary_provider() {
1594
+ AUTH_IMAGE_ID=$1
1595
+ AUTH_PROVIDER=${2-}
1596
+ validate_exact_image_id "$AUTH_IMAGE_ID" || return $?
1597
+ case "$AUTH_PROVIDER" in
1598
+ openai-compatible) AUTH_CONTAINER=ouro-butler-provider-auth-glm ;;
1599
+ openai-compatible-gemini) AUTH_CONTAINER=ouro-butler-provider-auth-gemini ;;
1600
+ *) return 1 ;;
1601
+ esac
1602
+ AUTH_RUNTIME_ROOT=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli
1603
+ AUTH_AGENT_ROOT=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro
1604
+ ! docker container inspect "$AUTH_CONTAINER" >/dev/null 2>&1 || return 1
1605
+ docker run --rm -it --pull=never --network host --name "$AUTH_CONTAINER" --user 10001:10001 \
1606
+ --mount "type=bind,src=$AUTH_RUNTIME_ROOT,dst=/home/ouro/.ouro-cli" \
1607
+ --mount "type=bind,src=$AUTH_AGENT_ROOT,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
1608
+ --entrypoint node "$AUTH_IMAGE_ID" /opt/ouro/dist/heart/daemon/ouro-entry.js \
1609
+ auth --agent sanctuary --provider "$AUTH_PROVIDER" || return $?
1610
+ ! docker container inspect "$AUTH_CONTAINER" >/dev/null 2>&1 || return 1
1611
+ }
1612
+ verify_sanctuary_provider_readiness() {
1613
+ READINESS_IMAGE_ID=$1
1614
+ validate_exact_image_id "$READINESS_IMAGE_ID" || return $?
1615
+ READINESS_RUNTIME_ROOT=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli
1616
+ READINESS_AGENT_ROOT=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro
1617
+ ! docker container inspect ouro-butler-provider-readiness >/dev/null 2>&1 || return 1
1618
+ docker run --rm --pull=never --network host --name ouro-butler-provider-readiness --user 10001:10001 \
1619
+ --mount "type=bind,src=$READINESS_RUNTIME_ROOT,dst=/home/ouro/.ouro-cli" \
1620
+ --mount "type=bind,src=$READINESS_AGENT_ROOT,dst=/home/ouro/AgentBundles/sanctuary.ouro" \
1621
+ --entrypoint /bin/sh "$READINESS_IMAGE_ID" -ceu '
1622
+ umask 077
1623
+ node /opt/ouro/dist/heart/daemon/ouro-entry.js check --agent sanctuary --lane outward
1624
+ node /opt/ouro/dist/heart/daemon/ouro-entry.js check --agent sanctuary --lane inner
1625
+ node - <<'"'"'NODE'"'"'
1626
+ (async () => {
1627
+ try {
1628
+ const fs = require("node:fs");
1629
+ const root = "/home/ouro/AgentBundles/sanctuary.ouro";
1630
+ const agent = JSON.parse(fs.readFileSync(`${root}/agent.json`, "utf8"));
1631
+ const policy = JSON.parse(fs.readFileSync(`${root}/provider-readiness.json`, "utf8"));
1632
+ const expectedPolicy = { version: 1, selectionPolicy: "explicit-same-lane-only" };
1633
+ const expected = new Map([
1634
+ ["minimax", { provider: "minimax", model: "MiniMax-M3", vaultItem: "providers/minimax" }],
1635
+ ]);
1636
+ const exactLane = value => value && value.provider === "minimax" && value.model === "MiniMax-M3";
1637
+ if (!exactLane(agent.humanFacing) || !exactLane(agent.agentFacing)
1638
+ || policy.version !== expectedPolicy.version || policy.selectionPolicy !== expectedPolicy.selectionPolicy
1639
+ || !Array.isArray(policy.providers) || policy.providers.length !== expected.size) throw new Error();
1640
+ for (const entry of policy.providers) {
1641
+ const wanted = expected.get(entry.provider);
1642
+ if (!wanted || entry.model !== wanted.model || entry.vaultItem !== wanted.vaultItem) throw new Error();
1643
+ expected.delete(entry.provider);
1644
+ }
1645
+ if (expected.size !== 0) throw new Error();
1646
+ const { refreshProviderCredentialPool } = require("/opt/ouro/dist/heart/provider-credentials.js");
1647
+ const refreshed = await refreshProviderCredentialPool("sanctuary", {
1648
+ providers: ["minimax"],
1649
+ skipCache: true,
1650
+ });
1651
+ if (!refreshed.ok) throw new Error();
1652
+ const minimax = refreshed.pool.providers["minimax"];
1653
+ const exactRecord = (record, provider) => record && record.provider === provider
1654
+ && typeof record.revision === "string" && record.revision.length > 0
1655
+ && typeof record.credentials?.apiKey === "string" && record.credentials.apiKey.trim().length > 0;
1656
+ if (!exactRecord(minimax, "minimax")) throw new Error();
1657
+ process.stdout.write("Sanctuary provider readiness verified.\n");
1658
+ } catch {
1659
+ process.stderr.write("Sanctuary provider readiness verification failed.\n");
1660
+ process.exitCode = 1;
1661
+ }
1662
+ })();
1663
+ NODE
1664
+ ' || return $?
1665
+ ! docker container inspect ouro-butler-provider-readiness >/dev/null 2>&1 || return 1
1666
+ validate_sanctuary_roots "$READINESS_RUNTIME_ROOT" "$READINESS_AGENT_ROOT" || return $?
1667
+ }
1668
+ verify_sanctuary_telegram_readiness() {
1669
+ TELEGRAM_READINESS_IMAGE_ID=$1
1670
+ validate_exact_image_id "$TELEGRAM_READINESS_IMAGE_ID" || return $?
1671
+ TELEGRAM_READINESS_CONTRACT=$(sanctuary_image_mount_contract "$TELEGRAM_READINESS_IMAGE_ID") || return $?
1672
+ TELEGRAM_READINESS_CONTEXT=${2-}
1673
+ case "$TELEGRAM_READINESS_CONTRACT" in
1674
+ canonical-gateway) TELEGRAM_READINESS_CONTEXT=${TELEGRAM_READINESS_CONTEXT:-strict}; set -- --mount "type=bind,src=/run/ouro-authority,dst=/run/ouro-authority,readonly" --mount "type=bind,src=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro/psyche,dst=/home/ouro/AgentBundles/sanctuary.ouro/psyche,readonly" ;;
1675
+ canonical-pre-gateway) TELEGRAM_READINESS_CONTEXT=${TELEGRAM_READINESS_CONTEXT:-live-precutover}; set -- ;;
1676
+ *) return 1 ;;
1677
+ esac
1678
+ case "$TELEGRAM_READINESS_CONTRACT:$TELEGRAM_READINESS_CONTEXT" in
1679
+ canonical-gateway:strict|canonical-pre-gateway:strict|canonical-pre-gateway:live-precutover) ;;
1680
+ *) return 1 ;;
1681
+ esac
1682
+ TELEGRAM_READINESS_RUNTIME_ROOT=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli
1683
+ TELEGRAM_READINESS_AGENT_ROOT=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro
1684
+ ! docker container inspect ouro-butler-telegram-readiness >/dev/null 2>&1 || return 1
1685
+ docker run --rm --pull=never --network host --name ouro-butler-telegram-readiness --user 10001:10001 \
1686
+ --read-only --cap-drop ALL --security-opt no-new-privileges \
1687
+ --mount "type=bind,src=$TELEGRAM_READINESS_RUNTIME_ROOT,dst=/home/ouro/.ouro-cli" \
1688
+ --mount "type=bind,src=$TELEGRAM_READINESS_AGENT_ROOT,dst=/home/ouro/AgentBundles/sanctuary.ouro,readonly" \
1689
+ --entrypoint /opt/ouro/deploy/unraid/sanctuary-acceptance-adapter.sh \
1690
+ "$@" "$TELEGRAM_READINESS_IMAGE_ID" telegram-readiness >/dev/null || return $?
1691
+ ! docker container inspect ouro-butler-telegram-readiness >/dev/null 2>&1 || return 1
1692
+ normalize_sanctuary_private_permissions "$TELEGRAM_READINESS_RUNTIME_ROOT" "$TELEGRAM_READINESS_AGENT_ROOT" "$TELEGRAM_READINESS_IMAGE_ID" || return $?
1693
+ validate_sanctuary_roots "$TELEGRAM_READINESS_RUNTIME_ROOT" "$TELEGRAM_READINESS_AGENT_ROOT" "$TELEGRAM_READINESS_CONTEXT" || return $?
1694
+ }
1695
+ read_sanctuary_authority_state() {
1696
+ (
1697
+ test -n "${STAGED_DOCKERMAN_TRANSACTION-}" || return 1
1698
+ AUTHORITY_STATUS=$(/usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" status) || return $?
1699
+ printf '%s' "$AUTHORITY_STATUS" | /usr/local/bin/node -e '
1700
+ let input = "";
1701
+ process.stdin.setEncoding("utf8");
1702
+ process.stdin.on("data", chunk => { input += chunk; });
1703
+ process.stdin.on("end", () => {
1704
+ const record = JSON.parse(input);
1705
+ if (record === null || (record && !Object.hasOwn(record, "authority"))) process.stdout.write("none");
1706
+ else if (["installing", "active", "retiring", "retired"].includes(record?.authority?.state)) process.stdout.write(record.authority.state);
1707
+ else process.exit(1);
1708
+ });
1709
+ ' || return $?
1710
+ )
1711
+ }
1712
+ retire_sanctuary_authority_if_pending() {
1713
+ (
1714
+ AUTHORITY_STATE=$(read_sanctuary_authority_state) || return $?
1715
+ test "$AUTHORITY_STATE" != none || return 0
1716
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" authority-retire >/dev/null || return $?
1717
+ )
1718
+ }
1719
+ receive_sanctuary_authority_token() {
1720
+ (
1721
+ test "$(id -u)" = 0 && test -t 0 || return 1
1722
+ test "$(stat -c '%u:%g:%a' /mnt/user/appdata/ouro-authority)" = 0:0:700 || return 1
1723
+ test ! -e /mnt/user/appdata/ouro-authority/incoming-token && test ! -L /mnt/user/appdata/ouro-authority/incoming-token || return 1
1724
+ TOKEN_TERMINAL_MODE=$(stty -g) || return $?
1725
+ trap 'stty "$TOKEN_TERMINAL_MODE"' EXIT
1726
+ trap 'exit 129' HUP
1727
+ trap 'exit 130' INT
1728
+ trap 'exit 143' TERM
1729
+ printf '%s\n' 'Human: paste the freshly rotated same-bot token, press Enter, then Ctrl-D. Input is hidden.' >&2
1730
+ stty -echo || return $?
1731
+ umask 077
1732
+ set -C
1733
+ dd status=none > /mnt/user/appdata/ouro-authority/incoming-token || return $?
1734
+ test -s /mnt/user/appdata/ouro-authority/incoming-token || return 1
1735
+ sync -f /mnt/user/appdata/ouro-authority/incoming-token || return $?
1736
+ )
1737
+ }
1738
+ prepare_sanctuary_authority_inputs() {
1739
+ (
1740
+ AUTHORITY_SOURCE=$1
1741
+ test "$(id -u)" = 0 || return 1
1742
+ /usr/local/bin/node - "$AUTHORITY_SOURCE" "$AUTHORITY_EPOCH_ID" "$AUTHORITY_BOT_ID" "$AUTHORITY_OWNER_ID" <<'NODE'
1743
+ const fs = require("node:fs");
1744
+ const path = require("node:path");
1745
+ const crypto = require("node:crypto");
1746
+ const [source, epochId, botId, ownerId] = process.argv.slice(2);
1747
+ const root = "/mnt/user/appdata/ouro-authority";
1748
+ const incoming = `${root}/incoming-package`;
1749
+ const sha = bytes => `sha256:${crypto.createHash("sha256").update(bytes).digest("hex")}`;
1750
+ const directory = target => {
1751
+ if (!fs.existsSync(target)) fs.mkdirSync(target, { mode: 0o700 });
1752
+ const stat = fs.lstatSync(target);
1753
+ if (!stat.isDirectory() || fs.realpathSync(target) !== target || stat.uid !== 0 || stat.gid !== 0 || (stat.mode & 0o7777) !== 0o700) throw new Error("unsafe authority input directory");
1754
+ };
1755
+ const owned = (target, mode) => {
1756
+ const stat = fs.lstatSync(target);
1757
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.uid !== 0 || stat.gid !== 0 || (stat.mode & 0o7777) !== mode) throw new Error("unsafe authority input file");
1758
+ return fs.readFileSync(target);
1759
+ };
1760
+ const persist = (target, bytes, mode) => {
1761
+ if (fs.existsSync(target)) {
1762
+ if (!owned(target, mode).equals(bytes)) throw new Error("authority input conflicts with retained recovery bytes");
1763
+ } else {
1764
+ const fd = fs.openSync(target, "wx", mode);
1765
+ try { fs.writeFileSync(fd, bytes); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
1766
+ }
1767
+ };
1768
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(epochId) || !/^[1-9][0-9]*$/.test(botId) || !/^[1-9][0-9]*$/.test(ownerId)) throw new Error("invalid reviewed identity");
1769
+ directory(root);
1770
+ directory(incoming);
1771
+ const sourceRoot = fs.realpathSync(source);
1772
+ const files = {};
1773
+ const walk = (relative, ancestors = []) => {
1774
+ const input = path.join(sourceRoot, relative);
1775
+ const resolved = fs.realpathSync(input);
1776
+ if (resolved !== sourceRoot && !resolved.startsWith(`${sourceRoot}/`)) throw new Error("package link escapes exact image payload");
1777
+ if (ancestors.includes(resolved)) throw new Error("package link cycle");
1778
+ const stat = fs.statSync(input);
1779
+ if (stat.isDirectory()) {
1780
+ directory(path.join(incoming, relative));
1781
+ for (const name of fs.readdirSync(input).sort()) {
1782
+ if (!/^[A-Za-z0-9_@.-]+$/.test(name) || name === "." || name === "..") throw new Error("unsupported package path");
1783
+ walk(path.join(relative, name), [...ancestors, resolved]);
1784
+ }
1785
+ } else {
1786
+ if (!stat.isFile()) throw new Error("non-file package payload");
1787
+ const bytes = fs.readFileSync(input);
1788
+ const mode = stat.mode & 0o111 ? 0o700 : 0o600;
1789
+ persist(path.join(incoming, relative), bytes, mode);
1790
+ files[relative] = { digest: sha(bytes), mode };
1791
+ }
1792
+ };
1793
+ walk("");
1794
+ const actual = [];
1795
+ const inventory = relative => {
1796
+ for (const entry of fs.readdirSync(path.join(incoming, relative), { withFileTypes: true })) {
1797
+ const name = path.join(relative, entry.name);
1798
+ if (entry.isDirectory()) inventory(name); else actual.push(name);
1799
+ }
1800
+ };
1801
+ inventory("");
1802
+ if (JSON.stringify(actual.sort()) !== JSON.stringify(Object.keys(files).sort())) throw new Error("unexpected incoming package residue");
1803
+ for (const required of ["package.json", "npm-shrinkwrap.json", "dist/heart/daemon/sanctuary-authority-root-lifecycle.js", "dist/heart/daemon/sanctuary-telegram-authority-entry.js", "dist/heart/daemon/sanctuary-host-supervisor-entry.js", "deploy/unraid/sanctuary-host-launcher.sh", "deploy/unraid/sanctuary-authority-service.sh"]) {
1804
+ if (!files[required]) throw new Error(`missing authority package asset: ${required}`);
1805
+ }
1806
+ if (!Object.keys(files).some(name => name.startsWith("node_modules/"))) throw new Error("production dependencies are absent");
1807
+ const manifest = Buffer.from(`${JSON.stringify({ schemaVersion: 1, files })}\n`);
1808
+ if (manifest.byteLength > 8388608) throw new Error("complete package manifest exceeds the root lifecycle 8388608-byte limit; stop before token rotation");
1809
+ persist(`${root}/package-manifest.json`, manifest, 0o600);
1810
+ const primitive = file => {
1811
+ const stat = fs.statSync(file);
1812
+ if (!stat.isFile() || stat.uid !== 0 || stat.gid !== 0 || (stat.mode & 0o022) || !(stat.mode & 0o111)) throw new Error("unsafe host primitive");
1813
+ return sha(fs.readFileSync(file));
1814
+ };
1815
+ const request = { schemaVersion: 1, epochId, botId, ownerUserId: ownerId, ownerChatId: ownerId, packageDigest: sha(manifest), nodeDigest: primitive("/usr/local/bin/node"), prlimitDigest: primitive("/usr/bin/prlimit"), setsidDigest: primitive("/usr/bin/setsid"), shellDigest: primitive("/bin/sh") };
1816
+ persist(`${root}/request.json`, Buffer.from(`${JSON.stringify(request)}\n`), 0o600);
1817
+ if (fs.existsSync(`${root}/incoming-token`)) owned(`${root}/incoming-token`, 0o600);
1818
+ const fd = fs.openSync(root, "r");
1819
+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
1820
+ NODE
1821
+ )
1822
+ }
1823
+ run_sanctuary_docker() {
1824
+ /usr/bin/timeout -s KILL 20 /usr/bin/docker "$@"
1825
+ }
1826
+ run_sanctuary_unraid_api() {
1827
+ /usr/bin/timeout -s KILL 20 /usr/local/sbin/unraid-api "$@"
1828
+ }
1829
+ run_sanctuary_node() {
1830
+ /usr/local/bin/node "$@"
1831
+ }
1832
+ resolve_sanctuary_unraid_key() {
1833
+ run_sanctuary_node -e '
1834
+ const fs = require("node:fs");
1835
+ const root = "/boot/config/plugins/dynamix.my.servers/keys";
1836
+ const expected = process.argv[1];
1837
+ const found = [];
1838
+ for (const name of fs.readdirSync(root)) {
1839
+ if (!/^[A-Za-z0-9._:-]+\.json$/.test(name)) process.exit(1);
1840
+ const path = `${root}/${name}`;
1841
+ const stat = fs.lstatSync(path);
1842
+ if (!stat.isFile() || stat.isSymbolicLink()) process.exit(1);
1843
+ const value = JSON.parse(fs.readFileSync(path, "utf8"));
1844
+ if (value.id === expected) found.push({ path, name: value.name });
1845
+ }
1846
+ if (found.length !== 1 || typeof found[0].name !== "string" || !/^[A-Za-z0-9 ._:-]+$/.test(found[0].name)) process.exit(1);
1847
+ process.stdout.write(`${found[0].path}\t${found[0].name}`);
1848
+ ' "$1"
1849
+ }
1850
+ sanctuary_revoked_key_recovery_path() {
1851
+ case "$1" in ''|*[!A-Za-z0-9._:-]*) return 1 ;; esac
1852
+ printf '%s/%s.json' /mnt/user/appdata/ouro-butler/acceptance/revoked-key-proof "$1"
1853
+ }
1854
+ validate_sanctuary_revoked_key_recovery() {
1855
+ test -f "$1" && test ! -L "$1" || return 1
1856
+ test "$(stat -c '%u:%g %a' "$1")" = "0:0 600" || return 1
1857
+ }
1858
+ preserve_sanctuary_revoked_key() {
1859
+ KEY_ID=$1
1860
+ KEY_SOURCE=$2
1861
+ RECOVERY_ROOT=/mnt/user/appdata/ouro-butler/acceptance/revoked-key-proof
1862
+ test -f "$KEY_SOURCE" && test ! -L "$KEY_SOURCE" || return 1
1863
+ if test ! -e "$RECOVERY_ROOT"; then
1864
+ install -d -m 0700 -o root -g root "$RECOVERY_ROOT" || return $?
1865
+ fi
1866
+ test -d "$RECOVERY_ROOT" && test ! -L "$RECOVERY_ROOT" || return 1
1867
+ test "$(stat -c '%u:%g %a' "$RECOVERY_ROOT")" = "0:0 700" || return 1
1868
+ RECOVERY_PATH=$(sanctuary_revoked_key_recovery_path "$KEY_ID") || return $?
1869
+ test ! -e "$RECOVERY_PATH" || return 1
1870
+ RECOVERY_TMP=$(mktemp "$RECOVERY_ROOT/$KEY_ID.json.tmp.XXXXXX") || return $?
1871
+ trap 'rm -f -- "$RECOVERY_TMP"' EXIT || return $?
1872
+ install -m 0600 -o root -g root "$KEY_SOURCE" "$RECOVERY_TMP" || return $?
1873
+ cmp -s "$KEY_SOURCE" "$RECOVERY_TMP" || return 1
1874
+ mv -f -- "$RECOVERY_TMP" "$RECOVERY_PATH" || return $?
1875
+ sync -f "$RECOVERY_ROOT" || return $?
1876
+ trap - EXIT || return $?
1877
+ }
1878
+ clear_sanctuary_revoked_key() {
1879
+ RECOVERY_PATH=$(sanctuary_revoked_key_recovery_path "$1") || return $?
1880
+ test -f "$RECOVERY_PATH" && test ! -L "$RECOVERY_PATH" || return 1
1881
+ test "$(stat -c '%u:%g %a' "$RECOVERY_PATH")" = "0:0 600" || return 1
1882
+ rm -f -- "$RECOVERY_PATH" || return $?
1883
+ sync -f "$(dirname "$RECOVERY_PATH")" || return $?
1884
+ }
1885
+ verify_vault_backed_unraid_key() {
1886
+ KEY_ID=$1
1887
+ CAPABILITY=$2
1888
+ case "$KEY_ID" in ''|*[!A-Za-z0-9._:-]*) return 1 ;; esac
1889
+ case "$CAPABILITY" in read-only|bounded-write) ;; *) return 1 ;; esac
1890
+ IMAGE_DIGEST=${IMAGE_ID#sha256:}
1891
+ test "$IMAGE_DIGEST" != "$IMAGE_ID" || return 1
1892
+ test "${#IMAGE_DIGEST}" -eq 64 || return 1
1893
+ case "$IMAGE_DIGEST" in *[!0-9a-f]*) return 1 ;; esac
1894
+ test "$(run_sanctuary_docker image inspect --format '{{.Id}}' "$IMAGE_ID")" = "$IMAGE_ID" || return $?
1895
+ KEY_TARGET=$(resolve_sanctuary_unraid_key "$KEY_ID") || return $?
1896
+ KEY_PATH=${KEY_TARGET%% *}
1897
+ test "$KEY_PATH" != "$KEY_TARGET" || return 1
1898
+ test -f "$KEY_PATH" && test ! -L "$KEY_PATH" || return 1
1899
+ VERIFY_RESULT=$(run_sanctuary_docker run --rm --pull=never --network host \
1900
+ --user 0:0 \
1901
+ --mount type=bind,src=/mnt/user/appdata/ouro-butler/runtime/.ouro-cli,dst=/home/ouro/.ouro-cli,readonly \
1902
+ --mount type=bind,src=/mnt/user/appdata/ouro-butler/agent/sanctuary.ouro,dst=/home/ouro/AgentBundles/sanctuary.ouro,readonly \
1903
+ --mount type=bind,src="$KEY_PATH",dst=/run/ouro-acceptance/unraid-key.json,readonly \
1904
+ --entrypoint /opt/ouro/deploy/unraid/sanctuary-acceptance-adapter.sh \
1905
+ "$IMAGE_ID" vault-probe "$KEY_ID" "$CAPABILITY") || return $?
1906
+ printf '%s' "$VERIFY_RESULT" | run_sanctuary_node -e '
1907
+ let input = "";
1908
+ process.stdin.setEncoding("utf8");
1909
+ process.stdin.on("data", chunk => { input += chunk; });
1910
+ process.stdin.on("end", () => {
1911
+ const value = JSON.parse(input);
1912
+ const expectedId = process.argv[1];
1913
+ const expectedCapability = process.argv[2];
1914
+ const expectedProof = expectedCapability === "read-only"
1915
+ ? "read-authorized-write-denied"
1916
+ : "read-authorized-write-reached-not-found";
1917
+ if (JSON.stringify(Object.keys(value).sort()) !== JSON.stringify(["capability", "keyId", "proof", "valid"])) process.exit(1);
1918
+ if (value.valid !== true || value.keyId !== expectedId || value.capability !== expectedCapability) process.exit(1);
1919
+ if (value.proof !== expectedProof) process.exit(1);
1920
+ });
1921
+ ' "$KEY_ID" "$CAPABILITY" || return $?
1922
+ }
1923
+ inventory_unraid_key_ids() {
1924
+ IMAGE_DIGEST=${IMAGE_ID#sha256:}
1925
+ test "$IMAGE_DIGEST" != "$IMAGE_ID" || return 1
1926
+ test "${#IMAGE_DIGEST}" -eq 64 || return 1
1927
+ case "$IMAGE_DIGEST" in *[!0-9a-f]*) return 1 ;; esac
1928
+ test "$(run_sanctuary_docker image inspect --format '{{.Id}}' "$IMAGE_ID")" = "$IMAGE_ID" || return $?
1929
+ INVENTORY_RESULT=$(printf '%s' '{"operation":"closed-inventory"}' | \
1930
+ run_sanctuary_docker run --rm -i --pull=never --network none \
1931
+ --user 0:0 --read-only \
1932
+ --mount type=bind,src=/boot/config/plugins/dynamix.my.servers/keys,dst=/boot/config/plugins/dynamix.my.servers/keys,readonly \
1933
+ --entrypoint /opt/ouro/deploy/unraid/sanctuary-acceptance-adapter.sh "$IMAGE_ID") || return $?
1934
+ printf '%s' "$INVENTORY_RESULT" | run_sanctuary_node -e '
1935
+ let input = "";
1936
+ process.stdin.setEncoding("utf8");
1937
+ process.stdin.on("data", chunk => { input += chunk; });
1938
+ process.stdin.on("end", () => {
1939
+ const value = JSON.parse(input);
1940
+ if (!value || JSON.stringify(Object.keys(value)) !== JSON.stringify(["keys"]) || !Array.isArray(value.keys)) process.exit(1);
1941
+ for (const key of value.keys) {
1942
+ if (!key || JSON.stringify(Object.keys(key).sort()) !== JSON.stringify(["id", "roles", "scope"])) process.exit(1);
1943
+ if (!/^[A-Za-z0-9._:-]+$/.test(key.id)) process.exit(1);
1944
+ if (!["read-only", "bounded-write", "legacy-write"].includes(key.scope) || key.roles !== "none") process.exit(1);
1945
+ process.stdout.write(`${key.id}\t${key.scope}\t${key.roles}\n`);
1946
+ }
1947
+ });
1948
+ ' || return $?
1949
+ }
1950
+ revoke_unraid_key_exact() {
1951
+ KEY_ID=$1
1952
+ case "$KEY_ID" in ''|*[!A-Za-z0-9._:-]*) return 1 ;; esac
1953
+ test "${REVOKED_KEY_FD_OPEN:-no}" = no || return 1
1954
+ KEY_TARGET=$(resolve_sanctuary_unraid_key "$KEY_ID") || return $?
1955
+ KEY_PATH=${KEY_TARGET%% *}
1956
+ KEY_NAME=${KEY_TARGET#* }
1957
+ test "$KEY_PATH" != "$KEY_TARGET" || return 1
1958
+ test -f "$KEY_PATH" && test ! -L "$KEY_PATH" || return $?
1959
+ preserve_sanctuary_revoked_key "$KEY_ID" "$KEY_PATH" || return $?
1960
+ if ! REVOKE_RESULT=$(run_sanctuary_unraid_api apikey --name "$KEY_NAME" --delete --json); then
1961
+ return 1
1962
+ fi
1963
+ if ! printf '%s' "$REVOKE_RESULT" | run_sanctuary_node -e '
1964
+ let input = "";
1965
+ process.stdin.setEncoding("utf8");
1966
+ process.stdin.on("data", chunk => { input += chunk; });
1967
+ process.stdin.on("end", () => {
1968
+ const value = JSON.parse(input);
1969
+ const expectedId = process.argv[1];
1970
+ const expectedName = process.argv[2];
1971
+ if (value.deleted !== 1 || !Array.isArray(value.keys) || value.keys.length !== 1) process.exit(1);
1972
+ if (value.keys[0].id !== expectedId || value.keys[0].name !== expectedName) process.exit(1);
1973
+ });
1974
+ ' "$KEY_ID" "$KEY_NAME"; then
1975
+ return 1
1976
+ fi
1977
+ }
1978
+ verify_revoked_unraid_key_rejected() {
1979
+ KEY_ID=$1
1980
+ case "$KEY_ID" in ''|*[!A-Za-z0-9._:-]*) return 1 ;; esac
1981
+ REVOKED_KEY_RECOVERY_PATH=$(sanctuary_revoked_key_recovery_path "$KEY_ID") || return $?
1982
+ validate_sanctuary_revoked_key_recovery "$REVOKED_KEY_RECOVERY_PATH" || return $?
1983
+ IMAGE_DIGEST=${IMAGE_ID#sha256:}
1984
+ test "$IMAGE_DIGEST" != "$IMAGE_ID" || return 1
1985
+ test "${#IMAGE_DIGEST}" -eq 64 || return 1
1986
+ case "$IMAGE_DIGEST" in *[!0-9a-f]*) return 1 ;; esac
1987
+ test "$(run_sanctuary_docker image inspect --format '{{.Id}}' "$IMAGE_ID")" = "$IMAGE_ID" || return 1
1988
+ REJECT_ATTEMPT=0
1989
+ while test "$REJECT_ATTEMPT" -lt 3; do
1990
+ REJECT_ATTEMPT=$((REJECT_ATTEMPT + 1))
1991
+ if REJECT_RESULT=$(run_sanctuary_docker run --rm -i --pull=never --network host \
1992
+ --user 10001:10001 --read-only \
1993
+ --entrypoint /bin/sh "$IMAGE_ID" -ceu \
1994
+ 'exec 3<&0; exec /opt/ouro/deploy/unraid/sanctuary-acceptance-adapter.sh revoked-probe "$1" "$2" 3<&3' \
1995
+ sanctuary-revoked-probe "$KEY_ID" http://127.0.0.1/graphql <"$REVOKED_KEY_RECOVERY_PATH") \
1996
+ && printf '%s' "$REJECT_RESULT" | run_sanctuary_node -e '
1997
+ let input = "";
1998
+ process.stdin.setEncoding("utf8");
1999
+ process.stdin.on("data", chunk => { input += chunk; });
2000
+ process.stdin.on("end", () => {
2001
+ const value = JSON.parse(input);
2002
+ if (JSON.stringify(Object.keys(value).sort()) !== JSON.stringify(["id", "rejected", "status"])) process.exit(1);
2003
+ if (value.rejected !== true || value.id !== process.argv[1] || ![401, 403].includes(value.status)) process.exit(1);
2004
+ });
2005
+ ' "$KEY_ID"; then
2006
+ clear_sanctuary_revoked_key "$KEY_ID" || return $?
2007
+ return 0
2008
+ fi
2009
+ test "$REJECT_ATTEMPT" -lt 3 || return 1
2010
+ sleep 2
2011
+ done
2012
+ return 1
2013
+ }
2014
+ Update:
2015
+ Before downloading or staging anything, classify the live production source with the existing topology gates unless the fixed root-owned DockerMan transaction journal signals that an interrupted update needs the exact packaged recovery tools. Staging-only adoption is retired. A recovery journal admits only image acquisition and private staging until the staged transaction implementation validates the full journal and restores a classifiable source:
2016
+ admit_sanctuary_update_entry
2017
+ Set the released package version, its reviewed release-manifest digest, and its reviewed platform-local image ID. The canonical package-version tag is immutable release identity, while the digest and local ID independently prove what the registry and this host resolved:
2018
+ PACKAGE_VERSION=<released-version>
2019
+ MANIFEST_DIGEST=sha256:<reviewed-release-manifest-digest>
2020
+ IMAGE_ID=sha256:<reviewed-local-image-id>
2021
+ VERSION_IMAGE="ghcr.io/ourostack/ouroboros-butler:$PACKAGE_VERSION"
2022
+ printf '%s\n' "$PACKAGE_VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'
2023
+ test "$(inspect_registry_manifest_digest "$VERSION_IMAGE")" = "$MANIFEST_DIGEST"
2024
+ docker pull "$VERSION_IMAGE"
2025
+ validate_exact_image_id "$IMAGE_ID"
2026
+ test "$(docker image inspect --format '{{.Id}}' "$VERSION_IMAGE")" = "$IMAGE_ID"
2027
+ AUDIT_RUNNER_IMAGE_ID=$IMAGE_ID
2028
+ validate_exact_image_id "$AUDIT_RUNNER_IMAGE_ID"
2029
+ TARGET_MOUNT_CONTRACT=$(sanctuary_image_mount_contract "$IMAGE_ID")
2030
+ test "$TARGET_MOUNT_CONTRACT" = canonical-gateway
2031
+ TEMPLATE_ICON=https://raw.githubusercontent.com/ourostack/ouroboros/main/assets/ouroboros.png
2032
+ DOCKERMAN_TEMPLATE_PATH=/boot/config/plugins/dockerMan/templates-user/my-ouro-butler.xml
2033
+ DOCKERMAN_TEMPLATE_JOURNAL=/boot/config/custom/ouro-butler/docker-man-template-transaction.json
2034
+ test "$DOCKERMAN_TEMPLATE_PATH" = /boot/config/plugins/dockerMan/templates-user/my-ouro-butler.xml
2035
+ test "$DOCKERMAN_TEMPLATE_JOURNAL" = /boot/config/custom/ouro-butler/docker-man-template-transaction.json
2036
+ Before stopping, renaming, or creating any Butler container, extract the complete /opt/ouro package from that exact image ID, including production node_modules and package-relative dist. Do not copy these files from a checkout or another image. Use the package version extracted from the selected immutable image; version alone is not the mount contract. Only the reviewed new image's bot.ouro.sanctuary.mount-contract=canonical-gateway label admits the fourth mount. The immutable source alpha.816 ID above remains canonical-pre-gateway and must never be retagged as the gateway release.
2037
+ Stage the event assets, audit the original version-tagged template, create a separate temporary copy for exact local-image-ID auditing, and keep the private stage until the outer transaction commits:
2038
+ EVENT_ASSET_STAGE=$(mktemp -d /mnt/user/appdata/ouro-butler/staging/ouro-events.XXXXXX)
2039
+ chmod 0700 "$EVENT_ASSET_STAGE"
2040
+ EVENT_SCRIPT_STAGE="$EVENT_ASSET_STAGE/ouro-events"
2041
+ mkdir "$EVENT_SCRIPT_STAGE"
2042
+ STAGED_PACKAGE_ROOT="$EVENT_ASSET_STAGE/package"
2043
+ mkdir "$STAGED_PACKAGE_ROOT"
2044
+ STAGED_TEMPLATE="$EVENT_ASSET_STAGE/sanctuary.xml"
2045
+ STAGED_EXACT_TEMPLATE="$EVENT_ASSET_STAGE/sanctuary.exact-image.xml"
2046
+ STAGED_RUNTIME_POLICY="$EVENT_ASSET_STAGE/container-runtime.json"
2047
+ STAGED_DOCKERMAN_TRANSACTION="$STAGED_PACKAGE_ROOT/deploy/unraid/docker-man-template-transaction.mjs"
2048
+ STAGED_DOCKERMAN_XML_VALIDATOR="$STAGED_PACKAGE_ROOT/deploy/unraid/docker-man-template-xml.cjs"
2049
+ EVENT_ASSET_CONTAINER=
2050
+ cleanup_event_asset_stage() {
2051
+ if test -n "$EVENT_ASSET_CONTAINER"; then
2052
+ docker rm --force "$EVENT_ASSET_CONTAINER" >/dev/null 2>&1 || true
2053
+ fi
2054
+ rm -rf -- "$EVENT_ASSET_STAGE"
2055
+ }
2056
+ trap cleanup_event_asset_stage EXIT
2057
+ EVENT_ASSET_CONTAINER=$(docker create --pull=never --network none --read-only --entrypoint /bin/false "$IMAGE_ID")
2058
+ test "$(docker inspect --format '{{.Image}}' "$EVENT_ASSET_CONTAINER")" = "$IMAGE_ID"
2059
+ docker cp "$EVENT_ASSET_CONTAINER:/opt/ouro/." "$STAGED_PACKAGE_ROOT/"
2060
+ docker cp "$EVENT_ASSET_CONTAINER:/opt/ouro/deploy/unraid/ouro-events/." "$EVENT_SCRIPT_STAGE/"
2061
+ docker cp "$EVENT_ASSET_CONTAINER:/opt/ouro/deploy/unraid/sanctuary.xml" "$STAGED_TEMPLATE"
2062
+ docker cp "$EVENT_ASSET_CONTAINER:/opt/ouro/deploy/unraid/container-runtime.json" "$STAGED_RUNTIME_POLICY"
2063
+ docker rm "$EVENT_ASSET_CONTAINER"
2064
+ EVENT_ASSET_CONTAINER=
2065
+ EXPECTED_RELEASE_ASSETS=$(printf '%s\n' container-runtime.json ouro-events package sanctuary.xml)
2066
+ ACTUAL_RELEASE_ASSETS=$(find "$EVENT_ASSET_STAGE" -mindepth 1 -maxdepth 1 -exec basename {} \; | LC_ALL=C sort)
2067
+ test "$ACTUAL_RELEASE_ASSETS" = "$EXPECTED_RELEASE_ASSETS"
2068
+ test -d "$EVENT_SCRIPT_STAGE" && test ! -L "$EVENT_SCRIPT_STAGE"
2069
+ test -f "$STAGED_TEMPLATE" && test ! -L "$STAGED_TEMPLATE"
2070
+ test -f "$STAGED_RUNTIME_POLICY" && test ! -L "$STAGED_RUNTIME_POLICY"
2071
+ test -f "$STAGED_DOCKERMAN_TRANSACTION" && test ! -L "$STAGED_DOCKERMAN_TRANSACTION"
2072
+ test -f "$STAGED_DOCKERMAN_XML_VALIDATOR" && test ! -L "$STAGED_DOCKERMAN_XML_VALIDATOR"
2073
+ chown 0:0 "$STAGED_TEMPLATE" "$STAGED_RUNTIME_POLICY" "$STAGED_DOCKERMAN_TRANSACTION" "$STAGED_DOCKERMAN_XML_VALIDATOR"
2074
+ chmod 0600 "$STAGED_TEMPLATE" "$STAGED_RUNTIME_POLICY" "$STAGED_DOCKERMAN_TRANSACTION" "$STAGED_DOCKERMAN_XML_VALIDATOR"
2075
+ chown -R 0:0 "$STAGED_PACKAGE_ROOT"
2076
+ chmod 0700 "$STAGED_PACKAGE_ROOT"
2077
+ EXPECTED_EVENT_ASSETS=$(printf '%s\n' bootstrap-spool.sh emit-event.mjs emit-usenet-event.sh install-usenet-guard.sh usenet-health.sh)
2078
+ ACTUAL_EVENT_ASSETS=$(find "$EVENT_SCRIPT_STAGE" -mindepth 1 -maxdepth 1 -type f -exec basename {} \; | LC_ALL=C sort)
2079
+ test "$ACTUAL_EVENT_ASSETS" = "$EXPECTED_EVENT_ASSETS"
2080
+ test -z "$(find "$EVENT_SCRIPT_STAGE" -mindepth 1 -maxdepth 1 \( -type l -o ! -type f \) -print -quit)"
2081
+ verify_installed_usenet_guard() {
2082
+ test "$(findmnt -n -o FSTYPE --target /boot/config/custom)" = vfat
2083
+ test "$(stat -c '%u:%g:%a' /boot/config/custom/usenet_health.sh)" = 0:0:600
2084
+ test "$(stat -c '%u:%g:%a' /boot/config/custom/ouro-events/bootstrap-spool.sh)" = 0:0:600
2085
+ test "$(stat -c '%u:%g:%a' /boot/config/custom/ouro-events/emit-event.mjs)" = 0:0:600
2086
+ test "$(stat -c '%u:%g:%a' /boot/config/custom/ouro-events/emit-usenet-event.sh)" = 0:0:600
2087
+ test "$(stat -c '%u:%g:%a' /boot/config/custom/ouro-events/install-usenet-guard.sh)" = 0:0:600
2088
+ cmp -s "$EVENT_SCRIPT_STAGE/usenet-health.sh" /boot/config/custom/usenet_health.sh
2089
+ cmp -s "$EVENT_SCRIPT_STAGE/bootstrap-spool.sh" /boot/config/custom/ouro-events/bootstrap-spool.sh
2090
+ cmp -s "$EVENT_SCRIPT_STAGE/emit-event.mjs" /boot/config/custom/ouro-events/emit-event.mjs
2091
+ cmp -s "$EVENT_SCRIPT_STAGE/emit-usenet-event.sh" /boot/config/custom/ouro-events/emit-usenet-event.sh
2092
+ cmp -s "$EVENT_SCRIPT_STAGE/install-usenet-guard.sh" /boot/config/custom/ouro-events/install-usenet-guard.sh
2093
+ test "$(grep -Fxc '/bin/bash /boot/config/custom/ouro-events/install-usenet-guard.sh --boot --install-root /boot/config/custom' /boot/config/go)" = 1
2094
+ test "$(grep -Fxc '/boot/config/custom/ouro-events/bootstrap-spool.sh --mount' /boot/config/go || true)" = 0
2095
+ test "$(grep -Fxc '(crontab -l 2>/dev/null | grep -v usenet_health; echo "*/15 * * * * /bin/bash /boot/config/custom/usenet_health.sh") | crontab -' /boot/config/go || true)" = 0
2096
+ INSTALLED_GUARD_CRON=$(crontab -l)
2097
+ test "$(printf '%s\n' "$INSTALLED_GUARD_CRON" | grep -Fxc '*/15 * * * * /bin/bash /boot/config/custom/usenet_health.sh # ouro:usenet-health')" = 1
2098
+ INSTALLED_LEGACY_GUARD_COUNT=$(printf '%s\n' "$INSTALLED_GUARD_CRON" | grep -Fxc '*/15 * * * * /bin/bash /boot/config/custom/usenet_health.sh' || true)
2099
+ test "$INSTALLED_LEGACY_GUARD_COUNT" = 0
2100
+ test "$(printf '%s\n' "$INSTALLED_GUARD_CRON" | grep -Fc '/bin/bash /boot/config/custom/usenet_health.sh')" = 1
2101
+ test "$(findmnt -n -o FSTYPE --target /boot/config/custom/ouro-events/spool)" = tmpfs
2102
+ test "$(stat -c '%u:%g:%a' /boot/config/custom/ouro-events/spool)" = 0:0:755
2103
+ INSTALLED_SPOOL_OPTIONS=$(findmnt -n -o OPTIONS --target /boot/config/custom/ouro-events/spool)
2104
+ for INSTALLED_SPOOL_OPTION in nodev nosuid noexec; do
2105
+ case ",$INSTALLED_SPOOL_OPTIONS," in *",$INSTALLED_SPOOL_OPTION,"*) ;; *) return 1 ;; esac
2106
+ done
2107
+ INSTALLED_SPOOL_SIZE=$(findmnt -bn -o SIZE --target /boot/config/custom/ouro-events/spool)
2108
+ test "$INSTALLED_SPOOL_SIZE" -le 4194304
2109
+ }
2110
+ docker run --rm --pull=never --network=none \
2111
+ --user 0:0 --read-only --cap-drop=ALL --security-opt=no-new-privileges \
2112
+ --entrypoint /opt/ouro/deploy/unraid/audit-container-spec.sh \
2113
+ --mount "type=bind,src=$STAGED_TEMPLATE,dst=/audit/sanctuary.xml,readonly" \
2114
+ --mount "type=bind,src=$STAGED_RUNTIME_POLICY,dst=/audit/container-runtime.json,readonly" \
2115
+ "$IMAGE_ID" --persistent-template /audit/sanctuary.xml --runtime-policy /audit/container-runtime.json --expected-image-reference "$VERSION_IMAGE" --mount-contract "$TARGET_MOUNT_CONTRACT"
2116
+ /usr/local/bin/node -e '
2117
+ const fs = require("node:fs");
2118
+ const [sourcePath, destinationPath, imageId] = process.argv.slice(1);
2119
+ if (!/^sha256:[0-9a-f]{64}$/.test(imageId)) throw new Error("invalid exact image ID");
2120
+ const source = fs.readFileSync(sourcePath, "utf8");
2121
+ const repositories = [...source.matchAll(/<Repository>[^<]*<\/Repository>/g)];
2122
+ if (repositories.length !== 1) throw new Error("template must contain exactly one Repository element");
2123
+ const staged = source.replace(repositories[0][0], `<Repository>${imageId}</Repository>`);
2124
+ if ((staged.match(/<Repository>[^<]*<\/Repository>/g) ?? []).length !== 1
2125
+ || !staged.includes(`<Repository>${imageId}</Repository>`)) throw new Error("exact Repository staging failed");
2126
+ fs.writeFileSync(destinationPath, staged, { mode: 0o600, flag: "wx" });
2127
+ ' "$STAGED_TEMPLATE" "$STAGED_EXACT_TEMPLATE" "$IMAGE_ID"
2128
+ chown 0:0 "$STAGED_EXACT_TEMPLATE"
2129
+ chmod 0600 "$STAGED_EXACT_TEMPLATE"
2130
+ docker run --rm --pull=never --network=none \
2131
+ --user 0:0 --read-only --cap-drop=ALL --security-opt=no-new-privileges \
2132
+ --entrypoint /opt/ouro/deploy/unraid/audit-container-spec.sh \
2133
+ --mount "type=bind,src=$STAGED_EXACT_TEMPLATE,dst=/audit/sanctuary.exact-image.xml,readonly" \
2134
+ --mount "type=bind,src=$STAGED_RUNTIME_POLICY,dst=/audit/container-runtime.json,readonly" \
2135
+ "$IMAGE_ID" --template /audit/sanctuary.exact-image.xml --runtime-policy /audit/container-runtime.json --expected-image "$IMAGE_ID" --mount-contract "$TARGET_MOUNT_CONTRACT"
2136
+ recover_dockerman_template_transaction
2137
+ recover_pending_sanctuary_bundle_migration "$IMAGE_ID"
2138
+ classify_sanctuary_update_source
2139
+ /bin/bash "$EVENT_SCRIPT_STAGE/install-usenet-guard.sh" --source-root "$EVENT_SCRIPT_STAGE"
2140
+ /bin/bash /boot/config/custom/ouro-events/install-usenet-guard.sh --boot --install-root /boot/config/custom
2141
+ verify_installed_usenet_guard
2142
+ If extraction or transactional installation fails, abort before changing any live Butler container. The installer restores the previous assets, go file, and cron; production stays running.
2143
+ If boot activation or verification fails after that transaction commits, leave production untouched, repair or rerun this exact-image installation, and stop. Container and DockerMan rollback begin only after the later production preflight succeeds.
2144
+ For normal updates, preflight accepts only the pinned alpha.742 two-mount source or an already package-managed canonical source before any autostart or live-container change. The pinned exception may validate an old source, but can never authorize creation of a new target. Provider authentication and standalone credential-readiness helpers are not normal-update prechecks; never place credentials in arguments, shell variables or history.
2145
+ The DockerMan transaction binds Jellyfin's container ID, image ID, state, and restart count. Update, rollback and recovery must preserve that checkpoint.
2146
+ For this authority migration, only the exact pinned alpha.816 predecessor may become rollback. The legacy-alpha742 digest remains supported for historical source audits, not a policy-weak authority rollback. Preserve one exact stopped alpha.816 predecessor, Jellyfin and every policy/history byte. Staging must be absent and production must be the only running resident. Capture the non-secret reviewed bot/owner/epoch inputs; OWNER_ID is the already authenticated private Telegram user/chat, never inferred from resident-written prose:
2147
+ AUTHORITY_EPOCH_ID=<new-reviewed-epoch-id>
2148
+ AUTHORITY_BOT_ID=8541786263
2149
+ AUTHORITY_OWNER_ID=<reviewed-private-owner-user-and-chat-id>
2150
+ install -d -m 0700 -o 0 -g 0 /mnt/user/appdata/ouro-authority
2151
+ Disable every Butler name in Unraid's array-autostart file before authority-install freezes the resident. First resolve and validate the exact known-good image while it is still running:
2152
+ /bin/bash /boot/config/custom/ouro-events/bootstrap-spool.sh --mount
2153
+ test "$(findmnt -n -o FSTYPE --target /boot/config/custom/ouro-events/spool)" = tmpfs
2154
+ test "$(stat -c '%u:%g:%a' /boot/config/custom/ouro-events/spool)" = 0:0:755
2155
+ ROLLBACK_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler)
2156
+ validate_exact_image_id "$ROLLBACK_IMAGE_ID"
2157
+ ROLLBACK_MOUNT_CONTRACT=$(sanctuary_image_mount_contract "$ROLLBACK_IMAGE_ID")
2158
+ test "$ROLLBACK_IMAGE_ID" = sha256:589b7cf8f96d139ee9fd86204a183126aadcbd3fbfb406063709be303397b1b2
2159
+ test "$ROLLBACK_MOUNT_CONTRACT" = canonical-pre-gateway
2160
+ if assert_update_topology "$ROLLBACK_IMAGE_ID"; then
2161
+ :
2162
+ else
2163
+ UPDATE_PREFLIGHT_STATUS=$?
2164
+ (exit "$UPDATE_PREFLIGHT_STATUS")
2165
+ fi
2166
+ assert_update_source "$ROLLBACK_IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID"
2167
+ if ( provision_sanctuary_sab_credential "$IMAGE_ID" ) \
2168
+ && verify_sanctuary_sab_readiness "$IMAGE_ID"; then
2169
+ :
2170
+ else
2171
+ PRECUTOVER_READINESS_STATUS=$?
2172
+ (exit "$PRECUTOVER_READINESS_STATUS")
2173
+ fi
2174
+ Prepare the complete package and request before human token revocation. The input helper's manifest-size check must pass the root lifecycle reader's 8388608-byte manifest limit; ordinary private records retain their 1048576-byte limit. Do not prune dependencies or split the inventory to bypass either bound. If this check refuses the full payload, leave the existing token, autostart and resident unchanged:
2175
+ prepare_sanctuary_authority_inputs "$STAGED_PACKAGE_ROOT"
2176
+ The input helper copies every regular package file and materializes only package-internal dependency symlinks as independent files, hashes the complete inventory with exact modes, and writes mode-0600 manifest/request files. The request binds schemaVersion, epochId, botId, ownerUserId, ownerChatId, packageDigest and the actual root node/prlimit/setsid/shell hashes. Review those hashes against the approved package and host primitives before prepare. Repeated preparation accepts only identical retained inputs; unknown extra files, external links or changed bytes fail closed. No network token probe or resident start occurs in preparation.
2177
+ Prepare the durable transaction and disable autostart before the human rotates any token:
2178
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" prepare --source-template "$STAGED_TEMPLATE" --version-tag "$VERSION_IMAGE" --manifest-digest "$MANIFEST_DIGEST" --rollback-image-id "$ROLLBACK_IMAGE_ID" --target-image-id "$IMAGE_ID" >/dev/null
2179
+ Guard the atomic autostart disable separately. If it fails, the original token remains valid and production has not been touched; restore the template and propagate the captured status:
2180
+ if disable_butler_autostart; then
2181
+ :
2182
+ else
2183
+ AUTOSTART_DISABLE_STATUS=$?
2184
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" rollback >/dev/null
2185
+ (exit "$AUTOSTART_DISABLE_STATUS")
2186
+ fi
2187
+ Stop the exact predecessor before its final Telegram and filesystem readiness check. Otherwise a concurrent private-runtime receipt can appear between permission normalization and strict validation. The full package and durable transaction are already prepared, and autostart is disabled. Keep the stopped-resident mode strict: no live control socket or mode exception is allowed. Before token rotation, any failure restores the same policy-aware predecessor and propagates the failure; an interrupted stop remains recoverable from the prepared transaction:
2188
+ if docker stop --time 30 ouro-butler \
2189
+ && assert_only_running_butler - \
2190
+ && verify_sanctuary_telegram_readiness "$ROLLBACK_IMAGE_ID" strict; then
2191
+ :
2192
+ else
2193
+ PRECUTOVER_QUIESCENCE_STATUS=$?
2194
+ assert_update_source "$ROLLBACK_IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID"
2195
+ start_only_butler_for_recovery
2196
+ wait_butler_ready ouro-butler
2197
+ enable_butler_autostart
2198
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" rollback >/dev/null
2199
+ (exit "$PRECUTOVER_QUIESCENCE_STATUS")
2200
+ fi
2201
+ Only after pinned stopped-image readiness, full-package preparation, durable transaction preparation and autostart disabling pass, the human rotates MendelowCloudButlerBot's token for that same numeric bot and uses the hidden root-terminal input helper. Do not echo the token, put it in argv/environment/history, copy it into the resident, or replace retained incoming-token during recovery. A failed or interrupted paste must be reconciled by the human before retry; retain the journal and disabled autostart, and do not invent a token:
2202
+ receive_sanctuary_authority_token
2203
+ test "$(stat -c '%u:%g:%a' /mnt/user/appdata/ouro-authority/incoming-token)" = 0:0:600
2204
+ Gateway installation and its tokenless readiness belong inside the stopped-resident transaction, never in the old live precheck. A failure attempts retirement and exact old-image restoration; failure of either keeps autostart disabled and the journals/root inputs intact:
2205
+ if /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" authority-install >/dev/null \
2206
+ && verify_sanctuary_telegram_readiness "$IMAGE_ID"; then
2207
+ :
2208
+ else
2209
+ AUTHORITY_INSTALL_STATUS=$?
2210
+ retire_sanctuary_authority_if_pending
2211
+ assert_update_source "$ROLLBACK_IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID"
2212
+ start_only_butler_for_recovery
2213
+ wait_butler_ready ouro-butler
2214
+ enable_butler_autostart
2215
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" rollback >/dev/null
2216
+ (exit "$AUTHORITY_INSTALL_STATUS")
2217
+ fi
2218
+ Define the stale-rollback cleanup used by the preparation guard:
2219
+ remove_stopped_rollback_if_present() {
2220
+ EXPECTED_STALE_ROLLBACK_IMAGE_ID=$1
2221
+ ROLLBACK_CONTAINER_NAMES=$(docker container ls -a --format '{{.Names}}') || return $?
2222
+ case "
2223
+ $ROLLBACK_CONTAINER_NAMES
2224
+ " in
2225
+ *"
2226
+ ouro-butler-rollback
2227
+ "*)
2228
+ ROLLBACK_RUNNING=$(docker inspect --format '{{.State.Running}}' ouro-butler-rollback) || return $?
2229
+ test "$ROLLBACK_RUNNING" = false || return $?
2230
+ CURRENT_STALE_ROLLBACK_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-rollback) || return $?
2231
+ test "$CURRENT_STALE_ROLLBACK_IMAGE_ID" = "$EXPECTED_STALE_ROLLBACK_IMAGE_ID" || return $?
2232
+ docker rm ouro-butler-rollback || return $?
2233
+ ;;
2234
+ esac
2235
+ }
2236
+ Stop production, remove only a stopped stale rollback, rename the known-good container, verify it remains stopped, and apply the exact target image's package-managed bundle migration in one explicit preparation guard.
2237
+ Package-managed files are exactly `provider-readiness.json`, `tool-profiles.json`, `habits/sanctuary-health.md`, `awaiting/house-care-sweep.md` (the Butler's daily house-care sweep, a never-resolving await), and the five canonical files under `psyche/`. The migration also merges the three bundle-meta version fields. It never installs or mutates steward policy authority. It preserves agent.json, all steward policy and audit bytes, relationships, sessions, and every other state path. Repeating it is a no-op.
2238
+ Before its first managed write, the migrator atomically fsyncs one mode-0600 rollback record at `.sanctuary-package-managed-rollback.json`. That record binds the verified prior bytes, modes, and parent existence for every managed file plus bundle-meta to distinct exact rollback and target image IDs. It is the migration receipt, not a second bundle authority.
2239
+ A managed-file failure restores the prior bytes immediately. Every later container rollback also restores those bytes before the old container restarts, while retaining the receipt; only after the old production container is audited, ready, and back on autostart does `finalize-rollback` remove it without marking the new release committed.
2240
+ After an interrupted update, the same receipt removes partial new containers, discards only validated interrupted-write stages, restores the prior bundle idempotently, and permits only the recorded rollback image to resume as production. A malformed receipt, wrong image, or restore failure leaves autostart disabled and stops safely.
2241
+ Once target readiness and autostart pass, `commit` durably marks the receipt as committing. If interruption happens then, the target stays in place and the next run rechecks its exact topology and readiness before finishing. Migration failure enters the same container rollback arm before target production starts:
2242
+ if docker stop ouro-butler \
2243
+ && remove_stopped_rollback_if_present "$ROLLBACK_IMAGE_ID" \
2244
+ && docker rename ouro-butler ouro-butler-rollback \
2245
+ && test "$(docker inspect --format '{{.State.Running}}' ouro-butler-rollback)" = false \
2246
+ && assert_only_running_butler - \
2247
+ && migrate_sanctuary_package_managed_bundle "$IMAGE_ID" migrate "$ROLLBACK_IMAGE_ID"; then
2248
+ :
2249
+ else
2250
+ PRODUCTION_PREPARATION_STATUS=$?
2251
+ PRODUCTION_PREPARATION_CLEANUP_STATUS=0
2252
+ PRODUCTION_PREPARATION_RECOVERY_SAFE=true
2253
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" verify-jellyfin >/dev/null
2254
+ retire_sanctuary_authority_if_pending
2255
+ if docker container inspect ouro-butler >/dev/null 2>&1; then
2256
+ if docker container inspect ouro-butler-rollback >/dev/null 2>&1; then
2257
+ docker stop ouro-butler-rollback >/dev/null 2>&1 || true
2258
+ CURRENT_ROLLBACK_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-rollback)
2259
+ test "$CURRENT_ROLLBACK_IMAGE_ID" = "$ROLLBACK_IMAGE_ID"
2260
+ docker rm --force ouro-butler-rollback >/dev/null 2>&1 || true
2261
+ fi
2262
+ if docker container inspect ouro-butler-rollback >/dev/null 2>&1; then
2263
+ PRODUCTION_PREPARATION_CLEANUP_STATUS=1
2264
+ if test "$(docker inspect --format '{{.State.Running}}' ouro-butler-rollback)" != false; then
2265
+ PRODUCTION_PREPARATION_RECOVERY_SAFE=false
2266
+ fi
2267
+ fi
2268
+ rollback_sanctuary_bundle_if_pending "$IMAGE_ID"
2269
+ if test "$PRODUCTION_PREPARATION_RECOVERY_SAFE" = true; then
2270
+ assert_update_source "$ROLLBACK_IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID"
2271
+ start_only_butler_for_recovery
2272
+ wait_butler_ready ouro-butler
2273
+ enable_butler_autostart
2274
+ finalize_sanctuary_bundle_rollback_if_retained "$IMAGE_ID"
2275
+ fi
2276
+ elif docker container inspect ouro-butler-rollback >/dev/null 2>&1; then
2277
+ docker stop ouro-butler-rollback >/dev/null 2>&1 || true
2278
+ test "$(docker inspect --format '{{.Image}}' ouro-butler-rollback)" = "$ROLLBACK_IMAGE_ID"
2279
+ rollback_sanctuary_bundle_if_pending "$IMAGE_ID"
2280
+ docker rename ouro-butler-rollback ouro-butler
2281
+ assert_update_source "$ROLLBACK_IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID"
2282
+ start_only_butler_for_recovery
2283
+ wait_butler_ready ouro-butler
2284
+ enable_butler_autostart
2285
+ finalize_sanctuary_bundle_rollback_if_retained "$IMAGE_ID"
2286
+ fi
2287
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" rollback >/dev/null
2288
+ if test "$PRODUCTION_PREPARATION_CLEANUP_STATUS" -ne 0; then
2289
+ exit "$PRODUCTION_PREPARATION_CLEANUP_STATUS"
2290
+ fi
2291
+ (exit "$PRODUCTION_PREPARATION_STATUS")
2292
+ fi
2293
+ Preparation failure therefore either restores the still-named exact production after attempting to remove any stale rollback, or renames the exact stopped rollback back. Both safe paths revalidate and start the old container, wait within the fixed bound, restore production-only autostart atomically, and return the original failure. If stale rollback removal fails, restore production only when the leftover is proven stopped; otherwise leave both containers untouched, roll back the journals, and return the cleanup failure for repair.
2294
+ If neither exact container can be found, the failure returns with Butler autostart disabled.
2295
+ Do not start a target-image daemon between the production rename and final production activation. The exact-image static audit and download-queue readiness have passed. The old image's pinned pre-gateway readiness ran before cutover; the new image's socket-mounted tokenless readiness ran only after authority-install proved the root gateway.
2296
+ Provider and complete daemon readiness are exercised only by the transactional production activation below. Its failure arm restores and revalidates the exact prior production, so a disposable daemon cannot reconcile or claim live external-event state before cutover.
2297
+ Create and activate production from the same exact image ID and exact authority in one explicit conditional so `set -eu` cannot exit before rollback. Only a successful create, effective audit, start, stopped-rollback assertion, and bounded readiness wait may enable production autostart.
2298
+ On failure, capture the activation status, remove only a partially created new production container, restore and audit the stopped rollback against its exact old image ID, prove it ready, restore production-only autostart atomically, and return the original failure. If the partial target cannot be removed, preserve its matching target bundle and retained migration receipt, roll back the DockerMan journal without attempting the colliding rename, then return the cleanup failure:
2299
+ if test "$(inspect_registry_manifest_digest "$VERSION_IMAGE")" = "$MANIFEST_DIGEST" \
2300
+ && test "$(docker image inspect --format '{{.Id}}' "$VERSION_IMAGE")" = "$IMAGE_ID" \
2301
+ && create_sanctuary_container "$IMAGE_ID" "$VERSION_IMAGE" "$TARGET_MOUNT_CONTRACT" \
2302
+ && audit_effective ouro-butler "$IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID" "$TARGET_MOUNT_CONTRACT" "$VERSION_IMAGE" "$TEMPLATE_ICON" \
2303
+ && assert_only_running_butler - \
2304
+ && /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" authority-activate >/dev/null \
2305
+ && assert_only_running_butler ouro-butler \
2306
+ && test "$(docker inspect --format '{{.Image}}' ouro-butler)" = "$IMAGE_ID" \
2307
+ && test "$(docker inspect --format '{{.State.Running}}' ouro-butler-rollback)" = false \
2308
+ && wait_butler_ready ouro-butler \
2309
+ && enable_butler_autostart \
2310
+ && /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" mark-committing >/dev/null; then
2311
+ :
2312
+ else
2313
+ PRODUCTION_ACTIVATION_STATUS=$?
2314
+ PRODUCTION_ACTIVATION_CLEANUP_STATUS=0
2315
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" verify-jellyfin >/dev/null
2316
+ retire_sanctuary_authority_if_pending
2317
+ if docker container inspect ouro-butler >/dev/null 2>&1; then
2318
+ docker stop ouro-butler >/dev/null 2>&1 || true
2319
+ PARTIAL_PRODUCTION_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler)
2320
+ test "$PARTIAL_PRODUCTION_IMAGE_ID" = "$IMAGE_ID"
2321
+ docker rm --force ouro-butler >/dev/null 2>&1 || true
2322
+ fi
2323
+ if docker container inspect ouro-butler >/dev/null 2>&1; then
2324
+ PRODUCTION_ACTIVATION_CLEANUP_STATUS=1
2325
+ fi
2326
+ if test "$PRODUCTION_ACTIVATION_CLEANUP_STATUS" -eq 0; then
2327
+ CURRENT_ROLLBACK_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler-rollback)
2328
+ test "$CURRENT_ROLLBACK_IMAGE_ID" = "$ROLLBACK_IMAGE_ID"
2329
+ migrate_sanctuary_package_managed_bundle "$IMAGE_ID" rollback
2330
+ docker rename ouro-butler-rollback ouro-butler
2331
+ assert_update_source "$ROLLBACK_IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID"
2332
+ start_only_butler_for_recovery
2333
+ wait_butler_ready ouro-butler
2334
+ enable_butler_autostart
2335
+ migrate_sanctuary_package_managed_bundle "$IMAGE_ID" finalize-rollback
2336
+ fi
2337
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" rollback >/dev/null
2338
+ if test "$PRODUCTION_ACTIVATION_CLEANUP_STATUS" -ne 0; then
2339
+ exit "$PRODUCTION_ACTIVATION_CLEANUP_STATUS"
2340
+ fi
2341
+ (exit "$PRODUCTION_ACTIVATION_STATUS")
2342
+ fi
2343
+ migrate_sanctuary_package_managed_bundle "$IMAGE_ID" commit
2344
+ FINAL_PROOF_ROOT="$EVENT_ASSET_STAGE/final-proof"
2345
+ FINAL_PROOF_PATH=$(write_dockerman_final_proof "$IMAGE_ID" "$VERSION_IMAGE" "$TEMPLATE_ICON" "$FINAL_PROOF_ROOT")
2346
+ verify_known_good_rollback_artifact "$ROLLBACK_IMAGE_ID"
2347
+ /usr/local/bin/node "$STAGED_DOCKERMAN_TRANSACTION" commit --proof "$FINAL_PROOF_PATH" >/dev/null
2348
+ cleanup_event_asset_stage
2349
+ trap - EXIT
2350
+ Keep ouro-butler-rollback stopped until the new production container is proven or the explicit rollback arm restores it. The rollback arm first retires root registrations and executions, stops the gateway, ends the epoch and restores the current valid token/cursor. Only then does it restore the prior bundle and rename the untouched three-mount alpha.816 container. start_only_butler_for_recovery invokes authority-restore while the authority journal exists; it cannot bypass retirement with docker start. Never create production from a mutable tag, a bare tag, or a bare local image ID.
2351
+ Docker tab Update, Force Update, Edit/Apply, Update All, and CA Action Centre updates remain visible but are unsupported because stock recreation deletes reviewed rollback evidence. Visibility, start, stop, and autostart remain supported; use only this reviewed version-tag transaction for updates.
2352
+ Community Apps determines installed state from the DockerMan template plus the live container name and image. The helper proves that same relationship without calling the endpoint that refreshes Community Apps' UI cache; the later live UI smoke confirms what Ari sees.
2353
+
2354
+ Execution-only primitive refresh:
2355
+
2356
+ A reviewed Unraid update to prlimit or setsid makes new host execution unavailable, but the installed gateway can still boot for Telegram and retire for rollback. Package, Node and shell pins remain mandatory. Gateway launch uses Node's native detached process support; it does not execute an unreviewed setsid binary.
2357
+
2358
+ Root maintainer: stop the verified gateway process using its exact root-owned lock/PID identity, then confirm there is no pending DockerMan transaction or unresolved execution, supervisor or cgroup state. Review the current prlimit and setsid file hashes and ownership before supplying their full SHA-256 digests to the package-owned command below. The command verifies those exact bytes and metadata; it never adopts current hashes implicitly. It changes no token, issuer, owner, cursor, policy or grant. An interrupted two-file publication remains fail-closed and can be completed by repeating the same reviewed command.
2359
+
2360
+ /usr/local/bin/node /mnt/user/appdata/ouro-authority/package/dist/heart/daemon/sanctuary-authority-root-lifecycle.js repin-execution sha256:REVIEWED_PRLIMIT_SHA256 sha256:REVIEWED_SETSID_SHA256
2361
+ /usr/local/bin/node /mnt/user/appdata/ouro-authority/package/dist/heart/daemon/sanctuary-authority-root-lifecycle.js boot
2362
+
2363
+ Replace each REVIEWED_*_SHA256 placeholder with its reviewed 64 hexadecimal digits. After restart, verify the signed host.status health result before proposing a new host command. Changed package, Node or shell pins require repair of that separate boundary, not this execution-only refresh.
2364
+
2365
+ Backup:
2366
+ Set BACKUP_ROOT to a new absolute snapshot path on the destination filesystem.
2367
+ Set AUDIT_RUNNER_IMAGE_TAG to the reviewed new image containing the
2368
+ legacy-aware auditor; the alpha.742 source image cannot be the runner.
2369
+ Capture and validate the exact source image before stopping ouro-butler, then
2370
+ build a temporary snapshot with root-only provenance and atomically rename it into place:
2371
+ test -n "${BACKUP_ROOT-}"
2372
+ case "$BACKUP_ROOT" in /*) ;; *) exit 1 ;; esac
2373
+ test "$BACKUP_ROOT" != /
2374
+ test ! -e "$BACKUP_ROOT"
2375
+ BACKUP_PARENT=$(dirname -- "$BACKUP_ROOT")
2376
+ test "$(cd -- "$BACKUP_PARENT" && pwd -P)" = "$BACKUP_PARENT"
2377
+ BACKUP_TMP=$BACKUP_ROOT.tmp.$$
2378
+ test ! -e "$BACKUP_TMP"
2379
+ AUDIT_RUNNER_IMAGE_TAG=ouro-butler:<new-version>
2380
+ AUDIT_RUNNER_IMAGE_ID=$(docker image inspect --format '{{.Id}}' "$AUDIT_RUNNER_IMAGE_TAG")
2381
+ validate_exact_image_id "$AUDIT_RUNNER_IMAGE_ID"
2382
+ test "$AUDIT_RUNNER_IMAGE_ID" != sha256:681449ad47a2621705cd339b481e6339236b31dc65e195b1cf5025d0f2191d7d
2383
+ BACKUP_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler)
2384
+ validate_exact_image_id "$BACKUP_IMAGE_ID"
2385
+ assert_update_source "$BACKUP_IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID"
2386
+ assert_only_running_butler ouro-butler
2387
+ wait_butler_ready ouro-butler
2388
+ BACKUP_AUTOSTART_COUNTS=$(butler_autostart_counts)
2389
+ case "$BACKUP_AUTOSTART_COUNTS" in "0 0 0 0"|"1 0 0 0") ;; *) exit 1 ;; esac
2390
+ backup_host_file() {
2391
+ BACKUP_HOST_SOURCE=$1
2392
+ BACKUP_HOST_RELATIVE=$2
2393
+ case "$BACKUP_HOST_RELATIVE" in
2394
+ custom/usenet_health.sh|custom/ouro-events/bootstrap-spool.sh|custom/ouro-events/emit-event.mjs|custom/ouro-events/emit-usenet-event.sh|custom/ouro-events/install-usenet-guard.sh) ;;
2395
+ *) return 1 ;;
2396
+ esac
2397
+ if test -e "$BACKUP_HOST_SOURCE" || test -L "$BACKUP_HOST_SOURCE"; then
2398
+ test -f "$BACKUP_HOST_SOURCE" && test ! -L "$BACKUP_HOST_SOURCE" || return 1
2399
+ ! host_file_contains_inline_credential "$BACKUP_HOST_SOURCE" || return 1
2400
+ install -D -m 0600 -o 0 -g 0 "$BACKUP_HOST_SOURCE" "$BACKUP_TMP/host/$BACKUP_HOST_RELATIVE" || return $?
2401
+ printf 'present\t%s\n' "$BACKUP_HOST_RELATIVE" >>"$BACKUP_TMP/host/inventory" || return $?
2402
+ else
2403
+ printf 'absent\t%s\n' "$BACKUP_HOST_RELATIVE" >>"$BACKUP_TMP/host/inventory" || return $?
2404
+ fi
2405
+ }
2406
+ host_file_contains_inline_credential() {
2407
+ LC_ALL=C awk '
2408
+ BEGIN { IGNORECASE = 1; found = 0 }
2409
+ /[0-9]{6,}:[A-Za-z0-9_-]{20,}/ { found = 1 }
2410
+ /Authorization:[[:space:]]*(Bearer|Basic)[[:space:]]+["\047]?[A-Za-z0-9][A-Za-z0-9._~+\/=:-]{11,}/ { found = 1 }
2411
+ /--(token|api-key|api_key|secret|password)(=|[[:space:]]+)["\047]?[A-Za-z0-9][A-Za-z0-9._~+\/=:-]{11,}/ { found = 1 }
2412
+ /[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\/@[:space:]]+:[^\/@[:space:]]+@/ { found = 1 }
2413
+ /-----BEGIN ([A-Z0-9]+ )*PRIVATE KEY-----/ { found = 1 }
2414
+ /(token|secret|password|pass|api[_-]?key)[A-Za-z0-9_-]*["\047[:space:]]*[:=][[:space:]]*["\047]?[A-Za-z0-9][A-Za-z0-9._~+\/=:-]{11,}/ { found = 1 }
2415
+ END { exit found ? 0 : 1 }
2416
+ ' "$1"
2417
+ }
2418
+ snapshot_butler_go_fragments() {
2419
+ BACKUP_GO_SOURCE=$1
2420
+ BACKUP_GO_TARGET=$2
2421
+ : >"$BACKUP_GO_TARGET" || return $?
2422
+ while IFS= read -r BACKUP_GO_LINE || test -n "$BACKUP_GO_LINE"; do
2423
+ case "$BACKUP_GO_LINE" in
2424
+ "/boot/config/custom/ouro-events/bootstrap-spool.sh --mount"|"/bin/bash /boot/config/custom/ouro-events/bootstrap-spool.sh --mount"|"/bin/bash /boot/config/custom/ouro-events/install-usenet-guard.sh --boot"|"/bin/bash /boot/config/custom/ouro-events/install-usenet-guard.sh --boot --install-root /boot/config/custom")
2425
+ printf '%s\n' "$BACKUP_GO_LINE" >>"$BACKUP_GO_TARGET" || return $?
2426
+ ;;
2427
+ esac
2428
+ done <"$BACKUP_GO_SOURCE"
2429
+ }
2430
+ snapshot_butler_cron_fragments() {
2431
+ BACKUP_CRON_INPUT=$1
2432
+ BACKUP_CRON_TARGET=$2
2433
+ : >"$BACKUP_CRON_TARGET" || return $?
2434
+ while IFS= read -r BACKUP_CRON_LINE || test -n "$BACKUP_CRON_LINE"; do
2435
+ case "$BACKUP_CRON_LINE" in
2436
+ "*/15 * * * * /bin/bash /boot/config/custom/usenet_health.sh"|"*/15 * * * * /bin/bash /boot/config/custom/usenet_health.sh # ouro:usenet-health")
2437
+ printf '%s\n' "$BACKUP_CRON_LINE" >>"$BACKUP_CRON_TARGET" || return $?
2438
+ ;;
2439
+ esac
2440
+ done <"$BACKUP_CRON_INPUT"
2441
+ }
2442
+ create_private_cron_capture() {
2443
+ BACKUP_CRON_ROOT=$(mktemp -d /tmp/ouro-backup-cron.XXXXXX) || return $?
2444
+ BACKUP_CRON_SOURCE=$BACKUP_CRON_ROOT/stdout
2445
+ BACKUP_CRON_ERROR=$BACKUP_CRON_ROOT/stderr
2446
+ test -d "$BACKUP_CRON_ROOT" && test ! -L "$BACKUP_CRON_ROOT" || return 1
2447
+ test "$(stat -c '%u:%a' "$BACKUP_CRON_ROOT" 2>/dev/null || stat -f '%u:%Lp' "$BACKUP_CRON_ROOT")" = "$(id -u):700" || return 1
2448
+ install -m 0600 /dev/null "$BACKUP_CRON_SOURCE" || return $?
2449
+ install -m 0600 /dev/null "$BACKUP_CRON_ERROR" || return $?
2450
+ test -f "$BACKUP_CRON_SOURCE" && test ! -L "$BACKUP_CRON_SOURCE" || return 1
2451
+ test -f "$BACKUP_CRON_ERROR" && test ! -L "$BACKUP_CRON_ERROR" || return 1
2452
+ test "$(stat -c '%u:%a' "$BACKUP_CRON_SOURCE" 2>/dev/null || stat -f '%u:%Lp' "$BACKUP_CRON_SOURCE")" = "$(id -u):600" || return 1
2453
+ test "$(stat -c '%u:%a' "$BACKUP_CRON_ERROR" 2>/dev/null || stat -f '%u:%Lp' "$BACKUP_CRON_ERROR")" = "$(id -u):600" || return 1
2454
+ }
2455
+ cleanup_private_cron_capture() {
2456
+ rm -f -- "$BACKUP_CRON_SOURCE" "$BACKUP_CRON_ERROR" || return $?
2457
+ rmdir -- "$BACKUP_CRON_ROOT"
2458
+ }
2459
+ snapshot_butler_host_fragments() {
2460
+ create_private_cron_capture || return $?
2461
+ trap 'cleanup_private_cron_capture' RETURN
2462
+ if test -f /boot/config/go && test ! -L /boot/config/go; then
2463
+ BACKUP_GO_STATE=present
2464
+ BACKUP_GO_DIGEST=$(sha256sum /boot/config/go | awk '{print $1}') || return $?
2465
+ snapshot_butler_go_fragments /boot/config/go "$BACKUP_TMP/host/go.butler-lines" || return $?
2466
+ elif test -e /boot/config/go || test -L /boot/config/go; then
2467
+ return 1
2468
+ else
2469
+ BACKUP_GO_STATE=absent
2470
+ BACKUP_GO_DIGEST=-
2471
+ : >"$BACKUP_TMP/host/go.butler-lines" || return $?
2472
+ fi
2473
+ BACKUP_CRON_USER=$(id -un) || return $?
2474
+ if crontab -l >"$BACKUP_CRON_SOURCE" 2>"$BACKUP_CRON_ERROR"; then
2475
+ BACKUP_CRON_STATE=present
2476
+ BACKUP_CRON_DIGEST=$(sha256sum "$BACKUP_CRON_SOURCE" | awk '{print $1}') || return $?
2477
+ else
2478
+ BACKUP_CRON_STATUS=$?
2479
+ if test "$BACKUP_CRON_STATUS" -eq 1 && grep -Fxq "no crontab for $BACKUP_CRON_USER" "$BACKUP_CRON_ERROR"; then
2480
+ BACKUP_CRON_STATE=absent
2481
+ BACKUP_CRON_DIGEST=-
2482
+ : >"$BACKUP_CRON_SOURCE" || return $?
2483
+ else
2484
+ return "$BACKUP_CRON_STATUS"
2485
+ fi
2486
+ fi
2487
+ rm -f -- "$BACKUP_CRON_ERROR" || return $?
2488
+ snapshot_butler_cron_fragments "$BACKUP_CRON_SOURCE" "$BACKUP_TMP/host/crontab.butler-lines" || return $?
2489
+ BACKUP_GO_COUNT=$(awk 'END { print NR + 0 }' "$BACKUP_TMP/host/go.butler-lines") || return $?
2490
+ BACKUP_CRON_COUNT=$(awk 'END { print NR + 0 }' "$BACKUP_TMP/host/crontab.butler-lines") || return $?
2491
+ printf 'go\t%s\t%s\t%s\ncrontab\t%s\t%s\t%s\n' "$BACKUP_GO_STATE" "$BACKUP_GO_DIGEST" "$BACKUP_GO_COUNT" "$BACKUP_CRON_STATE" "$BACKUP_CRON_DIGEST" "$BACKUP_CRON_COUNT" >"$BACKUP_TMP/host/global-state" || return $?
2492
+ chown 0:0 "$BACKUP_TMP/host/go.butler-lines" "$BACKUP_TMP/host/crontab.butler-lines" "$BACKUP_TMP/host/global-state" || return $?
2493
+ chmod 0600 "$BACKUP_TMP/host/go.butler-lines" "$BACKUP_TMP/host/crontab.butler-lines" "$BACKUP_TMP/host/global-state" || return $?
2494
+ printf 'present\t%s\n' go.butler-lines crontab.butler-lines global-state >>"$BACKUP_TMP/host/inventory" || return $?
2495
+ cleanup_private_cron_capture || return $?
2496
+ trap - RETURN
2497
+ }
2498
+ Snapshot both of these directories together:
2499
+ /mnt/user/appdata/ouro-butler/runtime/.ouro-cli
2500
+ /mnt/user/appdata/ouro-butler/agent/sanctuary.ouro
2501
+ A routine backup must not contain container-credentials.json or
2502
+ container-credentials.json.consuming. If either exists, credential migration
2503
+ is pending or failed and must be reconciled before taking the backup.
2504
+ The Telegram control socket is live process state, not durable data. Exclude
2505
+ exactly that socket while preserving every regular file byte-for-byte, then
2506
+ require it to be absent from the stopped backup:
2507
+ BACKUP_OPERATION_STATUS=0
2508
+ if docker stop ouro-butler \
2509
+ && test "$(docker inspect --format '{{.State.Running}}' ouro-butler)" = false \
2510
+ && install -d -m 0700 -o 0 -g 0 "$BACKUP_TMP" "$BACKUP_TMP/runtime" "$BACKUP_TMP/agent" "$BACKUP_TMP/host" "$BACKUP_TMP/provenance" \
2511
+ && install -d -m 0700 -o 0 -g 0 "$BACKUP_TMP/host/custom" "$BACKUP_TMP/host/custom/ouro-events" \
2512
+ && install -m 0600 -o 0 -g 0 /dev/null "$BACKUP_TMP/host/inventory" \
2513
+ && backup_host_file /boot/config/custom/usenet_health.sh custom/usenet_health.sh \
2514
+ && backup_host_file /boot/config/custom/ouro-events/bootstrap-spool.sh custom/ouro-events/bootstrap-spool.sh \
2515
+ && backup_host_file /boot/config/custom/ouro-events/emit-event.mjs custom/ouro-events/emit-event.mjs \
2516
+ && backup_host_file /boot/config/custom/ouro-events/emit-usenet-event.sh custom/ouro-events/emit-usenet-event.sh \
2517
+ && backup_host_file /boot/config/custom/ouro-events/install-usenet-guard.sh custom/ouro-events/install-usenet-guard.sh \
2518
+ && snapshot_butler_host_fragments \
2519
+ && test ! -e "$BACKUP_TMP/host/notify.conf" \
2520
+ && test ! -e "$BACKUP_TMP/host/sabnzbd.ini" \
2521
+ && rsync -a --exclude='/state/acceptance/telegram-control.sock' /mnt/user/appdata/ouro-butler/runtime/.ouro-cli "$BACKUP_TMP/runtime/" \
2522
+ && rsync -a --exclude='/state/acceptance/telegram-control.sock' /mnt/user/appdata/ouro-butler/agent/sanctuary.ouro "$BACKUP_TMP/agent/" \
2523
+ && test ! -S "$BACKUP_TMP/agent/sanctuary.ouro/state/acceptance/telegram-control.sock" \
2524
+ && validate_sanctuary_roots "$BACKUP_TMP/runtime/.ouro-cli" "$BACKUP_TMP/agent/sanctuary.ouro" \
2525
+ && docker container inspect ouro-butler >"$BACKUP_TMP/provenance/container-inspect.json" \
2526
+ && docker image inspect "$BACKUP_IMAGE_ID" >"$BACKUP_TMP/provenance/image-inspect.json" \
2527
+ && docker run --rm --pull=never --network=none --read-only --entrypoint /usr/local/bin/node "$BACKUP_IMAGE_ID" -p 'require("/opt/ouro/package.json").version' >"$BACKUP_TMP/provenance/package-version" \
2528
+ && printf '%s\n' "$BACKUP_IMAGE_ID" >"$BACKUP_TMP/provenance/image-id" \
2529
+ && chown 0:0 "$BACKUP_TMP/provenance/container-inspect.json" "$BACKUP_TMP/provenance/image-inspect.json" "$BACKUP_TMP/provenance/package-version" "$BACKUP_TMP/provenance/image-id" \
2530
+ && chmod 0600 "$BACKUP_TMP/provenance/container-inspect.json" "$BACKUP_TMP/provenance/image-inspect.json" "$BACKUP_TMP/provenance/package-version" "$BACKUP_TMP/provenance/image-id" \
2531
+ && (cd "$BACKUP_TMP" && find runtime agent host provenance -xdev -type f ! -path provenance/manifest.sha256 -exec sha256sum -- {} + | LC_ALL=C sort -k2 >provenance/manifest.sha256) \
2532
+ && chown 0:0 "$BACKUP_TMP/provenance/manifest.sha256" \
2533
+ && chmod 0600 "$BACKUP_TMP/provenance/manifest.sha256" \
2534
+ && verify_sanctuary_snapshot_provenance "$BACKUP_TMP" "$BACKUP_IMAGE_ID" \
2535
+ && sync -f "$BACKUP_TMP/provenance/manifest.sha256" \
2536
+ && mv -- "$BACKUP_TMP" "$BACKUP_ROOT" \
2537
+ && sync -f "$BACKUP_PARENT"; then
2538
+ :
2539
+ else
2540
+ BACKUP_OPERATION_STATUS=$?
2541
+ fi
2542
+ if assert_update_source "$BACKUP_IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID" \
2543
+ && assert_only_running_butler - \
2544
+ && docker start ouro-butler \
2545
+ && assert_only_running_butler ouro-butler \
2546
+ && wait_butler_ready ouro-butler \
2547
+ && verify_butler_autostart "$BACKUP_AUTOSTART_COUNTS"; then
2548
+ :
2549
+ else
2550
+ BACKUP_RECOVERY_STATUS=$?
2551
+ if test -d "$BACKUP_ROOT"; then
2552
+ printf '%s\n' "CRITICAL: production recovery failed after backup; completed snapshot remains intact at $BACKUP_ROOT" >&2
2553
+ else
2554
+ printf '%s\n' "CRITICAL: production recovery failed and no completed snapshot was published; inspect $BACKUP_TMP" >&2
2555
+ fi
2556
+ (exit "$BACKUP_RECOVERY_STATUS")
2557
+ fi
2558
+ if test "$BACKUP_OPERATION_STATUS" -ne 0; then
2559
+ if test -d "$BACKUP_ROOT"; then
2560
+ printf '%s\n' "Backup publication was not durably confirmed; production was recovered; completed snapshot remains intact at $BACKUP_ROOT" >&2
2561
+ else
2562
+ printf '%s\n' "Backup failed before atomic publication; production was recovered; inspect $BACKUP_TMP" >&2
2563
+ fi
2564
+ (exit "$BACKUP_OPERATION_STATUS")
2565
+ fi
2566
+
2567
+ Restore:
2568
+ Set BACKUP_ROOT to the exact verified snapshot containing `runtime/.ouro-cli`
2569
+ and `agent/sanctuary.ouro`, set IMAGE_ID to its recorded local image ID, and
2570
+ set AUDIT_RUNNER_IMAGE_ID to the exact reviewed new image containing the
2571
+ legacy-aware auditor. The runner is independent from the restored image.
2572
+ AUDIT_RUNNER_IMAGE_TAG=ouro-butler:<new-version>
2573
+ AUDIT_RUNNER_IMAGE_ID=$(docker image inspect --format '{{.Id}}' "$AUDIT_RUNNER_IMAGE_TAG")
2574
+ RESTORE_VERSION_IMAGE=$(/usr/local/bin/node -e '
2575
+ const fs = require("node:fs");
2576
+ const [containerPath, versionPath] = process.argv.slice(1);
2577
+ const containers = JSON.parse(fs.readFileSync(containerPath, "utf8"));
2578
+ const version = fs.readFileSync(versionPath, "utf8").trim();
2579
+ const expected = `ghcr.io/ourostack/ouroboros-butler:${version}`;
2580
+ if (!Array.isArray(containers) || containers.length !== 1 || containers[0]?.Config?.Image !== expected) process.exit(1);
2581
+ process.stdout.write(expected);
2582
+ ' "$BACKUP_ROOT/provenance/container-inspect.json" "$BACKUP_ROOT/provenance/package-version")
2583
+ test "$(docker image inspect --format '{{.Id}}' "$RESTORE_VERSION_IMAGE")" = "$IMAGE_ID"
2584
+ RESTORE_MOUNT_CONTRACT=$(sanctuary_image_mount_contract "$IMAGE_ID")
2585
+ audit_registered_dockerman_template "$AUDIT_RUNNER_IMAGE_ID" "$RESTORE_VERSION_IMAGE" "$RESTORE_MOUNT_CONTRACT"
2586
+ This data-snapshot Restore is not authority rollback. It must not overwrite a current gateway cursor, reintroduce a revoked resident token or remove a gateway mount behind the root owner. Refuse before mutation if a root epoch/config or deployment journal exists; use the retained Update transaction's authority-retire/authority-restore recovery instead. After a committed authority installation, obtain a reviewed root-aware restore transaction rather than applying this historical data snapshot:
2587
+ test ! -e /mnt/user/appdata/ouro-authority/active.json && test ! -L /mnt/user/appdata/ouro-authority/active.json
2588
+ test ! -e /boot/config/custom/ouro-butler/docker-man-template-transaction.json && test ! -L /boot/config/custom/ouro-butler/docker-man-template-transaction.json
2589
+ test "$RESTORE_MOUNT_CONTRACT" = canonical-pre-gateway
2590
+ Before changing autostart, durable roots, or live containers, run the nounset-safe input, backup-root, image, and topology preflight. It requires a nonempty canonical absolute BACKUP_ROOT other than /, both required directories, an exact local sha256 image ID, canonical production as the only running Butler, no staging or rollback, and at most one exact stopped legacy-evidence container. It also audits the live source container with the reviewed runner.
2591
+ Restore never rewrites DockerMan registration outside the reviewed template transaction. The preflight therefore stops unless the persistent template already names the exact snapshot version, and the post-start check proves DockerMan and Community Apps still recognize it.
2592
+ If the template names another version, first run the same reviewed version-tag update transaction for the snapshot version, then rerun Restore. A mismatch stops before autostart, durable-root, or production-container changes:
2593
+ if assert_restore_preflight; then
2594
+ :
2595
+ else
2596
+ RESTORE_PREFLIGHT_STATUS=$?
2597
+ (exit "$RESTORE_PREFLIGHT_STATUS")
2598
+ fi
2599
+ The verified host snapshot is restored only by this explicit Restore path.
2600
+ Ordinary update failure continues to use the installer's short-lived
2601
+ transaction rollback. Extract the installer from the reviewed runner image,
2602
+ then let that fixed allowlist transaction restore exact presence/absence for
2603
+ the five guard assets and reapply only the captured Butler-owned go/crontab
2604
+ fragments. Unrelated current go/crontab lines are never stored in the durable
2605
+ snapshot and remain untouched by restore. The transaction deactivates the
2606
+ current owned cron before swapping files and restores the entire pre-restore
2607
+ host state if any swap or final crontab activation fails:
2608
+ HOST_RESTORE_INSTALLER=$(mktemp /tmp/ouro-usenet-host-restore.XXXXXX)
2609
+ docker run --rm --pull=never --network=none --entrypoint /bin/cat "$AUDIT_RUNNER_IMAGE_ID" /opt/ouro/deploy/unraid/ouro-events/install-usenet-guard.sh >"$HOST_RESTORE_INSTALLER"
2610
+ chmod 0500 "$HOST_RESTORE_INSTALLER"
2611
+ Guard the atomic autostart disable before stopping or removing any Butler
2612
+ container. Failure propagates while the existing production remains untouched:
2613
+ /bin/bash /boot/config/custom/ouro-events/bootstrap-spool.sh --mount
2614
+ test "$(findmnt -n -o FSTYPE --target /boot/config/custom/ouro-events/spool)" = tmpfs
2615
+ test "$(stat -c '%u:%g:%a' /boot/config/custom/ouro-events/spool)" = 0:0:755
2616
+ RESTORE_INSTALL_PROOF_ROOT=$(mktemp -d /mnt/user/appdata/ouro-butler/staging/restore-install-proof.XXXXXX)
2617
+ chmod 0700 "$RESTORE_INSTALL_PROOF_ROOT"
2618
+ if disable_butler_autostart; then
2619
+ :
2620
+ else
2621
+ RESTORE_AUTOSTART_DISABLE_STATUS=$?
2622
+ rmdir -- "$RESTORE_INSTALL_PROOF_ROOT"
2623
+ (exit "$RESTORE_AUTOSTART_DISABLE_STATUS")
2624
+ fi
2625
+ Stop and remove only ouro-butler, restore both roots without stale files,
2626
+ restore exact ownership, validate the image, and create/audit/start/bounded-wait
2627
+ the restored production inside one explicit condition. The initial tolerant
2628
+ stop plus inspected force-removal safely handles an already absent or stopped
2629
+ container:
2630
+ if { docker stop ouro-butler >/dev/null 2>&1 || true; } \
2631
+ && {
2632
+ if docker container inspect ouro-butler >/dev/null 2>&1; then
2633
+ docker rm --force ouro-butler
2634
+ else
2635
+ :
2636
+ fi
2637
+ } \
2638
+ && ! docker container inspect ouro-butler >/dev/null 2>&1 \
2639
+ && rsync -a --delete "$BACKUP_ROOT/runtime/.ouro-cli/" /mnt/user/appdata/ouro-butler/runtime/.ouro-cli/ \
2640
+ && rsync -a --delete "$BACKUP_ROOT/agent/sanctuary.ouro/" /mnt/user/appdata/ouro-butler/agent/sanctuary.ouro/ \
2641
+ && chown -R 10001:10001 /mnt/user/appdata/ouro-butler/runtime/.ouro-cli /mnt/user/appdata/ouro-butler/agent/sanctuary.ouro \
2642
+ && validate_sanctuary_roots /mnt/user/appdata/ouro-butler/runtime/.ouro-cli /mnt/user/appdata/ouro-butler/agent/sanctuary.ouro \
2643
+ && /bin/bash "$HOST_RESTORE_INSTALLER" --restore-root "$BACKUP_ROOT/host" \
2644
+ && rm -f "$HOST_RESTORE_INSTALLER" \
2645
+ && docker image inspect "$IMAGE_ID" >/dev/null \
2646
+ && create_sanctuary_container "$IMAGE_ID" "$RESTORE_VERSION_IMAGE" "$RESTORE_MOUNT_CONTRACT" \
2647
+ && audit_effective ouro-butler "$IMAGE_ID" "$AUDIT_RUNNER_IMAGE_ID" "$RESTORE_MOUNT_CONTRACT" "$RESTORE_VERSION_IMAGE" https://raw.githubusercontent.com/ourostack/ouroboros/main/assets/ouroboros.png \
2648
+ && assert_only_running_butler - \
2649
+ && docker start ouro-butler \
2650
+ && assert_only_running_butler ouro-butler \
2651
+ && test "$(docker inspect --format '{{.Image}}' ouro-butler)" = "$IMAGE_ID" \
2652
+ && wait_butler_ready ouro-butler \
2653
+ && verify_dockerman_and_community_apps "$RESTORE_VERSION_IMAGE" "$RESTORE_INSTALL_PROOF_ROOT/install.json" \
2654
+ && rm -f -- "$RESTORE_INSTALL_PROOF_ROOT/install.json" \
2655
+ && rmdir -- "$RESTORE_INSTALL_PROOF_ROOT" \
2656
+ && enable_butler_autostart; then
2657
+ :
2658
+ else
2659
+ RESTORE_ACTIVATION_STATUS=$?
2660
+ if docker container inspect ouro-butler >/dev/null 2>&1; then
2661
+ docker stop ouro-butler >/dev/null 2>&1 || true
2662
+ PARTIAL_RESTORE_IMAGE_ID=$(docker inspect --format '{{.Image}}' ouro-butler)
2663
+ test "$PARTIAL_RESTORE_IMAGE_ID" = "$IMAGE_ID"
2664
+ docker rm --force ouro-butler >/dev/null 2>&1 || true
2665
+ fi
2666
+ ! docker container inspect ouro-butler >/dev/null 2>&1 || exit 1
2667
+ rm -f "$HOST_RESTORE_INSTALLER"
2668
+ rm -f -- "$RESTORE_INSTALL_PROOF_ROOT/install.json"
2669
+ rmdir -- "$RESTORE_INSTALL_PROOF_ROOT"
2670
+ (exit "$RESTORE_ACTIVATION_STATUS")
2671
+ fi
2672
+ A restore has no retained old container or pre-restore data root to roll back
2673
+ to. Any stop/remove, data replacement, ownership, image validation, create,
2674
+ audit, start, or readiness failure therefore reaches the same cleanup arm,
2675
+ leaves all Butler autostart entries disabled, and propagates the captured
2676
+ failure for operator repair or a verified restore retry.
2677
+
2678
+ Credential recovery:
2679
+ The one canonical Telegram identity is display name `Mendelow Cloud Butler`,
2680
+ username `MendelowCloudButlerBot`, numeric bot ID `8541786263`. Treat any
2681
+ different display name, username, numeric ID, or fallback handle as a hard
2682
+ preflight failure; do not start polling or send a test message.
2683
+ Run `bootstrap_sanctuary_vault "$IMAGE_ID"` interactively before installing
2684
+ credentials. It uses only fresh `--rm` containers from that exact image as
2685
+ UID/GID 10001 with the canonical two binds; create/unlock is the sole `-it`
2686
+ action so the master secret remains on the hidden terminal prompt.
2687
+ Its first read-only `vault status` is authoritative: it runs `vault create`
2688
+ only when the locator is absent, runs `vault unlock` only when the locator
2689
+ exists but local unlock is missing, and does not prompt when local unlock is
2690
+ already available. It then requires the configured locator, available local
2691
+ unlock, and successful auth verification. Never guess from a failed status
2692
+ command.
2693
+ Initial legacy adoption passes the exact legacy envelope path as the helper's
2694
+ second argument. After vault availability, the helper validates and atomically
2695
+ copies that envelope into the canonical runtime root, imports it with a fresh
2696
+ same-image one-shot container, and requires both canonical source and claim to
2697
+ be absent before provider readiness. The exact legacy source remains untouched
2698
+ as rollback evidence until canonical acceptance completes.
2699
+ Restore or unlock the Sanctuary agent vault, then run provider refresh.
2700
+ /mnt/user/appdata/ouro-butler/runtime/.ouro-cli/container-credentials.json
2701
+ exists only for a one-time migration: if
2702
+ used, install it atomically as root with ownership 10001:10001 and mode 0600.
2703
+ Startup atomically claims it as container-credentials.json.consuming and
2704
+ writes every credential class into the unlocked Sanctuary vault before deleting the claimed envelope.
2705
+ Only then does it refresh the daemon's in-memory credentials.
2706
+ If validation or any vault write fails, startup fails closed and preserves
2707
+ container-credentials.json.consuming for the next startup to reconcile.
2708
+ Restore or create/unlock the configured agent vault, then restart the same
2709
+ reviewed image and let it retry the preserved claim. If both the source and
2710
+ claimed envelope exist and they are safe regular 0600 files owned by the
2711
+ runtime user, startup resumes automatically only when they are byte-for-byte identical:
2712
+ it durably removes the redundant unclaimed source and continues the existing claim.
2713
+ If they differ, the repair is human-required: stop the Butler, securely compare and quarantine
2714
+ the two envelopes, then restore exactly one reviewed envelope at the source path.
2715
+ Never print either envelope's contents or place them in logs or command arguments.
2716
+ After successful import, both files
2717
+ are absent and the vault is the only credential source of truth.
2718
+ `provision_sanctuary_sab_credential "$IMAGE_ID"` is the one-shot migration for
2719
+ the existing SAB key. Root reads the fixed host INI, writes only a mode-0600
2720
+ `ouro.runtimeCredentialBootstrap` envelope owned by 10001:10001, and a
2721
+ same-image one-shot container merges `sabnzbdApiKey` into
2722
+ `runtime/machines/sanctuary/config`; the key never appears in argv, the
2723
+ environment, logs, the Unraid template, or the Butler mounts. The bootstrap
2724
+ reconciler is idempotent for the same value and fails closed on a conflict.
2725
+ `verify_sanctuary_sab_readiness "$IMAGE_ID"` then reloads that machine item
2726
+ from the vault and performs a real bounded queue read before any poller
2727
+ cutover. The runtime and agent roots are persistent binds and package-managed
2728
+ updates do not replace the machine vault item, so the credential survives
2729
+ template and image updates.
2730
+ Bootstrap is not the rotation path. After SAB rotates its key, use the
2731
+ existing hidden-prompt merge command
2732
+ `ouro vault config set --agent sanctuary --key sabnzbdApiKey --scope machine`,
2733
+ restart the reviewed Butler container so its machine-config cache refreshes,
2734
+ and rerun `verify_sanctuary_sab_readiness "$IMAGE_ID"`; a conflicting
2735
+ bootstrap is expected to stop rather than overwrite canonical vault state.
2736
+ Never print or place credential values in logs, templates, command arguments,
2737
+ backups, or this runbook.
2738
+
2739
+ Packaged deployment-target containment gates:
2740
+ Unit 16 is fixed to the `staging` profile and therefore targets only
2741
+ `ouro-butler-staging`; it does not require `ouro-butler` to exist. Before the
2742
+ broker starts, the packaged deployment auditor captures all present canonical
2743
+ production/staging/rollback identities in one Docker inspect, verifies the
2744
+ target image, `unless-stopped`, host networking, matching GraphQL and durable
2745
+ file autostart identity/state for every present canonical container,
2746
+ and exactly one running Butler, then repeats the canonical snapshot to reject
2747
+ races. It binds the target PID and exact Docker cgroup-v2 path to the inspected
2748
+ container ID; Unit 16 carries that immutable ID into every launcher and broker
2749
+ Docker operation and binds it to the GraphQL PrefixedID suffix. It scans every
2750
+ cgroup process and requires stable before/after process, owned-socket, and
2751
+ listener inventories. Between the two canonical topology captures, it verifies
2752
+ the exact immutable-ID target is running and unpaused, pauses that ID without
2753
+ changing restart or autostart state, and performs every cgroup, all-thread
2754
+ descriptor, TCP, UDP, and Unix observation inside that one quiesced window,
2755
+ including two matching complete terminal snapshots; nonconvergence fails
2756
+ closed after eight attempts. It always makes bounded exact-ID unpause attempts,
2757
+ verifies the same ID and PID resumed their original running, unpaused state,
2758
+ and only then performs the final full-profile topology capture. It
2759
+ rejects every owned UDP listener and every externally reachable owned TCP listener.
2760
+ Only loopback Mailbox port 6876 plus stream-listening endpoints at /tmp/ouroboros-daemon.sock, /tmp/ouroboros-daemon.sock.frontend, and /home/ouro/AgentBundles/sanctuary.ouro/state/acceptance/telegram-control.sock are permitted; all other named Unix endpoint types (including datagrams) fail closed.
2761
+ Inherited descriptors for the same socket inode are deduplicated, while unknown loopback ports, wildcard/host-address listeners, process/socket/listener drift, or ambiguous ownership fail closed.
2762
+ Unit 18 uses the separately packaged fixed final command after activation.
2763
+ It accepts either the legacy-adoption topology with no canonical rollback or
2764
+ exactly one stopped, non-autostarted rollback; running/autostarted rollback,
2765
+ staging presence, and ambiguous canonical identities always fail closed:
2766
+ UNIT18_TARGET_TMP=$(mktemp /run/sanctuary-unit18-target-audit.sh.XXXXXX)
2767
+ /usr/bin/timeout -s KILL 20 /usr/bin/docker run --rm --pull=never --network none \
2768
+ --entrypoint /bin/cat "$IMAGE_ID" /opt/ouro/deploy/unraid/sanctuary-unit18-target-audit.sh >"$UNIT18_TARGET_TMP"
2769
+ chmod 0500 "$UNIT18_TARGET_TMP"
2770
+ "$UNIT18_TARGET_TMP" "$IMAGE_ID"
2771
+ rm -f -- "$UNIT18_TARGET_TMP"
2772
+ Neither packaged command accepts a container name or an open-ended profile.
2773
+
2774
+ Packaged Unit 16 acceptance execution:
2775
+ Use only the launcher packaged in the exact reviewed image. Install it without
2776
+ network access, then create the two private roots with the runtime UID/GID:
2777
+ UNIT16_ROOT=/mnt/user/appdata/ouro-butler/acceptance
2778
+ install -d -m 0700 -o 10001 -g 10001 "$UNIT16_ROOT/configs" "$UNIT16_ROOT/evidence"
2779
+ UNIT16_LAUNCHER_TMP=$(mktemp "$UNIT16_ROOT/sanctuary-unit16-run.sh.tmp.XXXXXX")
2780
+ /usr/bin/timeout -s KILL 20 /usr/bin/docker run --rm --pull=never --network none \
2781
+ --entrypoint /bin/cat "$IMAGE_ID" /opt/ouro/deploy/unraid/sanctuary-unit16-run.sh >"$UNIT16_LAUNCHER_TMP"
2782
+ install -m 0755 -o root -g root "$UNIT16_LAUNCHER_TMP" "$UNIT16_ROOT/sanctuary-unit16-run.sh"
2783
+ rm -f -- "$UNIT16_LAUNCHER_TMP"
2784
+ After final activation, create the disjoint final-profile roots and invoke the
2785
+ same immutable launcher with its only non-staging selector. The selector is a
2786
+ closed `staging|final` enum; it never accepts a container name, ID, or path:
2787
+ UNIT18_ROOT=/mnt/user/appdata/ouro-butler/acceptance/final
2788
+ install -d -m 0700 -o 10001 -g 10001 "$UNIT18_ROOT/configs" "$UNIT18_ROOT/evidence"
2789
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final materialize evidence-snapshot
2790
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final evidence-snapshot evidence-snapshot.json
2791
+ Use `--profile final` on every final pre-reboot and post-reboot materialize/run
2792
+ command. Omitting it remains the byte-for-byte Unit 16 staging path. Never mix
2793
+ staging and final config/evidence roots or reuse a config across profiles.
2794
+ Never hand-author a Unit 16 config. Materialize it from the exact image, then
2795
+ execute it in the order below. Before every execution the launcher regenerates
2796
+ the config from the packaged fixed contract and requires byte-for-byte equality.
2797
+ Unit 16d-2 stops at the pre-model quarantine boundary: use a genuinely distinct private Telegram sender, confirm the fixed acknowledgement and owner admission card, and do not approve the contact during this scenario. The production-identical allow-to-one-turn continuation is covered by the Telegram admission integration suite when a second live account is unavailable. Unit 16h is acceptance-only: it exercises the delivery path against isolated state, restores exact health and cron bytes, and does not activate a production daily digest.
2798
+ The cursor snapshot is deliberately materialized and executed twice around the live scenario. Every telegram-offset proof uses the fresh signed telegram.cursor.snapshot logical progress digest, excluding snapshot time/signature rather than hashing a fixed resident offset file. Stale, absent or frozen resident offsets cannot satisfy cursor evidence. Telegram bootstrap confirms the already pinned root owner through gateway poll/settle; it performs no token acquisition, vault credential write or direct getUpdates. Its one-shot has network=none and a readonly runtime mount. Callback injection alone maps reviewed saved callback-update JSON from host fd 3 through Docker stdin to in-container fd 3.
2799
+ Allow the 90-second config materializer budget and the existing 65-second gateway socket wait; do not replace timeout failure with resident token readiness. Unit16b is explicitly retired as a production containment assertion and remains runtime-vault-readiness. Unit16e is the exact five-mount production snapshot with readOnlyRoot=false; mountsExact remains strict.
2800
+ Stage the reviewed callback JSON at the fixed path below in the root-owned
2801
+ tmpfs inbox, then use this single fail-closed helper. It opens the input once,
2802
+ validates the opened descriptor and its original path refer to the same
2803
+ root-owned mode-0600 regular file, and invokes the launcher only afterward.
2804
+ Success overwrites, fsyncs, and unlinks the raw input. Any failure allocates a
2805
+ collision-free quarantine file atomically, copies and fsyncs the input into it,
2806
+ locks it to mode 000, then overwrites and removes the tmpfs source;
2807
+ no raw callback update remains loose in `/root` or the inbox.
2808
+ UNIT16_CALLBACK_INBOX=/run/ouro-unit16-callback-input
2809
+ UNIT16_CALLBACK_FILE=$UNIT16_CALLBACK_INBOX/callback-update.json
2810
+ UNIT16_CALLBACK_QUARANTINE_ROOT=$UNIT16_ROOT/callback-quarantine
2811
+ install -d -m 0700 -o root -g root "$UNIT16_CALLBACK_INBOX" "$UNIT16_CALLBACK_QUARANTINE_ROOT"
2812
+ run_unit16_callback_inject() {
2813
+ (
2814
+ UNIT16_CALLBACK_VALIDATED=no
2815
+ UNIT16_CALLBACK_STATUS=1
2816
+ unit16_callback_cleanup() {
2817
+ UNIT16_CALLBACK_STATUS=$?
2818
+ trap - EXIT HUP INT TERM
2819
+ if test -e "$UNIT16_CALLBACK_FILE" || test -L "$UNIT16_CALLBACK_FILE"; then
2820
+ if test "$UNIT16_CALLBACK_STATUS" -eq 0 && test "$UNIT16_CALLBACK_VALIDATED" = yes; then
2821
+ if ! truncate -s 0 /proc/self/fd/3 || ! sync -f /proc/self/fd/3 \
2822
+ || ! rm -f -- "$UNIT16_CALLBACK_FILE" || ! sync -f "$UNIT16_CALLBACK_INBOX"; then
2823
+ UNIT16_CALLBACK_STATUS=1
2824
+ fi
2825
+ elif test -f "$UNIT16_CALLBACK_FILE" && test ! -L "$UNIT16_CALLBACK_FILE"; then
2826
+ UNIT16_CALLBACK_QUARANTINE_FILE=$(mktemp "$UNIT16_CALLBACK_QUARANTINE_ROOT/failed.XXXXXX") || UNIT16_CALLBACK_QUARANTINE_FILE=
2827
+ if test -n "$UNIT16_CALLBACK_QUARANTINE_FILE" \
2828
+ && chmod 0600 "$UNIT16_CALLBACK_QUARANTINE_FILE" \
2829
+ && cp -- "$UNIT16_CALLBACK_FILE" "$UNIT16_CALLBACK_QUARANTINE_FILE" \
2830
+ && sync -f "$UNIT16_CALLBACK_QUARANTINE_FILE" \
2831
+ && chmod 000 "$UNIT16_CALLBACK_QUARANTINE_FILE" \
2832
+ && sync -f "$UNIT16_CALLBACK_QUARANTINE_ROOT"; then
2833
+ :
2834
+ else
2835
+ test -z "${UNIT16_CALLBACK_QUARANTINE_FILE-}" || rm -f -- "$UNIT16_CALLBACK_QUARANTINE_FILE"
2836
+ UNIT16_CALLBACK_STATUS=1
2837
+ fi
2838
+ if ! truncate -s 0 "$UNIT16_CALLBACK_FILE" || ! sync -f "$UNIT16_CALLBACK_FILE" \
2839
+ || ! rm -f -- "$UNIT16_CALLBACK_FILE" || ! sync -f "$UNIT16_CALLBACK_INBOX"; then
2840
+ UNIT16_CALLBACK_STATUS=1
2841
+ fi
2842
+ else
2843
+ rm -f -- "$UNIT16_CALLBACK_FILE" || UNIT16_CALLBACK_STATUS=1
2844
+ sync -f "$UNIT16_CALLBACK_INBOX" || UNIT16_CALLBACK_STATUS=1
2845
+ fi
2846
+ fi
2847
+ exec 3<&-
2848
+ exit "$UNIT16_CALLBACK_STATUS"
2849
+ }
2850
+ trap unit16_callback_cleanup EXIT
2851
+ trap 'exit 129' HUP
2852
+ trap 'exit 130' INT
2853
+ trap 'exit 143' TERM
2854
+ test -d "$UNIT16_CALLBACK_INBOX" && test ! -L "$UNIT16_CALLBACK_INBOX" || exit 1
2855
+ test "$(stat -c '%F %u:%g %a' "$UNIT16_CALLBACK_INBOX")" = "directory 0:0 700" || exit 1
2856
+ test -d "$UNIT16_CALLBACK_QUARANTINE_ROOT" && test ! -L "$UNIT16_CALLBACK_QUARANTINE_ROOT" || exit 1
2857
+ test "$(stat -c '%F %u:%g %a' "$UNIT16_CALLBACK_QUARANTINE_ROOT")" = "directory 0:0 700" || exit 1
2858
+ test -f "$UNIT16_CALLBACK_FILE" && test ! -L "$UNIT16_CALLBACK_FILE" || exit 1
2859
+ exec 3<"$UNIT16_CALLBACK_FILE"
2860
+ test "$(stat -Lc '%F' /proc/self/fd/3)" = "regular file" || exit 1
2861
+ test "$(stat -c '%d:%i' "$UNIT16_CALLBACK_FILE")" = "$(stat -Lc '%d:%i' /proc/self/fd/3)" || exit 1
2862
+ UNIT16_CALLBACK_VALIDATED=yes
2863
+ test "$(stat -Lc '%F %u:%g %a' /proc/self/fd/3)" = "regular file 0:0 600" || exit 1
2864
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final callback-inject callback-inject.json 3<&3
2865
+ )
2866
+ }
2867
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final materialize telegram-bootstrap
2868
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final telegram-bootstrap telegram-bootstrap.json
2869
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final materialize cursor-snapshot before
2870
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final cursor-snapshot cursor-snapshot.json
2871
+ # Perform the live scenario whose cursor movement is being measured.
2872
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final materialize cursor-snapshot after
2873
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final cursor-snapshot cursor-snapshot.json
2874
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final materialize cursor-delta
2875
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final cursor-delta cursor-delta.json
2876
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final materialize callback-inject
2877
+ run_unit16_callback_inject
2878
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final materialize unraid-key-rotate
2879
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final unraid-key-rotate unraid-key-rotate.json
2880
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final materialize reboot-request
2881
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final reboot-request reboot-request.json
2882
+ # The preceding command captures and seals preflight evidence before it asks
2883
+ # the broker to stage the reboot, then seals the requested-phase evidence and
2884
+ # fsyncs the requested checkpoint before invoking the host reboot. Reconnect
2885
+ # only after Unraid and Docker are ready.
2886
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final materialize reboot-resume
2887
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final reboot-resume reboot-resume.json
2888
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final materialize evidence-snapshot
2889
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final evidence-snapshot evidence-snapshot.json
2890
+ # reboot-resume seals the changed boot identity and recovery milestones.
2891
+ # evidence-snapshot then runs the remaining scenarios sequentially with a
2892
+ # 72-minute aggregate bound; each completed scenario records provenance at
2893
+ # capture time and always clears its public gate, private marker, and receipt.
2894
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final materialize evidence-bundle-index
2895
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final evidence-bundle-index evidence-bundle-index.json
2896
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final materialize evidence-bundle-verify
2897
+ "$UNIT16_ROOT/sanctuary-unit16-run.sh" "$IMAGE_ID" --profile final evidence-bundle-verify evidence-bundle-verify.json
2898
+ Each execution revalidates the immutable image and the production container's
2899
+ exact image ID. The main one-shot gets a read-only root filesystem, one writable
2900
+ evidence mount, narrowly selected runtime/bundle modes, and individual read-only
2901
+ image/container/health/boot fact files. Host-only operations cross an ephemeral
2902
+ root-owned private Unix socket (root:10001 mode 0660) to a root broker extracted
2903
+ from the same exact image. The broker accepts only fixed Unraid inventory/create/
2904
+ exact-revoke/rejection operations, exact fixed-target snapshots, and a
2905
+ two-phase reboot reservation/final commit. Reservation drains queued owner
2906
+ mutations and rejects new ones; after the requested checkpoint is fsynced, the
2907
+ broker repeats the array/parity/mover/durable-health preflight and invokes the
2908
+ fixed host reboot itself exactly once. The Unit 16 broker inspects only the
2909
+ deployment profile's attested immutable container ID (staging is
2910
+ `ouro-butler-staging`), requires its immutable image ID, writes that exact typed/redacted
2911
+ snapshot before accepting requests, and exposes a nonnegative Docker restart
2912
+ count. Both initial and refreshed snapshots share the same exact schema. The
2913
+ broker derives `autostartExact` from both the Unraid GraphQL `autoStart` value
2914
+ and exactly one staging entry in `/var/lib/docker/unraid-autostart`, derives
2915
+ `updaterDisabled` from `/opt/ouro/container-runtime.json` inside the exact image,
2916
+ and derives `vaultUnlocked`/`manualAuthRequired` from a bounded live Sanctuary
2917
+ vault-status command only when its non-secret summary proves the required
2918
+ Telegram runtime fields and both configured provider records were freshly read.
2919
+ Scenario handles remain private to the scenario adapter. The main one-shot
2920
+ never receives the Docker socket, Unraid key directory, or a host-root mount.
2921
+ Telegram bootstrap brackets its one-shot with a host-controlled quiescence guard: it verifies the exact healthy profile-selected resident, assumes recovery responsibility before stopping it with a 30-second grace bound, and proves it is stopped while one live root gateway owns polling. The broker proves the exact root lock/command/start identity and revoked predecessor token epoch; it does not accept a zero-poller file or a resident offset as authority. Every separately launched gateway consumer mounts only /run/ouro-authority readonly. The exit/signal trap restarts the same resident and waits up to 120 seconds for healthy recovery on success or failure without changing Unraid autostart. Every command receives a fresh redacted typed container snapshot, never raw environment or credential values.
2922
+ Callback injection requires two stable zero observations from a durable callback playback journal under
2923
+ `state/approvals`; the journal is keyed only by the full callback-coordinate
2924
+ digest and stores no raw update, callback data, user, chat, message, or query ID.
2925
+ Evidence-snapshot keeps the bundle mount read-only and overlays only the exact
2926
+ canonical `state/acceptance` directory as writable. It first stops the exact
2927
+ healthy staging container under recovery responsibility, then opens the
2928
+ directory with `O_DIRECTORY|O_NOFOLLOW` and bind-mounts from the inherited fd
2929
+ while no Sanctuary UID process is running. The launcher bind-pins that inode
2930
+ behind a root-only alias and back onto the canonical path against rename swaps,
2931
+ restarts the same exact image healthy, and compares the alias, canonical path,
2932
+ and staging container's inode before and after capture. Cleanup unmounts the
2933
+ canonical pin and then the alias. The staging daemon therefore sees the same
2934
+ inode used by the one-shot for marker correlation.
2935
+
2936
+ Audit and safety verification:
2937
+ Inspect AgentBundles/sanctuary.ouro/state/approvals for durable approval and restart-attempt receipts. Confirm with docker inspect that the container has no Docker socket, device, host-root mount, or published port. Confirm `Config.Image` equals the canonical package-version tag and `.Image` equals the exact reviewed local image ID. The read key must reject Docker stop and restart mutations; only the separate write key may perform the one typed approved restart action.
2938
+ The packaged `unraid-key-rotate` command is the only canonical key-rotation
2939
+ authority. Its host launcher stops the exact production container and assumes
2940
+ trap-backed recovery responsibility before key mutation. It inventories the
2941
+ two occupied canonical names by exact immutable ID, creates collision-safe
2942
+ `Butler RO Rotation <suffix>` and
2943
+ `Butler RW Rotation <suffix>` keys, stores and capability-probes both through
2944
+ the Sanctuary machine vault, and on the uninterrupted path requires an exact
2945
+ four-key inventory. Because
2946
+ Unraid 7.2.3 cannot create a role-free key through its CLI, the root broker
2947
+ creates each key as provisional `GUEST` with the intended scope plus only
2948
+ `API_KEY:UPDATE_ANY`, then immediately uses that in-memory credential to
2949
+ self-downgrade the same immutable ID to no roles and the exact intended scope.
2950
+ Disk and live-auth proofs must pass before the credential may reach the vault.
2951
+ The provisional credential never reaches argv, logs, evidence, the bundle, or
2952
+ the model. It then
2953
+ revokes both old IDs and proves each old credential receives a 401 or 403.
2954
+ Only after an exact inventory contains the temporary pair alone does it create,
2955
+ store, and probe the canonical `Butler RO` and `Butler RW` pair. It requires an
2956
+ exact four-key temporary-plus-canonical inventory on the uninterrupted path,
2957
+ revokes and rejection-probes
2958
+ both temporary IDs, and finally requires exactly the canonical pair. Every
2959
+ unexpected key, duplicate, malformed permission set, role, name, inventory
2960
+ delta, or probe response fails closed. A resumed path may observe fewer keys
2961
+ only when the transaction checkpoint plus a durable rejection receipt proves
2962
+ that the missing immutable ID was already revoked; it never treats absence
2963
+ alone as success.
2964
+
2965
+ A failed invocation resumes from the durable redacted transaction checkpoint
2966
+ instead of reminting known keys. The checkpoint binds every created immutable
2967
+ ID to its name, scope, vault field, temporary/canonical class, and attestation
2968
+ state. Recovery reconciles exact live inventory and rejection proofs, skips
2969
+ already-attested vault writes after canonical fields advance, and never
2970
+ recreates a temporary key already known revoked. Root-owned recovery ownership
2971
+ survives broker response loss and is cleared only after the harness has
2972
+ checkpointed the immutable ID and the vault has read back the exact binding.
2973
+
2974
+ Record only IDs, names, and permission sets in evidence; never raw key values.
2975
+ Raw credentials must not appear in argv, shell history, stdout, logs, or
2976
+ acceptance evidence. They may cross only the ephemeral private Unit 16 Unix
2977
+ socket in process memory. The narrow revocation-retry recovery records under
2978
+ `/mnt/user/appdata/ouro-butler/acceptance/revoked-key-proof` are the sole file
2979
+ exception: they are root-owned mode 0600 beneath a root-owned mode 0700
2980
+ directory, excluded from backup/evidence, and readable only by the root broker.
2981
+ Recovery state is retained across failed retries.
2982
+ Creation intent is fsynced before the CLI side effect so an exact provisional
2983
+ key can be adopted after process death. Raw recovery proof is durably deleted
2984
+ only after the exact authentication rejection and its redacted replayable
2985
+ receipt are fsynced. Never substitute names for IDs when revoking keys.
2986
+
2987
+ Shipping a Butler release (one command)
2988
+
2989
+ From the Mac, after the release PR has merged to main:
2990
+
2991
+ npm run butler:ship -- <version> [--host sanctuary] [--no-gate] [--plant <case>] [--dry-run]
2992
+
2993
+ It resolves the release merge commit, waits for that commit's coverage-gate and for the GHCR image to resolve on the host, backs up the host's /tmp/butler-upgrade.mjs and /tmp/sanctuary-replay-gate.mjs to .bak-<previous>, stages the release's own copies, runs preflight, starts the gated upgrade detached with its log at /var/log/ouro-upgrade-<version>.log, follows the case lines to a terminal line and runs verify. The last stdout line is one JSON result: {version, result: kept|rolled_back|refused|failed, running_image, cases, verify, log}. Exit 0 only when the result is kept and verify is green. --dry-run runs only the read-only steps. BUTLER_HOST overrides the default host alias.
2994
+
2995
+ Manual fallback (the script automates exactly these): wait for coverage-gate and `docker manifest inspect ghcr.io/ourostack/ouroboros-butler:<version>` on the host; copy deploy/unraid/sanctuary-butler-upgrade.mjs to /tmp/butler-upgrade.mjs and deploy/unraid/sanctuary-replay-gate.mjs to /tmp/sanctuary-replay-gate.mjs; run `node /tmp/butler-upgrade.mjs preflight <version>`; start `setsid nohup /usr/local/bin/node /tmp/butler-upgrade.mjs upgrade <version> > /var/log/ouro-upgrade-<version>.log 2>&1 < /dev/null &`; read the log for GATE PASS, GATE FAIL (rolled back), UPGRADE done, REFUSING or FAILED; then run `node /tmp/butler-upgrade.mjs verify`. Check for a live upgrade with pgrep -f "[b]utler-upgrade.mjs upgrade" so the check does not match its own shell.