@songsid/agend 2.4.0-beta.25 → 2.4.0-beta.26

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 (157) hide show
  1. package/dist/agent-file-read.js +1 -1
  2. package/dist/agent-file-read.js.map +1 -1
  3. package/dist/auth-api.js +3 -1
  4. package/dist/auth-api.js.map +1 -1
  5. package/dist/build-provenance.json +1 -1
  6. package/dist/channel/mcp-tools.js +1 -1
  7. package/dist/channel/mcp-tools.js.map +1 -1
  8. package/dist/delivery-outbox.js +4 -1
  9. package/dist/delivery-outbox.js.map +1 -1
  10. package/dist/fleet-lock.d.ts +16 -0
  11. package/dist/fleet-lock.js +40 -0
  12. package/dist/fleet-lock.js.map +1 -1
  13. package/dist/fleet-manager.d.ts +20 -1
  14. package/dist/fleet-manager.js +154 -14
  15. package/dist/fleet-manager.js.map +1 -1
  16. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +6 -1
  17. package/dist/general-knowledge/skills/hub/SKILL.md +12 -1
  18. package/dist/general-knowledge/skills/web-appearance/SKILL.md +3 -1
  19. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +7 -0
  20. package/dist/hub/client.js +7 -0
  21. package/dist/hub/client.js.map +1 -1
  22. package/dist/hub/compose/member.js +6 -1
  23. package/dist/hub/compose/member.js.map +1 -1
  24. package/dist/hub/compose/server.d.ts +1 -0
  25. package/dist/hub/compose/server.js +3 -2
  26. package/dist/hub/compose/server.js.map +1 -1
  27. package/dist/hub/http/compose.js +3 -2
  28. package/dist/hub/http/compose.js.map +1 -1
  29. package/dist/hub/http/deps.d.ts +1 -0
  30. package/dist/hub/member/room-ask.d.ts +7 -8
  31. package/dist/hub/member/room-ask.js +52 -13
  32. package/dist/hub/member/room-ask.js.map +1 -1
  33. package/dist/hub/member/room-reaction-acks.d.ts +12 -0
  34. package/dist/hub/member/room-reaction-acks.js +44 -0
  35. package/dist/hub/member/room-reaction-acks.js.map +1 -0
  36. package/dist/hub/protocol.d.ts +4 -0
  37. package/dist/hub/protocol.js +2 -2
  38. package/dist/hub/protocol.js.map +1 -1
  39. package/dist/hub/roles/audit-details.d.ts +2 -0
  40. package/dist/hub/roles/audit-details.js +1 -1
  41. package/dist/hub/roles/audit-details.js.map +1 -1
  42. package/dist/hub/roles/authority.d.ts +8 -3
  43. package/dist/hub/roles/authority.js +144 -102
  44. package/dist/hub/roles/authority.js.map +1 -1
  45. package/dist/hub/roles/delegation.js +2 -2
  46. package/dist/hub/roles/delegation.js.map +1 -1
  47. package/dist/hub/roles/model.d.ts +5 -2
  48. package/dist/hub/roles/model.js +5 -4
  49. package/dist/hub/roles/model.js.map +1 -1
  50. package/dist/hub/roles/review.js +2 -2
  51. package/dist/hub/roles/review.js.map +1 -1
  52. package/dist/hub/room-react-ack-model.d.ts +2 -0
  53. package/dist/hub/room-react-ack-model.js +3 -0
  54. package/dist/hub/room-react-ack-model.js.map +1 -0
  55. package/dist/hub/rooms/admin.d.ts +6 -0
  56. package/dist/hub/rooms/admin.js +33 -0
  57. package/dist/hub/rooms/admin.js.map +1 -1
  58. package/dist/hub/rooms/agents.d.ts +2 -0
  59. package/dist/hub/rooms/agents.js +44 -3
  60. package/dist/hub/rooms/agents.js.map +1 -1
  61. package/dist/hub/rooms/service.d.ts +5 -1
  62. package/dist/hub/rooms/service.js +76 -24
  63. package/dist/hub/rooms/service.js.map +1 -1
  64. package/dist/hub/rooms/types.d.ts +2 -0
  65. package/dist/hub/server.js +6 -1
  66. package/dist/hub/server.js.map +1 -1
  67. package/dist/hub/types.d.ts +2 -0
  68. package/dist/locale.js +2 -2
  69. package/dist/locale.js.map +1 -1
  70. package/dist/public-web-gateway.js +2 -0
  71. package/dist/public-web-gateway.js.map +1 -1
  72. package/dist/recover.cjs +212 -26
  73. package/dist/request-contact-native.js +4 -0
  74. package/dist/request-contact-native.js.map +1 -1
  75. package/dist/scheduler/scheduler.d.ts +9 -0
  76. package/dist/scheduler/scheduler.js +26 -0
  77. package/dist/scheduler/scheduler.js.map +1 -1
  78. package/dist/scheduler/scheduler.test.js +17 -0
  79. package/dist/scheduler/scheduler.test.js.map +1 -1
  80. package/dist/settings-api.js +72 -0
  81. package/dist/settings-api.js.map +1 -1
  82. package/dist/settings-change.js +13 -0
  83. package/dist/settings-change.js.map +1 -1
  84. package/dist/settings-effect.js +11 -1
  85. package/dist/settings-effect.js.map +1 -1
  86. package/dist/ui/contact-auth-strings.js +7 -2
  87. package/dist/ui/contact-permissions.js +10 -2
  88. package/dist/ui/fleet-office-pack.d.ts +2 -2
  89. package/dist/ui/fleet-office-pack.js +25 -8
  90. package/dist/ui/fleet-office-vehicles.js +28 -11
  91. package/dist/ui/fleet-office-zones.js +2 -2
  92. package/dist/ui/fleet-office.js +25 -5
  93. package/dist/ui/hub-admin-rooms-strings.js +6 -2
  94. package/dist/ui/hub-admin-rooms.js +3 -1
  95. package/dist/ui/hub-group-search.js +2 -2
  96. package/dist/ui/hub-notify-keep.js +49 -0
  97. package/dist/ui/hub-role-view.js +1 -1
  98. package/dist/ui/hub-roles-strings.js +14 -10
  99. package/dist/ui/hub-roles.js +1 -1
  100. package/dist/ui/hub-room-notify.js +2 -1
  101. package/dist/ui/hub-room-strings.js +3 -3
  102. package/dist/ui/hub-room-thread.js +9 -4
  103. package/dist/ui/panel-hub.js +3 -2
  104. package/dist/ui/panel-needs.js +13 -5
  105. package/dist/ui/settings-update.js +13 -0
  106. package/dist/ui/shared/app-install.js +123 -0
  107. package/dist/ui/shared/app-shell.js +4 -2
  108. package/dist/ui/shared/app-update.js +16 -2
  109. package/dist/ui/shared/app.css +43 -0
  110. package/dist/ui/shared/app.js +3 -0
  111. package/dist/ui/shared/hub-chat.css +6 -0
  112. package/dist/ui/shared/ui-confirm.js +4 -3
  113. package/dist/ui/shared/ui-icons.js +2 -0
  114. package/dist/ui/shared/update-card-ui.js +419 -0
  115. package/dist/update-abandon.d.ts +26 -0
  116. package/dist/update-abandon.js +111 -0
  117. package/dist/update-abandon.js.map +1 -0
  118. package/dist/update-forward.d.ts +5 -19
  119. package/dist/update-forward.js +19 -75
  120. package/dist/update-forward.js.map +1 -1
  121. package/dist/update-goback.d.ts +90 -0
  122. package/dist/update-goback.js +260 -0
  123. package/dist/update-goback.js.map +1 -0
  124. package/dist/update-journal.d.ts +8 -0
  125. package/dist/update-journal.js +8 -2
  126. package/dist/update-journal.js.map +1 -1
  127. package/dist/update-package-restore.d.ts +11 -2
  128. package/dist/update-package-restore.js +16 -5
  129. package/dist/update-package-restore.js.map +1 -1
  130. package/dist/update-quiescence.d.ts +38 -9
  131. package/dist/update-quiescence.js +50 -10
  132. package/dist/update-quiescence.js.map +1 -1
  133. package/dist/update-recovery/recover.js +10 -0
  134. package/dist/update-recovery/recover.js.map +1 -1
  135. package/dist/update-recovery/runner.d.ts +4 -0
  136. package/dist/update-recovery/runner.js +38 -5
  137. package/dist/update-recovery/runner.js.map +1 -1
  138. package/dist/update-restore.d.ts +7 -1
  139. package/dist/update-restore.js +10 -5
  140. package/dist/update-restore.js.map +1 -1
  141. package/dist/update-retained.d.ts +28 -1
  142. package/dist/update-retained.js +28 -3
  143. package/dist/update-retained.js.map +1 -1
  144. package/dist/update-settings.d.ts +27 -0
  145. package/dist/update-settings.js +40 -0
  146. package/dist/update-settings.js.map +1 -1
  147. package/dist/update-snapshot-scope.js +1 -0
  148. package/dist/update-snapshot-scope.js.map +1 -1
  149. package/dist/web-icons.d.ts +11 -0
  150. package/dist/web-icons.js +14 -2
  151. package/dist/web-icons.js.map +1 -1
  152. package/dist/web-mentions.d.ts +27 -8
  153. package/dist/web-mentions.js +108 -1
  154. package/dist/web-mentions.js.map +1 -1
  155. package/dist/web-office-acts.js +3 -0
  156. package/dist/web-office-acts.js.map +1 -1
  157. package/package.json +2 -2
