@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,124 @@
1
+ /**
2
+ * dsh_web_restart tool — the safe restart path for the model running inside
3
+ * dsh web. Scheduling a restart through this tool instead of a raw kill keeps
4
+ * the restart inside the supervisor's ownership loop:
5
+ *
6
+ * 1. dry-boot gate — if the plugin tree changed since the latest LKG, boot a
7
+ * copy of the live profile on an ephemeral DSH_HOME first and only
8
+ * schedule when that boot serves HTTP.
9
+ * 2. intent sidecar — record the caller session + reason under
10
+ * ~/.dsh/.supervisor/intents/ for attribution.
11
+ * 3. hand-off — write the restart-request marker (planned-restart.json with
12
+ * callerSessionId) that the supervisor daemon owns and acts on
13
+ * (out-of-band). This tool NEVER restarts the host in-tree.
14
+ */
15
+ import { writeRestartRequest, readRestartRequest } from './restart-guards.js';
16
+ import { type DaemonState } from './daemon-freshness.js';
17
+ /**
18
+ * Copy a live profile tree for an isolated dry-boot. A naive recursive copy
19
+ * breaks `link:` installs: their node_modules entries are relative symlinks
20
+ * (e.g. `../../../shared/pkg`) that resolve against the copy location and
21
+ * dangle. Every symlink left dangling by the copy is rewritten to the
22
+ * absolute live target it pointed at, so the dry-boot loads the same code
23
+ * the live tree loads. Links already broken in the live tree are left alone
24
+ * (the dry-boot must stay faithful, not fix the live tree).
25
+ */
26
+ export declare function copyProfileForDryBoot(srcDir: string, destDir: string): void;
27
+ /**
28
+ * A dry-boot orphan candidate: a `dsh web` process rooted at a temp DSH_HOME
29
+ * with an ephemeral-port listener. Ports 3080/3081/3082 are the live tree and
30
+ * can never be candidates.
31
+ */
32
+ export interface DryBootCandidate {
33
+ pid: number;
34
+ port: number;
35
+ dshHome: string;
36
+ }
37
+ export interface GcReaders {
38
+ readProc?: () => Array<{
39
+ pid: number;
40
+ cmd: string;
41
+ env: string;
42
+ }>;
43
+ ssPortsOf?: (pid: number) => number[];
44
+ selfPid?: number;
45
+ }
46
+ /**
47
+ * List dry-boot orphans: `dsh web` processes on a temp DSH_HOME holding an
48
+ * ephemeral 9000-9999 listener. Conjunctive fingerprint + absolute exclusions
49
+ * (self PID, live ports, real-home DSH_HOME) — a process is returned only when
50
+ * every signal agrees it is a disposable dry-boot.
51
+ */
52
+ export declare function listDryBootCandidates(readers?: GcReaders): DryBootCandidate[];
53
+ /**
54
+ * Boot a copy of the live web profile on an isolated DSH_HOME and verify the
55
+ * plugin tree loads and serves. Returns ok + a one-line detail for the tool
56
+ * message. The spawned tree is killed (best-effort) and the temp home removed.
57
+ * Unit tests mock this (never spawn a real node boot in tests).
58
+ *
59
+ * NOTE (bin.ts finding): the `web` alias already implies `--profile web`, and
60
+ * the web app's own commander program (no allowUnknownOption) rejects a stray
61
+ * `--profile` in its inner args — so the spawn passes only `web --no-open
62
+ * --port <port>`.
63
+ */
64
+ export declare function dryBootVerify(harnessRoot: string, opts?: {
65
+ timeoutMs?: number;
66
+ }): Promise<{
67
+ ok: boolean;
68
+ detail: string;
69
+ }>;
70
+ /**
71
+ * Classify a failed dry-boot's log tail into a precise one-line detail. The
72
+ * most common operator-actionable failure is an EADDRINUSE — the candidate
73
+ * collided with the live dsh web tree on :3000/:3080 or with another process
74
+ * on the ephemeral 9000-9999 port — so name the colliding port instead of
75
+ * reporting a generic boot failure. Plugin-tree load errors keep their stable
76
+ * codes (the caller's refused message reads `dry-boot failed — restart
77
+ * refused. <detail>`).
78
+ */
79
+ export declare function dryBootFailureDetail(tail: string, exitCode: number): string;
80
+ /** Minimal file metadata the drift check reads; injectable for deterministic tests. */
81
+ export interface FileStat {
82
+ mtimeMs: number;
83
+ }
84
+ /**
85
+ * Whether the live plugin tree differs from the latest LKG snapshot. Three
86
+ * signals are combined:
87
+ *
88
+ * 1. manifest drift — the live profile's web `package.json` text vs baseline;
89
+ * 2. cordis patch drift — the live profile's web `cordis.patch.yml` text vs
90
+ * baseline (a patch-only config edit changes the boot-time row wiring
91
+ * without touching the manifest — the manifest check alone misses it);
92
+ * 3. plugin-lib drift — any `@ddtcorex` plugin `lib/` file newer than the
93
+ * snapshot moment. Link-installed plugins resolve to the same workspace
94
+ * files in both live and LKG, so the stored copies cannot be compared
95
+ * byte-wise; the snapshot itself is the meaningful baseline and a rebuilt
96
+ * `lib/` bumps a file past it even when the manifest text is unchanged.
97
+ * writeLKG writes `manifest.json` LAST, so its FILE mtime is the
98
+ * authoritative snapshot moment; the snapshot dir mtime is only a
99
+ * fallback for legacy snapshots without a manifest.
100
+ *
101
+ * `statFile` (default `statSync`) reads the metadata so tests can inject a
102
+ * controlled reader instead of relying on filesystem utimes (which CI runners
103
+ * do not reliably reflect). No LKG baseline, a missing file on either side, or
104
+ * any stat/read error means "changed" — the caller falls back to the dry-boot
105
+ * gate.
106
+ */
107
+ export declare function isPluginTreeChanged(harnessRoot: string, lkgDir?: string, opts?: {
108
+ statFile?: (p: string) => FileStat;
109
+ }): boolean;
110
+ /**
111
+ * Register the dsh_web_restart tool. Registration is fail-safe (warns, never
112
+ * throws) and the returned function disposes the registration. `deps` are
113
+ * injectable for tests.
114
+ */
115
+ export declare function registerRestartTool(ctx: any, deps?: {
116
+ sessionIdOf?: (exec: any) => string | undefined;
117
+ dryBoot?: typeof dryBootVerify;
118
+ writeRestartRequest?: typeof writeRestartRequest;
119
+ readRestartRequest?: typeof readRestartRequest;
120
+ harnessRoot?: string;
121
+ gcReaders?: GcReaders;
122
+ killPid?: (pid: number, sig: string) => void;
123
+ daemonState?: () => DaemonState;
124
+ }): () => void;
@@ -0,0 +1,539 @@
1
+ /**
2
+ * dsh_web_restart tool — the safe restart path for the model running inside
3
+ * dsh web. Scheduling a restart through this tool instead of a raw kill keeps
4
+ * the restart inside the supervisor's ownership loop:
5
+ *
6
+ * 1. dry-boot gate — if the plugin tree changed since the latest LKG, boot a
7
+ * copy of the live profile on an ephemeral DSH_HOME first and only
8
+ * schedule when that boot serves HTTP.
9
+ * 2. intent sidecar — record the caller session + reason under
10
+ * ~/.dsh/.supervisor/intents/ for attribution.
11
+ * 3. hand-off — write the restart-request marker (planned-restart.json with
12
+ * callerSessionId) that the supervisor daemon owns and acts on
13
+ * (out-of-band). This tool NEVER restarts the host in-tree.
14
+ */
15
+ import { join, dirname, resolve } from 'node:path';
16
+ import { mkdtempSync, rmSync, cpSync, existsSync, readFileSync, readdirSync, statSync, lstatSync, readlinkSync, symlinkSync, unlinkSync } from 'node:fs';
17
+ import { tmpdir, homedir } from 'node:os';
18
+ import { spawn, execFileSync } from 'node:child_process';
19
+ import { createRequire } from 'node:module';
20
+ import { writeRestartRequest, readRestartRequest } from './restart-guards.js';
21
+ import { intentPath, readIntent, readRestartOutcome } from './intents.js';
22
+ import { supervisorDaemonState, describeDaemonState } from './daemon-freshness.js';
23
+ /**
24
+ * Copy a live profile tree for an isolated dry-boot. A naive recursive copy
25
+ * breaks `link:` installs: their node_modules entries are relative symlinks
26
+ * (e.g. `../../../shared/pkg`) that resolve against the copy location and
27
+ * dangle. Every symlink left dangling by the copy is rewritten to the
28
+ * absolute live target it pointed at, so the dry-boot loads the same code
29
+ * the live tree loads. Links already broken in the live tree are left alone
30
+ * (the dry-boot must stay faithful, not fix the live tree).
31
+ */
32
+ export function copyProfileForDryBoot(srcDir, destDir) {
33
+ cpSync(srcDir, destDir, { recursive: true, preserveTimestamps: true });
34
+ const repair = (dir, rel) => {
35
+ for (const name of readdirSync(dir)) {
36
+ const p = join(dir, name);
37
+ const r = rel ? `${rel}/${name}` : name;
38
+ const st = lstatSync(p);
39
+ if (st.isSymbolicLink()) {
40
+ if (!existsSync(p)) {
41
+ const liveTarget = resolve(srcDir, dirname(r), readlinkSync(p));
42
+ if (existsSync(liveTarget)) {
43
+ unlinkSync(p);
44
+ symlinkSync(liveTarget, p);
45
+ }
46
+ }
47
+ }
48
+ else if (st.isDirectory()) {
49
+ repair(p, r);
50
+ }
51
+ }
52
+ };
53
+ repair(destDir, '');
54
+ }
55
+ const LIVE_PORTS = new Set([3080, 3081, 3082]);
56
+ function defaultReadProc() {
57
+ const out = [];
58
+ let names = [];
59
+ try {
60
+ names = readdirSync('/proc');
61
+ }
62
+ catch {
63
+ return out;
64
+ }
65
+ for (const name of names) {
66
+ if (!/^\d+$/.test(name))
67
+ continue;
68
+ try {
69
+ const cmd = readFileSync(`/proc/${name}/cmdline`, 'utf8').replace(/\0/g, ' ');
70
+ const env = readFileSync(`/proc/${name}/environ`, 'utf8');
71
+ out.push({ pid: Number(name), cmd, env });
72
+ }
73
+ catch { /* process exited mid-scan — ignore */ }
74
+ }
75
+ return out;
76
+ }
77
+ function defaultSsPortsOf(pid) {
78
+ try {
79
+ const out = execFileSync('ss', ['-tlnp'], { encoding: 'utf8' });
80
+ const ports = [];
81
+ for (const line of out.split('\n')) {
82
+ if (!line.includes(`pid=${pid},`))
83
+ continue;
84
+ const m = /:(\d+)\s/.exec(line);
85
+ if (m)
86
+ ports.push(Number(m[1]));
87
+ }
88
+ return ports;
89
+ }
90
+ catch {
91
+ return [];
92
+ }
93
+ }
94
+ /**
95
+ * List dry-boot orphans: `dsh web` processes on a temp DSH_HOME holding an
96
+ * ephemeral 9000-9999 listener. Conjunctive fingerprint + absolute exclusions
97
+ * (self PID, live ports, real-home DSH_HOME) — a process is returned only when
98
+ * every signal agrees it is a disposable dry-boot.
99
+ */
100
+ export function listDryBootCandidates(readers = {}) {
101
+ const readProc = readers.readProc ?? defaultReadProc;
102
+ const ssPortsOf = readers.ssPortsOf ?? defaultSsPortsOf;
103
+ const selfPid = readers.selfPid ?? process.pid;
104
+ const out = [];
105
+ for (const p of readProc()) {
106
+ if (p.pid === selfPid)
107
+ continue;
108
+ if (!/bin\.ts web/.test(p.cmd))
109
+ continue;
110
+ const home = /^DSH_HOME=([^\0]*)/m.exec(p.env)?.[1] ?? '';
111
+ if (!home.startsWith(join(tmpdir(), 'dsh-dryboot-')))
112
+ continue;
113
+ const ports = ssPortsOf(p.pid);
114
+ if (ports.some(port => LIVE_PORTS.has(port)))
115
+ continue;
116
+ const eph = ports.filter(port => port >= 9000 && port <= 9999);
117
+ if (eph.length === 0)
118
+ continue;
119
+ out.push({ pid: p.pid, port: eph[0], dshHome: home });
120
+ }
121
+ return out;
122
+ }
123
+ /**
124
+ * Boot a copy of the live web profile on an isolated DSH_HOME and verify the
125
+ * plugin tree loads and serves. Returns ok + a one-line detail for the tool
126
+ * message. The spawned tree is killed (best-effort) and the temp home removed.
127
+ * Unit tests mock this (never spawn a real node boot in tests).
128
+ *
129
+ * NOTE (bin.ts finding): the `web` alias already implies `--profile web`, and
130
+ * the web app's own commander program (no allowUnknownOption) rejects a stray
131
+ * `--profile` in its inner args — so the spawn passes only `web --no-open
132
+ * --port <port>`.
133
+ */
134
+ export async function dryBootVerify(harnessRoot, opts = {}) {
135
+ const timeoutMs = opts.timeoutMs ?? 60_000;
136
+ const home = homedir();
137
+ const liveProfile = join(home, '.dsh', 'profiles', 'web');
138
+ if (!existsSync(liveProfile))
139
+ return { ok: true, detail: 'skipped (no live web profile)' };
140
+ const tmpHome = mkdtempSync(join(tmpdir(), 'dsh-dryboot-'));
141
+ const logs = [];
142
+ let child = null;
143
+ try {
144
+ copyProfileForDryBoot(liveProfile, join(tmpHome, 'profiles', 'web'));
145
+ const port = String(9000 + Math.floor(Math.random() * 1000));
146
+ const url = `http://127.0.0.1:${port}/`;
147
+ child = spawn('node', ['--import', 'tsx/esm', 'apps/cli/src/bin.ts', 'web', '--no-open', '--port', port], {
148
+ cwd: harnessRoot, env: { ...process.env, DSH_HOME: tmpHome }, stdio: ['ignore', 'pipe', 'pipe'],
149
+ });
150
+ child.stdout?.on('data', (d) => logs.push(d.toString()));
151
+ child.stderr?.on('data', (d) => logs.push(d.toString()));
152
+ const deadline = Date.now() + timeoutMs;
153
+ let code = -1;
154
+ while (Date.now() < deadline) {
155
+ if (child.exitCode !== null) {
156
+ code = child.exitCode;
157
+ break;
158
+ }
159
+ try {
160
+ const r = await fetch(url);
161
+ if (r.status === 200 || r.status === 401) {
162
+ code = 0;
163
+ break;
164
+ }
165
+ }
166
+ catch { }
167
+ await new Promise(r => setTimeout(r, 500));
168
+ }
169
+ const tail = logs.join('').slice(-3000);
170
+ const loadErr = /ERR_MODULE_NOT_FOUND|assertChannel|must declare output|failed to apply loader entry/.exec(tail);
171
+ if (code === 0 && !loadErr)
172
+ return { ok: true, detail: 'dry-boot ok' };
173
+ return { ok: false, detail: dryBootFailureDetail(tail, code) };
174
+ }
175
+ catch (e) {
176
+ return { ok: false, detail: `dry-boot error: ${e?.message ?? String(e)}` };
177
+ }
178
+ finally {
179
+ // Kill on every exit path — a successful boot included. The dry boot only
180
+ // exists to verify the tree; leaving the child up would orphan a dsh web
181
+ // on the ephemeral port whose temp DSH_HOME is removed below, and a stale
182
+ // orphan could later answer a port collision with a false-positive 200.
183
+ try {
184
+ child?.kill('SIGKILL');
185
+ }
186
+ catch { }
187
+ try {
188
+ rmSync(tmpHome, { recursive: true, force: true });
189
+ }
190
+ catch { }
191
+ }
192
+ }
193
+ /**
194
+ * Classify a failed dry-boot's log tail into a precise one-line detail. The
195
+ * most common operator-actionable failure is an EADDRINUSE — the candidate
196
+ * collided with the live dsh web tree on :3000/:3080 or with another process
197
+ * on the ephemeral 9000-9999 port — so name the colliding port instead of
198
+ * reporting a generic boot failure. Plugin-tree load errors keep their stable
199
+ * codes (the caller's refused message reads `dry-boot failed — restart
200
+ * refused. <detail>`).
201
+ */
202
+ export function dryBootFailureDetail(tail, exitCode) {
203
+ const addrInUse = /EADDRINUSE[^]*?:(\d+)/.exec(tail);
204
+ if (addrInUse) {
205
+ const port = addrInUse[1];
206
+ return `dry-boot failed: port ${port} already in use (EADDRINUSE) — the live dsh web tree or another process holds it`;
207
+ }
208
+ const loadErr = /ERR_MODULE_NOT_FOUND|assertChannel|must declare output|failed to apply loader entry/.exec(tail);
209
+ if (loadErr)
210
+ return `dry-boot failed: ${loadErr[0]}`;
211
+ return `dry-boot failed (exit ${exitCode})`;
212
+ }
213
+ /**
214
+ * Whether the live plugin tree differs from the latest LKG snapshot. Three
215
+ * signals are combined:
216
+ *
217
+ * 1. manifest drift — the live profile's web `package.json` text vs baseline;
218
+ * 2. cordis patch drift — the live profile's web `cordis.patch.yml` text vs
219
+ * baseline (a patch-only config edit changes the boot-time row wiring
220
+ * without touching the manifest — the manifest check alone misses it);
221
+ * 3. plugin-lib drift — any `@ddtcorex` plugin `lib/` file newer than the
222
+ * snapshot moment. Link-installed plugins resolve to the same workspace
223
+ * files in both live and LKG, so the stored copies cannot be compared
224
+ * byte-wise; the snapshot itself is the meaningful baseline and a rebuilt
225
+ * `lib/` bumps a file past it even when the manifest text is unchanged.
226
+ * writeLKG writes `manifest.json` LAST, so its FILE mtime is the
227
+ * authoritative snapshot moment; the snapshot dir mtime is only a
228
+ * fallback for legacy snapshots without a manifest.
229
+ *
230
+ * `statFile` (default `statSync`) reads the metadata so tests can inject a
231
+ * controlled reader instead of relying on filesystem utimes (which CI runners
232
+ * do not reliably reflect). No LKG baseline, a missing file on either side, or
233
+ * any stat/read error means "changed" — the caller falls back to the dry-boot
234
+ * gate.
235
+ */
236
+ export function isPluginTreeChanged(harnessRoot, lkgDir = join(homedir(), '.dsh/.supervisor/lkg'), opts = {}) {
237
+ void harnessRoot;
238
+ const statFile = opts.statFile ?? ((p) => statSync(p));
239
+ try {
240
+ const entries = existsSync(lkgDir) ? readdirSync(lkgDir).sort() : [];
241
+ const latest = entries[entries.length - 1];
242
+ if (!latest)
243
+ return true; // no baseline → assume changed
244
+ const lkgHome = join(lkgDir, latest, 'profiles', 'web');
245
+ const live = join(homedir(), '.dsh', 'profiles', 'web');
246
+ const lkgManifest = join(lkgHome, 'package.json');
247
+ const liveManifest = join(live, 'package.json');
248
+ if (!existsSync(lkgManifest) || !existsSync(liveManifest))
249
+ return true;
250
+ if (readFileSync(liveManifest, 'utf8') !== readFileSync(lkgManifest, 'utf8'))
251
+ return true;
252
+ // cordis.patch.yml — compare only when at least one side has it (profiles
253
+ // without a patch are the baseline; a patch appearing on either side alone
254
+ // is drift). The text compare keeps the check cheap and hermetic.
255
+ const lkgPatch = join(lkgHome, 'cordis.patch.yml');
256
+ const livePatch = join(live, 'cordis.patch.yml');
257
+ if (existsSync(lkgPatch) || existsSync(livePatch)) {
258
+ if (!existsSync(lkgPatch) || !existsSync(livePatch))
259
+ return true;
260
+ if (readFileSync(livePatch, 'utf8') !== readFileSync(lkgPatch, 'utf8'))
261
+ return true;
262
+ }
263
+ const snapshotManifest = join(lkgDir, latest, 'manifest.json');
264
+ const baseline = existsSync(snapshotManifest)
265
+ ? statFile(snapshotManifest).mtimeMs
266
+ : statFile(join(lkgDir, latest)).mtimeMs;
267
+ const livePlugins = join(live, 'node_modules', '@ddtcorex');
268
+ if (existsSync(livePlugins)) {
269
+ for (const name of readdirSync(livePlugins)) {
270
+ const libDir = join(livePlugins, name, 'lib');
271
+ if (!existsSync(libDir))
272
+ continue;
273
+ if (newestFileMtime(libDir, statFile) > baseline)
274
+ return true;
275
+ }
276
+ }
277
+ return false;
278
+ }
279
+ catch {
280
+ return true;
281
+ }
282
+ }
283
+ /** Newest mtime under a directory; recursion threads the injected stat reader. */
284
+ function newestFileMtime(dir, statFile) {
285
+ let newest = 0;
286
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
287
+ const p = join(dir, entry.name);
288
+ if (entry.isDirectory())
289
+ newest = Math.max(newest, newestFileMtime(p, statFile));
290
+ else
291
+ newest = Math.max(newest, statFile(p).mtimeMs);
292
+ }
293
+ return newest;
294
+ }
295
+ function currentSessionId(exec, fallback) {
296
+ // dsh-tools dispatch hands a ToolRunContext — the exec itself has no
297
+ // sessionId/session/caller fields; session identity lives on the agent
298
+ // (exec.agent.id is the branded SessionId, exec.agent.session.id also
299
+ // exists). Probe those first so production dispatches are identifiable.
300
+ return exec?.agent?.id ?? exec?.agent?.session?.id ?? exec?.sessionId ?? exec?.session?.id ?? exec?.caller?.sessionId ?? fallback?.(exec);
301
+ }
302
+ /**
303
+ * Register the dsh_web_restart tool. Registration is fail-safe (warns, never
304
+ * throws) and the returned function disposes the registration. `deps` are
305
+ * injectable for tests.
306
+ */
307
+ export function registerRestartTool(ctx, deps = {}) {
308
+ const doDryBoot = deps.dryBoot ?? dryBootVerify;
309
+ const doWrite = deps.writeRestartRequest ?? writeRestartRequest;
310
+ const doRead = deps.readRestartRequest ?? readRestartRequest;
311
+ const doSessionId = deps.sessionIdOf ?? currentSessionId;
312
+ const readDaemonState = deps.daemonState ?? supervisorDaemonState;
313
+ let dispose;
314
+ let disposeDryboot;
315
+ let disposeGc;
316
+ let disposeStatus;
317
+ try {
318
+ dispose = ctx.tools.register({
319
+ name: 'dsh_web_restart',
320
+ description: 'Schedule a safe restart of the dsh web host: dry-boots the plugin tree when it changed, records an intent for the calling session, and hands the swap to the supervisor daemon (out-of-band — it never restarts in-tree). Returns immediately; the swap lands ~1-5 min later and kills the calling turn, so call this as the LAST action of the turn and verify with dsh_web_restart_status in the NEXT one (never sleep here). Do not call dsh_web_dryboot first — this tool already dry-boots. The result carries the supervisor daemon verdict: a "stale" line means run its `kill -TERM <pid>` before the swap lands.',
321
+ parameters: {
322
+ type: 'object',
323
+ properties: {
324
+ reason: { type: 'string', description: 'Why the restart is happening (recorded in the intent)' },
325
+ pluginChanged: { type: 'boolean', description: 'Override for the auto-detected plugin-tree change check' },
326
+ },
327
+ additionalProperties: false,
328
+ },
329
+ output: {
330
+ schema: { type: 'object', additionalProperties: true, properties: { ok: { type: 'boolean' }, detail: { type: 'string' } } },
331
+ render: (_args, value) => [{ type: 'text', text: value.detail }],
332
+ },
333
+ execute: async (args, exec) => {
334
+ // Serialize: a fresh restart-request marker means a restart is
335
+ // already in flight (another session, the daemon, or an earlier
336
+ // call of this tool). Scheduling another one overlaps the ~90s
337
+ // SIGTERM stop and crash-loops on EADDRINUSE — refuse fast, before
338
+ // the dry-boot gate, and point at the status tool instead.
339
+ let inflight;
340
+ try {
341
+ inflight = doRead();
342
+ }
343
+ catch {
344
+ inflight = undefined;
345
+ }
346
+ if (inflight !== undefined) {
347
+ const by = inflight.callerSessionId ?? 'unknown session';
348
+ const why = inflight.reason ? `: ${inflight.reason.slice(0, 120)}` : '';
349
+ return { ok: false, detail: `restart already in progress (requested by ${by}${why}) — check dsh_web_restart_status instead of scheduling another` };
350
+ }
351
+ const harnessRoot = deps.harnessRoot ?? (await import('./paths.js')).resolveDeepseekHarnessDir();
352
+ const lkgDir = join(homedir(), '.dsh/.supervisor/lkg');
353
+ const changed = args.pluginChanged === true || (args.pluginChanged !== false && isPluginTreeChanged(harnessRoot, lkgDir));
354
+ if (changed) {
355
+ const gate = await doDryBoot(harnessRoot);
356
+ if (!gate.ok)
357
+ return { ok: false, detail: `dry-boot failed — restart refused. ${gate.detail}` };
358
+ }
359
+ const callerSessionId = doSessionId(exec);
360
+ if (!callerSessionId) {
361
+ // The daemon's grace branch keys on callerSessionId — without it the
362
+ // marker would be written but no restart would ever be supervised.
363
+ return { ok: false, detail: 'cannot identify the calling session — restart not scheduled' };
364
+ }
365
+ doWrite({ callerSessionId, reason: typeof args.reason === 'string' ? args.reason : undefined, oldPid: process.pid }, 180_000);
366
+ writeIntentSidecar(callerSessionId, args.reason);
367
+ // A read-only probe, and it must never fail the swap: an unmeasurable
368
+ // daemon is reported as such, not treated as a blocker.
369
+ let daemon;
370
+ try {
371
+ daemon = readDaemonState();
372
+ }
373
+ catch {
374
+ daemon = { verdict: 'unknown' };
375
+ }
376
+ return {
377
+ ok: true,
378
+ detail: `restart scheduled — caller ${callerSessionId}. The swap lands ~1-5 min from now (measured 2026-10-02: 5m04s schedule→outcome; the dry-boot gate, the daemon's poll, the ~90s SIGTERM stop and the new boot all sit inside that window). THIS TURN ENDS AT THE SWAP: poll dsh_web_restart_status in the next turn, never sleep here. ${describeDaemonState(daemon)}`,
379
+ oldPid: process.pid,
380
+ intentPath: intentPath(callerSessionId),
381
+ };
382
+ },
383
+ });
384
+ }
385
+ catch (e) {
386
+ try {
387
+ ctx.logger?.warn?.(`[supervisor] dsh_web_restart tool failed: ${e?.message ?? String(e)}`);
388
+ }
389
+ catch { }
390
+ }
391
+ try {
392
+ disposeDryboot = ctx.tools.register({
393
+ name: 'dsh_web_dryboot',
394
+ description: 'Validate the plugin tree by booting a copy of the live profile on an ephemeral port. Never schedules or performs a restart; temp home removed afterwards.',
395
+ parameters: {
396
+ type: 'object',
397
+ properties: {
398
+ timeoutMs: { type: 'number', description: 'Gate timeout in ms (default 60000).' },
399
+ },
400
+ additionalProperties: false,
401
+ },
402
+ output: {
403
+ schema: { type: 'object', additionalProperties: true, properties: { ok: { type: 'boolean' }, detail: { type: 'string' } } },
404
+ render: (_args, value) => [{ type: 'text', text: value.detail }],
405
+ },
406
+ execute: async (args) => {
407
+ const harnessRoot = deps.harnessRoot ?? (await import('./paths.js')).resolveDeepseekHarnessDir();
408
+ const gate = await doDryBoot(harnessRoot, typeof args.timeoutMs === 'number' ? { timeoutMs: args.timeoutMs } : undefined);
409
+ return { ok: gate.ok, detail: gate.detail };
410
+ },
411
+ });
412
+ }
413
+ catch (e) {
414
+ try {
415
+ ctx.logger?.warn?.(`[supervisor] dsh_web_dryboot tool failed: ${e?.message ?? String(e)}`);
416
+ }
417
+ catch { }
418
+ }
419
+ try {
420
+ const doKill = deps.killPid ?? ((pid, sig) => process.kill(pid, sig));
421
+ disposeGc = ctx.tools.register({
422
+ name: 'dsh_web_gc',
423
+ description: 'Reap orphaned dry-boot dsh web processes (temp DSH_HOME + ephemeral port). Preview-first: returns candidates without killing unless confirm:true.',
424
+ parameters: {
425
+ type: 'object',
426
+ properties: {
427
+ confirm: { type: 'boolean', description: 'Actually SIGKILL the candidates and verify they are gone.' },
428
+ },
429
+ additionalProperties: false,
430
+ },
431
+ output: {
432
+ schema: { type: 'object', additionalProperties: true, properties: { killed: { type: 'array' }, candidates: { type: 'array' } } },
433
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
434
+ },
435
+ execute: async (args) => {
436
+ // INVARIANT: kill only conjunctive-fingerprint dry-boots (temp DSH_HOME
437
+ // + ephemeral listener), never self / live ports / real-home processes.
438
+ // Preview is the default; killing requires explicit confirm:true.
439
+ const found = listDryBootCandidates(deps.gcReaders);
440
+ if (args.confirm !== true)
441
+ return { killed: [], candidates: found };
442
+ const killed = [];
443
+ for (const c of found) {
444
+ try {
445
+ doKill(c.pid, 'SIGKILL');
446
+ }
447
+ catch { }
448
+ }
449
+ const remaining = listDryBootCandidates(deps.gcReaders);
450
+ const alive = new Set(remaining.map(c => c.pid));
451
+ for (const c of found) {
452
+ if (!alive.has(c.pid))
453
+ killed.push(c.pid);
454
+ }
455
+ return { killed, candidates: remaining };
456
+ },
457
+ });
458
+ }
459
+ catch (e) {
460
+ try {
461
+ ctx.logger?.warn?.(`[supervisor] dsh_web_gc tool failed: ${e?.message ?? String(e)}`);
462
+ }
463
+ catch { }
464
+ }
465
+ try {
466
+ disposeStatus = ctx.tools.register({
467
+ name: 'dsh_web_restart_status',
468
+ description: 'Read the outcome of the calling session\u2019s latest scheduled dsh web restart (pending until the daemon swaps and health-checks).',
469
+ parameters: {
470
+ type: 'object',
471
+ properties: {},
472
+ additionalProperties: false,
473
+ },
474
+ output: {
475
+ schema: { type: 'object', additionalProperties: true },
476
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
477
+ },
478
+ execute: async (_args, exec) => {
479
+ const callerSessionId = doSessionId(exec);
480
+ if (!callerSessionId)
481
+ return { state: 'none', detail: 'cannot identify the calling session' };
482
+ const outcome = readRestartOutcome(callerSessionId);
483
+ if (outcome)
484
+ return { ...outcome };
485
+ const intent = readIntent(callerSessionId);
486
+ if (intent)
487
+ return { state: 'pending', detail: 'restart scheduled, daemon has not reported back yet' };
488
+ return { state: 'none', detail: 'no restart scheduled for this session' };
489
+ },
490
+ });
491
+ }
492
+ catch (e) {
493
+ try {
494
+ ctx.logger?.warn?.(`[supervisor] dsh_web_restart_status tool failed: ${e?.message ?? String(e)}`);
495
+ }
496
+ catch { }
497
+ }
498
+ return () => {
499
+ try {
500
+ if (typeof dispose === 'function')
501
+ dispose();
502
+ }
503
+ catch { }
504
+ try {
505
+ if (typeof disposeDryboot === 'function')
506
+ disposeDryboot();
507
+ }
508
+ catch { }
509
+ try {
510
+ if (typeof disposeGc === 'function')
511
+ disposeGc();
512
+ }
513
+ catch { }
514
+ try {
515
+ if (typeof disposeStatus === 'function')
516
+ disposeStatus();
517
+ }
518
+ catch { }
519
+ };
520
+ }
521
+ function writeIntentSidecar(sessionId, reason) {
522
+ try {
523
+ if (!sessionId)
524
+ return;
525
+ const dir = join(homedir(), '.dsh/.supervisor/intents');
526
+ const require = createRequire(import.meta.url);
527
+ const { mkdirSync, writeFileSync, chmodSync } = require('node:fs');
528
+ mkdirSync(dir, { recursive: true });
529
+ // Flatten slash-namespaced ids ('proj/abc' → 'proj_abc') so the sidecar is
530
+ // a single file under intents/ and never needs a nested intents/proj/ dir.
531
+ const safeId = sessionId.replace(/[^A-Za-z0-9._-]/g, '_');
532
+ writeFileSync(join(dir, `${safeId}.json`), JSON.stringify({ ts: Date.now(), sessionId, reason: reason ?? '' }), 'utf8');
533
+ try {
534
+ chmodSync(join(dir, `${safeId}.json`), 0o600);
535
+ }
536
+ catch { }
537
+ }
538
+ catch { }
539
+ }