@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,446 @@
1
+ import { checkPlannedRestart, BOOT_BOUNDARY_MARKER } from './restart-guards.js'
2
+ import { execSync as execSyncImpl } from 'node:child_process'
3
+
4
+ export interface HealthState {
5
+ up: boolean
6
+ httpCode?: number
7
+ error?: string
8
+ degraded?: boolean
9
+ logTail?: string
10
+ /** Boot verdict for the unit start this poll observed (see bootFreshness). */
11
+ bootPhase?: BootFreshness
12
+ }
13
+
14
+ /**
15
+ * Wall-clock epoch ms of the current dsh-web unit start, or undefined when
16
+ * systemd does not manage the unit (portable host) or the lookup is disabled.
17
+ * `ActiveEnterTimestampMonotonic` is deliberately gone: a monotonic reading
18
+ * cannot be compared with a timestamp-less append-only log.
19
+ */
20
+ export function getActiveEnterMs(): number | undefined {
21
+ if (process.env.VITEST) return undefined
22
+ try {
23
+ const out = execSyncImpl('systemctl --user show -p ActiveEnterTimestamp dsh-web.service 2>/dev/null', { encoding: 'utf8' } as any) as unknown as string
24
+ const m = (out as string).match(/ActiveEnterTimestamp=(.+)/)
25
+ if (m) {
26
+ const s = m[1].trim()
27
+ if (!s || s === 'n/a') return undefined
28
+ const ms = Date.parse(s)
29
+ if (!Number.isNaN(ms)) return ms
30
+ }
31
+ } catch {}
32
+ return undefined
33
+ }
34
+
35
+ /** @deprecated kept for callers; identical to getActiveEnterMs(). */
36
+ export function getActiveEnterWallMs(): number | undefined {
37
+ return getActiveEnterMs()
38
+ }
39
+
40
+ export interface PollHealthOpts {
41
+ fetch?: () => Promise<{ status: number; text: () => Promise<string> }>
42
+ psAlive?: () => Promise<boolean>
43
+ logTail?: () => Promise<string>
44
+ url?: string
45
+ timeoutMs?: number
46
+ /** injectable for tests — overrides the systemctl lookup */
47
+ getActiveEnterMs?: () => number | undefined
48
+ /** Wall-clock epoch ms of the current dsh-web unit start (see bootFreshness). */
49
+ activeEnterAtMs?: number
50
+ /** Boot budget in ms; a younger boot without its own success marker is 'booting'. */
51
+ bootGraceMs?: number
52
+ }
53
+
54
+ // Specific parse/boot-failure markers only. Bare 'JSON'/'YAML' were removed
55
+ // (2026-08-31): they matched any line whose payload merely *contained* those
56
+ // substrings — e.g. maestro-sync's status JSON listing session.jsonl.zstd /
57
+ // settings.json paths — turning a healthy 401 into a rollback + restart.
58
+ const ERROR_PATTERNS = [
59
+ 'ERR_MODULE_NOT_FOUND',
60
+ 'ERR_PNPM',
61
+ 'assertChannel',
62
+ 'unhandledRejection',
63
+ 'SyntaxError',
64
+ 'YAMLParseError',
65
+ 'ParseError',
66
+ 'corrupted',
67
+ 'allowBuilds',
68
+ 'Cannot find module',
69
+ 'Failed to load',
70
+ 'EADDRINUSE',
71
+ 'address already in use',
72
+ ]
73
+
74
+ export type BootFreshness = 'unknown' | 'booting' | 'settled'
75
+
76
+ /**
77
+ * Decide whether the current unit start can already be judged.
78
+ *
79
+ * `activeEnterAtMs` is WALL-CLOCK epoch ms from
80
+ * `systemctl --user show -p ActiveEnterTimestamp dsh-web.service`.
81
+ * Deliberately NOT `ActiveEnterTimestampMonotonic`: a monotonic reading can
82
+ * never be compared against an append-only log that carries no timestamps, and
83
+ * that mismatch is why the previous scan filter silently fell through and let
84
+ * the previous boot's crash text be read as this boot's (incident 2026-09-13).
85
+ *
86
+ * - 'unknown' — no boot anchor (systemd absent, lookup disabled, clock skew):
87
+ * behave exactly as before the fix; never suppress anything.
88
+ * - 'booting' — the unit started less than `bootGraceMs` ago and has not yet
89
+ * proven itself by actually serving a request: weak failures are
90
+ * suppressed and log lines are inconclusive.
91
+ * - 'settled' — the boot proved itself, or the grace window expired: judge
92
+ * normally.
93
+ */
94
+ export function bootFreshness(opts: {
95
+ activeEnterAtMs?: number
96
+ now: number
97
+ bootGraceMs: number
98
+ /**
99
+ * Did THIS poll receive a serving response (200/401)?
100
+ *
101
+ * Deliberately not "the log shows `dsh web: http`": that line is printed the
102
+ * moment the raw webserver binds, seconds into a boot that can take ~90s to
103
+ * finish loading the plugin tree. Crediting it as proof ended the grace while
104
+ * the proxy in front was still coming up, so probes that hung during the rest
105
+ * of the boot were judged as crashes — the 2026-09-13 restart loop.
106
+ */
107
+ probeSucceeded: boolean
108
+ }): BootFreshness {
109
+ const { activeEnterAtMs, now, bootGraceMs, probeSucceeded } = opts
110
+ if (activeEnterAtMs === undefined || !Number.isFinite(activeEnterAtMs)) return 'unknown'
111
+ if (now < activeEnterAtMs) return 'unknown'
112
+ if (probeSucceeded) return 'settled'
113
+ return now - activeEnterAtMs < bootGraceMs ? 'booting' : 'settled'
114
+ }
115
+
116
+ /**
117
+ * Classify a fetch failure by what it says about the process.
118
+ *
119
+ * 'refused' — nothing is listening, so the process is gone: a strong down
120
+ * signal that must never be masked by a boot grace.
121
+ * 'timeout' — something may be alive but slow: weak, only meaningful once the
122
+ * boot grace expired.
123
+ * 'other' — anything we cannot attribute.
124
+ *
125
+ * Walks the `cause` chain because undici surfaces a refused connection as
126
+ * `TypeError: fetch failed` with the real `ECONNREFUSED` on `cause`.
127
+ */
128
+ export function classifyFetchFailure(err: unknown): 'refused' | 'timeout' | 'other' {
129
+ const parts: string[] = []
130
+ let cur: any = err
131
+ for (let depth = 0; cur != null && depth < 5; depth++) {
132
+ if (typeof cur === 'string') { parts.push(cur); break }
133
+ const code = typeof cur.code === 'string' ? cur.code : ''
134
+ const name = typeof cur.name === 'string' ? cur.name : ''
135
+ const message = typeof cur.message === 'string' ? cur.message : ''
136
+ parts.push(`${code} ${name} ${message}`)
137
+ cur = cur.cause
138
+ }
139
+ const text = parts.join(' ').toLowerCase()
140
+ if (/econnrefused|connection refused|ehostunreach|enetunreach/.test(text)) return 'refused'
141
+ if (/abort|timed? ?out|etimedout|und_err_connect_timeout/.test(text)) return 'timeout'
142
+ return 'other'
143
+ }
144
+
145
+ export const SUCCESS_MARKER = 'dsh web: http'
146
+
147
+ /** Index of the last boot-boundary line in the tail, or -1 when it predates the tail. */
148
+ export function lastBootBoundaryIndex(lines: string[]): number {
149
+ for (let i = lines.length - 1; i >= 0; i--) {
150
+ if (lines[i].includes(BOOT_BOUNDARY_MARKER)) return i
151
+ }
152
+ return -1
153
+ }
154
+
155
+ /** Index of the last "dsh web: http" success marker (`lowerLines` must be lower-cased). */
156
+ export function lastSuccessMarkerIndex(lowerLines: string[]): number {
157
+ for (let i = lowerLines.length - 1; i >= 0; i--) {
158
+ if (lowerLines[i].includes(SUCCESS_MARKER)) return i
159
+ }
160
+ return -1
161
+ }
162
+
163
+ /** Wall-clock ms parsed from a boot-boundary line, or undefined when unparseable. */
164
+ export function parseBootBoundaryMs(line: string): number | undefined {
165
+ const m = /boot-boundary\s+(\S+)/.exec(line)
166
+ if (!m) return undefined
167
+ const ms = Date.parse(m[1]!)
168
+ return Number.isNaN(ms) ? undefined : ms
169
+ }
170
+
171
+ export async function pollHealth(opts: PollHealthOpts = {}): Promise<HealthState> {
172
+ // 5s was too tight for a busy plugin-tree boot: a lone AbortError from a slow
173
+ // (but otherwise fine) response was indistinguishable from a real crash, and
174
+ // combined with a low down-threshold this caused a self-sustaining restart
175
+ // loop (see Supervisor.downThreshold). 12s gives boot room without masking
176
+ // a genuinely dead process for long. 20s (Option A 2026-09-03) tolerates
177
+ // high load (loadavg 12) stalls; configurable via domains.supervisor.pollTimeoutMs.
178
+ // If opts.timeoutMs is not injected, read from supervisor config (maestro settings).
179
+ let effectiveTimeout = opts.timeoutMs
180
+ let bootGraceMs = opts.bootGraceMs
181
+ if (effectiveTimeout === undefined || bootGraceMs === undefined) {
182
+ try {
183
+ const { readSupervisorConfig } = await import('./config.js')
184
+ const cfg: any = await readSupervisorConfig()
185
+ if (effectiveTimeout === undefined && typeof cfg.pollTimeoutMs === 'number' && cfg.pollTimeoutMs > 0) effectiveTimeout = cfg.pollTimeoutMs
186
+ if (bootGraceMs === undefined && typeof cfg.bootGraceMs === 'number' && cfg.bootGraceMs > 0) bootGraceMs = cfg.bootGraceMs
187
+ } catch {}
188
+ effectiveTimeout ??= 20000
189
+ bootGraceMs ??= 180000
190
+ }
191
+ const fetchFn = opts.fetch ?? defaultFetch(opts.url ?? 'http://127.0.0.1:3080/', effectiveTimeout)
192
+ const psAliveFn = opts.psAlive ?? defaultPsAlive
193
+ const logTailFn = opts.logTail ?? defaultLogTail
194
+
195
+ let httpCode: number | undefined
196
+ let fetchError: string | undefined
197
+
198
+ try {
199
+ const res = await fetchFn()
200
+ httpCode = res.status
201
+ // 401 is healthy: dsh web is up but requires browser token (since 0.1.2). Only 5xx / network errors are down.
202
+ if (res.status !== 200 && res.status !== 401) {
203
+ fetchError = `http ${res.status}`
204
+ }
205
+ } catch (e: any) {
206
+ fetchError = e?.message ?? String(e)
207
+ }
208
+
209
+ let logContent = ''
210
+ try {
211
+ logContent = await logTailFn()
212
+ } catch {
213
+ // ignore log read errors
214
+ }
215
+
216
+ // Suppression gate: an in-flight planned restart, or a boot that has not yet
217
+ // proven itself, means transients are expected. A refused connection is
218
+ // never suppressed: nothing is listening, so the process is gone (D2).
219
+ const suppressed = checkPlannedRestart()
220
+
221
+ let activeEnterAtMs: number | undefined = opts.activeEnterAtMs
222
+ if (activeEnterAtMs === undefined) {
223
+ try {
224
+ const fn = opts.getActiveEnterMs ?? getActiveEnterMs
225
+ activeEnterAtMs = fn()
226
+ } catch {
227
+ activeEnterAtMs = undefined
228
+ }
229
+ }
230
+
231
+ const now = Date.now()
232
+ const lines = logContent.split('\n')
233
+ const lowerLines = lines.map(l => l.toLowerCase())
234
+ // Scope the scan to the current boot. The boundary line is only trusted for
235
+ // the unit start it was written for: a start more than a boot budget later
236
+ // (a systemd auto-restart, a manual start) is a different boot.
237
+ const boundaryIdx = lastBootBoundaryIndex(lines)
238
+ const boundaryMs = boundaryIdx === -1 ? undefined : parseBootBoundaryMs(lines[boundaryIdx]!)
239
+ const scopedToThisBoot = boundaryMs !== undefined
240
+ && activeEnterAtMs !== undefined
241
+ && activeEnterAtMs >= boundaryMs
242
+ && activeEnterAtMs - boundaryMs <= bootGraceMs
243
+ const bootLines = scopedToThisBoot ? lines.slice(boundaryIdx + 1) : lines
244
+ const bootLower = scopedToThisBoot ? lowerLines.slice(boundaryIdx + 1) : lowerLines
245
+ // Proof of a finished boot is a serving probe, not a log line (see bootFreshness).
246
+ const probeSucceeded = httpCode === 200 || httpCode === 401
247
+ const bootPhase = bootFreshness({ activeEnterAtMs, now, bootGraceMs, probeSucceeded })
248
+ const booting = bootPhase === 'booting'
249
+ const graceActive = suppressed || booting
250
+
251
+ // Inside the current boot, only lines after its own success marker may be a
252
+ // post-start crash. With no marker and no scope proving these lines are this
253
+ // boot's, the scan is inconclusive (D3) instead of inheriting the previous
254
+ // boot's crash text — that inheritance is what produced the 2026-09-13
255
+ // rollback report ("rollback — degraded: This operation was aborted") from a
256
+ // healthy, still-booting instance reading the previous boot's EADDRINUSE.
257
+ const successIdx = lastSuccessMarkerIndex(bootLower)
258
+ let scanLines: string[]
259
+ let scanLower: string[]
260
+ if (successIdx !== -1) {
261
+ scanLines = bootLines.slice(successIdx + 1)
262
+ scanLower = bootLower.slice(successIdx + 1)
263
+ } else if (booting && !scopedToThisBoot) {
264
+ scanLines = []
265
+ scanLower = []
266
+ } else {
267
+ scanLines = bootLines
268
+ scanLower = bootLower
269
+ }
270
+ if (scanLines.length > 200) {
271
+ scanLines = scanLines.slice(-200)
272
+ scanLower = scanLower.slice(-200)
273
+ }
274
+
275
+ let lastErrorIdx = -1
276
+ let matchedLine = ''
277
+ for (let i = scanLines.length - 1; i >= 0; i--) {
278
+ const lower = scanLower[i]
279
+ for (const pat of ERROR_PATTERNS) {
280
+ if (lower.includes(pat.toLowerCase())) {
281
+ lastErrorIdx = i
282
+ matchedLine = scanLines[i].trim().slice(0, 500)
283
+ break
284
+ }
285
+ }
286
+ if (lastErrorIdx !== -1) break
287
+ }
288
+ let logError: string | undefined
289
+ if (lastErrorIdx !== -1) {
290
+ let hasSuccessAfter = false
291
+ for (let i = lastErrorIdx + 1; i < scanLines.length; i++) {
292
+ if (scanLower[i].includes(SUCCESS_MARKER)) { hasSuccessAfter = true; break }
293
+ }
294
+ if (!hasSuccessAfter) logError = matchedLine
295
+ }
296
+
297
+ if (fetchError) {
298
+ const kind = classifyFetchFailure(fetchError)
299
+ // D1: a timeout/abort while the current boot is unproven is a slow boot,
300
+ // not a crash — increment nothing. D2: a refused connection is different
301
+ // (nothing is listening, the process is gone) and is never masked.
302
+ if (booting && kind !== 'refused') {
303
+ return { up: true, httpCode, bootPhase, logTail: logContent.slice(-5000) }
304
+ }
305
+ // D5: inside the boot window a refused connection with a verifiably alive
306
+ // process is a boot symptom, not a crash — the listener may not be bound
307
+ // yet. Outside the window, or with a dead process, the verdict below is
308
+ // exactly the pre-D5 behaviour (degraded when the port still answers,
309
+ // down when it does not).
310
+ if (booting && kind === 'refused') {
311
+ let alive = false
312
+ try { alive = await psAliveFn() } catch { alive = false }
313
+ if (alive) {
314
+ return { up: true, httpCode, bootPhase, logTail: logContent.slice(-5000) }
315
+ }
316
+ }
317
+ if (suppressed) {
318
+ return { up: true, httpCode, bootPhase, logTail: logContent.slice(-5000) }
319
+ }
320
+ // Corroborate with a cheap port-liveness check before declaring a crash.
321
+ // The HTTP fetch shares dsh-web's own event loop, so a busy-but-alive
322
+ // process (e.g. heavy GitLab-webhook-triggered review work) times out
323
+ // the same way a genuinely dead one does — but a real crash always frees
324
+ // the port, while `ss` does not depend on the contended event loop to
325
+ // answer. Downgrade to DEGRADED (still visible, still escalates after
326
+ // repeated ticks) instead of forcing an immediate rollback + restartWeb
327
+ // that would kill an in-flight review for nothing.
328
+ let portAlive = false
329
+ try { portAlive = await psAliveFn() } catch { portAlive = false }
330
+ if (portAlive) {
331
+ return {
332
+ up: true,
333
+ httpCode,
334
+ bootPhase,
335
+ error: logError ? `${fetchError} + ${logError}` : fetchError,
336
+ degraded: true,
337
+ logTail: logContent.slice(-5000),
338
+ }
339
+ }
340
+ return {
341
+ up: false,
342
+ httpCode,
343
+ bootPhase,
344
+ error: logError ? `${fetchError} + ${logError}` : fetchError,
345
+ degraded: false,
346
+ logTail: logContent.slice(-5000),
347
+ }
348
+ }
349
+ // During grace, a windowed logError that is still present is considered
350
+ // stale/boot transient as well — treat as up to avoid double restart.
351
+ if (graceActive && logError) {
352
+ return { up: true, httpCode, bootPhase, logTail: logContent.slice(-5000) }
353
+ }
354
+ if (logError) {
355
+ // EADDRINUSE is fatal even with http 200 — an old process still holds
356
+ // the port and the new start failed; treat as FULL down so the supervisor
357
+ // kills + restarts.
358
+ const lowerErr = logError.toLowerCase()
359
+ const isFatalPortError = lowerErr.includes('eaddrinuse') || lowerErr.includes('address already in use')
360
+ if (isFatalPortError) {
361
+ return { up: false, httpCode, bootPhase, error: logError, degraded: false, logTail: logContent.slice(-5000) }
362
+ }
363
+ // http 200 but log error → DEGRADED (isolatable), not FULL
364
+ if (httpCode === 200) {
365
+ return { up: true, httpCode, bootPhase, error: logError, degraded: true, logTail: logContent.slice(-5000) }
366
+ }
367
+ return { up: false, httpCode, bootPhase, error: logError, degraded: false, logTail: logContent.slice(-5000) }
368
+ }
369
+
370
+ // Also check psAlive as secondary signal — if fetch ok but ps dead, still down
371
+ try {
372
+ const alive = await psAliveFn()
373
+ if (!alive && httpCode === 200) {
374
+ // fetch succeeded but ps says dead — likely stale, still consider up if http 200
375
+ }
376
+ } catch {
377
+ // ignore
378
+ }
379
+
380
+ return { up: httpCode === 200 || httpCode === 401, httpCode, bootPhase, logTail: logContent.slice(-5000) }
381
+ }
382
+
383
+ function defaultFetch(url: string, timeoutMs: number): () => Promise<{ status: number; text: () => Promise<string> }> {
384
+ return async () => {
385
+ const controller = new AbortController()
386
+ const t = setTimeout(() => controller.abort(), timeoutMs)
387
+ try {
388
+ const res = await fetch(url, { signal: controller.signal })
389
+ return { status: res.status, text: async () => res.text() }
390
+ } finally {
391
+ clearTimeout(t)
392
+ }
393
+ }
394
+ }
395
+
396
+ async function defaultPsAlive(): Promise<boolean> {
397
+ // Check if any listener on 3080 exists via ss — fallback to true if ss unavailable
398
+ try {
399
+ const { execSync } = await import('node:child_process')
400
+ const out = execSync('ss -tln 2>/dev/null || true', { encoding: 'utf-8' })
401
+ return out.includes(':3080')
402
+ } catch {
403
+ return true
404
+ }
405
+ }
406
+
407
+ export async function collectLogTail(): Promise<string> {
408
+ try {
409
+ const { readFileSync, existsSync, statSync } = await import('node:fs')
410
+ const { homedir } = await import('node:os')
411
+ const candidates = [
412
+ `${homedir()}/.dsh/dsh-web.log`,
413
+ `${homedir()}/.dsh/.supervisor/supervisor.log`,
414
+ `${homedir()}/.dsh.log`,
415
+ ]
416
+ for (const logPath of candidates) {
417
+ try {
418
+ if (!existsSync(logPath)) continue
419
+ // avoid reading huge files fully — if >1MB, read tail via shell
420
+ try {
421
+ const sz = statSync(logPath).size
422
+ if (sz > 1024 * 1024) {
423
+ const { execSync } = await import('node:child_process')
424
+ const out = execSync(`tail -c 5000 ${JSON.stringify(logPath)} 2>/dev/null || cat ${JSON.stringify(logPath)} 2>/dev/null | tail -c 5000`, { encoding: 'utf-8', timeout: 2000 })
425
+ if (out) return out.slice(-5000)
426
+ }
427
+ } catch {}
428
+ const content = readFileSync(logPath, 'utf-8')
429
+ if (content && content.trim()) return content.slice(-5000)
430
+ } catch {}
431
+ }
432
+ // fallback: try journalctl for the dsh-web or supervisor units (if running via systemd)
433
+ try {
434
+ const { execSync } = await import('node:child_process')
435
+ const journal = execSync('journalctl --user -u dsh-web-supervisor --no-pager -n 100 2>/dev/null | tail -c 5000 || journalctl --user --no-pager -n 100 2>/dev/null | tail -c 5000 || true', { encoding: 'utf-8', timeout: 2000 })
436
+ if (journal && journal.trim()) return journal.slice(-5000)
437
+ } catch {}
438
+ return ''
439
+ } catch {
440
+ return ''
441
+ }
442
+ }
443
+
444
+ async function defaultLogTail(): Promise<string> {
445
+ return collectLogTail()
446
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * dsh-maestro-core — Cordis host plugin entry.
3
+ * The daemon CLI lives in bin.ts (lib/bin.js); this file is the
4
+ * host plugin loaded by DSH web via cordis.patch.yml.
5
+ */
6
+ export * from './plugin.js'
7
+ export { apply, inject } from './plugin.js'
@@ -0,0 +1,67 @@
1
+ import { existsSync, readFileSync, unlinkSync, mkdirSync, writeFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { homedir } from 'node:os'
4
+
5
+ /**
6
+ * Durable self-restart intent sidecar written by `dsh_web_restart`
7
+ * (`~/.dsh/.supervisor/intents/<sessionId>.json`, mode 600). Consumed by
8
+ * auto-resume so a session that requested the restart is resumed with a
9
+ * contextual message instead of the generic "outcome unknown" recovery text.
10
+ */
11
+ export interface RestartIntent { ts: number; sessionId?: string; reason?: string }
12
+
13
+ export function intentsDir(): string {
14
+ return join(homedir(), '.dsh', '.supervisor', 'intents')
15
+ }
16
+
17
+ export function intentPath(sessionId: string): string {
18
+ const safe = sessionId.replace(/[^A-Za-z0-9._-]/g, '_')
19
+ return join(intentsDir(), `${safe}.json`)
20
+ }
21
+
22
+ export function readIntent(sessionId: string): RestartIntent | undefined {
23
+ try {
24
+ const p = intentPath(sessionId)
25
+ if (!existsSync(p)) return undefined
26
+ return JSON.parse(readFileSync(p, 'utf8')) as RestartIntent
27
+ } catch { return undefined }
28
+ }
29
+
30
+ export function consumeIntent(sessionId: string): void {
31
+ try { unlinkSync(intentPath(sessionId)) } catch {}
32
+ }
33
+
34
+ /**
35
+ * Post-swap outcome written by the supervisor daemon after acting on a
36
+ * restart request (`<sessionId>.outcome.json`, mode 600, same dir). Read by
37
+ * `dsh_web_restart_status` so callers learn the new PID + HTTP status without
38
+ * hand-probing `ss`/`curl`.
39
+ */
40
+ export interface RestartOutcome {
41
+ state: 'ok' | 'failed'
42
+ oldPid?: number
43
+ newPid?: number
44
+ httpStatus?: number
45
+ swappedAt: number
46
+ error?: string
47
+ }
48
+
49
+ export function outcomePath(sessionId: string): string {
50
+ const safe = sessionId.replace(/[^A-Za-z0-9._-]/g, '_')
51
+ return join(intentsDir(), `${safe}.outcome.json`)
52
+ }
53
+
54
+ export function writeRestartOutcome(sessionId: string, outcome: RestartOutcome): void {
55
+ try {
56
+ mkdirSync(intentsDir(), { recursive: true })
57
+ writeFileSync(outcomePath(sessionId), JSON.stringify(outcome), { encoding: 'utf8', mode: 0o600 })
58
+ } catch {}
59
+ }
60
+
61
+ export function readRestartOutcome(sessionId: string): RestartOutcome | undefined {
62
+ try {
63
+ const p = outcomePath(sessionId)
64
+ if (!existsSync(p)) return undefined
65
+ return JSON.parse(readFileSync(p, 'utf8')) as RestartOutcome
66
+ } catch { return undefined }
67
+ }
@@ -0,0 +1,71 @@
1
+ import { checkPlannedRestart } from './restart-guards.js'
2
+
3
+ export interface NotifierOpts {
4
+ send?: (msg: string) => Promise<void>
5
+ }
6
+
7
+ export async function notifyAutoRestart(
8
+ reason: string,
9
+ opts: NotifierOpts & { httpCode?: string | number; lkgId?: string; reportPath?: string } = {},
10
+ ): Promise<void> {
11
+ if (checkPlannedRestart()) return
12
+ const httpCode = (opts as any).httpCode ?? 'n/a'
13
+ const lkgId = (opts as any).lkgId ?? (opts as any).lkg ?? 'n/a'
14
+ const reportPath = (opts as any).reportPath ?? (opts as any).report ?? 'n/a'
15
+ const msg = `🔄 dsh web auto-restart — ${reason} — ${new Date().toISOString()} — up:${httpCode} — LKG:${lkgId} — report:${reportPath}`
16
+ await notify(msg, opts)
17
+ }
18
+
19
+ export async function notify(msg: string, opts: NotifierOpts = {}): Promise<void> {
20
+ const send = opts.send ?? defaultSend
21
+ try {
22
+ await send(msg)
23
+ } catch {
24
+ // never block caller — rollback/report must not fail due to notifier
25
+ }
26
+ }
27
+
28
+ async function defaultSend(msg: string): Promise<void> {
29
+ // 1) Try hard dependency: @ddtcorex/dsh-maestro-notifier if installed (workspace:^)
30
+ try {
31
+ // dynamic import so daemon still runs when notifier is not installed (loose mode)
32
+ // @ts-ignore — optional hard dep, may not be installed
33
+ const mod: any = await import('@ddtcorex/dsh-maestro-notifier' as any).catch(() => null)
34
+ if (mod?.sendTelegram || mod?.notify) {
35
+ const fn = mod.sendTelegram ?? mod.notify
36
+ await fn(msg)
37
+ return
38
+ }
39
+ } catch {
40
+ // ignore and fall through
41
+ }
42
+ // 2) Try env Telegram token (TELEGRAM_BOT_TOKEN + TELEGRAM_CHAT_ID)
43
+ const token = process.env.TELEGRAM_BOT_TOKEN
44
+ const chatId = process.env.TELEGRAM_CHAT_ID
45
+ if (token && chatId) {
46
+ try {
47
+ await fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
48
+ method: 'POST',
49
+ headers: { 'Content-Type': 'application/json' },
50
+ body: JSON.stringify({ chat_id: chatId, text: msg, parse_mode: 'Markdown' }),
51
+ })
52
+ return
53
+ } catch {
54
+ // fall through to log
55
+ }
56
+ }
57
+ // 3) Fallback — log only, never throw
58
+ console.log(`[supervisor notify] ${msg}`)
59
+ }
60
+
61
+ export async function notifyCrash(reportPath: string, error: string, opts: NotifierOpts = {}): Promise<void> {
62
+ await notify(`CRASH detected → rollback (report: ${reportPath}, error: ${error})`, opts)
63
+ }
64
+
65
+ export async function notifyDegraded(id: string, error: string, opts: NotifierOpts = {}): Promise<void> {
66
+ await notify(`DEGRADED: ${id} failed — ${error}`, opts)
67
+ }
68
+
69
+ export async function notifyFixed(branch: string, sessions: string[], opts: NotifierOpts = {}): Promise<void> {
70
+ await notify(`FIXED: ${branch}, sessions resumed: [${sessions.join(', ')}]`, opts)
71
+ }
@@ -0,0 +1,70 @@
1
+ import * as fs from 'node:fs'
2
+ import * as path from 'node:path'
3
+
4
+ /**
5
+ * Resolve Maestro Harness root without hardcoding a machine-specific home path.
6
+ * Priority: env > walk up from current file > cwd check > homedir fallback (last resort).
7
+ */
8
+ export function resolveHarnessRoot(): string {
9
+ if (process.env.MAESTRO_HARNESS_ROOT) return process.env.MAESTRO_HARNESS_ROOT
10
+
11
+ // Walk up from this file's directory (works for both src and lib)
12
+ try {
13
+ // In ESM, __dirname is not available; use import.meta.url if possible, else process.cwd()
14
+ // Fallback to file path heuristic: supervisor is at packages/dsh-maestro-core/{src,lib}
15
+ const candidates: string[] = []
16
+ // Try to derive from current working file via stack-relative: use process.argv[1] or cwd
17
+ // Most reliable: check common locations relative to this file
18
+ // For compiled lib: lib/paths.js -> ../../.. = maestro-harness
19
+ // For src: src/host/paths.ts -> ../../.. = maestro-harness
20
+ const here = path.dirname(new URL(import.meta.url).pathname)
21
+ candidates.push(path.resolve(here, '../../..')) // lib -> maestro-harness
22
+ candidates.push(path.resolve(here, '../../../..')) // src/host -> maestro-harness
23
+ candidates.push(path.resolve(here, '../../../../..'))
24
+ candidates.push(process.cwd())
25
+
26
+ for (const c of candidates) {
27
+ try {
28
+ if (fs.existsSync(path.join(c, 'deepseek-harness', 'package.json')) && fs.existsSync(path.join(c, 'packages', 'dsh-maestro-core', 'package.json'))) {
29
+ return c
30
+ }
31
+ } catch {}
32
+ }
33
+ // Fallback to first candidate that exists
34
+ for (const c of candidates) {
35
+ if (fs.existsSync(c)) return c
36
+ }
37
+ } catch {}
38
+
39
+ // Last resort: cwd
40
+ return process.cwd()
41
+ }
42
+
43
+ export function resolveDeepseekHarnessDir(): string {
44
+ return path.join(resolveHarnessRoot(), 'deepseek-harness')
45
+ }
46
+
47
+ /**
48
+ * Resolve this package's own directory (the one holding its package.json),
49
+ * walking up from this file. Works from `src/host/` and from the built `lib/`,
50
+ * and from an npm install under `node_modules/@ddtcorex/dsh-maestro-core`
51
+ * — so no call site has to assume a workspace layout.
52
+ */
53
+ export function resolveSupervisorPackageDir(): string {
54
+ const here = path.dirname(new URL(import.meta.url).pathname)
55
+ let dir = here
56
+ for (let i = 0; i < 6; i++) {
57
+ try {
58
+ const pkg = path.join(dir, 'package.json')
59
+ if (fs.existsSync(pkg) && JSON.parse(fs.readFileSync(pkg, 'utf8')).name === '@ddtcorex/dsh-maestro-core') {
60
+ return dir
61
+ }
62
+ } catch {}
63
+ const up = path.dirname(dir)
64
+ if (up === dir) break
65
+ dir = up
66
+ }
67
+ // Fallback: one level above the dir this module was loaded from — `lib/` in
68
+ // production, `src/host/` from vitest. Only used when the walk above fails.
69
+ return path.resolve(here, '..')
70
+ }