@ddtcorex/dsh-maestro-core 0.10.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 (285) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +209 -0
  3. package/cordis.patch.yml +43 -0
  4. package/lib/bin.d.ts +2 -0
  5. package/lib/bin.js +3 -0
  6. package/lib/boot-guard.d.ts +33 -0
  7. package/lib/boot-guard.js +68 -0
  8. package/lib/boot-lock.d.ts +56 -0
  9. package/lib/boot-lock.js +155 -0
  10. package/lib/cli.d.ts +31 -0
  11. package/lib/cli.js +336 -0
  12. package/lib/client.js +2901 -0
  13. package/lib/config/index.d.ts +34 -0
  14. package/lib/config/index.js +62 -0
  15. package/lib/config/service.d.ts +18 -0
  16. package/lib/config/service.js +28 -0
  17. package/lib/config.d.ts +1 -0
  18. package/lib/config.js +19 -0
  19. package/lib/daemon-freshness.d.ts +48 -0
  20. package/lib/daemon-freshness.js +122 -0
  21. package/lib/debug-agent.d.ts +17 -0
  22. package/lib/debug-agent.js +144 -0
  23. package/lib/dsh-session.d.ts +26 -0
  24. package/lib/dsh-session.js +45 -0
  25. package/lib/guard/config.d.ts +82 -0
  26. package/lib/guard/config.js +211 -0
  27. package/lib/guard/decide.d.ts +30 -0
  28. package/lib/guard/decide.js +38 -0
  29. package/lib/guard/full-scan-tool.d.ts +6 -0
  30. package/lib/guard/full-scan-tool.js +65 -0
  31. package/lib/guard/index.d.ts +85 -0
  32. package/lib/guard/index.js +254 -0
  33. package/lib/guard/journal.d.ts +146 -0
  34. package/lib/guard/journal.js +398 -0
  35. package/lib/guard/migrate.d.ts +15 -0
  36. package/lib/guard/migrate.js +42 -0
  37. package/lib/guard/parse.d.ts +193 -0
  38. package/lib/guard/parse.js +1103 -0
  39. package/lib/guard/paths.d.ts +104 -0
  40. package/lib/guard/paths.js +254 -0
  41. package/lib/guard/permission-policy.d.ts +10 -0
  42. package/lib/guard/permission-policy.js +21 -0
  43. package/lib/guard/redact.d.ts +25 -0
  44. package/lib/guard/redact.js +52 -0
  45. package/lib/guard/rules.d.ts +65 -0
  46. package/lib/guard/rules.js +832 -0
  47. package/lib/guard/status-tool.d.ts +54 -0
  48. package/lib/guard/status-tool.js +195 -0
  49. package/lib/guard/tiers.d.ts +2 -0
  50. package/lib/guard/tiers.js +1 -0
  51. package/lib/guard/validators.d.ts +4 -0
  52. package/lib/guard/validators.js +45 -0
  53. package/lib/health-poller.d.ts +90 -0
  54. package/lib/health-poller.js +430 -0
  55. package/lib/index.d.ts +7 -0
  56. package/lib/index.js +7 -0
  57. package/lib/intents.d.ts +32 -0
  58. package/lib/intents.js +49 -0
  59. package/lib/notifier.d.ts +12 -0
  60. package/lib/notifier.js +62 -0
  61. package/lib/paths.d.ts +13 -0
  62. package/lib/paths.js +70 -0
  63. package/lib/plugin.d.ts +250 -0
  64. package/lib/plugin.js +1126 -0
  65. package/lib/preset.d.ts +73 -0
  66. package/lib/preset.js +158 -0
  67. package/lib/report.d.ts +11 -0
  68. package/lib/report.js +58 -0
  69. package/lib/restart-exec.d.ts +35 -0
  70. package/lib/restart-exec.js +60 -0
  71. package/lib/restart-guards.d.ts +39 -0
  72. package/lib/restart-guards.js +150 -0
  73. package/lib/restart-tool.d.ts +124 -0
  74. package/lib/restart-tool.js +539 -0
  75. package/lib/restart-web.d.ts +26 -0
  76. package/lib/restart-web.js +58 -0
  77. package/lib/resume-log.d.ts +24 -0
  78. package/lib/resume-log.js +18 -0
  79. package/lib/resume-tools.d.ts +131 -0
  80. package/lib/resume-tools.js +337 -0
  81. package/lib/resume.d.ts +33 -0
  82. package/lib/resume.js +221 -0
  83. package/lib/scan.d.ts +20 -0
  84. package/lib/scan.js +71 -0
  85. package/lib/self-kill-guard.d.ts +81 -0
  86. package/lib/self-kill-guard.js +208 -0
  87. package/lib/session-health.d.ts +89 -0
  88. package/lib/session-health.js +274 -0
  89. package/lib/session-log-file.d.ts +22 -0
  90. package/lib/session-log-file.js +74 -0
  91. package/lib/skill-provider.d.ts +6 -0
  92. package/lib/skill-provider.js +73 -0
  93. package/lib/snapshot.d.ts +59 -0
  94. package/lib/snapshot.js +358 -0
  95. package/lib/source.d.ts +19 -0
  96. package/lib/source.js +19 -0
  97. package/lib/store/index.d.ts +42 -0
  98. package/lib/store/index.js +340 -0
  99. package/lib/store/legacy.d.ts +17 -0
  100. package/lib/store/legacy.js +85 -0
  101. package/lib/supervisor.d.ts +119 -0
  102. package/lib/supervisor.js +741 -0
  103. package/lib/sync/backup-config.d.ts +55 -0
  104. package/lib/sync/backup-config.js +119 -0
  105. package/lib/sync/backup-service.d.ts +110 -0
  106. package/lib/sync/backup-service.js +440 -0
  107. package/lib/sync/bidirectional.d.ts +39 -0
  108. package/lib/sync/bidirectional.js +25 -0
  109. package/lib/sync/cli.d.ts +38 -0
  110. package/lib/sync/cli.js +536 -0
  111. package/lib/sync/config.d.ts +77 -0
  112. package/lib/sync/config.js +90 -0
  113. package/lib/sync/fingerprint.d.ts +29 -0
  114. package/lib/sync/fingerprint.js +65 -0
  115. package/lib/sync/hashing.d.ts +9 -0
  116. package/lib/sync/hashing.js +47 -0
  117. package/lib/sync/index.d.ts +6 -0
  118. package/lib/sync/index.js +634 -0
  119. package/lib/sync/machine-id.d.ts +29 -0
  120. package/lib/sync/machine-id.js +66 -0
  121. package/lib/sync/merge.d.ts +33 -0
  122. package/lib/sync/merge.js +88 -0
  123. package/lib/sync/peer-host.d.ts +22 -0
  124. package/lib/sync/peer-host.js +62 -0
  125. package/lib/sync/process-runner.d.ts +31 -0
  126. package/lib/sync/process-runner.js +161 -0
  127. package/lib/sync/remote-agent.d.ts +42 -0
  128. package/lib/sync/remote-agent.js +217 -0
  129. package/lib/sync/remote-cache.d.ts +18 -0
  130. package/lib/sync/remote-cache.js +60 -0
  131. package/lib/sync/remote-manifest.d.ts +8 -0
  132. package/lib/sync/remote-manifest.js +64 -0
  133. package/lib/sync/s3-object-store.d.ts +38 -0
  134. package/lib/sync/s3-object-store.js +126 -0
  135. package/lib/sync/session-merge.d.ts +18 -0
  136. package/lib/sync/session-merge.js +191 -0
  137. package/lib/sync/session-plan.d.ts +29 -0
  138. package/lib/sync/session-plan.js +213 -0
  139. package/lib/sync/sigv4.d.ts +20 -0
  140. package/lib/sync/sigv4.js +57 -0
  141. package/lib/sync/snapshot.d.ts +21 -0
  142. package/lib/sync/snapshot.js +176 -0
  143. package/lib/sync/ssh-mux.d.ts +12 -0
  144. package/lib/sync/ssh-mux.js +48 -0
  145. package/lib/sync/sync-plan.d.ts +24 -0
  146. package/lib/sync/sync-plan.js +366 -0
  147. package/lib/sync/sync-service.d.ts +177 -0
  148. package/lib/sync/sync-service.js +819 -0
  149. package/lib/sync/sync-types.d.ts +87 -0
  150. package/lib/sync/sync-types.js +1 -0
  151. package/lib/sync/transport.d.ts +75 -0
  152. package/lib/sync/transport.js +200 -0
  153. package/lib/sync/tunnel-restore.d.ts +77 -0
  154. package/lib/sync/tunnel-restore.js +142 -0
  155. package/lib/sync/validation.d.ts +10 -0
  156. package/lib/sync/validation.js +83 -0
  157. package/lib/tool-view.d.ts +62 -0
  158. package/lib/tool-view.js +70 -0
  159. package/lib/types/client/auto-reload.d.ts +8 -0
  160. package/lib/types/client/auto-reload.d.ts.map +1 -0
  161. package/lib/types/client/config/MaestroSettings.d.ts +25 -0
  162. package/lib/types/client/config/MaestroSettings.d.ts.map +1 -0
  163. package/lib/types/client/config/components/BrandMark.d.ts +50 -0
  164. package/lib/types/client/config/components/BrandMark.d.ts.map +1 -0
  165. package/lib/types/client/config/guard-view.d.ts +83 -0
  166. package/lib/types/client/config/guard-view.d.ts.map +1 -0
  167. package/lib/types/client/config/index.d.ts +20 -0
  168. package/lib/types/client/config/index.d.ts.map +1 -0
  169. package/lib/types/client/config/maestro-mark.d.ts +29 -0
  170. package/lib/types/client/config/maestro-mark.d.ts.map +1 -0
  171. package/lib/types/client/config/settings-nav-icon.d.ts +21 -0
  172. package/lib/types/client/config/settings-nav-icon.d.ts.map +1 -0
  173. package/lib/types/client/index.d.ts +16 -0
  174. package/lib/types/client/index.d.ts.map +1 -0
  175. package/lib/types/client/sync/R2SyncPanel.d.ts +6 -0
  176. package/lib/types/client/sync/R2SyncPanel.d.ts.map +1 -0
  177. package/lib/types/client/sync/SyncPanel.d.ts +12 -0
  178. package/lib/types/client/sync/SyncPanel.d.ts.map +1 -0
  179. package/lib/types/client/sync/confirm-dialog.d.ts +43 -0
  180. package/lib/types/client/sync/confirm-dialog.d.ts.map +1 -0
  181. package/lib/types/client/sync/index.d.ts +10 -0
  182. package/lib/types/client/sync/index.d.ts.map +1 -0
  183. package/lib/types/client/sync/ui.d.ts +79 -0
  184. package/lib/types/client/sync/ui.d.ts.map +1 -0
  185. package/lib/types/client/sync/use-backup.d.ts +50 -0
  186. package/lib/types/client/sync/use-backup.d.ts.map +1 -0
  187. package/lib/types/client/sync/use-sync.d.ts +88 -0
  188. package/lib/types/client/sync/use-sync.d.ts.map +1 -0
  189. package/package.json +89 -0
  190. package/skills/dsh-safe-restart/SKILL.md +206 -0
  191. package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +468 -0
  192. package/src/client/auto-reload.ts +104 -0
  193. package/src/client/config/MaestroSettings.tsx +892 -0
  194. package/src/client/config/components/BrandMark.tsx +94 -0
  195. package/src/client/config/guard-view.ts +187 -0
  196. package/src/client/config/index.tsx +109 -0
  197. package/src/client/config/maestro-mark.ts +37 -0
  198. package/src/client/config/settings-nav-icon.ts +68 -0
  199. package/src/client/index.tsx +33 -0
  200. package/src/client/sync/R2SyncPanel.tsx +260 -0
  201. package/src/client/sync/SyncPanel.tsx +422 -0
  202. package/src/client/sync/confirm-dialog.tsx +202 -0
  203. package/src/client/sync/index.tsx +336 -0
  204. package/src/client/sync/ui.tsx +313 -0
  205. package/src/client/sync/use-backup.ts +207 -0
  206. package/src/client/sync/use-sync.ts +502 -0
  207. package/src/host/bin.ts +3 -0
  208. package/src/host/boot-guard.ts +76 -0
  209. package/src/host/boot-lock.ts +155 -0
  210. package/src/host/cli.ts +288 -0
  211. package/src/host/config/index.ts +78 -0
  212. package/src/host/config/service.ts +40 -0
  213. package/src/host/config.ts +18 -0
  214. package/src/host/daemon-freshness.ts +143 -0
  215. package/src/host/debug-agent.ts +145 -0
  216. package/src/host/dsh-session.ts +56 -0
  217. package/src/host/dsh-skill.d.ts +44 -0
  218. package/src/host/guard/augment.d.ts +33 -0
  219. package/src/host/guard/config.ts +244 -0
  220. package/src/host/guard/decide.ts +40 -0
  221. package/src/host/guard/full-scan-tool.ts +61 -0
  222. package/src/host/guard/index.ts +281 -0
  223. package/src/host/guard/journal.ts +440 -0
  224. package/src/host/guard/migrate.ts +41 -0
  225. package/src/host/guard/parse.ts +1150 -0
  226. package/src/host/guard/paths.ts +239 -0
  227. package/src/host/guard/permission-policy.ts +15 -0
  228. package/src/host/guard/redact.ts +64 -0
  229. package/src/host/guard/rules.ts +891 -0
  230. package/src/host/guard/status-tool.ts +229 -0
  231. package/src/host/guard/tiers.ts +2 -0
  232. package/src/host/guard/validators.ts +29 -0
  233. package/src/host/health-poller.ts +446 -0
  234. package/src/host/index.ts +7 -0
  235. package/src/host/intents.ts +67 -0
  236. package/src/host/notifier.ts +71 -0
  237. package/src/host/paths.ts +70 -0
  238. package/src/host/plugin.ts +1097 -0
  239. package/src/host/preset.ts +170 -0
  240. package/src/host/report.ts +71 -0
  241. package/src/host/restart-exec.ts +81 -0
  242. package/src/host/restart-guards.ts +150 -0
  243. package/src/host/restart-tool.ts +483 -0
  244. package/src/host/restart-web.ts +72 -0
  245. package/src/host/resume-log.ts +39 -0
  246. package/src/host/resume-tools.ts +385 -0
  247. package/src/host/resume.ts +204 -0
  248. package/src/host/scan.ts +61 -0
  249. package/src/host/self-kill-guard.ts +216 -0
  250. package/src/host/session-health.ts +236 -0
  251. package/src/host/session-log-file.ts +77 -0
  252. package/src/host/skill-provider.ts +69 -0
  253. package/src/host/snapshot.ts +337 -0
  254. package/src/host/source.ts +19 -0
  255. package/src/host/store/index.ts +348 -0
  256. package/src/host/store/legacy.ts +96 -0
  257. package/src/host/supervisor.ts +720 -0
  258. package/src/host/sync/backup-config.ts +159 -0
  259. package/src/host/sync/backup-service.ts +453 -0
  260. package/src/host/sync/bidirectional.ts +66 -0
  261. package/src/host/sync/cli.ts +539 -0
  262. package/src/host/sync/config.ts +119 -0
  263. package/src/host/sync/fingerprint.ts +83 -0
  264. package/src/host/sync/hashing.ts +58 -0
  265. package/src/host/sync/index.ts +737 -0
  266. package/src/host/sync/machine-id.ts +81 -0
  267. package/src/host/sync/merge.ts +102 -0
  268. package/src/host/sync/peer-host.ts +65 -0
  269. package/src/host/sync/process-runner.ts +177 -0
  270. package/src/host/sync/remote-agent.ts +213 -0
  271. package/src/host/sync/remote-cache.ts +68 -0
  272. package/src/host/sync/remote-manifest.ts +70 -0
  273. package/src/host/sync/s3-object-store.ts +144 -0
  274. package/src/host/sync/session-merge.ts +220 -0
  275. package/src/host/sync/session-plan.ts +237 -0
  276. package/src/host/sync/sigv4.ts +81 -0
  277. package/src/host/sync/snapshot.ts +162 -0
  278. package/src/host/sync/ssh-mux.ts +56 -0
  279. package/src/host/sync/sync-plan.ts +366 -0
  280. package/src/host/sync/sync-service.ts +855 -0
  281. package/src/host/sync/sync-types.ts +102 -0
  282. package/src/host/sync/transport.ts +261 -0
  283. package/src/host/sync/tunnel-restore.ts +160 -0
  284. package/src/host/sync/validation.ts +91 -0
  285. package/src/host/tool-view.ts +98 -0
