@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,176 @@
1
+ import { createHash } from 'node:crypto';
2
+ import * as path from 'node:path';
3
+ import { normalizeEligiblePath } from './validation.js';
4
+ export function hashBuffer(buf) {
5
+ return createHash('sha256').update(buf).digest('hex');
6
+ }
7
+ export function kindForPath(p) {
8
+ const normalized = p; // caller should have validated; we still dispatch by suffix
9
+ if (normalized.endsWith('.zstd'))
10
+ return 'session';
11
+ if (normalized.endsWith('.jsonl'))
12
+ return 'jsonl';
13
+ return 'memory';
14
+ }
15
+ export function snapshotFile(validatedPath, content) {
16
+ const normalized = normalizeEligiblePath(validatedPath);
17
+ const sha256 = hashBuffer(content);
18
+ const kind = kindForPath(normalized);
19
+ return { path: normalized, sha256, size: content.length, kind };
20
+ }
21
+ /**
22
+ * Collect snapshots for all eligible files under root using the provided fs.
23
+ * - Walks recursively via fs.readdirSync/statSync/readFileSync when available.
24
+ * - Validates each discovered relative path via normalizeEligiblePath.
25
+ * - Hashes file bytes with SHA-256 and records kind.
26
+ * Returns sorted snapshots by path for determinism.
27
+ */
28
+ export function collectSnapshots(root, fs) {
29
+ const result = [];
30
+ if (!root || typeof root !== 'string')
31
+ return result;
32
+ const fsMod = fs ?? {};
33
+ // Check root exists
34
+ try {
35
+ if (fsMod.existsSync && !fsMod.existsSync(root))
36
+ return [];
37
+ }
38
+ catch {
39
+ return [];
40
+ }
41
+ const walk = (dir, base) => {
42
+ let entries = [];
43
+ try {
44
+ if (typeof fsMod.readdirSync !== 'function')
45
+ return;
46
+ const raw = fsMod.readdirSync(dir, { withFileTypes: true });
47
+ if (!raw || raw.length === 0)
48
+ return;
49
+ // handle string[] mode (no withFileTypes)
50
+ if (typeof raw[0] === 'string') {
51
+ for (const name of raw) {
52
+ const full = path.join(dir, name);
53
+ let st = null;
54
+ try {
55
+ st = fsMod.statSync ? fsMod.statSync(full) : null;
56
+ }
57
+ catch {
58
+ continue;
59
+ }
60
+ const isDir = st && typeof st.isDirectory === 'function' ? st.isDirectory() : false;
61
+ if (isDir)
62
+ walk(full, path.join(base, name));
63
+ else {
64
+ const relPosix = path.join(base, name).split(path.sep).join('/');
65
+ try {
66
+ normalizeEligiblePath(relPosix);
67
+ }
68
+ catch {
69
+ continue;
70
+ }
71
+ try {
72
+ let buf;
73
+ if (typeof fsMod.readFileSync === 'function') {
74
+ const data = fsMod.readFileSync(full);
75
+ buf = Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf-8');
76
+ }
77
+ else {
78
+ continue;
79
+ }
80
+ result.push(snapshotFile(relPosix, buf));
81
+ }
82
+ catch {
83
+ // skip unreadable
84
+ }
85
+ }
86
+ }
87
+ return;
88
+ }
89
+ for (const ent of raw) {
90
+ const name = ent.name ?? String(ent);
91
+ const full = path.join(dir, name);
92
+ const isDir = typeof ent.isDirectory === 'function' ? ent.isDirectory() : false;
93
+ if (isDir) {
94
+ walk(full, path.join(base, name));
95
+ }
96
+ else {
97
+ const relPosix = path.join(base, name).split(path.sep).join('/');
98
+ try {
99
+ normalizeEligiblePath(relPosix);
100
+ }
101
+ catch {
102
+ continue;
103
+ }
104
+ try {
105
+ let buf;
106
+ if (typeof fsMod.readFileSync === 'function') {
107
+ const data = fsMod.readFileSync(full);
108
+ buf = Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf-8');
109
+ }
110
+ else
111
+ continue;
112
+ result.push(snapshotFile(relPosix, buf));
113
+ }
114
+ catch {
115
+ // skip
116
+ }
117
+ }
118
+ }
119
+ }
120
+ catch {
121
+ // walk errors are ignored
122
+ }
123
+ };
124
+ walk(root, '');
125
+ // Deterministic sort
126
+ result.sort((a, b) => a.path.localeCompare(b.path));
127
+ return result;
128
+ }
129
+ /**
130
+ * Snapshot a specific list of validated eligible paths under root.
131
+ * Useful for hashing staged remote files where we already know the manifest.
132
+ */
133
+ export function snapshotPaths(root, paths, fs) {
134
+ const fsMod = fs ?? {};
135
+ const out = [];
136
+ for (const p of paths) {
137
+ let normalized;
138
+ try {
139
+ normalized = normalizeEligiblePath(p);
140
+ }
141
+ catch {
142
+ continue;
143
+ }
144
+ const full = path.join(root, normalized);
145
+ try {
146
+ if (fsMod.existsSync && !fsMod.existsSync(full))
147
+ continue;
148
+ if (typeof fsMod.readFileSync !== 'function')
149
+ continue;
150
+ const data = fsMod.readFileSync(full);
151
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf-8');
152
+ out.push(snapshotFile(normalized, buf));
153
+ }
154
+ catch {
155
+ continue;
156
+ }
157
+ }
158
+ out.sort((a, b) => a.path.localeCompare(b.path));
159
+ return out;
160
+ }
161
+ /**
162
+ * Snapshot from an in-memory map of path -> Buffer (useful for testing staged remote).
163
+ */
164
+ export function snapshotFromMap(contents) {
165
+ const out = [];
166
+ for (const [p, buf] of contents.entries()) {
167
+ try {
168
+ out.push(snapshotFile(p, buf));
169
+ }
170
+ catch {
171
+ continue;
172
+ }
173
+ }
174
+ out.sort((a, b) => a.path.localeCompare(b.path));
175
+ return out;
176
+ }
@@ -0,0 +1,12 @@
1
+ import type { ProcessRunner } from './process-runner.js';
2
+ export interface SshMux {
3
+ socketPath: string;
4
+ sshArgs: string[];
5
+ rsyncRsh: string;
6
+ dispose(): Promise<void>;
7
+ }
8
+ export declare function openSshMux(opts: {
9
+ host: string;
10
+ baseDir: string;
11
+ runner: ProcessRunner;
12
+ }): Promise<SshMux>;
@@ -0,0 +1,48 @@
1
+ // src/host/ssh-mux.ts — per-operation SSH ControlMaster multiplexing.
2
+ //
3
+ // One backgrounded master (`ssh -S <socket> -o ControlMaster=yes -f -N`) owns
4
+ // the connection; every subsequent spawn in the operation passes `-S <socket>`
5
+ // (ssh slaves) or `rsync -e "ssh -S <socket>"` (single validated argv) so a
6
+ // multi-spawn flow pays one handshake. The socket lives in a private 0700 dir
7
+ // and is torn down with `-O exit`; a dead master degrades to a fresh handshake.
8
+ import * as fs from 'node:fs';
9
+ import * as path from 'node:path';
10
+ function sanitizeHost(host) {
11
+ return host.replace(/[^A-Za-z0-9._-]/g, '_');
12
+ }
13
+ export async function openSshMux(opts) {
14
+ const dir = path.join(opts.baseDir, `${sanitizeHost(opts.host)}-${Math.random().toString(16).slice(2, 6)}`);
15
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
16
+ const socketPath = path.join(dir, 'ssh.sock');
17
+ const connectOpts = ['-o', 'ConnectTimeout=5', '-o', 'BatchMode=yes'];
18
+ // -f backgrounds the master after auth and the process exits 0, so runner.run
19
+ // does not hang on a connection that is meant to stay alive.
20
+ const masterArgs = ['-S', socketPath, '-o', 'ControlMaster=yes', '-o', 'ControlPersist=60', ...connectOpts, opts.host, '-f', '-N'];
21
+ const res = await opts.runner.run('ssh', masterArgs, { timeoutMs: 8000 });
22
+ if (res.exitCode !== 0) {
23
+ try {
24
+ fs.rmSync(dir, { recursive: true, force: true });
25
+ }
26
+ catch { }
27
+ throw Object.assign(new Error(`ssh mux master failed: ${res.stderr.toString()}`), {
28
+ phase: 'snapshot',
29
+ code: 'MUX_FAILED',
30
+ detail: res.stderr.toString() || `exit ${res.exitCode}`,
31
+ });
32
+ }
33
+ return {
34
+ socketPath,
35
+ sshArgs: ['-S', socketPath],
36
+ rsyncRsh: `ssh -S ${socketPath}`,
37
+ dispose: async () => {
38
+ try {
39
+ await opts.runner.run('ssh', ['-S', socketPath, '-O', 'exit', opts.host], { timeoutMs: 5000 });
40
+ }
41
+ catch { }
42
+ try {
43
+ fs.rmSync(dir, { recursive: true, force: true });
44
+ }
45
+ catch { }
46
+ },
47
+ };
48
+ }
@@ -0,0 +1,24 @@
1
+ import type { FileSnapshot, SyncPlan, SyncPreview, SyncDirection } from './sync-types.js';
2
+ export declare const PREVIEW_TTL_MS = 60000;
3
+ export declare const MAX_PREVIEWS = 50;
4
+ /**
5
+ * Persist a preview to disk so a later process (a separate CLI apply) can
6
+ * consume it. The file mirrors the in-memory record; the TTL is enforced on
7
+ * read. Sidecar only — a plain operational folder under DSH_HOME, never part
8
+ * of the eligible sync data.
9
+ */
10
+ export declare function persistPreview(preview: SyncPreview, direction?: SyncDirection, dir?: string): string;
11
+ /** Delete every persisted preview file under dir (cleanup helper). */
12
+ export declare function clearPreviewStore(dir: string): void;
13
+ export declare function storePreview(preview: SyncPreview, direction?: SyncDirection, dir?: string): void;
14
+ export declare function getPreview(id: string, dir?: string): SyncPreview | undefined;
15
+ export declare function getPreviewDirection(id: string): SyncDirection | undefined;
16
+ export declare function deletePreview(id: string, dir?: string): void;
17
+ export declare function clearPreviews(): void;
18
+ export declare function revisionFrom(snapshots: FileSnapshot[], direction: SyncDirection): string;
19
+ export declare function buildPlan(localSnapshots: FileSnapshot[], remoteSnapshots: FileSnapshot[], direction: SyncDirection, localContents: Map<string, Buffer>, remoteContents: Map<string, Buffer>, opts?: {
20
+ countOnlySessions?: boolean;
21
+ }): Promise<SyncPlan>;
22
+ export declare function buildPreview(localSnapshots: FileSnapshot[], remoteSnapshots: FileSnapshot[], direction: SyncDirection, localContents: Map<string, Buffer>, remoteContents: Map<string, Buffer>, opts?: {
23
+ countOnlySessions?: boolean;
24
+ }): Promise<SyncPreview>;
@@ -0,0 +1,366 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import * as path from 'node:path';
3
+ import * as fs from 'node:fs';
4
+ import { mergeDelimited } from './merge.js';
5
+ import { isSameSession, mergeSessionBuffers } from './session-plan.js';
6
+ export const PREVIEW_TTL_MS = 60_000;
7
+ export const MAX_PREVIEWS = 50;
8
+ const previews = new Map();
9
+ const previewDirections = new Map();
10
+ function previewFile(id, dir) {
11
+ return path.join(dir, `${id}.json`);
12
+ }
13
+ /** Read a persisted preview record (null when missing/corrupt). */
14
+ function readPersisted(id, dir) {
15
+ try {
16
+ const parsed = JSON.parse(fs.readFileSync(previewFile(id, dir), 'utf-8'));
17
+ if (!parsed || typeof parsed !== 'object' || typeof parsed.preview?.previewId !== 'string')
18
+ return null;
19
+ return { preview: parsed.preview, direction: parsed.direction };
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ }
25
+ function pruneExpired() {
26
+ const now = Date.now();
27
+ for (const [id, p] of previews.entries()) {
28
+ if (new Date(p.expiresAt).getTime() <= now) {
29
+ previews.delete(id);
30
+ previewDirections.delete(id);
31
+ }
32
+ }
33
+ if (previews.size > MAX_PREVIEWS) {
34
+ const entries = [...previews.entries()].sort((a, b) => new Date(a[1].expiresAt).getTime() - new Date(b[1].expiresAt).getTime());
35
+ const toDelete = previews.size - MAX_PREVIEWS;
36
+ for (let i = 0; i < toDelete; i++) {
37
+ const delId = entries[i][0];
38
+ previews.delete(delId);
39
+ previewDirections.delete(delId);
40
+ }
41
+ }
42
+ }
43
+ /**
44
+ * Persist a preview to disk so a later process (a separate CLI apply) can
45
+ * consume it. The file mirrors the in-memory record; the TTL is enforced on
46
+ * read. Sidecar only — a plain operational folder under DSH_HOME, never part
47
+ * of the eligible sync data.
48
+ */
49
+ export function persistPreview(preview, direction, dir) {
50
+ if (!dir)
51
+ return '';
52
+ try {
53
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
54
+ const now = Date.now();
55
+ let files = [];
56
+ try {
57
+ files = fs.readdirSync(dir).filter((f) => f.endsWith('.json'));
58
+ }
59
+ catch {
60
+ files = [];
61
+ }
62
+ // purge expired records, then cap at MAX_PREVIEWS (oldest first)
63
+ const keep = [];
64
+ for (const f of files) {
65
+ if (f === `${preview.previewId}.json`)
66
+ continue;
67
+ const record = readPersisted(f.slice(0, -5), dir);
68
+ if (record && new Date(record.preview.expiresAt).getTime() > now)
69
+ keep.push(f);
70
+ else {
71
+ try {
72
+ fs.unlinkSync(path.join(dir, f));
73
+ }
74
+ catch { }
75
+ }
76
+ }
77
+ keep.sort();
78
+ while (keep.length >= MAX_PREVIEWS) {
79
+ const old = keep.shift();
80
+ try {
81
+ fs.unlinkSync(path.join(dir, old));
82
+ }
83
+ catch { }
84
+ }
85
+ const target = previewFile(preview.previewId, dir);
86
+ const tmp = target + `.tmp.${randomBytes(4).toString('hex')}`;
87
+ fs.writeFileSync(tmp, JSON.stringify({ preview, direction }), 'utf-8');
88
+ fs.renameSync(tmp, target);
89
+ try {
90
+ fs.chmodSync(target, 0o600);
91
+ }
92
+ catch { }
93
+ }
94
+ catch {
95
+ // persistence is best-effort; the in-memory record still works in-process
96
+ }
97
+ return previewFile(preview.previewId, dir);
98
+ }
99
+ /** Delete every persisted preview file under dir (cleanup helper). */
100
+ export function clearPreviewStore(dir) {
101
+ if (!dir)
102
+ return;
103
+ try {
104
+ for (const f of fs.readdirSync(dir)) {
105
+ if (f.endsWith('.json')) {
106
+ try {
107
+ fs.unlinkSync(path.join(dir, f));
108
+ }
109
+ catch { }
110
+ }
111
+ }
112
+ }
113
+ catch { }
114
+ }
115
+ export function storePreview(preview, direction, dir) {
116
+ pruneExpired();
117
+ if (previews.size >= MAX_PREVIEWS) {
118
+ let oldestId = null;
119
+ let oldestTime = Infinity;
120
+ for (const [id, p] of previews.entries()) {
121
+ const t = new Date(p.expiresAt).getTime();
122
+ if (t < oldestTime) {
123
+ oldestTime = t;
124
+ oldestId = id;
125
+ }
126
+ }
127
+ if (oldestId) {
128
+ previews.delete(oldestId);
129
+ previewDirections.delete(oldestId);
130
+ }
131
+ }
132
+ previews.set(preview.previewId, preview);
133
+ if (direction)
134
+ previewDirections.set(preview.previewId, direction);
135
+ if (dir)
136
+ persistPreview(preview, direction, dir);
137
+ const ttl = Math.max(0, new Date(preview.expiresAt).getTime() - Date.now());
138
+ setTimeout(() => {
139
+ previews.delete(preview.previewId);
140
+ previewDirections.delete(preview.previewId);
141
+ }, ttl).unref?.();
142
+ }
143
+ export function getPreview(id, dir) {
144
+ const cached = previews.get(id);
145
+ if (cached) {
146
+ if (new Date(cached.expiresAt).getTime() <= Date.now()) {
147
+ previews.delete(id);
148
+ previewDirections.delete(id);
149
+ return undefined;
150
+ }
151
+ return cached;
152
+ }
153
+ if (!dir)
154
+ return undefined;
155
+ const record = readPersisted(id, dir);
156
+ if (!record)
157
+ return undefined;
158
+ const p = record.preview;
159
+ if (new Date(p.expiresAt).getTime() <= Date.now()) {
160
+ try {
161
+ fs.unlinkSync(previewFile(id, dir));
162
+ }
163
+ catch { }
164
+ return undefined;
165
+ }
166
+ // hydrate into memory for single-process idempotence
167
+ previews.set(p.previewId, p);
168
+ if (record.direction)
169
+ previewDirections.set(p.previewId, record.direction);
170
+ return p;
171
+ }
172
+ export function getPreviewDirection(id) {
173
+ return previewDirections.get(id);
174
+ }
175
+ export function deletePreview(id, dir) {
176
+ previews.delete(id);
177
+ previewDirections.delete(id);
178
+ if (dir) {
179
+ try {
180
+ fs.unlinkSync(previewFile(id, dir));
181
+ }
182
+ catch { }
183
+ }
184
+ }
185
+ export function clearPreviews() {
186
+ previews.clear();
187
+ previewDirections.clear();
188
+ }
189
+ export function revisionFrom(snapshots, direction) {
190
+ const h = createHash('sha256');
191
+ h.update(direction);
192
+ const sorted = [...snapshots].sort((a, b) => a.path.localeCompare(b.path));
193
+ for (const s of sorted) {
194
+ h.update(s.path + ':' + s.sha256 + ':' + String(s.size) + ':' + s.kind);
195
+ }
196
+ return h.digest('hex').slice(0, 16);
197
+ }
198
+ function unionJsonlAdded(localBuf, remoteBuf) {
199
+ const localLines = localBuf.toString('utf-8').split('\n').filter((l) => l.length > 0);
200
+ const remoteLines = remoteBuf.toString('utf-8').split('\n').filter((l) => l.length > 0);
201
+ const seen = new Set(localLines);
202
+ let added = 0;
203
+ for (const line of remoteLines) {
204
+ if (!seen.has(line)) {
205
+ seen.add(line);
206
+ added++;
207
+ }
208
+ }
209
+ return added;
210
+ }
211
+ export async function buildPlan(localSnapshots, remoteSnapshots, direction, localContents, remoteContents, opts = {}) {
212
+ const localMap = new Map(localSnapshots.map((s) => [s.path, s]));
213
+ const remoteMap = new Map(remoteSnapshots.map((s) => [s.path, s]));
214
+ const allPaths = new Set([...localMap.keys(), ...remoteMap.keys()]);
215
+ const actions = [];
216
+ let copied = 0;
217
+ let merged = 0;
218
+ let skipped = 0;
219
+ let conflicts = 0;
220
+ let added = 0;
221
+ // Count-only sessions: preview reports added/updated/deleted/identical from
222
+ // path+checksum without staging content. These files never produce action
223
+ // rows — the UI shows the counts instead of per-file rows. Apply is untouched:
224
+ // it re-inventories with full content and builds a real merge plan.
225
+ let sessionCounts = { added: 0, updated: 0, deleted: 0, identical: 0 };
226
+ const isSession = (p) => p.endsWith('.zstd');
227
+ const sortedPaths = [...allPaths].sort((a, b) => a.localeCompare(b));
228
+ for (const p of sortedPaths) {
229
+ const ls = localMap.get(p);
230
+ const rs = remoteMap.get(p);
231
+ const target = direction === 'pull' ? 'local' : 'remote';
232
+ if (opts.countOnlySessions && isSession(p)) {
233
+ if (!ls && rs) {
234
+ if (direction === 'pull')
235
+ sessionCounts.added++;
236
+ else
237
+ sessionCounts.deleted++;
238
+ }
239
+ else if (ls && !rs) {
240
+ if (direction === 'pull')
241
+ sessionCounts.deleted++;
242
+ else
243
+ sessionCounts.added++;
244
+ }
245
+ else if (ls && rs) {
246
+ if (ls.sha256 === rs.sha256)
247
+ sessionCounts.identical++;
248
+ else
249
+ sessionCounts.updated++;
250
+ }
251
+ continue;
252
+ }
253
+ if (ls && !rs) {
254
+ if (direction === 'push') {
255
+ actions.push({ path: p, action: 'copy', target: 'remote', added: 0, reason: 'local only', expectedTargetSha256: undefined });
256
+ copied++;
257
+ }
258
+ else {
259
+ actions.push({ path: p, action: 'skip', target: 'local', added: 0, reason: 'local only, pull skips' });
260
+ skipped++;
261
+ }
262
+ continue;
263
+ }
264
+ if (!ls && rs) {
265
+ if (direction === 'pull') {
266
+ actions.push({ path: p, action: 'copy', target: 'local', added: 0, reason: 'remote only' });
267
+ copied++;
268
+ }
269
+ else {
270
+ actions.push({ path: p, action: 'skip', target: 'remote', added: 0, reason: 'remote only, push skips' });
271
+ skipped++;
272
+ }
273
+ continue;
274
+ }
275
+ if (ls && rs) {
276
+ if (ls.sha256 === rs.sha256) {
277
+ actions.push({ path: p, action: 'skip', target, added: 0, reason: 'identical bytes', expectedTargetSha256: ls.sha256 });
278
+ skipped++;
279
+ continue;
280
+ }
281
+ const localBuf = localContents.get(p);
282
+ const remoteBuf = remoteContents.get(p);
283
+ if (!localBuf || !remoteBuf) {
284
+ actions.push({ path: p, action: 'conflict', target, added: 0, reason: 'missing content for merge', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
285
+ conflicts++;
286
+ continue;
287
+ }
288
+ try {
289
+ if (p.endsWith('.md')) {
290
+ const localStr = localBuf.toString('utf-8');
291
+ const remoteStr = remoteBuf.toString('utf-8');
292
+ const { added: addedCount } = direction === 'pull' ? mergeDelimited(localStr, remoteStr) : mergeDelimited(remoteStr, localStr);
293
+ if (addedCount === 0) {
294
+ // same delimited entries, different bytes/order — nothing to add
295
+ actions.push({ path: p, action: 'skip', target, added: 0, reason: 'content-equal, no new entries', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
296
+ skipped++;
297
+ }
298
+ else {
299
+ actions.push({ path: p, action: 'merge', target, added: addedCount, reason: 'content differs, merge', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
300
+ merged++;
301
+ added += addedCount;
302
+ }
303
+ }
304
+ else if (p.endsWith('.jsonl')) {
305
+ const addedCount = direction === 'pull' ? unionJsonlAdded(localBuf, remoteBuf) : unionJsonlAdded(remoteBuf, localBuf);
306
+ if (addedCount === 0) {
307
+ actions.push({ path: p, action: 'skip', target, added: 0, reason: 'content-equal, no new lines', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
308
+ skipped++;
309
+ }
310
+ else {
311
+ actions.push({ path: p, action: 'merge', target, added: addedCount, reason: 'content differs, merge', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
312
+ merged++;
313
+ added += addedCount;
314
+ }
315
+ }
316
+ else if (p.endsWith('.zstd')) {
317
+ // Session handling is Buffer/path-only and preserves DSH standalone checksummed Zstd header frame.
318
+ // Never convert Zstd bytes to UTF-8 string; use validated Zstd artifact API via session-plan.
319
+ try {
320
+ if (!isSameSession(localBuf, remoteBuf)) {
321
+ actions.push({ path: p, action: 'conflict', target, added: 0, reason: 'session header mismatch', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
322
+ conflicts++;
323
+ }
324
+ else {
325
+ const { added: addedCount } = direction === 'pull' ? mergeSessionBuffers(localBuf, remoteBuf) : mergeSessionBuffers(remoteBuf, localBuf);
326
+ if (addedCount === 0) {
327
+ // identical session lines under a (possibly different) zstd frame layout
328
+ actions.push({ path: p, action: 'skip', target, added: 0, reason: 'content-equal, no new entries', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
329
+ skipped++;
330
+ }
331
+ else {
332
+ actions.push({ path: p, action: 'merge', target, added: addedCount, reason: 'session differs, merge', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
333
+ merged++;
334
+ added += addedCount;
335
+ }
336
+ }
337
+ }
338
+ catch (e) {
339
+ actions.push({ path: p, action: 'conflict', target, added: 0, reason: e?.message ?? 'session merge failed', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
340
+ conflicts++;
341
+ }
342
+ }
343
+ else {
344
+ actions.push({ path: p, action: 'conflict', target, added: 0, reason: 'unknown kind', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
345
+ conflicts++;
346
+ }
347
+ }
348
+ catch (e) {
349
+ actions.push({ path: p, action: 'conflict', target, added: 0, reason: e?.message ?? 'merge failed', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
350
+ conflicts++;
351
+ }
352
+ }
353
+ }
354
+ const revision = revisionFrom([...localSnapshots, ...remoteSnapshots], direction);
355
+ const summary = { copied, merged, skipped, conflicts, added };
356
+ actions.sort((a, b) => a.path.localeCompare(b.path));
357
+ return { revision, actions, summary, sessionCounts: opts.countOnlySessions ? sessionCounts : undefined };
358
+ }
359
+ export async function buildPreview(localSnapshots, remoteSnapshots, direction, localContents, remoteContents, opts = {}) {
360
+ const plan = await buildPlan(localSnapshots, remoteSnapshots, direction, localContents, remoteContents, opts);
361
+ const previewId = randomBytes(16).toString('hex');
362
+ const expiresAt = new Date(Date.now() + PREVIEW_TTL_MS).toISOString();
363
+ const preview = { ...plan, previewId, expiresAt };
364
+ storePreview(preview, direction);
365
+ return preview;
366
+ }