@thebriangao/totem 1.4.4 → 2.0.0

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 (763) hide show
  1. package/.dev.vars.example +5 -0
  2. package/.dockerignore +5 -0
  3. package/.env.example +29 -20
  4. package/CHANGELOG.md +99 -1
  5. package/CONTRIBUTING.md +48 -116
  6. package/Dockerfile +46 -12
  7. package/README.md +172 -498
  8. package/SECURITY.md +36 -59
  9. package/TOOLS.md +448 -311
  10. package/WHOOP.md +497 -2659
  11. package/assets/brand/SOURCES.md +38 -0
  12. package/assets/brand/totem.png +0 -0
  13. package/assets/brand/totem.svg +13 -0
  14. package/assets/fonts/Manrope-OFL.txt +93 -0
  15. package/assets/fonts/manrope-latin.woff2 +0 -0
  16. package/dist/build_info.js +5 -0
  17. package/dist/build_info.js.map +1 -0
  18. package/dist/cli/app.js +675 -0
  19. package/dist/cli/app.js.map +1 -0
  20. package/dist/cli/auth.js +297 -0
  21. package/dist/cli/auth.js.map +1 -0
  22. package/dist/cli/auth_flow.js +268 -0
  23. package/dist/cli/auth_flow.js.map +1 -0
  24. package/dist/cli/browser_login.js +368 -0
  25. package/dist/cli/browser_login.js.map +1 -0
  26. package/dist/cli/clients.js +403 -0
  27. package/dist/cli/clients.js.map +1 -0
  28. package/dist/cli/deploy_record.js +96 -0
  29. package/dist/cli/deploy_record.js.map +1 -0
  30. package/dist/cli/index.js +39 -575
  31. package/dist/cli/index.js.map +1 -1
  32. package/dist/cli/links.js +28 -0
  33. package/dist/cli/links.js.map +1 -0
  34. package/dist/cli/logo.js +63 -0
  35. package/dist/cli/logo.js.map +1 -0
  36. package/dist/cli/setup.js +1157 -1017
  37. package/dist/cli/setup.js.map +1 -1
  38. package/dist/cli/spawn.js +80 -0
  39. package/dist/cli/spawn.js.map +1 -0
  40. package/dist/cli/sys.js +219 -0
  41. package/dist/cli/sys.js.map +1 -0
  42. package/dist/cli/ui.js +712 -463
  43. package/dist/cli/ui.js.map +1 -1
  44. package/dist/cli/update.js +425 -282
  45. package/dist/cli/update.js.map +1 -1
  46. package/dist/cloudflare/token_store.js +48 -0
  47. package/dist/cloudflare/token_store.js.map +1 -0
  48. package/dist/cloudflare/worker.js +155 -0
  49. package/dist/cloudflare/worker.js.map +1 -0
  50. package/dist/data/behaviors.js +2733 -617
  51. package/dist/data/behaviors.js.map +1 -1
  52. package/dist/data/endpoint_catalog.js +2681 -0
  53. package/dist/data/endpoint_catalog.js.map +1 -0
  54. package/dist/data/exercises.js +373 -4859
  55. package/dist/data/exercises.js.map +1 -1
  56. package/dist/data/garments.js +19 -0
  57. package/dist/data/garments.js.map +1 -0
  58. package/dist/data/sports.js +219 -208
  59. package/dist/data/sports.js.map +1 -1
  60. package/dist/lib/activity_list.js +123 -0
  61. package/dist/lib/activity_list.js.map +1 -0
  62. package/dist/lib/activity_records.js +195 -0
  63. package/dist/lib/activity_records.js.map +1 -0
  64. package/dist/lib/activity_results.js +44 -0
  65. package/dist/lib/activity_results.js.map +1 -0
  66. package/dist/lib/activity_types.js +164 -0
  67. package/dist/lib/activity_types.js.map +1 -0
  68. package/dist/lib/brand.js +63 -0
  69. package/dist/lib/brand.js.map +1 -0
  70. package/dist/lib/clock.js +24 -0
  71. package/dist/lib/clock.js.map +1 -0
  72. package/dist/lib/coach_session.js +345 -0
  73. package/dist/lib/coach_session.js.map +1 -0
  74. package/dist/lib/concurrency.js.map +1 -1
  75. package/dist/lib/dates.js +19 -0
  76. package/dist/lib/dates.js.map +1 -1
  77. package/dist/lib/env_file.js +195 -0
  78. package/dist/lib/env_file.js.map +1 -0
  79. package/dist/lib/health_plans_write.js +44 -0
  80. package/dist/lib/health_plans_write.js.map +1 -0
  81. package/dist/lib/heart_rate.js +34 -0
  82. package/dist/lib/heart_rate.js.map +1 -0
  83. package/dist/lib/highlight.js +81 -0
  84. package/dist/lib/highlight.js.map +1 -0
  85. package/dist/lib/install_links.js +47 -0
  86. package/dist/lib/install_links.js.map +1 -0
  87. package/dist/lib/instant.js +50 -0
  88. package/dist/lib/instant.js.map +1 -0
  89. package/dist/lib/journal_behaviors.js +382 -0
  90. package/dist/lib/journal_behaviors.js.map +1 -0
  91. package/dist/lib/lift_catalog.js +218 -0
  92. package/dist/lib/lift_catalog.js.map +1 -0
  93. package/dist/lib/lift_history.js +66 -0
  94. package/dist/lib/lift_history.js.map +1 -0
  95. package/dist/lib/lift_sets.js +146 -0
  96. package/dist/lib/lift_sets.js.map +1 -0
  97. package/dist/lib/lift_tool.js +20 -0
  98. package/dist/lib/lift_tool.js.map +1 -0
  99. package/dist/lib/profile_settings.js +101 -0
  100. package/dist/lib/profile_settings.js.map +1 -0
  101. package/dist/lib/screen_content.js +44 -0
  102. package/dist/lib/screen_content.js.map +1 -0
  103. package/dist/lib/timezone.js +48 -6
  104. package/dist/lib/timezone.js.map +1 -1
  105. package/dist/lib/walk.js +6 -1
  106. package/dist/lib/walk.js.map +1 -1
  107. package/dist/lib/weight_readings.js +61 -0
  108. package/dist/lib/weight_readings.js.map +1 -0
  109. package/dist/projections/activities.js +193 -0
  110. package/dist/projections/activities.js.map +1 -0
  111. package/dist/projections/alarm_schedule.js +102 -0
  112. package/dist/projections/alarm_schedule.js.map +1 -0
  113. package/dist/projections/coach.js +203 -0
  114. package/dist/projections/coach.js.map +1 -0
  115. package/dist/projections/community.js +165 -0
  116. package/dist/projections/community.js.map +1 -0
  117. package/dist/projections/health_features.js +167 -0
  118. package/dist/projections/health_features.js.map +1 -0
  119. package/dist/projections/hormonal_insights.js +239 -0
  120. package/dist/projections/hormonal_insights.js.map +1 -0
  121. package/dist/projections/journal_v2.js +157 -0
  122. package/dist/projections/journal_v2.js.map +1 -0
  123. package/dist/projections/lift_cards.js +115 -0
  124. package/dist/projections/lift_cards.js.map +1 -0
  125. package/dist/projections/lift_exercise_v2.js +131 -0
  126. package/dist/projections/lift_exercise_v2.js.map +1 -0
  127. package/dist/projections/lift_library_v2.js +67 -0
  128. package/dist/projections/lift_library_v2.js.map +1 -0
  129. package/dist/projections/lift_sessions.js +211 -0
  130. package/dist/projections/lift_sessions.js.map +1 -0
  131. package/dist/projections/memory.js +95 -0
  132. package/dist/projections/memory.js.map +1 -0
  133. package/dist/projections/milestones.js +119 -0
  134. package/dist/projections/milestones.js.map +1 -0
  135. package/dist/projections/profile_v2.js +150 -0
  136. package/dist/projections/profile_v2.js.map +1 -0
  137. package/dist/projections/settings_v2.js +153 -0
  138. package/dist/projections/settings_v2.js.map +1 -0
  139. package/dist/projections/sleep.js +4 -21
  140. package/dist/projections/sleep.js.map +1 -1
  141. package/dist/projections/v2/calendar.js +43 -0
  142. package/dist/projections/v2/calendar.js.map +1 -0
  143. package/dist/projections/v2/core_common.js +86 -0
  144. package/dist/projections/v2/core_common.js.map +1 -0
  145. package/dist/projections/v2/core_home.js +136 -0
  146. package/dist/projections/v2/core_home.js.map +1 -0
  147. package/dist/projections/v2/core_sleep_need.js +23 -0
  148. package/dist/projections/v2/core_sleep_need.js.map +1 -0
  149. package/dist/projections/v2/day.js +92 -0
  150. package/dist/projections/v2/day.js.map +1 -0
  151. package/dist/projections/v2/heart_rate.js +54 -0
  152. package/dist/projections/v2/heart_rate.js.map +1 -0
  153. package/dist/projections/v2/history.js +140 -0
  154. package/dist/projections/v2/history.js.map +1 -0
  155. package/dist/projections/v2/now.js +39 -0
  156. package/dist/projections/v2/now.js.map +1 -0
  157. package/dist/projections/v2/recovery.js +77 -0
  158. package/dist/projections/v2/recovery.js.map +1 -0
  159. package/dist/projections/v2/sleep.js +218 -0
  160. package/dist/projections/v2/sleep.js.map +1 -0
  161. package/dist/projections/v2/strain.js +39 -0
  162. package/dist/projections/v2/strain.js.map +1 -0
  163. package/dist/projections/v2/stress.js +92 -0
  164. package/dist/projections/v2/stress.js.map +1 -0
  165. package/dist/projections/v2/trend.js +205 -0
  166. package/dist/projections/v2/trend.js.map +1 -0
  167. package/dist/projections/weekly_plan.js +66 -0
  168. package/dist/projections/weekly_plan.js.map +1 -0
  169. package/dist/projections/weight_readings.js +57 -0
  170. package/dist/projections/weight_readings.js.map +1 -0
  171. package/dist/projections/workout.js +37 -15
  172. package/dist/projections/workout.js.map +1 -1
  173. package/dist/schemas/activities.js +123 -0
  174. package/dist/schemas/activities.js.map +1 -0
  175. package/dist/schemas/alarm_schedule.js +62 -0
  176. package/dist/schemas/alarm_schedule.js.map +1 -0
  177. package/dist/schemas/coach.js +76 -8
  178. package/dist/schemas/coach.js.map +1 -1
  179. package/dist/schemas/community.js +70 -0
  180. package/dist/schemas/community.js.map +1 -0
  181. package/dist/schemas/health.js +36 -0
  182. package/dist/schemas/health.js.map +1 -0
  183. package/dist/schemas/hormonal_insights.js +90 -0
  184. package/dist/schemas/hormonal_insights.js.map +1 -0
  185. package/dist/schemas/journal.js +4 -0
  186. package/dist/schemas/journal.js.map +1 -1
  187. package/dist/schemas/journal_v2.js +106 -0
  188. package/dist/schemas/journal_v2.js.map +1 -0
  189. package/dist/schemas/memory.js +42 -0
  190. package/dist/schemas/memory.js.map +1 -0
  191. package/dist/schemas/milestones.js +39 -0
  192. package/dist/schemas/milestones.js.map +1 -0
  193. package/dist/schemas/profile_v2.js +60 -0
  194. package/dist/schemas/profile_v2.js.map +1 -0
  195. package/dist/schemas/settings_v2.js +56 -0
  196. package/dist/schemas/settings_v2.js.map +1 -0
  197. package/dist/schemas/sleep.js +8 -1
  198. package/dist/schemas/sleep.js.map +1 -1
  199. package/dist/schemas/strength.js +10 -1
  200. package/dist/schemas/strength.js.map +1 -1
  201. package/dist/schemas/strength_v2.js +190 -0
  202. package/dist/schemas/strength_v2.js.map +1 -0
  203. package/dist/schemas/v2/calendar.js +8 -0
  204. package/dist/schemas/v2/calendar.js.map +1 -0
  205. package/dist/schemas/v2/core_common.js +42 -0
  206. package/dist/schemas/v2/core_common.js.map +1 -0
  207. package/dist/schemas/v2/day.js +73 -0
  208. package/dist/schemas/v2/day.js.map +1 -0
  209. package/dist/schemas/v2/now.js +25 -0
  210. package/dist/schemas/v2/now.js.map +1 -0
  211. package/dist/schemas/v2/recovery.js +35 -0
  212. package/dist/schemas/v2/recovery.js.map +1 -0
  213. package/dist/schemas/v2/sleep.js +44 -0
  214. package/dist/schemas/v2/sleep.js.map +1 -0
  215. package/dist/schemas/v2/strain.js +16 -0
  216. package/dist/schemas/v2/strain.js.map +1 -0
  217. package/dist/schemas/v2/stress.js +20 -0
  218. package/dist/schemas/v2/stress.js.map +1 -0
  219. package/dist/schemas/v2/trend.js +42 -0
  220. package/dist/schemas/v2/trend.js.map +1 -0
  221. package/dist/schemas/weekly_plan.js +31 -0
  222. package/dist/schemas/weekly_plan.js.map +1 -0
  223. package/dist/schemas/weight.js +28 -0
  224. package/dist/schemas/weight.js.map +1 -0
  225. package/dist/scripts/build_behaviors.js +114 -0
  226. package/dist/scripts/build_behaviors.js.map +1 -0
  227. package/dist/scripts/cognito_bootstrap.js +9 -277
  228. package/dist/scripts/cognito_bootstrap.js.map +1 -1
  229. package/dist/scripts/gen_activity_catalogs.js +104 -0
  230. package/dist/scripts/gen_activity_catalogs.js.map +1 -0
  231. package/dist/server-admin.js +156 -0
  232. package/dist/server-admin.js.map +1 -0
  233. package/dist/server-http.js +270 -48
  234. package/dist/server-http.js.map +1 -1
  235. package/dist/server.js +136 -23
  236. package/dist/server.js.map +1 -1
  237. package/dist/tools/annotations.js +15 -0
  238. package/dist/tools/annotations.js.map +1 -0
  239. package/dist/tools/define.js +31 -0
  240. package/dist/tools/define.js.map +1 -0
  241. package/dist/tools/register.js +59 -94
  242. package/dist/tools/register.js.map +1 -1
  243. package/dist/tools/resources.js +70 -0
  244. package/dist/tools/resources.js.map +1 -0
  245. package/dist/tools/slim_schema.js +90 -0
  246. package/dist/tools/slim_schema.js.map +1 -0
  247. package/dist/tools/v2/activity_delete.js +63 -17
  248. package/dist/tools/v2/activity_delete.js.map +1 -1
  249. package/dist/tools/v2/activity_edit.js +396 -0
  250. package/dist/tools/v2/activity_edit.js.map +1 -0
  251. package/dist/tools/v2/activity_log.js +152 -0
  252. package/dist/tools/v2/activity_log.js.map +1 -0
  253. package/dist/tools/v2/calendar.js +19 -21
  254. package/dist/tools/v2/calendar.js.map +1 -1
  255. package/dist/tools/v2/coach_ask.js +74 -110
  256. package/dist/tools/v2/coach_ask.js.map +1 -1
  257. package/dist/tools/v2/coach_history.js +120 -0
  258. package/dist/tools/v2/coach_history.js.map +1 -0
  259. package/dist/tools/v2/community.js +124 -0
  260. package/dist/tools/v2/community.js.map +1 -0
  261. package/dist/tools/v2/cycle.js +63 -15
  262. package/dist/tools/v2/cycle.js.map +1 -1
  263. package/dist/tools/v2/cycle_log.js +289 -32
  264. package/dist/tools/v2/cycle_log.js.map +1 -1
  265. package/dist/tools/v2/day.js +126 -24
  266. package/dist/tools/v2/day.js.map +1 -1
  267. package/dist/tools/v2/health.js +116 -0
  268. package/dist/tools/v2/health.js.map +1 -0
  269. package/dist/tools/v2/hr_zones_set.js +134 -34
  270. package/dist/tools/v2/hr_zones_set.js.map +1 -1
  271. package/dist/tools/v2/journal.js +75 -17
  272. package/dist/tools/v2/journal.js.map +1 -1
  273. package/dist/tools/v2/journal_log.js +306 -65
  274. package/dist/tools/v2/journal_log.js.map +1 -1
  275. package/dist/tools/v2/lift_exercise.js +125 -22
  276. package/dist/tools/v2/lift_exercise.js.map +1 -1
  277. package/dist/tools/v2/lift_exercise_set.js +291 -0
  278. package/dist/tools/v2/lift_exercise_set.js.map +1 -0
  279. package/dist/tools/v2/lift_library.js +51 -12
  280. package/dist/tools/v2/lift_library.js.map +1 -1
  281. package/dist/tools/v2/lift_log.js +309 -72
  282. package/dist/tools/v2/lift_log.js.map +1 -1
  283. package/dist/tools/v2/lift_sessions.js +248 -0
  284. package/dist/tools/v2/lift_sessions.js.map +1 -0
  285. package/dist/tools/v2/lift_template.js +232 -0
  286. package/dist/tools/v2/lift_template.js.map +1 -0
  287. package/dist/tools/v2/memory.js +45 -0
  288. package/dist/tools/v2/memory.js.map +1 -0
  289. package/dist/tools/v2/memory_set.js +107 -0
  290. package/dist/tools/v2/memory_set.js.map +1 -0
  291. package/dist/tools/v2/milestones.js +50 -0
  292. package/dist/tools/v2/milestones.js.map +1 -0
  293. package/dist/tools/v2/now.js +49 -0
  294. package/dist/tools/v2/now.js.map +1 -0
  295. package/dist/tools/v2/preferences.js +51 -0
  296. package/dist/tools/v2/preferences.js.map +1 -0
  297. package/dist/tools/v2/preferences_set.js +388 -0
  298. package/dist/tools/v2/preferences_set.js.map +1 -0
  299. package/dist/tools/v2/profile.js +54 -22
  300. package/dist/tools/v2/profile.js.map +1 -1
  301. package/dist/tools/v2/profile_update.js +167 -55
  302. package/dist/tools/v2/profile_update.js.map +1 -1
  303. package/dist/tools/v2/raw.js +91 -34
  304. package/dist/tools/v2/raw.js.map +1 -1
  305. package/dist/tools/v2/recovery.js +37 -23
  306. package/dist/tools/v2/recovery.js.map +1 -1
  307. package/dist/tools/v2/sleep.js +52 -16
  308. package/dist/tools/v2/sleep.js.map +1 -1
  309. package/dist/tools/v2/smart_alarm.js +54 -20
  310. package/dist/tools/v2/smart_alarm.js.map +1 -1
  311. package/dist/tools/v2/smart_alarm_set.js +264 -86
  312. package/dist/tools/v2/smart_alarm_set.js.map +1 -1
  313. package/dist/tools/v2/strain.js +15 -15
  314. package/dist/tools/v2/strain.js.map +1 -1
  315. package/dist/tools/v2/stress.js +17 -15
  316. package/dist/tools/v2/stress.js.map +1 -1
  317. package/dist/tools/v2/trend.js +56 -20
  318. package/dist/tools/v2/trend.js.map +1 -1
  319. package/dist/tools/v2/weekly_plan.js +30 -0
  320. package/dist/tools/v2/weekly_plan.js.map +1 -0
  321. package/dist/tools/v2/weekly_plan_set.js +134 -0
  322. package/dist/tools/v2/weekly_plan_set.js.map +1 -0
  323. package/dist/tools/v2/weight.js +56 -0
  324. package/dist/tools/v2/weight.js.map +1 -0
  325. package/dist/tools/v2/weight_log.js +188 -0
  326. package/dist/tools/v2/weight_log.js.map +1 -0
  327. package/dist/tools/v2/workouts.js +159 -25
  328. package/dist/tools/v2/workouts.js.map +1 -1
  329. package/dist/version.js +6 -0
  330. package/dist/version.js.map +1 -0
  331. package/dist/whoop/bff.js +94 -0
  332. package/dist/whoop/bff.js.map +1 -0
  333. package/dist/whoop/client.js +392 -18
  334. package/dist/whoop/client.js.map +1 -1
  335. package/dist/whoop/cognito.js +106 -79
  336. package/dist/whoop/cognito.js.map +1 -1
  337. package/dist/whoop/connect_page.js +165 -0
  338. package/dist/whoop/connect_page.js.map +1 -0
  339. package/dist/whoop/consent_font.js +287 -0
  340. package/dist/whoop/consent_font.js.map +1 -0
  341. package/dist/whoop/consent_logos.js +22 -0
  342. package/dist/whoop/consent_logos.js.map +1 -0
  343. package/dist/whoop/consent_page.js +291 -0
  344. package/dist/whoop/consent_page.js.map +1 -0
  345. package/dist/whoop/constants.js +5 -1
  346. package/dist/whoop/constants.js.map +1 -1
  347. package/dist/whoop/device.js +4 -4
  348. package/dist/whoop/device.js.map +1 -1
  349. package/dist/whoop/errors.js +85 -4
  350. package/dist/whoop/errors.js.map +1 -1
  351. package/dist/whoop/init_timezone.js +57 -17
  352. package/dist/whoop/init_timezone.js.map +1 -1
  353. package/dist/whoop/installation.js +15 -10
  354. package/dist/whoop/installation.js.map +1 -1
  355. package/dist/whoop/json_out.js +52 -6
  356. package/dist/whoop/json_out.js.map +1 -1
  357. package/dist/whoop/oauth_provider.js +81 -78
  358. package/dist/whoop/oauth_provider.js.map +1 -1
  359. package/dist/whoop/token_lock.js +331 -0
  360. package/dist/whoop/token_lock.js.map +1 -0
  361. package/dist/whoop/token_manager.js +536 -42
  362. package/dist/whoop/token_manager.js.map +1 -1
  363. package/dist/whoop/token_store.js +303 -36
  364. package/dist/whoop/token_store.js.map +1 -1
  365. package/dist/whoop/units.js +28 -0
  366. package/dist/whoop/units.js.map +1 -0
  367. package/package.json +29 -13
  368. package/scripts/build-mcpb.mjs +72 -0
  369. package/scripts/embed-consent-font.mjs +34 -0
  370. package/scripts/readme-media.ts +195 -0
  371. package/scripts/tools-md.ts +89 -0
  372. package/scripts/whoop-md.ts +119 -0
  373. package/src/build_info.ts +4 -0
  374. package/src/cli/app.ts +696 -0
  375. package/src/cli/auth.ts +350 -0
  376. package/src/cli/auth_flow.ts +356 -0
  377. package/src/cli/browser_login.ts +402 -0
  378. package/src/cli/clients.ts +467 -0
  379. package/src/cli/deploy_record.ts +100 -0
  380. package/src/cli/index.ts +41 -583
  381. package/src/cli/links.ts +43 -0
  382. package/src/cli/logo.ts +64 -0
  383. package/src/cli/setup.ts +1147 -979
  384. package/src/cli/spawn.ts +88 -0
  385. package/src/cli/sys.ts +267 -0
  386. package/src/cli/ui.ts +778 -436
  387. package/src/cli/update.ts +436 -274
  388. package/src/cloudflare/runtime.d.ts +27 -0
  389. package/src/cloudflare/token_store.ts +57 -0
  390. package/src/cloudflare/worker.ts +174 -0
  391. package/src/data/behaviors.ts +2760 -622
  392. package/src/data/endpoint_catalog.ts +2695 -0
  393. package/src/data/exercises.ts +379 -4861
  394. package/src/data/garments.ts +28 -0
  395. package/src/data/sports.ts +239 -211
  396. package/src/lib/activity_list.ts +150 -0
  397. package/src/lib/activity_records.ts +213 -0
  398. package/src/lib/activity_results.ts +51 -0
  399. package/src/lib/activity_types.ts +176 -0
  400. package/src/lib/brand.ts +71 -0
  401. package/src/lib/clock.ts +16 -0
  402. package/src/lib/coach_session.ts +434 -0
  403. package/src/lib/dates.ts +18 -0
  404. package/src/lib/env_file.ts +191 -0
  405. package/src/lib/health_plans_write.ts +53 -0
  406. package/src/lib/heart_rate.ts +42 -0
  407. package/src/lib/highlight.ts +71 -0
  408. package/src/lib/install_links.ts +61 -0
  409. package/src/lib/instant.ts +54 -0
  410. package/src/lib/journal_behaviors.ts +453 -0
  411. package/src/lib/lift_catalog.ts +258 -0
  412. package/src/lib/lift_history.ts +75 -0
  413. package/src/lib/lift_sets.ts +164 -0
  414. package/src/lib/lift_tool.ts +25 -0
  415. package/src/lib/profile_settings.ts +102 -0
  416. package/src/lib/screen_content.ts +40 -0
  417. package/src/lib/timezone.ts +44 -8
  418. package/src/lib/walk.ts +4 -1
  419. package/src/lib/weight_readings.ts +82 -0
  420. package/src/projections/activities.ts +199 -0
  421. package/src/projections/alarm_schedule.ts +98 -0
  422. package/src/projections/coach.ts +218 -0
  423. package/src/projections/community.ts +187 -0
  424. package/src/projections/health_features.ts +191 -0
  425. package/src/projections/hormonal_insights.ts +277 -0
  426. package/src/projections/journal_v2.ts +173 -0
  427. package/src/projections/lift_cards.ts +131 -0
  428. package/src/projections/lift_exercise_v2.ts +147 -0
  429. package/src/projections/lift_library_v2.ts +77 -0
  430. package/src/projections/lift_sessions.ts +250 -0
  431. package/src/projections/memory.ts +100 -0
  432. package/src/projections/milestones.ts +133 -0
  433. package/src/projections/profile_v2.ts +166 -0
  434. package/src/projections/settings_v2.ts +179 -0
  435. package/src/projections/sleep.ts +7 -21
  436. package/src/projections/v2/calendar.ts +48 -0
  437. package/src/projections/v2/core_common.ts +95 -0
  438. package/src/projections/v2/core_home.ts +177 -0
  439. package/src/projections/v2/core_sleep_need.ts +37 -0
  440. package/src/projections/v2/day.ts +162 -0
  441. package/src/projections/v2/heart_rate.ts +73 -0
  442. package/src/projections/v2/history.ts +153 -0
  443. package/src/projections/v2/now.ts +59 -0
  444. package/src/projections/v2/recovery.ts +120 -0
  445. package/src/projections/v2/sleep.ts +281 -0
  446. package/src/projections/v2/strain.ts +63 -0
  447. package/src/projections/v2/stress.ts +111 -0
  448. package/src/projections/v2/trend.ts +242 -0
  449. package/src/projections/weekly_plan.ts +79 -0
  450. package/src/projections/weight_readings.ts +57 -0
  451. package/src/projections/workout.ts +36 -17
  452. package/src/schemas/activities.ts +136 -0
  453. package/src/schemas/alarm_schedule.ts +70 -0
  454. package/src/schemas/coach.ts +98 -8
  455. package/src/schemas/community.ts +77 -0
  456. package/src/schemas/health.ts +36 -0
  457. package/src/schemas/hormonal_insights.ts +108 -0
  458. package/src/schemas/journal.ts +4 -0
  459. package/src/schemas/journal_v2.ts +112 -0
  460. package/src/schemas/memory.ts +48 -0
  461. package/src/schemas/milestones.ts +48 -0
  462. package/src/schemas/profile_v2.ts +63 -0
  463. package/src/schemas/settings_v2.ts +63 -0
  464. package/src/schemas/sleep.ts +9 -1
  465. package/src/schemas/strength.ts +10 -1
  466. package/src/schemas/strength_v2.ts +210 -0
  467. package/src/schemas/v2/calendar.ts +8 -0
  468. package/src/schemas/v2/core_common.ts +50 -0
  469. package/src/schemas/v2/day.ts +79 -0
  470. package/src/schemas/v2/now.ts +25 -0
  471. package/src/schemas/v2/recovery.ts +38 -0
  472. package/src/schemas/v2/sleep.ts +46 -0
  473. package/src/schemas/v2/strain.ts +16 -0
  474. package/src/schemas/v2/stress.ts +20 -0
  475. package/src/schemas/v2/trend.ts +45 -0
  476. package/src/schemas/weekly_plan.ts +36 -0
  477. package/src/schemas/weight.ts +53 -0
  478. package/src/scripts/build_behaviors.ts +116 -0
  479. package/src/scripts/cognito_bootstrap.ts +10 -249
  480. package/src/scripts/gen_activity_catalogs.ts +121 -0
  481. package/src/server-admin.ts +171 -0
  482. package/src/server-http.ts +290 -53
  483. package/src/server.ts +130 -26
  484. package/src/tools/annotations.ts +25 -0
  485. package/src/tools/define.ts +53 -0
  486. package/src/tools/register.ts +64 -94
  487. package/src/tools/resources.ts +92 -0
  488. package/src/tools/slim_schema.ts +102 -0
  489. package/src/tools/v2/activity_delete.ts +61 -23
  490. package/src/tools/v2/activity_edit.ts +378 -0
  491. package/src/tools/v2/activity_log.ts +154 -0
  492. package/src/tools/v2/calendar.ts +22 -21
  493. package/src/tools/v2/coach_ask.ts +83 -119
  494. package/src/tools/v2/coach_history.ts +140 -0
  495. package/src/tools/v2/community.ts +137 -0
  496. package/src/tools/v2/cycle.ts +78 -20
  497. package/src/tools/v2/cycle_log.ts +291 -40
  498. package/src/tools/v2/day.ts +126 -25
  499. package/src/tools/v2/health.ts +114 -0
  500. package/src/tools/v2/hr_zones_set.ts +132 -45
  501. package/src/tools/v2/journal.ts +78 -23
  502. package/src/tools/v2/journal_log.ts +321 -69
  503. package/src/tools/v2/lift_exercise.ts +135 -27
  504. package/src/tools/v2/lift_exercise_set.ts +272 -0
  505. package/src/tools/v2/lift_library.ts +57 -21
  506. package/src/tools/v2/lift_log.ts +325 -83
  507. package/src/tools/v2/lift_sessions.ts +255 -0
  508. package/src/tools/v2/lift_template.ts +229 -0
  509. package/src/tools/v2/memory.ts +54 -0
  510. package/src/tools/v2/memory_set.ts +110 -0
  511. package/src/tools/v2/milestones.ts +59 -0
  512. package/src/tools/v2/now.ts +61 -0
  513. package/src/tools/v2/preferences.ts +61 -0
  514. package/src/tools/v2/preferences_set.ts +403 -0
  515. package/src/tools/v2/profile.ts +56 -26
  516. package/src/tools/v2/profile_update.ts +151 -60
  517. package/src/tools/v2/raw.ts +89 -36
  518. package/src/tools/v2/recovery.ts +44 -25
  519. package/src/tools/v2/sleep.ts +57 -18
  520. package/src/tools/v2/smart_alarm.ts +62 -24
  521. package/src/tools/v2/smart_alarm_set.ts +240 -90
  522. package/src/tools/v2/strain.ts +19 -16
  523. package/src/tools/v2/stress.ts +22 -17
  524. package/src/tools/v2/trend.ts +58 -20
  525. package/src/tools/v2/weekly_plan.ts +38 -0
  526. package/src/tools/v2/weekly_plan_set.ts +132 -0
  527. package/src/tools/v2/weight.ts +61 -0
  528. package/src/tools/v2/weight_log.ts +193 -0
  529. package/src/tools/v2/workouts.ts +156 -26
  530. package/src/version.ts +5 -0
  531. package/src/whoop/bff.ts +84 -0
  532. package/src/whoop/client.ts +448 -18
  533. package/src/whoop/cognito.ts +110 -99
  534. package/src/whoop/connect_page.ts +183 -0
  535. package/src/whoop/consent_font.ts +289 -0
  536. package/src/whoop/consent_logos.ts +24 -0
  537. package/src/whoop/consent_page.ts +326 -0
  538. package/src/whoop/constants.ts +5 -1
  539. package/src/whoop/device.ts +4 -4
  540. package/src/whoop/errors.ts +89 -4
  541. package/src/whoop/init_timezone.ts +57 -16
  542. package/src/whoop/installation.ts +16 -7
  543. package/src/whoop/json_out.ts +51 -6
  544. package/src/whoop/oauth_provider.ts +84 -91
  545. package/src/whoop/token_lock.ts +345 -0
  546. package/src/whoop/token_manager.ts +580 -53
  547. package/src/whoop/token_store.ts +341 -32
  548. package/src/whoop/units.ts +35 -0
  549. package/wrangler.jsonc +17 -0
  550. package/assets/banner.svg +0 -38
  551. package/dist/data/endpoints.js +0 -320
  552. package/dist/data/endpoints.js.map +0 -1
  553. package/dist/lib/format.js +0 -22
  554. package/dist/lib/format.js.map +0 -1
  555. package/dist/lib/stats.js +0 -32
  556. package/dist/lib/stats.js.map +0 -1
  557. package/dist/projections/calendar.js +0 -33
  558. package/dist/projections/calendar.js.map +0 -1
  559. package/dist/projections/communities.js +0 -105
  560. package/dist/projections/communities.js.map +0 -1
  561. package/dist/projections/cycle.js +0 -81
  562. package/dist/projections/cycle.js.map +0 -1
  563. package/dist/projections/hr_zones.js +0 -35
  564. package/dist/projections/hr_zones.js.map +0 -1
  565. package/dist/projections/journal.js +0 -56
  566. package/dist/projections/journal.js.map +0 -1
  567. package/dist/projections/leaderboard.js +0 -37
  568. package/dist/projections/leaderboard.js.map +0 -1
  569. package/dist/projections/lift_exercise.js +0 -22
  570. package/dist/projections/lift_exercise.js.map +0 -1
  571. package/dist/projections/lift_history.js +0 -133
  572. package/dist/projections/lift_history.js.map +0 -1
  573. package/dist/projections/lift_library.js +0 -71
  574. package/dist/projections/lift_library.js.map +0 -1
  575. package/dist/projections/lift_progression.js +0 -138
  576. package/dist/projections/lift_progression.js.map +0 -1
  577. package/dist/projections/lift_prs.js +0 -20
  578. package/dist/projections/lift_prs.js.map +0 -1
  579. package/dist/projections/live_hr.js +0 -19
  580. package/dist/projections/live_hr.js.map +0 -1
  581. package/dist/projections/live_state.js +0 -23
  582. package/dist/projections/live_state.js.map +0 -1
  583. package/dist/projections/live_stress.js +0 -11
  584. package/dist/projections/live_stress.js.map +0 -1
  585. package/dist/projections/performance_assessment.js +0 -15
  586. package/dist/projections/performance_assessment.js.map +0 -1
  587. package/dist/projections/profile.js +0 -59
  588. package/dist/projections/profile.js.map +0 -1
  589. package/dist/projections/recovery.js +0 -131
  590. package/dist/projections/recovery.js.map +0 -1
  591. package/dist/projections/sleep_need.js +0 -32
  592. package/dist/projections/sleep_need.js.map +0 -1
  593. package/dist/projections/smart_alarm.js +0 -45
  594. package/dist/projections/smart_alarm.js.map +0 -1
  595. package/dist/projections/strain.js +0 -128
  596. package/dist/projections/strain.js.map +0 -1
  597. package/dist/projections/stress.js +0 -86
  598. package/dist/projections/stress.js.map +0 -1
  599. package/dist/projections/today.js +0 -129
  600. package/dist/projections/today.js.map +0 -1
  601. package/dist/projections/trend.js +0 -149
  602. package/dist/projections/trend.js.map +0 -1
  603. package/dist/projections/workouts.js +0 -37
  604. package/dist/projections/workouts.js.map +0 -1
  605. package/dist/schemas/calendar.js +0 -12
  606. package/dist/schemas/calendar.js.map +0 -1
  607. package/dist/schemas/communities.js +0 -51
  608. package/dist/schemas/communities.js.map +0 -1
  609. package/dist/schemas/compare.js +0 -15
  610. package/dist/schemas/compare.js.map +0 -1
  611. package/dist/schemas/leaderboard.js +0 -25
  612. package/dist/schemas/leaderboard.js.map +0 -1
  613. package/dist/schemas/live.js +0 -26
  614. package/dist/schemas/live.js.map +0 -1
  615. package/dist/schemas/performance.js +0 -12
  616. package/dist/schemas/performance.js.map +0 -1
  617. package/dist/schemas/profile.js +0 -39
  618. package/dist/schemas/profile.js.map +0 -1
  619. package/dist/schemas/recovery.js +0 -27
  620. package/dist/schemas/recovery.js.map +0 -1
  621. package/dist/schemas/settings.js +0 -26
  622. package/dist/schemas/settings.js.map +0 -1
  623. package/dist/schemas/sleep_need.js +0 -15
  624. package/dist/schemas/sleep_need.js.map +0 -1
  625. package/dist/schemas/smart_alarm.js +0 -36
  626. package/dist/schemas/smart_alarm.js.map +0 -1
  627. package/dist/schemas/strain.js +0 -24
  628. package/dist/schemas/strain.js.map +0 -1
  629. package/dist/schemas/stress.js +0 -16
  630. package/dist/schemas/stress.js.map +0 -1
  631. package/dist/schemas/today.js +0 -38
  632. package/dist/schemas/today.js.map +0 -1
  633. package/dist/schemas/trend.js +0 -50
  634. package/dist/schemas/trend.js.map +0 -1
  635. package/dist/schemas/womens_health.js +0 -23
  636. package/dist/schemas/womens_health.js.map +0 -1
  637. package/dist/tools/v2/activity_create.js +0 -64
  638. package/dist/tools/v2/activity_create.js.map +0 -1
  639. package/dist/tools/v2/behavior_impact.js +0 -36
  640. package/dist/tools/v2/behavior_impact.js.map +0 -1
  641. package/dist/tools/v2/communities.js +0 -60
  642. package/dist/tools/v2/communities.js.map +0 -1
  643. package/dist/tools/v2/compare.js +0 -67
  644. package/dist/tools/v2/compare.js.map +0 -1
  645. package/dist/tools/v2/endpoints.js +0 -28
  646. package/dist/tools/v2/endpoints.js.map +0 -1
  647. package/dist/tools/v2/hidden_metric.js +0 -28
  648. package/dist/tools/v2/hidden_metric.js.map +0 -1
  649. package/dist/tools/v2/hr_zones.js +0 -24
  650. package/dist/tools/v2/hr_zones.js.map +0 -1
  651. package/dist/tools/v2/journal_autopop.js +0 -19
  652. package/dist/tools/v2/journal_autopop.js.map +0 -1
  653. package/dist/tools/v2/journal_catalog.js +0 -44
  654. package/dist/tools/v2/journal_catalog.js.map +0 -1
  655. package/dist/tools/v2/leaderboard.js +0 -79
  656. package/dist/tools/v2/leaderboard.js.map +0 -1
  657. package/dist/tools/v2/lift_catalog.js +0 -47
  658. package/dist/tools/v2/lift_catalog.js.map +0 -1
  659. package/dist/tools/v2/lift_custom_exercise.js +0 -108
  660. package/dist/tools/v2/lift_custom_exercise.js.map +0 -1
  661. package/dist/tools/v2/lift_history.js +0 -39
  662. package/dist/tools/v2/lift_history.js.map +0 -1
  663. package/dist/tools/v2/lift_progression.js +0 -30
  664. package/dist/tools/v2/lift_progression.js.map +0 -1
  665. package/dist/tools/v2/lift_prs.js +0 -21
  666. package/dist/tools/v2/lift_prs.js.map +0 -1
  667. package/dist/tools/v2/lift_template_save.js +0 -83
  668. package/dist/tools/v2/lift_template_save.js.map +0 -1
  669. package/dist/tools/v2/live_hr.js +0 -21
  670. package/dist/tools/v2/live_hr.js.map +0 -1
  671. package/dist/tools/v2/live_state.js +0 -21
  672. package/dist/tools/v2/live_state.js.map +0 -1
  673. package/dist/tools/v2/live_stress.js +0 -22
  674. package/dist/tools/v2/live_stress.js.map +0 -1
  675. package/dist/tools/v2/performance_assessment.js +0 -38
  676. package/dist/tools/v2/performance_assessment.js.map +0 -1
  677. package/dist/tools/v2/sleep_need.js +0 -21
  678. package/dist/tools/v2/sleep_need.js.map +0 -1
  679. package/dist/tools/v2/sports_catalog.js +0 -26
  680. package/dist/tools/v2/sports_catalog.js.map +0 -1
  681. package/dist/tools/v2/symptom_log.js +0 -72
  682. package/dist/tools/v2/symptom_log.js.map +0 -1
  683. package/dist/tools/v2/today.js +0 -30
  684. package/dist/tools/v2/today.js.map +0 -1
  685. package/dist/tools/v2/workout.js +0 -23
  686. package/dist/tools/v2/workout.js.map +0 -1
  687. package/dist/whoop/build_lift_body.js +0 -67
  688. package/dist/whoop/build_lift_body.js.map +0 -1
  689. package/dist/whoop/session_state.js +0 -34
  690. package/dist/whoop/session_state.js.map +0 -1
  691. package/dist/whoop/types.js +0 -82
  692. package/dist/whoop/types.js.map +0 -1
  693. package/src/data/endpoints.ts +0 -319
  694. package/src/lib/format.ts +0 -27
  695. package/src/lib/stats.ts +0 -35
  696. package/src/projections/calendar.ts +0 -46
  697. package/src/projections/communities.ts +0 -135
  698. package/src/projections/cycle.ts +0 -85
  699. package/src/projections/hr_zones.ts +0 -43
  700. package/src/projections/journal.ts +0 -55
  701. package/src/projections/leaderboard.ts +0 -49
  702. package/src/projections/lift_exercise.ts +0 -29
  703. package/src/projections/lift_history.ts +0 -140
  704. package/src/projections/lift_library.ts +0 -70
  705. package/src/projections/lift_progression.ts +0 -138
  706. package/src/projections/lift_prs.ts +0 -23
  707. package/src/projections/live_hr.ts +0 -21
  708. package/src/projections/live_state.ts +0 -28
  709. package/src/projections/live_stress.ts +0 -13
  710. package/src/projections/performance_assessment.ts +0 -19
  711. package/src/projections/profile.ts +0 -71
  712. package/src/projections/recovery.ts +0 -133
  713. package/src/projections/sleep_need.ts +0 -36
  714. package/src/projections/smart_alarm.ts +0 -70
  715. package/src/projections/strain.ts +0 -131
  716. package/src/projections/stress.ts +0 -95
  717. package/src/projections/today.ts +0 -166
  718. package/src/projections/trend.ts +0 -149
  719. package/src/projections/workouts.ts +0 -36
  720. package/src/schemas/calendar.ts +0 -13
  721. package/src/schemas/communities.ts +0 -56
  722. package/src/schemas/compare.ts +0 -17
  723. package/src/schemas/leaderboard.ts +0 -26
  724. package/src/schemas/live.ts +0 -31
  725. package/src/schemas/performance.ts +0 -13
  726. package/src/schemas/profile.ts +0 -40
  727. package/src/schemas/recovery.ts +0 -28
  728. package/src/schemas/settings.ts +0 -30
  729. package/src/schemas/sleep_need.ts +0 -16
  730. package/src/schemas/smart_alarm.ts +0 -40
  731. package/src/schemas/strain.ts +0 -25
  732. package/src/schemas/stress.ts +0 -17
  733. package/src/schemas/today.ts +0 -39
  734. package/src/schemas/trend.ts +0 -53
  735. package/src/schemas/womens_health.ts +0 -26
  736. package/src/tools/v2/activity_create.ts +0 -74
  737. package/src/tools/v2/behavior_impact.ts +0 -39
  738. package/src/tools/v2/communities.ts +0 -65
  739. package/src/tools/v2/compare.ts +0 -83
  740. package/src/tools/v2/endpoints.ts +0 -32
  741. package/src/tools/v2/hidden_metric.ts +0 -33
  742. package/src/tools/v2/hr_zones.ts +0 -29
  743. package/src/tools/v2/journal_autopop.ts +0 -26
  744. package/src/tools/v2/journal_catalog.ts +0 -48
  745. package/src/tools/v2/leaderboard.ts +0 -92
  746. package/src/tools/v2/lift_catalog.ts +0 -48
  747. package/src/tools/v2/lift_custom_exercise.ts +0 -117
  748. package/src/tools/v2/lift_history.ts +0 -52
  749. package/src/tools/v2/lift_progression.ts +0 -34
  750. package/src/tools/v2/lift_prs.ts +0 -26
  751. package/src/tools/v2/lift_template_save.ts +0 -89
  752. package/src/tools/v2/live_hr.ts +0 -26
  753. package/src/tools/v2/live_state.ts +0 -26
  754. package/src/tools/v2/live_stress.ts +0 -27
  755. package/src/tools/v2/performance_assessment.ts +0 -44
  756. package/src/tools/v2/sleep_need.ts +0 -26
  757. package/src/tools/v2/sports_catalog.ts +0 -32
  758. package/src/tools/v2/symptom_log.ts +0 -78
  759. package/src/tools/v2/today.ts +0 -35
  760. package/src/tools/v2/workout.ts +0 -28
  761. package/src/whoop/build_lift_body.ts +0 -84
  762. package/src/whoop/session_state.ts +0 -41
  763. package/src/whoop/types.ts +0 -89