@@ -0,0 +1,720 @@
1
+ import { classifyFetchFailure, type HealthState } from './health-poller.js'
2
+ import { runDebugAgent } from './debug-agent.js'
3
+ import { findInterrupted as defaultFindInterrupted, parseDuration } from './resume.js'
4
+ import * as fs from 'node:fs'
5
+ import * as path from 'node:path'
6
+ import * as os from 'node:os'
7
+ import { resolveHarnessRoot } from './paths.js'
8
+ import { readSupervisorConfig } from './config.js'
9
+ import { writePlannedRestart as defaultWritePlannedRestart, checkPlannedRestart as defaultCheckPlannedRestart, clearPlannedRestart } from './restart-guards.js'
10
+ import type { RestartRequest } from './restart-guards.js'
11
+ import { writeRestartOutcome as defaultWriteOutcome, type RestartOutcome } from './intents.js'
12
+ import { execFileSync } from 'node:child_process'
13
+ import { mintDshSessionCookie, type MintCookieOpts } from './dsh-session.js'
14
+
15
+ /** Partial-restore report a rollback may hand back (cli.ts wires RestoreResult). */
16
+ export interface RollbackSummary {
17
+ target?: string
18
+ restored?: number
19
+ skipped?: Array<{ path: string; reason: string }>
20
+ }
21
+
22
+ export interface SupervisorDeps {
23
+ pollHealth: () => Promise<HealthState>
24
+ writeLKG: () => Promise<{ ts: string; manifest?: any }>
25
+ writeFailed: () => Promise<{ ts: string; manifest?: any }>
26
+ writeReport: (opts: { ts: string; health: HealthState; action: string; logTail?: string; gitDiff?: string }) => Promise<string>
27
+ rollback: (ts?: string) => Promise<RollbackSummary | void>
28
+ restartWeb?: () => Promise<void>
29
+ notify: (msg: string) => Promise<void>
30
+ intervalMs?: number
31
+ debounceMs?: number
32
+ // Number of consecutive "down" polls required before a crash is confirmed
33
+ // and rollback/restart fires. A single transient poll failure (e.g. a
34
+ // fetch timeout while the plugin tree is still booting) must not trigger
35
+ // a full rollback — that restart itself produces transient errors on the
36
+ // next poll, which would otherwise re-trigger endlessly. Default 3 (at the
37
+ // daemon's 3s interval, ~9s of continuous down before acting).
38
+ downThreshold?: number
39
+ // Boot budget in ms (default 180_000). A boot younger than this that has not
40
+ // printed its own success marker is unproven: weak failures and degraded
41
+ // verdicts must not advance the counters (incident 2026-09-13).
42
+ bootGraceMs?: number
43
+ getTime?: () => number
44
+ // Checks the dsh-safe-web-update marker (see
45
+ // docs/specs/2026-08-28-supervisor-planned-restart-design.md): a down poll
46
+ // while this resolves true is an intentional restart in progress, not a
47
+ // crash — skip rollback/restartWeb entirely rather than racing it.
48
+ isPlannedRestartActive?: () => boolean | Promise<boolean>
49
+ // 30s planned-restart marker (restart-guards.ts): single owner for restart
50
+ // decisions. Injected for tests so tick/restartWeb can be verified without
51
+ // touching the filesystem.
52
+ writePlannedRestart?: (ttlMs?: number) => void
53
+ checkPlannedRestart?: () => boolean
54
+ // Clears the restart-request/planned-restart marker; injectable for tests so
55
+ // the re-arm decision after a self-restart can be verified without fs.
56
+ clearPlannedRestart?: () => void
57
+ // injectable for test / LLM wiring
58
+ runDebugAgent?: (opts: { reportPath: string; health: HealthState }) => Promise<{ fixed: boolean; reason: string }>
59
+ findInterrupted?: () => Promise<{ scanned: number; interrupted: string[] }>
60
+ resumeSessions?: (ids: string[]) => Promise<{ resumed: string[] }>
61
+ // dsh_web_restart hand-off (restart-tool.ts): the daemon is the restart
62
+ // owner. Reads the caller marker and, after a ~5s grace, restarts dsh web
63
+ // once (single-flight per marker), notifies, then clears the marker.
64
+ readRestartRequest?: () => RestartRequest | undefined
65
+ onRestartRequestHandled?: (req: RestartRequest) => void
66
+ // Outcome sink for supervised restarts (intents.ts sidecar); injectable so
67
+ // tick() tests never touch the real ~/.dsh.
68
+ writeOutcome?: (sessionId: string, outcome: RestartOutcome) => void
69
+ // PID of the process listening on a port (ss parse); injectable for tests.
70
+ listenerPid?: (port: number) => number | undefined
71
+ }
72
+
73
+ /** PID holding a 127.0.0.1 listener on the port, or undefined. Never throws. */
74
+ export function defaultListenerPid(port: number): number | undefined {
75
+ try {
76
+ const out = execFileSync('ss', ['-tlnp'], { encoding: 'utf8' })
77
+ for (const line of out.split('\n')) {
78
+ const m = new RegExp(`127\\.0\\.0\\.1:${port}\\s[^]*?pid=(\\d+)`).exec(line)
79
+ if (m) return Number(m[1])
80
+ }
81
+ } catch {}
82
+ return undefined
83
+ }
84
+
85
+ export async function resumeViaRpc(
86
+ ids: string[],
87
+ fetchFn: (url: string, init: RequestInit) => Promise<Response> = globalThis.fetch,
88
+ extraHeaders: Record<string, string> = {},
89
+ ): Promise<{ resumed: string[] }> {
90
+ const rpcId = crypto.randomUUID()
91
+ const response = await fetchFn('http://127.0.0.1:3080/dsh-maestro-supervisor-resume/resume', {
92
+ method: 'POST',
93
+ headers: { 'content-type': 'application/json', ...extraHeaders },
94
+ body: JSON.stringify({ type: 'client-request', rpcId, method: 'resume', payload: { ids } }),
95
+ })
96
+ if (!response.ok) throw new Error(`resume RPC returned HTTP ${response.status}`)
97
+
98
+ const envelope = await response.json() as any
99
+ const resumed = envelope?.type === 'server-response'
100
+ && envelope?.rpcId === rpcId
101
+ && envelope?.result?.ok === true
102
+ && Array.isArray(envelope?.result?.value?.resumed)
103
+ ? envelope.result.value.resumed.filter((id: unknown): id is string => typeof id === 'string')
104
+ : undefined
105
+ if (resumed === undefined) throw new Error('resume RPC returned an invalid result')
106
+ return { resumed }
107
+ }
108
+
109
+ /**
110
+ * Daemon default resume path: mint the `dsh-auth-*` session cookie first (the
111
+ * `/resume` RPC sits behind the raw webserver's browser-trust fence, which 401s
112
+ * cookie-less loopback calls since the local-pin-gate topology moved the
113
+ * webserver behind the PIN proxies) and attach it to the POST. Falls back to an
114
+ * unauthenticated POST when no boot token is readable — old behavior preserved.
115
+ */
116
+ export async function resumeViaRpcWithSession(
117
+ ids: string[],
118
+ fetchFn: (url: string, init: RequestInit) => Promise<Response> = globalThis.fetch,
119
+ opts: MintCookieOpts = {},
120
+ ): Promise<{ resumed: string[] }> {
121
+ let cookie: string | undefined
122
+ try { cookie = await mintDshSessionCookie(fetchFn, opts) } catch { cookie = undefined }
123
+ return resumeViaRpc(ids, fetchFn, cookie === undefined ? {} : { cookie })
124
+ }
125
+
126
+ export class Supervisor {
127
+ private deps: SupervisorDeps
128
+ private lastRollback = 0
129
+ private rollingBack = false
130
+ private lastLKGWrite = 0
131
+ private lastDegradedNotify = 0
132
+ private consecutiveDown = 0
133
+ private consecutiveDegraded = 0
134
+ private timer: ReturnType<typeof setInterval> | null = null
135
+ private restartRequestHandled = false
136
+ private restartRequestTimer: ReturnType<typeof setTimeout> | null = null
137
+ private awaitingHealthyBoot = false
138
+ private pendingRestartRequest: RestartRequest | undefined
139
+
140
+ constructor(deps: SupervisorDeps) {
141
+ this.deps = deps
142
+ }
143
+
144
+ private getWritePlannedRestart(): (ttlMs?: number) => void {
145
+ return this.deps.writePlannedRestart ?? defaultWritePlannedRestart
146
+ }
147
+
148
+ private getCheckPlannedRestart(): () => boolean {
149
+ return this.deps.checkPlannedRestart ?? defaultCheckPlannedRestart
150
+ }
151
+
152
+ private getClearPlannedRestart(): () => void {
153
+ return this.deps.clearPlannedRestart ?? clearPlannedRestart
154
+ }
155
+
156
+ async restartWeb(): Promise<void> {
157
+ const grace = await this.getEffectiveBootGraceMs()
158
+ // Marker first, and its TTL is the boot budget — not 30 s. The observed
159
+ // boot took 1m52s: after +30 s every poll was judged as a crash, which is
160
+ // exactly how the 2026-09-13 rollback report was produced (D5).
161
+ this.getWritePlannedRestart()(grace)
162
+ if (this.deps.restartWeb) {
163
+ // Injected implementation (cli.ts daemon wiring, tests): it owns the
164
+ // boot lock, so the single-flight guarantee stays in one place.
165
+ await this.deps.restartWeb()
166
+ return
167
+ }
168
+ const { performSingleBootRestart } = await import('./restart-web.js')
169
+ const res = await performSingleBootRestart({ bootGraceMs: grace })
170
+ if (!res.restarted) {
171
+ await this.deps.notify(`restart skipped: ${res.reason ?? 'boot lock held'}`).catch(() => {})
172
+ }
173
+ }
174
+
175
+ private getRunDebugAgent() {
176
+ return this.deps.runDebugAgent ?? runDebugAgent
177
+ }
178
+
179
+ private getFindInterrupted() {
180
+ return this.deps.findInterrupted ?? defaultFindInterrupted
181
+ }
182
+
183
+ private getResumeSessions() {
184
+ return this.deps.resumeSessions ?? resumeViaRpcWithSession
185
+ }
186
+
187
+ private getAutoResumeEnabled(): boolean {
188
+ // Priority: env > supervisor config.json > maestro settings.json > default true (enabled)
189
+ // Configures whether interrupted sessions are auto-resumed after restart (vs only notify).
190
+ // For Settings UI: boolean toggle — true = auto-resume within window, false = notify only.
191
+ const env = process.env.DSH_SUPERVISOR_AUTO_RESUME
192
+ if (env !== undefined) {
193
+ const v = env.trim().toLowerCase()
194
+ if (['1','true','yes','on','enabled'].includes(v)) return true
195
+ if (['0','false','no','off','disabled'].includes(v)) return false
196
+ }
197
+ try {
198
+ const cfgPath = path.join(os.homedir(), '.dsh/.supervisor/config.json')
199
+ if (fs.existsSync(cfgPath)) {
200
+ const cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf-8'))
201
+ const raw = (cfg as any).autoResumeEnabled ?? (cfg as any).autoResume
202
+ if (typeof raw === 'boolean') return raw
203
+ if (typeof raw === 'string') {
204
+ const v = raw.trim().toLowerCase()
205
+ if (['1','true','yes','on'].includes(v)) return true
206
+ if (['0','false','no','off'].includes(v)) return false
207
+ }
208
+ }
209
+ const maestroPath = path.join(os.homedir(), '.dsh/maestro/settings.json')
210
+ if (fs.existsSync(maestroPath)) {
211
+ const j = JSON.parse(fs.readFileSync(maestroPath, 'utf-8'))
212
+ const raw = j?.domains?.supervisor?.autoResumeEnabled ?? j?.supervisor?.autoResumeEnabled ?? j?.domains?.supervisor?.autoResume ?? j?.supervisor?.autoResume
213
+ if (typeof raw === 'boolean') return raw
214
+ if (typeof raw === 'string') {
215
+ const v = raw.trim().toLowerCase()
216
+ if (['1','true','yes','on'].includes(v)) return true
217
+ if (['0','false','no','off'].includes(v)) return false
218
+ }
219
+ }
220
+ } catch {}
221
+ return true // default enabled
222
+ }
223
+
224
+ private getResumeWithinMs(): number {
225
+ // Priority: env > supervisor config.json > maestro settings.json > default 5 (minutes)
226
+ // Note: config value is in MINUTES (number 5 = 5 minutes). String "5m"/"30s"/"1h" also supported via parseDuration.
227
+ const env = process.env.DSH_SUPERVISOR_RESUME_WITHIN
228
+ if (env) {
229
+ // Bare number in env like "5" → treat as minutes for ergonomics
230
+ if (/^\d+$/.test(env.trim())) {
231
+ const n = parseInt(env.trim(), 10)
232
+ if (!isNaN(n)) return n * 60 * 1000
233
+ }
234
+ const v = parseDuration(env)
235
+ if (v !== undefined) return v
236
+ const n = parseInt(env, 10)
237
+ if (!isNaN(n)) return n
238
+ }
239
+ try {
240
+ const cfgPath = path.join(os.homedir(), '.dsh/.supervisor/config.json')
241
+ if (fs.existsSync(cfgPath)) {
242
+ const cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf-8'))
243
+ const raw = (cfg as any).autoResumeWithin ?? (cfg as any).resumeWithin
244
+ if (typeof raw === 'string') {
245
+ if (/^\d+$/.test(raw.trim())) return parseInt(raw.trim(), 10) * 60 * 1000 // bare string digits → minutes
246
+ const v = parseDuration(raw)
247
+ if (v !== undefined) return v
248
+ } else if (typeof raw === 'number') return raw * 60 * 1000 // number is MINUTES
249
+ }
250
+ const maestroPath = path.join(os.homedir(), '.dsh/maestro/settings.json')
251
+ if (fs.existsSync(maestroPath)) {
252
+ const j = JSON.parse(fs.readFileSync(maestroPath, 'utf-8'))
253
+ const raw = j?.domains?.supervisor?.autoResumeWithin ?? j?.supervisor?.autoResumeWithin
254
+ if (typeof raw === 'string') {
255
+ if (/^\d+$/.test(raw.trim())) return parseInt(raw.trim(), 10) * 60 * 1000
256
+ const v = parseDuration(raw)
257
+ if (v !== undefined) return v
258
+ } else if (typeof raw === 'number') return raw * 60 * 1000
259
+ }
260
+ } catch {}
261
+ return 5 * 60 * 1000 // default 5 minutes
262
+ }
263
+
264
+ private async getEffectiveIntervalMs(): Promise<number> {
265
+ if (this.deps.intervalMs !== undefined) return this.deps.intervalMs
266
+ try {
267
+ const cfg = await readSupervisorConfig()
268
+ if (typeof (cfg as any).intervalMs === 'number' && (cfg as any).intervalMs > 0) return (cfg as any).intervalMs
269
+ } catch {}
270
+ return 5000
271
+ }
272
+
273
+ private async getEffectiveDownThreshold(): Promise<number> {
274
+ if (this.deps.downThreshold !== undefined) return this.deps.downThreshold
275
+ try {
276
+ const cfg = await readSupervisorConfig()
277
+ if (typeof (cfg as any).downThreshold === 'number' && (cfg as any).downThreshold > 0) return (cfg as any).downThreshold
278
+ } catch {}
279
+ return 6
280
+ }
281
+
282
+ private async getEffectiveDegradedThreshold(): Promise<number> {
283
+ try {
284
+ const cfg = await readSupervisorConfig()
285
+ if (typeof (cfg as any).degradedThreshold === 'number' && (cfg as any).degradedThreshold > 0) return (cfg as any).degradedThreshold
286
+ } catch {}
287
+ return 5
288
+ }
289
+
290
+ private async getEffectivePollTimeoutMs(): Promise<number> {
291
+ try {
292
+ const cfg = await readSupervisorConfig()
293
+ if (typeof (cfg as any).pollTimeoutMs === 'number' && (cfg as any).pollTimeoutMs > 0) return (cfg as any).pollTimeoutMs
294
+ } catch {}
295
+ return 20000
296
+ }
297
+
298
+ private async getEffectiveBootGraceMs(): Promise<number> {
299
+ if (this.deps.bootGraceMs !== undefined) return this.deps.bootGraceMs
300
+ try {
301
+ const cfg = await readSupervisorConfig()
302
+ if (typeof (cfg as any).bootGraceMs === 'number' && (cfg as any).bootGraceMs > 0) return (cfg as any).bootGraceMs
303
+ } catch {}
304
+ return 180_000
305
+ }
306
+
307
+ private async findInterruptedRecent(withinMs?: number): Promise<{ scanned: number; interrupted: string[] }> {
308
+ const ms = withinMs ?? this.getResumeWithinMs()
309
+ // Prefer injected mock for testability
310
+ if (this.deps.findInterrupted) {
311
+ try {
312
+ const res = await this.deps.findInterrupted()
313
+ // If mock doesn't filter by time, we still return as-is (test expects all)
314
+ // For real filtering when mock is not time-aware, try to filter via resume module if possible
315
+ if (ms !== undefined && res.interrupted.length) {
316
+ try {
317
+ const { findInterrupted } = await import('./resume.js')
318
+ // Re-query with time filter for real filesystem; if mock was used for test, keep mock result
319
+ if (process.env.VITEST) return res
320
+ return findInterrupted(undefined, { withinMs: ms })
321
+ } catch {}
322
+ }
323
+ return res
324
+ } catch {
325
+ // fallback to real
326
+ }
327
+ }
328
+ try {
329
+ const { findInterrupted } = await import('./resume.js')
330
+ return findInterrupted(undefined, { withinMs: ms })
331
+ } catch {
332
+ return this.getFindInterrupted()()
333
+ }
334
+ }
335
+
336
+ private async collectGitDiff(): Promise<string> {
337
+ try {
338
+ const { execSync } = await import('node:child_process')
339
+ const ws = resolveHarnessRoot()
340
+ try {
341
+ const out = execSync(`git -C ${JSON.stringify(ws)} status --porcelain 2>/dev/null | head -n 50`, { encoding: 'utf-8', timeout: 2000 })
342
+ if (out.trim()) {
343
+ const diff = execSync(`git -C ${JSON.stringify(ws)} diff 2>/dev/null | head -n 200`, { encoding: 'utf-8', timeout: 2000 })
344
+ return diff || out
345
+ }
346
+ } catch {}
347
+ const diff = execSync('git diff 2>/dev/null | head -n 200', { encoding: 'utf-8', timeout: 2000 })
348
+ return diff.trim() ? diff : ''
349
+ } catch {
350
+ return ''
351
+ }
352
+ }
353
+
354
+ private async attemptAutoResume(ids: string[]): Promise<void> {
355
+ if (!ids.length) return
356
+ if (!this.getAutoResumeEnabled()) {
357
+ await this.deps.notify(`RESUME: ${ids.length} interrupted sessions (${ids.slice(0, 3).join(', ')}) — auto-resume disabled`).catch(() => {})
358
+ return
359
+ }
360
+ try {
361
+ const { resumed } = await this.getResumeSessions()(ids)
362
+ if (!resumed.length) {
363
+ await this.deps.notify(`RESUME SKIPPED: no interrupted sessions could be re-attached (${ids.slice(0, 3).join(', ')})`).catch(() => {})
364
+ return
365
+ }
366
+ await this.deps.notify(`RESUME: ${resumed.length} interrupted sessions — continue triggered (${resumed.slice(0, 3).join(', ')})`).catch(() => {})
367
+ } catch (e: any) {
368
+ await this.deps.notify(`RESUME FAILED: ${ids.length} interrupted sessions (${ids.slice(0, 3).join(', ')}) — ${e?.message ?? String(e)}`).catch(() => {})
369
+ }
370
+ }
371
+
372
+ /**
373
+ * D4: a restore that could not put every entry back must be surfaced loudly.
374
+ * Without this, a half-restored tree reads exactly like a clean recovery in
375
+ * the log and in the operator's Telegram feed.
376
+ */
377
+ private async reportRollbackResult(summary: RollbackSummary | void, reportPath: string): Promise<void> {
378
+ if (!summary || !summary.skipped?.length) return
379
+ const first = summary.skipped.slice(0, 3).map(s => `${s.path} (${s.reason})`).join('; ')
380
+ await this.deps.notify(
381
+ `ROLLBACK PARTIAL: ${summary.restored ?? 0} restored, ${summary.skipped.length} skipped — ${first} (report: ${reportPath})`,
382
+ ).catch(() => {})
383
+ }
384
+
385
+ private handleDebugResult(reportPath: string, res: { fixed: boolean; reason: string }): void {
386
+ if (res.fixed) {
387
+ void this.deps.notify(`FIXED: debug-agent fixed ${reportPath} — ${res.reason}`).catch(() => {})
388
+ // After fix, try to resume interrupted sessions (only recent, default 5 from config, in minutes)
389
+ void this.findInterruptedRecent().then(r => {
390
+ if (r.interrupted.length) void this.attemptAutoResume(r.interrupted).catch(() => {})
391
+ }).catch(() => {})
392
+ } else if (res.reason.includes('max attempts')) {
393
+ void this.deps.notify(`FIX FAILED after 3 attempts — needs human (report: ${reportPath}, reason: ${res.reason})`).catch(() => {})
394
+ } else if (res.reason.includes('cooldown')) {
395
+ // silent — cooldown, no notify
396
+ } else {
397
+ // non-fixed but not max attempts — still surface for visibility
398
+ void this.deps.notify(`FIX FAILED: ${res.reason} (report: ${reportPath})`).catch(() => {})
399
+ }
400
+ }
401
+
402
+ async tick(): Promise<void> {
403
+ const health = await this.deps.pollHealth()
404
+
405
+ // dsh_web_restart hand-off: the tool wrote a caller marker and handed the
406
+ // restart to the daemon (out-of-band). Honor one request per marker — one
407
+ // grace timer → restartWeb once → notify. The suppression marker and the
408
+ // single-flight latch are held until a post-restart health.up tick clears
409
+ // them, so the in-flight down of our own restart can never be mistaken for
410
+ // a crash and raced with a rollback + second restart by the crash path.
411
+ const restartReq = this.deps.readRestartRequest ? this.deps.readRestartRequest() : undefined
412
+ if (restartReq?.callerSessionId && !this.restartRequestHandled) {
413
+ this.restartRequestHandled = true
414
+ this.restartRequestTimer = setTimeout(() => {
415
+ void (async () => {
416
+ try {
417
+ // Debounce crash handling from the moment the restart is issued —
418
+ // the crash path sets lastRollback the same way. A slow boot must
419
+ // not be classified as a crash even after the suppression marker's
420
+ // own 30s TTL runs out.
421
+ this.lastRollback = this.deps.getTime ? this.deps.getTime() : Date.now()
422
+ await this.restartWeb()
423
+ // restartWeb() already wrote the marker with the boot budget as its
424
+ // TTL; the marker is cleared on the first healthy poll instead.
425
+ await this.deps.notify(`restarted dsh-web after self-restart by session ${restartReq.callerSessionId}`)
426
+ } catch (e: any) {
427
+ await this.deps.notify(`self-restart dsh-web failed: ${e?.message ?? String(e)}`).catch(() => {})
428
+ if (restartReq.callerSessionId) {
429
+ try {
430
+ ;(this.deps.writeOutcome ?? defaultWriteOutcome)(restartReq.callerSessionId, {
431
+ state: 'failed',
432
+ oldPid: restartReq.oldPid,
433
+ swappedAt: this.deps.getTime ? this.deps.getTime() : Date.now(),
434
+ error: e?.message ?? String(e),
435
+ })
436
+ } catch {}
437
+ }
438
+ } finally {
439
+ // Hold the marker and latch until health.up: clearing here would
440
+ // drop crash suppression mid-restart, and re-arming here would let
441
+ // a still-present marker re-fire into a second restart.
442
+ this.awaitingHealthyBoot = true
443
+ this.pendingRestartRequest = restartReq
444
+ this.restartRequestTimer = null
445
+ }
446
+ })()
447
+ }, 5000)
448
+ return
449
+ }
450
+
451
+ // DEGRADED: http 200 but log has plugin error → report + notify, rollback after consecutive threshold
452
+ if (health.degraded) {
453
+ this.consecutiveDown = 0
454
+ // D1: a degraded verdict while the current boot is unproven is a boot
455
+ // transient, not a plugin error — the incident's report line
456
+ // "rollback — degraded: This operation was aborted" was produced exactly
457
+ // here, five polls after a slow boot.
458
+ if (health.bootPhase === 'booting') {
459
+ this.consecutiveDegraded = 0
460
+ return
461
+ }
462
+ // Check suppression first — don't count degraded during planned restart grace
463
+ let suppressedByMarkerDeg = false
464
+ try { suppressedByMarkerDeg = this.getCheckPlannedRestart()() } catch { suppressedByMarkerDeg = false }
465
+ if (suppressedByMarkerDeg) {
466
+ this.consecutiveDegraded = 0
467
+ return
468
+ }
469
+ if (this.deps.isPlannedRestartActive) {
470
+ let planned = false
471
+ try { planned = await Promise.resolve(this.deps.isPlannedRestartActive()) } catch { planned = false }
472
+ if (planned) { this.consecutiveDegraded = 0; return }
473
+ }
474
+ const now = this.deps.getTime ? this.deps.getTime() : Date.now()
475
+ // degraded needs consecutive hits to avoid flapping — Option A 2026-09-03: 3→5 (via config)
476
+ const degradedThreshold = await this.getEffectiveDegradedThreshold()
477
+ this.consecutiveDegraded++
478
+ if (this.consecutiveDegraded < degradedThreshold) {
479
+ if (now - this.lastDegradedNotify < 60000) return
480
+ this.lastDegradedNotify = now
481
+ try {
482
+ const ts = new Date().toISOString().replace(/[:.]/g, '-')
483
+ const logTail = (health as any).logTail ?? ''
484
+ const gitDiff = await this.collectGitDiff().catch(() => '')
485
+ const reportPath = await this.deps.writeReport({ ts, health, action: `degraded — ${health.error ?? 'plugin'}`, logTail, gitDiff }).catch(() => '')
486
+ await this.deps.notify(`DEGRADED: ${health.error ?? 'plugin'} (report: ${reportPath})`).catch(() => {})
487
+ const runner = this.getRunDebugAgent()
488
+ const isInjected = !!this.deps.runDebugAgent
489
+ if (isInjected) {
490
+ void runner({ reportPath, health }).then(res => this.handleDebugResult(reportPath, res)).catch(() => {})
491
+ setTimeout(() => {
492
+ this.findInterruptedRecent().then(r => {
493
+ if (r.interrupted.length) void this.attemptAutoResume(r.interrupted).catch(() => {})
494
+ }).catch(() => {})
495
+ }, 0)
496
+ } else if (!process.env.VITEST) {
497
+ void runner({ reportPath, health }).then(res => this.handleDebugResult(reportPath, res)).catch(() => {})
498
+ setTimeout(() => {
499
+ this.findInterruptedRecent().then(r => {
500
+ if (r.interrupted.length) void this.attemptAutoResume(r.interrupted).catch(() => {})
501
+ }).catch(() => {})
502
+ }, 0)
503
+ }
504
+ } catch {}
505
+ return
506
+ }
507
+ // consecutive degraded threshold reached → treat as down: rollback + restart
508
+ this.consecutiveDegraded = 0
509
+ const degradedError = health.error ?? 'degraded plugin error'
510
+ if (this.rollingBack) return
511
+ const now2 = this.deps.getTime ? this.deps.getTime() : Date.now()
512
+ const debounceMs2 = this.deps.debounceMs ?? 60000
513
+ if (now2 - this.lastRollback < debounceMs2) return
514
+ this.rollingBack = true
515
+ this.lastRollback = now2
516
+ try {
517
+ const failed = await this.deps.writeFailed().catch(() => ({ ts: new Date().toISOString().replace(/[:.]/g, '-'), manifest: null }))
518
+ const ts2 = (failed as any)?.ts ?? new Date().toISOString().replace(/[:.]/g, '-')
519
+ const logTail2 = (health as any).logTail ?? ''
520
+ const gitDiff2 = await this.collectGitDiff().catch(() => '')
521
+ const degradedHealth: HealthState = { up: false, httpCode: health.httpCode, error: `degraded → down: ${degradedError}`, logTail: logTail2, degraded: false }
522
+ const reportPath2 = await this.deps.writeReport({ ts: ts2, health: degradedHealth, action: `rollback — degraded: ${degradedError}`, logTail: logTail2, gitDiff: gitDiff2 }).catch(() => '')
523
+ try {
524
+ const summary = await this.deps.rollback()
525
+ await this.reportRollbackResult(summary, reportPath2)
526
+ } catch (e: any) { await this.deps.notify(`rollback failed: ${e?.message ?? String(e)} (report: ${reportPath2})`).catch(() => {}) }
527
+ if (this.deps.restartWeb) {
528
+ try { await this.deps.restartWeb(); await this.deps.notify(`restarted dsh-web after rollback (report: ${reportPath2})`).catch(() => {}) } catch (e: any) { await this.deps.notify(`restart dsh-web failed: ${e?.message ?? String(e)} (report: ${reportPath2})`).catch(() => {}) }
529
+ }
530
+ await this.deps.notify(`DEGRADED → rollback (report: ${reportPath2}, error: ${degradedError})`).catch(() => {})
531
+ try { await this.deps.notify(`🔄 dsh web auto-restart — degraded: ${degradedError} — ${new Date().toISOString()}`).catch(() => {}) } catch {}
532
+ } finally { this.rollingBack = false }
533
+ return
534
+ }
535
+
536
+ if (health.up) {
537
+ this.consecutiveDown = 0
538
+ this.consecutiveDegraded = 0
539
+ // D5: a healthy poll is the authoritative "the restart succeeded"
540
+ // signal — clear the suppression marker here instead of waiting for its
541
+ // TTL, so a stale marker can never mute a later real crash.
542
+ let markerClearedThisTick = false
543
+ try {
544
+ if (this.getCheckPlannedRestart()()) {
545
+ this.getClearPlannedRestart()()
546
+ markerClearedThisTick = true
547
+ }
548
+ } catch {}
549
+ // Post-self-restart boot proved healthy: run the post-restart
550
+ // session-scan hook and re-arm the single-flight latch. A failed clear
551
+ // keeps the latch set so the same marker is never re-handled into a
552
+ // second restart.
553
+ if (this.awaitingHealthyBoot) {
554
+ this.awaitingHealthyBoot = false
555
+ const req = this.pendingRestartRequest
556
+ this.pendingRestartRequest = undefined
557
+ let cleared = markerClearedThisTick
558
+ if (!cleared) {
559
+ try { this.getClearPlannedRestart()(); cleared = true } catch {}
560
+ }
561
+ if (cleared) this.restartRequestHandled = false
562
+ if (req) {
563
+ try { this.deps.onRestartRequestHandled?.(req) } catch {}
564
+ if (req.callerSessionId) {
565
+ try {
566
+ const listen = this.deps.listenerPid ?? defaultListenerPid
567
+ ;(this.deps.writeOutcome ?? defaultWriteOutcome)(req.callerSessionId, {
568
+ state: 'ok',
569
+ oldPid: req.oldPid,
570
+ newPid: listen(3082),
571
+ httpStatus: (health as any)?.httpCode ?? 200,
572
+ swappedAt: this.deps.getTime ? this.deps.getTime() : Date.now(),
573
+ })
574
+ } catch {}
575
+ }
576
+ }
577
+ }
578
+ // Throttle LKG writes to at most once per 5 minutes
579
+ const now = this.deps.getTime ? this.deps.getTime() : Date.now()
580
+ if (now - this.lastLKGWrite > 5 * 60 * 1000) {
581
+ try {
582
+ await this.deps.writeLKG()
583
+ this.lastLKGWrite = now
584
+ } catch {
585
+ // ignore snapshot errors
586
+ }
587
+ }
588
+ return
589
+ }
590
+
591
+ // Single-owner 30s marker: planned restart in progress — suppress crash
592
+ // handling entirely for 30s (no writeFailed/writeReport/rollback).
593
+ // Check both the new JSON marker (writePlannedRestart) and the legacy
594
+ // isPlannedRestartActive (dsh-safe-web-update plain file) for compat.
595
+ let suppressedByMarker = false
596
+ try { suppressedByMarker = this.getCheckPlannedRestart()() } catch { suppressedByMarker = false }
597
+ if (suppressedByMarker) {
598
+ this.consecutiveDown = 0
599
+ return
600
+ }
601
+
602
+ // Down while an intentional restart (e.g. dsh-safe-web-update) is in
603
+ // flight is expected, not a crash — never race it with our own
604
+ // rollback/restartWeb.
605
+ if (this.deps.isPlannedRestartActive) {
606
+ let planned = false
607
+ try { planned = await Promise.resolve(this.deps.isPlannedRestartActive()) } catch { planned = false }
608
+ if (planned) {
609
+ this.consecutiveDown = 0
610
+ return
611
+ }
612
+ }
613
+
614
+ // Down — require consecutive confirmations before treating as a crash.
615
+ // A lone timed-out poll (e.g. a slow plugin-tree boot) must not trigger
616
+ // rollback/restart: that restart produces its own transient errors on
617
+ // the next poll, which would otherwise re-trigger this same path forever.
618
+ // D1/D2: while the boot is unproven only a refused connection may advance
619
+ // the down counter — nothing is listening, so the process is gone. A
620
+ // timeout/abort (or anything unattributable) is a slow boot, not a crash.
621
+ if (health.bootPhase === 'booting' && classifyFetchFailure(health.error) !== 'refused') {
622
+ this.consecutiveDown = 0
623
+ return
624
+ }
625
+ this.consecutiveDown++
626
+ let downThreshold = await this.getEffectiveDownThreshold()
627
+ // When a planned restart marker is active, double the threshold (3→6 at
628
+ // 3s interval ≈ 9s→18s). Health-poller already suppresses fetch failed in
629
+ // this window, but supervisor also doubles so a transient that escapes
630
+ // health still needs longer to trigger. The early return above already
631
+ // suppresses fully for 30s; doubling remains for the legacy
632
+ // isPlannedRestartActive path and for any race where the marker was
633
+ // written between the early check and this line.
634
+ try {
635
+ if (this.getCheckPlannedRestart()()) downThreshold *= 2
636
+ } catch {}
637
+ if (this.consecutiveDown < downThreshold) return
638
+
639
+ // Down — check debounce and rolling state
640
+ if (this.rollingBack) return
641
+ const now = this.deps.getTime ? this.deps.getTime() : Date.now()
642
+ const debounceMs = this.deps.debounceMs ?? 60000
643
+ if (now - this.lastRollback < debounceMs) return
644
+
645
+ this.rollingBack = true
646
+ this.consecutiveDown = 0
647
+ this.lastRollback = now
648
+
649
+ try {
650
+ const failed = await this.deps.writeFailed().catch(() => ({ ts: new Date().toISOString().replace(/[:.]/g, '-'), manifest: null }))
651
+ const ts = (failed as any)?.ts ?? new Date().toISOString().replace(/[:.]/g, '-')
652
+ const logTail = (health as any).logTail ?? ''
653
+ const gitDiff = await this.collectGitDiff().catch(() => '')
654
+ const reportPath = await this.deps.writeReport({ ts, health, action: `rollback — ${health.error ?? 'down'}`, logTail, gitDiff }).catch(() => '')
655
+ try {
656
+ const summary = await this.deps.rollback()
657
+ await this.reportRollbackResult(summary, reportPath)
658
+ } catch (e: any) {
659
+ await this.deps.notify(`rollback failed: ${e?.message ?? String(e)} (report: ${reportPath})`).catch(() => {})
660
+ }
661
+ // Always attempt to (re)start dsh web — survives reboot even when rollback is a no-op
662
+ if (this.deps.restartWeb) {
663
+ try {
664
+ await this.deps.restartWeb()
665
+ await this.deps.notify(`restarted dsh-web after rollback (report: ${reportPath})`).catch(() => {})
666
+ } catch (e: any) {
667
+ await this.deps.notify(`restart dsh-web failed: ${e?.message ?? String(e)} (report: ${reportPath})`).catch(() => {})
668
+ }
669
+ }
670
+ await this.deps.notify(`CRASH detected → rollback (report: ${reportPath}, error: ${health.error ?? 'down'})`).catch(() => {})
671
+ const runner = this.getRunDebugAgent()
672
+ const isInjected = !!this.deps.runDebugAgent
673
+ if (isInjected) {
674
+ void runner({ reportPath, health }).then(res => this.handleDebugResult(reportPath, res)).catch(() => {})
675
+ setTimeout(() => {
676
+ this.findInterruptedRecent().then(r => {
677
+ if (r.interrupted.length) void this.attemptAutoResume(r.interrupted).catch(() => {})
678
+ }).catch(() => {})
679
+ }, 0)
680
+ } else if (!process.env.VITEST) {
681
+ void runner({ reportPath, health }).then(res => this.handleDebugResult(reportPath, res)).catch(() => {})
682
+ setTimeout(() => {
683
+ this.findInterruptedRecent().then(r => {
684
+ if (r.interrupted.length) void this.attemptAutoResume(r.interrupted).catch(() => {})
685
+ }).catch(() => {})
686
+ }, 0)
687
+ }
688
+ } finally {
689
+ this.rollingBack = false
690
+ }
691
+ }
692
+
693
+ async start(): Promise<void> {
694
+ if (this.timer) return
695
+ const intervalMs = await this.getEffectiveIntervalMs()
696
+ this.timer = setInterval(() => { this.tick().catch(() => {}) }, intervalMs)
697
+ // Immediate tick so a reboot is recovered in ~0-3s, not 3s
698
+ this.tick().catch(() => {})
699
+ }
700
+
701
+ // Synchronous start wrapper for callers that do not await (daemon cli fire-and-forget)
702
+ startSync(): void {
703
+ // The caller never observes this promise: an escaping rejection would reach
704
+ // the host's unhandled-rejection path and exit the daemon.
705
+ void this.start().catch((err) => {
706
+ console.error('dsh-web-supervisor: start failed:', err instanceof Error ? err.message : err)
707
+ })
708
+ }
709
+
710
+ stop(): void {
711
+ if (this.timer) {
712
+ clearInterval(this.timer)
713
+ this.timer = null
714
+ }
715
+ if (this.restartRequestTimer) {
716
+ clearTimeout(this.restartRequestTimer)
717
+ this.restartRequestTimer = null
718
+ }
719
+ }
720
+ }