@ouro.bot/cli 0.1.0-alpha.172 → 0.1.0-alpha.1721

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 (1720) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +158 -44
  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 +1 -0
  11. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +1 -1
  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 +10031 -64
  16. package/deploy/unraid/Dockerfile +87 -0
  17. package/deploy/unraid/INSTALL.md +64 -0
  18. package/deploy/unraid/README.txt +3036 -0
  19. package/deploy/unraid/audit-container-spec.sh +4 -0
  20. package/deploy/unraid/container-runtime.json +1 -0
  21. package/deploy/unraid/credit-gateway.md +95 -0
  22. package/deploy/unraid/docker-man-template-transaction.mjs +733 -0
  23. package/deploy/unraid/docker-man-template-xml.cjs +105 -0
  24. package/deploy/unraid/github_known_hosts +3 -0
  25. package/deploy/unraid/install.sh +281 -0
  26. package/deploy/unraid/migrate-sanctuary-bundle.mjs +68 -0
  27. package/deploy/unraid/ouro-events/bootstrap-spool.sh +92 -0
  28. package/deploy/unraid/ouro-events/emit-event.mjs +310 -0
  29. package/deploy/unraid/ouro-events/emit-usenet-event.sh +54 -0
  30. package/deploy/unraid/ouro-events/install-usenet-guard.sh +435 -0
  31. package/deploy/unraid/ouro-events/usenet-health.sh +176 -0
  32. package/deploy/unraid/ouro-host-lock.mjs +245 -0
  33. package/deploy/unraid/ouro-sync-ssh +98 -0
  34. package/deploy/unraid/ouro-sync.sudoers +3 -0
  35. package/deploy/unraid/sanctuary-acceptance-adapter.sh +43 -0
  36. package/deploy/unraid/sanctuary-acceptance-contract.json +198 -0
  37. package/deploy/unraid/sanctuary-acceptance-harness.sh +23 -0
  38. package/deploy/unraid/sanctuary-authority-installation.json +36 -0
  39. package/deploy/unraid/sanctuary-authority-service.sh +30 -0
  40. package/deploy/unraid/sanctuary-butler-upgrade.mjs +1820 -0
  41. package/deploy/unraid/sanctuary-deployment-target.mjs +711 -0
  42. package/deploy/unraid/sanctuary-replay-gate.mjs +2824 -0
  43. package/deploy/unraid/sanctuary-safe-rename.py +24 -0
  44. package/deploy/unraid/sanctuary-sync-cutover.sh +1057 -0
  45. package/deploy/unraid/sanctuary-unit16-host-broker.mjs +2107 -0
  46. package/deploy/unraid/sanctuary-unit16-run.sh +575 -0
  47. package/deploy/unraid/sanctuary-unit18-target-audit.sh +27 -0
  48. package/deploy/unraid/sanctuary.ouro/agent.json +72 -0
  49. package/deploy/unraid/sanctuary.ouro/arc/README.md +3 -0
  50. package/deploy/unraid/sanctuary.ouro/awaiting/house-care-sweep.md +17 -0
  51. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +5 -0
  52. package/deploy/unraid/sanctuary.ouro/habits/sanctuary-health.md +8 -0
  53. package/deploy/unraid/sanctuary.ouro/mcp/media-mcp.mjs +2546 -0
  54. package/deploy/unraid/sanctuary.ouro/product/PRODUCT.md +13 -0
  55. package/deploy/unraid/sanctuary.ouro/provider-readiness.json +11 -0
  56. package/deploy/unraid/sanctuary.ouro/psyche/ASPIRATIONS.md +5 -0
  57. package/deploy/unraid/sanctuary.ouro/psyche/IDENTITY.md +7 -0
  58. package/deploy/unraid/sanctuary.ouro/psyche/LORE.md +7 -0
  59. package/deploy/unraid/sanctuary.ouro/psyche/SOUL.md +15 -0
  60. package/deploy/unraid/sanctuary.ouro/psyche/TACIT.md +3 -0
  61. package/deploy/unraid/sanctuary.ouro/state/policy/steward.json +7 -0
  62. package/deploy/unraid/sanctuary.ouro/tool-profiles.json +274 -0
  63. package/deploy/unraid/sanctuary.xml +30 -0
  64. package/desk.lock.json +8 -0
  65. package/dist/a2a/approval-relay-forward.js +117 -0
  66. package/dist/a2a/approval-relay.js +95 -0
  67. package/dist/a2a/approval-request-wire.js +123 -0
  68. package/dist/a2a/card.js +57 -0
  69. package/dist/a2a/client.js +331 -0
  70. package/dist/a2a/config.js +54 -0
  71. package/dist/a2a/delegated-command-grants.js +93 -0
  72. package/dist/a2a/delegated-command.js +200 -0
  73. package/dist/a2a/delegation-stores.js +56 -0
  74. package/dist/a2a/did-resolution.js +205 -0
  75. package/dist/a2a/escalation-grants.js +84 -0
  76. package/dist/a2a/escalation-wiring.js +81 -0
  77. package/dist/a2a/identity.js +258 -0
  78. package/dist/a2a/inbound-share.js +131 -0
  79. package/dist/a2a/mission-result-wire.js +265 -0
  80. package/dist/a2a/onboarding.js +133 -0
  81. package/dist/a2a/operator-trust.js +399 -0
  82. package/dist/a2a/outbox-client.js +59 -0
  83. package/dist/a2a/outbox-store.js +245 -0
  84. package/dist/a2a/outbox-wire.js +106 -0
  85. package/dist/a2a/pin-store.js +167 -0
  86. package/dist/a2a/refusals.js +55 -0
  87. package/dist/a2a/relay-client.js +106 -0
  88. package/dist/a2a/relay-config-vault.js +64 -0
  89. package/dist/a2a/relay-contacts.js +120 -0
  90. package/dist/a2a/relay-inbox.js +360 -0
  91. package/dist/a2a/relay-retirements.js +89 -0
  92. package/dist/a2a/replay-grant-holders.js +33 -0
  93. package/dist/a2a/replay-harness.js +188 -0
  94. package/dist/a2a/resolution-proof.js +53 -0
  95. package/dist/a2a/sealed-chat.js +142 -0
  96. package/dist/a2a/seen-ledger.js +216 -0
  97. package/dist/a2a/server.js +1089 -0
  98. package/dist/a2a/task-store.js +69 -0
  99. package/dist/a2a/transport.js +100 -0
  100. package/dist/a2a/trust-commands.js +203 -0
  101. package/dist/a2a/trusted-files.js +185 -0
  102. package/dist/a2a/types.js +3 -0
  103. package/dist/actions/generated/mailbox/actions.json +639 -0
  104. package/dist/actions/generated/mailbox/commands.json +181 -0
  105. package/dist/actions/generated/mailbox/mcp.json +469 -0
  106. package/dist/actions/generated/mailbox-tools/tools.json +547 -0
  107. package/dist/arc/attention-types.js +8 -0
  108. package/dist/arc/cares.js +360 -0
  109. package/dist/arc/episodes.js +118 -0
  110. package/dist/arc/evolution.js +490 -0
  111. package/dist/arc/flight-recorder.js +1009 -0
  112. package/dist/arc/intentions.js +134 -0
  113. package/dist/arc/json-store.js +117 -0
  114. package/dist/arc/obligations.js +386 -0
  115. package/dist/arc/packets.js +336 -0
  116. package/dist/arc/presence.js +185 -0
  117. package/dist/arc/task-lifecycle.js +57 -0
  118. package/dist/commerce/store.js +755 -0
  119. package/dist/commerce/types.js +3 -0
  120. package/dist/eval/assertions/index.js +378 -0
  121. package/dist/eval/billing-guard.js +23 -0
  122. package/dist/eval/budget.js +170 -0
  123. package/dist/eval/domain/case.js +115 -0
  124. package/dist/eval/domain/stats.js +19 -0
  125. package/dist/eval/guest-entry.js +18 -0
  126. package/dist/eval/h-guest-entry.js +19 -0
  127. package/dist/eval/interview-entry.js +174 -0
  128. package/dist/eval/interview-grade-entry.js +36 -0
  129. package/dist/eval/interview-guest-entry.js +19 -0
  130. package/dist/eval/interviews/allocation.js +92 -0
  131. package/dist/eval/interviews/final.js +133 -0
  132. package/dist/eval/interviews/grader.js +209 -0
  133. package/dist/eval/interviews/guest/arms.js +173 -0
  134. package/dist/eval/interviews/guest/ax/ax-command.js +792 -0
  135. package/dist/eval/interviews/guest/ax/effects.js +51 -0
  136. package/dist/eval/interviews/guest/ax/exit-codes.js +51 -0
  137. package/dist/eval/interviews/guest/ax/help.js +181 -0
  138. package/dist/eval/interviews/guest/ax/mcp.js +246 -0
  139. package/dist/eval/interviews/guest/ax/outcome.js +211 -0
  140. package/dist/eval/interviews/guest/ax/output.js +53 -0
  141. package/dist/eval/interviews/guest/ax/precise-copy.js +200 -0
  142. package/dist/eval/interviews/guest/ax/problem.js +95 -0
  143. package/dist/eval/interviews/guest/ax/voice.js +83 -0
  144. package/dist/eval/interviews/guest/ax/wait.js +158 -0
  145. package/dist/eval/interviews/guest/books-core.js +54 -0
  146. package/dist/eval/interviews/guest/cli-shell.js +267 -0
  147. package/dist/eval/interviews/guest/h/codex.js +201 -0
  148. package/dist/eval/interviews/guest/h/fidelity.js +59 -0
  149. package/dist/eval/interviews/guest/h/openhands.js +176 -0
  150. package/dist/eval/interviews/guest/h/run.js +99 -0
  151. package/dist/eval/interviews/guest/h/wire.js +403 -0
  152. package/dist/eval/interviews/guest/loop.js +87 -0
  153. package/dist/eval/interviews/guest/operations.js +108 -0
  154. package/dist/eval/interviews/guest/run.js +81 -0
  155. package/dist/eval/interviews/guest/u/arms.js +268 -0
  156. package/dist/eval/interviews/h/kit.js +119 -0
  157. package/dist/eval/interviews/latch.js +161 -0
  158. package/dist/eval/interviews/protocol.js +127 -0
  159. package/dist/eval/interviews/rewrite.js +57 -0
  160. package/dist/eval/interviews/runner.js +365 -0
  161. package/dist/eval/interviews/u/kit.js +121 -0
  162. package/dist/eval/kill-switch.js +33 -0
  163. package/dist/eval/month-ledger.js +95 -0
  164. package/dist/eval/readback/hedges.js +39 -0
  165. package/dist/eval/remote-entry.js +32 -0
  166. package/dist/eval/report.js +85 -0
  167. package/dist/eval/run-command.js +188 -0
  168. package/dist/eval/run-entry.js +93 -0
  169. package/dist/eval/sandbox/agent-profile.js +74 -0
  170. package/dist/eval/sandbox/declared-gaps.js +17 -0
  171. package/dist/eval/sandbox/docker.js +390 -0
  172. package/dist/eval/sandbox/guest.js +55 -0
  173. package/dist/eval/sandbox/host-lock.js +62 -0
  174. package/dist/eval/sandbox/images.js +39 -0
  175. package/dist/eval/sandbox/neutral-bundle.js +117 -0
  176. package/dist/eval/sandbox/oracle.js +32 -0
  177. package/dist/eval/sandbox/projection.js +127 -0
  178. package/dist/eval/sandbox/readback.js +137 -0
  179. package/dist/eval/sandbox/remote.js +102 -0
  180. package/dist/eval/sandbox/slugger-projection.js +377 -0
  181. package/dist/eval/self-test.js +84 -0
  182. package/dist/eval/stop-command.js +71 -0
  183. package/dist/eval/stop-entry.js +46 -0
  184. package/dist/eval/targets/index.js +127 -0
  185. package/dist/eval/transport/provider-proxy.js +262 -0
  186. package/dist/eval/transport/synthetic-sanctuary.js +117 -0
  187. package/dist/eval/transport/telegram-turn.js +241 -0
  188. package/dist/eval/watch/cli.js +63 -0
  189. package/dist/eval/watch/guarded-fs.js +254 -0
  190. package/dist/eval/watch/log-reader.js +99 -0
  191. package/dist/eval/watch/rows.js +143 -0
  192. package/dist/eval/watch/run-watch.js +160 -0
  193. package/dist/eval/watch-entry.js +26 -0
  194. package/dist/gateway/keys.js +117 -0
  195. package/dist/gateway/server.js +429 -0
  196. package/dist/heart/active-work.js +423 -45
  197. package/dist/heart/agent-entry.js +255 -4
  198. package/dist/heart/approval-files.js +94 -0
  199. package/dist/heart/approval-store.js +1000 -0
  200. package/dist/heart/atomic-file.js +115 -0
  201. package/dist/heart/attachments/downloaded-store.js +89 -0
  202. package/dist/heart/attachments/image-normalize.js +201 -0
  203. package/dist/heart/attachments/materialize.js +97 -0
  204. package/dist/heart/attachments/originals.js +102 -0
  205. package/dist/heart/attachments/render.js +29 -0
  206. package/dist/heart/attachments/sources/bluebubbles.js +155 -0
  207. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  208. package/dist/heart/attachments/sources/downloaded.js +76 -0
  209. package/dist/heart/attachments/sources/index.js +19 -0
  210. package/dist/heart/attachments/store.js +132 -0
  211. package/dist/heart/attachments/transcribe-audio.js +231 -0
  212. package/dist/heart/attachments/types.js +93 -0
  213. package/dist/heart/attachments/understand.js +195 -0
  214. package/dist/heart/auth/auth-flow.js +589 -0
  215. package/dist/heart/auth/github-device-login.js +104 -0
  216. package/dist/heart/autonomy-budget.js +426 -0
  217. package/dist/heart/awaiting/a2a-await-delivery.js +109 -0
  218. package/dist/heart/awaiting/await-alert.js +152 -0
  219. package/dist/heart/awaiting/await-expiry.js +143 -0
  220. package/dist/heart/awaiting/await-loader.js +91 -0
  221. package/dist/heart/awaiting/await-parser.js +152 -0
  222. package/dist/heart/awaiting/await-runtime-state.js +130 -0
  223. package/dist/heart/awaiting/await-scheduler.js +462 -0
  224. package/dist/heart/background-operations.js +281 -0
  225. package/dist/heart/bluebubbles-host-account.js +78 -0
  226. package/dist/heart/bridges/manager.js +137 -17
  227. package/dist/heart/bridges/store.js +14 -2
  228. package/dist/heart/bundle-state.js +168 -0
  229. package/dist/heart/butler-agent.js +54 -0
  230. package/dist/heart/chat-interaction.js +69 -0
  231. package/dist/heart/commitments.js +44 -14
  232. package/dist/heart/config-registry.js +340 -0
  233. package/dist/heart/config.js +193 -137
  234. package/dist/heart/context-loss-gauntlet.js +387 -0
  235. package/dist/heart/context-loss-sentinel.js +1260 -0
  236. package/dist/heart/core.js +2824 -697
  237. package/dist/heart/cross-chat-delivery.js +29 -22
  238. package/dist/heart/daemon/agent-config-check.js +494 -0
  239. package/dist/heart/daemon/agent-discovery.js +304 -3
  240. package/dist/heart/daemon/agent-home.js +409 -0
  241. package/dist/heart/daemon/agent-service.js +210 -28
  242. package/dist/heart/daemon/agentic-repair.js +548 -0
  243. package/dist/heart/daemon/app-sessions-record.js +82 -0
  244. package/dist/heart/daemon/await-private-wake.js +59 -0
  245. package/dist/heart/daemon/bluebubbles-cli-integration.js +71 -0
  246. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  247. package/dist/heart/daemon/bluebubbles-host-protocol.js +433 -0
  248. package/dist/heart/daemon/bluebubbles-host.js +273 -0
  249. package/dist/heart/daemon/boot-sync-probe.js +223 -0
  250. package/dist/heart/daemon/cadence.js +130 -0
  251. package/dist/heart/daemon/cli-arg-redaction.js +26 -0
  252. package/dist/heart/daemon/cli-commands/a2a.js +26 -0
  253. package/dist/heart/daemon/cli-commands/cards.js +68 -0
  254. package/dist/heart/daemon/cli-commands/coding-tools.js +13 -0
  255. package/dist/heart/daemon/cli-commands/desk.js +43 -0
  256. package/dist/heart/daemon/cli-commands/dns.js +13 -0
  257. package/dist/heart/daemon/cli-commands/entry-points.js +173 -0
  258. package/dist/heart/daemon/cli-commands/failure-code.js +11 -0
  259. package/dist/heart/daemon/cli-commands/friends.js +18 -0
  260. package/dist/heart/daemon/cli-commands/habits.js +15 -0
  261. package/dist/heart/daemon/cli-commands/lifecycle.js +42 -0
  262. package/dist/heart/daemon/cli-commands/mail.js +11 -0
  263. package/dist/heart/daemon/cli-commands/mailbox-handle.js +32 -0
  264. package/dist/heart/daemon/cli-commands/mind.js +25 -0
  265. package/dist/heart/daemon/cli-commands/presence.js +28 -0
  266. package/dist/heart/daemon/cli-commands/providers.js +20 -0
  267. package/dist/heart/daemon/cli-commands/rsvp.js +20 -0
  268. package/dist/heart/daemon/cli-commands/shepherd.js +17 -0
  269. package/dist/heart/daemon/cli-commands/vault.js +23 -0
  270. package/dist/heart/daemon/cli-defaults.js +999 -0
  271. package/dist/heart/daemon/cli-desk.js +346 -0
  272. package/dist/heart/daemon/cli-exec.js +9698 -0
  273. package/dist/heart/daemon/cli-gate.js +198 -0
  274. package/dist/heart/daemon/cli-help.js +800 -0
  275. package/dist/heart/daemon/cli-manifest.js +118 -0
  276. package/dist/heart/daemon/cli-parse.js +3645 -0
  277. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  278. package/dist/heart/daemon/cli-render.js +816 -0
  279. package/dist/heart/daemon/cli-types.js +8 -0
  280. package/dist/heart/daemon/compile-cache.js +69 -0
  281. package/dist/heart/daemon/connect-bay.js +323 -0
  282. package/dist/heart/daemon/container-credential-bootstrap.js +273 -0
  283. package/dist/heart/daemon/container-healthcheck.js +125 -0
  284. package/dist/heart/daemon/container-runtime.js +115 -0
  285. package/dist/heart/daemon/container-spec-auditor-main.js +187 -0
  286. package/dist/heart/daemon/container-spec-auditor.js +272 -0
  287. package/dist/heart/daemon/daemon-bootstrap-startup.js +147 -0
  288. package/dist/heart/daemon/daemon-cli.js +29 -3317
  289. package/dist/heart/daemon/daemon-entry.js +1075 -56
  290. package/dist/heart/daemon/daemon-health.js +51 -1
  291. package/dist/heart/daemon/daemon-rollup.js +57 -0
  292. package/dist/heart/daemon/daemon-runtime-sync.js +147 -13
  293. package/dist/heart/daemon/daemon-tombstone.js +116 -3
  294. package/dist/heart/daemon/daemon.js +2107 -186
  295. package/dist/heart/daemon/desk-admin.js +420 -0
  296. package/dist/heart/daemon/dns-workflow.js +394 -0
  297. package/dist/heart/daemon/doctor-types.js +8 -0
  298. package/dist/heart/daemon/doctor.js +1966 -0
  299. package/dist/heart/daemon/freshness.js +345 -0
  300. package/dist/heart/daemon/habit-private-wake.js +61 -0
  301. package/dist/heart/daemon/handoff-blockers.js +118 -0
  302. package/dist/heart/daemon/health-monitor.js +256 -12
  303. package/dist/heart/daemon/home-filesystem.js +93 -0
  304. package/dist/heart/daemon/hook-post-tool-use.js +149 -0
  305. package/dist/heart/daemon/hooks/bundle-meta.js +135 -1
  306. package/dist/heart/daemon/http-health-probe.js +80 -0
  307. package/dist/heart/daemon/human-command-screens.js +234 -0
  308. package/dist/heart/daemon/human-readiness.js +114 -0
  309. package/dist/heart/daemon/inner-status.js +7 -18
  310. package/dist/heart/daemon/interactive-repair.js +394 -0
  311. package/dist/heart/daemon/launchd.js +40 -10
  312. package/dist/heart/daemon/linux-service.js +382 -0
  313. package/dist/heart/daemon/log-tailer.js +79 -10
  314. package/dist/heart/daemon/logs-prune.js +132 -0
  315. package/dist/heart/daemon/mailroom-copy-proof.js +158 -0
  316. package/dist/heart/daemon/mcp-canary.js +525 -0
  317. package/dist/heart/daemon/message-router.js +65 -5
  318. package/dist/heart/daemon/migrate-to-desk.js +848 -0
  319. package/dist/heart/daemon/os-cron-deps.js +22 -0
  320. package/dist/heart/daemon/os-cron.js +50 -15
  321. package/dist/heart/daemon/ouro-bot-entry.js +8 -3
  322. package/dist/heart/daemon/ouro-cli-main.js +50 -0
  323. package/dist/heart/daemon/ouro-entry.js +43 -20
  324. package/dist/heart/daemon/owner-alert-routes.js +159 -0
  325. package/dist/heart/daemon/owner-channel-outage.js +386 -0
  326. package/dist/heart/daemon/plugin-cli.js +432 -0
  327. package/dist/heart/daemon/portable-git-install.js +265 -0
  328. package/dist/heart/daemon/portable-git.js +179 -0
  329. package/dist/heart/daemon/presence-daemon.js +265 -0
  330. package/dist/heart/daemon/presence-roster.js +260 -0
  331. package/dist/heart/daemon/presence.js +469 -0
  332. package/dist/heart/daemon/process-manager.js +790 -71
  333. package/dist/heart/daemon/process-tree.js +109 -0
  334. package/dist/heart/daemon/provider-discovery.js +171 -0
  335. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  336. package/dist/heart/daemon/prunable-bundle.js +144 -0
  337. package/dist/heart/daemon/pulse.js +511 -0
  338. package/dist/heart/daemon/readiness-repair.js +365 -0
  339. package/dist/heart/daemon/runtime-logging.js +54 -14
  340. package/dist/heart/daemon/runtime-metadata.js +2 -30
  341. package/dist/heart/daemon/runtime-mode.js +13 -2
  342. package/dist/heart/daemon/runtime-replacement-handoff.js +207 -0
  343. package/dist/heart/daemon/sanctuary-acceptance-adapter.js +2662 -0
  344. package/dist/heart/daemon/sanctuary-acceptance-harness.js +1832 -0
  345. package/dist/heart/daemon/sanctuary-acceptance-marker.js +277 -0
  346. package/dist/heart/daemon/sanctuary-acceptance-scenarios.js +957 -0
  347. package/dist/heart/daemon/sanctuary-authority-codec.js +86 -0
  348. package/dist/heart/daemon/sanctuary-authority-epoch.js +291 -0
  349. package/dist/heart/daemon/sanctuary-authority-installation.js +161 -0
  350. package/dist/heart/daemon/sanctuary-authority-ledger.js +241 -0
  351. package/dist/heart/daemon/sanctuary-authority-root-lifecycle.js +1421 -0
  352. package/dist/heart/daemon/sanctuary-authority-vault-migration.js +117 -0
  353. package/dist/heart/daemon/sanctuary-bundle-migration.js +1039 -0
  354. package/dist/heart/daemon/sanctuary-host-authority.js +1008 -0
  355. package/dist/heart/daemon/sanctuary-host-detached-supervisor.js +493 -0
  356. package/dist/heart/daemon/sanctuary-host-executor.js +670 -0
  357. package/dist/heart/daemon/sanctuary-host-linux-kernel.js +334 -0
  358. package/dist/heart/daemon/sanctuary-host-supervisor-entry.js +210 -0
  359. package/dist/heart/daemon/sanctuary-host-supervisor.js +95 -0
  360. package/dist/heart/daemon/sanctuary-package-management.js +117 -0
  361. package/dist/heart/daemon/sanctuary-scheduler-liveness.js +147 -0
  362. package/dist/heart/daemon/sanctuary-telegram-authority-entry.js +481 -0
  363. package/dist/heart/daemon/sanctuary-telegram-authority-gateway.js +614 -0
  364. package/dist/heart/daemon/sanctuary-telegram-authority-service.js +763 -0
  365. package/dist/heart/daemon/sanctuary-telegram-test-driver-entry.js +97 -0
  366. package/dist/heart/daemon/sanctuary-telegram-test-driver.js +294 -0
  367. package/dist/heart/daemon/scheduler-attestation.js +249 -0
  368. package/dist/heart/daemon/sense-manager.js +1070 -60
  369. package/dist/heart/daemon/skill-management-installer.js +1 -1
  370. package/dist/heart/daemon/socket-client.js +185 -13
  371. package/dist/heart/daemon/stale-bundle-prune.js +113 -0
  372. package/dist/heart/daemon/startup-tui.js +339 -0
  373. package/dist/heart/daemon/state-retention.js +234 -0
  374. package/dist/heart/daemon/supercronic-supervisor.js +282 -0
  375. package/dist/heart/daemon/task-scheduler.js +115 -15
  376. package/dist/heart/daemon/terminal-ui.js +503 -0
  377. package/dist/heart/daemon/thoughts.js +133 -49
  378. package/dist/heart/daemon/up-progress.js +366 -0
  379. package/dist/heart/daemon/vault-items.js +56 -0
  380. package/dist/heart/daemon/vault-outage.js +74 -0
  381. package/dist/heart/delegated-work-report.js +115 -0
  382. package/dist/heart/delegation.js +0 -3
  383. package/dist/heart/external-events/router.js +1803 -0
  384. package/dist/heart/failure-reports.js +398 -0
  385. package/dist/heart/file-lock.js +109 -0
  386. package/dist/heart/frontend-approval-runtime.js +506 -0
  387. package/dist/heart/frontend-journal.js +215 -0
  388. package/dist/heart/frontend-session-service.js +332 -0
  389. package/dist/heart/frontend-socket-client.js +173 -0
  390. package/dist/heart/frontend-socket.js +434 -0
  391. package/dist/heart/frontend-turn-errors.js +20 -0
  392. package/dist/heart/git-binary.js +115 -0
  393. package/dist/heart/habits/habit-cancel.js +810 -0
  394. package/dist/heart/habits/habit-lifecycle.js +1324 -0
  395. package/dist/heart/{daemon → habits}/habit-migration.js +41 -28
  396. package/dist/heart/habits/habit-parser.js +258 -0
  397. package/dist/heart/habits/habit-runtime-state.js +93 -0
  398. package/dist/heart/habits/habit-scheduler.js +678 -0
  399. package/dist/heart/habits/habit-session-summary.js +318 -0
  400. package/dist/heart/habits/habit-session.js +638 -0
  401. package/dist/heart/{daemon → hatch}/hatch-flow.js +60 -38
  402. package/dist/heart/{daemon → hatch}/hatch-specialist.js +6 -8
  403. package/dist/heart/{daemon → hatch}/specialist-prompt.js +7 -5
  404. package/dist/heart/hatch/specialist-tools.js +395 -0
  405. package/dist/heart/identity.js +335 -29
  406. package/dist/heart/keep-in-touch.js +75 -0
  407. package/dist/heart/kept-notes.js +289 -0
  408. package/dist/heart/letters/answer-command.js +38 -0
  409. package/dist/heart/letters/answer-reader.js +216 -0
  410. package/dist/heart/letters/answered-note.js +108 -0
  411. package/dist/heart/letters/answering.js +183 -0
  412. package/dist/heart/letters/doors-tools.js +64 -0
  413. package/dist/heart/letters/doors.js +440 -0
  414. package/dist/heart/letters/expired-note.js +72 -0
  415. package/dist/heart/letters/filed-note.js +86 -0
  416. package/dist/heart/letters/letter-index.js +90 -0
  417. package/dist/heart/letters/letter.js +271 -0
  418. package/dist/heart/letters/render.js +46 -0
  419. package/dist/heart/letters/return-to-session.js +99 -0
  420. package/dist/heart/letters/seen-command.js +38 -0
  421. package/dist/heart/letters/store.js +242 -0
  422. package/dist/heart/letters/tell-agent.js +27 -0
  423. package/dist/heart/letters/writer.js +622 -0
  424. package/dist/heart/machine-identity.js +175 -0
  425. package/dist/heart/mail-import-discovery.js +356 -0
  426. package/dist/heart/mcp/mcp-server.js +922 -0
  427. package/dist/heart/migrate-config.js +15 -42
  428. package/dist/heart/model-capabilities.js +98 -16
  429. package/dist/heart/model-limits.js +49 -0
  430. package/dist/heart/optional-packages.js +77 -0
  431. package/dist/heart/orientation-frame.js +393 -0
  432. package/dist/heart/platform.js +81 -0
  433. package/dist/heart/primitives.js +1 -1
  434. package/dist/heart/private-runtime/decision-renderer.js +158 -0
  435. package/dist/heart/private-runtime/index.js +18 -0
  436. package/dist/heart/private-runtime/ledger.js +212 -0
  437. package/dist/heart/private-runtime/policy.js +327 -0
  438. package/dist/heart/private-runtime/types.js +2 -0
  439. package/dist/heart/product/active.js +313 -0
  440. package/dist/heart/product/types.js +2 -0
  441. package/dist/heart/progress-story.js +1 -1
  442. package/dist/heart/provider-attempt.js +137 -0
  443. package/dist/heart/provider-binding-resolver.js +273 -0
  444. package/dist/heart/provider-credentials.js +449 -0
  445. package/dist/heart/provider-failover.js +260 -37
  446. package/dist/heart/provider-fallback.js +228 -0
  447. package/dist/heart/provider-models.js +96 -0
  448. package/dist/heart/provider-ping-child.js +125 -0
  449. package/dist/heart/provider-ping-entry.js +8 -0
  450. package/dist/heart/provider-ping.js +217 -91
  451. package/dist/heart/provider-readiness-cache.js +119 -0
  452. package/dist/heart/provider-visibility.js +188 -0
  453. package/dist/heart/providers/account-pool.js +717 -0
  454. package/dist/heart/providers/anthropic-token.js +15 -47
  455. package/dist/heart/providers/anthropic.js +270 -73
  456. package/dist/heart/providers/azure.js +16 -28
  457. package/dist/heart/providers/error-classification.js +129 -0
  458. package/dist/heart/providers/github-copilot.js +127 -32
  459. package/dist/heart/providers/minimax-vlm.js +189 -0
  460. package/dist/heart/providers/minimax.js +17 -25
  461. package/dist/heart/providers/openai-codex-token.js +349 -0
  462. package/dist/heart/providers/openai-codex.js +43 -54
  463. package/dist/heart/providers/openai-compatible.js +177 -0
  464. package/dist/heart/quota/fleet-readings.js +222 -0
  465. package/dist/heart/quota/tranche.js +59 -0
  466. package/dist/heart/reach-channel.js +85 -0
  467. package/dist/heart/reply-style.js +52 -0
  468. package/dist/heart/run-ledger.js +247 -0
  469. package/dist/heart/runtime-capability-check.js +170 -0
  470. package/dist/heart/runtime-credentials.js +647 -0
  471. package/dist/heart/runtime-cwd.js +87 -0
  472. package/dist/heart/sense-truth.js +26 -4
  473. package/dist/heart/sent-message-ledger.js +98 -0
  474. package/dist/heart/session-activity.js +84 -17
  475. package/dist/heart/session-events.js +1609 -0
  476. package/dist/heart/session-path.js +49 -0
  477. package/dist/heart/session-playback-cli-main.js +10 -0
  478. package/dist/heart/session-playback-cli.js +36 -0
  479. package/dist/heart/session-playback.js +231 -0
  480. package/dist/heart/session-stats-cli-main.js +10 -0
  481. package/dist/heart/session-stats.js +183 -0
  482. package/dist/heart/session-transcript.js +133 -0
  483. package/dist/heart/shelf-claims.js +136 -0
  484. package/dist/heart/shepherd/custody-types.js +2 -0
  485. package/dist/heart/shepherd/mandates.js +352 -0
  486. package/dist/heart/shepherd/operation-commands.js +19 -0
  487. package/dist/heart/shepherd/operations.js +139 -0
  488. package/dist/heart/shepherd/supervision-read.js +131 -0
  489. package/dist/heart/shepherd/supervision.js +114 -0
  490. package/dist/heart/shepherd/types.js +2 -0
  491. package/dist/heart/shepherd-config.js +113 -0
  492. package/dist/heart/source-grounding.js +313 -0
  493. package/dist/heart/sqlite.js +18 -0
  494. package/dist/heart/start-of-turn-packet.js +372 -0
  495. package/dist/heart/steward-policy.js +656 -0
  496. package/dist/heart/streaming.js +627 -193
  497. package/dist/heart/structured-output.js +196 -0
  498. package/dist/heart/sync-classification.js +176 -0
  499. package/dist/heart/sync-health.js +152 -0
  500. package/dist/heart/sync-lock.js +431 -0
  501. package/dist/heart/sync.js +1583 -0
  502. package/dist/heart/target-resolution.js +28 -7
  503. package/dist/heart/tempo.js +93 -0
  504. package/dist/heart/temporal-view.js +41 -0
  505. package/dist/heart/termination-guard.js +27 -0
  506. package/dist/heart/timeouts.js +101 -0
  507. package/dist/heart/tool-activity-callbacks.js +27 -4
  508. package/dist/heart/tool-approval.js +382 -0
  509. package/dist/heart/tool-description.js +29 -9
  510. package/dist/heart/tool-friction.js +55 -0
  511. package/dist/heart/tool-images.js +42 -0
  512. package/dist/heart/tool-loop.js +9 -3
  513. package/dist/heart/tool-output-budget.js +41 -0
  514. package/dist/heart/turn-context.js +501 -0
  515. package/dist/heart/turn-execution-lease.js +78 -0
  516. package/dist/heart/turn-summary.js +216 -0
  517. package/dist/heart/versioning/host-self-update.js +118 -0
  518. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +6 -5
  519. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +12 -3
  520. package/dist/heart/versioning/ouro-path-installer.js +432 -0
  521. package/dist/heart/versioning/ouro-recovery-launcher.js +98 -0
  522. package/dist/heart/versioning/ouro-version-manager.js +445 -0
  523. package/dist/heart/versioning/release-sources.js +185 -0
  524. package/dist/heart/versioning/self-update-defaults.js +432 -0
  525. package/dist/heart/versioning/self-update-lock.js +151 -0
  526. package/dist/heart/versioning/self-update.js +301 -0
  527. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  528. package/dist/heart/{daemon → versioning}/update-checker.js +12 -35
  529. package/dist/heart/versioning/update-hooks.js +160 -0
  530. package/dist/heart/versioning/update-state.js +134 -0
  531. package/dist/heart/versioning/updater-launchd.js +204 -0
  532. package/dist/heart/versioning/version-intent.js +114 -0
  533. package/dist/heart/work-card.js +380 -0
  534. package/dist/mailroom/attention.js +167 -0
  535. package/dist/mailroom/autonomy.js +209 -0
  536. package/dist/mailroom/azure-sdk.js +27 -0
  537. package/dist/mailroom/blob-store.js +991 -0
  538. package/dist/mailroom/body-cache.js +61 -0
  539. package/dist/mailroom/cache-sync-cli.js +58 -0
  540. package/dist/mailroom/core.js +813 -0
  541. package/dist/mailroom/entry.js +169 -0
  542. package/dist/mailroom/file-store.js +568 -0
  543. package/dist/mailroom/hosted-cache-sync.js +384 -0
  544. package/dist/mailroom/mbox-import.js +393 -0
  545. package/dist/mailroom/migration.js +164 -0
  546. package/dist/mailroom/outbound.js +380 -0
  547. package/dist/mailroom/policy.js +263 -0
  548. package/dist/mailroom/reader.js +308 -0
  549. package/dist/mailroom/search-cache.js +513 -0
  550. package/dist/mailroom/search-relevance.js +319 -0
  551. package/dist/mailroom/smtp-ingress.js +176 -0
  552. package/dist/mailroom/source-state.js +176 -0
  553. package/dist/mailroom/sweep-orphans-cli.js +34 -0
  554. package/dist/mailroom/thread.js +109 -0
  555. package/dist/mailroom/travel-extract.js +89 -0
  556. package/dist/mind/bundle-manifest.js +25 -4
  557. package/dist/mind/context.js +335 -198
  558. package/dist/mind/desk-section.js +332 -0
  559. package/dist/mind/diary-integrity.js +60 -0
  560. package/dist/mind/diary.js +38 -56
  561. package/dist/mind/embedding-provider.js +60 -0
  562. package/dist/mind/file-state.js +179 -0
  563. package/dist/mind/friend-link-codes.js +209 -0
  564. package/dist/mind/friend-merge.js +336 -0
  565. package/dist/mind/house-names.js +43 -0
  566. package/dist/mind/note-search.js +198 -0
  567. package/dist/mind/obligation-steering.js +15 -9
  568. package/dist/mind/outbound-record.js +176 -0
  569. package/dist/mind/pending.js +324 -11
  570. package/dist/mind/prompt-budget.js +511 -0
  571. package/dist/mind/prompt-refresh.js +3 -2
  572. package/dist/mind/prompt.js +939 -376
  573. package/dist/mind/provenance-trust.js +26 -0
  574. package/dist/mind/record-paths.js +312 -0
  575. package/dist/mind/scrutiny.js +121 -0
  576. package/dist/mind/session-transaction.js +642 -0
  577. package/dist/mind/token-estimate.js +17 -0
  578. package/dist/mind/where-am-i.js +177 -0
  579. package/dist/nerves/cli-logging.js +7 -1
  580. package/dist/nerves/coverage/audit-rules.js +15 -6
  581. package/dist/nerves/coverage/audit.js +28 -2
  582. package/dist/nerves/coverage/cli-main.js +6 -1
  583. package/dist/nerves/coverage/cli.js +1 -1
  584. package/dist/nerves/coverage/contract.js +5 -5
  585. package/dist/nerves/coverage/file-completeness.js +159 -5
  586. package/dist/nerves/coverage/run-artifacts.js +55 -35
  587. package/dist/nerves/coverage/source-scanner.js +4 -4
  588. package/dist/nerves/index.js +269 -31
  589. package/dist/nerves/observation.js +2 -4
  590. package/dist/nerves/redact.js +79 -0
  591. package/dist/nerves/review/cli-main.js +10 -0
  592. package/dist/nerves/review/cli.js +156 -0
  593. package/dist/nerves/review/core.js +159 -0
  594. package/dist/nerves/runtime.js +16 -1
  595. package/dist/ouro-ax/ax-command.js +794 -0
  596. package/dist/ouro-ax/effects.js +51 -0
  597. package/dist/ouro-ax/exit-codes.js +51 -0
  598. package/dist/ouro-ax/help.js +181 -0
  599. package/dist/ouro-ax/outcome.js +221 -0
  600. package/dist/ouro-ax/precise-copy.js +200 -0
  601. package/dist/ouro-ax/problem.js +95 -0
  602. package/dist/ouro-ax/voice.js +83 -0
  603. package/dist/ouro-ax/wait.js +158 -0
  604. package/dist/products/butler.js +209 -0
  605. package/dist/repertoire/ado-client.js +15 -56
  606. package/dist/repertoire/ado-semantic.js +108 -40
  607. package/dist/repertoire/api-client.js +97 -0
  608. package/dist/repertoire/auth-required.js +22 -0
  609. package/dist/repertoire/bitwarden-native.js +458 -0
  610. package/dist/repertoire/bitwarden-store.js +1296 -0
  611. package/dist/repertoire/bundle-templates.js +71 -0
  612. package/dist/repertoire/butler-status.js +248 -0
  613. package/dist/repertoire/bw-installer.js +268 -0
  614. package/dist/repertoire/coding/context-pack.js +80 -3
  615. package/dist/repertoire/coding/feedback.js +27 -26
  616. package/dist/repertoire/coding/index.js +63 -6
  617. package/dist/repertoire/coding/manager.js +31 -14
  618. package/dist/repertoire/coding/orca-client.js +194 -0
  619. package/dist/repertoire/coding/orca-manager.js +534 -0
  620. package/dist/repertoire/coding/router.js +124 -0
  621. package/dist/repertoire/coding/spawner.js +3 -2
  622. package/dist/repertoire/coding/tools.js +178 -34
  623. package/dist/repertoire/coding/workbench-client.js +272 -0
  624. package/dist/repertoire/coding/workbench-manager.js +404 -0
  625. package/dist/repertoire/commerce-errors.js +109 -0
  626. package/dist/repertoire/commerce-self-test.js +156 -0
  627. package/dist/repertoire/credential-access.js +183 -0
  628. package/dist/repertoire/desk/classifier.js +362 -0
  629. package/dist/repertoire/desk-mcp.js +204 -0
  630. package/dist/repertoire/duffel-client.js +185 -0
  631. package/dist/repertoire/github-client.js +14 -55
  632. package/dist/repertoire/graph-client.js +11 -52
  633. package/dist/repertoire/guardrails.js +1301 -77
  634. package/dist/repertoire/house-sweep.js +471 -0
  635. package/dist/repertoire/in-turn-tools-door.js +55 -0
  636. package/dist/repertoire/mcp-client.js +58 -5
  637. package/dist/repertoire/mcp-declared-tools.js +156 -0
  638. package/dist/repertoire/mcp-manager.js +457 -141
  639. package/dist/repertoire/mcp-tools.js +199 -0
  640. package/dist/repertoire/mcp-write-guard.js +85 -0
  641. package/dist/repertoire/plugin-mcp.js +175 -0
  642. package/dist/repertoire/plugins.js +253 -0
  643. package/dist/repertoire/relationship-authorization.js +322 -0
  644. package/dist/repertoire/sanctuary-container-policy.js +50 -0
  645. package/dist/repertoire/shell-sessions.js +136 -0
  646. package/dist/repertoire/skill-search.js +177 -0
  647. package/dist/repertoire/skill-summaries.js +129 -0
  648. package/dist/repertoire/skills.js +34 -4
  649. package/dist/repertoire/stripe-client.js +163 -0
  650. package/dist/repertoire/tool-arguments.js +180 -0
  651. package/dist/repertoire/tool-candidates.js +50 -0
  652. package/dist/repertoire/tool-catalog.js +228 -0
  653. package/dist/repertoire/tool-error-code.js +30 -0
  654. package/dist/repertoire/tool-limits.js +20 -0
  655. package/dist/repertoire/tool-results.js +29 -0
  656. package/dist/repertoire/tools-a2a.js +792 -0
  657. package/dist/repertoire/tools-app-sessions.js +219 -0
  658. package/dist/repertoire/tools-attachments.js +302 -0
  659. package/dist/repertoire/tools-awaiting.js +937 -0
  660. package/dist/repertoire/tools-base.js +85 -1422
  661. package/dist/repertoire/tools-bridge.js +153 -0
  662. package/dist/repertoire/tools-bundle.js +998 -0
  663. package/dist/repertoire/tools-chat.js +185 -0
  664. package/dist/repertoire/tools-commerce.js +272 -0
  665. package/dist/repertoire/tools-config.js +199 -0
  666. package/dist/repertoire/tools-continuity.js +648 -0
  667. package/dist/repertoire/tools-credential.js +410 -0
  668. package/dist/repertoire/tools-escalation.js +98 -0
  669. package/dist/repertoire/tools-evolution.js +560 -0
  670. package/dist/repertoire/tools-files.js +521 -0
  671. package/dist/repertoire/tools-flight.js +313 -0
  672. package/dist/repertoire/tools-flow.js +176 -0
  673. package/dist/repertoire/tools-friend-link.js +69 -0
  674. package/dist/repertoire/tools-github.js +11 -4
  675. package/dist/repertoire/tools-habits.js +111 -0
  676. package/dist/repertoire/tools-house-care.js +190 -0
  677. package/dist/repertoire/tools-mail.js +1930 -0
  678. package/dist/repertoire/tools-notes.js +571 -0
  679. package/dist/repertoire/tools-obligations.js +187 -0
  680. package/dist/repertoire/tools-orientation.js +36 -0
  681. package/dist/repertoire/tools-record.js +497 -0
  682. package/dist/repertoire/tools-rsvp.js +148 -0
  683. package/dist/repertoire/tools-runtime.js +260 -0
  684. package/dist/repertoire/tools-sanctuary-host.js +222 -0
  685. package/dist/repertoire/tools-session.js +997 -0
  686. package/dist/repertoire/tools-shell.js +275 -0
  687. package/dist/repertoire/tools-shepherd-guidance.js +183 -0
  688. package/dist/repertoire/tools-shepherd.js +369 -0
  689. package/dist/repertoire/tools-steward-policy.js +157 -0
  690. package/dist/repertoire/tools-stripe.js +244 -0
  691. package/dist/repertoire/tools-surface.js +609 -0
  692. package/dist/repertoire/tools-teams.js +67 -17
  693. package/dist/repertoire/tools-telegram-contacts.js +41 -0
  694. package/dist/repertoire/tools-travel.js +142 -0
  695. package/dist/repertoire/tools-trip.js +1041 -0
  696. package/dist/repertoire/tools-unraid.js +627 -0
  697. package/dist/repertoire/tools-user-profile.js +166 -0
  698. package/dist/repertoire/tools-vault.js +46 -0
  699. package/dist/repertoire/tools-voice-local.js +210 -0
  700. package/dist/repertoire/tools-voice.js +153 -0
  701. package/dist/repertoire/tools-web.js +238 -0
  702. package/dist/repertoire/tools.js +628 -288
  703. package/dist/repertoire/travel-api-client.js +463 -0
  704. package/dist/repertoire/unraid-client.js +155 -0
  705. package/dist/repertoire/unraid-restart.js +342 -0
  706. package/dist/repertoire/user-profile.js +131 -0
  707. package/dist/repertoire/vault-setup.js +298 -0
  708. package/dist/repertoire/vault-unlock.js +816 -0
  709. package/dist/rsvp/aisleplanner-client.js +354 -0
  710. package/dist/rsvp/cli.js +886 -0
  711. package/dist/rsvp/config.js +327 -0
  712. package/dist/rsvp/cutover.js +453 -0
  713. package/dist/rsvp/diagnostics.js +232 -0
  714. package/dist/rsvp/diff-renderer.js +176 -0
  715. package/dist/rsvp/habit-policy.js +109 -0
  716. package/dist/rsvp/habit-stage.js +122 -0
  717. package/dist/rsvp/incident-bundle.js +97 -0
  718. package/dist/rsvp/migration.js +204 -0
  719. package/dist/rsvp/native-habit-runner.js +621 -0
  720. package/dist/rsvp/outbound-state.js +628 -0
  721. package/dist/rsvp/query.js +118 -0
  722. package/dist/rsvp/replay.js +233 -0
  723. package/dist/rsvp/snapshot.js +232 -0
  724. package/dist/rsvp/spend-ledger.js +175 -0
  725. package/dist/scripts/claude-code-stop-hook.js +4 -3
  726. package/dist/senses/a2a-entry.js +134 -0
  727. package/dist/senses/acp-server.js +452 -0
  728. package/dist/senses/app-sessions/client.js +128 -0
  729. package/dist/senses/app-sessions/digest-cards.js +263 -0
  730. package/dist/senses/app-sessions/digest-push.js +108 -0
  731. package/dist/senses/app-sessions/digest-sources.js +204 -0
  732. package/dist/senses/app-sessions/digest.js +284 -0
  733. package/dist/senses/app-sessions/run-command.js +51 -0
  734. package/dist/senses/app-sessions/sense.js +242 -0
  735. package/dist/senses/app-sessions/shepherd-cli.js +166 -0
  736. package/dist/senses/app-sessions/shepherd-rows.js +67 -0
  737. package/dist/senses/app-sessions/store.js +149 -0
  738. package/dist/senses/app-sessions/waiting-prompts.js +137 -0
  739. package/dist/senses/app-sessions/waiting-status.js +23 -0
  740. package/dist/senses/app-sessions-entry.js +87 -0
  741. package/dist/senses/attention-queue.js +95 -6
  742. package/dist/senses/await-turn-message.js +65 -0
  743. package/dist/senses/bluebubbles/active-turns.js +241 -0
  744. package/dist/senses/bluebubbles/agent-client.js +161 -0
  745. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  746. package/dist/senses/bluebubbles/attachment-download.js +143 -0
  747. package/dist/senses/bluebubbles/client.js +957 -0
  748. package/dist/senses/bluebubbles/context-packet.js +207 -0
  749. package/dist/senses/bluebubbles/context-smoke.js +144 -0
  750. package/dist/senses/bluebubbles/entry.js +80 -0
  751. package/dist/senses/bluebubbles/host-account-verifier.js +113 -0
  752. package/dist/senses/bluebubbles/host-trust.js +13 -0
  753. package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +21 -3
  754. package/dist/senses/bluebubbles/index.js +4948 -0
  755. package/dist/senses/bluebubbles/latest-turn.js +342 -0
  756. package/dist/senses/bluebubbles/letter-answer-ingress.js +35 -0
  757. package/dist/senses/bluebubbles/letter-guard.js +144 -0
  758. package/dist/senses/bluebubbles/media.js +255 -0
  759. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +152 -30
  760. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +24 -13
  761. package/dist/senses/bluebubbles/outbound-state.js +335 -0
  762. package/dist/senses/bluebubbles/processed-log.js +133 -0
  763. package/dist/senses/bluebubbles/reactions.js +18 -0
  764. package/dist/senses/bluebubbles/replay.js +284 -0
  765. package/dist/senses/bluebubbles/runtime-state.js +172 -0
  766. package/dist/senses/bluebubbles/semantic-receipts.js +2014 -0
  767. package/dist/senses/bluebubbles/send-file.js +25 -0
  768. package/dist/senses/bluebubbles/send-health.js +126 -0
  769. package/dist/senses/bluebubbles/server-message.js +40 -0
  770. package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
  771. package/dist/senses/bluebubbles/url-trust.js +37 -0
  772. package/dist/senses/bluebubbles/webhook-registration.js +257 -0
  773. package/dist/senses/bluebubbles-meta-guard.js +39 -0
  774. package/dist/senses/chat-file.js +75 -0
  775. package/dist/senses/cli/bracketed-paste.js +82 -0
  776. package/dist/senses/cli/image-paste.js +287 -0
  777. package/dist/senses/cli/image-ref-navigation.js +75 -0
  778. package/dist/senses/cli/ink-app.js +156 -0
  779. package/dist/senses/cli/inline-diff.js +64 -0
  780. package/dist/senses/cli/input-keys.js +209 -0
  781. package/dist/senses/cli/kill-ring.js +86 -0
  782. package/dist/senses/cli/message-list.js +51 -0
  783. package/dist/senses/cli/ouro-tui.js +633 -0
  784. package/dist/senses/cli/spinner-imperative.js +135 -0
  785. package/dist/senses/cli/spinner.js +101 -0
  786. package/dist/senses/cli/status-line.js +60 -0
  787. package/dist/senses/cli/streaming-markdown.js +526 -0
  788. package/dist/senses/cli/tool-display.js +85 -0
  789. package/dist/senses/cli/tool-render.js +85 -0
  790. package/dist/senses/cli/tui-store.js +252 -0
  791. package/dist/senses/cli/virtual-list.js +35 -0
  792. package/dist/senses/cli-entry.js +62 -9
  793. package/dist/senses/cli.js +621 -368
  794. package/dist/senses/commands.js +29 -3
  795. package/dist/senses/context-packet-ledger.js +367 -0
  796. package/dist/senses/context-packets.js +154 -0
  797. package/dist/senses/habit-lifecycle-guard.js +24 -0
  798. package/dist/senses/habit-turn-message.js +58 -6
  799. package/dist/senses/inbound-journal.js +186 -0
  800. package/dist/senses/ingress-evidence.js +2 -0
  801. package/dist/senses/mail-entry.js +69 -0
  802. package/dist/senses/mail.js +524 -0
  803. package/dist/senses/ordinary-owner-decision.js +98 -0
  804. package/dist/senses/pipeline.js +1265 -298
  805. package/dist/senses/private-runtime-worker.js +820 -0
  806. package/dist/senses/private-runtime.js +1634 -0
  807. package/dist/senses/proactive-content-guard.js +166 -0
  808. package/dist/senses/program-status.js +155 -0
  809. package/dist/senses/repeat-while.js +36 -0
  810. package/dist/senses/reply-gate.js +237 -0
  811. package/dist/senses/root-host-approval-port.js +345 -0
  812. package/dist/senses/root-host-approval-runtime.js +394 -0
  813. package/dist/senses/sanctuary-authority-resident.js +102 -0
  814. package/dist/senses/sanctuary-download-credit-presentation.js +32 -0
  815. package/dist/senses/sanctuary-full-visibility-contract.js +302 -0
  816. package/dist/senses/sanctuary-grounding.js +118 -0
  817. package/dist/senses/sanctuary-health-acceptance-probe-entry.js +21 -0
  818. package/dist/senses/sanctuary-health-acceptance-probe.js +814 -0
  819. package/dist/senses/sanctuary-health-runner.js +107 -0
  820. package/dist/senses/sanctuary-health.js +442 -0
  821. package/dist/senses/sanctuary-house.js +97 -0
  822. package/dist/senses/sanctuary-install-state-contract.js +169 -0
  823. package/dist/senses/sanctuary-interactive-control.js +410 -0
  824. package/dist/senses/sanctuary-media-catalog-contract.js +268 -0
  825. package/dist/senses/sanctuary-media-optimization.js +517 -0
  826. package/dist/senses/sanctuary-runtime.js +388 -0
  827. package/dist/senses/sanctuary-sab.js +85 -0
  828. package/dist/senses/sanctuary-storage-optimization-contract.js +32 -0
  829. package/dist/senses/sense-shutdown.js +72 -0
  830. package/dist/senses/shared-turn.js +741 -98
  831. package/dist/senses/shepherd/agent-presentation.js +88 -0
  832. package/dist/senses/shepherd/attention-page.js +166 -0
  833. package/dist/senses/shepherd/attention-sidebar.js +76 -0
  834. package/dist/senses/shepherd/attention.js +295 -0
  835. package/dist/senses/shepherd/checkin-config.js +76 -0
  836. package/dist/senses/shepherd/checkin-store.js +383 -0
  837. package/dist/senses/shepherd/client.js +196 -0
  838. package/dist/senses/shepherd/cmux.js +483 -0
  839. package/dist/senses/shepherd/composer.js +336 -0
  840. package/dist/senses/shepherd/conversation-hold.js +78 -0
  841. package/dist/senses/shepherd/feedback-reply.js +108 -0
  842. package/dist/senses/shepherd/feedback-source.js +20 -0
  843. package/dist/senses/shepherd/feedback-store.js +328 -0
  844. package/dist/senses/shepherd/feedback-submit.js +182 -0
  845. package/dist/senses/shepherd/feedback-worker.js +208 -0
  846. package/dist/senses/shepherd/guidance.js +273 -0
  847. package/dist/senses/shepherd/herdr.js +427 -0
  848. package/dist/senses/shepherd/host.js +14 -0
  849. package/dist/senses/shepherd/human-decision-guard.js +29 -0
  850. package/dist/senses/shepherd/judge-evaluation-command.js +185 -0
  851. package/dist/senses/shepherd/judge-evaluation-entry.js +20 -0
  852. package/dist/senses/shepherd/judge-evaluation.js +144 -0
  853. package/dist/senses/shepherd/judge.js +210 -0
  854. package/dist/senses/shepherd/notice-outbox.js +254 -0
  855. package/dist/senses/shepherd/observation-publisher.js +320 -0
  856. package/dist/senses/shepherd/operations-defaults.js +86 -0
  857. package/dist/senses/shepherd/operations.js +159 -0
  858. package/dist/senses/shepherd/owner-notice.js +496 -0
  859. package/dist/senses/shepherd/prompt-state.js +60 -0
  860. package/dist/senses/shepherd/recovery.js +543 -0
  861. package/dist/senses/shepherd/redact.js +66 -0
  862. package/dist/senses/shepherd/returns.js +79 -0
  863. package/dist/senses/shepherd/sense.js +862 -0
  864. package/dist/senses/shepherd/shepherd-judge-corpus-v1.json +170 -0
  865. package/dist/senses/shepherd/surface.js +125 -0
  866. package/dist/senses/shepherd/target-binding.js +13 -0
  867. package/dist/senses/shepherd/terminal-process.js +147 -0
  868. package/dist/senses/shepherd-entry.js +98 -0
  869. package/dist/senses/surface-tool.js +60 -34
  870. package/dist/senses/teams-attachments.js +68 -0
  871. package/dist/senses/teams-entry.js +80 -9
  872. package/dist/senses/teams-image.js +128 -0
  873. package/dist/senses/teams-inbound.js +76 -0
  874. package/dist/senses/teams-off-turn.js +199 -0
  875. package/dist/senses/teams-outbox.js +249 -0
  876. package/dist/senses/teams.js +1346 -373
  877. package/dist/senses/telegram-admission.js +700 -0
  878. package/dist/senses/telegram-approval-relay.js +293 -0
  879. package/dist/senses/telegram-approval-runtime.js +831 -0
  880. package/dist/senses/telegram-attachments.js +128 -0
  881. package/dist/senses/telegram-audit-ledger.js +220 -0
  882. package/dist/senses/telegram-authority-transport.js +233 -0
  883. package/dist/senses/telegram-chat-actions.js +57 -0
  884. package/dist/senses/telegram-client.js +1896 -0
  885. package/dist/senses/telegram-effect-adapter.js +893 -0
  886. package/dist/senses/telegram-entry.js +87 -0
  887. package/dist/senses/telegram-handoff.js +150 -0
  888. package/dist/senses/telegram-identity-key.js +143 -0
  889. package/dist/senses/telegram-markdown.js +331 -0
  890. package/dist/senses/telegram-owner-route.js +129 -0
  891. package/dist/senses/telegram.js +2798 -0
  892. package/dist/senses/terminal-handoff.js +44 -0
  893. package/dist/senses/trust-gate.js +104 -9
  894. package/dist/senses/turn-attempts.js +171 -0
  895. package/dist/senses/turn-watch.js +268 -0
  896. package/dist/senses/voice/audio-playback.js +237 -0
  897. package/dist/senses/voice/audio-routing.js +119 -0
  898. package/dist/senses/voice/call-auth.js +250 -0
  899. package/dist/senses/voice/elevenlabs.js +202 -0
  900. package/dist/senses/voice/floor-control.js +431 -0
  901. package/dist/senses/voice/floor-controller.js +115 -0
  902. package/dist/senses/voice/golden-path.js +116 -0
  903. package/dist/senses/voice/index.js +29 -0
  904. package/dist/senses/voice/local-audio-control.js +344 -0
  905. package/dist/senses/voice/local-audio-devices.js +516 -0
  906. package/dist/senses/voice/local-audio-disclosure.js +174 -0
  907. package/dist/senses/voice/local-audio-identity.js +103 -0
  908. package/dist/senses/voice/local-audio-join.js +325 -0
  909. package/dist/senses/voice/local-audio-mute.js +199 -0
  910. package/dist/senses/voice/local-audio-notify.js +124 -0
  911. package/dist/senses/voice/local-audio-prompts.js +116 -0
  912. package/dist/senses/voice/local-audio-transport.js +427 -0
  913. package/dist/senses/voice/local-audio.js +281 -0
  914. package/dist/senses/voice/local-media-stream.js +145 -0
  915. package/dist/senses/voice/meeting.js +113 -0
  916. package/dist/senses/voice/outbound.js +190 -0
  917. package/dist/senses/voice/phone.js +33 -0
  918. package/dist/senses/voice/playback.js +139 -0
  919. package/dist/senses/voice/process-guards.js +51 -0
  920. package/dist/senses/voice/realtime-eval.js +496 -0
  921. package/dist/senses/voice/realtime-tool-schema.js +195 -0
  922. package/dist/senses/voice/realtime-trace.js +531 -0
  923. package/dist/senses/voice/realtime-utterances.js +158 -0
  924. package/dist/senses/voice/transcript.js +70 -0
  925. package/dist/senses/voice/turn.js +219 -0
  926. package/dist/senses/voice/twilio-phone-runtime.js +836 -0
  927. package/dist/senses/voice/twilio-phone.js +5660 -0
  928. package/dist/senses/voice/types.js +2 -0
  929. package/dist/senses/voice/utterances.js +207 -0
  930. package/dist/senses/voice/whisper.js +153 -0
  931. package/dist/senses/voice-entry.js +84 -0
  932. package/dist/senses/voice-realtime-eval-command.js +99 -0
  933. package/dist/senses/voice-realtime-eval-entry.js +25 -0
  934. package/dist/senses/voice-twilio-entry.js +88 -0
  935. package/dist/trips/core.js +138 -0
  936. package/dist/trips/store.js +265 -0
  937. package/dist/util/frontmatter.js +69 -0
  938. package/node_modules/@ouro.bot/friends/LICENSE +201 -0
  939. package/node_modules/@ouro.bot/friends/README.md +687 -0
  940. package/node_modules/@ouro.bot/friends/actions/generated/mcp.json +1105 -0
  941. package/node_modules/@ouro.bot/friends/changelog.json +197 -0
  942. package/node_modules/@ouro.bot/friends/dist/a2a-client/a2a-message.d.ts +39 -0
  943. package/node_modules/@ouro.bot/friends/dist/a2a-client/a2a-message.js +54 -0
  944. package/node_modules/@ouro.bot/friends/dist/a2a-client/adapter.d.ts +117 -0
  945. package/node_modules/@ouro.bot/friends/dist/a2a-client/adapter.js +202 -0
  946. package/node_modules/@ouro.bot/friends/dist/a2a-client/agent-card.d.ts +50 -0
  947. package/node_modules/@ouro.bot/friends/dist/a2a-client/agent-card.js +32 -0
  948. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-key.d.ts +38 -0
  949. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-key.js +120 -0
  950. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-verifier.d.ts +195 -0
  951. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-verifier.js +342 -0
  952. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-web.d.ts +26 -0
  953. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-web.js +140 -0
  954. package/node_modules/@ouro.bot/friends/dist/a2a-client/envelope-binding.d.ts +62 -0
  955. package/node_modules/@ouro.bot/friends/dist/a2a-client/envelope-binding.js +83 -0
  956. package/node_modules/@ouro.bot/friends/dist/a2a-client/index.d.ts +26 -0
  957. package/node_modules/@ouro.bot/friends/dist/a2a-client/index.js +82 -0
  958. package/node_modules/@ouro.bot/friends/dist/a2a-client/jcs.d.ts +5 -0
  959. package/node_modules/@ouro.bot/friends/dist/a2a-client/jcs.js +84 -0
  960. package/node_modules/@ouro.bot/friends/dist/a2a-client/reachability.d.ts +22 -0
  961. package/node_modules/@ouro.bot/friends/dist/a2a-client/reachability.js +17 -0
  962. package/node_modules/@ouro.bot/friends/dist/a2a-client/roster-verify.d.ts +15 -0
  963. package/node_modules/@ouro.bot/friends/dist/a2a-client/roster-verify.js +61 -0
  964. package/node_modules/@ouro.bot/friends/dist/a2a-client/seal.d.ts +47 -0
  965. package/node_modules/@ouro.bot/friends/dist/a2a-client/seal.js +95 -0
  966. package/node_modules/@ouro.bot/friends/dist/a2a-client/sealed-envelope.d.ts +58 -0
  967. package/node_modules/@ouro.bot/friends/dist/a2a-client/sealed-envelope.js +113 -0
  968. package/node_modules/@ouro.bot/friends/dist/a2a-client/sign.d.ts +42 -0
  969. package/node_modules/@ouro.bot/friends/dist/a2a-client/sign.js +87 -0
  970. package/node_modules/@ouro.bot/friends/dist/a2a-client/sodium.d.ts +5 -0
  971. package/node_modules/@ouro.bot/friends/dist/a2a-client/sodium.js +19 -0
  972. package/node_modules/@ouro.bot/friends/dist/account-roster.d.ts +52 -0
  973. package/node_modules/@ouro.bot/friends/dist/account-roster.js +108 -0
  974. package/node_modules/@ouro.bot/friends/dist/agent-peer.d.ts +26 -0
  975. package/node_modules/@ouro.bot/friends/dist/agent-peer.js +138 -0
  976. package/node_modules/@ouro.bot/friends/dist/audit.d.ts +42 -0
  977. package/node_modules/@ouro.bot/friends/dist/audit.js +86 -0
  978. package/node_modules/@ouro.bot/friends/dist/channel.d.ts +16 -0
  979. package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/channel.js +73 -6
  980. package/node_modules/@ouro.bot/friends/dist/connect-authority.d.ts +43 -0
  981. package/node_modules/@ouro.bot/friends/dist/connect-authority.js +84 -0
  982. package/node_modules/@ouro.bot/friends/dist/connect.d.ts +56 -0
  983. package/node_modules/@ouro.bot/friends/dist/connect.js +163 -0
  984. package/node_modules/@ouro.bot/friends/dist/consent.d.ts +34 -0
  985. package/node_modules/@ouro.bot/friends/dist/consent.js +65 -0
  986. package/node_modules/@ouro.bot/friends/dist/coordination.d.ts +116 -0
  987. package/node_modules/@ouro.bot/friends/dist/coordination.js +329 -0
  988. package/node_modules/@ouro.bot/friends/dist/delegation-grant.d.ts +21 -0
  989. package/node_modules/@ouro.bot/friends/dist/delegation-grant.js +39 -0
  990. package/node_modules/@ouro.bot/friends/dist/file-bundle.d.ts +17 -0
  991. package/node_modules/@ouro.bot/friends/dist/file-bundle.js +27 -0
  992. package/node_modules/@ouro.bot/friends/dist/friend-lookup.d.ts +9 -0
  993. package/node_modules/@ouro.bot/friends/dist/friend-lookup.js +69 -0
  994. package/node_modules/@ouro.bot/friends/dist/grant-store-file.d.ts +19 -0
  995. package/node_modules/@ouro.bot/friends/dist/grant-store-file.js +157 -0
  996. package/node_modules/@ouro.bot/friends/dist/grant-store.d.ts +7 -0
  997. package/node_modules/@ouro.bot/friends/dist/grant-store.js +8 -0
  998. package/node_modules/@ouro.bot/friends/dist/grants.d.ts +43 -0
  999. package/node_modules/@ouro.bot/friends/dist/grants.js +100 -0
  1000. package/node_modules/@ouro.bot/friends/dist/group-context.d.ts +21 -0
  1001. package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/group-context.js +5 -4
  1002. package/node_modules/@ouro.bot/friends/dist/identity.d.ts +17 -0
  1003. package/node_modules/@ouro.bot/friends/dist/identity.js +68 -0
  1004. package/node_modules/@ouro.bot/friends/dist/index.d.ts +73 -0
  1005. package/node_modules/@ouro.bot/friends/dist/index.js +164 -0
  1006. package/node_modules/@ouro.bot/friends/dist/link-identity.d.ts +14 -0
  1007. package/node_modules/@ouro.bot/friends/dist/link-identity.js +157 -0
  1008. package/node_modules/@ouro.bot/friends/dist/mailbox/index.d.ts +105 -0
  1009. package/node_modules/@ouro.bot/friends/dist/mailbox/index.js +205 -0
  1010. package/node_modules/@ouro.bot/friends/dist/mcp/bin.d.ts +2 -0
  1011. package/node_modules/@ouro.bot/friends/dist/mcp/bin.js +17 -0
  1012. package/node_modules/@ouro.bot/friends/dist/mcp/dispatch.d.ts +40 -0
  1013. package/node_modules/@ouro.bot/friends/dist/mcp/dispatch.js +744 -0
  1014. package/node_modules/@ouro.bot/friends/dist/mcp/index.d.ts +6 -0
  1015. package/node_modules/@ouro.bot/friends/dist/mcp/index.js +14 -0
  1016. package/node_modules/@ouro.bot/friends/dist/mcp/run-main.d.ts +7 -0
  1017. package/node_modules/@ouro.bot/friends/dist/mcp/run-main.js +59 -0
  1018. package/node_modules/@ouro.bot/friends/dist/mcp/schemas.d.ts +10 -0
  1019. package/node_modules/@ouro.bot/friends/dist/mcp/schemas.js +23 -0
  1020. package/node_modules/@ouro.bot/friends/dist/mcp/server.d.ts +30 -0
  1021. package/node_modules/@ouro.bot/friends/dist/mcp/server.js +195 -0
  1022. package/node_modules/@ouro.bot/friends/dist/message.d.ts +93 -0
  1023. package/node_modules/@ouro.bot/friends/dist/message.js +129 -0
  1024. package/node_modules/@ouro.bot/friends/dist/mission-result.d.ts +89 -0
  1025. package/node_modules/@ouro.bot/friends/dist/mission-result.js +207 -0
  1026. package/node_modules/@ouro.bot/friends/dist/mission-share.d.ts +94 -0
  1027. package/node_modules/@ouro.bot/friends/dist/mission-share.js +232 -0
  1028. package/node_modules/@ouro.bot/friends/dist/mission-store-file.d.ts +18 -0
  1029. package/node_modules/@ouro.bot/friends/dist/mission-store-file.js +169 -0
  1030. package/node_modules/@ouro.bot/friends/dist/mission-store.d.ts +10 -0
  1031. package/node_modules/@ouro.bot/friends/dist/mission-store.js +9 -0
  1032. package/node_modules/@ouro.bot/friends/dist/missions.d.ts +31 -0
  1033. package/node_modules/@ouro.bot/friends/dist/missions.js +99 -0
  1034. package/node_modules/@ouro.bot/friends/dist/notes.d.ts +11 -0
  1035. package/node_modules/@ouro.bot/friends/dist/notes.js +90 -0
  1036. package/node_modules/@ouro.bot/friends/dist/observability.d.ts +27 -0
  1037. package/node_modules/@ouro.bot/friends/dist/observability.js +31 -0
  1038. package/node_modules/@ouro.bot/friends/dist/outcomes.d.ts +9 -0
  1039. package/node_modules/@ouro.bot/friends/dist/outcomes.js +51 -0
  1040. package/node_modules/@ouro.bot/friends/dist/resolver.d.ts +59 -0
  1041. package/node_modules/@ouro.bot/friends/dist/resolver.js +276 -0
  1042. package/node_modules/@ouro.bot/friends/dist/results.d.ts +10 -0
  1043. package/node_modules/@ouro.bot/friends/dist/results.js +2 -0
  1044. package/node_modules/@ouro.bot/friends/dist/room.d.ts +22 -0
  1045. package/node_modules/@ouro.bot/friends/dist/room.js +40 -0
  1046. package/node_modules/@ouro.bot/friends/dist/roster-store-file.d.ts +16 -0
  1047. package/node_modules/@ouro.bot/friends/dist/roster-store-file.js +125 -0
  1048. package/node_modules/@ouro.bot/friends/dist/roster-store-memory.d.ts +9 -0
  1049. package/node_modules/@ouro.bot/friends/dist/roster-store-memory.js +20 -0
  1050. package/node_modules/@ouro.bot/friends/dist/roster-store.d.ts +29 -0
  1051. package/node_modules/@ouro.bot/friends/dist/roster-store.js +9 -0
  1052. package/node_modules/@ouro.bot/friends/dist/roster-verifier.d.ts +23 -0
  1053. package/node_modules/@ouro.bot/friends/dist/roster-verifier.js +47 -0
  1054. package/node_modules/@ouro.bot/friends/dist/share.d.ts +113 -0
  1055. package/node_modules/@ouro.bot/friends/dist/share.js +314 -0
  1056. package/node_modules/@ouro.bot/friends/dist/standing.d.ts +83 -0
  1057. package/node_modules/@ouro.bot/friends/dist/standing.js +111 -0
  1058. package/node_modules/@ouro.bot/friends/dist/store-file.d.ts +82 -0
  1059. package/node_modules/@ouro.bot/friends/dist/store-file.js +1089 -0
  1060. package/node_modules/@ouro.bot/friends/dist/store.d.ts +43 -0
  1061. package/node_modules/@ouro.bot/friends/dist/tokens.d.ts +10 -0
  1062. package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/tokens.js +7 -4
  1063. package/node_modules/@ouro.bot/friends/dist/trust-explanation.d.ts +22 -0
  1064. package/node_modules/@ouro.bot/friends/dist/trust-explanation.js +90 -0
  1065. package/node_modules/@ouro.bot/friends/dist/trust-mutation.d.ts +16 -0
  1066. package/node_modules/@ouro.bot/friends/dist/trust-mutation.js +67 -0
  1067. package/node_modules/@ouro.bot/friends/dist/types.d.ts +333 -0
  1068. package/node_modules/@ouro.bot/friends/dist/types.js +55 -0
  1069. package/node_modules/@ouro.bot/friends/dist/util/cap-string.d.ts +7 -0
  1070. package/node_modules/@ouro.bot/friends/dist/util/cap-string.js +35 -0
  1071. package/node_modules/@ouro.bot/friends/dist/util/safe-id.d.ts +1 -0
  1072. package/node_modules/@ouro.bot/friends/dist/util/safe-id.js +10 -0
  1073. package/node_modules/@ouro.bot/friends/dist/verifier.d.ts +11 -0
  1074. package/node_modules/@ouro.bot/friends/dist/verifier.js +29 -0
  1075. package/node_modules/@ouro.bot/friends/dist/whoami.d.ts +7 -0
  1076. package/node_modules/@ouro.bot/friends/dist/whoami.js +39 -0
  1077. package/node_modules/@ouro.bot/friends/package.json +82 -0
  1078. package/node_modules/libsodium/LICENSE +16 -0
  1079. package/node_modules/libsodium/README.md +281 -0
  1080. package/node_modules/libsodium/dist/modules/libsodium.js +1 -0
  1081. package/node_modules/libsodium/dist/modules-esm/libsodium.mjs +1 -0
  1082. package/node_modules/libsodium/package.json +54 -0
  1083. package/node_modules/libsodium-wrappers/LICENSE +16 -0
  1084. package/node_modules/libsodium-wrappers/README.md +281 -0
  1085. package/node_modules/libsodium-wrappers/dist/modules/libsodium-wrappers.d.ts +2155 -0
  1086. package/node_modules/libsodium-wrappers/dist/modules/libsodium-wrappers.js +1 -0
  1087. package/node_modules/libsodium-wrappers/dist/modules-esm/libsodium-wrappers.d.mts +2743 -0
  1088. package/node_modules/libsodium-wrappers/dist/modules-esm/libsodium-wrappers.mjs +1 -0
  1089. package/node_modules/libsodium-wrappers/package.json +74 -0
  1090. package/npm-shrinkwrap.json +8789 -0
  1091. package/package.json +100 -12
  1092. package/skills/agent-commerce.md +116 -0
  1093. package/skills/browser-navigation.md +120 -0
  1094. package/skills/commerce-setup-guide.md +116 -0
  1095. package/skills/commerce-setup.md +87 -0
  1096. package/skills/configure-dev-tools.md +32 -14
  1097. package/skills/sense-setup.md +56 -0
  1098. package/skills/travel-planning.md +141 -0
  1099. package/vendor/desk/.claude-plugin/plugin.json +35 -0
  1100. package/vendor/desk/.mcp.claude-codex.json +28 -0
  1101. package/vendor/desk/.mcp.copilot.json +16 -0
  1102. package/vendor/desk/.ouro-desk.json +6 -0
  1103. package/vendor/desk/CHANGELOG.md +7644 -0
  1104. package/vendor/desk/README.md +195 -0
  1105. package/vendor/desk/activation/README.md +98 -0
  1106. package/vendor/desk/activation/copilot-root.flattened-bundle.json +38 -0
  1107. package/vendor/desk/activation/desk.activation.json +251 -0
  1108. package/vendor/desk/activation/host-capability-evidence.md +46 -0
  1109. package/vendor/desk/activation/support-matrix.json +84 -0
  1110. package/vendor/desk/agency.json +20 -0
  1111. package/vendor/desk/agents/observer.agent.md +26 -0
  1112. package/vendor/desk/agents/observer.md +29 -0
  1113. package/vendor/desk/agents/worker.agent.md +32 -0
  1114. package/vendor/desk/agents/worker.md +40 -0
  1115. package/vendor/desk/artifacts/tombstones/tombstone.schema.json +53 -0
  1116. package/vendor/desk/artifacts/tombstones/tombstones.jsonl +1 -0
  1117. package/vendor/desk/changelog.d/README.md +12 -0
  1118. package/vendor/desk/docs/agent-files.md +104 -0
  1119. package/vendor/desk/docs/agentic-engineering-v2-rfc.md +206 -0
  1120. package/vendor/desk/docs/agentic-engineering-v3-rfc.md +109 -0
  1121. package/vendor/desk/docs/browser-remote-desktops.md +69 -0
  1122. package/vendor/desk/docs/dependency-activation-stories-and-criteria.md +500 -0
  1123. package/vendor/desk/docs/evaluation-packet.md +363 -0
  1124. package/vendor/desk/docs/factory-local-capture.md +651 -0
  1125. package/vendor/desk/docs/factory-store-playbook.md +927 -0
  1126. package/vendor/desk/docs/images/factory-site.png +0 -0
  1127. package/vendor/desk/docs/issue-drains.md +81 -0
  1128. package/vendor/desk/docs/lfs-inspection.md +55 -0
  1129. package/vendor/desk/docs/preview-diagnostics.md +11 -0
  1130. package/vendor/desk/docs/relays.md +88 -0
  1131. package/vendor/desk/docs/schedules.md +69 -0
  1132. package/vendor/desk/docs/search-recovery.md +22 -0
  1133. package/vendor/desk/docs/session-labels.md +157 -0
  1134. package/vendor/desk/docs/session-retention.md +125 -0
  1135. package/vendor/desk/docs/sessions.md +17 -0
  1136. package/vendor/desk/docs/stalled-nudges.md +54 -0
  1137. package/vendor/desk/docs/webhooks.md +80 -0
  1138. package/vendor/desk/docs/workspace-tidy.md +74 -0
  1139. package/vendor/desk/hooks/boot-checks.cjs +7 -0
  1140. package/vendor/desk/hooks/claude-session-start.cjs +123 -0
  1141. package/vendor/desk/hooks/compatible-node.cjs +97 -0
  1142. package/vendor/desk/hooks/copilot-boot-prompt.cjs +69 -0
  1143. package/vendor/desk/hooks/copilot-durable-files.cjs +8 -0
  1144. package/vendor/desk/hooks/copilot-hooks.json +61 -0
  1145. package/vendor/desk/hooks/copilot-intake-context.cjs +5 -0
  1146. package/vendor/desk/hooks/copilot-lane-model.cjs +8 -0
  1147. package/vendor/desk/hooks/copilot-session-start.cjs +264 -0
  1148. package/vendor/desk/hooks/copilot-skill-current.cjs +28 -0
  1149. package/vendor/desk/hooks/factory-end.cjs +5 -0
  1150. package/vendor/desk/hooks/factory-start.cjs +27 -0
  1151. package/vendor/desk/hooks/hooks.json +40 -0
  1152. package/vendor/desk/hooks/lib/boot-checks.cjs +643 -0
  1153. package/vendor/desk/hooks/lib/child-agent.cjs +14 -0
  1154. package/vendor/desk/hooks/lib/copilot-intake-context.cjs +73 -0
  1155. package/vendor/desk/hooks/lib/current-release.cjs +162 -0
  1156. package/vendor/desk/hooks/lib/delivery-stop.cjs +326 -0
  1157. package/vendor/desk/hooks/lib/detach-worker.cjs +43 -0
  1158. package/vendor/desk/hooks/lib/durable-files.cjs +102 -0
  1159. package/vendor/desk/hooks/lib/factory-end.cjs +330 -0
  1160. package/vendor/desk/hooks/lib/lane-model.cjs +82 -0
  1161. package/vendor/desk/hooks/lib/node-required.cjs +56 -0
  1162. package/vendor/desk/hooks/lib/orca-session-title.cjs +60 -0
  1163. package/vendor/desk/hooks/lib/session-end.cjs +30 -0
  1164. package/vendor/desk/hooks/lib/sync-end.cjs +89 -0
  1165. package/vendor/desk/hooks/loop-start.cjs +105 -0
  1166. package/vendor/desk/hooks/node-missing.sh +78 -0
  1167. package/vendor/desk/hooks/orca-session-title.cjs +8 -0
  1168. package/vendor/desk/hooks/session-end.cjs +8 -0
  1169. package/vendor/desk/mcp/README.md +277 -0
  1170. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1171. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1172. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1173. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1174. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1175. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1176. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1177. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1178. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1179. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1180. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1181. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1182. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1183. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1184. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1185. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/support-matrix.json +72 -0
  1186. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1187. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1188. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1189. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1190. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1191. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1192. package/vendor/desk/mcp/artifacts/runtime-deps/README.md +25 -0
  1193. package/vendor/desk/mcp/bootstrap.cjs +787 -0
  1194. package/vendor/desk/mcp/docs/private-feedback.md +13 -0
  1195. package/vendor/desk/mcp/idle-proxy.cjs +431 -0
  1196. package/vendor/desk/mcp/index.js +813 -0
  1197. package/vendor/desk/mcp/package-lock.json +3717 -0
  1198. package/vendor/desk/mcp/package.json +44 -0
  1199. package/vendor/desk/mcp/scripts/agency-desk-channel.js +7 -0
  1200. package/vendor/desk/mcp/scripts/build-runtime-deps-pack.js +5 -0
  1201. package/vendor/desk/mcp/scripts/crew.js +89 -0
  1202. package/vendor/desk/mcp/scripts/drains-launcher.mjs +330 -0
  1203. package/vendor/desk/mcp/scripts/drains.js +5 -0
  1204. package/vendor/desk/mcp/scripts/factory.js +666 -0
  1205. package/vendor/desk/mcp/scripts/file-desk-problem.js +9 -0
  1206. package/vendor/desk/mcp/scripts/finish-commit.js +7 -0
  1207. package/vendor/desk/mcp/scripts/lfs.js +37 -0
  1208. package/vendor/desk/mcp/scripts/local-recovery.js +445 -0
  1209. package/vendor/desk/mcp/scripts/migrations.js +11 -0
  1210. package/vendor/desk/mcp/scripts/private-view.js +177 -0
  1211. package/vendor/desk/mcp/scripts/resolve-desk-root.js +105 -0
  1212. package/vendor/desk/mcp/scripts/session-boot.js +22 -0
  1213. package/vendor/desk/mcp/scripts/session-retention.js +5 -0
  1214. package/vendor/desk/mcp/scripts/session-sync.js +10 -0
  1215. package/vendor/desk/mcp/scripts/sessions.js +5 -0
  1216. package/vendor/desk/mcp/scripts/sync-push.js +13 -0
  1217. package/vendor/desk/mcp/scripts/tidy-status.js +8 -0
  1218. package/vendor/desk/mcp/scripts/verify-runtime-deps-pack.js +5 -0
  1219. package/vendor/desk/mcp/src/actions/desk-read.actions.mts +73 -0
  1220. package/vendor/desk/mcp/src/actions/desk-session.actions.mts +57 -0
  1221. package/vendor/desk/mcp/src/actions/desk-web.actions.mts +52 -0
  1222. package/vendor/desk/mcp/src/actions/desk.actions.mts +5 -0
  1223. package/vendor/desk/mcp/src/actions/generated/desk/OuroActions.swift +649 -0
  1224. package/vendor/desk/mcp/src/actions/generated/desk/OuroActionsReins.swift +61 -0
  1225. package/vendor/desk/mcp/src/actions/generated/desk/actions.json +315 -0
  1226. package/vendor/desk/mcp/src/actions/generated/desk/commands.json +145 -0
  1227. package/vendor/desk/mcp/src/actions/generated/desk/mcp.json +289 -0
  1228. package/vendor/desk/mcp/src/actions/generated/desk/web.ts +59 -0
  1229. package/vendor/desk/mcp/src/actions/generated/desk/webmcp.json +250 -0
  1230. package/vendor/desk/mcp/src/actions/generated/desk-web/OuroActions.swift +241 -0
  1231. package/vendor/desk/mcp/src/actions/generated/desk-web/OuroActionsReins.swift +25 -0
  1232. package/vendor/desk/mcp/src/actions/generated/desk-web/actions.json +73 -0
  1233. package/vendor/desk/mcp/src/actions/generated/desk-web/commands.json +53 -0
  1234. package/vendor/desk/mcp/src/actions/generated/desk-web/mcp.json +83 -0
  1235. package/vendor/desk/mcp/src/actions/generated/desk-web/web.ts +47 -0
  1236. package/vendor/desk/mcp/src/actions/generated/desk-web/webmcp.json +81 -0
  1237. package/vendor/desk/mcp/src/actions/served.js +5 -0
  1238. package/vendor/desk/mcp/src/activation/admit.js +77 -0
  1239. package/vendor/desk/mcp/src/activation/failures.js +65 -0
  1240. package/vendor/desk/mcp/src/activation/readiness-policy.js +102 -0
  1241. package/vendor/desk/mcp/src/activation/schema.js +17 -0
  1242. package/vendor/desk/mcp/src/activation/superpowers-context.js +274 -0
  1243. package/vendor/desk/mcp/src/activation/validate.js +540 -0
  1244. package/vendor/desk/mcp/src/artifacts/tombstones.js +61 -0
  1245. package/vendor/desk/mcp/src/crew/initiative.js +287 -0
  1246. package/vendor/desk/mcp/src/crew/workspace.js +1285 -0
  1247. package/vendor/desk/mcp/src/db/init.js +75 -0
  1248. package/vendor/desk/mcp/src/db/schema.sql +83 -0
  1249. package/vendor/desk/mcp/src/desk/active-tasks.js +408 -0
  1250. package/vendor/desk/mcp/src/desk/card-commit-guard.js +282 -0
  1251. package/vendor/desk/mcp/src/desk/cleanup-index.js +53 -0
  1252. package/vendor/desk/mcp/src/desk/content-home.js +262 -0
  1253. package/vendor/desk/mcp/src/desk/crew-config.js +102 -0
  1254. package/vendor/desk/mcp/src/desk/crew-member.js +196 -0
  1255. package/vendor/desk/mcp/src/desk/crew-roster.js +151 -0
  1256. package/vendor/desk/mcp/src/desk/frontmatter-lite.js +228 -0
  1257. package/vendor/desk/mcp/src/desk/gh-logins.js +109 -0
  1258. package/vendor/desk/mcp/src/desk/handles.js +123 -0
  1259. package/vendor/desk/mcp/src/desk/handoff-reference.js +35 -0
  1260. package/vendor/desk/mcp/src/desk/improvement-authority.js +3 -0
  1261. package/vendor/desk/mcp/src/desk/improvement-cards.js +704 -0
  1262. package/vendor/desk/mcp/src/desk/improvement-person.js +51 -0
  1263. package/vendor/desk/mcp/src/desk/lifecycle.js +16 -0
  1264. package/vendor/desk/mcp/src/desk/machine-desks.js +119 -0
  1265. package/vendor/desk/mcp/src/desk/naming.js +333 -0
  1266. package/vendor/desk/mcp/src/desk/organization.js +592 -0
  1267. package/vendor/desk/mcp/src/desk/resources.js +274 -0
  1268. package/vendor/desk/mcp/src/desk/runtime-resolver.js +30 -0
  1269. package/vendor/desk/mcp/src/desk/scratch-paths.js +44 -0
  1270. package/vendor/desk/mcp/src/desk/step-delivery.js +140 -0
  1271. package/vendor/desk/mcp/src/desk/steps.js +263 -0
  1272. package/vendor/desk/mcp/src/desk/tidy.js +930 -0
  1273. package/vendor/desk/mcp/src/desk/unsigned-deliveries.js +359 -0
  1274. package/vendor/desk/mcp/src/factory/agent-types.js +45 -0
  1275. package/vendor/desk/mcp/src/factory/andon-watch.js +109 -0
  1276. package/vendor/desk/mcp/src/factory/binding.js +612 -0
  1277. package/vendor/desk/mcp/src/factory/boot-check.js +645 -0
  1278. package/vendor/desk/mcp/src/factory/capture-classify.js +158 -0
  1279. package/vendor/desk/mcp/src/factory/capture-count.js +183 -0
  1280. package/vendor/desk/mcp/src/factory/capture-flush.js +268 -0
  1281. package/vendor/desk/mcp/src/factory/capture-publish.js +141 -0
  1282. package/vendor/desk/mcp/src/factory/capture-schema.js +193 -0
  1283. package/vendor/desk/mcp/src/factory/capture-sweep.js +239 -0
  1284. package/vendor/desk/mcp/src/factory/catch-point.js +60 -0
  1285. package/vendor/desk/mcp/src/factory/commit-resolve.js +94 -0
  1286. package/vendor/desk/mcp/src/factory/consent-answer.js +37 -0
  1287. package/vendor/desk/mcp/src/factory/context-capability.js +15 -0
  1288. package/vendor/desk/mcp/src/factory/context-outbox.js +885 -0
  1289. package/vendor/desk/mcp/src/factory/context-run.js +386 -0
  1290. package/vendor/desk/mcp/src/factory/context-schema.js +249 -0
  1291. package/vendor/desk/mcp/src/factory/copilot-turn-index.js +93 -0
  1292. package/vendor/desk/mcp/src/factory/copilot-usage.js +148 -0
  1293. package/vendor/desk/mcp/src/factory/credential.js +45 -0
  1294. package/vendor/desk/mcp/src/factory/derive-claude.js +960 -0
  1295. package/vendor/desk/mcp/src/factory/derive-codex.js +734 -0
  1296. package/vendor/desk/mcp/src/factory/derive-common.js +279 -0
  1297. package/vendor/desk/mcp/src/factory/derive-copilot.js +1057 -0
  1298. package/vendor/desk/mcp/src/factory/derive-run.js +807 -0
  1299. package/vendor/desk/mcp/src/factory/desk-problem-file.js +310 -0
  1300. package/vendor/desk/mcp/src/factory/desk-problem-fingerprint.js +70 -0
  1301. package/vendor/desk/mcp/src/factory/desk-problem-known.js +246 -0
  1302. package/vendor/desk/mcp/src/factory/desk-problem-template.js +107 -0
  1303. package/vendor/desk/mcp/src/factory/desk-repo.js +1223 -0
  1304. package/vendor/desk/mcp/src/factory/desk-task-line.js +28 -0
  1305. package/vendor/desk/mcp/src/factory/desk-visibility.js +48 -0
  1306. package/vendor/desk/mcp/src/factory/end-hook.js +14 -0
  1307. package/vendor/desk/mcp/src/factory/evaluate-kick.js +164 -0
  1308. package/vendor/desk/mcp/src/factory/evaluate-run.js +678 -0
  1309. package/vendor/desk/mcp/src/factory/evaluator-step.js +484 -0
  1310. package/vendor/desk/mcp/src/factory/filer-launch.js +79 -0
  1311. package/vendor/desk/mcp/src/factory/flush-health.js +26 -0
  1312. package/vendor/desk/mcp/src/factory/flush.js +1758 -0
  1313. package/vendor/desk/mcp/src/factory/focus.js +326 -0
  1314. package/vendor/desk/mcp/src/factory/headless-flag.cjs +32 -0
  1315. package/vendor/desk/mcp/src/factory/headless-flag.js +25 -0
  1316. package/vendor/desk/mcp/src/factory/headless-ledger.js +743 -0
  1317. package/vendor/desk/mcp/src/factory/headless.js +567 -0
  1318. package/vendor/desk/mcp/src/factory/held-route.js +93 -0
  1319. package/vendor/desk/mcp/src/factory/host-flags.js +36 -0
  1320. package/vendor/desk/mcp/src/factory/improvement-verify.js +429 -0
  1321. package/vendor/desk/mcp/src/factory/kaizen-file.js +231 -0
  1322. package/vendor/desk/mcp/src/factory/label-binding.js +90 -0
  1323. package/vendor/desk/mcp/src/factory/label-schema.js +426 -0
  1324. package/vendor/desk/mcp/src/factory/local-status.js +368 -0
  1325. package/vendor/desk/mcp/src/factory/loop-conditions.js +121 -0
  1326. package/vendor/desk/mcp/src/factory/loop-health.js +500 -0
  1327. package/vendor/desk/mcp/src/factory/loop-slot.js +90 -0
  1328. package/vendor/desk/mcp/src/factory/loop-status.js +100 -0
  1329. package/vendor/desk/mcp/src/factory/loop-switch.cjs +14 -0
  1330. package/vendor/desk/mcp/src/factory/loop-worker-state.js +96 -0
  1331. package/vendor/desk/mcp/src/factory/loop-worker.js +290 -0
  1332. package/vendor/desk/mcp/src/factory/marker.js +61 -0
  1333. package/vendor/desk/mcp/src/factory/mirror-step.js +145 -0
  1334. package/vendor/desk/mcp/src/factory/os-protect.js +243 -0
  1335. package/vendor/desk/mcp/src/factory/outbox.js +2231 -0
  1336. package/vendor/desk/mcp/src/factory/outcome.js +431 -0
  1337. package/vendor/desk/mcp/src/factory/pipeline/andon.js +319 -0
  1338. package/vendor/desk/mcp/src/factory/pipeline/attention-rollup.js +158 -0
  1339. package/vendor/desk/mcp/src/factory/pipeline/attention.js +146 -0
  1340. package/vendor/desk/mcp/src/factory/pipeline/build.js +299 -0
  1341. package/vendor/desk/mcp/src/factory/pipeline/compare.js +148 -0
  1342. package/vendor/desk/mcp/src/factory/pipeline/formulas.js +652 -0
  1343. package/vendor/desk/mcp/src/factory/pipeline/kaizen.js +387 -0
  1344. package/vendor/desk/mcp/src/factory/pipeline/lifecycle-clocks.js +345 -0
  1345. package/vendor/desk/mcp/src/factory/pipeline/normalize.js +73 -0
  1346. package/vendor/desk/mcp/src/factory/pipeline/number-states.js +154 -0
  1347. package/vendor/desk/mcp/src/factory/pipeline/outcomes.js +268 -0
  1348. package/vendor/desk/mcp/src/factory/pipeline/report.js +737 -0
  1349. package/vendor/desk/mcp/src/factory/pipeline/rollups.js +883 -0
  1350. package/vendor/desk/mcp/src/factory/pipeline/stretches.js +523 -0
  1351. package/vendor/desk/mcp/src/factory/pipeline/timeline.js +199 -0
  1352. package/vendor/desk/mcp/src/factory/pipeline/validate-pr.js +238 -0
  1353. package/vendor/desk/mcp/src/factory/pipeline/versions.js +42 -0
  1354. package/vendor/desk/mcp/src/factory/pipeline/walk.js +1177 -0
  1355. package/vendor/desk/mcp/src/factory/plugin-registry.js +72 -0
  1356. package/vendor/desk/mcp/src/factory/plugin-sources.cjs +249 -0
  1357. package/vendor/desk/mcp/src/factory/pr-green.js +77 -0
  1358. package/vendor/desk/mcp/src/factory/process-lock.js +142 -0
  1359. package/vendor/desk/mcp/src/factory/proof-session.js +75 -0
  1360. package/vendor/desk/mcp/src/factory/publish.js +637 -0
  1361. package/vendor/desk/mcp/src/factory/published-schema.js +648 -0
  1362. package/vendor/desk/mcp/src/factory/reconcile-reasons.js +22 -0
  1363. package/vendor/desk/mcp/src/factory/reconcile-step.js +251 -0
  1364. package/vendor/desk/mcp/src/factory/reconcile.js +808 -0
  1365. package/vendor/desk/mcp/src/factory/release-version.js +134 -0
  1366. package/vendor/desk/mcp/src/factory/repo-name.js +13 -0
  1367. package/vendor/desk/mcp/src/factory/retention.js +60 -0
  1368. package/vendor/desk/mcp/src/factory/route-desk.js +40 -0
  1369. package/vendor/desk/mcp/src/factory/route-issues.js +251 -0
  1370. package/vendor/desk/mcp/src/factory/route-local.js +264 -0
  1371. package/vendor/desk/mcp/src/factory/schema.js +957 -0
  1372. package/vendor/desk/mcp/src/factory/session-kind.js +16 -0
  1373. package/vendor/desk/mcp/src/factory/session-lifetime.js +56 -0
  1374. package/vendor/desk/mcp/src/factory/session-route.js +183 -0
  1375. package/vendor/desk/mcp/src/factory/shell-git.js +500 -0
  1376. package/vendor/desk/mcp/src/factory/store-issues.js +143 -0
  1377. package/vendor/desk/mcp/src/factory/store-route.js +208 -0
  1378. package/vendor/desk/mcp/src/factory/test-state-guard.js +103 -0
  1379. package/vendor/desk/mcp/src/factory/time.js +36 -0
  1380. package/vendor/desk/mcp/src/factory/tool-issue-file.js +84 -0
  1381. package/vendor/desk/mcp/src/factory/tool-kinds.js +87 -0
  1382. package/vendor/desk/mcp/src/factory/triage-schema.js +233 -0
  1383. package/vendor/desk/mcp/src/factory/windows-acl.js +679 -0
  1384. package/vendor/desk/mcp/src/indexer/chunk.js +232 -0
  1385. package/vendor/desk/mcp/src/indexer/discover.js +442 -0
  1386. package/vendor/desk/mcp/src/indexer/exclusions.js +247 -0
  1387. package/vendor/desk/mcp/src/indexer/index.js +167 -0
  1388. package/vendor/desk/mcp/src/indexer/refs.js +0 -0
  1389. package/vendor/desk/mcp/src/indexer/text-hash.js +18 -0
  1390. package/vendor/desk/mcp/src/lib/ouro-actions/actions.claims.json +75 -0
  1391. package/vendor/desk/mcp/src/lib/ouro-actions/dist-manifest.json +70 -0
  1392. package/vendor/desk/mcp/src/lib/ouro-actions/ouro-actions.mts +1416 -0
  1393. package/vendor/desk/mcp/src/lib/ouro-ui/LICENSE +21 -0
  1394. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/ax-claims.ts +191 -0
  1395. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/ax-command.ts +1040 -0
  1396. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/checks.ts +343 -0
  1397. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/cli.ts +240 -0
  1398. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/component.ts +430 -0
  1399. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/dev-commands.ts +204 -0
  1400. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/doctor.ts +126 -0
  1401. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/effects.ts +68 -0
  1402. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/exit-codes.ts +75 -0
  1403. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/help.ts +220 -0
  1404. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/mcp.ts +268 -0
  1405. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/outcome.ts +265 -0
  1406. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/output.ts +67 -0
  1407. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/precise-copy.ts +235 -0
  1408. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/problem.ts +124 -0
  1409. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/surfaces.kit.mts +8 -0
  1410. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/surfaces.ts +568 -0
  1411. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/terminal.ts +245 -0
  1412. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/voice.ts +136 -0
  1413. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/wait.ts +226 -0
  1414. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/work-event.ts +181 -0
  1415. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/xray.kit.mts +18 -0
  1416. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/xray.ts +2110 -0
  1417. package/vendor/desk/mcp/src/package-metadata.js +20 -0
  1418. package/vendor/desk/mcp/src/protected/legacy-ledger.js +55 -0
  1419. package/vendor/desk/mcp/src/readiness/leftovers.js +75 -0
  1420. package/vendor/desk/mcp/src/readiness/process-start.js +149 -0
  1421. package/vendor/desk/mcp/src/runtime/admission-worker.js +194 -0
  1422. package/vendor/desk/mcp/src/runtime/admission.js +177 -0
  1423. package/vendor/desk/mcp/src/runtime/agency-desk-channel.js +342 -0
  1424. package/vendor/desk/mcp/src/runtime/agents-md.js +62 -0
  1425. package/vendor/desk/mcp/src/runtime/append-lane.js +68 -0
  1426. package/vendor/desk/mcp/src/runtime/argv-safe-reason.js +55 -0
  1427. package/vendor/desk/mcp/src/runtime/boot-dependencies.js +75 -0
  1428. package/vendor/desk/mcp/src/runtime/boot-text.js +504 -0
  1429. package/vendor/desk/mcp/src/runtime/boot.js +1676 -0
  1430. package/vendor/desk/mcp/src/runtime/bootstrap.js +1455 -0
  1431. package/vendor/desk/mcp/src/runtime/chunked-import.js +102 -0
  1432. package/vendor/desk/mcp/src/runtime/copilot-commit-trailer.js +133 -0
  1433. package/vendor/desk/mcp/src/runtime/copilot-session.js +155 -0
  1434. package/vendor/desk/mcp/src/runtime/deliver.js +506 -0
  1435. package/vendor/desk/mcp/src/runtime/desk-channel.js +86 -0
  1436. package/vendor/desk/mcp/src/runtime/desk-failure.js +26 -0
  1437. package/vendor/desk/mcp/src/runtime/desk-health.js +168 -0
  1438. package/vendor/desk/mcp/src/runtime/desk-session.js +1451 -0
  1439. package/vendor/desk/mcp/src/runtime/diagnostic-server.js +72 -0
  1440. package/vendor/desk/mcp/src/runtime/diagnostics.js +241 -0
  1441. package/vendor/desk/mcp/src/runtime/drains-cli.js +195 -0
  1442. package/vendor/desk/mcp/src/runtime/drains.js +1220 -0
  1443. package/vendor/desk/mcp/src/runtime/elsewhere-note.js +9 -0
  1444. package/vendor/desk/mcp/src/runtime/failure-evidence.js +21 -0
  1445. package/vendor/desk/mcp/src/runtime/fast-refs.js +209 -0
  1446. package/vendor/desk/mcp/src/runtime/filer-throttle.js +66 -0
  1447. package/vendor/desk/mcp/src/runtime/focused-card.js +147 -0
  1448. package/vendor/desk/mcp/src/runtime/front-door.js +204 -0
  1449. package/vendor/desk/mcp/src/runtime/gate-wait.js +2 -0
  1450. package/vendor/desk/mcp/src/runtime/git-inspection.js +201 -0
  1451. package/vendor/desk/mcp/src/runtime/git-read-worker.js +157 -0
  1452. package/vendor/desk/mcp/src/runtime/health.js +50 -0
  1453. package/vendor/desk/mcp/src/runtime/hooks.js +353 -0
  1454. package/vendor/desk/mcp/src/runtime/hosted.js +165 -0
  1455. package/vendor/desk/mcp/src/runtime/inbox.js +102 -0
  1456. package/vendor/desk/mcp/src/runtime/index-drift.js +118 -0
  1457. package/vendor/desk/mcp/src/runtime/last-start.js +133 -0
  1458. package/vendor/desk/mcp/src/runtime/lesson-section.js +92 -0
  1459. package/vendor/desk/mcp/src/runtime/lessons-shelf.js +100 -0
  1460. package/vendor/desk/mcp/src/runtime/lfs.js +319 -0
  1461. package/vendor/desk/mcp/src/runtime/native-path.js +12 -0
  1462. package/vendor/desk/mcp/src/runtime/newest-release.js +197 -0
  1463. package/vendor/desk/mcp/src/runtime/node-selection.js +233 -0
  1464. package/vendor/desk/mcp/src/runtime/orca-session-title.js +225 -0
  1465. package/vendor/desk/mcp/src/runtime/other-sessions.js +183 -0
  1466. package/vendor/desk/mcp/src/runtime/pending-migrations.js +657 -0
  1467. package/vendor/desk/mcp/src/runtime/plugin-update.js +215 -0
  1468. package/vendor/desk/mcp/src/runtime/pluginless-runtimes.js +34 -0
  1469. package/vendor/desk/mcp/src/runtime/pr-publication.js +252 -0
  1470. package/vendor/desk/mcp/src/runtime/preview-snapshot.js +23 -0
  1471. package/vendor/desk/mcp/src/runtime/publication-mode.js +19 -0
  1472. package/vendor/desk/mcp/src/runtime/relays.js +983 -0
  1473. package/vendor/desk/mcp/src/runtime/release-alert.js +148 -0
  1474. package/vendor/desk/mcp/src/runtime/remote-identity.js +162 -0
  1475. package/vendor/desk/mcp/src/runtime/resolve-here.js +4 -0
  1476. package/vendor/desk/mcp/src/runtime/runtime-deps-cli.js +65 -0
  1477. package/vendor/desk/mcp/src/runtime/runtime-deps.js +1109 -0
  1478. package/vendor/desk/mcp/src/runtime/runtime-identity.js +22 -0
  1479. package/vendor/desk/mcp/src/runtime/runtime-swap.js +101 -0
  1480. package/vendor/desk/mcp/src/runtime/schedules.js +235 -0
  1481. package/vendor/desk/mcp/src/runtime/session-activity.js +190 -0
  1482. package/vendor/desk/mcp/src/runtime/session-label.js +30 -0
  1483. package/vendor/desk/mcp/src/runtime/session-retention.js +662 -0
  1484. package/vendor/desk/mcp/src/runtime/session-sync.js +333 -0
  1485. package/vendor/desk/mcp/src/runtime/session-trailer.js +126 -0
  1486. package/vendor/desk/mcp/src/runtime/sessions-cli.js +301 -0
  1487. package/vendor/desk/mcp/src/runtime/signoff-listed.js +81 -0
  1488. package/vendor/desk/mcp/src/runtime/skills.js +76 -0
  1489. package/vendor/desk/mcp/src/runtime/stale-card-lead.js +52 -0
  1490. package/vendor/desk/mcp/src/runtime/stale-desk-refresh.js +198 -0
  1491. package/vendor/desk/mcp/src/runtime/stale-desk.js +219 -0
  1492. package/vendor/desk/mcp/src/runtime/stalled.js +255 -0
  1493. package/vendor/desk/mcp/src/runtime/standing-authority.js +79 -0
  1494. package/vendor/desk/mcp/src/runtime/startup-boot.js +341 -0
  1495. package/vendor/desk/mcp/src/runtime/startup-resolve.js +140 -0
  1496. package/vendor/desk/mcp/src/runtime/state-branch.js +203 -0
  1497. package/vendor/desk/mcp/src/runtime/status-compact.js +165 -0
  1498. package/vendor/desk/mcp/src/runtime/status-inspection-child.js +26 -0
  1499. package/vendor/desk/mcp/src/runtime/status-inspection.js +147 -0
  1500. package/vendor/desk/mcp/src/runtime/status-root.js +39 -0
  1501. package/vendor/desk/mcp/src/runtime/sync-worker.js +913 -0
  1502. package/vendor/desk/mcp/src/runtime/test-state-guard.js +107 -0
  1503. package/vendor/desk/mcp/src/runtime/unmerged-saves.js +273 -0
  1504. package/vendor/desk/mcp/src/runtime/workspace-claim.js +53 -0
  1505. package/vendor/desk/mcp/src/runtime/workspace-evidence.js +96 -0
  1506. package/vendor/desk/mcp/src/runtime/workspace-tidy.js +509 -0
  1507. package/vendor/desk/mcp/src/search/direct-lexical.js +54 -0
  1508. package/vendor/desk/mcp/src/search/embedder.js +108 -0
  1509. package/vendor/desk/mcp/src/search/engine.js +406 -0
  1510. package/vendor/desk/mcp/src/search/files-router.js +22 -0
  1511. package/vendor/desk/mcp/src/search/old-index.js +46 -0
  1512. package/vendor/desk/mcp/src/search/vectors.js +60 -0
  1513. package/vendor/desk/mcp/src/server.js +390 -0
  1514. package/vendor/desk/mcp/src/tool-names.js +71 -0
  1515. package/vendor/desk/mcp/src/tool-refusal.cjs +35 -0
  1516. package/vendor/desk/mcp/src/tool-schema-parts.js +12 -0
  1517. package/vendor/desk/mcp/src/tool-schemas.js +320 -0
  1518. package/vendor/desk/mcp/src/tools/_card-commit.js +148 -0
  1519. package/vendor/desk/mcp/src/tools/archive-links.js +188 -0
  1520. package/vendor/desk/mcp/src/tools/archive-move.js +18 -0
  1521. package/vendor/desk/mcp/src/tools/archive-native-session.js +728 -0
  1522. package/vendor/desk/mcp/src/tools/archive-state.js +513 -0
  1523. package/vendor/desk/mcp/src/tools/delivery-gate.js +251 -0
  1524. package/vendor/desk/mcp/src/tools/desk-save.js +449 -0
  1525. package/vendor/desk/mcp/src/tools/doctor.js +122 -0
  1526. package/vendor/desk/mcp/src/tools/done-evidence.js +260 -0
  1527. package/vendor/desk/mcp/src/tools/factory-context.js +204 -0
  1528. package/vendor/desk/mcp/src/tools/friction.js +332 -0
  1529. package/vendor/desk/mcp/src/tools/improvement.js +156 -0
  1530. package/vendor/desk/mcp/src/tools/lesson-lines.js +22 -0
  1531. package/vendor/desk/mcp/src/tools/lesson-owners.js +137 -0
  1532. package/vendor/desk/mcp/src/tools/lesson-team.js +169 -0
  1533. package/vendor/desk/mcp/src/tools/lesson.js +254 -0
  1534. package/vendor/desk/mcp/src/tools/local-only.js +151 -0
  1535. package/vendor/desk/mcp/src/tools/move.js +823 -0
  1536. package/vendor/desk/mcp/src/tools/native-stage-context.js +32 -0
  1537. package/vendor/desk/mcp/src/tools/note.js +267 -0
  1538. package/vendor/desk/mcp/src/tools/search.js +634 -0
  1539. package/vendor/desk/mcp/src/tools/shared-write.js +196 -0
  1540. package/vendor/desk/mcp/src/tools/sibling-desk.js +43 -0
  1541. package/vendor/desk/mcp/src/tools/status.js +236 -0
  1542. package/vendor/desk/mcp/src/tools/task-archive-due.js +9 -0
  1543. package/vendor/desk/mcp/src/tools/task-archived-resource.js +53 -0
  1544. package/vendor/desk/mcp/src/tools/task-body.js +141 -0
  1545. package/vendor/desk/mcp/src/tools/task-focus.js +164 -0
  1546. package/vendor/desk/mcp/src/tools/task-log.js +80 -0
  1547. package/vendor/desk/mcp/src/tools/task-signoff.js +155 -0
  1548. package/vendor/desk/mcp/src/tools/task.js +1780 -0
  1549. package/vendor/desk/mcp/src/tools/track-row.js +89 -0
  1550. package/vendor/desk/mcp/src/tools/track.js +240 -0
  1551. package/vendor/desk/mcp/src/util/agency-session.cjs +29 -0
  1552. package/vendor/desk/mcp/src/util/archive-links.js +105 -0
  1553. package/vendor/desk/mcp/src/util/bash.js +36 -0
  1554. package/vendor/desk/mcp/src/util/capture-record.js +73 -0
  1555. package/vendor/desk/mcp/src/util/cas-commit.js +252 -0
  1556. package/vendor/desk/mcp/src/util/citations.js +54 -0
  1557. package/vendor/desk/mcp/src/util/created-dirs.js +71 -0
  1558. package/vendor/desk/mcp/src/util/deferred-tools.js +51 -0
  1559. package/vendor/desk/mcp/src/util/desk-owner.js +99 -0
  1560. package/vendor/desk/mcp/src/util/env-value.js +13 -0
  1561. package/vendor/desk/mcp/src/util/file-identity.js +40 -0
  1562. package/vendor/desk/mcp/src/util/finish-commit.js +145 -0
  1563. package/vendor/desk/mcp/src/util/fm.js +410 -0
  1564. package/vendor/desk/mcp/src/util/git-config-file.js +85 -0
  1565. package/vendor/desk/mcp/src/util/git-stage.js +440 -0
  1566. package/vendor/desk/mcp/src/util/main-publish.js +240 -0
  1567. package/vendor/desk/mcp/src/util/markdown-links.cjs +555 -0
  1568. package/vendor/desk/mcp/src/util/object-input.js +59 -0
  1569. package/vendor/desk/mcp/src/util/paths.js +647 -0
  1570. package/vendor/desk/mcp/src/util/rank.js +189 -0
  1571. package/vendor/desk/mcp/src/util/redact.js +92 -0
  1572. package/vendor/desk/mcp/src/util/remove-retry.js +35 -0
  1573. package/vendor/desk/mcp/src/util/rename-retry.js +73 -0
  1574. package/vendor/desk/mcp/src/util/route-around.js +265 -0
  1575. package/vendor/desk/mcp/src/util/shell-quote.js +18 -0
  1576. package/vendor/desk/mcp/src/util/startup-direction.js +124 -0
  1577. package/vendor/desk/mcp/src/util/state-ignore.js +33 -0
  1578. package/vendor/desk/mcp/src/util/tool-commits.js +64 -0
  1579. package/vendor/desk/mcp/src/util/unicode-16/LICENSE-MIT.txt +7 -0
  1580. package/vendor/desk/mcp/src/util/unicode-16/README.md +9 -0
  1581. package/vendor/desk/mcp/src/util/unicode-16/letter.cjs +1 -0
  1582. package/vendor/desk/mcp/src/util/unicode-16/mark.cjs +1 -0
  1583. package/vendor/desk/mcp/src/util/unicode-16/number.cjs +1 -0
  1584. package/vendor/desk/mcp/web-auth.cjs +1914 -0
  1585. package/vendor/desk/mcp/web-browser-discovery.cjs +53 -0
  1586. package/vendor/desk/mcp/web-catalog.json +34 -0
  1587. package/vendor/desk/mcp/web-launch.cjs +101 -0
  1588. package/vendor/desk/mcp/web-sso.cjs +52 -0
  1589. package/vendor/desk/mcp/web.cjs +1239 -0
  1590. package/vendor/desk/migrations/01-move-to-ourostack-desk.md +188 -0
  1591. package/vendor/desk/migrations/02-tidy-desk.md +87 -0
  1592. package/vendor/desk/migrations/03-desk-release-channel.md +38 -0
  1593. package/vendor/desk/optional/session-label/consumer.mjs +237 -0
  1594. package/vendor/desk/optional/session-label/extension.mjs +32 -0
  1595. package/vendor/desk/plugin.json +54 -0
  1596. package/vendor/desk/settings.json +3 -0
  1597. package/vendor/desk/skills/add-workspace-mcp/SKILL.md +180 -0
  1598. package/vendor/desk/skills/adopt-inflight-work/SKILL.md +212 -0
  1599. package/vendor/desk/skills/archive-workflow/SKILL.md +132 -0
  1600. package/vendor/desk/skills/content-routing/SKILL.md +95 -0
  1601. package/vendor/desk/skills/coordinating-lanes/SKILL.md +24 -0
  1602. package/vendor/desk/skills/core-meeting-capture/SKILL.md +47 -0
  1603. package/vendor/desk/skills/core-meeting-capture/references/capture-contract.md +175 -0
  1604. package/vendor/desk/skills/curator/SKILL.md +103 -0
  1605. package/vendor/desk/skills/delightful-decks/SKILL.md +67 -0
  1606. package/vendor/desk/skills/desk-problem/SKILL.md +87 -0
  1607. package/vendor/desk/skills/directory-structure/SKILL.md +169 -0
  1608. package/vendor/desk/skills/doc-review-rigor/SKILL.md +63 -0
  1609. package/vendor/desk/skills/draining-issues/SKILL.md +62 -0
  1610. package/vendor/desk/skills/evaluate-release/SKILL.md +96 -0
  1611. package/vendor/desk/skills/evidence-discipline/SKILL.md +146 -0
  1612. package/vendor/desk/skills/factory-evaluator/SKILL.md +122 -0
  1613. package/vendor/desk/skills/factory-task-context/SKILL.md +116 -0
  1614. package/vendor/desk/skills/factory-work/SKILL.md +16 -0
  1615. package/vendor/desk/skills/fast-honest-ci/SKILL.md +70 -0
  1616. package/vendor/desk/skills/fast-honest-ci/examples.md +49 -0
  1617. package/vendor/desk/skills/first-run-bootstrap/SKILL.md +95 -0
  1618. package/vendor/desk/skills/friction-management/SKILL.md +98 -0
  1619. package/vendor/desk/skills/git-hygiene/SKILL.md +259 -0
  1620. package/vendor/desk/skills/independent-review/SKILL.md +34 -0
  1621. package/vendor/desk/skills/interaction-style/SKILL.md +241 -0
  1622. package/vendor/desk/skills/lesson-capture/SKILL.md +85 -0
  1623. package/vendor/desk/skills/lesson-capture/agents-md-budget.mjs +61 -0
  1624. package/vendor/desk/skills/live-ui-iteration/SKILL.md +35 -0
  1625. package/vendor/desk/skills/online-evaluation/SKILL.md +81 -0
  1626. package/vendor/desk/skills/operator-voice-comments/LICENSE-humanize +21 -0
  1627. package/vendor/desk/skills/operator-voice-comments/SKILL.md +94 -0
  1628. package/vendor/desk/skills/operator-voice-comments/human-voice.md +43 -0
  1629. package/vendor/desk/skills/outside-approval/SKILL.md +10 -0
  1630. package/vendor/desk/skills/peer-pr-review/SKILL.md +104 -0
  1631. package/vendor/desk/skills/pr-feedback-on-own-pr/SKILL.md +149 -0
  1632. package/vendor/desk/skills/pr-review-interrogation/SKILL.md +121 -0
  1633. package/vendor/desk/skills/pr-reviewer-audit/SKILL.md +68 -0
  1634. package/vendor/desk/skills/pr-reviewer-audit/helpers/audit.py +353 -0
  1635. package/vendor/desk/skills/pr-reviewer-audit/helpers/test_audit.py +522 -0
  1636. package/vendor/desk/skills/pr-self-review/SKILL.md +86 -0
  1637. package/vendor/desk/skills/pr-surface-hygiene/SKILL.md +129 -0
  1638. package/vendor/desk/skills/pr-surface-hygiene/check-visual-proof.cjs +112 -0
  1639. package/vendor/desk/skills/pr-surface-hygiene/repository-setup.md +19 -0
  1640. package/vendor/desk/skills/pr-surface-hygiene/resources/pr-visual-proof.yml +29 -0
  1641. package/vendor/desk/skills/pr-surface-hygiene/resources/pull-request-template.md +5 -0
  1642. package/vendor/desk/skills/preflight-actions/SKILL.md +60 -0
  1643. package/vendor/desk/skills/preview-feedback/SKILL.md +70 -0
  1644. package/vendor/desk/skills/prior-art/SKILL.md +14 -0
  1645. package/vendor/desk/skills/repo-handling/SKILL.md +67 -0
  1646. package/vendor/desk/skills/rnd-lab/SKILL.md +52 -0
  1647. package/vendor/desk/skills/runtime-symptom-investigation/SKILL.md +110 -0
  1648. package/vendor/desk/skills/session-resumption/SKILL.md +128 -0
  1649. package/vendor/desk/skills/session-start/SKILL.md +54 -0
  1650. package/vendor/desk/skills/session-start/details.md +150 -0
  1651. package/vendor/desk/skills/session-start-migrations/README.md +71 -0
  1652. package/vendor/desk/skills/session-start-migrations/SKILL.md +108 -0
  1653. package/vendor/desk/skills/start-task/SKILL.md +88 -0
  1654. package/vendor/desk/skills/task-card-format/SKILL.md +198 -0
  1655. package/vendor/desk/skills/task-lifecycle/SKILL.md +217 -0
  1656. package/vendor/desk/skills/track-card-format/SKILL.md +90 -0
  1657. package/vendor/desk/skills/using-desk/SKILL.md +58 -0
  1658. package/vendor/desk/skills/using-superpowers-with-desk/SKILL.md +158 -0
  1659. package/vendor/desk/skills/visual-proof/SKILL.md +42 -0
  1660. package/vendor/desk/skills/work-orchestration/SKILL.md +177 -0
  1661. package/dist/heart/daemon/auth-flow.js +0 -477
  1662. package/dist/heart/daemon/habit-parser.js +0 -119
  1663. package/dist/heart/daemon/habit-scheduler.js +0 -369
  1664. package/dist/heart/daemon/mcp-server.js +0 -591
  1665. package/dist/heart/daemon/ouro-path-installer.js +0 -221
  1666. package/dist/heart/daemon/ouro-version-manager.js +0 -171
  1667. package/dist/heart/daemon/outlook-http.js +0 -399
  1668. package/dist/heart/daemon/outlook-read.js +0 -1291
  1669. package/dist/heart/daemon/outlook-render.js +0 -1032
  1670. package/dist/heart/daemon/outlook-types.js +0 -7
  1671. package/dist/heart/daemon/outlook-view.js +0 -194
  1672. package/dist/heart/daemon/specialist-tools.js +0 -283
  1673. package/dist/heart/daemon/update-hooks.js +0 -138
  1674. package/dist/heart/obligations.js +0 -197
  1675. package/dist/heart/session-recall.js +0 -216
  1676. package/dist/mind/associative-recall.js +0 -287
  1677. package/dist/mind/friends/resolver.js +0 -84
  1678. package/dist/mind/friends/store-file.js +0 -190
  1679. package/dist/mind/friends/trust-explanation.js +0 -74
  1680. package/dist/mind/friends/types.js +0 -29
  1681. package/dist/mind/journal-index.js +0 -161
  1682. package/dist/mind/obligations.js +0 -134
  1683. package/dist/outlook-ui/assets/index-Cy9jh-Dy.js +0 -61
  1684. package/dist/outlook-ui/assets/index-DpCQrQXd.css +0 -1
  1685. package/dist/outlook-ui/index.html +0 -15
  1686. package/dist/repertoire/tasks/board.js +0 -160
  1687. package/dist/repertoire/tasks/fix.js +0 -182
  1688. package/dist/repertoire/tasks/index.js +0 -228
  1689. package/dist/repertoire/tasks/lifecycle.js +0 -80
  1690. package/dist/repertoire/tasks/middleware.js +0 -65
  1691. package/dist/repertoire/tasks/parser.js +0 -174
  1692. package/dist/repertoire/tasks/scanner.js +0 -289
  1693. package/dist/repertoire/tasks/transitions.js +0 -128
  1694. package/dist/repertoire/tools-bluebubbles.js +0 -94
  1695. package/dist/senses/bluebubbles-client.js +0 -532
  1696. package/dist/senses/bluebubbles-entry.js +0 -13
  1697. package/dist/senses/bluebubbles-media.js +0 -339
  1698. package/dist/senses/bluebubbles-runtime-state.js +0 -109
  1699. package/dist/senses/bluebubbles.js +0 -1327
  1700. package/dist/senses/inner-dialog-worker.js +0 -154
  1701. package/dist/senses/inner-dialog.js +0 -739
  1702. package/subagents/README.md +0 -7
  1703. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  1704. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  1705. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  1706. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  1707. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  1708. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  1709. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  1710. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  1711. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  1712. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  1713. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  1714. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  1715. /package/dist/{repertoire/tasks/types.js → heart/attachments/sources/adapter.js} +0 -0
  1716. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  1717. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  1718. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  1719. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
  1720. /package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/store.js +0 -0