package/src/cli/update.ts CHANGED
@@ -1,70 +1,72 @@
1
- // `totem update` — the interactive updater.
1
+ // `totem update`: the updater.
2
2
  //
3
- // Three entry points, all dispatched from runUpdate():
4
- // totem update → interactive: pick a version (newest default, older
5
- // warns), apply with an animated build, then offer to
6
- // turn on auto-update.
7
- // totem update --auto on → install a background job that auto-pulls new releases
8
- // totem update --auto off → remove it
9
- // totem update --check → non-interactive: print installed-vs-latest + auto state
10
- // totem update --auto-run → internal: the scheduled job's non-interactive apply
3
+ // totem update pick a version (newest first), install it, redeploy
4
+ // totem update --check installed vs latest, and whether auto-update is on
5
+ // totem update --auto on install new releases automatically (launchd / cron)
6
+ // totem update --auto off stop doing that
7
+ // totem update --auto-run internal: what the scheduled job runs
11
8
  //
12
- // Version index: every release is a git tag (git installs) + an npm version (npm
13
- // installs); GitHub Releases supplies the notes/dates shown in the picker. No
14
- // separate hosting — the tags / registry / releases ARE the index.
15
- import { existsSync, readFileSync, writeFileSync, rmSync, mkdirSync } from "node:fs";
16
- import { resolve } from "node:path";
17
- import {
18
- c, capture, captureAsync, spin, withSpinner, select, promptYesNo, ping, httpGet, commandExists,
19
- } from "./ui.js";
20
-
21
- // What index.ts hands us so this module stays free of the command registry.
9
+ // Version index: every release is a git tag (git installs) and an npm version
10
+ // (npm installs); GitHub Releases supplies the dates and notes in the picker.
11
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
12
+ import { delimiter as pathDelimiter, dirname, resolve } from "node:path";
13
+ import { lastLine, tildify } from "./clients.js";
14
+ import { configFile, dockerBuildArgs } from "./deploy_record.js";
15
+ import { pkgBin } from "./spawn.js";
16
+ import { realIo, type ExecResult, type Io } from "./sys.js";
17
+ import { duration, listOf, shellLines, shellPath } from "./ui.js";
18
+
19
+ // What the dispatcher hands over, so this module doesn't know the commands.
22
20
  export interface UpdateCtx {
23
21
  root: string;
24
- version: string; // current version (PKG.version)
22
+ version: string; // the installed version
25
23
  pkgPath: string; // path to package.json
26
24
  pkgName: string; // @thebriangao/totem
27
- cliEntry: string; // absolute path to the running dist/cli/index.js (for the scheduler)
25
+ cliEntry: string; // the running dist/cli/index.js (for the scheduler)
28
26
  isGit: boolean; // git checkout vs npm-global install
29
27
  detectDeploy: () => DeployInfo | null;
30
- redeploy: () => Promise<number>; // = `totem deploy`
28
+ /** `totem deploy`, captured: each line it prints goes to `onLine`. */
29
+ redeploy: (onLine: (line: string) => void) => Promise<ExecResult>;
31
30
  }
