@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
package/lib/cli.js ADDED
@@ -0,0 +1,336 @@
1
+ import { Supervisor } from './supervisor.js';
2
+ import { pollHealth } from './health-poller.js';
3
+ import { writeLKG, verifyLKG, isLkgExcluded, failureReason } from './snapshot.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 { isSelfCopyError, checkPlannedRestart, readRestartRequest, clearPlannedRestart } from './restart-guards.js';
9
+ import { readSupervisorConfig } from './config.js';
10
+ /**
11
+ * Make a destination (recursively) writable before overwriting it (D3).
12
+ *
13
+ * `fs.cpSync` copies into an existing destination file with
14
+ * `O_WRONLY|O_CREAT|O_TRUNC`, so a mode-`0400` object fails with EACCES and
15
+ * aborts the whole restore — the exact 2026-09-13 failure
16
+ * (`EACCES, Permission denied '.../attachments/v1/objects/f8'`). Only entries
17
+ * that actually lack the needed bit are chmod-ed, so a healthy tree costs
18
+ * stats, not a chmod per file.
19
+ */
20
+ function makeWritable(target) {
21
+ let st;
22
+ try {
23
+ st = fs.lstatSync(target);
24
+ }
25
+ catch {
26
+ return;
27
+ }
28
+ if (st.isSymbolicLink())
29
+ return;
30
+ if (st.isDirectory()) {
31
+ if ((st.mode & 0o300) !== 0o300) {
32
+ try {
33
+ fs.chmodSync(target, st.mode | 0o300);
34
+ }
35
+ catch { }
36
+ }
37
+ let names = [];
38
+ try {
39
+ names = fs.readdirSync(target);
40
+ }
41
+ catch {
42
+ return;
43
+ }
44
+ for (const name of names)
45
+ makeWritable(path.join(target, name));
46
+ return;
47
+ }
48
+ if ((st.mode & 0o200) === 0) {
49
+ try {
50
+ fs.chmodSync(target, st.mode | 0o200);
51
+ }
52
+ catch { }
53
+ }
54
+ }
55
+ /** Files (and symlinks) a restore of this source entry would write. */
56
+ function countRestorable(srcPath) {
57
+ try {
58
+ const st = fs.lstatSync(srcPath);
59
+ if (st.isDirectory())
60
+ return walkFiles(srcPath).length;
61
+ return 1;
62
+ }
63
+ catch {
64
+ return 0;
65
+ }
66
+ }
67
+ function walkFiles(dir, base = dir) {
68
+ const out = [];
69
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
70
+ const full = path.join(dir, entry.name);
71
+ if (entry.isDirectory())
72
+ out.push(...walkFiles(full, base));
73
+ else if (entry.isFile())
74
+ out.push(path.relative(base, full));
75
+ }
76
+ return out;
77
+ }
78
+ /**
79
+ * Copy a chosen LKG snapshot back into the DSH home. Recent snapshots are
80
+ * tried newest-first, skipping any that still carry a failing plugin so a
81
+ * broken bundle is not restored. `sessions/` and every other runtime-data entry
82
+ * is deliberately NOT restored (D1) — session logs are append-only truth and
83
+ * rolling them back to a snapshot would drop every turn recorded after that
84
+ * snapshot.
85
+ *
86
+ * Never throws for a per-entry failure: the failures are collected into
87
+ * `skipped` and the caller reports them (D2/D4). The only throw left is "there
88
+ * is no snapshot at all", which the caller must know about.
89
+ *
90
+ * @returns the restore summary (snapshot id + what was/was not restored).
91
+ */
92
+ export async function rollbackLKG(opts) {
93
+ const { dshHome, lkgRoot, failingPlugin } = opts;
94
+ const entries = fs.existsSync(lkgRoot) ? fs.readdirSync(lkgRoot).sort() : [];
95
+ if (!entries.length)
96
+ throw new Error('no LKG to rollback to');
97
+ const candidates = [...entries].reverse().slice(0, 3);
98
+ let chosen;
99
+ for (const cand of candidates) {
100
+ if (!failingPlugin) {
101
+ chosen = cand;
102
+ break;
103
+ }
104
+ try {
105
+ const pkgPath = path.join(lkgRoot, cand, 'profiles/web/package.json');
106
+ if (!fs.existsSync(pkgPath)) {
107
+ chosen = cand;
108
+ break;
109
+ }
110
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
111
+ const bundles = pkg?.dsh?.profile?.bundles ?? [];
112
+ const deps = pkg?.dependencies ?? {};
113
+ const hasFailing = bundles.some((b) => b.includes(failingPlugin)) || Object.keys(deps).some(k => k.includes(failingPlugin));
114
+ if (!hasFailing) {
115
+ chosen = cand;
116
+ break;
117
+ }
118
+ console.log(`[supervisor] skipping LKG ${cand} still contains failing plugin ${failingPlugin}`);
119
+ }
120
+ catch {
121
+ chosen = cand;
122
+ break;
123
+ }
124
+ }
125
+ const target = chosen ?? entries[entries.length - 1];
126
+ const src = path.join(lkgRoot, target);
127
+ const skipped = [];
128
+ let restored = 0;
129
+ for (const entry of fs.readdirSync(src)) {
130
+ if (entry === 'manifest.json')
131
+ continue;
132
+ if (isLkgExcluded(entry)) {
133
+ // Legacy snapshots (taken before D1) still carry runtime data. Restoring
134
+ // a stale sessions/ over live sessions can lose a log, and a 0400
135
+ // attachment blob is what aborted this very path — report, never restore.
136
+ skipped.push({ path: entry, reason: 'runtime data excluded from the LKG scope (not required to boot)' });
137
+ continue;
138
+ }
139
+ const srcPath = path.join(src, entry);
140
+ const destPath = path.join(dshHome, entry);
141
+ try {
142
+ // Skip if src and dest are the same file (e.g. symlink to same target like ~/.dsh/AGENTS.md)
143
+ try {
144
+ if (fs.existsSync(srcPath) && fs.existsSync(destPath) && fs.realpathSync(srcPath) === fs.realpathSync(destPath))
145
+ continue;
146
+ }
147
+ catch { }
148
+ makeWritable(destPath);
149
+ fs.cpSync(srcPath, destPath, { recursive: true, force: true });
150
+ restored += countRestorable(srcPath);
151
+ }
152
+ catch (e) {
153
+ if (isSelfCopyError(String(e?.message ?? '')))
154
+ continue;
155
+ skipped.push({ path: entry, reason: failureReason(e) });
156
+ }
157
+ }
158
+ return { target, restored, skipped };
159
+ }
160
+ export async function runCli(args) {
161
+ const cmd = args[2] ?? '--help';
162
+ if (cmd === '--help' || cmd === '-h' || cmd === 'help') {
163
+ console.log(`Usage: dsh-web-supervisor <command>
164
+
165
+ Commands:
166
+ daemon Run supervisor daemon (poll every 3s)
167
+ status Show health + LKG status
168
+ logs Tail supervisor reports
169
+ rollback --to <ts> Rollback to LKG <ts>
170
+ resume [--within <dur>] List interrupted sessions (filter by time, e.g. 5m, 30s, 1h)
171
+ boot-guard acquire|release --pid <pid> Take/release boot.lock + boot-boundary (used by the safe-restart script)
172
+ `);
173
+ return;
174
+ }
175
+ if (cmd === 'boot-guard') {
176
+ const { runBootGuardCli } = await import('./boot-guard.js');
177
+ process.exit(runBootGuardCli(args.slice(3)));
178
+ }
179
+ if (cmd === 'status') {
180
+ const health = await pollHealth();
181
+ console.log(`up: ${health.up}, httpCode: ${health.httpCode}, error: ${health.error ?? 'none'}`);
182
+ const lkgRoot = path.join(os.homedir(), '.dsh/.supervisor/lkg');
183
+ if (fs.existsSync(lkgRoot)) {
184
+ const entries = fs.readdirSync(lkgRoot).sort();
185
+ console.log(`LKG: ${entries.length} snapshots, latest: ${entries[entries.length - 1] ?? 'none'}`);
186
+ if (entries.length) {
187
+ const ok = await verifyLKG(path.join(lkgRoot, entries[entries.length - 1])).catch(() => false);
188
+ console.log(`latest LKG valid: ${ok}`);
189
+ }
190
+ }
191
+ else {
192
+ console.log('LKG: none');
193
+ }
194
+ return;
195
+ }
196
+ if (cmd === 'resume') {
197
+ const withinIdx = args.indexOf('--within');
198
+ let withinMs;
199
+ if (withinIdx !== -1) {
200
+ const raw = args[withinIdx + 1] ?? '';
201
+ const { parseDuration } = await import('./resume.js');
202
+ withinMs = parseDuration(raw);
203
+ if (withinMs === undefined) {
204
+ console.error(`invalid --within value: ${raw} (use e.g. 5m, 30s, 1h)`);
205
+ process.exit(1);
206
+ }
207
+ }
208
+ const { findInterrupted } = await import('./resume.js');
209
+ const res = await findInterrupted(undefined, withinMs !== undefined ? { withinMs } : undefined);
210
+ if (withinMs !== undefined) {
211
+ console.log(`interrupted within ${args[withinIdx + 1]}: ${res.interrupted.length}/${res.scanned}`);
212
+ }
213
+ else {
214
+ console.log(`interrupted: ${res.interrupted.length}/${res.scanned}`);
215
+ }
216
+ for (const id of res.interrupted)
217
+ console.log(id);
218
+ return;
219
+ }
220
+ if (cmd === 'daemon') {
221
+ console.log('[supervisor] starting daemon — poll every 3s, Ctrl+C to stop');
222
+ const dshHome = path.join(os.homedir(), '.dsh');
223
+ const lkgRoot = path.join(os.homedir(), '.dsh/.supervisor/lkg');
224
+ const failedRoot = path.join(os.homedir(), '.dsh/.supervisor/failed');
225
+ const reportsRoot = path.join(os.homedir(), '.dsh/.supervisor/reports');
226
+ const supervisor = new Supervisor({
227
+ pollHealth: () => pollHealth(),
228
+ writeLKG: () => writeLKG(dshHome, lkgRoot),
229
+ writeFailed: () => writeLKG(dshHome, failedRoot),
230
+ writeReport: async ({ ts, health, action, logTail, gitDiff }) => {
231
+ const { writeReport, collectGitDiff } = await import('./report.js');
232
+ const { collectLogTail } = await import('./health-poller.js');
233
+ // Prefer supervisor-provided tail/diff (from health.logTail); fallback to live collect
234
+ let tail = logTail ?? health.logTail ?? '';
235
+ if (!tail) {
236
+ try {
237
+ tail = await collectLogTail();
238
+ }
239
+ catch {
240
+ tail = '';
241
+ }
242
+ }
243
+ let diff = gitDiff ?? '';
244
+ if (!diff) {
245
+ try {
246
+ const harnessRoot = resolveHarnessRoot();
247
+ diff = await collectGitDiff(harnessRoot).catch(() => '');
248
+ if (!diff) {
249
+ // fallback: try git diff in cwd
250
+ const { execSync } = await import('node:child_process');
251
+ try {
252
+ diff = execSync('git diff 2>/dev/null | head -n 200', { encoding: 'utf-8', timeout: 2000 });
253
+ }
254
+ catch {
255
+ diff = '';
256
+ }
257
+ }
258
+ }
259
+ catch {
260
+ diff = '';
261
+ }
262
+ }
263
+ return writeReport({ reportsRoot, ts, health, gitDiff: diff, logTail: tail, action });
264
+ },
265
+ rollback: async () => {
266
+ const { execSync } = await import('node:child_process');
267
+ // Extract failing plugin from current log tail if possible
268
+ let failingPlugin;
269
+ try {
270
+ const tail = fs.readFileSync(path.join(os.homedir(), '.dsh/dsh-web.log'), 'utf8').slice(-5000);
271
+ const m = tail.match(/@ddtcorex\/dsh-maestro-[a-z0-9_-]+/i) ?? tail.match(/dsh-maestro-[a-z0-9_-]+/i);
272
+ if (m)
273
+ failingPlugin = m[0].replace(/^@ddtcorex\//, '');
274
+ }
275
+ catch { }
276
+ const res = await rollbackLKG({ dshHome, lkgRoot, failingPlugin });
277
+ console.log(`[supervisor] rolled back to ${res.target} — ${res.restored} file(s) restored${failingPlugin ? ` (avoiding ${failingPlugin})` : ''}`);
278
+ // D4: a partial restore is surfaced loudly, never silently.
279
+ if (res.skipped.length) {
280
+ console.log(`[supervisor] ROLLBACK PARTIAL: ${res.skipped.length} entr(ies) not restored`);
281
+ for (const s of res.skipped.slice(0, 10))
282
+ console.log(`[supervisor] skipped ${s.path}: ${s.reason}`);
283
+ if (res.skipped.length > 10)
284
+ console.log(`[supervisor] … ${res.skipped.length - 10} more`);
285
+ }
286
+ // Reconcile node_modules from restored package.json (critical for link: deps)
287
+ try {
288
+ execSync('pnpm --dir ~/.dsh/profiles/web install --silent', { timeout: 30000, stdio: 'pipe' });
289
+ console.log('[supervisor] pnpm install reconciled profiles/web');
290
+ }
291
+ catch (e) {
292
+ console.log(`[supervisor] pnpm install failed: ${e?.message ?? String(e)}`);
293
+ }
294
+ return res;
295
+ },
296
+ restartWeb: async () => {
297
+ // One implementation of the single-boot restart: marker (TTL = boot
298
+ // budget) → boot.lock → serialized systemd start → direct-node nohup
299
+ // only on hosts where the unit does not exist (D4/D5).
300
+ const { performSingleBootRestart, DEFAULT_BOOT_GRACE_MS } = await import('./restart-web.js');
301
+ let grace = DEFAULT_BOOT_GRACE_MS;
302
+ try {
303
+ const cfg = await readSupervisorConfig();
304
+ if (typeof cfg.bootGraceMs === 'number' && cfg.bootGraceMs > 0)
305
+ grace = cfg.bootGraceMs;
306
+ }
307
+ catch { }
308
+ const res = await performSingleBootRestart({ bootGraceMs: grace });
309
+ if (!res.restarted)
310
+ console.log(`[supervisor] restart skipped: ${res.reason ?? 'boot lock held'}`);
311
+ },
312
+ notify: async (msg) => console.log(`[notify] ${msg}`),
313
+ isPlannedRestartActive: () => checkPlannedRestart(),
314
+ // dsh_web_restart marker ownership: the daemon acts on the marker. After
315
+ // the restart, scan recent session logs for torn tails (an in-flight
316
+ // session truncated by the restart) and report; the marker is cleared in
317
+ // the supervisor's own finally block and again here as a safety net.
318
+ readRestartRequest: () => readRestartRequest(),
319
+ onRestartRequestHandled: async () => {
320
+ const { scanSessions } = await import('./scan.js');
321
+ const res = await scanSessions(path.join(os.homedir(), '.dsh'), { withinMs: 10 * 60 * 1000 }).catch(() => ({ scanned: 0, torn: [] }));
322
+ if (res.torn.length) {
323
+ console.log(`[supervisor] post-self-restart scan: ${res.torn.length} torn session log(s)`);
324
+ }
325
+ else {
326
+ console.log('[supervisor] post-self-restart scan: clean');
327
+ }
328
+ void clearPlannedRestart();
329
+ },
330
+ });
331
+ await supervisor.start();
332
+ // keep process alive
333
+ await new Promise(() => { });
334
+ }
335
+ console.log(`unknown command: ${cmd} — try --help`);
336
+ }