@@ -0,0 +1,1820 @@
1
+ #!/usr/local/bin/node
2
+ // Sanctuary Butler automated update path.
3
+ //
4
+ // One tool for the whole upgrade, built after a manual upgrade attempt took the
5
+ // household's Telegram bot down twice: once from a hand-rolled migration, once
6
+ // from a shipped-install defect discovered only AFTER the bot token had been
7
+ // revoked. The lesson both times was the same — verify the end state, and prove
8
+ // the upgrade can succeed BEFORE doing anything irreversible.
9
+ //
10
+ // Phases (each idempotent, each stops on the first failure):
11
+ // preflight read-only rehearsal. Proves the install can succeed and touches
12
+ // nothing. Its centerpiece is the fenced vault-read check (D-018):
13
+ // the exact operation that failed the last upgrade, run before the
14
+ // token is ever rotated.
15
+ // prepare extract the package, build the manifest + request, stage inputs,
16
+ // verify against the installer's own rules. Writes only to the
17
+ // authority staging area; the running Butler is untouched.
18
+ // install drive the DockerMan authority transaction to completion, with
19
+ // automatic rollback on ANY failure so the Butler is never left
20
+ // down. Requires a freshly rotated token at incoming-token.
21
+ // verify health + preservation (Jellyfin, steward policy) + readback.
22
+ // upgrade in-place upgrade of an INSTALLED authority (D-043): same epoch,
23
+ // token and cursor; new package, pins and resident image. The new
24
+ // package's own lifecycle does the work and rolls back exactly on
25
+ // any failure. `--rehearse <step>` stops after that step and rolls
26
+ // back, proving the rollback on real hardware. No token rotation.
27
+ //
28
+ // Run `preflight` and `prepare` freely. `install` is the first-install phase and
29
+ // refuses without a rotated incoming-token. Run `upgrade` detached so an SSH drop
30
+ // cannot interrupt it: setsid nohup node <this> upgrade <version> > /var/log/ouro-upgrade.log 2>&1 &
31
+ //
32
+ // An `upgrade` ends with the replay gate (sanctuary-replay-gate.mjs): the new Butler is held UNCOMMITTED (the lifecycle
33
+ // keeps its journal and the predecessor's records, because a committed upgrade cannot be rolled back), the gate replays
34
+ // real requests over A2A and reads the outcome back from machine state, and only a pass commits, pins the template and
35
+ // prunes images. A failed gate runs `upgrade-rollback`, confirms the predecessor is healthy, and exits 1.
36
+ // --no-gate skip the gate and commit straight away (emergencies; logged loudly)
37
+ // --plant <case> make that gate case fail on purpose, proving the rollback end to end
38
+ // verify --gate run the gate against the live version without upgrading
39
+ //
40
+ // A fresh install (a host that never ran a Butler) passes --fresh to preflight and prepare. prepare --fresh takes the
41
+ // bot id from Telegram getMe on the token already at incoming-token and the owner from --owner-id, and writes
42
+ // predecessorContract "none" into request.json; install, upgrade and verify read that contract from there.
43
+ //
44
+ // Usage: sanctuary-butler-upgrade.mjs <preflight|prepare|install|verify|upgrade> <version> [--rehearse <step>] [--no-gate] [--plant <case>]
45
+ // sanctuary-butler-upgrade.mjs preflight <version> --fresh
46
+ // sanctuary-butler-upgrade.mjs prepare <version> --fresh --owner-id <telegram user id>
47
+ // sanctuary-butler-upgrade.mjs verify [--gate]
48
+
49
+ import { execFileSync, spawn, spawnSync } from "node:child_process"
50
+ import { createHash, randomBytes } from "node:crypto"
51
+ import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync, statSync, lstatSync, chmodSync, realpathSync, readdirSync, openSync, closeSync, fchownSync, fchmodSync, fstatSync, readSync, renameSync, unlinkSync, constants as fsConstants } from "node:fs"
52
+ import { fileURLToPath } from "node:url"
53
+ import { createRequire } from "node:module"
54
+ import { tmpdir } from "node:os"
55
+ import { join } from "node:path"
56
+
57
+ const ROOT = "/mnt/user/appdata/ouro-authority"
58
+ // The host folder that holds the Butler's bundle. The live host's bundle stays sanctuary.ouro through the rename; only
59
+ // where it is mounted inside the container follows the Butler name the image runs (butlerNameFromEntrypoint).
60
+ const AGENT_DIR = "/mnt/user/appdata/ouro-butler/agent"
61
+ const RUNTIME = "/mnt/user/appdata/ouro-butler/runtime/.ouro-cli"
62
+ const CONTAINER = "ouro-butler"
63
+ const TEMPLATE = "/boot/config/plugins/dockerMan/templates-user/my-ouro-butler.xml"
64
+ const JOURNAL = "/boot/config/custom/ouro-butler/docker-man-template-transaction.json"
65
+ const PRIMITIVES = ["/usr/local/bin/node", "/bin/sh", "/usr/bin/prlimit", "/usr/bin/setsid"]
66
+ const REQUIRED_PROGRAMS = [
67
+ "dist/heart/daemon/sanctuary-telegram-authority-entry.js",
68
+ "dist/heart/daemon/sanctuary-authority-root-lifecycle.js",
69
+ "dist/heart/daemon/sanctuary-host-supervisor-entry.js",
70
+ "deploy/unraid/sanctuary-host-launcher.sh",
71
+ "deploy/unraid/sanctuary-authority-service.sh",
72
+ ]
73
+ const MIN_FREE_GB = 2
74
+ const INCOMING_MANIFEST = `${ROOT}/incoming-package-manifest.json`
75
+ const INCOMING_REQUEST = `${ROOT}/incoming-request.json`
76
+ const UPGRADE_JOURNAL = `${ROOT}/upgrade.json`
77
+ // Host supervision skips its work while this flag is fresh (< 30 min), so a crashed
78
+ // upgrade can never leave self-heal off for longer than that. A paused upgrade keeps it
79
+ // fresh with a heartbeat (holdSupervision), because the replay gate alone takes about an hour.
80
+ const MAINTENANCE = "/run/ouro-authority-maintenance"
81
+ // The stop hook's flag: every keeper watchdog version stands down while it exists.
82
+ const SHUTDOWN_FLAG = "/run/ouro-authority-shutdown"
83
+ const GATE_SCRIPT = `${ROOT}/package/deploy/unraid/sanctuary-replay-gate.mjs`
84
+ // The replay clients' seeds and provisioning record: a root-owned host folder outside the bundle, which the Butler's user cannot write.
85
+ const GATE_PROVISION = "/mnt/user/appdata/ouro-butler/replay-client/provision.json"
86
+ // The whole gate (every case, including the eight-minute await wait) must finish well inside this; a hung gate is a failed gate.
87
+ export const GATE_TIMEOUT_MS = 95 * 60 * 1000
88
+ const UPGRADE_STEPS = ["stop", "switch", "resident", "migrate", "start"]
89
+
90
+ const sh = (file, args, opts = {}) => execFileSync(file, args, { encoding: "utf8", maxBuffer: 64 << 20, ...opts })
91
+ const docker = (args, opts = {}) => sh("/usr/bin/docker", args, opts)
92
+ const image = (version) => `ghcr.io/ourostack/ouroboros-butler:${version}`
93
+
94
+ // ---- the Butler's name --------------------------------------------------------
95
+ // The Butler's names, as src/heart/butler-agent.ts has them. This script is staged on its own, so it carries the rule itself.
96
+ export const BUTLER_NAMES = ["butler", "sanctuary"]
97
+ /** The Butler an image runs, from its ENTRYPOINT: the argument after --package-managed-agent when it is a Butler name, otherwise sanctuary. */
98
+ export function butlerNameFromEntrypoint(entrypoint) {
99
+ if (!Array.isArray(entrypoint)) return "sanctuary"
100
+ const flag = entrypoint.indexOf("--package-managed-agent")
101
+ return flag >= 0 && BUTLER_NAMES.includes(entrypoint[flag + 1]) ? entrypoint[flag + 1] : "sanctuary"
102
+ }
103
+ /** The host bundle folder, by the name it has on disk, worked out at each use; sanctuary.ouro when neither or both are there. It never moves. */
104
+ export function hostBundle(exists = existsSync) {
105
+ const present = BUTLER_NAMES.filter((name) => exists(`${AGENT_DIR}/${name}.ouro`))
106
+ return `${AGENT_DIR}/${present.length === 1 ? present[0] : "sanctuary"}.ouro`
107
+ }
108
+ const policyFile = () => `${hostBundle()}/state/policy/steward.json`
109
+ /** Where a Butler of this name finds its bundle, its psyche and the operator trust inside its container. */
110
+ export const containerBundle = (name) => `/home/ouro/AgentBundles/${name}.ouro`
111
+ export const psycheTarget = (name) => `${containerBundle(name)}/psyche`
112
+ export const trustTarget = (name) => `/etc/ouro/trust/${name}`
113
+ /** The Butler name an image (a reference or an id) runs, read from its own config. */
114
+ function imageButlerName(reference) {
115
+ return butlerNameFromEntrypoint(JSON.parse(docker(["image", "inspect", "--format", "{{json .Config.Entrypoint}}", reference], { stdio: ["ignore", "pipe", "pipe"] })))
116
+ }
117
+ /** The Butler name the running resident's image runs. */
118
+ function liveButlerName() {
119
+ return imageButlerName(docker(["inspect", CONTAINER, "--format", "{{.Image}}"], { stdio: ["ignore", "pipe", "pipe"] }).trim())
120
+ }
121
+
122
+ // ---- a rename's predecessor ----------------------------------------------------
123
+ // What the running release must hold before an upgrade may change the Butler's name, as the root lifecycle has it
124
+ // (BUTLER_RENAME_PREDECESSOR_MARKERS): a rollback lands on that release, so it has to rewrite the bundle's container
125
+ // paths for a named Butler (#1983), and its daemon has to merge the other name's events and find an event Await's record
126
+ // under either name (M2 step 4b). Read as files, so a release is judged by what it can do, not by its version number.
127
+ export const BUTLER_RENAME_PREDECESSOR_MARKERS = [
128
+ ["deploy/unraid/migrate-sanctuary-bundle.mjs", "--butler-name"],
129
+ ["dist/heart/external-events/router.js", "externalEventAwaitRecordPath"],
130
+ ]
131
+ /** Null when an upgrade from Butler name `running` to `target` may go ahead; otherwise why not. `read(file)` is the running release's file, or null. */
132
+ export function renamePredecessorProblem(running, target, read) {
133
+ if (running === target) return null
134
+ const missing = BUTLER_RENAME_PREDECESSOR_MARKERS.filter(([file, marker]) => !(read(file) ?? "").includes(marker)).map(([file]) => file)
135
+ if (missing.length === 0) return null
136
+ return `this upgrade renames the Butler from ${running} to ${target}, but the running release cannot take a rollback across that rename (its ${missing.join(" and ")} predate it). Ship a release from after M2 step 4b ("Butler: what the rename needs first") with the name unchanged first, then the release that renames it`
137
+ }
138
+ /** The running release's file: from the installed package, or from the running image when no authority is installed yet. */
139
+ function runningReleaseFile(runningImage, file) {
140
+ try {
141
+ return existsSync(`${ROOT}/active.json`) ? readFileSync(`${ROOT}/package/${file}`, "utf8")
142
+ : docker(["run", "--rm", "--entrypoint", "/bin/cat", runningImage, `/opt/ouro/${file}`], { stdio: ["ignore", "pipe", "ignore"] })
143
+ } catch { return null }
144
+ }
145
+ function renamePredecessorIssue(version, runningImage) {
146
+ return renamePredecessorProblem(imageButlerName(runningImage), imageButlerName(image(version)), (file) => runningReleaseFile(runningImage, file))
147
+ }
148
+
149
+ // Unraid's cgroup2-unraid daemon watches /sys/fs/cgroup via inotify and rmdir's any
150
+ // cgroup that reports `populated 0`. The authority install creates its cgroup empty and
151
+ // keeps it empty through staging/verification (which asserts cgroup.procs === ""), so the
152
+ // reaper deletes /sys/fs/cgroup/ouro-authority within ~2s and stage fails ENOENT on
153
+ // cgroup.controllers. Pausing the reaper (SIGSTOP) lets the empty cgroup survive until the
154
+ // gateway process populates it; we always resume it (SIGCONT) afterwards.
155
+ let REAPER_PAUSED = false
156
+ function reaperPid() {
157
+ try { const p = readFileSync("/run/cgroup2-unraid.pid", "utf8").trim(); if (/^[0-9]+$/.test(p) && existsSync(`/proc/${p}`)) return p } catch { /* fall through */ }
158
+ try { const p = sh("/bin/sh", ["-c", "pgrep -f 'cgroup2-unraid --daemon' | head -1"]).trim(); return /^[0-9]+$/.test(p) ? p : null } catch { return null }
159
+ }
160
+ function pauseCgroupReaper() {
161
+ const pid = reaperPid()
162
+ if (!pid) { console.log(" note: cgroup2-unraid reaper not found; nothing to pause"); return }
163
+ try { sh("/bin/kill", ["-STOP", pid]); REAPER_PAUSED = true; ok(`paused cgroup2-unraid reaper (pid ${pid}) so the authority cgroup survives staging`) }
164
+ catch (e) { console.log(` note: could not pause cgroup2-unraid (${e.message}); install may fail on empty-cgroup reaping`) }
165
+ }
166
+ function resumeCgroupReaper() {
167
+ if (!REAPER_PAUSED) return
168
+ const pid = reaperPid()
169
+ if (pid) { try { sh("/bin/kill", ["-CONT", pid]); ok(`resumed cgroup2-unraid reaper (pid ${pid})`) } catch (e) { console.log(` WARN: failed to resume cgroup2-unraid (${e.message}); run: kill -CONT ${pid}`) } }
170
+ REAPER_PAUSED = false
171
+ }
172
+ const digest = (b) => `sha256:${createHash("sha256").update(b).digest("hex")}`
173
+
174
+ let RED = 0
175
+ const ok = (m) => console.log(` ok ${m}`)
176
+ const bad = (m) => { console.log(` FAIL ${m}`); RED += 1 }
177
+ const say = (m) => console.log(`\n== ${m}`)
178
+
179
+ function requireRoot() {
180
+ if (process.getuid() !== 0) { console.error("must run as root"); process.exit(2) }
181
+ }
182
+
183
+ function imageId(version) {
184
+ try { return docker(["image", "inspect", image(version), "--format", "{{.Id}}"], { stdio: ["ignore", "pipe", "ignore"] }).trim() }
185
+ catch { return null }
186
+ }
187
+
188
+ // ---- read-only rehearsal --------------------------------------------------
189
+
190
+ function preflight(version, { fresh = false } = {}) {
191
+ say(`preflight for ${version}${fresh ? " (fresh install)" : ""} (read-only; nothing is changed)`)
192
+
193
+ say("target image present and pulled")
194
+ let id = imageId(version)
195
+ if (!id) { try { docker(["pull", image(version)]); id = imageId(version) } catch { /* reported below */ } }
196
+ id ? ok(`image ${id.slice(0, 19)}…`) : bad(`image ${image(version)} not present and could not be pulled`)
197
+
198
+ say(fresh ? "no Butler on this host yet" : "running Butler and rollback material")
199
+ let runningImage = null
200
+ if (fresh) {
201
+ containerExists(CONTAINER) ? bad(`an ${CONTAINER} container already exists; a fresh install needs a host without one`) : ok(`no ${CONTAINER} container`)
202
+ existsSync(`${ROOT}/active.json`) ? bad("an authority is installed; this host is not fresh") : ok("no installed authority")
203
+ } else try {
204
+ runningImage = docker(["inspect", CONTAINER, "--format", "{{.Image}}"], { stdio: ["ignore", "pipe", "ignore"] }).trim()
205
+ ok(`running image ${runningImage.slice(0, 19)}… (this is the rollback target)`)
206
+ } catch { bad(`the ${CONTAINER} container is absent`) }
207
+ if (id && runningImage && id === runningImage) bad("target and running image are identical — nothing to upgrade")
208
+
209
+ const installed = !fresh && existsSync(`${ROOT}/active.json`)
210
+ if (installed) console.log(" note: an authority is installed, so this is an in-place upgrade (run `upgrade`, no token rotation)")
211
+
212
+ say("no stale authority runtime state")
213
+ if (!installed) {
214
+ const stale = ["/sys/fs/cgroup/ouro-authority", "/var/lib/ouro-authority", "/run/ouro-authority", `${ROOT}/epochs`].filter((d) => existsSync(d))
215
+ if (stale.length && !existsSync(`${ROOT}/active.json`)) console.log(` note: stale dirs present, install will clear them: ${stale.join(", ")}`)
216
+ else if (!stale.length) ok("no stale authority runtime dirs")
217
+ else bad(`stale dirs present with a live authority: ${stale.join(", ")}`)
218
+ }
219
+
220
+ say("no upgrade already in flight")
221
+ existsSync(JOURNAL) ? bad(`a template transaction journal is pending at ${JOURNAL}; resolve it first`) : ok("no pending template transaction")
222
+ if (installed) existsSync(UPGRADE_JOURNAL) ? console.log(" note: an in-place upgrade is pending; `upgrade` resumes it") : ok("no pending in-place upgrade")
223
+ if (installed && existsSync(`${ROOT}/incoming-token`)) console.log(" note: a stale incoming-token copy is present; the upgrade removes it (D-044)")
224
+
225
+ say("host primitives (root-owned, not group/world-writable)")
226
+ for (const f of PRIMITIVES) {
227
+ try {
228
+ const [uid, gid, mode] = sh("/usr/bin/stat", ["-Lc", "%u %g %a", f]).trim().split(" ")
229
+ if (uid === "0" && gid === "0" && (parseInt(mode, 8) & 0o022) === 0) ok(`${f} ${uid}:${gid} ${mode}`)
230
+ else bad(`${f} is ${uid}:${gid} ${mode} — must be root-owned and not group/world-writable`)
231
+ } catch { bad(`${f} is missing`) }
232
+ }
233
+
234
+ say("delegated-command grants the Butler will still honour")
235
+ {
236
+ const friendRecords = {}
237
+ try {
238
+ const friends = `${hostBundle()}/friends`
239
+ for (const file of readdirSync(friends).filter((name) => name.endsWith(".json"))) {
240
+ try { friendRecords[file.replace(/\.json$/u, "")] = JSON.parse(readFileSync(`${friends}/${file}`, "utf8")) } catch { /* unreadable record: not a grant source */ }
241
+ }
242
+ } catch { /* no friends folder yet */ }
243
+ let trustedGrants = {}
244
+ try { trustedGrants = JSON.parse(readFileSync(`${TRUST_HOST_DIR}/delegated-command-grants.json`, "utf8")).grants ?? {} } catch { /* no trusted grants yet */ }
245
+ const warnings = legacyDelegationGrantWarnings(friendRecords, trustedGrants)
246
+ warnings.length === 0 ? ok("no friend record relies on the old delegationGrant") : warnings.forEach((line) => console.log(` WARNING: ${line}`))
247
+ }
248
+
249
+ say("escalation holders the upgrade would drop")
250
+ {
251
+ // The grant command is run against the Butler that is running now, under its name.
252
+ let name = "sanctuary"
253
+ try { if (runningImage) name = imageButlerName(runningImage) } catch { /* reported with the default name */ }
254
+ const dropped = escalationGrantProblems(name)
255
+ dropped.length === 0 ? ok("every escalation holder in the bundle is already in the trusted file") : dropped.forEach((line) => bad(line))
256
+ }
257
+
258
+ say("a rollback can undo a change of the Butler's name")
259
+ if (id && runningImage) {
260
+ try {
261
+ const issue = renamePredecessorIssue(version, runningImage)
262
+ issue ? bad(issue) : ok("the name stays the same, or the running release can take a rollback across the rename")
263
+ } catch (e) { bad(`could not check the Butler's name: ${String(e.message).split("\n")[0]}`) }
264
+ } else if (!fresh) bad("skipped (no image or no running Butler)")
265
+ else ok("not needed: a fresh install has nothing to roll back to")
266
+
267
+ say("no credential handoff left for another Butler name")
268
+ if (id) {
269
+ try {
270
+ const issue = credentialHandoffIssue(imageButlerName(image(version)))
271
+ issue ? bad(issue) : ok("no container-credentials handoff names another agent")
272
+ } catch (e) { bad(`could not check the credential handoff: ${String(e.message).split("\n")[0]}`) }
273
+ } else bad("skipped (no image)")
274
+
275
+ say("required programs in the target image")
276
+ try {
277
+ const missing = REQUIRED_PROGRAMS.filter((p) => {
278
+ try { docker(["run", "--rm", "--entrypoint", "/bin/sh", image(version), "-c", `test -f /opt/ouro/${p}`]); return false }
279
+ catch { return true }
280
+ })
281
+ missing.length ? bad(`image is missing: ${missing.join(", ")}`) : ok(`all ${REQUIRED_PROGRAMS.length} authority programs present`)
282
+ } catch { bad("could not inspect the image contents") }
283
+
284
+ say("D-018: the fenced vault read the install depends on")
285
+ if (installed) ok("not needed: the installed gateway already holds the token in root custody")
286
+ else if (fresh) ok("not needed: a fresh install hands the new token straight to the root authority")
287
+ else if (id) {
288
+ // Run the read fenced exactly as THIS version's install will fence it, so
289
+ // the rehearsal is faithful: an unfixed image is tested without the fix and
290
+ // correctly fails here rather than during a real install.
291
+ const hasFix = targetHasVaultFix(version)
292
+ console.log(` note: target ${hasFix ? "carries" : "does NOT carry"} the D-018 fenced-read fix`)
293
+ try {
294
+ const out = JSON.parse(fencedVaultRead(version, hasFix))
295
+ out.tokenPresent === true
296
+ ? ok("fenced root vault read works with this image's own fencing")
297
+ : bad(`fenced vault read returned ${JSON.stringify(out)} — expected {tokenPresent:true}`)
298
+ } catch (e) {
299
+ bad(`fenced vault read FAILED: ${String(e.message).split("\n")[0]} — this image cannot read its own credentials; installing it would strand Telegram (this is exactly what happened on the last upgrade)`)
300
+ }
301
+ } else bad("skipped (no image)")
302
+
303
+ say("disk headroom")
304
+ try {
305
+ const freeKb = Number(sh("/bin/df", ["-Pk", "/mnt/user/appdata"]).trim().split("\n").at(-1).split(/\s+/)[3])
306
+ const freeGb = freeKb / 1024 / 1024
307
+ freeGb >= MIN_FREE_GB ? ok(`${freeGb.toFixed(1)} GB free on appdata`) : bad(`only ${freeGb.toFixed(1)} GB free (want ≥ ${MIN_FREE_GB})`)
308
+ } catch { bad("could not read disk free space") }
309
+
310
+ say("preservation baselines readable")
311
+ const policy = policyFile()
312
+ existsSync(policy) ? ok(`steward policy present (${sha12(policy)})`) : fresh ? ok("no steward policy yet (fresh install)") : bad(`steward policy missing at ${policy}`)
313
+
314
+ say("the DockerMan template can follow this image's Butler name")
315
+ if (id) {
316
+ try {
317
+ const problem = templatePinProblem(version)
318
+ problem ? bad(problem) : ok(`the DockerMan template can pin ${image(version)}`)
319
+ } catch (e) { bad(`could not check the DockerMan template: ${String(e.message).split("\n")[0]}`) }
320
+ } else bad("skipped (no image)")
321
+ try { ok(jellyfinState() ? "jellyfin inspectable for the unchanged-check" : "no jellyfin container; it must stay absent") }
322
+ catch { bad("docker could not list or inspect the jellyfin container") }
323
+
324
+ console.log("")
325
+ if (RED === 0) console.log(installed ? "PREFLIGHT GREEN — run `upgrade` (detached)." : fresh ? "PREFLIGHT GREEN — next: put the bot token at incoming-token, prepare --fresh, install." : "PREFLIGHT GREEN — the upgrade can proceed. Next: prepare, rotate the token, install.")
326
+ else console.log(`PREFLIGHT RED — ${RED} blocker(s) above. Nothing was changed; fix these before rotating the token.`)
327
+ process.exit(RED === 0 ? 0 : 1)
328
+ }
329
+
330
+ // Does the target image's own #vault carry the D-018 fix? Read it from the image
331
+ // so the rehearsal fences the read the same way the real install will.
332
+ function targetHasVaultFix(version) {
333
+ try {
334
+ const src = docker(["run", "--rm", "--entrypoint", "/bin/cat", image(version),
335
+ "/opt/ouro/dist/heart/daemon/sanctuary-authority-root-lifecycle.js"], { stdio: ["ignore", "pipe", "ignore"] })
336
+ return src.includes("--cap-add=DAC_OVERRIDE") && src.includes("/home/ouro/.bw-src")
337
+ } catch { return false }
338
+ }
339
+
340
+ const CLI = "/opt/ouro/dist/heart/daemon/sanctuary-authority-root-lifecycle.js"
341
+ // The fenced vault read, replicating the target version's own #vault fencing.
342
+ function fencedVaultRead(version, hasFix) {
343
+ const bundleMount = `type=bind,src=${hostBundle()},dst=${containerBundle(imageButlerName(image(version)))},readonly`
344
+ const base = ["run", "--rm", "-i", "--pull=never", "--network", "host", "--user", "0:0", "--read-only",
345
+ "--cap-drop=ALL", "--security-opt=no-new-privileges"]
346
+ const args = hasFix
347
+ ? [...base, "--cap-add=DAC_OVERRIDE", "--entrypoint", "/bin/sh",
348
+ "--mount", `type=bind,src=${RUNTIME},dst=/home/ouro/.ouro-cli,readonly`,
349
+ "--mount", `type=bind,src=${RUNTIME}/bitwarden,dst=/home/ouro/.bw-src,readonly`,
350
+ "--mount", bundleMount,
351
+ "--tmpfs", "/home/ouro/.ouro-cli/bitwarden:rw,nosuid,nodev,noexec,mode=0700",
352
+ "--tmpfs", "/home/ouro/.config:rw,nosuid,nodev,noexec,mode=0700",
353
+ "--tmpfs", "/tmp:rw,nosuid,nodev,noexec,mode=0700",
354
+ image(version), "-c", `cp -r /home/ouro/.bw-src/. /home/ouro/.ouro-cli/bitwarden/ && exec /usr/local/bin/node ${CLI} vault presence`]
355
+ : [...base, "--entrypoint", "/usr/local/bin/node",
356
+ "--mount", `type=bind,src=${RUNTIME},dst=/home/ouro/.ouro-cli,readonly`,
357
+ "--mount", bundleMount,
358
+ "--tmpfs", "/home/ouro/.ouro-cli/bitwarden:rw,nosuid,nodev,noexec,mode=0700",
359
+ "--tmpfs", "/tmp:rw,nosuid,nodev,noexec,mode=0700",
360
+ image(version), CLI, "vault", "presence"]
361
+ return docker(args, { stdio: ["pipe", "pipe", "pipe"], input: "" })
362
+ }
363
+
364
+ function sha12(path) { return digest(readFileSync(path)).slice(7, 19) }
365
+
366
+ // ---- fresh install helpers (a host with no predecessor Butler) -------------
367
+
368
+ /** The root request for a fresh install: the bot comes from Telegram getMe on the new token, the owner from the installer. */
369
+ export function freshInstallRequest({ epochId, botId, ownerId, pins }) {
370
+ if (!/^[1-9][0-9]*$/u.test(String(botId))) throw new Error("the bot id from Telegram is invalid")
371
+ if (!/^[1-9][0-9]*$/u.test(String(ownerId))) throw new Error("the owner's Telegram id must be a positive number")
372
+ return { schemaVersion: 1, epochId, botId: String(botId), ownerUserId: String(ownerId), ownerChatId: String(ownerId), ...pins, predecessorContract: "none" }
373
+ }
374
+ /** The bot id a Telegram getMe answer names, checked against the token's own prefix. */
375
+ export function botIdFromGetMe(body, token) {
376
+ const id = body?.ok === true && Number.isSafeInteger(body.result?.id) ? String(body.result.id) : null
377
+ if (!id) throw new Error("Telegram did not accept the bot token (getMe failed)")
378
+ if (String(token).split(":")[0] !== id) throw new Error("the bot token does not belong to the bot Telegram names")
379
+ return id
380
+ }
381
+ /** The incoming request for an in-place upgrade: the same identity, new pins, and a fresh install's contract carried forward. */
382
+ export function upgradeRequest(current, pins) {
383
+ return {
384
+ schemaVersion: 1, epochId: current.epochId, botId: current.botId, ownerUserId: current.ownerUserId, ownerChatId: current.ownerChatId, ...pins,
385
+ ...(current.predecessorContract === "none" ? { predecessorContract: "none" } : {}),
386
+ }
387
+ }
388
+ /** Whether a preserved file stayed as it was; one that was absent before had nothing to preserve. */
389
+ export function unchanged(before, after) { return before === null || before === after }
390
+ function containerExists(name) { return docker(["container", "ls", "--all", "--quiet", "--filter", `name=^/${name}$`]).trim() !== "" }
391
+ /** Jellyfin's identity for the unchanged-check, or null on a host without Jellyfin (it must then stay absent). */
392
+ function jellyfinState() {
393
+ return containerExists("jellyfin") ? docker(["inspect", "jellyfin", "--format", "{{.Id}}|{{.Image}}|{{.RestartCount}}|{{.State.StartedAt}}"]).trim() : null
394
+ }
395
+ function policyState() { const policy = policyFile(); return existsSync(policy) ? sha12(policy) : null }
396
+ function installedRequest() { try { return JSON.parse(readFileSync(`${ROOT}/request.json`, "utf8")) } catch { return null } }
397
+
398
+ // ---- prepare (idempotent staging; running Butler untouched) ---------------
399
+
400
+ async function prepare(version, { fresh = false, ownerId } = {}) {
401
+ say(`prepare inputs for ${version}${fresh ? " (fresh install)" : ""}`)
402
+ const id = imageId(version)
403
+ if (!id) fail(`image ${image(version)} is not present; pull it first`)
404
+ if (existsSync(`${ROOT}/active.json`)) fail("an authority is installed; use `upgrade` (in place, no token rotation) instead of prepare/install")
405
+ let botId = null
406
+ if (fresh) {
407
+ if (containerExists(CONTAINER)) fail(`an ${CONTAINER} container already exists; a fresh install needs a host without one`)
408
+ const tokenPath = `${ROOT}/incoming-token`
409
+ if (!existsSync(tokenPath) || statSync(tokenPath).size === 0) fail(`no bot token at ${tokenPath}; the installer puts it there first`)
410
+ const token = readFileSync(tokenPath, "utf8").trim()
411
+ const body = await fetch(`https://api.telegram.org/bot${token}/getMe`).then((response) => response.json()).catch(() => null)
412
+ try { botId = botIdFromGetMe(body, token) } catch (error) { fail(error.message) }
413
+ ok(`Telegram knows the bot (id ${botId})`)
414
+ }
415
+ const epochId = `${version.replace(/[^A-Za-z0-9_-]/g, "-")}-${new Date().toISOString().slice(0, 10).replace(/-/g, "")}`
416
+ const manifestBytes = stageIncomingPackage(version)
417
+ writePrivate(`${ROOT}/package-manifest.json`, manifestBytes)
418
+ let request
419
+ if (fresh) {
420
+ try { request = freshInstallRequest({ epochId, botId, ownerId, pins: packagePins(manifestBytes) }) } catch (error) { fail(error.message) }
421
+ } else {
422
+ const creds = JSON.parse(readFileSync(`/mnt/user/appdata/ouro-butler/runtime/container-credentials.json`, "utf8")).credentials[0].runtimeConfig
423
+ request = {
424
+ schemaVersion: 1, epochId,
425
+ botId: String(creds.telegramBotToken).split(":")[0],
426
+ ownerUserId: String(creds.telegramAuthorizedUserId), ownerChatId: String(creds.telegramAuthorizedChatId),
427
+ ...packagePins(manifestBytes),
428
+ }
429
+ }
430
+ if (request.ownerUserId !== request.ownerChatId) fail("owner user and chat must match")
431
+ writePrivate(`${ROOT}/request.json`, Buffer.from(JSON.stringify(request)))
432
+ ok(`epoch ${epochId}, package ${request.packageDigest.slice(7, 19)}…`)
433
+
434
+ say("verify the prepared package against the installer's own rules")
435
+ verifyPackage(`${ROOT}/incoming-package`, `${ROOT}/package-manifest.json`, `${ROOT}/request.json`)
436
+ ok("package verifies")
437
+
438
+ console.log(fresh ? "\nPREPARE done. Next: install." : "\nPREPARE done. Next: rotate the bot token into ${ROOT}/incoming-token, then install.".replace("${ROOT}", ROOT))
439
+ }
440
+
441
+ // The package digest plus the host primitive pins every request carries.
442
+ function packagePins(manifestBytes) {
443
+ const d = (f) => digest(readFileSync(f))
444
+ return {
445
+ packageDigest: digest(manifestBytes),
446
+ nodeDigest: d("/usr/local/bin/node"), prlimitDigest: d("/usr/bin/prlimit"),
447
+ setsidDigest: d("/usr/bin/setsid"), shellDigest: d(sh("/bin/readlink", ["-f", "/bin/sh"]).trim()),
448
+ }
449
+ }
450
+
451
+ // Extract the exact package from the image into incoming-package, normalised to the
452
+ // installer's rules, and return its manifest bytes. The running Butler is untouched.
453
+ function stageIncomingPackage(version) {
454
+ const incoming = `${ROOT}/incoming-package`
455
+
456
+ say("extract the exact package from the image")
457
+ sh("/bin/rm", ["-rf", incoming]); sh("/bin/mkdir", ["-p", incoming])
458
+ const cid = docker(["create", "--entrypoint", "/bin/sh", image(version)]).trim()
459
+ try { docker(["cp", `${cid}:/opt/ouro/.`, `${incoming}/`]) } finally { docker(["rm", "-f", cid]) }
460
+ ok(`extracted ${sh("/usr/bin/find", [incoming, "-type", "f"]).trim().split("\n").length} files`)
461
+
462
+ say("normalise: drop symlinks, root-own, dirs 700, files 644/755, break hard links")
463
+ sh("/usr/bin/find", [incoming, "-type", "l", "-delete"])
464
+ sh("/bin/chown", ["-R", "0:0", incoming])
465
+ sh("/usr/bin/find", [incoming, "-type", "d", "-exec", "chmod", "700", "{}", "+"])
466
+ sh("/bin/sh", ["-c", `find ${incoming} -type f ! -perm 755 -exec chmod 644 {} +`])
467
+ const linked = sh("/bin/sh", ["-c", `find ${incoming} -type f -links +1 | wc -l`]).trim()
468
+ if (linked !== "0") sh("/bin/sh", ["-c", `find ${incoming} -type f -links +1 -exec sh -c 'cp -p "$1" "$1.u" && mv -f "$1.u" "$1"' _ {} \\;`])
469
+ ok("normalised")
470
+
471
+ say("required programs survived")
472
+ for (const p of REQUIRED_PROGRAMS) if (!existsSync(`${incoming}/${p}`)) fail(`missing after normalise: ${p}`)
473
+ ok("all present")
474
+
475
+ say("build package manifest + request")
476
+ const files = {}
477
+ const allowed = new Set([0o600, 0o644, 0o700, 0o755])
478
+ const walk = (rel) => {
479
+ for (const entry of sh("/bin/sh", ["-c", `cd ${incoming} && find ${rel || "."} -maxdepth 1 -mindepth 1 -printf '%y %f\n'`]).trim().split("\n").filter(Boolean)) {
480
+ const [type, ...nameParts] = entry.split(" "); const name = (rel ? `${rel}/` : "") + nameParts.join(" ")
481
+ if (type === "d") walk(name)
482
+ else if (type === "f") {
483
+ const mode = parseInt(sh("/usr/bin/stat", ["-c", "%a", `${incoming}/${name}`]).trim(), 8)
484
+ if (!allowed.has(mode)) fail(`mode ${mode.toString(8)} not allowed: ${name}`)
485
+ files[name] = { digest: digest(readFileSync(`${incoming}/${name}`)), mode }
486
+ }
487
+ }
488
+ }
489
+ walk("")
490
+ ok(`${Object.keys(files).length} files pinned`)
491
+ return Buffer.from(JSON.stringify({ schemaVersion: 1, files }))
492
+ }
493
+
494
+ function writePrivate(path, bytes) { writeFileSync(path, bytes, { mode: 0o600 }); sh("/bin/chown", ["0:0", path]); chmodSync(path, 0o600) }
495
+
496
+ // A faithful re-check of the installer's verifySanctuaryAuthorityInstallation
497
+ // package rules, so prepare fails loudly rather than the install failing late.
498
+ function verifyPackage(pkg, manifestPath, requestPath) {
499
+ const canonical = (p) => { if (sh("/bin/readlink", ["-f", p]).trim() !== p) fail(`not canonical: ${p}`) }
500
+ const dirMode = (p) => parseInt(sh("/usr/bin/stat", ["-c", "%a", p]).trim(), 8)
501
+ canonical(pkg); if (dirMode(pkg) !== 0o700) fail(`package root must be 0700, is ${dirMode(pkg).toString(8)}`)
502
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"))
503
+ const request = JSON.parse(readFileSync(requestPath, "utf8"))
504
+ if (digest(readFileSync(manifestPath)) !== request.packageDigest) fail("manifest digest != request.packageDigest")
505
+ const allowed = new Set([0o600, 0o644, 0o700, 0o755])
506
+ for (const [rel, pin] of Object.entries(manifest.files)) {
507
+ if (!/^[A-Za-z0-9_@.-]+(?:\/[A-Za-z0-9_@.-]+)*$/.test(rel)) fail(`bad path: ${rel}`)
508
+ if (!allowed.has(pin.mode)) fail(`bad mode pin: ${rel}`)
509
+ if (digest(readFileSync(`${pkg}/${rel}`)) !== pin.digest) fail(`digest changed: ${rel}`)
510
+ }
511
+ for (const p of REQUIRED_PROGRAMS) if (!manifest.files[p]) fail(`manifest missing program: ${p}`)
512
+ const prim = (f, want) => { const st = sh("/usr/bin/stat", ["-Lc", "%u %g %a", f]).trim().split(" "); if (!(st[0] === "0" && st[1] === "0" && (parseInt(st[2], 8) & 0o022) === 0 && digest(readFileSync(f)) === want)) fail(`host primitive pin would fail: ${f}`) }
513
+ prim("/usr/local/bin/node", request.nodeDigest); prim(sh("/bin/readlink", ["-f", "/bin/sh"]).trim(), request.shellDigest)
514
+ prim("/usr/bin/prlimit", request.prlimitDigest); prim("/usr/bin/setsid", request.setsidDigest)
515
+ }
516
+
517
+ // ---- install (the one destructive phase; auto-rolls-back on any failure) --
518
+
519
+ function tx(op, extra = []) {
520
+ const driver = `${ROOT}/incoming-package/deploy/unraid/docker-man-template-transaction.mjs`
521
+ try {
522
+ return sh("/usr/local/bin/node", [driver, op, ...extra], { stdio: ["pipe", "pipe", "pipe"] })
523
+ } catch (e) {
524
+ // Surface the transaction's real stderr/stdout, not just "Command failed".
525
+ const detail = [e.stderr, e.stdout].map((x) => (x ? String(x).trim() : "")).filter(Boolean).join("\n")
526
+ throw new Error(`${op} failed:\n${detail || e.message}`)
527
+ }
528
+ }
529
+
530
+ const AUTOSTART_FILE = "/var/lib/docker/unraid-autostart"
531
+ let RESIDENT_AUTOSTART_LINE = "ouro-butler 0"
532
+ const AUTOSTART_RE = /^ouro-butler(?:-rollback|-staging|-legacy-evidence)?(?:\s|$)/u
533
+ // configure-resident/#configured require the resident to be ABSENT from Unraid's direct
534
+ // autostart during the handoff (the authority controls its start, not Unraid boot). The
535
+ // final commit proof then requires it PRESENT. So we disable it before authority-activate
536
+ // and re-enable it before commit. #directAutostartDisabled also requires the file be
537
+ // root:root 0644, which we preserve.
538
+ function disableResidentAutostart() {
539
+ if (!existsSync(AUTOSTART_FILE)) return
540
+ const lines = readFileSync(AUTOSTART_FILE, "utf8").split("\n")
541
+ const found = lines.find((l) => AUTOSTART_RE.test(l))
542
+ if (found) RESIDENT_AUTOSTART_LINE = found
543
+ writeFileSync(AUTOSTART_FILE, lines.filter((l) => !AUTOSTART_RE.test(l)).join("\n"))
544
+ sh("/bin/chown", ["0:0", AUTOSTART_FILE]); chmodSync(AUTOSTART_FILE, 0o644)
545
+ ok("disabled ouro-butler direct autostart for the authority handoff")
546
+ }
547
+ function enableResidentAutostart() {
548
+ const lines = existsSync(AUTOSTART_FILE) ? readFileSync(AUTOSTART_FILE, "utf8").split("\n").filter((l) => l.length) : []
549
+ if (!lines.some((l) => AUTOSTART_RE.test(l))) lines.push(RESIDENT_AUTOSTART_LINE)
550
+ writeFileSync(AUTOSTART_FILE, lines.join("\n") + "\n")
551
+ sh("/bin/chown", ["0:0", AUTOSTART_FILE]); chmodSync(AUTOSTART_FILE, 0o644)
552
+ ok("re-enabled ouro-butler direct autostart")
553
+ }
554
+
555
+ // Recreate the resident container into the tokenless, gateway-mounted target form that
556
+ // #configure/#target require. Nothing in the authority transaction does this — on Unraid it
557
+ // is a DockerMan "Apply" of the swapped template. We perform the equivalent here, matching
558
+ // what DockerMan produces (managed label + icon + the template's mounts) so start-resident,
559
+ // verify-install and the final commit proof are all satisfied. The container is created
560
+ // stopped; start-resident starts it. #target asserts: target image, user 10001:10001, no
561
+ // token env, exactly one read-only /run/ouro-authority mount, no docker.sock/${ROOT} mounts.
562
+ // Operator-set grants (delegated commands, escalation) live outside the bundle, in a root-owned host directory mounted
563
+ // read-only at /etc/ouro/trust/<the image's Butler name>. The bundle's recursive chown cannot reach it, and the resident cannot write it.
564
+ // The host directory keeps its name whatever the Butler is called.
565
+ export const TRUST_HOST_DIR = "/mnt/user/appdata/ouro-butler/trust/sanctuary"
566
+ export const trustMount = (name) => `type=bind,src=${TRUST_HOST_DIR},dst=${trustTarget(name)},readonly`
567
+ // The bundle sync deploy key: root places it on the host, and the Butler reads it through a read-only mount. The key can
568
+ // push to the owner's repo, so nothing inside the Butler can write the mount.
569
+ export const SYNC_HOST_DIR = "/mnt/user/appdata/ouro-butler/sync"
570
+ export const SYNC_TARGET = "/run/ouro-sync"
571
+ export const SYNC_MOUNT = `${SYNC_HOST_DIR}:${SYNC_TARGET}:ro`
572
+
573
+ /** What is wrong with a host trust directory's stat, or null when it is a real root-owned directory closed to group and other writes. */
574
+ export function trustDirIssue(stat) {
575
+ if (stat.isSymbolicLink()) return `${TRUST_HOST_DIR} is a symlink`
576
+ if (!stat.isDirectory()) return `${TRUST_HOST_DIR} is not a directory`
577
+ if (stat.uid !== 0) return `${TRUST_HOST_DIR} must be owned by root`
578
+ if ((stat.mode & 0o022) !== 0) return `${TRUST_HOST_DIR} is writable by group or other`
579
+ return null
580
+ }
581
+
582
+ // Creates the host trust directory root-owned 0755 when it is missing; refuses one the resident could have made.
583
+ function ensureTrustHostDir() {
584
+ if (!existsSync(TRUST_HOST_DIR)) {
585
+ sh("/bin/mkdir", ["-p", TRUST_HOST_DIR])
586
+ sh("/bin/chown", ["-h", "0:0", TRUST_HOST_DIR])
587
+ chmodSync(TRUST_HOST_DIR, 0o755)
588
+ }
589
+ const issue = trustDirIssue(lstatSync(TRUST_HOST_DIR))
590
+ if (issue) fail(`${issue}; fix it as root before the upgrade`)
591
+ }
592
+
593
+ /** What is wrong with the resident's trust mount, from `docker inspect` Mounts, or null when it is the read-only host directory. */
594
+ export function trustMountIssue(mounts, name = "sanctuary") {
595
+ const mount = (Array.isArray(mounts) ? mounts : []).find((entry) => entry?.Destination === trustTarget(name))
596
+ if (!mount) return "the operator trust directory is not mounted in the resident, so no grant would be honoured"
597
+ if (mount.Source !== TRUST_HOST_DIR) return `the operator trust directory is mounted from ${mount.Source}, not the root-owned host directory`
598
+ return mount.RW === false ? null : "the operator trust directory is mounted read-write in the resident"
599
+ }
600
+
601
+ /** Friends whose records still carry the old delegationGrant but have no trusted grant: the record is now only a hint, so they are refused. */
602
+ export function legacyDelegationGrantWarnings(friendRecords, trustedGrants) {
603
+ return Object.entries(friendRecords)
604
+ .filter(([id, record]) => record?.delegationGrant && !(id in trustedGrants))
605
+ .map(([id, record]) => `${record.name ?? id} (${id}) has a delegationGrant on its friend record that is no longer honoured; grant it with \`ouro a2a delegated-commands grant --friend ${id} --did <did:key>\` as root`)
606
+ }
607
+
608
+ /**
609
+ * Escalation holders the old harness honoured (the bundle's state/a2a/escalation-grants.json) that the trusted file does not list. The
610
+ * upgrade never copies a grant out of the bundle, so each of these loses the escalation grant until the operator re-grants it.
611
+ */
612
+ export function legacyEscalationGrantProblems(legacyGrants, trustedGrants, name = "sanctuary") {
613
+ return Object.entries(legacyGrants ?? {})
614
+ .filter(([id]) => !(id in (trustedGrants ?? {})))
615
+ .map(([id, grant]) => `escalation holder ${id} is in the bundle's state/a2a/escalation-grants.json but not in ${TRUST_HOST_DIR}/escalation-grants.json, so the upgrade would drop it; grant it as root first with \`ouro a2a escalation grant --agent ${name} --friend ${id} --did ${typeof grant?.did === "string" ? grant.did : "<did:key>"}\` (the one-off container form is in deploy/unraid/README.txt)`)
616
+ }
617
+
618
+ /** Reads the legacy bundle file and the trusted file from the host and returns the holders the upgrade would drop. */
619
+ function escalationGrantProblems(name) {
620
+ const read = (file) => { try { return JSON.parse(readFileSync(file, "utf8")).grants ?? {} } catch { return {} } }
621
+ return legacyEscalationGrantProblems(read(`${hostBundle()}/state/a2a/escalation-grants.json`), read(`${TRUST_HOST_DIR}/escalation-grants.json`), name)
622
+ }
623
+
624
+ /**
625
+ * What is wrong with a leftover container-credentials handoff (the file, or its `.consuming` claim) for a Butler of this
626
+ * name: one naming any other agent makes the daemon refuse to start (container-credential-bootstrap.ts). Null when there is
627
+ * none or every one names this Butler. `read` returns a file's text, or null when it is absent.
628
+ */
629
+ export function credentialHandoffIssue(name, read = (file) => (existsSync(file) ? readFileSync(file, "utf8") : null)) {
630
+ for (const file of [`${RUNTIME}/container-credentials.json`, `${RUNTIME}/container-credentials.json.consuming`]) {
631
+ const text = read(file)
632
+ if (text === null) continue
633
+ let agents
634
+ try { agents = JSON.parse(text).credentials.map((message) => message?.agentName) } catch { return `${file} cannot be read as a credential handoff; quarantine it before the upgrade` }
635
+ const other = agents.find((agent) => agent !== name)
636
+ if (other !== undefined) return `${file} names ${JSON.stringify(other)}, not ${name}, so the new Butler would refuse to start; quarantine it before the upgrade`
637
+ }
638
+ return null
639
+ }
640
+
641
+ function recreateResident(version) {
642
+ say("recreate resident container (tokenless, gateway socket mounted)")
643
+ disableResidentAutostart()
644
+ ensureTrustHostDir()
645
+ const icon = "https://raw.githubusercontent.com/ourostack/ouroboros/main/assets/ouroboros.png"
646
+ // The image names where the bundle and trust are mounted; the host folders stay. --mount refuses a missing source,
647
+ // where -v would have Docker create an empty folder in its place. Read the name before the resident goes, so a failed
648
+ // inspect leaves it standing.
649
+ const name = imageButlerName(image(version))
650
+ docker(["rm", "-f", CONTAINER], { stdio: "ignore" })
651
+ docker(["create", "--name", CONTAINER, "--network", "host", "--restart", "unless-stopped", "--user", "10001:10001",
652
+ "-l", "net.unraid.docker.managed=dockerman",
653
+ "-l", `net.unraid.docker.icon=${icon}`,
654
+ "-l", "org.opencontainers.image.source=https://github.com/ourostack/ouroboros",
655
+ "-v", "/mnt/user/appdata/ouro-butler/runtime/.ouro-cli:/home/ouro/.ouro-cli:rw",
656
+ "--mount", `type=bind,src=${hostBundle()},dst=${containerBundle(name)}`,
657
+ "-v", "/boot/config/custom/ouro-events/spool:/run/ouro-events:ro",
658
+ "-v", "/run/ouro-authority:/run/ouro-authority:ro",
659
+ "--mount", trustMount(name),
660
+ "-v", SYNC_MOUNT,
661
+ image(version)])
662
+ const ref = docker(["inspect", CONTAINER, "--format", "{{.Config.Image}}"]).trim()
663
+ if (ref !== image(version)) fail(`recreated resident is ${ref}, expected ${image(version)}`)
664
+ ok(`recreated ${CONTAINER} on ${version} (created, stopped, gateway-mounted)`)
665
+ }
666
+
667
+ // Migrate the agent bundle to the target version against the packaged bundle template
668
+ // (deploy/unraid/sanctuary.ouro inside the extracted package — it holds provider-readiness.json
669
+ // and the rest of the package-managed files). Without this, the target runtime reads an
670
+ // unmigrated predecessor bundle and its context-loss sentinel goes critical, crash-looping the
671
+ // resident telegram sense. Run while the resident is stopped (between recreate and activate).
672
+ // The recursive chown above also hands state/replay to the resident, but the replay gate's trust rests on that
673
+ // directory being root-owned and read-only to it. Put it back (the resident is stopped) and drop any window file.
674
+ // The recursive restore runs while the resident owns the bundle, so state/<name>, or state itself, may be a link it planted.
675
+ // A WARN line in the upgrade log says plainly that a restore step refused; nothing is chowned or chmodded through a link.
676
+ const warn = (m) => console.log(`\nWARN ${m}`)
677
+ export function trustedStateChild(bundle, name, { lstat = lstatSync, realpath = realpathSync, log = warn } = {}) {
678
+ const dir = `${bundle}/state/${name}`
679
+ const refuse = (reason) => { log(`upgrade restore REFUSED ${dir}: ${reason}; no chown or chmod was applied through it`); return null }
680
+ let stat
681
+ try { stat = lstat(dir) } catch { return null }
682
+ if (!stat.isDirectory()) return refuse(stat.isSymbolicLink() ? "it is a symlink" : "it is not a directory")
683
+ let resolved = ""
684
+ let expected = ""
685
+ try { resolved = realpath(dir); expected = `${realpath(bundle)}/state/${name}` } catch { /* unresolvable: refused below */ }
686
+ if (!resolved || resolved !== expected) return refuse("it resolves outside the bundle's own state directory")
687
+ return dir
688
+ }
689
+ export function restoreReplayRoot(bundle = hostBundle(), { lstat = lstatSync, realpath = realpathSync, chmod = chmodSync, rm = rmSync, run = sh, log = warn } = {}) {
690
+ const dir = trustedStateChild(bundle, "replay", { lstat, realpath, log })
691
+ if (!dir) return
692
+ run("/bin/chown", ["-h", "0:0", dir])
693
+ chmod(dir, 0o755)
694
+ rm(`${dir}/window.json`, { force: true, recursive: true })
695
+ }
696
+ // The psyche files stay owned by the resident (uid 10001) at exactly mode 0600: alpha.978's boot check
697
+ // (prepareSanctuaryPackageManagedBundle) requires that, and a rollback may start that release again. The recursive chown above
698
+ // already handed them to 10001; this puts the modes back (directories 0755, files 0600) and is the state psycheProblems checks.
699
+ export function restorePsycheModes(dir, { lstat = lstatSync, readdir = readdirSync, chmod = chmodSync } = {}) {
700
+ const walk = (current) => {
701
+ const stat = lstat(current)
702
+ if (stat.isSymbolicLink()) return
703
+ if (stat.isDirectory()) {
704
+ chmod(current, 0o755)
705
+ for (const name of readdir(current)) walk(`${current}/${name}`)
706
+ } else chmod(current, 0o600)
707
+ }
708
+ walk(dir)
709
+ }
710
+ function restorePsycheRoot() {
711
+ const dir = `${hostBundle()}/psyche`
712
+ if (existsSync(dir)) restorePsycheModes(dir)
713
+ }
714
+
715
+ /** What is wrong with the psyche folder: anything not owned by the resident, writable by group or others, or a symlink. A file the Butler creates may be 0644. Empty when it is sound. */
716
+ export function psycheProblems(dir, { lstat = lstatSync, readdir = readdirSync } = {}) {
717
+ const problems = []
718
+ const walk = (current) => {
719
+ const stat = lstat(current)
720
+ if (stat.isSymbolicLink()) { problems.push(`${current} is a symlink`); return }
721
+ if (stat.uid !== 10001) problems.push(`${current} is owned by uid ${stat.uid}, not the resident (10001)`)
722
+ if ((stat.mode & 0o022) !== 0) problems.push(`${current} is writable by group or others (mode ${(stat.mode & 0o777).toString(8)})`)
723
+ if (stat.isDirectory()) for (const name of readdir(current)) walk(`${current}/${name}`)
724
+ }
725
+ walk(dir)
726
+ return problems
727
+ }
728
+ // A gated upgrade plants a marker in the psyche and hashes the four identity files, then proves both survived the release
729
+ // and any rollback. TACIT is the Butler's own and may change, so only that it is there is checked.
730
+ // Root works inside a folder the Butler's user owns, which could rename psyche/ and put a symlink in its place at any moment.
731
+ // So every operation goes through one descriptor held on the real psyche/ (/proc/self/fd/<fd>/<name> on the Linux host),
732
+ // every read opens a regular file without following links or blocking, and before each write, rename or unlink the path
733
+ // psyche/ must still be that same directory.
734
+ export const PSYCHE_IDENTITY_FILES = ["SOUL.md", "IDENTITY.md", "LORE.md", "ASPIRATIONS.md"]
735
+ const PSYCHE_FILES = [...PSYCHE_IDENTITY_FILES, "TACIT.md"]
736
+ const PSYCHE_MARKER = ".release-marker"
737
+ const PSYCHE_READ_LIMIT = 1024 * 1024
738
+ export const psycheFdPath = (dirfd, name) => `/proc/self/fd/${dirfd}/${name}`
739
+
740
+ /** Read at most `limit` bytes from an open file; more than that is a problem, even if the file grew after it was checked. */
741
+ export function readPsycheBytes(fd, limit = PSYCHE_READ_LIMIT) {
742
+ const buffer = Buffer.alloc(limit + 1)
743
+ let length = 0
744
+ for (let read; length <= limit && (read = readSync(fd, buffer, length, limit + 1 - length, null)) > 0;) length += read
745
+ return length > limit ? { problem: "is larger than 1 MiB" } : { bytes: buffer.subarray(0, length) }
746
+ }
747
+
748
+ function readPsycheFile(dirfd, name, at) {
749
+ let fd
750
+ try { fd = openSync(at(dirfd, name), fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK) } catch (e) {
751
+ const why = e.code === "ENOENT" ? "is missing" : e.code === "ELOOP" ? "is a symlink" : `could not be opened (${e.code ?? e.message})`
752
+ return { problem: `psyche/${name} ${why}` }
753
+ }
754
+ try {
755
+ if (!fstatSync(fd).isFile()) return { problem: `psyche/${name} is not a regular file` }
756
+ const read = readPsycheBytes(fd)
757
+ return read.problem ? { problem: `psyche/${name} ${read.problem}` } : read
758
+ } finally { closeSync(fd) }
759
+ }
760
+
761
+ /** Run `work` with a descriptor on the real psyche/ and a guard that throws if the path psyche/ is no longer that directory. */
762
+ function withPsycheDir(dir, work) {
763
+ let dirfd
764
+ try { dirfd = openSync(dir, fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW) } catch { throw new Error(`${dir} is not a real directory`) }
765
+ try {
766
+ const held = fstatSync(dirfd)
767
+ const guard = () => {
768
+ let now = null
769
+ try { now = lstatSync(dir) } catch { /* gone counts as replaced */ }
770
+ if (!now?.isDirectory() || now.dev !== held.dev || now.ino !== held.ino) throw new Error(`${dir} was replaced while root was working in it; refusing`)
771
+ }
772
+ return work(dirfd, guard)
773
+ } finally { closeSync(dirfd) }
774
+ }
775
+
776
+ const hashOf = (bytes) => createHash("sha256").update(bytes).digest("hex")
777
+
778
+ /** Write psyche/.release-marker (0600, resident-owned, a random token) and hash the identity files. Refuses unless all five psyche files are regular files. */
779
+ export function plantPsycheMarker(dir, { uid, gid }, { at = psycheFdPath } = {}) {
780
+ return withPsycheDir(dir, (dirfd, guard) => {
781
+ const read = Object.fromEntries(PSYCHE_FILES.map((name) => [name, readPsycheFile(dirfd, name, at)]))
782
+ for (const name of PSYCHE_FILES) if (read[name].problem) throw new Error(read[name].problem)
783
+ const identity = Object.fromEntries(PSYCHE_IDENTITY_FILES.map((name) => [name, hashOf(read[name].bytes)]))
784
+ const token = randomBytes(16).toString("hex")
785
+ const staged = `${PSYCHE_MARKER}.${token}`
786
+ guard()
787
+ const fd = openSync(at(dirfd, staged), fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_NOFOLLOW, 0o600)
788
+ try {
789
+ fchownSync(fd, uid, gid)
790
+ fchmodSync(fd, 0o600)
791
+ writeFileSync(fd, token)
792
+ } finally { closeSync(fd) }
793
+ try { guard() } catch (e) { try { unlinkSync(at(dirfd, staged)) } catch { /* the guard's error is the one to report */ } throw e }
794
+ renameSync(at(dirfd, staged), at(dirfd, PSYCHE_MARKER))
795
+ return { token, identity }
796
+ })
797
+ }
798
+
799
+ /** Null when the marker holds the token, all five psyche files are regular files and the four identity hashes match; otherwise the first problem. */
800
+ export function psycheSurvival(dir, planted, { at = psycheFdPath } = {}) {
801
+ try {
802
+ return withPsycheDir(dir, (dirfd) => {
803
+ const marker = readPsycheFile(dirfd, PSYCHE_MARKER, at)
804
+ if (marker.problem) return marker.problem
805
+ if (marker.bytes.toString("utf8") !== planted.token) return `psyche/${PSYCHE_MARKER} does not hold this upgrade's token`
806
+ const read = PSYCHE_FILES.map((name) => [name, readPsycheFile(dirfd, name, at)])
807
+ const unreadable = read.find(([, file]) => file.problem)
808
+ if (unreadable) return unreadable[1].problem
809
+ const changed = read.find(([name, file]) => name in planted.identity && hashOf(file.bytes) !== planted.identity[name])
810
+ return changed ? `psyche/${changed[0]} changed` : null
811
+ })
812
+ } catch (e) { return e.message }
813
+ }
814
+
815
+ /** Remove the marker only while it holds this upgrade's token, reading and unlinking through the same descriptor. Returns why it was left, or null. */
816
+ export function removePsycheMarker(dir, token, { at = psycheFdPath } = {}) {
817
+ try {
818
+ return withPsycheDir(dir, (dirfd, guard) => {
819
+ const marker = readPsycheFile(dirfd, PSYCHE_MARKER, at)
820
+ if (marker.problem) return marker.problem
821
+ if (marker.bytes.toString("utf8") !== token) return `psyche/${PSYCHE_MARKER} does not hold this upgrade's token`
822
+ guard()
823
+ unlinkSync(at(dirfd, PSYCHE_MARKER))
824
+ return null
825
+ })
826
+ } catch (e) { return e.message }
827
+ }
828
+
829
+ /** Print the survival check as a gate case line (the shape butler-ship's parseCases reports) and return the problem, if any. */
830
+ export function reportPsycheSurvival(id, dir, planted, log = console.log, options = {}) {
831
+ const problem = psycheSurvival(dir, planted, options)
832
+ const check = { name: "the psyche marker and all five psyche files survived, with the four identity files byte-identical", ok: problem === null, ...(problem ? { detail: problem } : {}) }
833
+ log(JSON.stringify({ id, status: problem ? "fail" : "pass", checks: [check] }))
834
+ return problem
835
+ }
836
+
837
+ /**
838
+ * What is wrong with the resident's psyche mount, from `docker inspect` Mounts, or null for a supported shape: no separate psyche
839
+ * mount (current releases), or a read-only one (alpha.978 and earlier, which a rollback recreates).
840
+ */
841
+ export function psycheMountIssue(mounts, name = "sanctuary") {
842
+ const mount = (Array.isArray(mounts) ? mounts : []).find((entry) => entry?.Destination === psycheTarget(name))
843
+ return !mount || mount.RW === false ? null : "psyche is mounted read-write as a separate mount in the resident"
844
+ }
845
+
846
+ function migrateBundle(version, rollbackImage) {
847
+ say(`migrate agent bundle to ${version}`)
848
+ const pkgBundle = `${ROOT}/incoming-package/deploy/unraid/sanctuary.ouro`
849
+ const migrate = `${ROOT}/incoming-package/deploy/unraid/migrate-sanctuary-bundle.mjs`
850
+ if (!existsSync(`${pkgBundle}/provider-readiness.json`)) fail(`packaged bundle template missing provider-readiness.json at ${pkgBundle}`)
851
+ const bundle = hostBundle()
852
+ if (rollbackImage === null) {
853
+ // A fresh install has no earlier image to roll back to: write the packaged files with no rollback record.
854
+ sh("/usr/local/bin/node", [migrate, "--package-root", pkgBundle, "--agent-root", bundle, "--operation", "seed"])
855
+ ok("bundle seeded from the package (fresh install)")
856
+ } else {
857
+ // The host folder keeps its name, so the migrate is told the Butler the target image runs: the bundle's own files name its container path.
858
+ sh("/usr/local/bin/node", [migrate, "--package-root", pkgBundle, "--agent-root", bundle, "--operation", "migrate",
859
+ "--rollback-image-id", rollbackImage, "--target-image-id", imageId(version), "--butler-name", imageButlerName(image(version))])
860
+ ok("bundle migrated (rollback retained)")
861
+ sh("/usr/local/bin/node", [migrate, "--package-root", pkgBundle, "--agent-root", bundle, "--operation", "commit"])
862
+ }
863
+ // migrate/commit ran as root; the resident owns its bundle as uid 10001, so restore ownership
864
+ sh("/bin/chown", ["-R", "10001:10001", bundle])
865
+ restoreReplayRoot(bundle)
866
+ restorePsycheRoot()
867
+ ok("bundle committed (ownership restored to resident)")
868
+ }
869
+
870
+ // Host supervision for the root-authority gateway on Unraid. Installs three scripts, all
871
+ // verified on the live box (see desk butler-agent D-026/D-029/D-032/D-033/D-035):
872
+ // - gateway-supervisor.sh: keeps cgroup2-unraid paused (D-026), creates/repairs the
873
+ // socket dir Docker would otherwise create wrong (D-033), and (re)starts the gateway
874
+ // through the authority's own boot path, start.sh --boot (D-032) — never raw node.
875
+ // - gateway-keeper-watchdog.sh: cron */2 resurrects the supervisor (D-029), except
876
+ // during shutdown.
877
+ // - /boot/config/stop: Unraid runs it before stopping the array; it stops the supervisor
878
+ // and gateway gracefully, resumes the reaper, and traces to /boot/logs (D-035).
879
+ const AUTHORITY_CUSTOM = "/boot/config/custom/ouro-authority"
880
+ const GATEWAY_SUPERVISOR = `${AUTHORITY_CUSTOM}/gateway-supervisor.sh`
881
+ const GATEWAY_WATCHDOG = `${AUTHORITY_CUSTOM}/gateway-keeper-watchdog.sh`
882
+ const UNRAID_STOP_HOOK = "/boot/config/stop"
883
+ const GATEWAY_SUPERVISOR_SH = String.raw`#!/bin/sh
884
+ # Ouro authority gateway keeper for Unraid.
885
+ # The root-authority gateway needs /sys/fs/cgroup/ouro-authority to persist, and Unraid's
886
+ # cgroup2-unraid removes every top-level cgroup that reports populated 0. The kernel will not
887
+ # remove a cgroup that has a child cgroup, so the authority keeps an empty ouro-keep child
888
+ # (D-026). This keeper:
889
+ # - creates that keep child and lets the reaper run; it pauses the reaper only while the
890
+ # keep child is missing (a fresh boot, or an authority older than the keep child),
891
+ # - keeps the gateway process alive,
892
+ # - reconnects the resident (docker restart) if it is unhealthy while the gateway is ready
893
+ # (handles reboot ordering, where Docker autostarts the resident before the gateway).
894
+ set -u
895
+ CG=/sys/fs/cgroup/ouro-authority
896
+ R=/mnt/user/appdata/ouro-authority
897
+ GW=$R/package/dist/heart/daemon/sanctuary-telegram-authority-entry.js
898
+ CFG=$R/active.json
899
+ LOG=/var/log/ouro-gateway.log
900
+ # Only an authority from 0.1.0-alpha.837 on understands the keep child; an older gateway
901
+ # refuses to start beside an unknown cgroup (a rollback to 830 hit exactly that). So the
902
+ # keep child exists only while the installed package supports it; otherwise it is removed
903
+ # and the reaper stays paused, the pre-837 behaviour.
904
+ keep_supported() { grep -q ouro-keep "$R/package/dist/heart/daemon/sanctuary-authority-installation.js" 2>/dev/null; }
905
+ reaper_policy() {
906
+ P=$(cat /run/cgroup2-unraid.pid 2>/dev/null) || return 0
907
+ [ -n "$P" ] || return 0
908
+ if keep_supported && [ -d "$CG/ouro-keep" ]; then kill -CONT "$P" 2>/dev/null; return 0; fi
909
+ S=$(ps -o stat= -p "$P" 2>/dev/null | tr -d ' ')
910
+ case "$S" in T*) : ;; *) kill -STOP "$P" 2>/dev/null ;; esac
911
+ }
912
+ ensure_cg() {
913
+ [ -d "$CG" ] || { mkdir -m 700 "$CG" 2>/dev/null; chown 0:0 "$CG" 2>/dev/null
914
+ for c in cpu memory pids; do echo "+$c" > "$CG/cgroup.subtree_control" 2>/dev/null; done; }
915
+ if keep_supported; then [ -d "$CG/ouro-keep" ] || mkdir -m 700 "$CG/ouro-keep" 2>/dev/null
916
+ else [ -d "$CG/ouro-keep" ] && rmdir "$CG/ouro-keep" 2>/dev/null; fi
917
+ }
918
+ ensure_sock() {
919
+ # Docker autostarts the resident before us and auto-creates its missing bind
920
+ # source /run/ouro-authority as 755 root:root; the authority boot rejects that as
921
+ # unsafe. Create it, or repair it in place (same inode, so the resident's bind
922
+ # mount stays valid), as 750 root:10001.
923
+ [ -d /run/ouro-authority ] || mkdir -p /run/ouro-authority
924
+ chown 0:10001 /run/ouro-authority 2>/dev/null
925
+ chmod 0750 /run/ouro-authority 2>/dev/null
926
+ }
927
+ gw_pid() { ps -eo pid,args | grep '[s]anctuary-telegram-authority-entry.js' | awk '{print $1}' | head -1; }
928
+ start_gw() {
929
+ # Launch through the authority lifecycle boot (start.sh --boot), never raw node:
930
+ # it waits for the array + Docker, rebuilds the tmpfs runtime state a reboot
931
+ # wipes (/var/lib/ouro-authority), clears a stale readiness.json, launches the
932
+ # gateway detached, and returns once it is ready.
933
+ rm -f "$R"/epochs/*/authority.lock 2>/dev/null
934
+ echo "$(date) keeper: authority boot (runtime dirs + gateway)" >> "$LOG"
935
+ /bin/sh /boot/config/custom/ouro-authority/start.sh --boot >> "$LOG" 2>&1 \
936
+ || echo "$(date) keeper: authority boot failed; will retry" >> "$LOG"
937
+ }
938
+ # An in-place upgrade pauses us with a flag; a stale flag (> 30 min) is ignored.
939
+ maintenance() { [ -n "$(find /run/ouro-authority-maintenance -mmin -30 2>/dev/null)" ]; }
940
+ reaper_policy; ensure_cg; ensure_sock
941
+ last_res=0
942
+ while true; do
943
+ if maintenance; then sleep 15; continue; fi
944
+ reaper_policy
945
+ ensure_cg
946
+ reaper_policy
947
+ ensure_sock
948
+ [ -n "$(gw_pid)" ] || { start_gw; sleep 8; }
949
+ rd=$(jq -rc .status "$R"/epochs/*/readiness.json 2>/dev/null)
950
+ st=$(docker inspect ouro-butler --format '{{.State.Health.Status}}' 2>/dev/null)
951
+ ss=$(docker inspect ouro-butler --format '{{.State.Status}}' 2>/dev/null)
952
+ now=$(date +%s)
953
+ # Unhealthy, or left stopped (an interrupted upgrade or restart): the gateway is ready, so bring it back.
954
+ if [ "$rd" = ready ] && { [ "$st" = unhealthy ] || [ "$ss" = exited ] || [ "$ss" = created ]; } && [ $((now - last_res)) -gt 90 ]; then
955
+ echo "$(date) keeper: reconnecting resident ($ss/$st)" >> "$LOG"
956
+ docker restart ouro-butler >/dev/null 2>&1
957
+ last_res=$now
958
+ fi
959
+ sleep 15
960
+ done
961
+ `
962
+ const GATEWAY_WATCHDOG_SH = String.raw`#!/bin/sh
963
+ # Ouro authority gateway-supervisor watchdog (D-028 hardening).
964
+ # gateway-supervisor.sh keeps the .830 root-authority gateway alive and the
965
+ # cgroup2-unraid reaper paused. The supervisor was a single point of failure:
966
+ # started once from /boot/config/go, nothing restarted it if it died -- and a dead
967
+ # supervisor means a dead gateway would never be restarted (bot fully offline, as the
968
+ # gateway holds the Telegram token). This watchdog (cron */2) resurrects it if absent.
969
+ set -u
970
+ # The stop hook sets this during shutdown; never resurrect the supervisor then.
971
+ [ -e /run/ouro-authority-shutdown ] && exit 0
972
+ # An in-place upgrade pauses supervision; a stale flag (> 30 min) is ignored.
973
+ [ -n "$(find /run/ouro-authority-maintenance -mmin -30 2>/dev/null)" ] && exit 0
974
+ SUP=/boot/config/custom/ouro-authority/gateway-supervisor.sh
975
+ LOG=/var/log/ouro-gateway.log
976
+ if [ ! -f "$SUP" ]; then
977
+ echo "$(date) watchdog: supervisor script MISSING at $SUP" >> "$LOG"
978
+ exit 0
979
+ fi
980
+ if ps -eo args 2>/dev/null | grep -q '[g]ateway-supervisor.sh'; then
981
+ exit 0
982
+ fi
983
+ echo "$(date) watchdog: supervisor not running -- restarting" >> "$LOG"
984
+ setsid /bin/sh "$SUP" >/dev/null 2>&1 &
985
+ `
986
+ const UNRAID_STOP_HOOK_SH = String.raw`#!/bin/bash
987
+ # Ouro authority stop hook (run by Unraid's rc.local_shutdown before the array stops).
988
+ # Stops our host processes cleanly so nothing of ours is respawning or frozen during
989
+ # shutdown, and leaves a trace on the flash drive for diagnosis. Every step is bounded.
990
+ LOG=/boot/logs/ouro-shutdown.log
991
+ mkdir -p /boot/logs
992
+ {
993
+ echo "$(date) stop hook: begin"
994
+ touch /run/ouro-authority-shutdown
995
+ for p in $(pgrep -f '^/bin/sh /boot/config/custom/ouro-authority/[g]ateway-supervisor'); do kill "$p"; done
996
+ for p in $(pgrep -f '[s]anctuary-telegram-authority-entry.js'); do kill "$p"; done
997
+ for i in 1 2 3 4 5 6 7 8 9 10; do pgrep -f '[s]anctuary-telegram-authority-entry.js' >/dev/null || break; sleep 1; done
998
+ pkill -9 -f '[s]anctuary-telegram-authority-entry.js' 2>/dev/null
999
+ P=$(cat /run/cgroup2-unraid.pid 2>/dev/null); [ -n "$P" ] && kill -CONT "$P"
1000
+ echo "$(date) stop hook: supervisor+gateway stopped, reaper resumed ($(pgrep -fc '[s]anctuary-telegram-authority-entry.js') gateways left)"
1001
+ } >> "$LOG" 2>&1
1002
+ `
1003
+ const WATCHDOG_CRON = `*/2 * * * * /bin/sh ${GATEWAY_WATCHDOG} # ouro-authority-gateway-watchdog`
1004
+ function installGatewaySupervisor() {
1005
+ for (const [path, body, mode] of [[GATEWAY_SUPERVISOR, GATEWAY_SUPERVISOR_SH, 0o700], [GATEWAY_WATCHDOG, GATEWAY_WATCHDOG_SH, 0o700], [UNRAID_STOP_HOOK, UNRAID_STOP_HOOK_SH, 0o755]]) {
1006
+ writeFileSync(path, body)
1007
+ sh("/bin/chown", ["0:0", path]); chmodSync(path, mode)
1008
+ }
1009
+ ok("gateway supervisor, watchdog, and Unraid stop hook installed")
1010
+ const go = "/boot/config/go"
1011
+ try {
1012
+ let g = readFileSync(go, "utf8")
1013
+ g = g.split("\n").filter((l) => !/ouro-authority\/start\.sh --boot/.test(l) && !/ouro-authority-gateway/.test(l) && !/gateway-keeper-watchdog/.test(l)).join("\n")
1014
+ if (!g.endsWith("\n")) g += "\n"
1015
+ g += `setsid /bin/sh ${GATEWAY_SUPERVISOR} >/dev/null 2>&1 & # ouro-authority-gateway\n`
1016
+ g += `(crontab -l 2>/dev/null | grep -v gateway-keeper-watchdog; echo "${WATCHDOG_CRON}") | crontab - # ouro-authority-gateway-watchdog\n`
1017
+ writeFileSync(go, g)
1018
+ ok("supervisor + watchdog cron wired into /boot/config/go for reboot durability")
1019
+ } catch (e) { console.log(` WARN: could not wire go hook (${e.message}); start manually on boot`) }
1020
+ sh("/bin/sh", ["-c", `(crontab -l 2>/dev/null | grep -v gateway-keeper-watchdog; echo "${WATCHDOG_CRON}") | crontab -`])
1021
+ // Replace any running supervisor so exactly one runs the new code; clear a stale shutdown flag.
1022
+ sh("/bin/sh", ["-c", "rm -f /run/ouro-authority-shutdown; for p in $(pgrep -f '^/bin/sh /boot/config/custom/ouro-authority/[g]ateway-supervisor' || true); do kill $p; done"])
1023
+ sh("/bin/sh", ["-c", `setsid /bin/sh ${GATEWAY_SUPERVISOR} >/dev/null 2>&1 &`])
1024
+ ok("gateway supervisor started")
1025
+ }
1026
+
1027
+ // On a successful authority-activate, finalize a durable, stable target: archive the DockerMan
1028
+ // transaction journal (committed-equivalent for our purposes), and hand cgroup-reaper pausing +
1029
+ // gateway/resident supervision to the keeper. The reaper is intentionally left paused (the
1030
+ // keeper keeps it paused); do not resume it here.
1031
+ function finalizeStable() {
1032
+ if (existsSync(JOURNAL)) { sh("/bin/mv", ["-f", JOURNAL, `${JOURNAL}.committed.${Date.now()}`]); ok("transaction journal archived (committed)") }
1033
+ installGatewaySupervisor()
1034
+ REAPER_PAUSED = false
1035
+ }
1036
+
1037
+ function install(version) {
1038
+ say(`install ${version}`)
1039
+ const incoming = `${ROOT}/incoming-package`
1040
+ if (!existsSync(`${ROOT}/request.json`) || !existsSync(incoming)) fail("not prepared; run prepare first")
1041
+ const pkgVersion = JSON.parse(readFileSync(`${incoming}/deploy/unraid/sanctuary.ouro/bundle-meta.json`, "utf8")).runtimeVersion
1042
+ if (pkgVersion !== version) fail(`prepared package is ${pkgVersion}, not ${version}; re-run prepare`)
1043
+ if (!existsSync(`${ROOT}/incoming-token`) || statSync(`${ROOT}/incoming-token`).size === 0) fail(`no rotated token at ${ROOT}/incoming-token — rotate it in BotFather first`)
1044
+ if (existsSync(JOURNAL)) fail("a template transaction is already pending; resolve it first")
1045
+ if (targetHasVaultFix(version) === false) fail(`${version} lacks the D-018 fenced-read fix; the install would strand Telegram (run preflight)`)
1046
+ const fresh = installedRequest()?.predecessorContract === "none"
1047
+
1048
+ // Clear stale authority runtime dirs from a prior failed attempt so #runtimeDirectories
1049
+ // starts clean (it skips a dir that already exists). Safe only when no authority is live
1050
+ // (no active.json) and no transaction is pending. Note: the empty-cgroup ENOENT at stage
1051
+ // is caused by Unraid's cgroup2-unraid reaper, handled by pauseCgroupReaper() below.
1052
+ if (!existsSync(`${ROOT}/active.json`) && !existsSync(JOURNAL)) {
1053
+ for (const d of ["/sys/fs/cgroup/ouro-authority", "/var/lib/ouro-authority", "/run/ouro-authority", `${ROOT}/epochs`, `${ROOT}/package`]) {
1054
+ try { if (existsSync(d)) { sh("/bin/sh", ["-c", `find ${d} -depth -type d -exec rmdir {} + 2>/dev/null; rm -rf ${d} 2>/dev/null`], { stdio: "ignore" }) } } catch { /* best effort */ }
1055
+ }
1056
+ killLeakedGateway()
1057
+ ok("cleared stale authority runtime dirs (cgroup/staging/socket/epochs) and any leaked gateway")
1058
+ }
1059
+ const targetImage = imageId(version)
1060
+ if (fresh && containerExists(CONTAINER)) fail(`an ${CONTAINER} container already exists; a fresh install needs a host without one`)
1061
+ const rollbackImage = fresh ? null : docker(["inspect", CONTAINER, "--format", "{{.Image}}"]).trim()
1062
+ if (!targetImage || targetImage === rollbackImage) fail("target/rollback image identity invalid")
1063
+ const renameIssue = rollbackImage ? renamePredecessorIssue(version, rollbackImage) : null
1064
+ if (renameIssue) fail(`${renameIssue}; nothing was changed`)
1065
+ const jellyfinBefore = jellyfinState()
1066
+ const policyBefore = fresh ? policyState() : policyState() ?? fail(`steward policy missing`)
1067
+ ok(`target ${targetImage.slice(0,19)}… rollback ${rollbackImage ? `${rollbackImage.slice(0,19)}…` : "none (fresh install)"} policy ${policyBefore ?? "none yet"}`)
1068
+
1069
+ const srcTemplate = `${ROOT}/source-template.xml`
1070
+ sh("/usr/bin/install", ["-m", "600", "-o", "0", "-g", "0", `${incoming}/deploy/unraid/sanctuary.xml`, srcTemplate])
1071
+ const manifestDigest = JSON.parse(readFileSync(`${ROOT}/request.json`, "utf8")).packageDigest
1072
+
1073
+ pauseCgroupReaper()
1074
+ try {
1075
+ say("transaction: prepare -> authority-install -> authority-activate -> commit")
1076
+ tx("prepare", ["--source-template", srcTemplate, "--version-tag", image(version),
1077
+ "--manifest-digest", manifestDigest, "--rollback-image-id", rollbackImage ?? "none", "--target-image-id", targetImage])
1078
+ ok("prepared")
1079
+ tx("authority-install"); ok("authority installed (gateway up)")
1080
+ recreateResident(version)
1081
+ migrateBundle(version, rollbackImage)
1082
+ tx("authority-activate"); ok("resident activated")
1083
+ waitHealthy(300)
1084
+ enableResidentAutostart()
1085
+ finalizeStable()
1086
+ ok("stabilized: bundle migrated, gateway supervised, journal committed")
1087
+ } catch (e) {
1088
+ resumeCgroupReaper()
1089
+ console.log(`\n!! install failed:\n${e.message}\n!! auto-rolling back so the Butler is not left down`)
1090
+ if (fresh) {
1091
+ freshRollback()
1092
+ fail("fresh install rolled back; nothing is left running. Fix the error above, then run prepare --fresh and install again.")
1093
+ }
1094
+ autoRollback(rollbackImage, version)
1095
+ fail("install rolled back; the Butler is on its prior version. See output above.")
1096
+ }
1097
+
1098
+ say("preservation")
1099
+ jellyfinState() === jellyfinBefore ? ok(jellyfinBefore ? "jellyfin unchanged" : "no jellyfin, as before") : fail("JELLYFIN CHANGED")
1100
+ unchanged(policyBefore, policyState()) ? ok(policyBefore ? "steward policy unchanged" : "no steward policy before install") : fail("STEWARD POLICY CHANGED")
1101
+ console.log(`\nINSTALL done — ${version} live. Run verify.`)
1102
+ }
1103
+
1104
+ // Kill any leaked authority host process (the gateway / host-supervisor). A failed
1105
+ // authority-retire/stop-gateway during rollback can leave sanctuary-telegram-authority-entry
1106
+ // running against a since-removed active.json — it competes for the Telegram token and holds
1107
+ // FUSE files open on ${ROOT}/package. Best-effort; the resident (ouro-butler) is untouched.
1108
+ function killLeakedGateway() {
1109
+ try {
1110
+ const pids = sh("/bin/sh", ["-c", "pgrep -f 'dist/heart/daemon/sanctuary-(telegram-authority|host-supervisor)-entry' || true"]).trim().split(/\s+/u).filter(Boolean)
1111
+ for (const pid of pids) { try { sh("/bin/kill", ["-TERM", pid]) } catch { /* ignore */ } }
1112
+ if (pids.length) { sh("/bin/sleep", ["3"]); for (const pid of pids) { try { sh("/bin/kill", ["-KILL", pid]) } catch { /* ignore */ } } ok(`stopped ${pids.length} leaked authority process(es)`) }
1113
+ } catch { /* best effort */ }
1114
+ }
1115
+
1116
+ // A fresh install rolls back to nothing: the authority retires and removes the resident it created, the template
1117
+ // transaction removes the template it wrote, and nothing is restarted because nothing ran before.
1118
+ function freshRollback() {
1119
+ for (const op of ["authority-retire", "authority-restore", "rollback"]) {
1120
+ try { tx(op) } catch (e) { console.log(` ${op}: ${String(e.message).split("\n")[0]}`) }
1121
+ }
1122
+ killLeakedGateway()
1123
+ try { if (containerExists(CONTAINER)) docker(["rm", "-f", CONTAINER]) } catch (e) { console.log(` remove ${CONTAINER}: ${String(e.message).split("\n")[0]}`) }
1124
+ console.log(containerExists(CONTAINER) ? ` ${CONTAINER} is still present — remove it by hand before retrying` : " rollback complete — no Butler container is left behind")
1125
+ }
1126
+
1127
+ function autoRollback(rollbackImage, version) {
1128
+ try { tx("authority-retire") } catch (e) { console.log(` authority-retire: ${String(e.message).split("\n")[0]}`) }
1129
+ try { tx("authority-restore") } catch (e) { console.log(` authority-restore: ${String(e.message).split("\n")[0]}`) }
1130
+ try { tx("rollback") } catch (e) { console.log(` template rollback: ${String(e.message).split("\n")[0]}`) }
1131
+ killLeakedGateway()
1132
+ try { if (!docker(["inspect", CONTAINER, "--format", "{{.State.Running}}"], { stdio: ["ignore","pipe","ignore"] }).trim().startsWith("true")) docker(["start", CONTAINER]) } catch { /* below */ }
1133
+ // The predecessor reads its token from the materialised credential cache, not
1134
+ // the vault directly. authority-restore returns the token to the vault, but a
1135
+ // stale cache leaves the resident crash-looping on 401 (this is exactly what
1136
+ // stranded the bot on 2026-09-22). Re-materialise the vault token into the
1137
+ // cache, keeping the value host-side only, and confirm recovery.
1138
+ try {
1139
+ rematerialiseToken(version)
1140
+ docker(["restart", CONTAINER])
1141
+ console.log(" re-materialised token from the vault and restarted the predecessor")
1142
+ } catch (e) { console.log(` re-materialise: ${String(e.message).split("\n")[0]} — MANUAL recovery may be needed`) }
1143
+ for (let i = 0; i < 24; i++) {
1144
+ const st = (() => { try { return docker(["inspect", CONTAINER, "--format", "{{.State.Status}}/{{.State.Health.Status}}"], { stdio: ["ignore","pipe","ignore"] }).trim() } catch { return "?" } })()
1145
+ if (st === "running/healthy") { console.log(" rollback complete — predecessor healthy again"); return }
1146
+ sh("/bin/sleep", ["10"])
1147
+ }
1148
+ console.log(" rollback container did NOT return healthy — inspect `docker logs ouro-butler` and re-materialise the token manually")
1149
+ }
1150
+
1151
+ // Restores the predecessor's telegram token after a failed install. The subtle
1152
+ // truth learned by dogfooding: once the upgrade has rotated the token, the OLD
1153
+ // token is REVOKED, so the predecessor cannot be restored to it — it must be
1154
+ // brought up on the NEW token (incoming-token). So this prefers incoming-token
1155
+ // when present (the post-rotation case), putting it back into the vault AND the
1156
+ // materialised cache; only if no rotation happened does it fall back to the
1157
+ // vault's own token. The value stays in host-side pipes, never in this process.
1158
+ // Runs through a quiet sole-user container of the target image (the reliable way
1159
+ // to reach the bitwarden store off the running resident).
1160
+ // Force an explicit `bw sync` inside the vault-fix container before a write. The
1161
+ // resident and the install's fenced ops share one local bitwarden cache; after an
1162
+ // interrupted install the local copy can be older than the server, so a bare
1163
+ // `bw edit` fails ("The client copy of this cipher is out of date"). The store's
1164
+ // own sync-on-login skips when its freshness marker is <60s old, so we sync
1165
+ // directly (unlock -> sync) and let the write proceed against a reconciled cache.
1166
+ export function forceBwSyncScript(butler) {
1167
+ return [
1168
+ 'const cp=require("node:child_process"),fs=require("node:fs");',
1169
+ 'const {readVaultUnlockSecret,bitwardenAppDataDir}=require("/opt/ouro/dist/repertoire/vault-unlock.js");',
1170
+ `const NAME=${JSON.stringify(butler)};`,
1171
+ `const cfg=JSON.parse(fs.readFileSync(${JSON.stringify(`${containerBundle(butler)}/agent.json`)},"utf8")).vault||{};`,
1172
+ 'const email=cfg.email, url=cfg.serverUrl;',
1173
+ // The bw folder is keyed by the agent's name, so the other name's folder may be there too: take this Butler's.
1174
+ // Hash the folder from the vault config the daemon resolves (normalised URL, legacy hosts mapped), or it misses.
1175
+ 'const {resolveVaultConfig}=require("/opt/ouro/dist/heart/identity.js");',
1176
+ 'const APP=bitwardenAppDataDir(NAME,resolveVaultConfig(NAME,cfg),"/home/ouro");',
1177
+ 'const u=readVaultUnlockSecret({agentName:NAME,email,serverUrl:url});',
1178
+ 'const env={...process.env,BITWARDENCLI_APPDATA_DIR:APP,OURO_BW_MASTER_PASSWORD:u.secret};',
1179
+ 'const sess=cp.execFileSync("bw",["unlock","--passwordenv","OURO_BW_MASTER_PASSWORD","--raw"],{env,encoding:"utf8"}).trim();',
1180
+ 'cp.execFileSync("bw",["sync"],{env:{...env,BW_SESSION:sess},encoding:"utf8"});',
1181
+ 'process.stdout.write("bw-synced");',
1182
+ ].join("")
1183
+ }
1184
+ function forceBwSync(name, butler) {
1185
+ const script = forceBwSyncScript(butler)
1186
+ try { docker(["exec", "-u", "0:0", name, "node", "-e", script], { stdio: ["ignore", "pipe", "pipe"] }); ok("forced bw sync before token restore") }
1187
+ catch (e) { console.log(` forceBwSync: ${String(e.message).split("\n")[0]} (continuing; restore may still succeed)`) }
1188
+ }
1189
+
1190
+ function rematerialiseToken(version) {
1191
+ const cc = "/mnt/user/appdata/ouro-butler/runtime/container-credentials.json"
1192
+ const incoming = `${ROOT}/incoming-token`
1193
+ const fromIncoming = existsSync(incoming) && statSync(incoming).size > 0
1194
+ const name = `ouro-vault-fix-${process.pid}`
1195
+ const butler = imageButlerName(image(version))
1196
+ docker(["rm", "-f", name], { stdio: "ignore" })
1197
+ docker(["run", "-d", "--name", name, "--network", "host", "--user", "0:0",
1198
+ "-v", `${RUNTIME}:/home/ouro/.ouro-cli`, "--mount", `type=bind,src=${hostBundle()},dst=${containerBundle(butler)}`,
1199
+ "--entrypoint", "sleep", image(version), "infinity"])
1200
+ try {
1201
+ sh("/bin/sleep", ["3"])
1202
+ if (fromIncoming) {
1203
+ // Put the new (valid) token back into the vault, then materialise it. Build the
1204
+ // restore JSON in JS and pipe it via stdin: jq's rtrimstr with a JS "\n" template
1205
+ // produced a raw newline inside jq's string literal and jq rejected it, which is what
1206
+ // stranded the bot on 2026-09-22. Owner ids come from the resident's own cache.
1207
+ const tok = readFileSync(incoming, "utf8").replace(/[\r\n]+$/u, "")
1208
+ const resident = JSON.parse(readFileSync(cc, "utf8"))
1209
+ const rc = resident.credentials[0].runtimeConfig
1210
+ const restore = JSON.stringify({ token: tok, botId: tok.split(":")[0],
1211
+ ownerUserId: String(rc.telegramAuthorizedUserId), ownerChatId: String(rc.telegramAuthorizedChatId) })
1212
+ forceBwSync(name, butler)
1213
+ docker(["exec", "-i", "-u", "0:0", name, "node", CLI, "vault", "restore"], { input: restore, stdio: ["pipe", "pipe", "pipe"] })
1214
+ // Fail loudly if the restored token is not actually live at Telegram, rather
1215
+ // than leaving a "healthy" container polling a revoked token (a deaf bot).
1216
+ try {
1217
+ const me = sh("/bin/sh", ["-c", `curl -s "https://api.telegram.org/bot${tok}/getMe"`]).trim()
1218
+ if (!/"ok":true/.test(me)) console.log(` WARN: restored token getMe not ok — the bot may be deaf: ${me.slice(0, 120)}`)
1219
+ else ok("restored token verified live at Telegram (getMe ok)")
1220
+ } catch { /* network check is best-effort */ }
1221
+ rc.telegramBotToken = tok
1222
+ writeFileSync(`${cc}.tmp`, JSON.stringify(resident))
1223
+ sh("/bin/sh", ["-c", `chown --reference=${cc} ${cc}.tmp && chmod --reference=${cc} ${cc}.tmp && mv ${cc}.tmp ${cc}`])
1224
+ } else {
1225
+ sh("/bin/sh", ["-c",
1226
+ `set -o pipefail; docker exec -u 0:0 ${name} node ${CLI} vault snapshot | jq -r .token > ${cc}.tok.$$ && ` +
1227
+ `jq --rawfile t ${cc}.tok.$$ '.credentials[0].runtimeConfig.telegramBotToken=($t|rtrimstr("\n"))' ${cc} > ${cc}.tmp.$$ && ` +
1228
+ `chown --reference=${cc} ${cc}.tmp.$$ && chmod --reference=${cc} ${cc}.tmp.$$ && mv ${cc}.tmp.$$ ${cc}; rm -f ${cc}.tok.$$`])
1229
+ }
1230
+ } finally { docker(["rm", "-f", name], { stdio: "ignore" }) }
1231
+ }
1232
+
1233
+ function waitHealthy(sec) {
1234
+ for (let i = 0; i < sec / 10; i++) {
1235
+ const st = docker(["inspect", CONTAINER, "--format", "{{.State.Health.Status}}"], { stdio: ["ignore","pipe","ignore"] }).trim()
1236
+ if (st === "healthy") { ok(`healthy after ${i * 10}s`); return }
1237
+ sh("/bin/sleep", ["10"])
1238
+ }
1239
+ fail("container did not become healthy in time")
1240
+ }
1241
+
1242
+ function buildFinalProof(version, out) {
1243
+ const tag = image(version)
1244
+ const c = JSON.parse(docker(["container", "inspect", CONTAINER, "--format",
1245
+ '{"name":{{json .Name}},"imageId":{{json .Image}},"imageReference":{{json .Config.Image}},"running":{{json .State.Running}},"health":{{json .State.Health.Status}},"labels":{{json .Config.Labels}}}']))
1246
+ const autostart = existsSync("/var/lib/docker/unraid-autostart") &&
1247
+ readFileSync("/var/lib/docker/unraid-autostart", "utf8").split("\n").some((l) => l.split(" ")[0] === "ouro-butler")
1248
+ const text = (tag2) => (readFileSync(TEMPLATE, "utf8").match(new RegExp(`<${tag2}>([^<]*)</${tag2}>`)) || [])[1]
1249
+ const bundle = JSON.parse(sh("/usr/local/bin/node", [`${ROOT}/incoming-package/deploy/unraid/migrate-sanctuary-bundle.mjs`,
1250
+ "--package-root", `${ROOT}/package`, "--agent-root", hostBundle(), "--operation", "status"]))
1251
+ const jf = JSON.parse(docker(["container", "inspect", "jellyfin", "--format",
1252
+ '{"containerId":{{json .Id}},"imageId":{{json .Image}},"state":{{json .State.Status}},"restartCount":{{json .RestartCount}}}']))
1253
+ const proof = {
1254
+ container: { name: c.name, imageId: c.imageId, imageReference: c.imageReference,
1255
+ running: c.running === true, healthy: c.health === "healthy", autostart,
1256
+ labels: { "net.unraid.docker.managed": c.labels["net.unraid.docker.managed"], "net.unraid.docker.icon": c.labels["net.unraid.docker.icon"] } },
1257
+ bundle,
1258
+ dockerMan: { templatePath: TEMPLATE, name: text("Name"), repository: text("Repository"), templateUrl: text("TemplateURL"), icon: text("Icon") },
1259
+ communityApps: { installed: true, name: "ouro-butler", repository: text("Repository"), templateUrl: text("TemplateURL"),
1260
+ stateModel: "previous-apps-inline-v1", entryPath: "/usr/local/emhttp/plugins/community.applications/include/exec.php",
1261
+ entryFunction: "previous_apps", implementationPath: "/usr/local/emhttp/plugins/community.applications/include/exec.php", implementationSymbol: "previous_apps" },
1262
+ jellyfin: jf,
1263
+ }
1264
+ if (c.imageReference !== tag) fail(`container image is ${c.imageReference}, expected ${tag}`)
1265
+ writeFileSync(out, JSON.stringify(proof), { mode: 0o600 })
1266
+ }
1267
+
1268
+ // ---- upgrade (in place, installed authority) --------------------------------
1269
+
1270
+ /**
1271
+ * Keeps host supervision paused for as long as this upgrade process lives, gate and rollback included: a detached
1272
+ * shell touches the maintenance flag every interval while the parent is alive. It never recreates a released flag
1273
+ * (touch -c). Once the parent is gone, however it ended, the shell drops the shutdown flag (which never expires) and
1274
+ * stops, so the maintenance flag ages out and self-heal returns within about 30 minutes of a crash.
1275
+ */
1276
+ export const SUPERVISION_HOLD_SH = 'while kill -0 "$1" 2>/dev/null; do touch -c "$2"; sleep "$4"; done; rm -f "$3"'
1277
+ export function holdSupervision({ spawnImpl = spawn, parentPid = process.pid, flag = MAINTENANCE, shutdownFlag = SHUTDOWN_FLAG, intervalSec = 60 } = {}) {
1278
+ const child = spawnImpl("/bin/sh", ["-c", SUPERVISION_HOLD_SH, "ouro-supervision-hold", String(parentPid), flag, shutdownFlag, String(intervalSec)], { detached: true, stdio: "ignore" })
1279
+ child.unref()
1280
+ return child
1281
+ }
1282
+ let HOLD = null
1283
+
1284
+ // A host still running an older keeper has a cron watchdog that ignores the maintenance
1285
+ // flag: it resurrected the paused supervisor, which restarted the resident mid-upgrade
1286
+ // (the first 830 -> 835 rehearsal). So put this version's keeper scripts in place first
1287
+ // (they honour the flag) and also raise the shutdown flag every watchdog version honours;
1288
+ // resumeSupervision clears both.
1289
+ function pauseSupervision() {
1290
+ writeFileSync(MAINTENANCE, `${new Date().toISOString()} ${process.pid}\n`)
1291
+ writeFileSync(SHUTDOWN_FLAG, `upgrade ${process.pid}\n`)
1292
+ HOLD ??= holdSupervision()
1293
+ for (const [path, body] of [[GATEWAY_SUPERVISOR, GATEWAY_SUPERVISOR_SH], [GATEWAY_WATCHDOG, GATEWAY_WATCHDOG_SH]]) {
1294
+ writeFileSync(path, body)
1295
+ sh("/bin/chown", ["0:0", path]); chmodSync(path, 0o700)
1296
+ }
1297
+ sh("/bin/sh", ["-c", "for p in $(pgrep -f '^/bin/sh /boot/config/custom/ouro-authority/[g]ateway-supervisor' || true); do kill $p; done"])
1298
+ if (sh("/bin/sh", ["-c", "pgrep -fc '^/bin/sh /boot/config/custom/ouro-authority/[g]ateway-supervisor' || true"]).trim() !== "0") fail("a gateway supervisor survived the pause")
1299
+ ok("host supervision paused (keeper scripts current; flags expire on their own)")
1300
+ }
1301
+ function resumeSupervision() {
1302
+ if (HOLD) { try { process.kill(-HOLD.pid, "SIGTERM") } catch { /* already gone; touch -c cannot recreate the flag */ } HOLD = null }
1303
+ rmSync(MAINTENANCE, { force: true })
1304
+ rmSync(SHUTDOWN_FLAG, { force: true })
1305
+ installGatewaySupervisor()
1306
+ }
1307
+
1308
+ /**
1309
+ * The template text without its psyche `<Config>` (Target exactly the psyche under either Butler name), so a DockerMan Apply cannot put the old read-only
1310
+ * psyche mount back. The element is removed with the whitespace that starts its line and the newline that ends it; every other byte
1311
+ * is kept. `parse` is docker-man-template-xml.cjs's parseDockerManTemplateXml: a template it cannot read, or one without exactly one
1312
+ * such Config, comes back unchanged, as does one where the textual match does not remove exactly that element.
1313
+ */
1314
+ export function withoutPsycheConfig(text, parse) {
1315
+ const targets = BUTLER_NAMES.map(psycheTarget)
1316
+ const psycheConfigs = (document) => document?.children.filter((child) => child.name === "Config" && targets.includes(child.attributes.Target)).length
1317
+ const before = parse(text)
1318
+ if (psycheConfigs(before) !== 1) return text
1319
+ const target = before.children.find((child) => child.name === "Config" && targets.includes(child.attributes.Target)).attributes.Target
1320
+ const next = text.replace(new RegExp(`[ \\t]*<Config\\b[^<>]*\\sTarget="${target.replace(/[.]/gu, "\\.")}"[^<>]*(?:/>|>[^<]*</Config>)[ \\t]*\\r?\\n?`, "u"), "")
1321
+ const after = parse(next)
1322
+ return after && psycheConfigs(after) === 0 && after.children.length === before.children.length - 1 ? next : text
1323
+ }
1324
+
1325
+ export const SYNC_CONFIG = ` <Config Name="Bundle sync key (read-only)" Target="${SYNC_TARGET}" Default="${SYNC_HOST_DIR}" Mode="ro" Description="Deploy key the Butler's bundle sync pushes with, owned by 10002:10002 mode 0400 so only the sync wrapper reads it. Read-only inside the Butler" Type="Path" Display="always" Required="true" Mask="false">${SYNC_HOST_DIR}</Config>`
1326
+
1327
+ /**
1328
+ * The DockerMan template with the sync key's read-only Config added before </Container>, so a DockerMan Apply keeps the
1329
+ * mount. `parse` is docker-man-template-xml.cjs's parseDockerManTemplateXml: a template it cannot read, one that already
1330
+ * has a Config for the target, or one where the insertion does not add exactly that element comes back unchanged.
1331
+ */
1332
+ export function withSyncConfig(text, parse) {
1333
+ const syncConfigs = (document) => document?.children.filter((child) => child.name === "Config" && child.attributes.Target === SYNC_TARGET).length
1334
+ const before = parse(text)
1335
+ if (!before || syncConfigs(before) !== 0) return text
1336
+ const close = text.lastIndexOf("</Container>")
1337
+ const next = `${text.slice(0, close)}${SYNC_CONFIG}\n${text.slice(close)}`
1338
+ const after = parse(next)
1339
+ return after && syncConfigs(after) === 1 && after.children.length === before.children.length + 1 ? next : text
1340
+ }
1341
+
1342
+ // Keep Unraid's DockerMan template (what the UI's Apply/Update uses) on the live image, without the old psyche mount, and
1343
+ // mounting the bundle and trust where that image's Butler expects them. Runs after the commit, so the parser comes from the
1344
+ // installed package (this script is staged on its own, without siblings). The upgrade checks it can pin before it changes
1345
+ // anything (templatePinProblem), so a template it cannot move to a new Butler name stops the upgrade instead of the pin.
1346
+ function pinTemplate(version) {
1347
+ const pin = templatePin(version)
1348
+ if (pin.absent) { console.log(" note: no DockerMan template to update"); return }
1349
+ if (pin.problem) fail(`${pin.problem}; a DockerMan Apply would mount the bundle and trust where ${image(version)} does not look for them, so fix the template by hand first`)
1350
+ for (const warning of pin.warnings) console.log(` WARN: ${warning}`)
1351
+ if (pin.text !== pin.original) { writeFileSync(`${TEMPLATE}.prev`, pin.original); writeFileSync(TEMPLATE, pin.text) }
1352
+ if (!pin.skipped) ok(`DockerMan template pins ${image(version)}`)
1353
+ }
1354
+
1355
+ /** The installed template, pinned for this version and the Butler name its image runs, without writing it. */
1356
+ function templatePin(version) {
1357
+ if (!existsSync(TEMPLATE)) return { absent: true }
1358
+ const original = readFileSync(TEMPLATE, "utf8")
1359
+ let parse = null
1360
+ let parserError = null
1361
+ try {
1362
+ // Load the parser fresh each time: preflight reads the predecessor package's copy, and the pin after the switch must
1363
+ // read the new one at the same path, which require's cache would otherwise hand back.
1364
+ const load = createRequire(import.meta.url)
1365
+ const parserPath = `${ROOT}/package/deploy/unraid/docker-man-template-xml.cjs`
1366
+ delete load.cache[load.resolve(parserPath)]
1367
+ parse = load(parserPath).parseDockerManTemplateXml
1368
+ } catch (error) { parserError = error.message }
1369
+ return { original, ...pinTemplateText(original, image(version), imageButlerName(image(version)), parse, parserError) }
1370
+ }
1371
+
1372
+ /** Why the installed template cannot be pinned for this version, or null (also when there is no template). */
1373
+ function templatePinProblem(version) { return templatePin(version).problem ?? null }
1374
+
1375
+ /**
1376
+ * Whether the template must have its bundle and trust Targets moved to this Butler name: it lacks either one under the name,
1377
+ * and the name is butler or the template already says butler somewhere. A sanctuary image never moves a sanctuary template,
1378
+ * so every sanctuary pin does exactly what it did before the rename.
1379
+ */
1380
+ export function templateNeedsButlerName(text, name) {
1381
+ const has = (target) => text.includes(`Target="${target}"`)
1382
+ if (has(containerBundle(name)) && has(trustTarget(name))) return false
1383
+ return name !== "sanctuary" || has(containerBundle("butler")) || has(trustTarget("butler"))
1384
+ }
1385
+
1386
+ /**
1387
+ * The template with its bundle Config's Target and its trust Config's Target moved to this Butler name. Their Defaults and
1388
+ * values, the host folders, stay. A template with no trust Config keeps none: the resident's trust mount comes from the root
1389
+ * lifecycle, which names it from the image, and the live install's template has never had one. `{ problem }` when the parser
1390
+ * cannot read it, it lacks exactly one bundle Config, it has more than one trust Config, a Target appears more than once in the
1391
+ * text, or the result does not parse with exactly those moved.
1392
+ */
1393
+ export function withButlerTargets(text, name, parse) {
1394
+ const configs = (document, targets) => document.children.filter((child) => child.name === "Config" && targets.includes(child.attributes.Target))
1395
+ const before = parse(text)
1396
+ if (!before) return { problem: "the DockerMan template cannot be parsed" }
1397
+ const bundles = configs(before, BUTLER_NAMES.map(containerBundle))
1398
+ const trusts = configs(before, BUTLER_NAMES.map(trustTarget))
1399
+ if (bundles.length !== 1 || trusts.length > 1) return { problem: "the DockerMan template does not have exactly one bundle Config and at most one trust Config" }
1400
+ let next = text
1401
+ const moves = [[bundles[0], containerBundle(name)], ...trusts.map((trust) => [trust, trustTarget(name)])]
1402
+ for (const [config, target] of moves) {
1403
+ const from = `Target="${config.attributes.Target}"`
1404
+ if (config.attributes.Target === target) continue
1405
+ if (next.split(from).length !== 2) return { problem: `the DockerMan template has ${from} more than once` }
1406
+ next = next.replace(from, `Target="${target}"`)
1407
+ }
1408
+ const after = parse(next)
1409
+ if (!after || after.children.length !== before.children.length || configs(after, [containerBundle(name)]).length !== 1 || configs(after, [trustTarget(name)]).length !== trusts.length) {
1410
+ return { problem: "moving the DockerMan template's bundle and trust Targets did not leave exactly those moved" }
1411
+ }
1412
+ return { text: next }
1413
+ }
1414
+
1415
+ /**
1416
+ * The template text pinned to `reference` for the Butler `name`: the Repository, no psyche Config, the sync key Config, and
1417
+ * the bundle and trust Targets under `name`. `parse` is null when the parser could not be loaded (`parserError` says why).
1418
+ * `{ problem }` when the Targets must move to a new name and cannot; otherwise `{ text, warnings, skipped }`, where the parts
1419
+ * a sanctuary pin has always only warned about stay warnings.
1420
+ */
1421
+ export function pinTemplateText(text, reference, name, parse, parserError) {
1422
+ const needsName = templateNeedsButlerName(text, name)
1423
+ const repository = `<Repository>${reference}</Repository>`
1424
+ let next = text.replace(/<Repository>ghcr\.io\/ourostack\/ouroboros-butler:[^<]+<\/Repository>/u, repository)
1425
+ if (!next.includes(repository)) {
1426
+ return needsName ? { problem: "the DockerMan template's Repository is not recognised" } : { text, warnings: ["DockerMan template Repository not recognised; left unchanged"], skipped: true }
1427
+ }
1428
+ const warnings = []
1429
+ if (!parse) {
1430
+ if (needsName) return { problem: `the DockerMan template parser could not be loaded (${parserError})` }
1431
+ warnings.push(`could not load the DockerMan template parser (${parserError}); psyche Config left in place, sync key Config not added`)
1432
+ } else {
1433
+ next = withSyncConfig(withoutPsycheConfig(next, parse), parse)
1434
+ if (needsName) {
1435
+ const moved = withButlerTargets(next, name, parse)
1436
+ if (moved.problem) return { problem: moved.problem }
1437
+ next = moved.text
1438
+ }
1439
+ }
1440
+ if (BUTLER_NAMES.some((butler) => next.includes(`Target="${psycheTarget(butler)}"`))) warnings.push("DockerMan template still has a psyche Config; remove it before the next DockerMan Apply")
1441
+ if (!next.includes(`Target="${SYNC_TARGET}"`)) warnings.push(`DockerMan template has no ${SYNC_TARGET} Config; add it before the next DockerMan Apply`)
1442
+ return { text: next, warnings, skipped: false }
1443
+ }
1444
+
1445
+ // Every release pulls a ~1 GB Butler image, and Unraid's docker.img filled to 88% with
1446
+ // twenty of them (D-046). After a successful upgrade keep only the live image and the
1447
+ // authority's recorded rollback image; Docker itself refuses to remove an image in use.
1448
+ function pruneButlerImages() {
1449
+ const activation = JSON.parse(readFileSync(`${ROOT}/activation.json`, "utf8"))
1450
+ const keep = new Set([activation.targetImageId, activation.rollbackImageId])
1451
+ let removed = 0
1452
+ for (const line of docker(["images", "--no-trunc", "--format", "{{.ID}} {{.Tag}}", "ghcr.io/ourostack/ouroboros-butler"]).trim().split("\n").filter(Boolean)) {
1453
+ const [id, tag] = line.split(" ")
1454
+ if (keep.has(id) || !tag || tag === "<none>") continue
1455
+ try { docker(["rmi", `ghcr.io/ourostack/ouroboros-butler:${tag}`], { stdio: ["ignore", "pipe", "pipe"] }); removed += 1 } catch { /* in use */ }
1456
+ }
1457
+ ok(`pruned ${removed} old Butler image(s); kept the live and rollback images`)
1458
+ }
1459
+
1460
+ // A failed rollback exits with supervision still paused: the keeper's boot would retry the rollback alongside a manual
1461
+ // retry (the 945 rollback on 2026-10-25). The flag then ages out and the keeper's boot retries it on its own.
1462
+ const ROLLBACK_FAILED = (e, lifecycle) => `ROLLBACK FAILED: ${lifecycleFailure(e)}\nThe journal is kept. Host supervision stays paused for about 30 minutes; after that the keeper's authority boot retries the rollback. To retry by hand sooner, keep it paused while you do: \`touch ${MAINTENANCE}; node ${lifecycle} upgrade-rollback\` (repeat the touch if the retry is slow).`
1463
+
1464
+ function lifecycleFailure(e) {
1465
+ const detail = [e.stderr, e.stdout].map((x) => (x ? String(x).trim() : "")).filter(Boolean).join(" | ")
1466
+ let last = ""
1467
+ try { last = readFileSync(`${ROOT}/lifecycle-failure.log`, "utf8").trim().split("\n").filter((l) => /^\d{4}-/.test(l)).at(-1) ?? "" } catch { /* none */ }
1468
+ return `${detail || e.message}${last ? `\n last root failure: ${last}` : ""}`
1469
+ }
1470
+
1471
+ /**
1472
+ * The end of a gated upgrade, with every side effect injected so the decision is testable: a pass commits the held
1473
+ * upgrade, pins the template and prunes; a fail rolls back to the predecessor and confirms it is healthy. Nothing is
1474
+ * committed, pinned or pruned unless the gate passed.
1475
+ */
1476
+ export function completeGatedUpgrade({ runGate, commit, rollback, confirmRollback, pin, prune, log = console.log }) {
1477
+ const gate = runGate()
1478
+ if (gate.ok) {
1479
+ commit()
1480
+ pin()
1481
+ prune()
1482
+ log("GATE PASS")
1483
+ return { passed: true }
1484
+ }
1485
+ log(`gate failed: ${gate.detail ?? "see the case lines above"}`)
1486
+ rollback()
1487
+ const restored = confirmRollback()
1488
+ log(`GATE FAIL — ROLLED BACK to ${restored}`)
1489
+ return { passed: false, rolledBackTo: restored }
1490
+ }
1491
+
1492
+ export function runReplayGate(plant, { spawn = spawnSync, exists = existsSync } = {}) {
1493
+ if (!exists(GATE_SCRIPT)) return { ok: false, detail: `the replay gate is missing from the live package (${GATE_SCRIPT})` }
1494
+ const result = spawn("/usr/local/bin/node", [GATE_SCRIPT, "run", ...(plant ? ["--plant", plant] : [])], { stdio: "inherit", timeout: GATE_TIMEOUT_MS, killSignal: "SIGKILL" })
1495
+ return result.status === 0 ? { ok: true } : { ok: false, detail: `the replay gate exited ${result.status ?? result.signal}` }
1496
+ }
1497
+
1498
+ /**
1499
+ * The commit step runs the lifecycle's `upgrade` again, which would START A FRESH UNGATED UPGRADE if the keeper had
1500
+ * rolled the held one back mid-gate. So commit only while the journal still exists and the new image is still live.
1501
+ */
1502
+ export function heldUpgradeProblem({ journalExists, liveImage, expectedImage }) {
1503
+ if (!journalExists) return "the held upgrade's journal is gone (the keeper or a boot rolled it back mid-gate)"
1504
+ if (liveImage !== expectedImage) return `the live Butler is ${liveImage}, not the held ${expectedImage}`
1505
+ return null
1506
+ }
1507
+
1508
+ function butlerState() {
1509
+ try { return docker(["inspect", CONTAINER, "--format", "{{.Config.Image}} {{.State.Status}}/{{.State.Health.Status}}"], { stdio: ["ignore", "pipe", "ignore"] }).trim() } catch { return "? ?/?" }
1510
+ }
1511
+
1512
+ function waitForButler(imageRef, seconds) {
1513
+ for (let waited = 0; waited <= seconds; waited += 10) {
1514
+ const [liveImage, state] = butlerState().split(" ")
1515
+ if (liveImage === imageRef && state === "running/healthy") return true
1516
+ sh("/bin/sleep", ["10"])
1517
+ }
1518
+ return false
1519
+ }
1520
+
1521
+ // The new gateway asks Telegram who it is (getMe) before it reports ready. When the host cannot reach
1522
+ // Telegram, that fails and the whole upgrade rolls back after host supervision was already paused
1523
+ // (the 863 -> 864 upgrade). Any HTTP answer from the API host proves the network path; no token is sent.
1524
+ export const TELEGRAM_API_URL = "https://api.telegram.org/"
1525
+ export async function telegramApiReachable({ fetchImpl = globalThis.fetch, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), tries = 3, timeoutMs = 8000, retryDelayMs = 3000 } = {}) {
1526
+ let detail = "no attempt made"
1527
+ for (let attempt = 1; attempt <= tries; attempt += 1) {
1528
+ try {
1529
+ const response = await fetchImpl(TELEGRAM_API_URL, { method: "GET", signal: AbortSignal.timeout(timeoutMs) })
1530
+ return { ok: true, detail: `HTTP ${response.status}` }
1531
+ } catch (error) {
1532
+ detail = error instanceof Error ? (error.cause instanceof Error ? `${error.message}: ${error.cause.message}` : error.message) : String(error)
1533
+ if (attempt < tries) await sleep(retryDelayMs)
1534
+ }
1535
+ }
1536
+ return { ok: false, detail: `${detail} (${tries} attempts)` }
1537
+ }
1538
+
1539
+ // A resume or rollback (an upgrade journal exists) must never be blocked by a network probe.
1540
+ export async function checkTelegramBeforePause({ journalExists, probe = telegramApiReachable }) {
1541
+ if (journalExists) return { skipped: true, ok: true, detail: "upgrade journal present" }
1542
+ return { skipped: false, ...(await probe()) }
1543
+ }
1544
+
1545
+ async function upgrade(version, rehearse, { noGate = false, plant } = {}) {
1546
+ say(`in-place upgrade to ${version}${rehearse ? ` — REHEARSAL: stop after "${rehearse}", then roll back` : ""}`)
1547
+ const hostLock = await loadHostLock()
1548
+ const taken = hostLockTake("the upgrade", { lockModule: hostLock, holder: `butler upgrade ${version}` })
1549
+ if (taken.refusal) fail(`${taken.refusal}; nothing was changed`)
1550
+ process.on("exit", () => hostLockLeave(taken, { lockModule: hostLock, holder: `butler:ship ${version}` }))
1551
+ const rollbackLock = () => { const held = hostLockWait("the rollback", { lockModule: hostLock, token: taken.token }); if (held) { console.error(`\n${ROLLBACK_LOCKED(held, lifecycle)}`); process.exit(1) } }
1552
+ if (rehearse && !UPGRADE_STEPS.includes(rehearse)) fail(`--rehearse takes one of: ${UPGRADE_STEPS.join(", ")}`)
1553
+ const gated = !rehearse && !noGate
1554
+ if (noGate && !rehearse) console.log("\n!! --no-gate: this upgrade will NOT be replay-gated or auto-rolled-back on a behavioural regression")
1555
+ if (gated && !existsSync(GATE_PROVISION)) fail(`replay peers are not provisioned (${GATE_PROVISION}); run \`sanctuary-replay-gate.mjs provision\` first (once, on the upgrade that moves the replay seeds out of the bundle into that root-owned folder, run \`provision --rotate-replay-identities\` instead so no earlier seed survives; any seed or provision.json under state/replay-client in the bundle was writable by the Butler and is ignored), or pass --no-gate`)
1556
+ if (!existsSync(`${ROOT}/active.json`) || !existsSync(`${ROOT}/activation.json`)) fail("no installed authority; use prepare + install")
1557
+ if (existsSync(JOURNAL)) fail("a template transaction is pending; resolve it first")
1558
+ let id = imageId(version)
1559
+ if (!id) { docker(["pull", image(version)]); id = imageId(version) }
1560
+ if (!id) fail(`image ${image(version)} could not be pulled`)
1561
+ ok(`image ${id.slice(0, 19)}…`)
1562
+ const current = JSON.parse(readFileSync(`${ROOT}/request.json`, "utf8"))
1563
+ if (existsSync(UPGRADE_JOURNAL)) console.log(" note: resuming the pending in-place upgrade with its staged package")
1564
+ else {
1565
+ // The root lifecycle refuses this too when the upgrade begins; refusing here leaves nothing staged or paused.
1566
+ const renameIssue = renamePredecessorIssue(version, docker(["inspect", CONTAINER, "--format", "{{.Image}}"]).trim())
1567
+ if (renameIssue) fail(`${renameIssue}; nothing was paused or changed`)
1568
+ const manifestBytes = stageIncomingPackage(version)
1569
+ const pkgVersion = JSON.parse(readFileSync(`${ROOT}/incoming-package/deploy/unraid/sanctuary.ouro/bundle-meta.json`, "utf8")).runtimeVersion
1570
+ if (pkgVersion !== version) fail(`staged package is ${pkgVersion}, not ${version}`)
1571
+ writePrivate(INCOMING_MANIFEST, manifestBytes)
1572
+ const request = upgradeRequest(current, packagePins(manifestBytes))
1573
+ writePrivate(INCOMING_REQUEST, Buffer.from(JSON.stringify(request)))
1574
+ verifyPackage(`${ROOT}/incoming-package`, INCOMING_MANIFEST, INCOMING_REQUEST)
1575
+ ok("new package staged beside the live one and verified")
1576
+ }
1577
+ const lifecycle = `${ROOT}/incoming-package/dist/heart/daemon/sanctuary-authority-root-lifecycle.js`
1578
+ const priorImage = butlerState().split(" ")[0]
1579
+ const jellyfinBefore = jellyfinState()
1580
+ const policyBefore = current.predecessorContract === "none" ? policyState() : policyState() ?? fail("steward policy missing")
1581
+ const telegram = await checkTelegramBeforePause({ journalExists: existsSync(UPGRADE_JOURNAL) })
1582
+ if (!telegram.ok) fail(`api.telegram.org is not reachable from this host (${telegram.detail}); the new gateway could not pass its Telegram identity check. Nothing was paused or changed; fix the network and re-run.`)
1583
+ if (telegram.skipped) console.log(" note: resuming a pending upgrade; Telegram reachability not re-checked")
1584
+ else ok(`api.telegram.org reachable (${telegram.detail})`)
1585
+ const pinProblem = templatePinProblem(version)
1586
+ if (pinProblem) fail(`${pinProblem}, so the DockerMan template could not follow ${image(version)}; nothing was paused or changed`)
1587
+ // The host bundle is found on disk at each use; it never moves, so every check below reads the same psyche.
1588
+ const psycheDir = () => `${hostBundle()}/psyche`
1589
+ let planted = null
1590
+ if (gated) {
1591
+ try { planted = plantPsycheMarker(psycheDir(), { uid: 10001, gid: 10001 }) } catch (e) { fail(`could not plant the psyche marker before the gated upgrade; nothing was paused or changed: ${e.message}`) }
1592
+ ok("psyche marker planted and the four identity files hashed")
1593
+ }
1594
+ pauseSupervision()
1595
+ let failure = null
1596
+ try {
1597
+ say(`lifecycle upgrade (stop → switch → resident → migrate → start${gated ? ", held uncommitted for the gate" : ""})`)
1598
+ ok(sh("/usr/local/bin/node", [lifecycle, "upgrade", id, image(version), ...(rehearse ? ["--fail-after", rehearse] : gated ? ["--hold-commit"] : [])], { stdio: ["ignore", "pipe", "pipe"] }).trim())
1599
+ } catch (e) { failure = e }
1600
+ // Only the lifecycle's own rehearsal stop is planned; anything else is a real failure,
1601
+ // even during a rehearsal (the first 830 -> 835 rehearsal was mislabelled "as planned").
1602
+ const reason = failure ? lifecycleFailure(failure) : ""
1603
+ const planned = Boolean(failure && rehearse && reason.includes(`rehearsal stopped after ${rehearse}`))
1604
+ if (failure) {
1605
+ console.log(`\n!! ${planned ? "rehearsal stopped as planned" : "upgrade FAILED"}: ${reason}\n!! rolling back to the predecessor`)
1606
+ rollbackLock()
1607
+ try { ok(`rollback: ${sh("/usr/local/bin/node", [lifecycle, "upgrade-rollback"], { stdio: ["ignore", "pipe", "pipe"] }).trim()}`) }
1608
+ catch (e) { fail(ROLLBACK_FAILED(e, lifecycle)) }
1609
+ } else if (!gated) { pinTemplate(version); pruneButlerImages() }
1610
+ // A held upgrade stays paused through the gate; commit or rollback resumes it.
1611
+ if (!gated || failure) resumeSupervision()
1612
+ say("preservation")
1613
+ const preserved = []
1614
+ const jellyfinNow = jellyfinState()
1615
+ jellyfinNow === jellyfinBefore ? ok(jellyfinBefore ? "jellyfin unchanged" : "no jellyfin, as before") : (gated && !failure ? (bad("JELLYFIN CHANGED"), preserved.push("jellyfin changed")) : fail("JELLYFIN CHANGED"))
1616
+ unchanged(policyBefore, policyState()) ? ok("steward policy unchanged") : (gated && !failure ? (bad("STEWARD POLICY CHANGED"), preserved.push("steward policy changed")) : fail("STEWARD POLICY CHANGED"))
1617
+ const live = docker(["inspect", CONTAINER, "--format", "{{.Config.Image}} {{.State.Status}}/{{.State.Health.Status}}"]).trim()
1618
+ ok(`butler: ${live}`)
1619
+ if (failure && !planned) fail("upgrade rolled back; the Butler is on its prior version (see above)")
1620
+ if (gated && !failure) {
1621
+ say(`replay gate${plant ? ` (planted failure: ${plant})` : ""}`)
1622
+ const stillHeld = () => heldUpgradeProblem({ journalExists: existsSync(UPGRADE_JOURNAL), liveImage: butlerState().split(" ")[0], expectedImage: image(version) })
1623
+ let outcome
1624
+ try {
1625
+ outcome = completeGatedUpgrade({
1626
+ runGate: () => {
1627
+ if (preserved.length) return { ok: false, detail: preserved.join("; ") }
1628
+ if (!waitForButler(image(version), 300)) return { ok: false, detail: `the new Butler did not become healthy on ${image(version)}` }
1629
+ const lost = reportPsycheSurvival("psyche-survives-release", psycheDir(), planted)
1630
+ if (lost) return { ok: false, detail: `the psyche did not survive the release: ${lost}` }
1631
+ const result = runReplayGate(plant)
1632
+ if (!result.ok) return result
1633
+ const problem = stillHeld()
1634
+ return problem ? { ok: false, detail: problem } : result
1635
+ },
1636
+ commit: () => {
1637
+ pauseSupervision()
1638
+ try {
1639
+ const problem = stillHeld()
1640
+ if (problem) throw new Error(`refusing to commit: ${problem}`)
1641
+ ok(`commit: ${sh("/usr/local/bin/node", [lifecycle, "upgrade", id, image(version)], { stdio: ["ignore", "pipe", "pipe"] }).trim()}`)
1642
+ } finally { resumeSupervision() }
1643
+ },
1644
+ rollback: () => {
1645
+ pauseSupervision()
1646
+ rollbackLock()
1647
+ try { ok(`rollback: ${sh("/usr/local/bin/node", [lifecycle, "upgrade-rollback"], { stdio: ["ignore", "pipe", "pipe"] }).trim()}`) }
1648
+ catch (e) { fail(ROLLBACK_FAILED(e, lifecycle)) }
1649
+ resumeSupervision()
1650
+ },
1651
+ confirmRollback: () => {
1652
+ if (!waitForButler(priorImage, 300)) fail(`rolled back, but ${priorImage} is not running healthy; inspect \`docker logs ${CONTAINER}\``)
1653
+ reportPsycheSurvival("psyche-survives-rollback", psycheDir(), planted)
1654
+ return priorImage
1655
+ },
1656
+ pin: () => pinTemplate(version),
1657
+ prune: () => pruneButlerImages(),
1658
+ })
1659
+ } finally {
1660
+ const left = removePsycheMarker(psycheDir(), planted.token)
1661
+ if (left) warn(`the psyche marker was left in place: ${left}`)
1662
+ }
1663
+ if (!outcome.passed) process.exit(1)
1664
+ console.log(`\nUPGRADE done — ${version} live and gate-verified. Run verify.`)
1665
+ return
1666
+ }
1667
+ console.log(rehearse ? "\nREHEARSAL done — the upgrade reached the planned step and the rollback restored the predecessor." : `\nUPGRADE done — ${version} live (NOT gate-verified). Run verify.`)
1668
+ }
1669
+
1670
+ // ---- verify ---------------------------------------------------------------
1671
+
1672
+ function verify(withGate = false) {
1673
+ say("verify")
1674
+ const st = docker(["inspect", CONTAINER, "--format", "{{.Config.Image}} {{.State.Status}}/{{.State.Health.Status}} restarts={{.RestartCount}}"]).trim()
1675
+ ok(`butler: ${st}`)
1676
+ const auth = docker(["logs", CONTAINER, "--since", "2m"], { stdio: ["ignore","pipe","pipe"] }).split("\n").filter((l) => l.includes("401")).length
1677
+ auth === 0 ? ok("no Telegram auth failures in the last 2m") : bad(`${auth} 401s in the last 2m`)
1678
+ const policy = policyFile()
1679
+ existsSync(policy) ? ok(`steward policy ${sha12(policy)}`) : installedRequest()?.predecessorContract === "none" ? ok("no steward policy yet") : bad("steward policy missing")
1680
+ // The paths inside the resident follow the Butler name its image runs.
1681
+ const name = liveButlerName()
1682
+ const psycheMount = JSON.parse(docker(["inspect", CONTAINER, "--format", "{{json .Mounts}}"]) || "[]")
1683
+ psycheMountIssue(psycheMount, name) === null ? ok("psyche mount is in a supported shape") : bad(psycheMountIssue(psycheMount, name))
1684
+ existsSync(TEMPLATE) && BUTLER_NAMES.some((butler) => readFileSync(TEMPLATE, "utf8").includes(`Target="${psycheTarget(butler)}"`))
1685
+ ? bad("installed DockerMan template still mounts the psyche read-only; a DockerMan Apply would restore it")
1686
+ : ok("installed DockerMan template has no separate psyche mount")
1687
+ const trustMount = JSON.parse(docker(["inspect", CONTAINER, "--format", "{{json .Mounts}}"]) || "[]")
1688
+ trustMountIssue(trustMount, name) === null ? ok("the operator trust directory is mounted read-only in the resident") : bad(trustMountIssue(trustMount, name))
1689
+ const trustIssue = existsSync(TRUST_HOST_DIR) ? trustDirIssue(lstatSync(TRUST_HOST_DIR)) : `${TRUST_HOST_DIR} is missing`
1690
+ trustIssue === null ? ok("the host trust directory is root-owned and closed to group and other writes") : bad(trustIssue)
1691
+ const droppedHolders = escalationGrantProblems(name)
1692
+ droppedHolders.length === 0 ? ok("every escalation holder is in the trusted file") : droppedHolders.forEach((line) => bad(line))
1693
+ const psycheDir = `${hostBundle()}/psyche`
1694
+ if (existsSync(psycheDir)) {
1695
+ const psycheIssues = psycheProblems(psycheDir)
1696
+ psycheIssues.length === 0 ? ok("psyche files are resident-owned and writable") : bad(`psyche files must be owned by the resident (uid 10001), not writable by group or others, and not symlinks: ${psycheIssues.slice(0, 3).join("; ")}`)
1697
+ } else bad("psyche folder missing from the bundle")
1698
+ ok(containerExists("jellyfin") ? `jellyfin ${docker(["inspect", "jellyfin", "--format", "{{.State.Status}} restarts={{.RestartCount}}"]).trim()}` : "no jellyfin container")
1699
+ if (withGate) {
1700
+ say("replay gate (live version, no upgrade)")
1701
+ const gate = runReplayGate(undefined)
1702
+ gate.ok ? ok("replay gate passed") : bad(`replay gate failed: ${gate.detail}`)
1703
+ }
1704
+ process.exit(RED === 0 ? 0 : 1)
1705
+ }
1706
+
1707
+ function fail(m) { console.error(`\nREFUSING: ${m}`); process.exit(1) }
1708
+
1709
+ // ---- host lock --------------------------------------------------------------
1710
+ // Eval runs hold the host lock (ouro-host-lock.mjs, staged beside this script by butler:ship) while they use this
1711
+ // host's Docker; butler:ship holds it for the whole ship and passes its token in OURO_HOST_LOCK_TOKEN. The upgrade
1712
+ // takes that lock over with its own pid (or takes its own when run by hand), waiting while anyone else holds it, and
1713
+ // each rollback checks it again: on 2026-11-23 an eval container vanishing mid-upgrade failed the upgrade and its
1714
+ // rollback and left the Butler down (#1760).
1715
+ export const HOST_LOCK_DIR = "/var/lock/ouro-host.d"
1716
+
1717
+ export const HOST_LOCK_TTL_MS = 4 * 60 * 60 * 1000
1718
+ const HAND_BACK_TTL_MS = 30 * 60 * 1000
1719
+
1720
+ export async function loadHostLock(url = new URL("./ouro-host-lock.mjs", import.meta.url)) {
1721
+ try { return await import(url.href) } catch (error) { if (error?.code === "ERR_MODULE_NOT_FOUND") return null; throw error }
1722
+ }
1723
+
1724
+ export const ROLLBACK_LOCKED = (held, lifecycle) => `ROLLBACK FAILED: ${held}. The Butler may be down or on the failed upgrade. Host supervision stays paused for about 30 minutes; after that the keeper's authority boot retries the rollback (that retry does not check the host lock). To roll back sooner once the lock is free: \`touch ${MAINTENANCE}; node ${lifecycle} upgrade-rollback\`.`
1725
+
1726
+ /**
1727
+ * Takes the host lock for this process before the upgrade changes anything, waiting up to waitMs while someone else
1728
+ * holds it. Handed butler:ship's token, it takes that lock over with this pid and a fresh expiry, so the lock lasts
1729
+ * exactly as long as the upgrade does. { token, adopted } or { refusal }; { token: undefined } on a host with neither
1730
+ * a lock nor the script to take one.
1731
+ */
1732
+ export function hostLockTake(what, {
1733
+ lockModule, dir = HOST_LOCK_DIR, token = process.env.OURO_HOST_LOCK_TOKEN, holder, pid = process.pid, ttlMs = HOST_LOCK_TTL_MS,
1734
+ waitMs = Number(process.env.OURO_HOST_LOCK_WAIT_S || 30 * 60) * 1000, pollMs = 15_000,
1735
+ now = Date.now, sleep = (ms) => sh("/bin/sleep", [String(ms / 1000)]), log = console.log,
1736
+ } = {}) {
1737
+ if (!lockModule) return existsSync(dir) ? { refusal: `the host lock ${dir} exists and ouro-host-lock.mjs is not beside this script to read it, so ${what} did not run` } : { token: undefined, adopted: false }
1738
+ const start = now()
1739
+ let said = false
1740
+ for (;;) {
1741
+ let got
1742
+ try { got = lockModule.tryAcquire(dir, { holder, ttlMs, pid, adopt: token }, { now }) } catch (error) {
1743
+ if (!/guard .* is busy/.test(String(error?.message))) return { refusal: `the host lock could not be taken (${error?.message ?? error}), so ${what} did not run` }
1744
+ got = { acquired: false, owner: { unreadable: true } }
1745
+ }
1746
+ if (got.acquired) return { token: got.token, adopted: Boolean(got.adopted) }
1747
+ const owner = lockModule.describeOwner(got.owner)
1748
+ if (now() - start >= waitMs) return { refusal: `the host lock is held by ${owner}, so ${what} did not run` }
1749
+ if (!said) { log(` waiting: the host lock is held by ${owner}; ${what} waits for it`); said = true }
1750
+ sleep(pollMs)
1751
+ }
1752
+ }
1753
+
1754
+ /** On exit: hands an adopted lock back to the ship that owns it (no pid, a short expiry), or frees one taken here. */
1755
+ export function hostLockLeave(taken, { lockModule, dir = HOST_LOCK_DIR, holder }) {
1756
+ if (!lockModule || !taken.token) return
1757
+ try {
1758
+ if (taken.adopted) lockModule.handBack(dir, taken.token, { holder, ttlMs: HAND_BACK_TTL_MS })
1759
+ else lockModule.release(dir, taken.token)
1760
+ } catch { /* the lock goes stale with this process */ }
1761
+ }
1762
+
1763
+ /** null when the way is clear; otherwise why `what` must not run. Waits up to waitMs while someone else holds the lock. */
1764
+ export function hostLockWait(what, {
1765
+ lockModule, dir = HOST_LOCK_DIR, token = process.env.OURO_HOST_LOCK_TOKEN,
1766
+ waitMs = Number(process.env.OURO_HOST_LOCK_WAIT_S || 30 * 60) * 1000, pollMs = 15_000,
1767
+ now = Date.now, sleep = (ms) => sh("/bin/sleep", [String(ms / 1000)]), log = console.log,
1768
+ } = {}) {
1769
+ if (!existsSync(dir)) return null
1770
+ if (!lockModule) return `the host lock ${dir} exists and ouro-host-lock.mjs is not beside this script to read it, so ${what} did not run`
1771
+ const start = now()
1772
+ let said = false
1773
+ for (;;) {
1774
+ const owner = lockModule.blocker(dir, token, { now })
1775
+ if (!owner) return null
1776
+ const holder = lockModule.describeOwner(owner)
1777
+ if (now() - start >= waitMs) return `the host lock is held by ${holder}, so ${what} did not run`
1778
+ if (!said) { log(` waiting: the host lock is held by ${holder}; ${what} waits for it`); said = true }
1779
+ sleep(pollMs)
1780
+ }
1781
+ }
1782
+
1783
+ // ---- entry ----------------------------------------------------------------
1784
+
1785
+ export function parseUpgradeArgs(argv) {
1786
+ const usage = "Usage: sanctuary-butler-upgrade.mjs <preflight|prepare|install|upgrade> <version> [--rehearse <step>] [--no-gate] [--plant <case>] | preflight <version> --fresh | prepare <version> --fresh --owner-id <id> | verify [--gate]"
1787
+ const [phase, ...rest] = argv
1788
+ if (!phase || !["preflight", "prepare", "install", "verify", "upgrade"].includes(phase)) throw new Error(usage)
1789
+ const parsed = { phase, version: undefined, rehearse: undefined, noGate: false, plant: undefined, gate: false, fresh: false, ownerId: undefined }
1790
+ for (let i = 0; i < rest.length; i += 1) {
1791
+ const arg = rest[i]
1792
+ if (arg === "--rehearse" && phase === "upgrade" && rest[i + 1]) parsed.rehearse = rest[++i]
1793
+ else if (arg === "--no-gate" && phase === "upgrade") parsed.noGate = true
1794
+ else if (arg === "--plant" && phase === "upgrade" && rest[i + 1]) parsed.plant = rest[++i]
1795
+ else if (arg === "--gate" && phase === "verify") parsed.gate = true
1796
+ else if (arg === "--fresh" && (phase === "preflight" || phase === "prepare")) parsed.fresh = true
1797
+ else if (arg === "--owner-id" && phase === "prepare" && rest[i + 1]) parsed.ownerId = rest[++i]
1798
+ else if (!arg.startsWith("--") && parsed.version === undefined && phase !== "verify") parsed.version = arg
1799
+ else throw new Error(usage)
1800
+ }
1801
+ if (parsed.noGate && parsed.plant) throw new Error("--plant needs the gate; it cannot be combined with --no-gate")
1802
+ if (parsed.rehearse && (parsed.noGate || parsed.plant)) throw new Error("--rehearse does not use the gate; do not combine it with --no-gate or --plant")
1803
+ if (phase === "prepare" && parsed.fresh !== (parsed.ownerId !== undefined)) throw new Error("prepare --fresh needs --owner-id <the owner's Telegram user id>, and --owner-id needs --fresh")
1804
+ if (parsed.ownerId !== undefined && !/^[1-9][0-9]*$/u.test(parsed.ownerId)) throw new Error("--owner-id must be a Telegram user id (a positive number)")
1805
+ if (phase !== "verify" && !/^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$/.test(parsed.version || "")) throw new Error("a semver version is required, e.g. 0.1.0-alpha.829")
1806
+ return parsed
1807
+ }
1808
+
1809
+ async function run(argv) {
1810
+ let args
1811
+ try { args = parseUpgradeArgs(argv) } catch (error) { console.error(error.message); process.exit(2) }
1812
+ requireRoot()
1813
+ if (args.phase === "preflight") preflight(args.version, { fresh: args.fresh })
1814
+ else if (args.phase === "prepare") await prepare(args.version, { fresh: args.fresh, ownerId: args.ownerId })
1815
+ else if (args.phase === "install") install(args.version)
1816
+ else if (args.phase === "verify") verify(args.gate)
1817
+ else if (args.phase === "upgrade") await upgrade(args.version, args.rehearse, { noGate: args.noGate, plant: args.plant })
1818
+ }
1819
+
1820
+ if (process.argv[1] && fileURLToPath(import.meta.url) === realpathSync(process.argv[1])) run(process.argv.slice(2)).catch((error) => { console.error(error); process.exit(1) })