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