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