@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,73 @@
1
+ /**
2
+ * Agent-preset composition for resumed sessions.
3
+ *
4
+ * `agents.resume()` composes an agent's scoped world ONLY through
5
+ * `ResumeAgentOptions.setup`; without it the agent is published joined to no
6
+ * preset and its tool view collapses to the deployment-global layer (2026-09-14
7
+ * incident). This module owns the three facts the supervisor needs: which preset
8
+ * a session records, how to compose it on a fresh agent context, and whether a
9
+ * live agent is actually joined to one — the roster's own answer
10
+ * (`agentPresets.composedPreset`), never a tool count.
11
+ * @module @ddtcorex/dsh-maestro-core/preset
12
+ */
13
+ /** Injectable seams for the preset readers/composers; every one is optional. */
14
+ export interface PresetDeps {
15
+ /** Read the preset id a session records. Default: projection → persisted header → raw log. */
16
+ readPresetId?: (sessionId: string) => Promise<string | undefined>;
17
+ /** Compose a preset on one agent context. Default: `agentPresets.mount`. */
18
+ mount?: (agentCtx: unknown, presetId: string) => Promise<unknown>;
19
+ /** Re-link one agent context to a preset. Default: `agentPresets.recompose`. */
20
+ recompose?: (agentCtx: unknown, presetId: string) => Promise<unknown>;
21
+ }
22
+ /**
23
+ * The preset a live agent is joined to, or undefined when it joined none.
24
+ *
25
+ * This is the authoritative composition fact: the roster records the binding it
26
+ * made for each agent scope.
27
+ * @param ctx - plugin context providing the optional `agentPresets` service.
28
+ * @param agent - the live agent (its `ctx` carries the scope the roster keys by).
29
+ * @returns the composed preset id, or undefined when there is none.
30
+ */
31
+ export declare function composedPresetId(ctx: any, agent: any): string | undefined;
32
+ /**
33
+ * The preset id a session records, in authority order: the attached session's
34
+ * `agentPreset` projection, the persisted session header, then the raw log's
35
+ * first line. A session that records none is a legitimately bare agent (created
36
+ * by ACP/headless), so undefined is a valid answer rather than an error.
37
+ * @param ctx - plugin context providing the optional session services.
38
+ * @param sessionId - the session whose preset is being resolved.
39
+ * @returns the recorded preset id, or undefined when the session records none.
40
+ */
41
+ export declare function resolveSessionPresetId(ctx: any, sessionId: string): Promise<string | undefined>;
42
+ /**
43
+ * Build the `setup` callback that joins an agent to its preset. The factory
44
+ * awaits it before publishing the agent, so the first request already carries
45
+ * the preset's tools. Without the roster service this degrades to "no
46
+ * composition" — the caller verifies the result and repairs rather than
47
+ * resuming blind.
48
+ * @param ctx - plugin context providing the optional `agentPresets` service.
49
+ * @param presetId - the preset the session records.
50
+ * @param deps - optional seams; `mount` overrides the roster call.
51
+ * @returns the setup callback handed to `agents.resume`.
52
+ */
53
+ export declare function makePresetSetup(ctx: any, presetId: string, deps?: PresetDeps): (agentCtx: unknown, agent?: unknown) => Promise<void>;
54
+ /** Outcome of one repair attempt; `reason` is the operator-facing classification. */
55
+ export interface RepairOutcome {
56
+ repaired: boolean;
57
+ presetId?: string;
58
+ reason: 'repaired' | 'already-composed' | 'no-preset-recorded' | 'no-live-agent' | 'recompose-failed';
59
+ composedAfter?: string;
60
+ }
61
+ /**
62
+ * Re-link a live agent that joined no preset.
63
+ *
64
+ * `recompose` on an agent whose binding is absent IS its first bind, so this is
65
+ * a mount in effect: it emits `tools/change`, and the next request records
66
+ * `request/header reason=change` with the restored tool set. Never throws — a
67
+ * failure is reported in the outcome so the caller can notify and park.
68
+ * @param ctx - plugin context providing `agents` and `agentPresets`.
69
+ * @param sessionId - the session whose live agent is repaired.
70
+ * @param deps - optional seams for tests.
71
+ * @returns the repair outcome.
72
+ */
73
+ export declare function repairAgentPreset(ctx: any, sessionId: string, deps?: PresetDeps): Promise<RepairOutcome>;
package/lib/preset.js ADDED
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Agent-preset composition for resumed sessions.
3
+ *
4
+ * `agents.resume()` composes an agent's scoped world ONLY through
5
+ * `ResumeAgentOptions.setup`; without it the agent is published joined to no
6
+ * preset and its tool view collapses to the deployment-global layer (2026-09-14
7
+ * incident). This module owns the three facts the supervisor needs: which preset
8
+ * a session records, how to compose it on a fresh agent context, and whether a
9
+ * live agent is actually joined to one — the roster's own answer
10
+ * (`agentPresets.composedPreset`), never a tool count.
11
+ * @module @ddtcorex/dsh-maestro-core/preset
12
+ */
13
+ import * as fs from 'node:fs';
14
+ import * as path from 'node:path';
15
+ import * as os from 'node:os';
16
+ import { execSync } from 'node:child_process';
17
+ import { resolveSessionLogPath } from './resume.js';
18
+ /**
19
+ * The preset a live agent is joined to, or undefined when it joined none.
20
+ *
21
+ * This is the authoritative composition fact: the roster records the binding it
22
+ * made for each agent scope.
23
+ * @param ctx - plugin context providing the optional `agentPresets` service.
24
+ * @param agent - the live agent (its `ctx` carries the scope the roster keys by).
25
+ * @returns the composed preset id, or undefined when there is none.
26
+ */
27
+ export function composedPresetId(ctx, agent) {
28
+ try {
29
+ const presets = ctx?.get?.('agentPresets') ?? ctx?.agentPresets;
30
+ const agentCtx = agent?.ctx;
31
+ if (typeof presets?.composedPreset !== 'function' || agentCtx === undefined)
32
+ return undefined;
33
+ const id = presets.composedPreset(agentCtx);
34
+ return typeof id === 'string' && id.length > 0 ? id : undefined;
35
+ }
36
+ catch {
37
+ /* an unreadable roster is "not composed", which the caller verifies and repairs */
38
+ return undefined;
39
+ }
40
+ }
41
+ /**
42
+ * The preset id a session records, in authority order: the attached session's
43
+ * `agentPreset` projection, the persisted session header, then the raw log's
44
+ * first line. A session that records none is a legitimately bare agent (created
45
+ * by ACP/headless), so undefined is a valid answer rather than an error.
46
+ * @param ctx - plugin context providing the optional session services.
47
+ * @param sessionId - the session whose preset is being resolved.
48
+ * @returns the recorded preset id, or undefined when the session records none.
49
+ */
50
+ export async function resolveSessionPresetId(ctx, sessionId) {
51
+ try {
52
+ const sessions = ctx?.get?.('sessions') ?? ctx?.sessions;
53
+ const session = typeof sessions?.get === 'function' ? sessions.get(sessionId) : undefined;
54
+ if (session !== undefined) {
55
+ const projections = ctx?.get?.('sessionProjections') ?? ctx?.sessionProjections;
56
+ const id = typeof projections?.stateOf === 'function' ? projections.stateOf(session, 'agentPreset') : undefined;
57
+ if (typeof id === 'string' && id.length > 0)
58
+ return id;
59
+ }
60
+ }
61
+ catch { }
62
+ try {
63
+ const query = ctx?.get?.('sessionQuery') ?? ctx?.sessionQuery;
64
+ if (typeof query?.observeSession === 'function') {
65
+ const observation = await query.observeSession(sessionId);
66
+ const id = observation?.header?.agentPreset;
67
+ if (typeof id === 'string' && id.length > 0)
68
+ return id;
69
+ }
70
+ }
71
+ catch { }
72
+ return readPresetIdFromRawLog(sessionId);
73
+ }
74
+ /**
75
+ * Read the preset out of a session's raw log. The first line is the `type:
76
+ * "session"` header, which carries the creation-time `agentPreset` even when no
77
+ * service can open the session. Root resolution mirrors the session-health scan
78
+ * (`SESSIONS_ROOT`, else `DSH_HOME/sessions`).
79
+ */
80
+ function readPresetIdFromRawLog(sessionId) {
81
+ const root = process.env.SESSIONS_ROOT
82
+ || path.join(process.env.DSH_HOME || path.join(os.homedir(), '.dsh'), 'sessions');
83
+ try {
84
+ for (const group of fs.readdirSync(root, { withFileTypes: true })) {
85
+ if (!group.isDirectory())
86
+ continue;
87
+ const logPath = resolveSessionLogPath(path.join(root, group.name, sessionId));
88
+ if (logPath === undefined)
89
+ continue;
90
+ const line = logPath.endsWith('.zstd')
91
+ ? execSync(`zstd -d -c ${JSON.stringify(logPath)} 2>/dev/null | head -1`, { encoding: 'utf-8' })
92
+ : fs.readFileSync(logPath, 'utf-8').split('\n')[0] ?? '';
93
+ const id = JSON.parse(line)?.agentPreset;
94
+ if (typeof id === 'string' && id.length > 0)
95
+ return id;
96
+ }
97
+ }
98
+ catch { }
99
+ return undefined;
100
+ }
101
+ /**
102
+ * Build the `setup` callback that joins an agent to its preset. The factory
103
+ * awaits it before publishing the agent, so the first request already carries
104
+ * the preset's tools. Without the roster service this degrades to "no
105
+ * composition" — the caller verifies the result and repairs rather than
106
+ * resuming blind.
107
+ * @param ctx - plugin context providing the optional `agentPresets` service.
108
+ * @param presetId - the preset the session records.
109
+ * @param deps - optional seams; `mount` overrides the roster call.
110
+ * @returns the setup callback handed to `agents.resume`.
111
+ */
112
+ export function makePresetSetup(ctx, presetId, deps = {}) {
113
+ const mount = deps.mount ?? ((agentCtx, agent) => {
114
+ void agent;
115
+ const presets = ctx?.get?.('agentPresets') ?? ctx?.agentPresets;
116
+ if (typeof presets?.mount !== 'function')
117
+ return Promise.resolve(undefined);
118
+ return presets.mount(agentCtx, presetId);
119
+ });
120
+ return async (agentCtx, agent) => { await mount(agentCtx, presetId); };
121
+ }
122
+ /**
123
+ * Re-link a live agent that joined no preset.
124
+ *
125
+ * `recompose` on an agent whose binding is absent IS its first bind, so this is
126
+ * a mount in effect: it emits `tools/change`, and the next request records
127
+ * `request/header reason=change` with the restored tool set. Never throws — a
128
+ * failure is reported in the outcome so the caller can notify and park.
129
+ * @param ctx - plugin context providing `agents` and `agentPresets`.
130
+ * @param sessionId - the session whose live agent is repaired.
131
+ * @param deps - optional seams for tests.
132
+ * @returns the repair outcome.
133
+ */
134
+ export async function repairAgentPreset(ctx, sessionId, deps = {}) {
135
+ try {
136
+ const agents = ctx?.get?.('agents') ?? ctx?.agents;
137
+ const agent = typeof agents?.get === 'function' ? agents.get(sessionId) : undefined;
138
+ if (agent === undefined)
139
+ return { repaired: false, reason: 'no-live-agent' };
140
+ const current = composedPresetId(ctx, agent);
141
+ if (current !== undefined)
142
+ return { repaired: false, reason: 'already-composed', composedAfter: current };
143
+ const presetId = deps.readPresetId !== undefined ? await deps.readPresetId(sessionId) : await resolveSessionPresetId(ctx, sessionId);
144
+ if (presetId === undefined)
145
+ return { repaired: false, reason: 'no-preset-recorded' };
146
+ const recompose = deps.recompose ?? ((agentCtx, id) => {
147
+ const presets = ctx?.get?.('agentPresets') ?? ctx?.agentPresets;
148
+ if (typeof presets?.recompose !== 'function')
149
+ throw new Error('agentPresets.recompose is unavailable');
150
+ return presets.recompose(agentCtx, id);
151
+ });
152
+ await recompose(agent.ctx, presetId);
153
+ return { repaired: true, presetId, reason: 'repaired', composedAfter: composedPresetId(ctx, agent) };
154
+ }
155
+ catch {
156
+ return { repaired: false, reason: 'recompose-failed' };
157
+ }
158
+ }
@@ -0,0 +1,11 @@
1
+ import type { HealthState } from './health-poller.js';
2
+ export interface ReportOpts {
3
+ reportsRoot: string;
4
+ ts: string;
5
+ health: HealthState;
6
+ gitDiff: string;
7
+ logTail: string;
8
+ action: string;
9
+ }
10
+ export declare function writeReport(opts: ReportOpts): Promise<string>;
11
+ export declare function collectGitDiff(workspaceRoot: string): Promise<string>;
package/lib/report.js ADDED
@@ -0,0 +1,58 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ export async function writeReport(opts) {
4
+ fs.mkdirSync(opts.reportsRoot, { recursive: true });
5
+ const fileName = `report-${opts.ts}.md`;
6
+ const filePath = path.join(opts.reportsRoot, fileName);
7
+ const content = `# DSH Web Crash Report — ${opts.ts}
8
+
9
+ **Action:** ${opts.action}
10
+
11
+ ## Health Snapshot
12
+
13
+ - up: ${opts.health.up}
14
+ - httpCode: ${opts.health.httpCode ?? 'n/a'}
15
+ - error: ${opts.health.error ?? 'none'}
16
+ - degraded: ${opts.health.degraded ?? false}
17
+
18
+ ## Git Diff (link plugins)
19
+
20
+ \`\`\`diff
21
+ ${opts.gitDiff || '(no changes)'}
22
+ \`\`\`
23
+
24
+ ## Log Tail (last 200 lines)
25
+
26
+ \`\`\`
27
+ ${opts.logTail.slice(-5000) || '(empty)'}
28
+ \`\`\`
29
+
30
+ ## Next Steps
31
+
32
+ - Check \`~/.dsh/.supervisor/lkg/\` for last-known-good
33
+ - Review \`failed/${opts.ts}/\` snapshot
34
+ - If degraded, fix the listed plugin row and run \`pnpm verify\` + dry-boot
35
+
36
+ ---
37
+ *Generated by dsh-web-supervisor*
38
+ `;
39
+ fs.writeFileSync(filePath, content);
40
+ return filePath;
41
+ }
42
+ export async function collectGitDiff(workspaceRoot) {
43
+ try {
44
+ const { execSync } = await import('node:child_process');
45
+ // Reports the workspace's own uncommitted changes. It does NOT inspect a
46
+ // profile: the link: scan a crash report would be most useful for lives in
47
+ // the dsh-safe-restart preflight, which reads the dump-config bundle headers.
48
+ const out = execSync('git -C ' + JSON.stringify(workspaceRoot) + ' status --porcelain 2>/dev/null || true', { encoding: 'utf-8' });
49
+ if (out.trim()) {
50
+ const diff = execSync('git -C ' + JSON.stringify(workspaceRoot) + ' diff 2>/dev/null | head -n 200', { encoding: 'utf-8' });
51
+ return diff || out;
52
+ }
53
+ return '';
54
+ }
55
+ catch {
56
+ return '';
57
+ }
58
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Serialized systemd restart for `dsh-web.service`: stop, wait until the
3
+ * unit is inactive, then start — instead of one raw `systemctl restart`
4
+ * that boots the new process while the old one still holds :3082 and
5
+ * crash-loops on EADDRINUSE (2026-09-11 outage: 4 restarts in
6
+ * 15 min over a ~90s SIGTERM stop → 30 EADDRINUSE crashes).
7
+ *
8
+ * All side effects are injectable so tests never touch systemd.
9
+ */
10
+ export interface SerializedRestartDeps {
11
+ /** Run a shell command; must throw on non-zero exit. */
12
+ exec?: (cmd: string) => void;
13
+ /** Whether the unit is currently active. */
14
+ isActive?: () => boolean;
15
+ sleep?: (ms: number) => Promise<void>;
16
+ /** Max time to wait for inactivity before starting anyway. */
17
+ stopTimeoutMs?: number;
18
+ /** Poll interval while waiting for inactivity. */
19
+ pollMs?: number;
20
+ /** Clock (injectable for tests). */
21
+ now?: () => number;
22
+ }
23
+ export declare function serializedSystemdRestart(deps?: SerializedRestartDeps): Promise<void>;
24
+ export declare const DSH_WEB_UNIT_NAME = "dsh-web.service";
25
+ export declare function dshWebUnitPath(): string;
26
+ /** Does systemd own `dsh-web.service` on this host? */
27
+ export declare function systemdUnitExists(unitPath?: string): boolean;
28
+ /**
29
+ * The direct-node `nohup` fallback exists for portable hosts that have no
30
+ * systemd unit. When the unit exists, systemd owns the boot: spawning node
31
+ * behind its back is how a second instance appears — the two starts / one
32
+ * rollback report of 2026-09-13. Gate on "the unit does not exist", never on
33
+ * "this particular start failed".
34
+ */
35
+ export declare function shouldUseNohupFallback(unitExists: boolean): boolean;
@@ -0,0 +1,60 @@
1
+ import { execSync } from 'node:child_process';
2
+ import * as fs from 'node:fs';
3
+ import * as os from 'node:os';
4
+ import * as path from 'node:path';
5
+ const STOP_TIMEOUT_MS = 120_000;
6
+ const POLL_MS = 2_000;
7
+ export async function serializedSystemdRestart(deps = {}) {
8
+ const exec = deps.exec ?? ((cmd) => {
9
+ execSync(cmd, { timeout: 15_000, stdio: 'pipe' });
10
+ });
11
+ const isActive = deps.isActive ?? (() => {
12
+ try {
13
+ execSync('systemctl --user is-active --quiet dsh-web.service', { timeout: 5_000, stdio: 'pipe' });
14
+ return true;
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ });
20
+ const sleep = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
21
+ const stopTimeoutMs = deps.stopTimeoutMs ?? STOP_TIMEOUT_MS;
22
+ const pollMs = deps.pollMs ?? POLL_MS;
23
+ const now = deps.now ?? Date.now;
24
+ // Best-effort: the unit may already be down (crash) — the wait + start
25
+ // below still apply.
26
+ try {
27
+ exec('systemctl --user stop dsh-web.service');
28
+ }
29
+ catch { /* fall through to wait + start */ }
30
+ const deadline = now() + stopTimeoutMs;
31
+ while (isActive()) {
32
+ if (now() >= deadline)
33
+ break;
34
+ await sleep(pollMs);
35
+ }
36
+ exec('systemctl --user start dsh-web.service');
37
+ }
38
+ export const DSH_WEB_UNIT_NAME = 'dsh-web.service';
39
+ export function dshWebUnitPath() {
40
+ return process.env.DSH_WEB_UNIT_PATH ?? path.join(os.homedir(), '.config/systemd/user/dsh-web.service');
41
+ }
42
+ /** Does systemd own `dsh-web.service` on this host? */
43
+ export function systemdUnitExists(unitPath = dshWebUnitPath()) {
44
+ try {
45
+ return fs.existsSync(unitPath);
46
+ }
47
+ catch {
48
+ return false;
49
+ }
50
+ }
51
+ /**
52
+ * The direct-node `nohup` fallback exists for portable hosts that have no
53
+ * systemd unit. When the unit exists, systemd owns the boot: spawning node
54
+ * behind its back is how a second instance appears — the two starts / one
55
+ * rollback report of 2026-09-13. Gate on "the unit does not exist", never on
56
+ * "this particular start failed".
57
+ */
58
+ export function shouldUseNohupFallback(unitExists) {
59
+ return !unitExists;
60
+ }
@@ -0,0 +1,39 @@
1
+ export declare function buildKillStalePortsCommand(ports?: number[]): string;
2
+ /**
3
+ * Sentinel appended to dsh-web.log immediately before a supervised restart.
4
+ *
5
+ * The log is append-only and carries no timestamps, so this line is the only
6
+ * durable ordering between "the previous boot's crash" and "this boot's
7
+ * output". Without it the health scan inherited the previous, failed boot's
8
+ * `EADDRINUSE` stack and rolled back a healthy, still-booting instance
9
+ * (incident 2026-09-13).
10
+ */
11
+ export declare const BOOT_BOUNDARY_MARKER = "[supervisor] boot-boundary";
12
+ /** The production dsh-web log (override with DSH_WEB_LOG for tests/tools). */
13
+ export declare function dshWebLogPath(): string;
14
+ /**
15
+ * Append the boot-boundary sentinel. Pass an explicit `logPath` in tests, or
16
+ * redirect with DSH_WEB_LOG. With no destination at all under VITEST this is a
17
+ * deliberate no-op so a unit test can never append to the operator's real log.
18
+ */
19
+ export declare function markBootBoundary(logPath?: string): void;
20
+ export declare function isSelfCopyError(message: string): boolean;
21
+ export declare const PLANNED_RESTART_TTL_MS = 180000;
22
+ export declare function isPlannedRestartFresh(mtimeMs: number, nowMs: number, ttlMs?: number): boolean;
23
+ export declare function plannedRestartPath(): string;
24
+ export declare function writePlannedRestart(ttlMs?: number): void;
25
+ export declare function checkPlannedRestart(markerPath?: string): boolean;
26
+ export declare function clearPlannedRestart(): void;
27
+ export interface RestartRequest {
28
+ ts: number;
29
+ ttl: number;
30
+ callerSessionId?: string;
31
+ reason?: string;
32
+ oldPid?: number;
33
+ }
34
+ export declare function writeRestartRequest(caller: {
35
+ callerSessionId?: string;
36
+ reason?: string;
37
+ oldPid?: number;
38
+ }, ttlMs?: number): void;
39
+ export declare function readRestartRequest(): RestartRequest | undefined;
@@ -0,0 +1,150 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import * as os from 'node:os';
4
+ // Regression guard: PR #17 added a "kill stale pid holding :3080/:3000 before
5
+ // restart" step (EADDRINUSE recovery), but the original `ss -tlnp` call had no
6
+ // port filter — it matched every listening process on the host, so every
7
+ // restart also killed unrelated services (redis, php-fpm, horizon, ssh, ...).
8
+ // The dsh-web MainThread holds both 3080 and 3000 (see AGENTS.md Known Issues),
9
+ // so filtering `ss` itself to those ports is both correct and sufficient.
10
+ export function buildKillStalePortsCommand(ports = [3080]) {
11
+ const filter = ports.map(p => `sport = :${p}`).join(' or ');
12
+ return `pids=$(ss -tlnp '( ${filter} )' 2>/dev/null | sed -n 's/.*pid=\\([0-9]*\\).*/\\1/p' | sort -u); if [ -n "$pids" ]; then echo "[supervisor] killing stale pids $pids"; kill $pids 2>/dev/null || true; sleep 2; fi`;
13
+ }
14
+ /**
15
+ * Sentinel appended to dsh-web.log immediately before a supervised restart.
16
+ *
17
+ * The log is append-only and carries no timestamps, so this line is the only
18
+ * durable ordering between "the previous boot's crash" and "this boot's
19
+ * output". Without it the health scan inherited the previous, failed boot's
20
+ * `EADDRINUSE` stack and rolled back a healthy, still-booting instance
21
+ * (incident 2026-09-13).
22
+ */
23
+ export const BOOT_BOUNDARY_MARKER = '[supervisor] boot-boundary';
24
+ /** The production dsh-web log (override with DSH_WEB_LOG for tests/tools). */
25
+ export function dshWebLogPath() {
26
+ return process.env.DSH_WEB_LOG ?? path.join(os.homedir(), '.dsh/dsh-web.log');
27
+ }
28
+ /**
29
+ * Append the boot-boundary sentinel. Pass an explicit `logPath` in tests, or
30
+ * redirect with DSH_WEB_LOG. With no destination at all under VITEST this is a
31
+ * deliberate no-op so a unit test can never append to the operator's real log.
32
+ */
33
+ export function markBootBoundary(logPath) {
34
+ const explicit = logPath ?? process.env.DSH_WEB_LOG;
35
+ if (explicit === undefined && process.env.VITEST)
36
+ return;
37
+ const p = explicit ?? dshWebLogPath();
38
+ try {
39
+ fs.mkdirSync(path.dirname(p), { recursive: true });
40
+ fs.appendFileSync(p, `${BOOT_BOUNDARY_MARKER} ${new Date().toISOString()}\n`);
41
+ }
42
+ catch { }
43
+ }
44
+ // LKG rollback copies each entry with fs.cpSync — an entry that resolves back
45
+ // into itself (e.g. a symlink cycle reachable from ~/.dsh, observed in
46
+ // production pointing into ~/.npm/_npx/.../node_modules/unist-util-position)
47
+ // always throws here. Node's wording for this varies by version ("cannot be
48
+ // the same", "subdirectory of itself"/"of self") — match all known phrasings
49
+ // so the entry is skipped instead of aborting the whole rollback.
50
+ export function isSelfCopyError(message) {
51
+ const lower = message.toLowerCase();
52
+ return lower.includes('cannot be the same') || lower.includes('subdirectory of');
53
+ }
54
+ // Coordination contract with dsh-safe-web-update's restart-dsh-web.sh (see
55
+ // <workspace-root>/docs/specs/2026-08-28-supervisor-planned-restart-design.md):
56
+ // that script writes this marker right before it intentionally takes dsh-web
57
+ // down, so the supervisor's own health poll does not mistake a deliberate
58
+ // restart (kill -> dry-boot -> relaunch, up to ~130s) for a crash and race it
59
+ // with its own rollback + restartWeb(). Presence + freshness is authoritative;
60
+ // the marker's content is never parsed.
61
+ export const PLANNED_RESTART_TTL_MS = 180_000;
62
+ export function isPlannedRestartFresh(mtimeMs, nowMs, ttlMs = PLANNED_RESTART_TTL_MS) {
63
+ return nowMs - mtimeMs < ttlMs;
64
+ }
65
+ export function plannedRestartPath() {
66
+ return path.join(os.homedir(), '.dsh/.supervisor/planned-restart.json');
67
+ }
68
+ export function writePlannedRestart(ttlMs = 30000) {
69
+ const p = plannedRestartPath();
70
+ fs.mkdirSync(path.dirname(p), { recursive: true });
71
+ fs.writeFileSync(p, JSON.stringify({ ts: Date.now(), ttl: ttlMs }), { mode: 0o600 });
72
+ try {
73
+ fs.chmodSync(p, 0o600);
74
+ }
75
+ catch { }
76
+ // The boundary belongs to the restart, not to the poller: every sanctioned
77
+ // restart path already writes this marker first.
78
+ markBootBoundary();
79
+ }
80
+ export function checkPlannedRestart(markerPath) {
81
+ // Legacy path explicit: check mtime of that file
82
+ if (markerPath) {
83
+ try {
84
+ const stat = fs.statSync(markerPath);
85
+ return isPlannedRestartFresh(stat.mtimeMs, Date.now());
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ }
91
+ // New JSON marker with {ts, ttl}
92
+ try {
93
+ const raw = fs.readFileSync(plannedRestartPath(), 'utf8');
94
+ const j = JSON.parse(raw);
95
+ if (typeof j.ts === 'number' && typeof j.ttl === 'number') {
96
+ return Date.now() - j.ts < j.ttl;
97
+ }
98
+ }
99
+ catch { }
100
+ // Fallback: legacy plain file written by dsh-safe-web-update (no .json, mtime-based)
101
+ try {
102
+ const legacy = path.join(os.homedir(), '.dsh/.supervisor/planned-restart');
103
+ const stat = fs.statSync(legacy);
104
+ return isPlannedRestartFresh(stat.mtimeMs, Date.now());
105
+ }
106
+ catch { }
107
+ return false;
108
+ }
109
+ export function clearPlannedRestart() {
110
+ try {
111
+ fs.unlinkSync(plannedRestartPath());
112
+ }
113
+ catch { }
114
+ // also clear legacy plain file if present (best-effort, avoids stale suppression)
115
+ try {
116
+ const legacy = path.join(os.homedir(), '.dsh/.supervisor/planned-restart');
117
+ if (fs.existsSync(legacy) && legacy !== plannedRestartPath()) {
118
+ // only remove legacy if it was created as test artifact; keep conservative
119
+ // but clearing both ensures checkPlannedRestart() returns false after clear
120
+ try {
121
+ fs.unlinkSync(legacy);
122
+ }
123
+ catch { }
124
+ }
125
+ }
126
+ catch { }
127
+ }
128
+ export function writeRestartRequest(caller, ttlMs = 180_000) {
129
+ const p = plannedRestartPath();
130
+ fs.mkdirSync(path.dirname(p), { recursive: true });
131
+ const body = { ts: Date.now(), ttl: ttlMs, ...caller };
132
+ fs.writeFileSync(p, JSON.stringify(body), { mode: 0o600 });
133
+ try {
134
+ fs.chmodSync(p, 0o600);
135
+ }
136
+ catch { }
137
+ }
138
+ export function readRestartRequest() {
139
+ try {
140
+ const raw = fs.readFileSync(plannedRestartPath(), 'utf8');
141
+ const j = JSON.parse(raw);
142
+ if (typeof j.ts === 'number' && typeof j.ttl === 'number') {
143
+ if (Date.now() - j.ts >= j.ttl)
144
+ return undefined;
145
+ return { ts: j.ts, ttl: j.ttl, callerSessionId: j.callerSessionId, reason: j.reason, oldPid: j.oldPid };
146
+ }
147
+ }
148
+ catch { }
149
+ return undefined;
150
+ }