@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ddtcorex
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,209 @@
1
+ # dsh-maestro-core
2
+
3
+ Supervisor for DSH Web resilience — **Phase 1 Guard & Report + Phase 3 Auto-Resume & Auto-Reload** — together with the settings store, the Maestro settings card, the tool guard and the harness-to-harness sync engine that used to be four separate packages.
4
+
5
+ Runs **outside** the `pnpm → sh → node` tree (systemd daemon) to survive tree crashes, plus **inside** `dsh web` as a host+client Cordis plugin to auto-resume interrupted sessions and auto-reload the browser after restart.
6
+
7
+ - **Daemon:** Polls `:3080` every 3s, keeps last-known-good (LKG) snapshots (`~/.dsh/.supervisor/lkg/`, `rotate 3`, `sha256` verify, `df` >500MB guard), auto-rollbacks on crash (`debounce 60s`, `flock` lock), writes `report-<ts>.md` (health + `git diff` + log tail), and notifies via Telegram (loose, never blocks).
8
+ - **Host plugin:** `runAutoResume()` 8s after boot — `findInterrupted` (tail 100) + `findDanglingOpenTurns` (full scan for recent sessions) within `autoResumeWithin` (default 5m) → `agents.resume({resumeSessionId, agentOptions: {provider,model}})` recovered from `request/context` → `followup('continue')`. Loopback RPC `POST /dsh-maestro-supervisor-resume/{scan,resume}` (authority `loopback`) for the daemon (`resumeViaRpc`).
9
+ - **Client plugin:** Hybrid auto-reload — `fetch HEAD /` polling 1s on `offline`/`WebSocket close`/`visibilitychange` → `200` → `location.reload()`. Served as `window.__ModuleLoader__.load` bundle at `/plugins/@ddtcorex/dsh-maestro-core/client.js` via `dsh.client`.
10
+
11
+ ## Modules
12
+
13
+ One package, four host rows and one client bundle.
14
+
15
+ | Module | Source | Row id | Channel | What it does |
16
+ |---|---|---|---|---|
17
+ | Supervisor | `src/host/*.ts` | `maestro-supervisor` | `/dsh-maestro-supervisor-resume` (loopback) | Crash polling, LKG snapshots, auto-resume, auto-reload |
18
+ | Store | `src/host/store/` | — | — | The namespaced `settings.json` every other module reads and writes |
19
+ | Config | `src/host/config/` | `maestro-config` | `/dsh-maestro-config` | `maestroConfig` service over the store, backing the Maestro settings card |
20
+ | Guard | `src/host/guard/` | `dsh-maestro-guard` | `/dsh-maestro-guard` | Rule classification, the approval gate and its journal |
21
+ | Sync | `src/host/sync/` | `dsh-maestro-sync` | `/dsh-maestro-sync` | Backup, restore, retention GC and two-machine sync |
22
+
23
+ Row `name`s for the absorbed modules are subpaths of this package (`@ddtcorex/dsh-maestro-core/lib/<module>/index.js`), which is why `exports["./lib/*"]` exists: a row name the exports map cannot resolve is skipped silently at boot.
24
+
25
+ The store is also published on its own (`@ddtcorex/dsh-maestro-core/store`) and can be vendored into a consumer with `scripts/vendor-store.mjs`, which writes one self-verifying file with a body hash.
26
+
27
+ ## Install
28
+
29
+ One package, one command:
30
+
31
+ ```bash
32
+ dsh plugin --profile web add @ddtcorex/dsh-maestro-core
33
+ ```
34
+
35
+ In a workspace checkout, build and link instead:
36
+
37
+ ```bash
38
+ pnpm --dir packages/dsh-maestro-core install
39
+ pnpm --dir packages/dsh-maestro-core build # tsc host + tsc client + esbuild bundle -> lib/ + lib/client.js
40
+ pnpm --dir packages/dsh-maestro-core verify # tsc --noEmit host + client
41
+ pnpm --dir packages/dsh-maestro-core test # vitest run
42
+ test -f packages/dsh-maestro-core/lib/index.js
43
+ test -f packages/dsh-maestro-core/lib/client.js
44
+ # link:() the checkout into ~/.dsh/profiles/web/package.json, then
45
+ pnpm --dir ~/.dsh/profiles/web install
46
+ ```
47
+
48
+ `pnpm build` is required after any `src/` change; `lib/` is gitignored build output. The client needs both `tsc` steps and the `build-client.mjs` bundle — plain `tsc` alone leaves `lib/client.js` as a bare ES module and `dsh web` will fail with `exports no "./client" bundle`.
49
+
50
+ The package declares `dsh.client` (`platform: web`, `inject: ["@deepseek-ai/dsh-client-connection", "@deepseek-ai/dsh-client-ui-slots"]`) so the browser half is auto-loaded — no extra `dsh.client` flag needed.
51
+
52
+ **Pre-flight (required):** before adding to a live profile's `bundles`, dry-boot must pass:
53
+
54
+ ```bash
55
+ DSH_HOME=$(mktemp -d) pnpm --dir deepseek-harness dsh web --port 0 &
56
+ # wait for "dsh web: http://127.0.0.1:<port>" and curl 200, then kill
57
+ # This catches load-time failures (missing lib/index.js, stale build, bad cordis.patch.yml)
58
+ # that no in-code try/catch can catch. See dsh-safe-restart skill.
59
+ ```
60
+
61
+ This exact failure class caused `dsh web` outages on 2026-08-27 (missing `lib/index.js`). See `AGENTS.md` Conventions.
62
+
63
+ ### Systemd daemon (optional, for crash detection outside the tree)
64
+
65
+ ```bash
66
+ bash packages/dsh-maestro-core/scripts/install-systemd.sh
67
+ systemctl --user daemon-reload
68
+ systemctl --user enable --now dsh-web-supervisor
69
+ systemctl --user status dsh-web-supervisor
70
+ journalctl --user -u dsh-web-supervisor -f
71
+ ```
72
+
73
+ The template leaves `Environment=TELEGRAM_BOT_TOKEN`/`TELEGRAM_CHAT_ID` commented — uncomment via `systemctl --user edit dsh-web-supervisor` if you want Telegram, otherwise it logs only.
74
+
75
+ To run without systemd (foreground, for debugging):
76
+
77
+ ```bash
78
+ node packages/dsh-maestro-core/lib/index.js daemon # poll every 3s
79
+ node packages/dsh-maestro-core/lib/index.js status
80
+ node packages/dsh-maestro-core/lib/index.js logs --tail 50
81
+ ```
82
+
83
+ ## Configuration
84
+
85
+ All `autoResumeWithin` values are **minutes** when given as `number` (e.g. `5` → 5 minutes). Strings support `30s`/`5m`/`1h`. Precedence (highest first):
86
+
87
+ 1. **Cordis config** (`cordis.patch.yml` `config:` or `apply(ctx, config)`) — explicit per-install.
88
+ 2. **Env** `DSH_SUPERVISOR_AUTO_RESUME` / `DSH_SUPERVISOR_RESUME_WITHIN` (bare `5` in env → 5m for ergonomics).
89
+ 3. **Supervisor config** `~/.dsh/.supervisor/config.json` (`autoResumeEnabled`, `autoResumeWithin`).
90
+ 4. **Maestro settings** `~/.dsh/maestro/settings.json` (`domains.supervisor.*`).
91
+ 5. **Default:** `true` / `5`.
92
+
93
+ | Key | Type | Default | Env | File | Notes |
94
+ |-----|------|---------|-----|------|-------|
95
+ | `autoResumeEnabled` | `boolean` | `true` | `DSH_SUPERVISOR_AUTO_RESUME` (`1`/`true`/`yes`/`on`/`enabled` vs `0`/`false`/`no`/…) | `config.json: autoResumeEnabled`, `settings.json: domains.supervisor.autoResumeEnabled` | `false` → notify only |
96
+ | `autoResumeWithin` | `number` (minutes) or `string` (`5m`) | `5` | `DSH_SUPERVISOR_RESUME_WITHIN` | `config.json: autoResumeWithin`, `settings.json: domains.supervisor.autoResumeWithin` | Window for `findInterrupted`/`findDangling` (mtime + `event.time`) |
97
+
98
+ Example `~/.dsh/.supervisor/config.json`:
99
+
100
+ ```json
101
+ {
102
+ "autoResumeWithin": 5,
103
+ "autoResumeEnabled": true
104
+ }
105
+ ```
106
+
107
+ ## CLI
108
+
109
+ ```bash
110
+ node packages/dsh-maestro-core/lib/index.js --help
111
+ node packages/dsh-maestro-core/lib/index.js status
112
+ node packages/dsh-maestro-core/lib/index.js daemon # poll 3s, debounce 60s
113
+ node packages/dsh-maestro-core/lib/index.js logs --tail 50
114
+ node packages/dsh-maestro-core/lib/index.js rollback --latest
115
+ ```
116
+
117
+ ## RPC (loopback only, `authority: loopback`)
118
+
119
+ ```bash
120
+ # Scan (findInterrupted only, tail 100)
121
+ curl -s http://127.0.0.1:3080/dsh-maestro-supervisor-resume/scan -X POST \
122
+ -H 'content-type: application/json' \
123
+ -d '{"type":"client-request","rpcId":"r1","method":"scan","payload":{"withinMs":300000}}'
124
+ # → {"type":"server-response","rpcId":"r1","result":{"ok":true,"value":{"scanned":425,"interrupted":[]}}}
125
+
126
+ # Resume (re-attaches agent + followup continue, recovers provider/model)
127
+ curl -s http://127.0.0.1:3080/dsh-maestro-supervisor-resume/resume -X POST \
128
+ -H 'content-type: application/json' \
129
+ -d '{"type":"client-request","rpcId":"r2","method":"resume","payload":{"ids":["--example-project--/session-abc"]}}'
130
+ # → {"type":"server-response","rpcId":"r2","result":{"ok":true,"value":{"resumed":["--example-project--/session-abc"]}}}
131
+ # or {"ok":false,"error":{"code":"bad-request","message":"resume requires at least one session id"}}
132
+ ```
133
+
134
+ The daemon uses `resumeViaRpc()` (`supervisor.ts:24`) which POSTs the same envelope to `http://127.0.0.1:3080/dsh-maestro-supervisor-resume/resume` with `fetch` and validates `server-response` + `rpcId` + `result.ok`.
135
+
136
+ ## Auto-Resume Details
137
+
138
+ - **When:** `apply()` sets `setTimeout 8000` after boot, then `runAutoResume()` — only safe right after fresh boot when `dsh web` is sole owner (an open turn found then cannot belong to a still-running generation). `resumeInterrupted` additionally checks `agents.get(sessionId)` and skips if already live.
139
+ - **What:** `findInterrupted` (tail 100, looks for `turn/end` with `reason.kind === 'interrupted'` at `time` within window) + `findDanglingOpenTurns` (full scan for recent sessions, looks for `turn/start` without matching `turn/end` at `time` within window) → `merged = Set([...interrupted, ...dangling])` → `resumeInterrupted` for each id.
140
+ - **How:** `agents.get(sessionId)` if live → `followup('continue')`; else `sessionPersistence.load(sessionId)` → find `request/context` with `provider`/`model` → `agents.resume({resumeSessionId, agentOptions})` → `followup('continue')`. If `load` fails, still resumes without `agentOptions` (degrades). Returns `string[] resumed` and logs `sent continue trigger`.
141
+ - **Subagents:** `findDangling` does **full log scan** for recent sessions (mtime within window, 1-2 files) — not tail — because subagent `b6487e33` had its only `turn/start` at seq 6 at the very beginning of a 1906-line log, missed by `tail -100`. `findInterrupted` stays tail 100 (interrupted closer is always at tail). The mtime pre-filter keeps full scans cheap (previously 5.5s for 425 sessions without it).
142
+
143
+ ## Auto-Reload Details (Hybrid)
144
+
145
+ - **Client** (`src/client/auto-reload.ts`, `lib/client.js` via `window.__ModuleLoader__.load`): `ctx.effect` hooks `WebSocket` (patches `window.WebSocket` to catch `close` for same-origin DSH ws), `offline`/`online`, `visibilitychange` → `setInterval(fetch HEAD / 1s)` when down → `200` → `location.reload()` (once, `reloading` guard). Also checks `HEAD /` on load in case the page was opened while down.
146
+ - **Host** (`supervisor.ts` `pollHealth` 3s + `notify`, `plugin.ts` `runAutoResume`): health check + restart + notify is the host half; together with client polling they cover manual, supervisor, and systemd restarts without `F5`. No extra host push channel needed — client polling is primary, host health is secondary; the `window.__ModuleLoader__` bundle is served at `/plugins/@ddtcorex/dsh-maestro-core/client.js` via `ClientModuleRegistry` (`dsh.client` + `exports["./client"]`).
147
+
148
+ ## Verification
149
+
150
+ ```bash
151
+ # Build & unit
152
+ pnpm --dir packages/dsh-maestro-core verify # host + client
153
+ pnpm --dir packages/dsh-maestro-core test # vitest run
154
+ test -f packages/dsh-maestro-core/lib/index.js
155
+ test -f packages/dsh-maestro-core/lib/client.js
156
+ curl -s http://127.0.0.1:3080/plugins/@ddtcorex/dsh-maestro-core/client.js | grep -c "window.location.reload" # 2
157
+
158
+ # Live
159
+ curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3080/ # 200
160
+ curl -s http://127.0.0.1:3080/dsh-maestro-supervisor-resume/scan -X POST -H 'content-type: application/json' -d '{"type":"client-request","rpcId":"t","method":"scan","payload":{"withinMs":300000}}' | head -c 200
161
+ node --input-type=module -e "import {findDanglingOpenTurns} from './packages/dsh-maestro-core/lib/resume.js'; console.log(await findDanglingOpenTurns(undefined,{withinMs:5*60*1000}))"
162
+ # Create a real dangling: pnpm --dir deepseek-harness dsh --profile headless "Run bash synchronously sleep 60" & sleep 4; kill $!; node -e "...findDangling..." # should be 1
163
+ # After restart, it should have turn/end interrupted → continue → turn2
164
+ ```
165
+
166
+ ## Troubleshooting
167
+
168
+ | Symptom | Cause | Fix |
169
+ |---------|-------|-----|
170
+ | `Cannot find package '.../dsh-maestro-core/index.js'` | `pnpm build` not run or `lib/` stale | `pnpm --dir packages/dsh-maestro-core build && pnpm --dir ~/.dsh/profiles/web install` |
171
+ | `exports no "./client" bundle` / `client bundle not found` | Missing `lib/client.js` or `exports["./client"]` | `pnpm build` (runs `tsc` + `tsc -p tsconfig.client.json` + `node scripts/build-client.mjs`), check `package.json` `exports` and `dsh.client`, `test -f lib/client.js`, `curl .../client.js` |
172
+ | `EADDRINUSE ::3000` on `dsh web --port 0` | Old `MainThread` still holds `:3000`+`:3080` | `ss -tlnp | grep 3080` → pid, `kill <pid>` (same pid holds both), wait `ss` free. Never `pkill -f "dsh web"` — it kills the test shell. |
173
+ | `uses .jsonl but backend is zstd` | Hand-written `session.jsonl` while backend is `zstd` | Use `zstd -c plain.jsonl > session.jsonl.zstd` or `JsonlSessionPersistence` API. Never hand-write opposite encoding — `listArtifacts` checks every project dir on boot and one stray file blocks all of `dsh web`. |
174
+ | `first frame is not exactly one header line` | zstd without `type: session` header | Use `toHeaderLine` + `compressZstdFrame(header)` + `compressZstdFrame(body)` as in `encodeMaterialization`. |
175
+ | `findDangling` 0 but subagent still open | Tail window too small (before `63b7719`) | Fixed: `findDangling` now full-scans recent sessions (mtime within window). `findInterrupted` stays tail 100. |
176
+ | `resumed: []` or `RESUME FAILED` | `agents.resume` failed (no persistence, no provider/model) | Check `session.jsonl.zstd` exists and `zstd -d -c ... \| head -n 1` is valid header. `request/context` with `provider`/`model` is recovered — if missing, still resumes without `agentOptions`. |
177
+ | `RESUME SKIPPED` | No session within `autoResumeWithin` window | Increase `autoResumeWithin` to `10`/`"10m"`, check `config.json` and `DSH_SUPERVISOR_RESUME_WITHIN`, verify with `withinMs: 60*60*1000`. |
178
+ | Page does not reload after restart | `lib/client.js` not served or browser cache | `curl .../client.js | grep -c "window.location.reload"` → 2, hard refresh `Ctrl+Shift+R`, check `window.__ModuleLoader__` in console. Client polls `HEAD /` 1s on `offline`/`WS close`. |
179
+ | `dangling` found but `agents.get` says live | Session still live in current process (not a crash) | `findDangling` is only safe right after fresh boot when `dsh web` is sole owner. `resumeInterrupted` skips if `agents.get` is live — correct, wait for next boot. |
180
+
181
+ ## Known Issues
182
+
183
+ - **Manual `session.jsonl` vs `zstd`:** One stray opposite-encoding file under `~/.dsh/sessions/` blocks the entire `workspace` `listArtifacts` on every boot (`encodingMismatch`). See Troubleshooting.
184
+ - **Tail vs full scan:** Before `63b7719`, `b6487e33` subagent missed because its only `turn/start` was at seq 6 at the very beginning of a 1906-line log. Fixed, but if you add a new scan variant, reuse `readSessionAllLines` with mtime pre-filter.
185
+ - **Port pair:** One `MainThread` holds `:3080`+`:3000`. Use `ss -tlnp` + `kill <pid>` for the one pid, not `pkill -f`.
186
+ - **Client bundling:** `lib/client.js` must be `window.__ModuleLoader__.load` wrapper via `scripts/build-client.mjs`, not bare `export`. Add new client files under `src/client/` and ensure `tsconfig.client.json` includes them, then `pnpm build`.
187
+ - **Config precedence:** `cordis.patch.yml` `config:` > env (`DSH_SUPERVISOR_RESUME_WITHIN` bare `5` → 5m) > `config.json` > `settings.json` > default. See `plugin.ts:71` and `supervisor.ts:82`.
188
+
189
+ ## Development
190
+
191
+ ```sh
192
+ pnpm --dir packages/dsh-maestro-core verify
193
+ pnpm --dir packages/dsh-maestro-core test
194
+ pnpm --dir packages/dsh-maestro-core build
195
+ ```
196
+
197
+ For daemon changes: `DSH_HOME=$(mktemp -d) pnpm --dir deepseek-harness dsh web --port 0` + corrupt `settings.json` → assert `report` + `rollback`.
198
+
199
+ ## Telegram
200
+
201
+ Loose by default: `notifier.ts` tries `import('@ddtcorex/dsh-maestro-notifier')`, then `TELEGRAM_BOT_TOKEN`/`TELEGRAM_CHAT_ID` env, then `console.log`. Enable via `systemctl --user edit dsh-web-supervisor` → uncomment `Environment=TELEGRAM_*` → `daemon-reload` + `restart`.
202
+
203
+ Hard mode (optional): `package.json` add `"@ddtcorex/dsh-maestro-notifier": "workspace:^0.1.0"` + `pnpm-workspace.yaml` `packages: ["../dsh-maestro-notifier"]` → `pnpm install` links it.
204
+
205
+ ## See Also
206
+
207
+ - Spec: `<workspace-root>/docs/specs/2026-08-27-dsh-web-resilience-design.md`
208
+ - Skill: `skills/dsh-safe-restart/` (`restart-dsh-web.sh` with `dry_boot_and_verify()` and `--auto`)
209
+ - Client bundling: `dsh-maestro-mobile` (`scripts/build-client.mjs` pattern)
@@ -0,0 +1,43 @@
1
+ # dsh-maestro-core bundle patch.
2
+ #
3
+ # One package, four host rows. The daemon CLI (bin) and the standalone systemd
4
+ # unit are the supervisor's own runtime; the rows below are the modules that
5
+ # load inside DSH web.
6
+ #
7
+ # The supervisor row auto-resumes interrupted sessions after a DSH web restart.
8
+ # The standalone daemon (systemd) handles crash detection and web restart.
9
+ # Install with `dsh plugin --profile web add @ddtcorex/dsh-maestro-core`
10
+ - insert:
11
+ - id: maestro-supervisor
12
+ name: '@ddtcorex/dsh-maestro-core'
13
+ config:
14
+ autoResumeWithin: 5
15
+
16
+ # Backup, restore, retention GC and the Maestro Sync settings section.
17
+ # The row name is a subpath of this package, so `exports["./lib/*"]` has to
18
+ # admit it: a name the exports map does not resolve is skipped silently at
19
+ # boot. The name follows the package rename, not before it.
20
+ - id: dsh-maestro-sync
21
+ name: '@ddtcorex/dsh-maestro-core/lib/sync/index.js'
22
+ channel: /dsh-maestro-sync
23
+ # rpc.handle registers a webServer route inside an effect fiber
24
+ # which carries only the row's inject (not the module's);
25
+ # without webServer the row fails on harnesses that provide webServer after rows apply (DSH 0.1.5-rc.1+).
26
+ inject: ['tools', 'connection', 'webServer']
27
+
28
+ # Guard rules, journal and approval prompts. The channel is declared by the
29
+ # row only: guard exposes no rpc.handle today, it answers through the
30
+ # harness approval prompt.
31
+ - id: dsh-maestro-guard
32
+ name: '@ddtcorex/dsh-maestro-core/lib/guard/index.js'
33
+ channel: /dsh-maestro-guard
34
+
35
+ # The Maestro settings card service over the shared namespaced store.
36
+ # Same subpath name rule as the rows above.
37
+ - id: maestro-config
38
+ name: '@ddtcorex/dsh-maestro-core/lib/config/index.js'
39
+ # rpc.handle registers a webServer route inside an effect fiber which
40
+ # carries only the row's inject (not the module's); without webServer
41
+ # the row fails on harnesses that provide webServer after rows apply (DSH 0.1.5-rc.1+).
42
+ inject: ['connection', 'webServer']
43
+ config: {}
package/lib/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/lib/bin.js ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from './cli.js';
3
+ runCli(process.argv).catch(e => { console.error(e); process.exit(1); });
@@ -0,0 +1,33 @@
1
+ import { type BootLockDeps } from './boot-lock.js';
2
+ /**
3
+ * D6 — one restart implementation per concern.
4
+ *
5
+ * `performSingleBootRestart` (the daemon's path) takes `boot.lock` and appends
6
+ * the `[supervisor] boot-boundary` sentinel through `markBootBoundary()`. The
7
+ * manual skill script (`skills/dsh-safe-restart/scripts/restart-dsh-web.sh`)
8
+ * must do exactly the same, or a human restart is neither serialized with a
9
+ * supervised one (two boots racing for :3082) nor scoped in the append-only log
10
+ * (the poller reads the previous boot's crash as this boot's).
11
+ *
12
+ * This module is that shared entry point: the script shells out to
13
+ * `lib/bin.js boot-guard acquire|release --pid <shell pid>` instead of writing
14
+ * either marker itself.
15
+ */
16
+ /** Log the boundary sentinel belongs to (isolated home wins when set, for rehearsals). */
17
+ export declare function bootBoundaryLogPath(env?: NodeJS.ProcessEnv): string;
18
+ export interface BootGuard {
19
+ acquired: boolean;
20
+ release: () => void;
21
+ }
22
+ /**
23
+ * Acquire the shared boot lock for `deps.pid` and append the boundary sentinel.
24
+ * The sentinel is written first-thing after the lock, matching
25
+ * `performSingleBootRestart` (marker before the port goes down).
26
+ */
27
+ export declare function acquireBootGuard(deps?: BootLockDeps, logPath?: string): BootGuard;
28
+ /** Release the lock only if `pid` still owns it (see releaseBootLock). */
29
+ export declare function releaseBootGuard(pid: number, deps?: BootLockDeps): boolean;
30
+ export declare const BOOT_GUARD_BUSY_EXIT = 3;
31
+ export declare const BOOT_GUARD_USAGE_EXIT = 64;
32
+ /** CLI used by the skill script; returns the process exit code. */
33
+ export declare function runBootGuardCli(args: string[], deps?: BootLockDeps, logPath?: string): number;
@@ -0,0 +1,68 @@
1
+ import * as path from 'node:path';
2
+ import { acquireBootLock, releaseBootLock } from './boot-lock.js';
3
+ import { markBootBoundary, dshWebLogPath } from './restart-guards.js';
4
+ /**
5
+ * D6 — one restart implementation per concern.
6
+ *
7
+ * `performSingleBootRestart` (the daemon's path) takes `boot.lock` and appends
8
+ * the `[supervisor] boot-boundary` sentinel through `markBootBoundary()`. The
9
+ * manual skill script (`skills/dsh-safe-restart/scripts/restart-dsh-web.sh`)
10
+ * must do exactly the same, or a human restart is neither serialized with a
11
+ * supervised one (two boots racing for :3082) nor scoped in the append-only log
12
+ * (the poller reads the previous boot's crash as this boot's).
13
+ *
14
+ * This module is that shared entry point: the script shells out to
15
+ * `lib/bin.js boot-guard acquire|release --pid <shell pid>` instead of writing
16
+ * either marker itself.
17
+ */
18
+ /** Log the boundary sentinel belongs to (isolated home wins when set, for rehearsals). */
19
+ export function bootBoundaryLogPath(env = process.env) {
20
+ if (env.DSH_WEB_LOG)
21
+ return env.DSH_WEB_LOG;
22
+ if (env.DSH_HOME)
23
+ return path.join(env.DSH_HOME, 'dsh-web.log');
24
+ return dshWebLogPath();
25
+ }
26
+ /**
27
+ * Acquire the shared boot lock for `deps.pid` and append the boundary sentinel.
28
+ * The sentinel is written first-thing after the lock, matching
29
+ * `performSingleBootRestart` (marker before the port goes down).
30
+ */
31
+ export function acquireBootGuard(deps = {}, logPath) {
32
+ const lock = acquireBootLock(deps);
33
+ if (!lock)
34
+ return { acquired: false, release: () => { } };
35
+ markBootBoundary(logPath ?? bootBoundaryLogPath());
36
+ return { acquired: true, release: lock.release };
37
+ }
38
+ /** Release the lock only if `pid` still owns it (see releaseBootLock). */
39
+ export function releaseBootGuard(pid, deps = {}) {
40
+ return releaseBootLock(pid, deps);
41
+ }
42
+ export const BOOT_GUARD_BUSY_EXIT = 3;
43
+ export const BOOT_GUARD_USAGE_EXIT = 64;
44
+ /** CLI used by the skill script; returns the process exit code. */
45
+ export function runBootGuardCli(args, deps = {}, logPath) {
46
+ const action = args[0];
47
+ const pidIdx = args.indexOf('--pid');
48
+ const pid = pidIdx === -1 ? Number.NaN : Number(args[pidIdx + 1]);
49
+ if (!Number.isInteger(pid) || pid <= 0) {
50
+ console.error('boot-guard: --pid <owner pid> is required (pass the shell PID: $$)');
51
+ return BOOT_GUARD_USAGE_EXIT;
52
+ }
53
+ if (action === 'acquire') {
54
+ const guard = acquireBootGuard({ ...deps, pid }, logPath);
55
+ if (!guard.acquired) {
56
+ console.error('busy: another boot holds boot.lock');
57
+ return BOOT_GUARD_BUSY_EXIT;
58
+ }
59
+ console.log('acquired');
60
+ return 0;
61
+ }
62
+ if (action === 'release') {
63
+ releaseBootGuard(pid, deps);
64
+ return 0;
65
+ }
66
+ console.error(`boot-guard: unknown action: ${action ?? ''} (expected acquire|release)`);
67
+ return BOOT_GUARD_USAGE_EXIT;
68
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * One-boot-at-a-time guard (spec D4, incident 2026-09-13). Every path that
3
+ * starts dsh web takes this lock from the moment the restart is issued until
4
+ * the port answers, so a racing tick, the dsh_web_restart hand-off, or a
5
+ * rollback that fires while the first boot is still coming up skips instead of
6
+ * producing the second systemd start that made the incident's log tail toxic.
7
+ *
8
+ * The lock is an atomically created file (`O_EXCL`) carrying `{pid, ts}`. An
9
+ * existing lock is honored unless its owner is gone or it has outlived
10
+ * `staleMs` (the boot budget). Node exposes no flock(2) binding; O_EXCL plus
11
+ * PID liveness gives the same mutual exclusion deterministically, and every
12
+ * side effect is injectable so tests never touch the real ~/.dsh/.supervisor.
13
+ */
14
+ export declare const DEFAULT_BOOT_LOCK_STALE_MS = 180000;
15
+ export interface BootLockDeps {
16
+ lockPath?: string;
17
+ createExclusive?: (p: string, body: string) => boolean;
18
+ readLock?: (p: string) => string | undefined;
19
+ remove?: (p: string) => void;
20
+ pidAlive?: (pid: number) => boolean;
21
+ now?: () => number;
22
+ staleMs?: number;
23
+ sleep?: (ms: number) => Promise<void>;
24
+ portUp?: () => Promise<boolean>;
25
+ waitTimeoutMs?: number;
26
+ pollMs?: number;
27
+ /**
28
+ * Owner recorded in the lock file; defaults to this process. The skill script
29
+ * (D6) holds the lock with the shell's own PID, so liveness stays meaningful
30
+ * while the shell performs the restart.
31
+ */
32
+ pid?: number;
33
+ }
34
+ export interface BootLock {
35
+ path: string;
36
+ release: () => void;
37
+ }
38
+ export declare function bootLockPath(): string;
39
+ /** Take the boot lock, or return undefined when another live boot owns it. */
40
+ export declare function acquireBootLock(deps?: BootLockDeps): BootLock | undefined;
41
+ /**
42
+ * Release the lock only when `pid` still owns it. A boot that lost the race (or
43
+ * whose stale lock was taken over) must never delete the winner's lock file.
44
+ */
45
+ export declare function releaseBootLock(pid: number, deps?: BootLockDeps): boolean;
46
+ /** Poll the port until it answers or the boot budget expires. */
47
+ export declare function waitForPort(deps?: BootLockDeps): Promise<boolean>;
48
+ /**
49
+ * Run `fn` under the boot lock, then hold the lock until the port answers (or
50
+ * the boot budget expires). Returns `{ acquired: false }` — without running
51
+ * `fn` — when another boot already owns the lock.
52
+ */
53
+ export declare function withBootLock<T>(fn: () => Promise<T>, deps?: BootLockDeps): Promise<{
54
+ acquired: boolean;
55
+ value?: T;
56
+ }>;
@@ -0,0 +1,155 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import * as os from 'node:os';
4
+ /**
5
+ * One-boot-at-a-time guard (spec D4, incident 2026-09-13). Every path that
6
+ * starts dsh web takes this lock from the moment the restart is issued until
7
+ * the port answers, so a racing tick, the dsh_web_restart hand-off, or a
8
+ * rollback that fires while the first boot is still coming up skips instead of
9
+ * producing the second systemd start that made the incident's log tail toxic.
10
+ *
11
+ * The lock is an atomically created file (`O_EXCL`) carrying `{pid, ts}`. An
12
+ * existing lock is honored unless its owner is gone or it has outlived
13
+ * `staleMs` (the boot budget). Node exposes no flock(2) binding; O_EXCL plus
14
+ * PID liveness gives the same mutual exclusion deterministically, and every
15
+ * side effect is injectable so tests never touch the real ~/.dsh/.supervisor.
16
+ */
17
+ export const DEFAULT_BOOT_LOCK_STALE_MS = 180_000;
18
+ export function bootLockPath() {
19
+ return process.env.DSH_SUPERVISOR_BOOT_LOCK ?? path.join(os.homedir(), '.dsh/.supervisor/boot.lock');
20
+ }
21
+ function resolved(deps) {
22
+ return {
23
+ lockPath: deps.lockPath ?? bootLockPath(),
24
+ createExclusive: deps.createExclusive ?? ((p, body) => {
25
+ try {
26
+ fs.mkdirSync(path.dirname(p), { recursive: true });
27
+ fs.writeFileSync(p, body, { flag: 'wx', mode: 0o600 });
28
+ return true;
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ }),
34
+ readLock: deps.readLock ?? ((p) => {
35
+ try {
36
+ return fs.readFileSync(p, 'utf8');
37
+ }
38
+ catch {
39
+ return undefined;
40
+ }
41
+ }),
42
+ remove: deps.remove ?? ((p) => { try {
43
+ fs.unlinkSync(p);
44
+ }
45
+ catch { } }),
46
+ pidAlive: deps.pidAlive ?? ((pid) => {
47
+ if (!Number.isInteger(pid) || pid <= 0)
48
+ return false;
49
+ if (pid === process.pid)
50
+ return true;
51
+ try {
52
+ process.kill(pid, 0);
53
+ return true;
54
+ }
55
+ catch {
56
+ return false;
57
+ }
58
+ }),
59
+ now: deps.now ?? (() => Date.now()),
60
+ staleMs: deps.staleMs ?? DEFAULT_BOOT_LOCK_STALE_MS,
61
+ sleep: deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms))),
62
+ portUp: deps.portUp ?? defaultPortUp,
63
+ waitTimeoutMs: deps.waitTimeoutMs ?? DEFAULT_BOOT_LOCK_STALE_MS,
64
+ pollMs: deps.pollMs ?? 3_000,
65
+ pid: deps.pid ?? process.pid,
66
+ };
67
+ }
68
+ function parseLock(raw) {
69
+ if (!raw)
70
+ return undefined;
71
+ try {
72
+ const j = JSON.parse(raw);
73
+ if (typeof j?.pid === 'number' && typeof j?.ts === 'number')
74
+ return { pid: j.pid, ts: j.ts };
75
+ }
76
+ catch { }
77
+ return undefined;
78
+ }
79
+ /** Take the boot lock, or return undefined when another live boot owns it. */
80
+ export function acquireBootLock(deps = {}) {
81
+ const d = resolved(deps);
82
+ const body = JSON.stringify({ pid: d.pid, ts: d.now() });
83
+ const take = () => d.createExclusive(d.lockPath, body) ? { path: d.lockPath, release: () => d.remove(d.lockPath) } : undefined;
84
+ const first = take();
85
+ if (first)
86
+ return first;
87
+ const existing = parseLock(d.readLock(d.lockPath));
88
+ const stale = existing === undefined || !d.pidAlive(existing.pid) || d.now() - existing.ts > d.staleMs;
89
+ if (!stale)
90
+ return undefined;
91
+ d.remove(d.lockPath);
92
+ return take();
93
+ }
94
+ /**
95
+ * Release the lock only when `pid` still owns it. A boot that lost the race (or
96
+ * whose stale lock was taken over) must never delete the winner's lock file.
97
+ */
98
+ export function releaseBootLock(pid, deps = {}) {
99
+ const d = resolved(deps);
100
+ const existing = parseLock(d.readLock(d.lockPath));
101
+ if (existing === undefined || existing.pid !== pid)
102
+ return false;
103
+ d.remove(d.lockPath);
104
+ return true;
105
+ }
106
+ async function defaultPortUp() {
107
+ try {
108
+ const ctrl = new AbortController();
109
+ const t = setTimeout(() => ctrl.abort(), 2000);
110
+ try {
111
+ // Any HTTP answer (200/303/401) means the boot is serving.
112
+ await fetch('http://127.0.0.1:3080/', { signal: ctrl.signal });
113
+ return true;
114
+ }
115
+ finally {
116
+ clearTimeout(t);
117
+ }
118
+ }
119
+ catch {
120
+ return false;
121
+ }
122
+ }
123
+ /** Poll the port until it answers or the boot budget expires. */
124
+ export async function waitForPort(deps = {}) {
125
+ const d = resolved(deps);
126
+ const deadline = d.now() + d.waitTimeoutMs;
127
+ for (;;) {
128
+ try {
129
+ if (await d.portUp())
130
+ return true;
131
+ }
132
+ catch { }
133
+ if (d.now() >= deadline)
134
+ return false;
135
+ await d.sleep(d.pollMs);
136
+ }
137
+ }
138
+ /**
139
+ * Run `fn` under the boot lock, then hold the lock until the port answers (or
140
+ * the boot budget expires). Returns `{ acquired: false }` — without running
141
+ * `fn` — when another boot already owns the lock.
142
+ */
143
+ export async function withBootLock(fn, deps = {}) {
144
+ const lock = acquireBootLock(deps);
145
+ if (!lock)
146
+ return { acquired: false };
147
+ try {
148
+ const value = await fn();
149
+ await waitForPort(deps);
150
+ return { acquired: true, value };
151
+ }
152
+ finally {
153
+ lock.release();
154
+ }
155
+ }
package/lib/cli.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ export interface RestoreResult {
2
+ /** Snapshot id that was restored. */
3
+ target: string;
4
+ /** Files (and symlinks) restored into the live DSH home. */
5
+ restored: number;
6
+ /** Entries that were not restored, each with a reason. Never silent. */
7
+ skipped: Array<{
8
+ path: string;
9
+ reason: string;
10
+ }>;
11
+ }
12
+ /**
13
+ * Copy a chosen LKG snapshot back into the DSH home. Recent snapshots are
14
+ * tried newest-first, skipping any that still carry a failing plugin so a
15
+ * broken bundle is not restored. `sessions/` and every other runtime-data entry
16
+ * is deliberately NOT restored (D1) — session logs are append-only truth and
17
+ * rolling them back to a snapshot would drop every turn recorded after that
18
+ * snapshot.
19
+ *
20
+ * Never throws for a per-entry failure: the failures are collected into
21
+ * `skipped` and the caller reports them (D2/D4). The only throw left is "there
22
+ * is no snapshot at all", which the caller must know about.
23
+ *
24
+ * @returns the restore summary (snapshot id + what was/was not restored).
25
+ */
26
+ export declare function rollbackLKG(opts: {
27
+ dshHome: string;
28
+ lkgRoot: string;
29
+ failingPlugin?: string;
30
+ }): Promise<RestoreResult>;
31
+ export declare function runCli(args: string[]): Promise<void>;