32
- interface DeployInfo { platform: string; app?: string; url?: string; region?: string; project?: string; }
31
+ interface DeployInfo { platform: string; app?: string | undefined; url?: string | undefined; region?: string | undefined; project?: string | undefined }
33
32
 
34
- interface VersionInfo {
33
+ export interface VersionInfo {
35
34
  version: string; // "1.4.2"
36
- tag: string; // "v1.4.2"
37
- date?: string | undefined; // "2026-06-07"
38
- notes?: string | undefined; // release name / first body line
35
+ tag: string; // "v1.4.2"
36
+ date?: string | undefined; // "2026-06-07"
37
+ notes?: string | undefined; // release name / first body line
39
38
  }
40
39
 
41
40
  const AUTO_LABEL = "com.totem.autoupdate";
42
- const AUTO_INTERVAL_SEC = 6 * 60 * 60; // poll every 6h — there's no push channel to a user's machine
41
+ const AUTO_INTERVAL_SEC = 6 * 60 * 60; // there is no push channel to a user's machine: poll
43
42
  const cleanUrl = (u: string): string => u.replace(/\/+$/, "");
44
- const home = (): string => process.env.HOME ?? process.env.USERPROFILE ?? "~";
45
43
  const autoLogPath = (root: string): string => resolve(root, ".totem-autoupdate.log");
44
+ const HOST_NAME: Record<string, string> = { fly: "Fly", railway: "Railway", cloudflare: "Cloudflare", cloudrun: "Cloud Run" };
46
45
 
47
46
  // ── semver ────────────────────────────────────────────────────────────────
48
- // Compare two x.y.z strings (leading "v" ignored). -1 / 0 / 1.
47
+ // Compare two x.y.z[-pre] strings (leading "v" ignored). -1 / 0 / 1. A
48
+ // prerelease sorts below its release (1.6.0-rc.1 < 1.6.0).
49
49
  export function compareSemver(a: string, b: string): number {
50
- const pa = a.replace(/^v/, "").split(".").map((n) => parseInt(n, 10) || 0);
51
- const pb = b.replace(/^v/, "").split(".").map((n) => parseInt(n, 10) || 0);
50
+ const [coreA = "", preA = ""] = a.replace(/^v/, "").split(/-(.*)/s);
51
+ const [coreB = "", preB = ""] = b.replace(/^v/, "").split(/-(.*)/s);
52
+ const pa = coreA.split(".").map((n) => parseInt(n, 10) || 0);
53
+ const pb = coreB.split(".").map((n) => parseInt(n, 10) || 0);
52
54
  for (let i = 0; i < 3; i++) {
53
55
  const d = (pa[i] ?? 0) - (pb[i] ?? 0);
54
56
  if (d !== 0) return d < 0 ? -1 : 1;
55
57
  }
56
- return 0;
58
+ if (preA === preB) return 0;
59
+ if (!preA) return 1;
60
+ if (!preB) return -1;
61
+ return Math.sign(preA.localeCompare(preB, "en", { numeric: true }));
57
62
  }
63
+
64
+ // Only plain x.y.z releases are installable — never prereleases.
65
+ export const isRelease = (v: string): boolean => /^\d+\.\d+\.\d+$/.test(v);
58
66
  export function isNewer(candidate: string, current: string): boolean {
59
67
  return compareSemver(candidate, current) > 0;
60
68
  }
61
69
 
62
- // The last meaningful line of captured output, for surfacing a failure reason.
63
- function lastLine(r: { stdout: string; stderr: string }): string {
64
- const lines = (r.stderr + "\n" + r.stdout).split("\n").map((l) => l.trim()).filter(Boolean);
65
- return lines.length ? lines[lines.length - 1]! : "";
66
- }
67
-
68
70
  // owner/repo for the GitHub Releases API, parsed from package.json repository.url.
69
71
  function repoSlug(pkgPath: string): string | null {
70
72
  try {
@@ -77,8 +79,8 @@ function repoSlug(pkgPath: string): string | null {
77
79
  }
78
80
  }
79
81
 
80
- // Best-effort notes/date index from the GitHub Releases API (works for both
81
- // install types; failure just means the picker shows versions without notes).
82
+ // Notes and dates from the GitHub Releases API. Best-effort: without them the
83
+ // picker shows bare versions.
82
84
  export function parseReleases(json: string): Map<string, { date?: string | undefined; notes?: string | undefined }> {
83
85
  const out = new Map<string, { date?: string | undefined; notes?: string | undefined }>();
84
86
  try {
@@ -94,171 +96,229 @@ export function parseReleases(json: string): Map<string, { date?: string | undef
94
96
  return out;
95
97
  }
96
98
 
97
- async function fetchReleaseNotes(ctx: UpdateCtx): Promise<Map<string, { date?: string | undefined; notes?: string | undefined }>> {
99
+ // The installable versions for THIS install type, newest first, with notes.
100
+ async function fetchVersions(ctx: UpdateCtx, io: Io): Promise<VersionInfo[]> {
101
+ const { sys } = io;
98
102
  const slug = repoSlug(ctx.pkgPath);
99
- if (!slug) return new Map();
100
- // GitHub's API requires a User-Agent — httpGet sends one ("totem-setup").
101
- const r = await httpGet(`https://api.github.com/repos/${slug}/releases?per_page=100`, 8000);
102
- return r.status === 200 ? parseReleases(r.body) : new Map();
103
- }
104
-
105
- // The installable versions for THIS install type, newest first, enriched with notes.
106
- async function fetchVersions(ctx: UpdateCtx): Promise<VersionInfo[]> {
107
- const notes = await fetchReleaseNotes(ctx);
103
+ const releases = slug ? await sys.httpGet(`https://api.github.com/repos/${slug}/releases?per_page=100`, 8000) : null;
104
+ const notes = releases?.status === 200 ? parseReleases(releases.body) : new Map<string, { date?: string | undefined; notes?: string | undefined }>();
108
105
  let versions: string[] = [];
109
106
  const commitDates = new Map<string, string>();
110
107
  if (ctx.isGit) {
111
- await captureAsync("git", ["fetch", "--tags", "--quiet", "origin"], { cwd: ctx.root });
112
- const out = capture("git", ["tag", "--sort=-v:refname"], { cwd: ctx.root }).stdout;
108
+ await sys.exec("git", ["fetch", "--tags", "--quiet", "origin"], { cwd: ctx.root });
109
+ const out = (await sys.exec("git", ["tag", "--sort=-v:refname"], { cwd: ctx.root })).stdout;
113
110
  versions = out.split("\n").map((s) => s.trim()).filter((t) => /^v\d+\.\d+\.\d+$/.test(t)).map((t) => t.replace(/^v/, ""));
114
- // Date a version by when its CODE was committed, not the GitHub release's
115
- // published_at — backfilled tags (e.g. v1.1.0, tagged days after v1.2.0) would
116
- // otherwise show the wrong, out-of-order date. `*committerdate` dereferences an
117
- // annotated tag to its commit; the trailing `committerdate` covers a lightweight
118
- // tag. The regex just grabs the first YYYY-MM-DD after the ref, which is the
119
- // commit date in both shapes.
120
- const dates = capture("git", ["for-each-ref", "--format=%(refname:short) %(*committerdate:short) %(committerdate:short)", "refs/tags"], { cwd: ctx.root }).stdout;
111
+ // Date a version by when its code was committed, not when the GitHub
112
+ // release was published: a tag added later would show out of order.
113
+ // `*committerdate` dereferences an annotated tag; the plain one covers a
114
+ // lightweight tag. The first date after the ref is the commit's either way.
115
+ const dates = (await sys.exec("git", ["for-each-ref", "--format=%(refname:short) %(*committerdate:short) %(committerdate:short)", "refs/tags"], { cwd: ctx.root })).stdout;
121
116
  for (const line of dates.split("\n")) {
122
117
  const m = line.trim().match(/^v(\d+\.\d+\.\d+)\s+(\d{4}-\d{2}-\d{2})/);
123
118
  if (m) commitDates.set(m[1]!, m[2]!);
124
119
  }
125
120
  } else {
126
- const out = capture("npm", ["view", ctx.pkgName, "versions", "--json"]).stdout.trim();
121
+ const out = (await sys.exec("npm", ["view", ctx.pkgName, "versions", "--json"])).stdout.trim();
127
122
  try {
128
123
  const parsed = JSON.parse(out) as string[] | string;
129
- versions = Array.isArray(parsed) ? parsed : [parsed];
124
+ versions = (Array.isArray(parsed) ? parsed : [parsed]).filter(isRelease);
130
125
  } catch { versions = []; }
131
126
  }
132
127
  versions = [...new Set(versions)].sort((a, b) => compareSemver(b, a));
133
128
  return versions.map((v) => ({ version: v, tag: `v${v}`, date: commitDates.get(v) ?? notes.get(v)?.date, notes: notes.get(v)?.notes }));
134
129
  }
135
130
 
136
- // ── animated apply ──────────────────────────────────────────────────────────
137
- // Run one captured step under a spinner; ✓ on success, ✗ + reason on failure.
138
- async function staged(label: string, fn: () => Promise<{ code: number; stdout: string; stderr: string }>): Promise<boolean> {
139
- const s = spin(label);
140
- const r = await fn();
141
- if (r.code === 0) { s.stop(` ${c.green("✓")} ${label}`); return true; }
142
- s.stop(` ${c.red("✗")} ${label}`);
143
- const why = lastLine(r);
144
- if (why) console.log(c.gray(` ${why}`));
131
+ // ── applying a version ───────────────────────────────────────────────────────
132
+
133
+ const tail = (r: ExecResult, lines = 6): string[] =>
134
+ `${r.stdout}\n${r.stderr}`.split("\n").map((l) => l.trimEnd()).filter((l) => l.trim() !== "").slice(-lines);
135
+
136
+ const RETRY: [string, string] = ["Try again", "totem update"];
137
+
138
+ /**
139
+ * One captured step: spinner while it runs, then ✓ with how long it took, or
140
+ * why it failed. `retry` adds the command to run again (left off when a
141
+ * rollback follows and says it after).
142
+ */
143
+ async function staged(io: Io, label: string, done: string, run: (onLine: (l: string) => void) => Promise<ExecResult>, opts: { slow?: boolean; retry?: boolean } = {}): Promise<boolean> {
144
+ const { ui, sys } = io;
145
+ const started = sys.now();
146
+ const r = await ui.task(label, run, { slow: Boolean(opts.slow) });
147
+ if (r.code === 0) {
148
+ ui.ok(done, duration(sys.now() - started));
149
+ return true;
150
+ }
151
+ ui.problem(`${label} failed.`, { detail: tail(r), fix: opts.retry ? [RETRY] : undefined });
145
152
  return false;
146
153
  }
147
154
 
148
- // Pull/install `target`, rebuild, and (if deployed) redeploy + health-check.
149
- // Returns 0 on success. `latest` is used only to decide latest-vs-pinned git path.
150
- async function applyVersion(ctx: UpdateCtx, target: VersionInfo, latest: VersionInfo): Promise<number> {
151
- console.log(c.bold(`\n Updating to v${target.version}`) + c.gray(" ────────────────────────────"));
155
+ /** What the update left this install and its server on. */
156
+ export type Applied =
157
+ /** Everything is on the new version. */
158
+ | "done"
159
+ /** This install is updated; a server exists that totem couldn't update from here. */
160
+ | "local-only"
161
+ /** Nothing changed (or it was put back). */
162
+ | "failed";
152
163
 
164
+ /**
165
+ * Install `target`, rebuild, and bring the server along. A git install checks
166
+ * out the release tag (never `main`); an npm install reinstalls that version.
167
+ */
168
+ export async function applyVersion(ctx: UpdateCtx, target: VersionInfo, io: Io = realIo()): Promise<Applied> {
169
+ const { ui, sys } = io;
170
+ const d = ctx.detectDeploy();
171
+ const remote = d && d.platform !== "local" ? d : null;
172
+ const total = remote ? 2 : 1;
173
+ const heading = (n: number, title: string): void => (total > 1 ? ui.step(n, total, title) : ui.section(title));
174
+
175
+ // Undo for a git install (set once the checkout is about to move). An npm
176
+ // install has nothing to undo: a failed `npm install -g` leaves the old one.
177
+ let rollback: () => Promise<void> = async () => {};
178
+
179
+ heading(1, `Install ${target.version}`);
153
180
  if (ctx.isGit) {
154
- // Never clobber tracked local edits (a dev checkout). Untracked files (.env,
155
- // dist/, fly.toml) don't block a checkout, so we ignore them.
156
- const dirty = capture("git", ["status", "--porcelain", "--untracked-files=no"], { cwd: ctx.root }).stdout.trim();
181
+ // Never clobber local edits to tracked files (a dev checkout). Untracked
182
+ // files (.env, dist/, fly.toml) don't block a checkout.
183
+ const dirty = (await sys.exec("git", ["status", "--porcelain", "--untracked-files=no"], { cwd: ctx.root })).stdout.trim();
157
184
  if (dirty) {
158
- console.log(c.red("\n Local changes to tracked files present — commit or stash them first:"));
159
- console.log(c.gray(" " + dirty.split("\n").slice(0, 5).join("\n ")));
160
- return 1;
161
- }
162
- if (!(await staged("fetching releases from GitHub", () => captureAsync("git", ["fetch", "--tags", "--quiet", "origin"], { cwd: ctx.root })))) return 1;
163
- if (target.version === latest.version) {
164
- // Latest lives on main; make sure we're on the branch, then fast-forward.
165
- const branch = capture("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd: ctx.root }).stdout.trim();
166
- if (branch !== "main" && !(await staged("switching to main", () => captureAsync("git", ["checkout", "main"], { cwd: ctx.root })))) return 1;
167
- if (!(await staged("pulling latest code", () => captureAsync("git", ["pull", "--ff-only", "origin", "main"], { cwd: ctx.root })))) return 1;
168
- } else {
169
- // A pinned older/newer version is a tag → detached checkout.
170
- if (!(await staged(`checking out ${target.tag}`, () => captureAsync("git", ["checkout", "--quiet", target.tag], { cwd: ctx.root })))) return 1;
185
+ ui.problem("This checkout has uncommitted changes to tracked files.", {
186
+ detail: dirty.split("\n").slice(0, 5),
187
+ fix: [["Commit or stash them, then", "totem update"]],
188
+ });
189
+ return "failed";
171
190
  }
172
- if (!(await staged("installing dependencies", () => captureAsync("npm", ["install"], { cwd: ctx.root })))) return 1;
173
- const tsc = resolve(ctx.root, "node_modules", ".bin", "tsc");
174
- if (!(await staged("building", () => captureAsync(process.execPath, [tsc], { cwd: ctx.root })))) return 1;
191
+ if (!(await staged(io, "Fetching releases", "Releases fetched", () => sys.exec("git", ["fetch", "--tags", "--quiet", "origin"], { cwd: ctx.root }), { retry: true }))) return "failed";
192
+ // Where to go back to if the update doesn't finish: the branch when on one,
193
+ // else the commit (a release tag is a detached checkout).
194
+ const previous = (await sys.exec("git", ["symbolic-ref", "--short", "-q", "HEAD"], { cwd: ctx.root })).stdout.trim()
195
+ || (await sys.exec("git", ["rev-parse", "HEAD"], { cwd: ctx.root })).stdout.trim();
196
+ // `npm install` may rewrite package-lock.json (another npm version writes it
197
+ // its own way). The tracked tree was clean when this began, so that change
198
+ // is npm's, not the person's. Left there, git refuses the checkout that
199
+ // goes back to the old version ("local changes would be overwritten": the
200
+ // lock differs between any two releases), and after a good update the next
201
+ // one stops at "uncommitted changes". Put the committed file back.
202
+ const install = async (onLine?: (l: string) => void): Promise<ExecResult> => {
203
+ const r = await sys.exec("npm", ["install"], { cwd: ctx.root, onLine });
204
+ await sys.exec("git", ["checkout", "--quiet", "--", "package-lock.json"], { cwd: ctx.root });
205
+ return r;
206
+ };
207
+ const build = async (onLine?: (l: string) => void): Promise<ExecResult> => {
208
+ const tsc = pkgBin(ctx.root, "typescript", "tsc");
209
+ return tsc ? sys.exec(sys.node, [tsc], { cwd: ctx.root, onLine }) : { code: 1, stdout: "", stderr: "typescript isn't installed in node_modules" };
210
+ };
211
+ // A half-applied update must not stay: the checkout has already moved
212
+ // package.json to the new version, so the next check would read that, find
213
+ // nothing newer and report "up to date" on top of the old build. Going back
214
+ // (the tracked tree was clean, so this only moves HEAD) means the next run
215
+ // tries again.
216
+ rollback = async (): Promise<void> => {
217
+ if (!previous) return;
218
+ const back = await ui.task(`Going back to ${ctx.version}`, () => sys.exec("git", ["checkout", "--quiet", previous], { cwd: ctx.root }));
219
+ if (back.code !== 0) {
220
+ ui.problem(`Couldn't go back to ${ctx.version}.`, { detail: lastLine(back), fix: [["Do it by hand", `git checkout ${previous} && npm install && totem build`]] });
221
+ return;
222
+ }
223
+ // Put the old build back too. Whatever broke the update may break this.
224
+ const rebuilt = await ui.task(`Rebuilding ${ctx.version}`, async () => (await install()).code === 0 && (await build()).code === 0);
225
+ if (rebuilt) ui.ok(`Back on ${ctx.version}; nothing changed`);
226
+ else ui.warn(`Back on ${ctx.version}'s source, but it didn't rebuild.`, "run: npm install && totem build");
227
+ ui.rows([[RETRY[0], ui.kit.c.accent(RETRY[1])]], 2);
228
+ };
229
+ // Every version, the latest included, is its release tag: a detached
230
+ // checkout. Never `main`: that is unreleased code, and on a fork's clone
231
+ // origin/main can be older than the release being installed.
232
+ if (!(await staged(io, `Checking out ${target.tag}`, `Checked out ${target.tag}`, () => sys.exec("git", ["checkout", "--quiet", target.tag], { cwd: ctx.root }), { retry: true }))) return "failed";
233
+ if (!(await staged(io, "Installing dependencies", "Dependencies installed", install, { slow: true }))) { await rollback(); return "failed"; }
234
+ if (!(await staged(io, "Building", "Built", build, { slow: true }))) { await rollback(); return "failed"; }
175
235
  } else {
176
- if (!(await staged(`installing ${ctx.pkgName}@${target.version}`, () => captureAsync("npm", ["install", "-g", `${ctx.pkgName}@${target.version}`])))) return 1;
236
+ const spec = `${ctx.pkgName}@${target.version}`;
237
+ if (!(await staged(io, `Installing ${spec}`, `Installed ${spec}`, (onLine) => sys.exec("npm", ["install", "-g", spec], { onLine }), { slow: true, retry: true }))) return "failed";
177
238
  }
178
239
 
179
- // Propagate the new code to wherever the server actually runs. What that takes
180
- // depends entirely on the user's RECORDED deploy state — branch on it, never
181
- // assume:
182
- // • no record → nothing remote exists; local code is already updated.
183
- // • local (stdio) → just restart the MCP client to pick up the new build.
184
- // • fly/railway/cloudrun → rebuild-from-source on deploy; fully automatic.
185
- // • custom / self-host → a container on a box we can't reach; we must NOT fake
186
- // a deploy or health-check (it'd pass against the OLD container) — print the
187
- // exact rebuild/restart steps instead.
188
- const d = ctx.detectDeploy();
189
- const AUTO_DEPLOY = new Set(["fly", "railway", "cloudrun"]);
190
- if (!d || d.platform === "local") {
191
- console.log(c.gray(d?.platform === "local"
192
- ? "\n Local install — restart your MCP client to load the new build."
193
- : "\n No deployment recorded — local code is updated (run `totem cloud` to deploy a server)."));
194
- } else if (AUTO_DEPLOY.has(d.platform)) {
195
- // The platform CLI must be present to push from here. If it's gone (a fresh
196
- // machine, or you ran update from a different box than you deployed from),
197
- // don't surface a cryptic `spawn fly ENOENT` + "server unchanged" — the local
198
- // code IS updated; say plainly the redeploy needs the CLI.
199
- const cliMissing = d.platform === "fly" ? !(commandExists("fly") || commandExists("flyctl"))
200
- : d.platform === "railway" ? !commandExists("railway")
201
- : !commandExists("gcloud");
202
- if (cliMissing) {
203
- const cli = d.platform === "fly" ? "flyctl" : d.platform === "railway" ? "railway" : "gcloud";
204
- console.log(c.yellow(`\n Local code updated — but the ${d.platform} CLI (${cli}) isn't installed here, so the deployment wasn't pushed.`));
205
- console.log(c.gray(` Install ${cli} and run \`totem deploy\`, or re-run \`totem cloud\`.`));
206
- return 0;
207
- }
208
- console.log(c.bold(`\n Redeploying to ${d.platform}${d.app ? ` (${d.app})` : ""}…`));
209
- if ((await ctx.redeploy()) !== 0) { console.log(c.red(" ✗ deploy failed — your live server is unchanged.")); return 1; }
210
- if (d.url) {
211
- const url = `${cleanUrl(d.url)}/health`;
212
- console.log(c.gray(` health check → ${url}`));
213
- if ((await ping(url)) !== 0) {
214
- console.log(c.red(" ⚠ /health didn't return 200 — the server may be unhealthy."));
215
- console.log(c.gray(d.platform === "fly" ? ` Roll back: fly releases -a ${d.app} → redeploy the prior release.` : " Roll back to the previous version on your host."));
216
- return 1;
217
- }
240
+ // Bring the server along. What that takes depends on where it runs:
241
+ // - nowhere / this computer: the client loads the new build when it restarts;
242
+ // - Fly, Railway, Cloud Run: redeploy from here and check /health;
243
+ // - a self-hosted container: totem can't reach it, so it must not pretend
244
+ // to (a health check would pass against the OLD container). Print the steps.
245
+ if (!remote) return "done";
246
+ const host = HOST_NAME[remote.platform];
247
+ if (!host) {
248
+ heading(2, "Your server");
249
+ selfHostSteps(io, ctx, remote);
250
+ return "local-only";
251
+ }
252
+ heading(2, `Deploy to ${host}`);
253
+ // The host's CLI has to be on this machine to deploy from it.
254
+ const cli = remote.platform === "fly" ? ["fly", "flyctl"] : remote.platform === "railway" ? ["railway"] : remote.platform === "cloudflare" ? ["npx"] : ["gcloud"];
255
+ if (!cli.some((c) => sys.has(c))) {
256
+ ui.warn(`The ${host} CLI (${cli[cli.length - 1]}) isn't installed on this machine, so the server still runs ${ctx.version}.`);
257
+ ui.hint(`Install it, then: totem deploy`);
258
+ return "local-only";
259
+ }
260
+ const started = sys.now();
261
+ const deploy = await ui.task(`Deploying${remote.app ? ` ${remote.app}` : ""}`, (set) => ctx.redeploy(set), { slow: true });
262
+ if (deploy.code !== 0) {
263
+ ui.problem("The deploy failed. The server is unchanged.", { detail: tail(deploy) });
264
+ // Keep this install on the version the server runs, so the next check sees
265
+ // the release as still to do instead of "up to date".
266
+ await rollback();
267
+ return "failed";
268
+ }
269
+ ui.ok(`Deployed${remote.app ? ` ${remote.app}` : ""}`, duration(sys.now() - started));
270
+ if (remote.url) {
271
+ const health = await ui.task("Checking the server", () => sys.httpGet(`${cleanUrl(remote.url!)}/health`, 10_000));
272
+ if (health.status < 200 || health.status >= 300) {
273
+ ui.problem("The new version is deployed, but the server isn't answering /health.", {
274
+ detail: health.status ? `HTTP ${health.status}` : health.error ?? "no answer",
275
+ fix: [["Read its logs", "totem logs"], ...(remote.platform === "fly" && remote.app ? [["See earlier releases", `fly releases -a ${remote.app}`] as [string, string]] : [])],
276
+ });
277
+ return "failed";
218
278
  }
219
- // A redeploy restarts the server. This is a code-only update — secrets persist
220
- // on the host, so tokens carry over. But /health passing doesn't prove Whoop
221
- // auth survived the restart (cloud uses the in-memory token store, which can
222
- // strand a rotated refresh token), so point at the fix if calls start failing.
223
- console.log(c.gray(" Tokens persist across the redeploy. If Whoop calls start failing afterward, run `totem auth` to refresh + re-push them."));
224
- } else {
225
- printSelfHostUpdate(ctx, d);
279
+ ui.ok("The server is up", "/health answered");
226
280
  }
227
- return 0;
228
- }
229
-
230
- // Self-hosted (Docker on a VPS / Render / a home box / …) — totem can't reach the
231
- // container, and the run command varies per user (compose, ports, restart policy,
232
- // remote host), so we never hardcode it: print the canonical rebuild/restart recipe
233
- // + the env file we wrote at deploy time, and let the user adapt it to their host.
234
- function printSelfHostUpdate(ctx: UpdateCtx, d: DeployInfo): void {
235
- const hasEnv = existsSync(resolve(ctx.root, ".env.deploy"));
236
- console.log(c.yellow(`\n Self-hosted (${d.platform}) — finish the update where your container runs (totem can't reach it):`));
237
- console.log(` ${c.violet("1")} Get this updated code onto that host ${c.gray("(git pull your checkout there, or copy the build over)")}`);
238
- console.log(` ${c.violet("2")} Rebuild: ${c.cyan("docker build -t totem .")}`);
239
- console.log(` ${c.violet("3")} Restart: ${c.cyan(`docker run -d --restart unless-stopped -p 3000:3000 --env-file ${hasEnv ? ".env.deploy" : "<your-env-file>"} totem`)}`);
240
- console.log(` ${c.gray("or: docker compose up -d --build · or your host's redeploy (Render/Coolify/etc.)")}`);
241
- if (d.url) console.log(` ${c.violet("4")} Verify: ${c.gray(`curl ${cleanUrl(d.url)}/health`)}`);
242
- console.log(c.gray("\n Your local code + build are already on the new version — only the remote container is left."));
281
+ if (remote.platform === "cloudrun") ui.warn("A new Cloud Run revision starts without a WHOOP login.", "log in again: totem auth");
282
+ else if (remote.platform === "cloudflare") ui.hint("The WHOOP login lives in the Worker's Durable Object and carries over. If tools start failing: totem auth");
283
+ else ui.hint("The WHOOP login lives on the server's volume and carries over. If tools start failing: totem auth");
284
+ return "done";
243
285
  }
244
286
 
245
- function printDone(version: string): void {
246
- console.log("");
247
- console.log(` ${c.green("✓")} ${c.bold(`Now on v${version}`)}`);
248
- console.log(c.brandDim(" ▁▁▂▂▆▂▁▁▁▁▂▂▆▂▁▁▁▁▂▂▆▂▁▁▁▁▂▂▆▂▁▁"));
249
- console.log("");
287
+ // Self-hosted (Docker on a VPS, a home server, …): totem can't reach the
288
+ // container, and how it is run varies, so print the recipe to adapt.
289
+ function selfHostSteps(io: Io, ctx: UpdateCtx, d: DeployInfo): void {
290
+ const { ui, sys } = io;
291
+ // The env file `totem cloud` wrote: in totem's config folder (installs before 2.0: .env.deploy in the install).
292
+ const envFile = [configFile(sys, "deploy.env"), resolve(ctx.root, ".env.deploy")].find((f) => existsSync(f));
293
+ const envArg = envFile ? shellPath(envFile) : "<your env file>";
294
+ ui.para("totem can't reach a self-hosted container. This install is updated; on the host that runs the server:");
295
+ ui.line();
296
+ ui.para("1. Get this version there (git pull the checkout, or copy it over).");
297
+ ui.para("2. Rebuild the image:");
298
+ ui.code(shellLines([...dockerBuildArgs(ctx.root), shellPath(ctx.root)], ui.style.width - 7, sys.platform), 5);
299
+ ui.para("3. Stop the old container, then start the new image the way you did before:");
300
+ ui.code(shellLines(["docker", "run", "-d", "--restart", "unless-stopped", "-p", "3000:3000", "-v", "totem-data:/data", "--env-file", envArg, "totem"], ui.style.width - 7, sys.platform), 5);
301
+ if (d.url) {
302
+ ui.para("4. Check it:");
303
+ ui.code([`curl ${cleanUrl(d.url)}/health`], 5);
304
+ }
250
305
  }
251
306
 
252
307
  // ── auto-update scheduler (launchd on macOS, cron on Linux) ──────────────────
253
- function plistPath(): string { return resolve(home(), "Library", "LaunchAgents", `${AUTO_LABEL}.plist`); }
308
+ const plistPath = (home: string): string => resolve(home, "Library", "LaunchAgents", `${AUTO_LABEL}.plist`);
254
309
 
255
310
  function xmlEscape(s: string): string {
256
311
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
257
312
  }
258
313
 
259
314
  // A launchd LaunchAgent that runs `totem update --auto-run` every intervalSec.
260
- export function launchdPlist(programArgs: string[], intervalSec: number, workingDir: string, logPath: string): string {
315
+ // `path` becomes the job's PATH: launchd starts jobs with /usr/bin:/bin:/usr/sbin:/sbin,
316
+ // where npm and the deploy CLIs usually aren't.
317
+ export function launchdPlist(programArgs: string[], intervalSec: number, workingDir: string, logPath: string, path?: string): string {
261
318
  const args = programArgs.map((a) => ` <string>${xmlEscape(a)}</string>`).join("\n");
319
+ const env = path
320
+ ? ` <key>EnvironmentVariables</key>\n <dict>\n <key>PATH</key>\n <string>${xmlEscape(path)}</string>\n </dict>\n`
321
+ : "";
262
322
  return `<?xml version="1.0" encoding="UTF-8"?>
263
323
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
264
324
  <plist version="1.0">
@@ -275,7 +335,7 @@ ${args}
275
335
  <false/>
276
336
  <key>WorkingDirectory</key>
277
337
  <string>${xmlEscape(workingDir)}</string>
278
- <key>StandardOutPath</key>
338
+ ${env} <key>StandardOutPath</key>
279
339
  <string>${xmlEscape(logPath)}</string>
280
340
  <key>StandardErrorPath</key>
281
341
  <string>${xmlEscape(logPath)}</string>
@@ -284,159 +344,261 @@ ${args}
284
344
  `;
285
345
  }
286
346
 
287
- // One cron line, tagged so we can find + remove exactly ours.
288
- export function cronLine(programArgs: string[], root: string, logPath: string): string {
289
- const cmd = programArgs.map((a) => (/\s/.test(a) ? `"${a}"` : a)).join(" ");
290
- return `0 */6 * * * cd ${root} && ${cmd} >> ${logPath} 2>&1 # ${AUTO_LABEL}`;
347
+ // One cron line, tagged so we can find + remove exactly ours. Every word is
348
+ // quoted for sh (cron hands the line to `sh -c`), and `%` is escaped: cron ends
349
+ // the command at a bare `%` and feeds the rest to it as stdin.
350
+ // `path`, when given, is exported first: cron's own PATH is /usr/bin:/bin.
351
+ export function cronLine(programArgs: string[], root: string, logPath: string, path?: string): string {
352
+ const shq = (s: string): string => `'${s.replace(/'/g, `'\\''`)}'`.replace(/%/g, "\\%");
353
+ const word = (s: string): string => (/^[A-Za-z0-9_/.:=@+-]+$/.test(s) ? s : shq(s));
354
+ const setPath = path ? `export PATH=${shq(path)}; ` : "";
355
+ return `0 */6 * * * ${setPath}cd ${shq(root)} && ${programArgs.map(word).join(" ")} >> ${shq(logPath)} 2>&1 # ${AUTO_LABEL}`;
356
+ }
357
+
358
+ /**
359
+ * The PATH a scheduled run gets: this node's directory (where npm lives) ahead
360
+ * of the PATH `totem update --auto on` was run with, which can see git and the
361
+ * deploy CLI. launchd and cron would otherwise start the job with a bare system
362
+ * PATH, where `npm install` and `fly deploy` fail with ENOENT.
363
+ */
364
+ export function schedulerPath(
365
+ execPath: string = process.execPath,
366
+ envPath: string = process.env.PATH ?? "",
367
+ delimiter: string = pathDelimiter,
368
+ ): string {
369
+ const dirs = [dirname(execPath), ...envPath.split(delimiter)].map((d) => d.trim()).filter(Boolean);
370
+ return [...new Set(dirs)].join(delimiter);
291
371
  }
292
372
 
293
- export function isAutoOn(): boolean {
294
- if (process.platform === "darwin") return existsSync(plistPath());
295
- if (process.platform === "linux") {
296
- const r = capture("crontab", ["-l"]);
373
+ /**
374
+ * The person's crontab without totem's line, or why it couldn't be read.
375
+ *
376
+ * `crontab -l` exits non-zero both when there is no crontab yet (start from an
377
+ * empty one) and when the crontab couldn't be read. Its output is empty either
378
+ * way, and writing back "everything but totem's line" after the second erased
379
+ * every job the person had.
380
+ */
381
+ async function otherCronJobs(io: Io): Promise<{ ok: true; lines: string[]; hadTotem: boolean } | { ok: false; why: string }> {
382
+ const r = await io.sys.exec("crontab", ["-l"]);
383
+ // "no crontab for <user>" (cron, cronie); "can't open '<user>': No such file or directory" (BusyBox).
384
+ if (r.code !== 0 && !/no crontab|no such file/i.test(`${r.stderr}\n${r.stdout}`)) return { ok: false, why: lastLine(r) };
385
+ const all = r.code === 0 ? r.stdout.split("\n") : [];
386
+ return { ok: true, lines: all.filter((l) => l && !l.includes(AUTO_LABEL)), hadTotem: all.some((l) => l.includes(AUTO_LABEL)) };
387
+ }
388
+
389
+ export async function isAutoOn(io: Io): Promise<boolean> {
390
+ const { sys } = io;
391
+ if (sys.platform === "darwin") return existsSync(plistPath(sys.home));
392
+ if (sys.platform === "linux") {
393
+ const r = await sys.exec("crontab", ["-l"]);
297
394
  return r.code === 0 && r.stdout.includes(AUTO_LABEL);
298
395
  }
299
396
  return false;
300
397
  }
301
398
 
302
- function autoRunArgs(ctx: UpdateCtx): string[] {
303
- return [process.execPath, ctx.cliEntry, "update", "--auto-run"];
304
- }
305
-
306
- async function enableAuto(ctx: UpdateCtx): Promise<boolean> {
307
- const args = autoRunArgs(ctx);
399
+ async function enableAuto(ctx: UpdateCtx, io: Io): Promise<boolean> {
400
+ const { ui, sys } = io;
401
+ const args = [sys.node, ctx.cliEntry, "update", "--auto-run"];
308
402
  const log = autoLogPath(ctx.root);
309
- if (process.platform === "darwin") {
310
- const p = plistPath();
311
- mkdirSync(resolve(home(), "Library", "LaunchAgents"), { recursive: true });
312
- writeFileSync(p, launchdPlist(args, AUTO_INTERVAL_SEC, ctx.root, log));
313
- await captureAsync("launchctl", ["unload", p]); // ignore if not loaded
314
- const load = await captureAsync("launchctl", ["load", p]);
315
- if (load.code !== 0) { console.log(c.red(` ✗ couldn't load the launchd agent: ${lastLine(load)}`)); return false; }
316
- console.log(c.green(" ✓ auto-update on") + c.gray(` — checks every 6h via launchd (${p})`));
317
- } else if (process.platform === "linux") {
318
- const existing = capture("crontab", ["-l"]).stdout.split("\n").filter((l) => l && !l.includes(AUTO_LABEL));
319
- existing.push(cronLine(args, ctx.root, log));
320
- const set = await captureAsync("crontab", ["-"], { input: existing.join("\n") + "\n" });
321
- if (set.code !== 0) { console.log(c.red(` ✗ couldn't write crontab: ${lastLine(set)}`)); return false; }
322
- console.log(c.green(" ✓ auto-update on") + c.gray(" — checks every 6h via cron"));
403
+ const path = schedulerPath(sys.node, sys.env.PATH ?? "");
404
+ let via: string;
405
+ if (sys.platform === "darwin") {
406
+ const p = plistPath(sys.home);
407
+ mkdirSync(dirname(p), { recursive: true });
408
+ writeFileSync(p, launchdPlist(args, AUTO_INTERVAL_SEC, ctx.root, log, path));
409
+ await sys.exec("launchctl", ["unload", p]); // fine if it wasn't loaded
410
+ const load = await sys.exec("launchctl", ["load", p]);
411
+ if (load.code !== 0) {
412
+ ui.problem("launchd wouldn't load the auto-update job.", { detail: lastLine(load), fix: [["Try again", "totem update --auto on"]] });
413
+ return false;
414
+ }
415
+ via = "launchd";
416
+ } else if (sys.platform === "linux") {
417
+ const others = await otherCronJobs(io);
418
+ if (!others.ok) {
419
+ ui.problem("Couldn't read your crontab, so totem left it as it is.", { detail: others.why, fix: [["Try again", "totem update --auto on"]] });
420
+ return false;
421
+ }
422
+ const existing = [...others.lines, cronLine(args, ctx.root, log, path)];
423
+ const set = await sys.exec("crontab", ["-"], { input: existing.join("\n") + "\n" });
424
+ if (set.code !== 0) {
425
+ ui.problem("cron wouldn't take the auto-update job.", { detail: lastLine(set), fix: [["Try again", "totem update --auto on"]] });
426
+ return false;
427
+ }
428
+ via = "cron";
323
429
  } else {
324
- console.log(c.yellow(" Auto-update isn't wired for this OS. Schedule this command every 6h yourself:"));
325
- console.log(c.gray(` ${args.join(" ")}`));
430
+ ui.warn("Auto-update isn't available on this system.");
431
+ ui.para("To get the same, schedule this command every 6 hours:", 2);
432
+ ui.code([args.join(" ")]);
326
433
  return false;
327
434
  }
328
- console.log(c.gray(` Log: ${log} · turn off: totem update --auto off`));
435
+ ui.ok("Auto-update is on", `checks every 6 hours, through ${via}`);
436
+ ui.rows([["Log", tildify(log, sys.home)], ["Turn it off", "totem update --auto off"]], 2);
329
437
  return true;
330
438
  }
331
439
 
332
- async function disableAuto(ctx: UpdateCtx): Promise<boolean> {
333
- if (process.platform === "darwin") {
334
- const p = plistPath();
335
- if (existsSync(p)) { await captureAsync("launchctl", ["unload", p]); rmSync(p, { force: true }); }
336
- console.log(c.green(" ✓ auto-update off"));
337
- } else if (process.platform === "linux") {
338
- const kept = capture("crontab", ["-l"]).stdout.split("\n").filter((l) => l && !l.includes(AUTO_LABEL));
339
- await captureAsync("crontab", ["-"], { input: kept.length ? kept.join("\n") + "\n" : "\n" });
340
- console.log(c.green(" ✓ auto-update off"));
440
+ async function disableAuto(io: Io): Promise<boolean> {
441
+ const { ui, sys } = io;
442
+ if (sys.platform === "darwin") {
443
+ const p = plistPath(sys.home);
444
+ if (existsSync(p)) { await sys.exec("launchctl", ["unload", p]); rmSync(p, { force: true }); }
445
+ } else if (sys.platform === "linux") {
446
+ const others = await otherCronJobs(io);
447
+ if (!others.ok) {
448
+ ui.problem("Couldn't read your crontab, so totem left it as it is.", { detail: others.why, fix: [["Try again", "totem update --auto off"]] });
449
+ return false;
450
+ }
451
+ // Only a crontab with totem's line in it needs rewriting.
452
+ if (others.hadTotem) await sys.exec("crontab", ["-"], { input: others.lines.length ? others.lines.join("\n") + "\n" : "\n" });
341
453
  } else {
342
- console.log(c.yellow(" Nothing scheduled by us on this OS — remove any manual schedule yourself."));
454
+ ui.warn("totem schedules nothing on this system. If you scheduled it yourself, remove that.");
455
+ return true;
343
456
  }
457
+ ui.ok("Auto-update is off", "update by hand with: totem update");
344
458
  return true;
345
459
  }
346
460
 
347
461
  // ── flows ────────────────────────────────────────────────────────────────────
348
- async function runInteractive(ctx: UpdateCtx): Promise<number> {
349
- console.log(c.bold("\ntotem update") + c.gray(` — you're on v${ctx.version}\n`));
350
- const versions = await withSpinner("checking available versions", () => fetchVersions(ctx));
462
+
463
+ function finish(io: Io, ctx: UpdateCtx, target: VersionInfo, applied: Applied): number {
464
+ const { ui } = io;
465
+ // The step that failed has said why, what version this is back on, and what to run.
466
+ if (applied === "failed") return 1;
467
+ const d = ctx.detectDeploy();
468
+ if (applied === "local-only") {
469
+ ui.next([`This install is on ${target.version}. The server is not yet: finish the steps above.`]);
470
+ return 0;
471
+ }
472
+ if (!d || d.platform === "local") ui.next([`totem is now ${target.version}.`, "Restart your AI client so it starts the new version."]);
473
+ else { ui.line(); ui.ok(`totem is now ${target.version}, here and on the server`); }
474
+ return 0;
475
+ }
476
+
477
+ async function runInteractive(ctx: UpdateCtx, io: Io): Promise<number> {
478
+ const { ui } = io;
479
+ const { g } = ui.kit;
480
+ ui.header("totem update", `Version ${ctx.version} is installed.`);
481
+ const versions = await ui.task("Looking up releases", () => fetchVersions(ctx, io));
351
482
  if (!versions.length) {
352
- console.log(c.red(" Couldn't list versions (offline, or no releases found)."));
483
+ ui.problem("Couldn't get the list of releases.", { detail: "Is this machine online?", fix: [["Try again", "totem update"]] });
353
484
  return 1;
354
485
  }
355
486
  const latest = versions[0]!;
356
487
  const choices = versions.map((v) => {
357
- const tags: string[] = [];
358
- if (v.version === latest.version) tags.push(c.green("latest"));
359
- if (v.version === ctx.version) tags.push(c.cyan("current"));
360
- if (v.date) tags.push(c.dim(v.date));
361
- const note = v.notes ? c.dim("· " + (v.notes.length > 44 ? v.notes.slice(0, 43) + "…" : v.notes)) : "";
362
- return { label: `v${v.version}`, hint: [tags.join(" "), note].filter(Boolean).join(" ") };
488
+ const facts = [v.version === latest.version ? "latest" : "", v.version === ctx.version ? "installed" : "", v.date ?? "", v.notes ?? ""].filter(Boolean);
489
+ return { label: v.version, hint: facts.join(` ${g.dot} `) };
363
490
  });
364
- const idx = await select("Update to which version? (newest is default)", choices, { defaultIndex: 0 });
365
- const target = versions[idx]!;
366
- const onLatest = target.version === latest.version;
367
-
368
- if (!onLatest) {
369
- const ahead = versions.filter((v) => compareSemver(v.version, target.version) > 0).map((v) => "v" + v.version);
370
- console.log(c.yellow(`\n ⚠ v${target.version} is NOT the newest — you'd be behind: ${ahead.join(", ")}.`));
371
- if (!(await promptYesNo(" Install this older version anyway?", false))) { console.log(c.gray(" Cancelled.")); return 0; }
491
+ const target = versions[await ui.select("Which version?", choices, 0)]!;
492
+
493
+ if (target.version !== latest.version) {
494
+ const ahead = versions.filter((v) => compareSemver(v.version, target.version) > 0).map((v) => v.version);
495
+ ui.warn(`${target.version} is older than ${listOf(ahead.length > 3 ? [...ahead.slice(0, 3), `${ahead.length - 3} more`] : ahead)}.`);
496
+ if (!(await ui.confirm(`Install ${target.version} anyway?`, false))) { ui.hint("Nothing changed.", 2); return 0; }
372
497
  } else if (target.version === ctx.version) {
373
- if (!(await promptYesNo(`\n You're already on v${ctx.version} (the latest). Re-apply anyway?`, false))) { console.log(c.gray(" Nothing to do.")); return 0; }
498
+ ui.ok(`${ctx.version} is the latest, and it is installed`);
499
+ if (!(await ui.confirm("Install it again anyway?", false))) return 0;
374
500
  }
375
501
 
376
- const code = await applyVersion(ctx, target, latest);
377
- if (code !== 0) return code;
378
-
379
- // After a successful apply, manage the auto-update toggle.
380
- const autoOn = isAutoOn();
381
- if (onLatest) {
382
- if (!autoOn) {
383
- console.log("");
384
- if (await promptYesNo(" Turn on auto-update? (auto-pulls + sets up every new release)", false)) await enableAuto(ctx);
385
- } else {
386
- console.log(c.gray("\n Auto-update is on — new releases install themselves."));
502
+ const applied = await applyVersion(ctx, target, io);
503
+ if (applied !== "failed") {
504
+ // The auto-update switch has to agree with the choice just made.
505
+ const autoOn = await isAutoOn(io);
506
+ if (target.version === latest.version && !autoOn && (io.sys.platform === "darwin" || io.sys.platform === "linux")) {
507
+ ui.line();
508
+ if (await ui.confirm("Install new releases automatically from now on?", false)) await enableAuto(ctx, io);
509
+ } else if (target.version !== latest.version && autoOn) {
510
+ ui.line();
511
+ ui.warn(`Auto-update is on: at its next check it would move you back to ${latest.version}.`);
512
+ if (await ui.confirm(`Turn it off to stay on ${target.version}?`, true)) await disableAuto(io);
387
513
  }
388
- } else if (autoOn) {
389
- console.log(c.yellow("\n ⚠ Auto-update is ON — it'll move you back to the latest on the next check."));
390
- if (await promptYesNo(" Turn auto-update OFF to stay pinned to this version?", true)) await disableAuto(ctx);
391
514
  }
392
-
393
- printDone(target.version);
394
- return 0;
515
+ return finish(io, ctx, target, applied);
395
516
  }
396
517
 
397
- async function runCheck(ctx: UpdateCtx): Promise<number> {
398
- console.log(c.bold("\ntotem update --check") + c.gray(` — installed v${ctx.version}\n`));
399
- const versions = await withSpinner("checking available versions", () => fetchVersions(ctx));
400
- if (!versions.length) { console.log(c.red(" Couldn't list versions (offline?).")); return 1; }
518
+ async function runCheck(ctx: UpdateCtx, io: Io): Promise<number> {
519
+ const { ui } = io;
520
+ ui.header("totem update --check");
521
+ const versions = await ui.task("Looking up releases", () => fetchVersions(ctx, io));
522
+ if (!versions.length) {
523
+ ui.problem("Couldn't get the list of releases.", { detail: "Is this machine online?", fix: [["Try again", "totem update --check"]] });
524
+ return 1;
525
+ }
401
526
  const latest = versions[0]!;
402
- console.log(` installed: v${ctx.version}`);
403
- console.log(` latest: v${latest.version}${latest.date ? c.gray(" " + latest.date) : ""}`);
404
- console.log(isNewer(latest.version, ctx.version)
405
- ? c.green(` ▲ update available — run \`totem update\``)
406
- : c.green(` ✓ up to date`));
407
- console.log(c.gray(` auto-update: ${isAutoOn() ? "on" : "off"} · ${versions.length} versions available`));
527
+ ui.rows([
528
+ ["Installed", ctx.version],
529
+ ["Latest", `${latest.version}${latest.date ? `, released ${latest.date}` : ""}`],
530
+ ["Auto-update", (await isAutoOn(io)) ? "on" : "off"],
531
+ ]);
532
+ ui.line();
533
+ if (isNewer(latest.version, ctx.version)) {
534
+ ui.warn(`An update is available: ${latest.version}.`);
535
+ ui.rows([["Install it", ui.kit.c.accent("totem update")]], 2);
536
+ } else {
537
+ ui.ok("Up to date");
538
+ }
408
539
  return 0;
409
540
  }
410
541
 
411
- // The scheduled job: non-interactive, pull-to-latest-if-newer, log everything.
412
- async function runAuto(ctx: UpdateCtx): Promise<number> {
413
- const stamp = new Date().toISOString();
414
- const versions = await fetchVersions(ctx);
415
- const latest = versions[0];
416
- if (!latest) { console.log(`[totem auto-update ${stamp}] no version list (offline?) — skipping`); return 0; }
417
- if (!isNewer(latest.version, ctx.version)) { console.log(`[totem auto-update ${stamp}] up to date on v${ctx.version}`); return 0; }
418
- console.log(`[totem auto-update ${stamp}] new release v${latest.version} (was v${ctx.version}) — applying`);
419
- const code = await applyVersion(ctx, latest, latest);
420
- console.log(`[totem auto-update ${stamp}] ${code === 0 ? `done → v${latest.version}` : `FAILED (exit ${code})`}`);
421
- return code;
542
+ /**
543
+ * Whether an unattended update may move this checkout: `git rev-parse
544
+ * --abbrev-ref HEAD` says `main`, or `HEAD` when detached (at a release tag).
545
+ * An empty answer (git failed) is not a yes.
546
+ */
547
+ export function followsReleases(branch: string): boolean {
548
+ return branch === "main" || branch === "HEAD";
422
549
  }
423
550
 
424
- export async function runUpdate(args: string[], ctx: UpdateCtx): Promise<number> {
551
+ // The scheduled job: no questions, install the latest if it is newer, and leave
552
+ // one dated line per outcome in the log.
553
+ async function runAuto(ctx: UpdateCtx, io: Io): Promise<number> {
554
+ const { ui, sys } = io;
555
+ const log = (message: string): void => ui.line(`[totem auto-update ${new Date(sys.now()).toISOString()}] ${message}`);
556
+ if (ctx.isGit) {
557
+ // An update checks out the release tag. Only do that unattended to a
558
+ // checkout that is following releases: on `main`, or already detached at a
559
+ // tag. Anything else is someone's work in progress (a feature branch whose
560
+ // tracked tree happens to be clean), and silently moving it off its branch
561
+ // loses their place.
562
+ const branch = (await sys.exec("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd: ctx.root })).stdout.trim();
563
+ if (!followsReleases(branch)) {
564
+ log(`on branch '${branch}', not main or a release tag: skipped (update it yourself with \`totem update\`)`);
565
+ return 0;
566
+ }
567
+ }
568
+ const latest = (await fetchVersions(ctx, io))[0];
569
+ if (!latest) { log("couldn't get the list of releases (offline?): skipped"); return 0; }
570
+ if (!isNewer(latest.version, ctx.version)) { log(`up to date on ${ctx.version}`); return 0; }
571
+ log(`${latest.version} is out (installed: ${ctx.version}): installing`);
572
+ const applied = await applyVersion(ctx, latest, io);
573
+ if (applied === "done") log(`now on ${latest.version}`);
574
+ else if (applied === "local-only") log(`this install is on ${latest.version}; the server was NOT updated (see above)`);
575
+ else log(`FAILED: still on ${ctx.version}; the next check tries again`);
576
+ return applied === "failed" ? 1 : 0;
577
+ }
578
+
579
+ export async function runUpdate(args: string[], ctx: UpdateCtx, io: Io = realIo()): Promise<number> {
580
+ const { ui } = io;
425
581
  const autoIdx = args.indexOf("--auto");
426
582
  if (autoIdx !== -1) {
427
583
  const val = (args[autoIdx + 1] ?? "").toLowerCase();
428
584
  if (val === "on") {
429
- console.log(c.bold("\ntotem update --auto on\n"));
430
- if (!(await enableAuto(ctx))) return 1;
431
- // Enabling implies "I want newest" — do one check/pull right now.
432
- console.log("");
433
- return runAuto(ctx);
585
+ ui.header("totem update --auto on", "Install new releases automatically.");
586
+ if (!(await enableAuto(ctx, io))) return 1;
587
+ // Turning it on means "I want the newest": check once now.
588
+ const latest = (await ui.task("Looking up releases", () => fetchVersions(ctx, io)))[0];
589
+ if (!latest) { ui.warn("Couldn't check for a release right now; the first scheduled check will."); return 0; }
590
+ if (!isNewer(latest.version, ctx.version)) { ui.ok("Up to date", `${ctx.version} is the latest`); return 0; }
591
+ ui.info(`${latest.version} is out: installing it now.`);
592
+ return finish(io, ctx, latest, await applyVersion(ctx, latest, io));
593
+ }
594
+ if (val === "off") {
595
+ ui.header("totem update --auto off");
596
+ return (await disableAuto(io)) ? 0 : 1;
434
597
  }
435
- if (val === "off") { console.log(c.bold("\ntotem update --auto off\n")); return (await disableAuto(ctx)) ? 0 : 1; }
436
- console.log(c.red("Usage: totem update --auto <on|off>"));
598
+ ui.error(`--auto takes "on" or "off"${val ? `, not "${val}"` : ""}.`, { fix: [["Turn it on", "totem update --auto on"], ["Turn it off", "totem update --auto off"]] });
437
599
  return 1;
438
600
  }
439
- if (args.includes("--auto-run")) return runAuto(ctx);
440
- if (args.includes("--check")) return runCheck(ctx);
441
- return runInteractive(ctx);
601
+ if (args.includes("--auto-run")) return runAuto(ctx, io);
602
+ if (args.includes("--check")) return runCheck(ctx, io);
603
+ return runInteractive(ctx, io);
442
604
  }