@@ -0,0 +1,419 @@
1
+ // M-3770 slice 1.4 (design #4480 §3.1, §3.2, §4.1, §6): the one update card on the web — its line on the banner, its
2
+ // answers (Update when idle, Pick a time, Not now, Update now, Cancel), the pre-flight result ("Updates on this
3
+ // machine"), and Settings → Version and update's controls (when not to update; Advanced: pin, longest wait). A module of
4
+ // its own (the module-skew rule): app-update.js and settings-update.js import it; an older cached copy of either simply
5
+ // does not show the card (it never meets a missing export). The server's words: GET /ui/update's `card` and `preflight`
6
+ // (S-234 / S-235 / S-236), POST /ui/update/answer, PUT /api/settings/fleet/updates.
7
+ import { html, useEffect, useState } from "./app-html.js";
8
+ import { register, t } from "./app-i18n.js";
9
+ import { confirmDialog } from "./ui-confirm.js";
10
+ import { Dialog } from "./ui-dialog.js";
11
+ import { toast } from "./ui-toast.js";
12
+ import { dateTimeText } from "./clock-text.js";
13
+
14
+ register("updatecard", {
15
+ en: {
16
+ ready: "AgEnD {0} is ready.",
17
+ continues: "Your work continues.",
18
+ backPhase1: "Your work continues; if the new version won't start, AgEnD tries to roll back to {0}.",
19
+ noWayBack: "Your work continues; this setup can't restart AgEnD by itself, so check on it afterwards.",
20
+ howTo: "How to update", pressOnlyLine: "AgEnD can't update itself on this machine; update it by hand.", sep: ", ", more: " and {0} more",
21
+ whenIdle: "Update when idle", pickTime: "Pick a time", notNow: "Not now", updateNow: "Update now", cancel: "Cancel",
22
+ waiting: "Updating to {0} as soon as your agents are idle.", waitingFor: "Waiting for: {0}", waitingSince: "Waiting since {0}",
23
+ scheduled: "Updating to {0} at {1}, when your agents are idle.", notNowUntil: "You chose Not now. The card comes back on {0}.",
24
+ starting: "Starting the update to {0}…", cantTitle: "AgEnD can't update itself on this machine.",
25
+ nowTitle: "Update now?", nowBody: "{0} agents are working. They stop for a few minutes while AgEnD restarts, then pick up where they were.",
26
+ nowBodyIdle: "AgEnD restarts for a few minutes; your agents pick up where they were.", nowGo: "Update now",
27
+ pickTitle: "When should AgEnD update?", pickTonight: "Tonight", pickMorning: "Tomorrow morning", pickOther: "Another time", pickDay: "Day", pickAt: "Time",
28
+ pickHint: "It still waits until your agents are idle at that time. Within the next 7 days.", pickGo: "Schedule", pickBad: "Pick a time in the next 7 days.",
29
+ changed: "The update changed while you were looking. Here it is again.", running: "An update is already running.",
30
+ failedAnswer: "That didn't work: {0}",
31
+ machine: "Updates on this machine", self: "AgEnD can update itself here.", adminOnly: "Updates here need you:",
32
+ stop: "AgEnD can't update here until this is fixed.", notChecked: "not checked yet", checking: "Not checked yet: it's checked when AgEnD starts and once a day.",
33
+ pauseTitle: "Don't update during", pauseHint: "Days and hours when AgEnD never updates (a waiting update waits for the window to end).",
34
+ pauseAdd: "Add a time", pauseRemove: "Remove", from: "From", to: "To", save: "Save", saved: "Saved.", saveFailed: "Couldn't save: {0}",
35
+ settingsLabel: "When AgEnD updates", pending: "Waiting for confirmation: this lets updates go ahead sooner.", applied: "Confirmed and saved.",
36
+ advanced: "Advanced", pin: "Pin to a version", pinHint: "No update is offered while a version is pinned. Leave empty for none.",
37
+ maxWait: "Longest wait for idle (hours)", maxWaitHint: "After this, AgEnD asks again instead of waiting (1–168, default 24).",
38
+ days: "Sun,Mon,Tue,Wed,Thu,Fri,Sat",
39
+ c_checkout: "AgEnD runs from a source checkout, not from an install npm updates. Update it with git.",
40
+ c_other_copy: "Another copy of AgEnD ({path}) is the one npm would update, not the one running. Run the fleet from the global install.",
41
+ c_path_shadow: "Another agend on the PATH ({path}) would run instead of this one. Remove it or fix the PATH.",
42
+ c_unreadable: "AgEnD can't read where it's installed right now. Try again in a minute.",
43
+ c_shared_home: "Another AgEnD install uses the same home folder. Give each its own home, or remove one.",
44
+ c_unknown_owner: "AgEnD can't prove which install runs this fleet. Restart it as a service and check again.",
45
+ c_other_install: "Another AgEnD install lives under this user. Updating one could affect the other.",
46
+ c_not_service: "AgEnD isn't running as a service, so it can't bring itself back after an update.",
47
+ c_service_unknown: "AgEnD can't confirm that its service will bring it back after an update.",
48
+ notAllChecked: "Some checks haven't run yet; they run when AgEnD starts and once a day.",
49
+ c_linger_off: "AgEnD stops when the user {user} signs out, so it can't restart itself. To fix it, run `sudo loginctl enable-linger {user}`.",
50
+ c_system_unit_not_root: "AgEnD runs as a system service; updating it needs root.",
51
+ c_unit_reload_pending: "The service definition changed and hasn't been reloaded. Run `systemctl --user daemon-reload`.",
52
+ c_no_write: "Updating needs write access to {path}. Run `sudo agend update` in a terminal on that computer, or reinstall with the one-line installer.",
53
+ c_linked: "This AgEnD is linked from a development folder ({path}); an update replaces the link.",
54
+ c_vendored: "This AgEnD sits inside another project ({path}).",
55
+ c_low_disk: "Updating needs about {need} free on {path}; there's {have}.",
56
+ c_npm_unreachable: "The update source can't be reached from this machine (network or proxy).",
57
+ c_rehearsal: "A rehearsal or test is running here; updates wait until it ends.",
58
+ c_update_running: "An update is already running.",
59
+ c_container: "AgEnD runs in a container; update the image.",
60
+ c_windows_runtime: "This computer's AgEnD Runtime updates itself.",
61
+ c_node_too_old: "AgEnD {0} needs Node {needs}; this machine has {node}.",
62
+ c_other: "A check didn't pass ({0}).",
63
+ },
64
+ "zh-TW": {
65
+ ready: "AgEnD {0} 可以更新了。",
66
+ continues: "工作不會中斷。",
67
+ backPhase1: "工作不會中斷;新版起不來時,AgEnD 會嘗試退回 {0}。",
68
+ noWayBack: "工作不會中斷;這台機器無法自行重新啟動 AgEnD,更新後請確認一下。",
69
+ howTo: "如何更新", pressOnlyLine: "這台機器上 AgEnD 無法自行更新,請手動更新。", sep: "、", more: ",另有 {0} 個",
70
+ whenIdle: "閒置時更新", pickTime: "選個時間", notNow: "先不要", updateNow: "立即更新", cancel: "取消",
71
+ waiting: "Agent 一閒置就更新到 {0}。", waitingFor: "正在等:{0}", waitingSince: "從 {0} 開始等",
72
+ scheduled: "排定在 {1},等 Agent 閒置後更新到 {0}。", notNowUntil: "你選了「先不要」,{0} 會再提醒。",
73
+ starting: "正在開始更新到 {0}…", cantTitle: "AgEnD 無法在這台機器上自行更新。",
74
+ nowTitle: "立即更新?", nowBody: "有 {0} 個 Agent 正在工作。AgEnD 重新啟動時會停下幾分鐘,之後從原處繼續。",
75
+ nowBodyIdle: "AgEnD 會重新啟動幾分鐘,Agent 之後從原處繼續。", nowGo: "立即更新",
76
+ pickTitle: "要在什麼時候更新?", pickTonight: "今晚", pickMorning: "明天早上", pickOther: "其他時間", pickDay: "日期", pickAt: "時間",
77
+ pickHint: "到了那個時間,仍會等 Agent 閒置才開始。可排定在未來 7 天內。", pickGo: "排定", pickBad: "請選擇未來 7 天內的時間。",
78
+ changed: "這個更新剛剛有變動,以下是最新狀態。", running: "已經有一個更新在進行中。",
79
+ failedAnswer: "沒有成功:{0}",
80
+ machine: "這台機器的更新", self: "AgEnD 可以在這裡自行更新。", adminOnly: "這裡的更新需要你來進行:",
81
+ stop: "這個問題解決前,AgEnD 無法在這裡更新。", notChecked: "尚未檢查", checking: "尚未檢查:AgEnD 啟動時和每天會檢查一次。",
82
+ pauseTitle: "這些時段不更新", pauseHint: "AgEnD 絕不會在這些日子和時段更新(等待中的更新會等時段結束)。",
83
+ pauseAdd: "新增時段", pauseRemove: "移除", from: "從", to: "到", save: "儲存", saved: "已儲存。", saveFailed: "無法儲存:{0}",
84
+ settingsLabel: "AgEnD 何時更新", pending: "等待確認中:這項變更會讓更新提早進行。", applied: "已確認並儲存。",
85
+ advanced: "進階", pin: "固定在某個版本", pinHint: "固定版本時不會提供任何更新。留空表示不固定。",
86
+ maxWait: "等 Agent 閒下來的上限(小時)", maxWaitHint: "超過之後,AgEnD 會再問你,而不是繼續等(1–168,預設 24)。",
87
+ days: "日,一,二,三,四,五,六",
88
+ c_checkout: "AgEnD 是從原始碼資料夾執行的,不是 npm 會更新的安裝。請用 git 更新。",
89
+ c_other_copy: "npm 會更新的是另一份 AgEnD({path}),不是正在執行的這份。請改用全域安裝執行 Fleet。",
90
+ c_path_shadow: "PATH 上的另一個 agend({path})會被優先執行。請移除它或修正 PATH。",
91
+ c_unreadable: "AgEnD 目前讀不到自己的安裝位置,請稍後再試。",
92
+ c_shared_home: "另一份 AgEnD 使用同一個 home 資料夾。請讓每份各用自己的 home,或移除其中一份。",
93
+ c_unknown_owner: "AgEnD 無法確認是哪一份安裝在執行這個 Fleet。請以服務方式重新啟動後再檢查。",
94
+ c_other_install: "這個使用者底下還有另一份 AgEnD。更新其中一份可能影響另一份。",
95
+ c_not_service: "AgEnD 不是以服務方式執行,更新後無法自己回來。",
96
+ c_service_unknown: "AgEnD 無法確認它的服務在更新後會讓它重新啟動。",
97
+ notAllChecked: "有些檢查還沒跑完;AgEnD 啟動時和每天會檢查一次。",
98
+ c_linger_off: "使用者 {user} 登出後 AgEnD 會停止,所以無法自行重新啟動。修正方式:執行 `sudo loginctl enable-linger {user}`。",
99
+ c_system_unit_not_root: "AgEnD 以系統服務執行,更新需要 root。",
100
+ c_unit_reload_pending: "服務定義已變更但尚未重新載入。請執行 `systemctl --user daemon-reload`。",
101
+ c_no_write: "更新需要 {path} 的寫入權限。請在那台電腦的終端機執行 `sudo agend update`,或用單行安裝指令重新安裝。",
102
+ c_linked: "這份 AgEnD 是從開發資料夾連結的({path}),更新會取代這個連結。",
103
+ c_vendored: "這份 AgEnD 位於另一個專案裡({path})。",
104
+ c_low_disk: "更新需要 {path} 約 {need} 的可用空間,目前只有 {have}。",
105
+ c_npm_unreachable: "這台機器連不到更新來源(網路或 Proxy 設定)。",
106
+ c_rehearsal: "這裡正在進行演練或測試,更新會等它結束。",
107
+ c_update_running: "已經有一個更新在進行中。",
108
+ c_container: "AgEnD 在容器裡執行,請更新映像檔。",
109
+ c_windows_runtime: "這台電腦的 AgEnD Runtime 會自行更新。",
110
+ c_node_too_old: "AgEnD {0} 需要 Node {needs},這台機器是 {node}。",
111
+ c_other: "有一項檢查沒有通過({0})。",
112
+ },
113
+ });
114
+ const tc = (key, ...a) => t(`updatecard.${key}`, ...a);
115
+
116
+ /** A pre-flight check's sentence: its code's words with the detail filled in (never raw error text). */
117
+ export function checkSentence(check, version = "") {
118
+ if (!check || !check.code) return "";
119
+ const key = `c_${String(check.code).replace(/-/g, "_")}`;
120
+ let s = t(`updatecard.${key}`, version);
121
+ if (s === `updatecard.${key}`) return tc("c_other", String(check.code));
122
+ const d = check.detail && typeof check.detail === "object" ? check.detail : {};
123
+ return s.replace(/\{(path|user|need|have|node|needs)\}/g, (_, k) => (d[k] !== undefined ? String(d[k]).replace(/`/g, "'") : "…"));
124
+ }
125
+ /** A check's sentence as plain text (a toast): the command marks dropped. */
126
+ export function checkText(check, version = "") { return checkSentence(check, version).replace(/`/g, ""); }
127
+ /** A check's sentence for the page: a `command` in it is shown as copyable code (#4487 UX look). */
128
+ export function checkRich(check, version = "") {
129
+ return checkSentence(check, version).split("`").map((part, i) => (i % 2 ? html`<code class="uc-cmd">${part}</code>` : part));
130
+ }
131
+ /** The checks that did not pass, in P-order (absent checks are not failures: they were not run). */
132
+ export function failedChecks(preflight) {
133
+ const checks = preflight && Array.isArray(preflight.checks) ? preflight.checks : [];
134
+ return checks.filter((c) => c && c.ok === false).sort((a, b) => Number(String(a.id).slice(1)) - Number(String(b.id).slice(1)));
135
+ }
136
+ /** Whether this machine is a service install (P3 present and passing): the Phase 1 "tries to put it back" sentence is true. */
137
+ export function serviceInstall(preflight) {
138
+ const p3 = preflight && Array.isArray(preflight.checks) ? preflight.checks.find((c) => c && c.id === "P3") : null;
139
+ return !!(p3 && p3.ok);
140
+ }
141
+ /** May the admin press Update here (the server's `pressHere`; no pre-flight yet: as today, yes). */
142
+ export function pressHere(info) { return !info || !info.preflight || info.preflight.pressHere !== false; }
143
+
144
+ /** The card's second sentence (§3.1, Phase 1): only what is true on this machine; none before pre-flight has run. */
145
+ export function backSentence(info) {
146
+ const pf = info && info.preflight;
147
+ if (!pf || !Array.isArray(pf.checks) || !pf.checks.some((c) => c && c.id === "P3")) return tc("continues");
148
+ return serviceInstall(pf) ? tc("backPhase1", info.current) : tc("noWayBack");
149
+ }
150
+ /** The busy agents, capped (the leader's copy pass): "A, B and 3 more" / 「A、B,另有 3 個」 (#4487 UX look). */
151
+ export function namesShown(names, max = 2) {
152
+ const list = Array.isArray(names) ? names.filter(Boolean) : [];
153
+ return list.length <= max ? list.join(tc("sep")) : `${list.slice(0, max).join(tc("sep"))}${tc("more", list.length - max)}`;
154
+ }
155
+
156
+ // M-3730: through the shared clock helper (24-hour in zh-TW); English is 24-hour here too, as the leader asked for this card.
157
+ const fmtTime = (ms) => dateTimeText(ms, { weekday: "short", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
158
+ const fmtDay = (ms) => dateTimeText(ms, { weekday: "short", month: "short", day: "numeric" }).replace(/\s*\d{1,2}:\d{2}(:\d{2})?$/, "");
159
+ /** "HH:MM" every `step` minutes of a day: the 24-hour choices (never the browser's own time input, which shows AM/PM). */
160
+ export function dayTimes(step = 15) { const out = []; for (let m = 0; m < 24 * 60; m += step) out.push(`${String(Math.floor(m / 60)).padStart(2, "0")}:${String(m % 60).padStart(2, "0")}`); return out; }
161
+
162
+ /**
163
+ * POST /ui/update/answer. The answer's card replaces the store's; 412 carries a fresh pre-flight; 409 card_changed reads
164
+ * again. `refresh` is app-update.js's, `setInfo` writes the store (passed in: this module never imports app-update.js).
165
+ */
166
+ export async function answerCard(body, { refresh, setInfo, getInfo }) {
167
+ const key = `answer-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
168
+ let res = null, out = null;
169
+ try {
170
+ res = await fetch("/ui/update/answer", { method: "POST", headers: { "Content-Type": "application/json", "Idempotency-Key": key }, body: JSON.stringify(body) });
171
+ try { out = await res.json(); } catch { out = null; }
172
+ } catch { res = null; }
173
+ const info = getInfo();
174
+ if (res && res.ok && out && "card" in out) { if (info) setInfo({ ...info, card: out.card }); return { ok: true, card: out.card }; }
175
+ if (res && res.status === 412 && out && out.preflight) {
176
+ if (info) setInfo({ ...info, preflight: out.preflight });
177
+ const first = failedChecks(out.preflight)[0];
178
+ toast(first ? checkText(first, info && info.card ? info.card.version : "") : tc("stop"), false);
179
+ return { ok: false, preflight: out.preflight };
180
+ }
181
+ if (res && res.status === 409) toast(out && out.key === "update_running" ? tc("running") : tc("changed"), false);
182
+ else toast(tc("failedAnswer", (out && (out.key || out.error)) || (res ? String(res.status) : "network")), false);
183
+ await refresh();
184
+ return { ok: false };
185
+ }
186
+
187
+ /** Update now: one question naming how many agents work now (the card's waitingFor), then the answer. */
188
+ export async function updateNow(info, deps) {
189
+ const busy = info && info.card && Array.isArray(info.card.waitingFor) ? info.card.waitingFor.length : 0;
190
+ const yes = await confirmDialog({ title: tc("nowTitle"), confirmLabel: tc("nowGo"), message: busy ? tc("nowBody", busy) : tc("nowBodyIdle") });
191
+ if (!yes) return { ok: false };
192
+ return answerCard({ action: "now", confirm: "update-agend" }, deps);
193
+ }
194
+
195
+ /** The next whole time at hh:00 local, today if it is still ahead (by 30 min), else tomorrow. */
196
+ export function nextAt(hour, now = new Date()) {
197
+ const d = new Date(now); d.setHours(hour, 0, 0, 0);
198
+ if (d.getTime() - now.getTime() < 30 * 60_000) d.setDate(d.getDate() + 1);
199
+ return d.getTime();
200
+ }
201
+ /** hh:00 tomorrow (never a morning that has already begun or passed). */
202
+ export function tomorrowAt(hour, now = new Date()) { const d = new Date(now); d.setDate(d.getDate() + 1); d.setHours(hour, 0, 0, 0); return d.getTime(); }
203
+ const WEEK = 7 * 24 * 60 * 60_000;
204
+ /** Pick a time: tonight, tomorrow morning, or another time in the next 7 days. Resolves to ms epoch or null. */
205
+ let pickResolve = null;
206
+ export function pickTimeDialog() { return new Promise((resolve) => { pickResolve = resolve; pickSignal.forEach((f) => f()); }); }
207
+ const pickSignal = new Set();
208
+ export function PickTimeHost() {
209
+ const [open, setOpen] = useState(false);
210
+ const [choice, setChoice] = useState("tonight");
211
+ const [day, setDay] = useState(0);
212
+ const [time, setTime] = useState("20:00");
213
+ useEffect(() => { const f = () => { setChoice("tonight"); setDay(0); setTime("20:00"); setOpen(true); }; pickSignal.add(f); return () => pickSignal.delete(f); }, []);
214
+ if (!open) return null;
215
+ const close = (v) => { setOpen(false); const r = pickResolve; pickResolve = null; if (r) r(v); };
216
+ const otherAt = () => { const d = new Date(); d.setDate(d.getDate() + day); const [h, m] = time.split(":").map(Number); d.setHours(h, m, 0, 0); return d.getTime(); };
217
+ const at = () => choice === "tonight" ? nextAt(22) : choice === "morning" ? tomorrowAt(8) : otherAt();
218
+ const go = () => { const v = at(); if (!Number.isFinite(v) || v <= Date.now() || v > Date.now() + WEEK) { toast(tc("pickBad"), false); return; } close(v); };
219
+ const radio = (id, label) => html`<label class="check uc-pick-row"><input type="radio" name="uc-pick" checked=${choice === id} onChange=${() => setChoice(id)} /><span>${label}</span></label>`;
220
+ const days = Array.from({ length: 8 }, (_, i) => { const d = new Date(); d.setDate(d.getDate() + i); return { i, label: fmtDay(d.getTime()) }; });
221
+ return html`<${Dialog} title=${tc("pickTitle")} onClose=${() => close(null)}
222
+ actions=${html`<button type="button" class="btn" onClick=${() => close(null)}>${tc("cancel")}</button><button type="button" class="btn btn-primary" onClick=${go}>${tc("pickGo")}</button>`}>
223
+ <div class="uc-pick">
224
+ ${radio("tonight", `${tc("pickTonight")} · ${fmtTime(nextAt(22))}`)}
225
+ ${radio("morning", `${tc("pickMorning")} · ${fmtTime(tomorrowAt(8))}`)}
226
+ ${radio("other", tc("pickOther"))}
227
+ ${choice === "other" ? html`<div class="uc-pick-frame">
228
+ <label class="uc-pick-field"><span>${tc("pickDay")}</span><select class="input uc-pick-day" value=${String(day)} onChange=${(e) => setDay(Number(e.currentTarget.value))}>
229
+ ${days.map((d) => html`<option value=${String(d.i)}>${d.label}</option>`)}</select></label>
230
+ <label class="uc-pick-field"><span>${tc("pickAt")}</span><select class="input uc-pick-time" value=${time} onChange=${(e) => setTime(e.currentTarget.value)}>
231
+ ${dayTimes(15).map((x) => html`<option value=${x}>${x}</option>`)}</select></label>
232
+ </div>` : null}
233
+ <p class="muted uc-pick-hint">${tc("pickHint")}</p>
234
+ </div>
235
+ </${Dialog}>`;
236
+ }
237
+ export async function pickTime(deps) {
238
+ const at = await pickTimeDialog();
239
+ if (!at) return { ok: false };
240
+ return answerCard({ action: "pick-time", at }, deps);
241
+ }
242
+
243
+ /**
244
+ * The banner's line for the card (null: nothing to show — not-now, done, no card). `Line` is app-update.js's line
245
+ * component and `busy` its starting flag (passed in). The progress and the failure lines stay app-update.js's own.
246
+ */
247
+ /** Whether Pick a time is offered: the server takes a schedule only on a machine whose pre-flight says it can update itself
248
+ * (class self; no result yet: as today, yes) — an admin-only machine updates on a press only (#4487 review P2). */
249
+ export function canSchedule(info) {
250
+ const pf = info && info.preflight;
251
+ return pressHere(info) && (!pf || pf.class === "self");
252
+ }
253
+ /** One action policy for the banner and Settings (#4487 review P2): what an admin can do with the card in its state, on
254
+ * this machine. Update now is never the filled button once the admin has chosen to wait (#4487 UX look). */
255
+ export function cardActions(info, deps) {
256
+ const c = info && info.card;
257
+ if (!c || !info.admin) return [];
258
+ const press = pressHere(info), sched = canSchedule(info);
259
+ const act = (key, label, run, primary = false) => ({ key, label, primary, run });
260
+ const whenIdle = act("when-idle", tc("whenIdle"), () => answerCard({ action: "when-idle" }, deps), true);
261
+ const pick = act("pick-time", tc("pickTime"), () => pickTime(deps));
262
+ const later = act("not-now", tc("notNow"), () => answerCard({ action: "not-now" }, deps));
263
+ const cancel = act("cancel", tc("cancel"), () => answerCard({ action: "cancel" }, deps));
264
+ const now = act("now", tc("updateNow"), () => updateNow(info, deps));
265
+ if (c.state === "offered") return [press && whenIdle, sched && pick, later].filter(Boolean);
266
+ if (c.state === "not-now") return [press && whenIdle, sched && pick].filter(Boolean);
267
+ if (c.state === "waiting-idle") return [press && now, sched && pick, cancel].filter(Boolean);
268
+ if (c.state === "scheduled") return [press && now, cancel].filter(Boolean);
269
+ return [];
270
+ }
271
+ export function cardLine(info, { Line, busy, deps }) {
272
+ const c = info && info.card;
273
+ if (!c || !info.admin) return null;
274
+ const press = pressHere(info), fails = failedChecks(info.preflight);
275
+ // "Can't update here" (class stop): one line, in one place — Needs you (the leader's copy pass), not the banner too.
276
+ if (info.preflight && info.preflight.class === "stop" && (c.state === "offered" || c.state === "cant")) return null;
277
+ const buttons = cardActions(info, deps).map((a) => html`<button type="button" key=${a.key} class=${`btn btn-sm${a.primary ? " btn-primary" : ""}`} disabled=${busy} onClick=${() => { void a.run(); }}>${a.label}</button>`);
278
+ const how = fails.length ? html`<details class="uc-how"><summary>${tc("howTo")}</summary>${fails.map((f) => html`<p>${checkRich(f, c.version)}</p>`)}</details>` : null;
279
+ if (c.state === "offered") {
280
+ const sub = press ? [backSentence(info)] : [tc("pressOnlyLine"), how];
281
+ return html`<${Line} title=${tc("ready", c.version)} sub=${sub}>${buttons}</${Line}>`;
282
+ }
283
+ if (c.state === "waiting-idle") {
284
+ const names = Array.isArray(c.waitingFor) && c.waitingFor.length ? tc("waitingFor", namesShown(c.waitingFor)) : null;
285
+ return html`<${Line} spinner title=${tc("waiting", c.version)} sub=${[names]}>${buttons}</${Line}>`;
286
+ }
287
+ if (c.state === "scheduled") return html`<${Line} icon="clock" title=${tc("scheduled", c.version, fmtTime(c.scheduledAt))}>${buttons}</${Line}>`;
288
+ if (c.state === "updating" && !(info.progress && info.progress.stage)) return html`<${Line} spinner title=${tc("starting", c.version)} />`;
289
+ return null;
290
+ }
291
+
292
+ /** Settings → Version and update: the card's state, the pre-flight result, and the controls (two + Advanced). */
293
+ export function UpdateCardSettings({ info, deps }) {
294
+ noteCurrentVersion(info && info.current);
295
+ return html`<div class="uc-settings">
296
+ <${CardStatus} info=${info} deps=${deps} />
297
+ <${MachineLine} info=${info} />
298
+ <${UpdatesControls} />
299
+ </div>`;
300
+ }
301
+ function CardStatus({ info }) {
302
+ const c = info && info.card;
303
+ if (!c) return null;
304
+ const line = c.state === "not-now" && c.notNowUntil ? tc("notNowUntil", fmtTime(c.notNowUntil))
305
+ : c.state === "scheduled" && c.scheduledAt ? tc("scheduled", c.version, fmtTime(c.scheduledAt))
306
+ : c.state === "waiting-idle" ? [tc("waiting", c.version), Array.isArray(c.waitingFor) && c.waitingFor.length ? tc("waitingFor", namesShown(c.waitingFor)) : ""].filter(Boolean).join(" ")
307
+ : null;
308
+ return line ? html`<p class="uc-status" role="status">${line}</p>` : null;
309
+ }
310
+ /** "Updates on this machine": ✓ / ◐ / ✗, then each check that did not pass, worded, and the ones not run yet. */
311
+ export function MachineLine({ info }) {
312
+ const pf = info && info.preflight;
313
+ if (!pf) return html`<div class="uc-machine"><strong>${tc("machine")}</strong> <span class="muted">${tc("checking")}</span></div>`;
314
+ const cls = pf.class === "self" ? "self" : pf.class === "admin-only" ? "admin-only" : "stop";
315
+ const mark = cls === "self" ? "✓" : cls === "admin-only" ? "◐" : "✗";
316
+ const fails = failedChecks(pf);
317
+ return html`<div class=${`uc-machine uc-${cls}`}>
318
+ <div><strong>${tc("machine")}</strong> <span class="uc-mark" aria-hidden="true">${mark}</span> <span>${tc(cls === "self" ? "self" : cls === "admin-only" ? "adminOnly" : "stop")}</span></div>
319
+ ${fails.length ? html`<ul class="uc-checks">${fails.map((f) => html`<li key=${f.id}>${checkRich(f, info.card ? info.card.version : "")}</li>`)}</ul>`
320
+ : cls !== "self" ? html`<p class="muted uc-checks">${tc("notAllChecked")}</p>` : null}
321
+ </div>`;
322
+ }
323
+
324
+ /** The running version (the placeholder of the pin): read from GET /ui/update's answer, kept by app-update.js's store. */
325
+ let currentVersion = "";
326
+ export function noteCurrentVersion(v) { if (typeof v === "string") currentVersion = v; }
327
+ const updateCurrentVersion = () => currentVersion;
328
+
329
+ /** Half-hour choices, plus a saved value that isn't on the half hour (written by hand in fleet.yaml) so it is kept. */
330
+ const timeChoices = (current) => { const all = dayTimes(30); return current && !all.includes(current) ? [...all, current].sort() : all; };
331
+
332
+ /** The controls: when not to update (pause windows) and, under Advanced, the pin and the longest wait. PUT /api/settings/fleet/updates. */
333
+ export function UpdatesControls() {
334
+ const [cfg, setCfg] = useState(null);
335
+ const [pause, setPause] = useState([]);
336
+ const [pin, setPin] = useState("");
337
+ const [wait, setWait] = useState("24");
338
+ const [busy, setBusy] = useState(false);
339
+ useEffect(() => {
340
+ let alive = true;
341
+ (async () => {
342
+ try {
343
+ const r = await fetch("/api/settings/fleet", { cache: "no-store" });
344
+ const body = r.ok ? await r.json() : null;
345
+ const u = body && body.updates && typeof body.updates === "object" ? body.updates : {};
346
+ if (!alive) return;
347
+ setCfg(u); setPause(Array.isArray(u.pause) ? u.pause.map((w) => ({ days: [...(w.days || [])], from: w.from || "09:00", to: w.to || "18:00" })) : []);
348
+ setPin(typeof u.pin === "string" ? u.pin : ""); setWait(String(Number.isInteger(u.maxIdleWait) ? u.maxIdleWait : 24));
349
+ } catch { if (alive) setCfg({}); }
350
+ })();
351
+ return () => { alive = false; };
352
+ }, []);
353
+ if (!cfg) return null;
354
+ const dayNames = tc("days").split(",");
355
+ // #4487 review P1: a held settings change. What only holds updates back applies at once ("Saved."); what lets an update go
356
+ // ahead sooner waits for a confirmation (the pending card), and says so — never "Saved." before it is applied.
357
+ const save = async (patch) => {
358
+ setBusy(true);
359
+ let r = null, waiting = false;
360
+ try {
361
+ // Settings' own module, loaded here only (the banner, on every page, never needs it).
362
+ const { confirmedWrite } = await import("/ui/js/settings-confirm.js");
363
+ r = await confirmedWrite("/api/settings/fleet/updates", { method: "PUT", body: patch, label: tc("settingsLabel"), resendable: true,
364
+ onPending: () => { waiting = true; setBusy(false); toast(tc("pending")); } });
365
+ } catch { r = null; }
366
+ setBusy(false);
367
+ if (r && r.ok) { toast(tc(waiting ? "applied" : "saved")); return true; }
368
+ const out = r && r.body;
369
+ const why = out && Array.isArray(out.problems) && out.problems[0] ? `${out.problems[0].path}: ${out.problems[0].message}` : (out && out.error) || (r ? String(r.status) : "network");
370
+ toast(tc("saveFailed", why), false);
371
+ return false;
372
+ };
373
+ const setRow = (i, next) => setPause((rows) => rows.map((r, j) => (j === i ? { ...r, ...next } : r)));
374
+ const toggleDay = (i, d) => setRow(i, { days: pause[i].days.includes(d) ? pause[i].days.filter((x) => x !== d) : [...pause[i].days, d].sort() });
375
+ return html`<div class="uc-controls">
376
+ <fieldset class="uc-pause"><legend>${tc("pauseTitle")}</legend>
377
+ <p class="muted uc-hint">${tc("pauseHint")}</p>
378
+ ${pause.map((w, i) => html`<div class="uc-pause-row" key=${i}>
379
+ <div class="uc-days" role="group" aria-label=${tc("pauseTitle")}>${dayNames.map((n, d) => html`<label class="check uc-day"><input type="checkbox" checked=${w.days.includes(d)} onChange=${() => toggleDay(i, d)} /><span>${n}</span></label>`)}</div>
380
+ <label class="uc-time">${tc("from")} <select class="input" value=${w.from} onChange=${(e) => setRow(i, { from: e.currentTarget.value })}>${timeChoices(w.from).map((x) => html`<option value=${x}>${x}</option>`)}</select></label>
381
+ <label class="uc-time">${tc("to")} <select class="input" value=${w.to} onChange=${(e) => setRow(i, { to: e.currentTarget.value })}>${timeChoices(w.to).map((x) => html`<option value=${x}>${x}</option>`)}</select></label>
382
+ <button type="button" class="btn btn-sm" onClick=${() => setPause((rows) => rows.filter((_, j) => j !== i))}>${tc("pauseRemove")}</button>
383
+ </div>`)}
384
+ <div class="uc-row-actions">
385
+ <button type="button" class="btn btn-sm" onClick=${() => setPause((rows) => [...rows, { days: [1, 2, 3, 4, 5], from: "09:00", to: "18:00" }])}>${tc("pauseAdd")}</button>
386
+ <button type="button" class="btn btn-sm btn-primary" disabled=${busy} onClick=${() => { void save({ pause }); }}>${tc("save")}</button>
387
+ </div>
388
+ </fieldset>
389
+ <details class="s-ui-disclosure uc-advanced"><summary>${tc("advanced")}</summary><div class="s-disclosure-body">
390
+ <label class="field"><span>${tc("pin")}</span><input class="input" value=${pin} placeholder=${updateCurrentVersion() || ""} onInput=${(e) => setPin(e.currentTarget.value)} /><span class="muted uc-hint">${tc("pinHint")}</span></label>
391
+ <label class="field"><span>${tc("maxWait")}</span><input class="input" type="number" min="1" max="168" step="1" value=${wait} onInput=${(e) => setWait(e.currentTarget.value)} /><span class="muted uc-hint">${tc("maxWaitHint")}</span></label>
392
+ <div class="uc-row-actions"><button type="button" class="btn btn-sm btn-primary" disabled=${busy}
393
+ onClick=${() => { void save({ pin: pin.trim() ? pin.trim() : null, maxIdleWait: Number(wait) }); }}>${tc("save")}</button></div>
394
+ </div></details>
395
+ </div>`;
396
+ }
397
+
398
+ /** Needs you (§3.1: only a failure or "can't update here"): one item from the store, not counted in the server's badge. */
399
+ /** #4487 review P2: the one update item Needs you shows, counts and weighs for its empty state — "failed", "cant" (can't
400
+ * update here: the card says so, or the pre-flight is class stop; never while Not now), or null. */
401
+ export function updateAttention(info) {
402
+ const c = info && info.admin ? info.card : null;
403
+ if (!c) return null;
404
+ if (c.state === "failed") return "failed";
405
+ if ((c.state === "cant" || (info.preflight && info.preflight.class === "stop")) && c.state !== "not-now") return "cant";
406
+ return null;
407
+ }
408
+ export function UpdateNeedsItem({ info, settingsHref }) {
409
+ const kind = updateAttention(info);
410
+ if (!kind) return null;
411
+ const c = info.card, fails = failedChecks(info.preflight);
412
+ if (kind === "failed") return html`<section class="n-group uc-needs"><div class="n-item"><strong>${t("update.failed_" + ((c.failed && c.failed.cause) || "other"))}</strong>
413
+ <p class="muted">${c.failed && c.failed.rolledBack ? t("update.unchanged", info.current) : t("update.afterInstall")}</p>
414
+ <a class="btn btn-sm" href=${settingsHref}>${t("app.settings")}</a></div></section>`;
415
+ // Can't update here: the reason itself is the one line (the leader's copy pass), with the way to Settings.
416
+ const first = fails[0];
417
+ return html`<section class="n-group uc-needs"><div class="n-item"><strong>${first ? checkRich(first, c.version) : tc("cantTitle")}</strong>
418
+ <a class="btn btn-sm" href=${settingsHref}>${t("app.settings")}</a></div></section>`;
419
+ }
@@ -0,0 +1,26 @@
1
+ import { type FleetLockHandle } from "./fleet-lock.js";
2
+ import { type AttemptRecord, type JournalIo } from "./update-journal.js";
3
+ import { type RollbackDeps } from "./update-rollback.js";
4
+ export type UpdateResult = {
5
+ ok: true;
6
+ attempt: AttemptRecord;
7
+ }
8
+ /** Not committed. `abandoned` / `rolled-back`: the way back completed. `manual`: manual-recovery is journaled.
9
+ * `retry`: the attempt stays open (a later run — the recovery runner, through the route — resumes it). */
10
+ | {
11
+ ok: false;
12
+ outcome: "abandoned" | "rolled-back" | "manual" | "retry";
13
+ reason: string;
14
+ attempt: AttemptRecord;
15
+ };
16
+ export interface AbandonDeps extends Pick<RollbackDeps, "self" | "liveness" | "isProcessAlive" | "manager" | "waitTakeover" | "newNonce" | "io" | "plistArgs"> {
17
+ /** `hand-back`: the old fleet has taken the inbox and the deferred jobs back and acknowledged them (2.2). */
18
+ handBack(attempt: AttemptRecord): boolean;
19
+ }
20
+ /**
21
+ * §2.3 abandon: a procedure, not a label — `restart-old`, `hand-back`, `route-removed`, then `abandoned`. Allowed from
22
+ * opened, barrier and stopping (no snapshot published). `fence` is the fence's handle when the caller holds it.
23
+ */
24
+ export declare function abandonAttempt(home: string, attempt: AttemptRecord, d: AbandonDeps, reason: string, fence?: FleetLockHandle | null): UpdateResult;
25
+ /** manual-recovery journaled (it keeps `current` until a person resolves it). */
26
+ export declare function journalManual(home: string, attempt: AttemptRecord, reason: string, io: JournalIo): UpdateResult;
@@ -0,0 +1,111 @@
1
+ /**
2
+ * M-3770 slice 2.5 (design update-transaction §2.3, §4.3; rev 13): the recorded abandon procedure — for the live updater
3
+ * (`runUpdate`, before the snapshot is published) and for the recovery runner acting for a dead one. Bundled into
4
+ * recover.cjs: no snapshot, install or SQLite code, node built-ins only.
5
+ */
6
+ import { existsSync } from "node:fs";
7
+ import { createUpdateFence, readFleetLockRecord, releaseFleetLock, setFleetLockHandoff } from "./fleet-lock.js";
8
+ import { identityOf } from "./install-ownership.js";
9
+ import { ackGeneration, advance, defaultJournalIo, finish, substep } from "./update-journal.js";
10
+ import { removeRecoveryRoute, unitPreimagePath } from "./update-recovery/route.js";
11
+ import { ensureFence, startGeneration } from "./update-rollback.js";
12
+ const generationsOf = (a) => (Array.isArray(a.fleets) ? a.fleets : []);
13
+ const didSubstep = (a, stage, name) => a.history.some(h => h.stage === stage && h.substep === name);
14
+ /**
15
+ * §2.3 abandon: a procedure, not a label — `restart-old`, `hand-back`, `route-removed`, then `abandoned`. Allowed from
16
+ * opened, barrier and stopping (no snapshot published). `fence` is the fence's handle when the caller holds it.
17
+ */
18
+ export function abandonAttempt(home, attempt, d, reason, fence = null) {
19
+ const io = d.io ?? defaultJournalIo;
20
+ let a = attempt;
21
+ const fail = (why, isManual = true) => (isManual ? journalManual(home, a, why, io) : { ok: false, outcome: "retry", reason: why, attempt: a });
22
+ const id = identityOf(a);
23
+ if (!id)
24
+ return journalManual(home, a, "the attempt's recorded ownership is missing or malformed", io);
25
+ if (a.stage !== "abandoning")
26
+ a = advance(home, a, "abandoning", { note: reason }, io);
27
+ const done = (n) => didSubstep(a, "abandoning", n);
28
+ // The old fleet must RUN until the hand-back is acknowledged (Fable #4536 F1): checked on every pass, not only once.
29
+ // A recorded `restart-old` whose fleet has since died (a crash, a reboot before the acks) is journaled dead and a new
30
+ // `old` generation started from the re-taken fence.
31
+ if (!done("hand-back")) {
32
+ const holder = readFleetLockRecord(home);
33
+ const old = generationsOf(a).find(g => g.gen === "old");
34
+ if (holder?.role === "fleet" && d.isProcessAlive(holder.pid)) {
35
+ // A live fleet holds the lock: the old fleet never stopped (barrier, an early failure), or abandon's own restart.
36
+ const gen = generationsOf(a).find(g => g.nonce === holder.nonce && !g.dead);
37
+ if (!gen || gen.gen !== "old")
38
+ return fail(`fleet.lock's holder (pid ${holder.pid}) isn't the running old fleet`);
39
+ if (!gen.consumed)
40
+ a = startGeneration(home, a, "old", null, d).attempt; // its takeover landed before a crash
41
+ }
42
+ else if (holder) {
43
+ // This attempt's fence (the updater's, adopted when it is gone), or a recorded generation's record whose fleet died
44
+ // (the old fleet crashed before the updater stopped it, or after abandon restarted it): journaled dead and its
45
+ // record re-taken (`ensureFence`).
46
+ if (holder.role === "update" && holder.attemptId !== a.id)
47
+ return fail(`fleet.lock fences another attempt (${holder.attemptId})`);
48
+ let own = fence;
49
+ if (!own) {
50
+ const f = ensureFence(home, a, d);
51
+ a = f.attempt;
52
+ if (!f.ok)
53
+ return fail(`this attempt's fence can't be held to restart the old fleet: ${f.reason}`);
54
+ own = f.handle;
55
+ }
56
+ if (old) {
57
+ const started = startGeneration(home, a, "old", own, d);
58
+ a = started.attempt;
59
+ if (!started.ok)
60
+ return fail(`the old fleet didn't restart: ${started.reason}`, started.manual);
61
+ }
62
+ else {
63
+ // No fleet ran when the attempt opened: the fence is simply let go.
64
+ const clear = own.record.handoff ? setFleetLockHandoff(own, null, () => true) : own;
65
+ if (!clear || !releaseFleetLock(clear))
66
+ return fail("this attempt's fence couldn't be released");
67
+ }
68
+ }
69
+ else if (old) {
70
+ // No lock, an old fleet recorded: a clean exit of it unlinks fleet.lock (a host shutdown, `systemctl stop` while the
71
+ // hand-back waits — Fable #4536 F2). Proven gone, it is journaled dead and a new old generation started from a
72
+ // fence taken afresh. A live old fleet without the lock stays manual (as the forward driver's no-holder case).
73
+ const last = [...generationsOf(a)].reverse().find(g => g.gen === "old" && g.consumed && !g.dead);
74
+ if (last?.pid !== undefined) {
75
+ if (d.isProcessAlive(last.pid))
76
+ return fail(`the old fleet (pid ${last.pid}) runs without holding fleet.lock`);
77
+ a = ackGeneration(home, a, last.nonce, last.pid, { dead: true }, io);
78
+ }
79
+ // createUpdateFence, not acquireFleetLock: this runs inside recover.cjs (Fable #4536 F3).
80
+ const created = createUpdateFence(home, { pid: d.self.pid, attemptId: a.id });
81
+ if (!created.ok)
82
+ return fail(`fleet.lock can't be taken as this attempt's fence (${created.reason})`, false);
83
+ const started = startGeneration(home, a, "old", created.handle, d);
84
+ a = started.attempt;
85
+ if (!started.ok)
86
+ return fail(`the old fleet didn't restart: ${started.reason}`, started.manual);
87
+ }
88
+ if (!done("restart-old"))
89
+ a = substep(home, a, "restart-old", io);
90
+ if (!d.handBack(a))
91
+ return fail("the old fleet didn't take the held messages and jobs back; it resumes on the next start", false);
92
+ a = substep(home, a, "hand-back", io);
93
+ }
94
+ // Only a route that was written (its unit preimage kept first): an abandon at the barrier has none to take off.
95
+ if (id.ownership.service && !done("route-removed") && existsSync(unitPreimagePath(home, a.id))) {
96
+ const r = removeRecoveryRoute(home, a, { plistArgs: d.plistArgs }, io);
97
+ if (!r.ok)
98
+ return fail(r.reason);
99
+ if (!d.manager.reload())
100
+ return fail("the service manager couldn't reload after the route was taken off", false);
101
+ a = substep(home, a, "route-removed", io);
102
+ }
103
+ a = finish(home, a, { kind: "abandoned", reason }, io);
104
+ return { ok: false, outcome: "abandoned", reason, attempt: a };
105
+ }
106
+ /** manual-recovery journaled (it keeps `current` until a person resolves it). */
107
+ export function journalManual(home, attempt, reason, io) {
108
+ const a = finish(home, attempt, { kind: "manual-recovery", reason }, io);
109
+ return { ok: false, outcome: "manual", reason, attempt: a };
110
+ }
111
+ //# sourceMappingURL=update-abandon.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"update-abandon.js","sourceRoot":"","sources":["../src/update-abandon.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,mBAAmB,EAAwB,MAAM,iBAAiB,CAAC;AACtI,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,gBAAgB,EAAE,MAAM,EAAE,OAAO,EAA4D,MAAM,qBAAqB,CAAC;AAC1J,OAAO,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AACnF,OAAO,EAAE,WAAW,EAAE,eAAe,EAAqB,MAAM,sBAAsB,CAAC;AAavF,MAAM,aAAa,GAAG,CAAC,CAAgB,EAAqB,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAE,CAAC,CAAC,MAA4B,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;AAChI,MAAM,UAAU,GAAG,CAAC,CAAgB,EAAE,KAAa,EAAE,IAAY,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAA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,mBAAmB,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,EAAE,EAAE,EAAE,CAAC,CAAC;QACvE,IAAI,CAAC,CAAC,CAAC,EAAE;YAAE,OAAO,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;QACjC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE;YAAE,OAAO,IAAI,CAAC,mEAAmE,EAAE,KAAK,CAAC,CAAC;QACjH,CAAC,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,EAAE,eAAe,EAAE,EAAE,CAAC,CAAC;IAC5C,CAAC;IACD,CAAC,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC;IACvD,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;AACjE,CAAC;AAED,iFAAiF;AACjF,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,OAAsB,EAAE,MAAc,EAAE,EAAa;IAC/F,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,iBAAiB,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC;IACzE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;AAC9D,CAAC"}
@@ -1,7 +1,7 @@
1
- import { type FleetLockHandle } from "./fleet-lock.js";
2
1
  import { type Ownership, type Proven, type TupleRead } from "./install-ownership.js";
3
2
  import { type AttemptRecord, type Artifact } from "./update-journal.js";
4
3
  import { type KitSources } from "./update-recovery/kit.js";
4
+ import { type UpdateResult } from "./update-abandon.js";
5
5
  import { type RollbackDeps } from "./update-rollback.js";
6
6
  type Check = {
7
7
  ok: true;
@@ -35,23 +35,15 @@ export interface UpdateDeps extends RollbackDeps {
35
35
  commit: CommitHands;
36
36
  /** Abandon's `hand-back`: the old fleet takes the inbox and the deferred jobs back and acknowledges them (2.2). */
37
37
  handBack(attempt: AttemptRecord): boolean;
38
+ /** §5.7 Go back (rev 16): checked at snapshotted → installing, with the fresh snapshot taken; a refusal rolls back. */
39
+ beforeInstall?(attempt: AttemptRecord): Check;
38
40
  }
39
41
  export interface UpdatePlan {
40
42
  target: Artifact;
41
43
  command: string[];
42
44
  }
43
- export type UpdateResult = {
44
- ok: true;
45
- attempt: AttemptRecord;
46
- }
47
- /** Not committed. `abandoned` / `rolled-back`: the way back completed. `manual`: manual-recovery is journaled.
48
- * `retry`: the attempt stays open (a later run — the recovery runner, through the route — resumes it). */
49
- | {
50
- ok: false;
51
- outcome: "abandoned" | "rolled-back" | "manual" | "retry";
52
- reason: string;
53
- attempt: AttemptRecord;
54
- };
45
+ export type { UpdateResult } from "./update-abandon.js";
46
+ export { abandonAttempt } from "./update-abandon.js";
55
47
  /** Drive `attempt` (stage `opened`) forward. */
56
48
  export declare function runUpdate(home: string, attempt: AttemptRecord, plan: UpdatePlan, d: UpdateDeps): UpdateResult;
57
49
  /**
@@ -65,9 +57,3 @@ export declare function commitAttempt(home: string, attempt: AttemptRecord, d: P
65
57
  * holds the home lock and fleet.lock.
66
58
  */
67
59
  export declare function resumeCommitting(home: string, attemptId: string, d: Pick<UpdateDeps, "commit" | "manager" | "plistArgs" | "io">): UpdateResult | null;
68
- /**
69
- * §2.3 abandon: a procedure, not a label — `restart-old`, `hand-back`, `route-removed`, then `abandoned`. Allowed from
70
- * opened, barrier and stopping (no snapshot published). `fence` is the fence's handle when the caller holds it.
71
- */
72
- export declare function abandonAttempt(home: string, attempt: AttemptRecord, d: UpdateDeps, reason: string, fence?: FleetLockHandle | null): UpdateResult;
73
- export {};