@ouro.bot/cli 0.1.0-alpha.83 → 0.1.0-alpha.831

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