@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,89 @@
1
+ /**
2
+ * Session-log health scan.
3
+ *
4
+ * Deeper resilience for dsh-safe-restart pre-flight: after (or before) a
5
+ * restart, individual session logs under a project session dir can end up in
6
+ * three distinct shapes:
7
+ *
8
+ * 1. healthy multi-frame — one frame per line (a header-only first frame,
9
+ * then per-event frames). The DSH reader depends on
10
+ * this shape to fast-seek the session header.
11
+ * 2. single-frame whole-log — the entire log was written as ONE zstd frame.
12
+ * Data is fully intact (whole-file decode works) but
13
+ * the header cannot be located by a frame walk.
14
+ * 3. corrupt first frame — the first frame cannot be decoded at all.
15
+ *
16
+ * Classification uses fzstd's whole-file decode + streaming Decompress and
17
+ * avoids a hand-rolled zstd frame-header walker (empirically wrong on both
18
+ * real file shapes; fzstd whole-file decode already handles single and
19
+ * concatenated frames). The first-frame probe only ever feeds the streaming
20
+ * decoder a bounded 64 KiB head (log2 scans of ≤256-byte-prefix steps), so it
21
+ * is stack-safe even on long-running many-frame logs — feeding a whole file
22
+ * into the streaming decoder recurses per frame and overflows the V8 stack.
23
+ *
24
+ * Repair re-encodes a single-frame whole-log into the canonical multi-frame
25
+ * shape (frame #1 = exactly the header line, trailing line-batched frames),
26
+ * byte-preserving every event; the original file is kept as a sidecar backup
27
+ * and the replace is atomic (write temp + rename).
28
+ *
29
+ * NOTE: fzstd is a decode-only pure-JS zstd library; re-encoding uses Node's
30
+ * native zlib zstd encoder, whose frames fzstd (and the zstd CLI / DSH's
31
+ * reader) decode as standard concatenated frames.
32
+ */
33
+ export type SessionLogClass = 'ok' | 'single-frame-whole-log' | 'corrupt-first-frame' | 'not-a-session-log';
34
+ export interface SessionHealthEntry {
35
+ path: string;
36
+ klass: SessionLogClass;
37
+ remark?: string;
38
+ }
39
+ /**
40
+ * Classify a single session log file per the validated algorithm.
41
+ *
42
+ * Fast path (dominant case): classify a healthy multi-frame log from its first
43
+ * frame alone — the bounded 64 KiB head probe finds the first-frame boundary,
44
+ * decodes just that frame, and a header-only first frame means `ok` WITHOUT
45
+ * ever decoding the whole file.
46
+ *
47
+ * Whole-file decode is ONLY the fallback corrupt gate:
48
+ * - first frame decodes but is multi-line (or the probe found no boundary
49
+ * within 64 KiB — a first frame bigger than the cap is never a canonical
50
+ * healthy log): whole decode throws → 'corrupt-first-frame', succeeds →
51
+ * 'single-frame-whole-log' (whole decodes to exactly one line → 'ok').
52
+ *
53
+ * Empty files are not session logs.
54
+ */
55
+ export declare function classifySessionLog(path: string): Promise<SessionHealthEntry>;
56
+ /**
57
+ * Re-encode a single-frame-whole-log into canonical multi-frame form:
58
+ * frame #1 = exactly the header line, then line-batched trailing frames.
59
+ * The original file is preserved as `path + backupSuffix` (first time only)
60
+ * and the replace is atomic (temp file + rename).
61
+ */
62
+ export declare function repairSingleFrameLog(path: string, backupSuffix?: string): Promise<void>;
63
+ /**
64
+ * Walk `root` recursively and classify the session log of every session
65
+ * directory found. One directory owns one log — the newest format generation
66
+ * in it (`session.v<N>.jsonl[.zstd]`, generation 0 without the `vN`) is exactly
67
+ * the file the harness reads, so a stale generation beside it is skipped.
68
+ * The process-write layout is <dshHome>/sessions/<project>/<session>/, but we
69
+ * recurse generically so tests and future layouts work unchanged. Resolving the
70
+ * generation by name is load-bearing: matching a literal went blind when the
71
+ * harness bumped it (v3 -> v4 on 2026-09-23), leaving this pre-flight with zero
72
+ * files to classify.
73
+ */
74
+ export declare function scanSessionLogs(root: string): Promise<SessionHealthEntry[]>;
75
+ /**
76
+ * Health check over a session-log root: repair single-frame logs (atomic
77
+ * re-encode), optionally quarantine corrupt-first-frame logs aside, and
78
+ * report counts. `remaining` counts unhealthy entries left untouched
79
+ * (not-a-session-log, corrupt frames when quarantine is off, and
80
+ * single-frame logs when repair is off).
81
+ */
82
+ export declare function runSessionHealthCheck(root: string, opts?: {
83
+ repair?: boolean;
84
+ quarantine?: boolean;
85
+ }): Promise<{
86
+ fixed: number;
87
+ quarantined: number;
88
+ remaining: number;
89
+ }>;
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Session-log health scan.
3
+ *
4
+ * Deeper resilience for dsh-safe-restart pre-flight: after (or before) a
5
+ * restart, individual session logs under a project session dir can end up in
6
+ * three distinct shapes:
7
+ *
8
+ * 1. healthy multi-frame — one frame per line (a header-only first frame,
9
+ * then per-event frames). The DSH reader depends on
10
+ * this shape to fast-seek the session header.
11
+ * 2. single-frame whole-log — the entire log was written as ONE zstd frame.
12
+ * Data is fully intact (whole-file decode works) but
13
+ * the header cannot be located by a frame walk.
14
+ * 3. corrupt first frame — the first frame cannot be decoded at all.
15
+ *
16
+ * Classification uses fzstd's whole-file decode + streaming Decompress and
17
+ * avoids a hand-rolled zstd frame-header walker (empirically wrong on both
18
+ * real file shapes; fzstd whole-file decode already handles single and
19
+ * concatenated frames). The first-frame probe only ever feeds the streaming
20
+ * decoder a bounded 64 KiB head (log2 scans of ≤256-byte-prefix steps), so it
21
+ * is stack-safe even on long-running many-frame logs — feeding a whole file
22
+ * into the streaming decoder recurses per frame and overflows the V8 stack.
23
+ *
24
+ * Repair re-encodes a single-frame whole-log into the canonical multi-frame
25
+ * shape (frame #1 = exactly the header line, trailing line-batched frames),
26
+ * byte-preserving every event; the original file is kept as a sidecar backup
27
+ * and the replace is atomic (write temp + rename).
28
+ *
29
+ * NOTE: fzstd is a decode-only pure-JS zstd library; re-encoding uses Node's
30
+ * native zlib zstd encoder, whose frames fzstd (and the zstd CLI / DSH's
31
+ * reader) decode as standard concatenated frames.
32
+ */
33
+ import { decompress, Decompress } from 'fzstd';
34
+ import { copyFileSync, existsSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
35
+ import { zstdCompressSync } from 'node:zlib';
36
+ import { join } from 'node:path';
37
+ import { resolveSessionLogPath } from './session-log-file.js';
38
+ /**
39
+ * Cap on the file head probed through the streaming decoder. Feeding a whole
40
+ * long-running log (thousands of concatenated zstd frames) into fzstd's
41
+ * streaming `Decompress` in one push recurses once per frame and overflows the
42
+ * V8 stack (RangeError: Maximum call stack size exceeded, seen on a real
43
+ * ~1.8 MB session log). Only the first frame matters for classification, so we
44
+ * never probe past 64 KiB — a canonical log's first frame is a few hundred
45
+ * bytes, and a frame can never legitimately straddle this cap.
46
+ */
47
+ const FIRST_FRAME_CAP = 64 * 1024;
48
+ /** Standard zstd frame encoder (node:zlib) — decode-compatible with fzstd. */
49
+ function compress(data) {
50
+ return zstdCompressSync(data);
51
+ }
52
+ /**
53
+ * Smallest head prefix at which the streaming decoder first emits output
54
+ * (≈ first-frame completion), searched only within FIRST_FRAME_CAP. Never
55
+ * pushes more than the cap into the decoder, so the probe is stack-safe on
56
+ * arbitrarily large many-frame logs. A push that throws on invalid bytes past
57
+ * the first decoded frame is harmless to the boundary search — once the first
58
+ * frame has emitted (`fired`), the boundary is already known, so the throw is
59
+ * swallowed. Only garbage that decodes nothing yields `{ found: false }`.
60
+ */
61
+ function firstFrameHead(buf) {
62
+ const emits = (len) => {
63
+ let fired = false;
64
+ const d = new Decompress((chunk) => { if (chunk.length > 0)
65
+ fired = true; });
66
+ try {
67
+ d.push(buf.subarray(0, len));
68
+ }
69
+ catch {
70
+ // Invalid bytes past the first frame (corrupt tail): the decoder had
71
+ // already emitted the first frame's output → keep `fired` as-is.
72
+ }
73
+ return fired;
74
+ };
75
+ const cap = Math.min(buf.length, FIRST_FRAME_CAP);
76
+ let hi = cap;
77
+ for (let l = 256; l <= cap; l += 256)
78
+ if (emits(l)) {
79
+ hi = l;
80
+ break;
81
+ }
82
+ if (!emits(cap))
83
+ return { found: false }; // no frame boundary within the cap
84
+ let lo = 0;
85
+ while (lo + 1 < hi) {
86
+ const mid = (lo + hi) >> 1;
87
+ emits(mid) ? hi = mid : lo = mid;
88
+ }
89
+ return { found: true, end: hi };
90
+ }
91
+ function isSingleHeaderLine(plain) {
92
+ if (plain.length === 0)
93
+ return false;
94
+ const nl = plain.indexOf(0x0a);
95
+ return nl === plain.length - 1; // exactly one line, terminated by '\n'
96
+ }
97
+ /**
98
+ * Classify a single session log file per the validated algorithm.
99
+ *
100
+ * Fast path (dominant case): classify a healthy multi-frame log from its first
101
+ * frame alone — the bounded 64 KiB head probe finds the first-frame boundary,
102
+ * decodes just that frame, and a header-only first frame means `ok` WITHOUT
103
+ * ever decoding the whole file.
104
+ *
105
+ * Whole-file decode is ONLY the fallback corrupt gate:
106
+ * - first frame decodes but is multi-line (or the probe found no boundary
107
+ * within 64 KiB — a first frame bigger than the cap is never a canonical
108
+ * healthy log): whole decode throws → 'corrupt-first-frame', succeeds →
109
+ * 'single-frame-whole-log' (whole decodes to exactly one line → 'ok').
110
+ *
111
+ * Empty files are not session logs.
112
+ */
113
+ export async function classifySessionLog(path) {
114
+ let buf;
115
+ try {
116
+ buf = readFileSync(path);
117
+ }
118
+ catch {
119
+ return { path, klass: 'not-a-session-log' };
120
+ }
121
+ if (buf.length === 0)
122
+ return { path, klass: 'not-a-session-log' };
123
+ const head = firstFrameHead(buf);
124
+ if (head.found) {
125
+ let first;
126
+ try {
127
+ first = Buffer.from(decompress(buf.subarray(0, head.end)));
128
+ }
129
+ catch { /* prefix not a complete frame */ }
130
+ if (first?.byteLength !== undefined && isSingleHeaderLine(first))
131
+ return { path, klass: 'ok' };
132
+ // First frame decodes but is multi-line (or the prefix is not a complete
133
+ // frame): the whole file must still decode for this to be recoverable.
134
+ try {
135
+ decompress(buf);
136
+ }
137
+ catch {
138
+ return { path, klass: 'corrupt-first-frame' };
139
+ }
140
+ return { path, klass: 'single-frame-whole-log' };
141
+ }
142
+ // No frame boundary within the cap — first frame is bigger than 64 KiB, never
143
+ // a canonical healthy log. The whole-file decode is authoritative.
144
+ let whole;
145
+ try {
146
+ whole = Buffer.from(decompress(buf));
147
+ }
148
+ catch {
149
+ return { path, klass: 'corrupt-first-frame' };
150
+ }
151
+ if (isSingleHeaderLine(whole))
152
+ return { path, klass: 'ok' };
153
+ return { path, klass: 'single-frame-whole-log' }; // whole-file decodes; first frame isn't header-only → recoverable
154
+ }
155
+ /**
156
+ * Re-encode a single-frame-whole-log into canonical multi-frame form:
157
+ * frame #1 = exactly the header line, then line-batched trailing frames.
158
+ * The original file is preserved as `path + backupSuffix` (first time only)
159
+ * and the replace is atomic (temp file + rename).
160
+ */
161
+ export async function repairSingleFrameLog(path, backupSuffix = '.corrupt-singleframe.bak') {
162
+ const buf = readFileSync(path);
163
+ const whole = Buffer.from(decompress(buf));
164
+ const nl = whole.indexOf(0x0a);
165
+ const header = whole.subarray(0, nl + 1);
166
+ const rest = whole.subarray(nl + 1);
167
+ if (!existsSync(path + backupSuffix))
168
+ copyFileSync(path, path + backupSuffix);
169
+ const frames = [compress(header)];
170
+ let start = 0;
171
+ for (let i = 0; i < rest.length; i++) {
172
+ if (rest[i] === 0x0a && i - start + 1 >= 64 * 1024) {
173
+ frames.push(compress(rest.subarray(start, i + 1)));
174
+ start = i + 1;
175
+ }
176
+ }
177
+ if (start < rest.length)
178
+ frames.push(compress(rest.subarray(start)));
179
+ const tmp = path + '.repair.tmp';
180
+ writeFileSync(tmp, Buffer.concat(frames));
181
+ renameSync(tmp, path);
182
+ }
183
+ /**
184
+ * Walk `root` recursively and classify the session log of every session
185
+ * directory found. One directory owns one log — the newest format generation
186
+ * in it (`session.v<N>.jsonl[.zstd]`, generation 0 without the `vN`) is exactly
187
+ * the file the harness reads, so a stale generation beside it is skipped.
188
+ * The process-write layout is <dshHome>/sessions/<project>/<session>/, but we
189
+ * recurse generically so tests and future layouts work unchanged. Resolving the
190
+ * generation by name is load-bearing: matching a literal went blind when the
191
+ * harness bumped it (v3 -> v4 on 2026-09-23), leaving this pre-flight with zero
192
+ * files to classify.
193
+ */
194
+ export async function scanSessionLogs(root) {
195
+ const found = [];
196
+ const walk = (dir) => {
197
+ let entries;
198
+ try {
199
+ entries = readdirSync(dir, { withFileTypes: true });
200
+ }
201
+ catch {
202
+ return;
203
+ }
204
+ const log = resolveSessionLogPath(dir);
205
+ if (log !== undefined)
206
+ found.push(log);
207
+ for (const e of entries)
208
+ if (e.isDirectory())
209
+ walk(join(dir, e.name));
210
+ };
211
+ walk(root);
212
+ const out = [];
213
+ for (const p of found) {
214
+ try {
215
+ out.push(await classifySessionLog(p));
216
+ }
217
+ catch (err) {
218
+ // One unreadable / unclassifiable file must never abort the whole scan.
219
+ out.push({ path: p, klass: 'corrupt-first-frame', remark: err instanceof Error ? err.message : String(err) });
220
+ }
221
+ }
222
+ return out;
223
+ }
224
+ /**
225
+ * Health check over a session-log root: repair single-frame logs (atomic
226
+ * re-encode), optionally quarantine corrupt-first-frame logs aside, and
227
+ * report counts. `remaining` counts unhealthy entries left untouched
228
+ * (not-a-session-log, corrupt frames when quarantine is off, and
229
+ * single-frame logs when repair is off).
230
+ */
231
+ export async function runSessionHealthCheck(root, opts = {}) {
232
+ const repair = opts.repair ?? true;
233
+ const quarantine = opts.quarantine ?? false;
234
+ let fixed = 0;
235
+ let quarantined = 0;
236
+ let remaining = 0;
237
+ for (const entry of await scanSessionLogs(root)) {
238
+ try {
239
+ switch (entry.klass) {
240
+ case 'single-frame-whole-log':
241
+ if (repair) {
242
+ await repairSingleFrameLog(entry.path);
243
+ fixed++;
244
+ }
245
+ else
246
+ remaining++;
247
+ break;
248
+ case 'corrupt-first-frame':
249
+ if (quarantine) {
250
+ let aside = entry.path + '.corrupt-' + Date.now() + '.bak';
251
+ let n = 0;
252
+ while (existsSync(aside))
253
+ aside = entry.path + '.corrupt-' + Date.now() + '-' + (++n) + '.bak';
254
+ renameSync(entry.path, aside);
255
+ quarantined++;
256
+ }
257
+ else
258
+ remaining++;
259
+ break;
260
+ case 'not-a-session-log':
261
+ remaining++;
262
+ break;
263
+ default:
264
+ break;
265
+ }
266
+ }
267
+ catch {
268
+ // Repair/quarantine of a single entry failed — it stays unhealthy and
269
+ // can never abort the whole pass. Counts always reconcile.
270
+ remaining++;
271
+ }
272
+ }
273
+ return { fixed, quarantined, remaining };
274
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Session format generation encoded in a log filename.
3
+ * @param name - bare file name (no directory).
4
+ * @returns the generation number, or `undefined` when the name is not a session log.
5
+ */
6
+ export declare function sessionLogGeneration(name: string): number | undefined;
7
+ /**
8
+ * Whether a bare file name is a session log of any generation.
9
+ * @param name - bare file name (no directory).
10
+ */
11
+ export declare function isSessionLogName(name: string): boolean;
12
+ /**
13
+ * Resolve the readable session log inside one session directory across format
14
+ * generations. The newest generation wins — that is where a live session
15
+ * persists, while older generations stay behind as migration artifacts (a
16
+ * directory can hold several, and judging the session by a stale one both
17
+ * misses a recovery and can fire a false one). Within one generation the
18
+ * compressed `.jsonl.zstd` artifact wins over plaintext.
19
+ * @param dir - one session directory.
20
+ * @returns the absolute log path, or `undefined` when the directory holds no log.
21
+ */
22
+ export declare function resolveSessionLogPath(dir: string): string | undefined;
@@ -0,0 +1,74 @@
1
+ import * as fs from 'node:fs';
2
+ import { join } from 'node:path';
3
+ /**
4
+ * Which file inside a session directory is that session's readable log.
5
+ *
6
+ * The harness names the artifact by Session format generation —
7
+ * `generationLogFilename(version, compression)`: version 0 keeps the
8
+ * suffix-only name (`session.jsonl[.zstd]`), and every later generation carries
9
+ * a lowercase numeric `vN` (`session.v4.jsonl.zstd`). Generations are
10
+ * unbounded, so this module PARSES the name and picks the newest generation
11
+ * instead of enumerating literal filenames.
12
+ *
13
+ * Why that matters: a hardcoded list goes blind at every generation bump, and
14
+ * the failure is silent — the scan simply finds no session. It happened on
15
+ * 2026-09-11 (v3 landed, auto-resume found nothing after a restart) and again
16
+ * on 2026-09-23 (v4 landed with DSH 0.1.7-rc.1: `findInterrupted` reported
17
+ * `0/N` interrupted, the boot pre-flight had nothing to classify, and session
18
+ * preset recovery read no header). Never reintroduce a literal generation list
19
+ * here.
20
+ */
21
+ /** `session.jsonl[.zstd]` (generation 0) or `session.v<N>.jsonl[.zstd]`. */
22
+ const SESSION_LOG_NAME = /^session(?:\.v(\d+))?\.jsonl(?:\.zstd)?$/;
23
+ /**
24
+ * Session format generation encoded in a log filename.
25
+ * @param name - bare file name (no directory).
26
+ * @returns the generation number, or `undefined` when the name is not a session log.
27
+ */
28
+ export function sessionLogGeneration(name) {
29
+ const match = SESSION_LOG_NAME.exec(name);
30
+ if (match === null)
31
+ return undefined;
32
+ return match[1] === undefined ? 0 : Number(match[1]);
33
+ }
34
+ /**
35
+ * Whether a bare file name is a session log of any generation.
36
+ * @param name - bare file name (no directory).
37
+ */
38
+ export function isSessionLogName(name) {
39
+ return sessionLogGeneration(name) !== undefined;
40
+ }
41
+ /**
42
+ * Resolve the readable session log inside one session directory across format
43
+ * generations. The newest generation wins — that is where a live session
44
+ * persists, while older generations stay behind as migration artifacts (a
45
+ * directory can hold several, and judging the session by a stale one both
46
+ * misses a recovery and can fire a false one). Within one generation the
47
+ * compressed `.jsonl.zstd` artifact wins over plaintext.
48
+ * @param dir - one session directory.
49
+ * @returns the absolute log path, or `undefined` when the directory holds no log.
50
+ */
51
+ export function resolveSessionLogPath(dir) {
52
+ let entries;
53
+ try {
54
+ entries = fs.readdirSync(dir);
55
+ }
56
+ catch {
57
+ return undefined;
58
+ }
59
+ let bestName;
60
+ let bestGeneration = -1;
61
+ let bestCompressed = false;
62
+ for (const name of entries) {
63
+ const generation = sessionLogGeneration(name);
64
+ if (generation === undefined)
65
+ continue;
66
+ const compressed = name.endsWith('.zstd');
67
+ if (generation > bestGeneration || (generation === bestGeneration && compressed && !bestCompressed)) {
68
+ bestName = name;
69
+ bestGeneration = generation;
70
+ bestCompressed = compressed;
71
+ }
72
+ }
73
+ return bestName === undefined ? undefined : join(dir, bestName);
74
+ }
@@ -0,0 +1,6 @@
1
+ import type { SkillCandidate, SkillDefinition, SkillLookupOptions } from '@deepseek-ai/dsh-skill';
2
+ export declare function makeSkillProvider(skillsDir: string): {
3
+ name: string;
4
+ list(_options: SkillLookupOptions): Promise<SkillCandidate[]>;
5
+ get(candidate: SkillCandidate, _options: SkillLookupOptions): Promise<SkillDefinition | undefined>;
6
+ };
@@ -0,0 +1,73 @@
1
+ import { readFile, stat } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ const SKILL_NAME = 'dsh-safe-restart';
4
+ /** Minimal frontmatter reader for our own SKILL.md — enough to serve the provider contract. */
5
+ function parseFrontmatter(raw) {
6
+ // `\r?\n` on both delimiters and on the line split: a SKILL.md checked out
7
+ // with CRLF (git core.autocrlf, a Windows editor) otherwise parses to an
8
+ // empty description with no error at all.
9
+ const m = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);
10
+ if (!m)
11
+ return { name: SKILL_NAME, description: '', body: raw };
12
+ const fm = m[1].split(/\r?\n/).reduce((acc, line) => {
13
+ const kv = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);
14
+ if (kv)
15
+ acc[kv[1]] = kv[2].replace(/^["']|["']$/g, '');
16
+ return acc;
17
+ }, {});
18
+ return { name: fm.name || SKILL_NAME, description: fm.description || '', body: m[2] };
19
+ }
20
+ export function makeSkillProvider(skillsDir) {
21
+ return {
22
+ // The dsh-skill service attributes candidates through the provider
23
+ // object's own `name` (maestro-skills returns `{ name, list, get }`); a
24
+ // missing name surfaces at runtime as `skill provider "undefined" returned
25
+ // skill ... for provider "maestro-supervisor"` and fails every turn.
26
+ name: 'maestro-supervisor',
27
+ async list(_options) {
28
+ const entry = join(skillsDir, SKILL_NAME);
29
+ const st = await stat(entry).catch(() => null);
30
+ if (!st?.isDirectory())
31
+ return [];
32
+ const skillFilePath = join(entry, 'SKILL.md');
33
+ const fileSt = await stat(skillFilePath).catch(() => null);
34
+ if (!fileSt?.isFile())
35
+ return [];
36
+ const raw = await readFile(skillFilePath, 'utf-8').catch(() => null);
37
+ if (raw === null)
38
+ return [];
39
+ const { name, description } = parseFrontmatter(raw);
40
+ return [{
41
+ name,
42
+ description,
43
+ invocation: { modelInvocable: true, userInvocable: true },
44
+ source: 'custom',
45
+ provider: 'maestro-supervisor',
46
+ rank: 360,
47
+ locator: skillFilePath,
48
+ path: skillFilePath,
49
+ resourceBase: { kind: 'directory', path: entry },
50
+ metadata: { name, description },
51
+ }];
52
+ },
53
+ async get(candidate, _options) {
54
+ try {
55
+ const raw = await readFile(candidate.path, 'utf-8');
56
+ const { name, description, body } = parseFrontmatter(raw);
57
+ return {
58
+ name, description,
59
+ invocation: candidate.invocation,
60
+ source: candidate.source,
61
+ provider: candidate.provider,
62
+ resourceBase: candidate.resourceBase,
63
+ path: candidate.path,
64
+ content: body,
65
+ metadata: candidate.metadata,
66
+ };
67
+ }
68
+ catch {
69
+ return undefined;
70
+ }
71
+ },
72
+ };
73
+ }
@@ -0,0 +1,59 @@
1
+ export interface SnapshotResult {
2
+ ts: string;
3
+ /** Files (and symlinks) copied into this snapshot. */
4
+ files: number;
5
+ /** Entries that could not be copied; the snapshot stays usable either way. */
6
+ skipped: Array<{
7
+ path: string;
8
+ reason: string;
9
+ }>;
10
+ }
11
+ export interface SnapshotDeps {
12
+ /**
13
+ * Copy one regular file, preserving `mode`. Injectable so a failing entry
14
+ * (the EACCES a read-only attachment object produces) can be table-tested
15
+ * without depending on the host's uid or filesystem quirks.
16
+ */
17
+ copyFile?: (src: string, dest: string, mode: number) => void;
18
+ }
19
+ /**
20
+ * DSH-home entries the last-known-good snapshot deliberately never copies.
21
+ *
22
+ * The LKG exists to recover a boot that fails while loading the plugin tree, so
23
+ * it holds boot **configuration**: `profiles/` (the plugin tree with its
24
+ * lockfile, `cordis.patch.yml` and sidecars), the per-plugin config directories
25
+ * and the settings documents. Everything below is runtime **data** — it is
26
+ * written continuously while `dsh web` runs, so restoring a snapshot of it can
27
+ * only lose newer state, and some of it is hostile to a bulk copy:
28
+ *
29
+ * - `sessions/` — append-only transcripts. Restoring a stale copy over live
30
+ * sessions drops every turn recorded after the snapshot, i.e. the recovery
31
+ * path would lose the log it is supposed to protect.
32
+ * - `attachments/` — content-addressed blobs stored mode `0400`. That read-only
33
+ * bit is exactly what made the 2026-09-13 rollback abort with
34
+ * `EACCES: Permission denied '.../attachments/v1/objects/f8'`.
35
+ * - `plugins-src/` — plugin source cache, re-fetched on demand (~400 MB host).
36
+ * - `.supervisor/` — the LKG root itself lives inside the DSH home, so copying
37
+ * it would recurse into every retained snapshot.
38
+ *
39
+ * This list is data, not a heuristic: the copy loop and the restore loop both
40
+ * consult `isLkgExcluded()`, and the table test pins the rule.
41
+ */
42
+ export declare const LKG_EXCLUDED_ENTRIES: readonly string[];
43
+ /**
44
+ * True when a DSH-home-relative path must never enter (or leave) the LKG.
45
+ *
46
+ * The named entries match the first path segment; `*.log` matches by basename
47
+ * anywhere, because append-only logs are data at any depth and a restored stale
48
+ * `dsh-web.log` would poison the boot-boundary scan.
49
+ */
50
+ export declare function isLkgExcluded(relPath: string): boolean;
51
+ /** Human-readable, bounded reason for a per-entry copy failure. */
52
+ export declare function failureReason(e: unknown): string;
53
+ export declare function writeLKG(dshHome: string, lkgRoot: string, deps?: SnapshotDeps): Promise<SnapshotResult>;
54
+ export declare function pruneByAge(root: string, maxAgeMs: number): Promise<void>;
55
+ export declare function pruneBySize(root: string, maxBytes: number): Promise<void>;
56
+ export declare function isDuplicateLKG(dshHome: string, lkgRoot: string): Promise<boolean>;
57
+ export declare function verifyLKG(lkgPath: string): Promise<boolean>;
58
+ export declare function rotateLKG(lkgRoot: string, keep?: number): Promise<void>;
59
+ export declare function writeFailed(dshHome: string, failedRoot: string): Promise<SnapshotResult>;