@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,855 @@
1
+ /**
2
+ * SyncService — content-aware, preview-bound merge for DSH state.
3
+ *
4
+ * Safety contract (docs/specs/2026-08-31-dsh-maestro-sync-remediation-design.md):
5
+ * - preview() is read-only: it stages remote eligible files once via argv-only
6
+ * rsync --files-from into a private temp dir and hashes raw Buffers. Binary
7
+ * session artifacts (.jsonl.zstd) are never UTF-8-decoded.
8
+ * - apply({previewId, direction, confirm:true}) is the ONLY mutation route. It
9
+ * re-inventories the local and remote sides, recomputes the plan, and rejects
10
+ * a changed inventory as STALE_PREVIEW before any write.
11
+ * - Pull publishes each destination through backup + fsync tmp + rename + dir
12
+ * fsync. Push materializes every output below a private operation dir, uploads
13
+ * to <root>/.maestro-sync/stage/<op>/ and commits through the fixed remote
14
+ * CAS helper (expectedTargetSha256); a mismatch is CONCURRENT_MODIFICATION.
15
+ * - Legacy pull()/push() are preview-only compatibility aliases and never write.
16
+ */
17
+ import * as nodeFs from 'node:fs';
18
+ import * as path from 'node:path';
19
+ import * as os from 'node:os';
20
+ import { randomBytes } from 'node:crypto';
21
+ import { mergeDelimited } from './merge.js';
22
+ import { mergeSessionBuffers } from './session-plan.js';
23
+ import { snapshotFile, kindForPath } from './snapshot.js';
24
+ import { hashFiles } from './hashing.js';
25
+ import { loadIndex, saveIndex, probeIndex, matchesStat, statFingerprint } from './fingerprint.js';
26
+ import type { RemoteManifestEntry } from './remote-manifest.js';
27
+ import { buildPlan, buildPreview, getPreview, getPreviewDirection, deletePreview, storePreview } from './sync-plan.js';
28
+ import { normalizeEligiblePath, validateRemoteTarget, validateHost } from './validation.js';
29
+ import type { RemoteTarget, SyncDirection, SyncPreview, SyncSummary, SyncFailure, SyncPlan, FileSnapshot, PlannedAction, SyncProgress, SyncScope } from './sync-types.js';
30
+ import { createProcessRunner, type ProcessRunner } from './process-runner.js';
31
+ import { createTransport, type SyncTransport } from './transport.js';
32
+
33
+ export interface PreviewRequest {
34
+ direction: SyncDirection;
35
+ scope?: SyncScope;
36
+ }
37
+
38
+ export interface ApplyRequest {
39
+ previewId: string;
40
+ direction: SyncDirection;
41
+ confirm: true;
42
+ scope?: SyncScope;
43
+ }
44
+
45
+ export interface ApplyResult {
46
+ ok: boolean;
47
+ revision: string;
48
+ summary: SyncSummary;
49
+ committed: string[];
50
+ failures: SyncFailure[];
51
+ }
52
+
53
+ export interface ConnectionStatus {
54
+ ok: boolean;
55
+ host: string;
56
+ latencyMs?: number;
57
+ error?: string;
58
+ }
59
+
60
+ /** Legacy status shape — counts never imply same path means same content. */
61
+ export interface StatusResult {
62
+ localOnly: number;
63
+ remoteOnly: number;
64
+ both: number;
65
+ localOnlyFiles: string[];
66
+ remoteOnlyFiles: string[];
67
+ bothFiles: string[];
68
+ connection: ConnectionStatus;
69
+ remoteHost: string;
70
+ }
71
+
72
+ /** Cursor-paged status page for bounded RPC payloads (< 64 KiB). */
73
+ export interface StatusPage {
74
+ total: number;
75
+ offset: number;
76
+ limit: number;
77
+ files: string[];
78
+ nextCursor: number | null;
79
+ connection: ConnectionStatus;
80
+ remoteHost: string;
81
+ }
82
+
83
+ export interface PullResult {
84
+ copied: number;
85
+ merged: number;
86
+ added: number;
87
+ conflicts: number;
88
+ }
89
+
90
+ export interface PushResult {
91
+ copied: number;
92
+ merged: number;
93
+ added: number;
94
+ conflicts: number;
95
+ }
96
+
97
+ export interface PreviewResult extends SyncPreview {
98
+ connection: ConnectionStatus;
99
+ remoteHost: string;
100
+ }
101
+
102
+ export interface SyncServiceOpts {
103
+ localDsh?: string;
104
+ remote?: string;
105
+ remoteDsh?: string;
106
+ previewDir?: string;
107
+ cacheDir?: string;
108
+ fs?: any;
109
+ runner?: ProcessRunner;
110
+ transport?: SyncTransport;
111
+ }
112
+
113
+ function syncFailure(phase: SyncFailure['phase'], code: string, detail: string, path?: string): Error & SyncFailure {
114
+ return Object.assign(new Error(detail), { phase, code, detail, path });
115
+ }
116
+
117
+ export class SyncService {
118
+ localDsh: string;
119
+ remote: string;
120
+ remoteDsh: string;
121
+ previewDir: string;
122
+ cacheDir: string;
123
+ fs: any;
124
+ runner: ProcessRunner;
125
+ transport: SyncTransport;
126
+
127
+ constructor(opts: SyncServiceOpts = {}) {
128
+ this.localDsh = opts.localDsh || process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
129
+ this.remote = opts.remote || process.env.REMOTE_HOST || process.env.REMOTE || 'kai@ssh.ddtcorex.com';
130
+ this.remoteDsh = opts.remoteDsh || process.env.REMOTE_DSH_PATH || '~/.dsh';
131
+ // Sidecar preview store shared by every CLI process (preview -> separate apply run).
132
+ this.previewDir = opts.previewDir ?? path.join(this.localDsh, 'dsh-maestro-sync', 'previews');
133
+ // Fingerprint cache sidecar — a pure speed hint; write targets are always re-hashed.
134
+ this.cacheDir = opts.cacheDir ?? path.join(this.localDsh, 'dsh-maestro-sync', 'cache');
135
+ this.fs = opts.fs || nodeFs;
136
+ this.runner = opts.runner ?? createProcessRunner();
137
+ this.transport = opts.transport ?? createTransport(this.runner);
138
+ }
139
+
140
+ /**
141
+ * Resolve + validate the remote target. A `~/.dsh` placeholder is resolved by
142
+ * the transport preflight (remote $HOME bytes) — never by local shell ~ expansion.
143
+ */
144
+ async resolveTarget(): Promise<RemoteTarget> {
145
+ let dshRoot = this.remoteDsh;
146
+ if (!dshRoot || dshRoot === '~' || dshRoot.startsWith('~/') || dshRoot.startsWith('~')) {
147
+ const home = await this.transport.remoteHome({ host: this.remote });
148
+ const suffix = dshRoot && dshRoot.startsWith('~/') ? dshRoot.slice(2) : '.dsh';
149
+ dshRoot = path.posix.join(home, suffix);
150
+ }
151
+ return validateRemoteTarget({ host: this.remote, dshRoot });
152
+ }
153
+
154
+ private async requireTarget(): Promise<RemoteTarget> {
155
+ try {
156
+ return await this.resolveTarget();
157
+ } catch (e: any) {
158
+ throw syncFailure('validate', 'INVALID_REMOTE_TARGET', `invalid remote target: ${e?.message ?? String(e)}`);
159
+ }
160
+ }
161
+
162
+ async checkConnection(): Promise<ConnectionStatus> {
163
+ // Validate the host before any spawn so an unsafe host can never reach ssh.
164
+ try {
165
+ validateHost(this.remote);
166
+ } catch (e: any) {
167
+ return { ok: false, host: this.remote, error: e?.message ?? 'invalid host' };
168
+ }
169
+ const start = Date.now();
170
+ try {
171
+ const res = await this.runner.run('ssh', ['-o', 'ConnectTimeout=5', '-o', 'BatchMode=yes', this.remote, 'echo ok'], { timeoutMs: 5000 });
172
+ if (res.exitCode === 0) return { ok: true, host: this.remote, latencyMs: Date.now() - start };
173
+ const detail = res.stderr.toString('utf-8').trim().slice(0, 400) || `exit ${res.exitCode}`;
174
+ return { ok: false, host: this.remote, error: detail };
175
+ } catch (e: any) {
176
+ return { ok: false, host: this.remote, error: String(e?.message ?? e).slice(0, 400) };
177
+ }
178
+ }
179
+
180
+ private async requireConnection(): Promise<ConnectionStatus> {
181
+ const connection = await this.checkConnection();
182
+ if (!connection.ok) {
183
+ throw syncFailure('validate', 'OFFLINE', `cannot reach ${this.remote}: ${connection.error ?? 'SSH connection failed'}`);
184
+ }
185
+ return connection;
186
+ }
187
+
188
+ /**
189
+ * Local eligible files (dsh-maestro-memory/*.md, dsh-maestro-memory/SUGGESTIONS.jsonl,
190
+ * sessions/<cwd-hash>/<id>/session.jsonl.zstd) as relative paths, sorted.
191
+ * Only content that matches the eligible contract is ever read or hashed.
192
+ */
193
+ listLocalFiles(): string[] {
194
+ const root = this.localDsh;
195
+ const result: string[] = [];
196
+ const fsMod = this.fs;
197
+ const walk = (dir: string, base: string) => {
198
+ let entries: any[] = [];
199
+ try {
200
+ if (typeof fsMod.readdirSync !== 'function') return;
201
+ const raw = fsMod.readdirSync(dir, { withFileTypes: true } as any);
202
+ if (!raw || raw.length === 0) return;
203
+ if (typeof raw[0] === 'string') {
204
+ for (const name of raw as unknown as string[]) {
205
+ const full = path.join(dir, name);
206
+ let st: any = null;
207
+ try {
208
+ st = fsMod.statSync ? fsMod.statSync(full) : null;
209
+ } catch {
210
+ continue;
211
+ }
212
+ if (st && typeof st.isDirectory === 'function' && st.isDirectory()) walk(full, path.join(base, name));
213
+ else result.push(path.join(base, name));
214
+ }
215
+ return;
216
+ }
217
+ for (const ent of raw as any[]) {
218
+ const name = ent.name ?? String(ent);
219
+ const full = path.join(dir, name);
220
+ const isDir = typeof ent.isDirectory === 'function' ? ent.isDirectory() : false;
221
+ if (isDir) walk(full, path.join(base, name));
222
+ else result.push(path.join(base, name));
223
+ }
224
+ } catch {
225
+ // best-effort walk
226
+ }
227
+ };
228
+ try {
229
+ if (fsMod.existsSync && !fsMod.existsSync(root)) return [];
230
+ } catch {
231
+ return [];
232
+ }
233
+ walk(root, '');
234
+ return [...new Set(
235
+ result
236
+ .map((p) => p.split(path.sep).join('/'))
237
+ .filter((p) => {
238
+ try {
239
+ normalizeEligiblePath(p);
240
+ return true;
241
+ } catch {
242
+ return false;
243
+ }
244
+ }),
245
+ )].sort();
246
+ }
247
+
248
+ /**
249
+ * Snapshot both sides with the manifest-first pipeline:
250
+ * - remote: ONE `transport.manifest` pass (path/sha256/size; NUL-framed,
251
+ * validated). No `list`+`rsync -rcn`+`hashes`, and identical sessions are
252
+ * counted from the manifest without byte transfer.
253
+ * - local: the fingerprint cache (dev+ino+size+mtimeNs+ctimeNs) supplies
254
+ * known SHA-256 values without re-reading files; only cache misses are
255
+ * stream-hashed. Content is loaded lazily for exactly the files a plan or
256
+ * merge needs — identical files are never read into memory.
257
+ * The cache is a pure speed hint: every file apply will WRITE is re-read and
258
+ * re-hashed at write time (see apply), so a stale cache can never publish a
259
+ * wrong mutation target.
260
+ */
261
+ private async snapshotBoth(opts: { scope?: SyncScope; sessionsCountOnly?: boolean; onProgress?: (p: SyncProgress) => void; shouldStop?: () => boolean } = {}): Promise<{
262
+ target: RemoteTarget;
263
+ localSnapshots: FileSnapshot[];
264
+ remoteSnapshots: FileSnapshot[];
265
+ localContents: Map<string, Buffer>;
266
+ remoteContents: Map<string, Buffer>;
267
+ cleanup: () => void;
268
+ }> {
269
+ const progress = (phase: SyncProgress['phase'], current: number, total: number, file?: string) => opts.onProgress?.({ phase, current, total, file });
270
+ const stop = () => {
271
+ if (opts.shouldStop?.()) throw syncFailure('snapshot', 'CANCELLED', 'preview cancelled');
272
+ };
273
+ const isSession = (p: string) => p.endsWith('.jsonl.zstd');
274
+ const fsMod = this.fs;
275
+ const target = await this.requireTarget();
276
+ stop();
277
+ // Scope filter: 'memory' covers dsh-maestro-memory only and skips the
278
+ // live session logs; undefined/'all' preserves the legacy full inventory.
279
+ const inScope = (p: string): boolean => opts.scope !== 'memory' || !p.startsWith('sessions/');
280
+ const localPaths = this.listLocalFiles().filter(inScope);
281
+ const remoteManifest = (await this.transport.manifest(target)).filter((e) => inScope(e.path));
282
+ stop();
283
+ const remoteSnapshots = remoteManifest.map((e) => ({ path: e.path, sha256: e.sha256, size: e.size, kind: kindForPath(e.path) }));
284
+ const remoteSet = new Set(remoteManifest.map((e) => e.path));
285
+
286
+ // ---- local side: fingerprint cache fast-path, stream-hash only misses ----
287
+ const index = loadIndex(this.cacheDir);
288
+ const localSnapshots: FileSnapshot[] = [];
289
+ const stale: string[] = [];
290
+ for (const p of localPaths) {
291
+ const entry = probeIndex(p, index);
292
+ let st: any = null;
293
+ try {
294
+ st = typeof fsMod.statSync === 'function' ? fsMod.statSync(path.join(this.localDsh, p), { bigint: true } as any) : null;
295
+ } catch {
296
+ st = null;
297
+ }
298
+ if (entry && st && matchesStat(entry, st)) {
299
+ localSnapshots.push({ path: p, sha256: entry.sha256, size: entry.size, kind: kindForPath(p) });
300
+ } else {
301
+ stale.push(p);
302
+ }
303
+ }
304
+ let hashedCount = 0;
305
+ const staleHashes = await hashFiles(fsMod, this.localDsh, stale, {
306
+ onFile: (h) => {
307
+ hashedCount++;
308
+ progress('hashing', hashedCount, stale.length, h.path);
309
+ stop();
310
+ },
311
+ });
312
+ for (const h of staleHashes) {
313
+ localSnapshots.push({ path: h.path, sha256: h.sha256, size: h.size, kind: kindForPath(h.path) });
314
+ try {
315
+ const st = typeof fsMod.statSync === 'function' ? fsMod.statSync(path.join(this.localDsh, h.path), { bigint: true } as any) : null;
316
+ if (st) index.entries[h.path] = { ...statFingerprint(st), sha256: h.sha256 };
317
+ } catch {
318
+ // stat races are tolerable — the entry simply misses next run
319
+ }
320
+ }
321
+ if (staleHashes.length > 0 || localPaths.length > 0) saveIndex(this.cacheDir, index);
322
+ localSnapshots.sort((a, b) => a.path.localeCompare(b.path));
323
+
324
+ // ---- changed set: anything not byte-identical on both sides ----
325
+ const localMap = new Map(localSnapshots.map((s) => [s.path, s]));
326
+ const remoteMap = new Map(remoteManifest.map((e) => [e.path, e]));
327
+ const changed: string[] = [];
328
+ for (const p of [...localMap.keys(), ...remoteMap.keys()]) {
329
+ const ls = localMap.get(p);
330
+ const rs = remoteMap.get(p);
331
+ if (!ls || !rs || ls.sha256 !== rs.sha256) changed.push(p);
332
+ }
333
+ changed.sort((a, b) => a.localeCompare(b));
334
+
335
+ // ---- content maps: only changed files carry content (lazy local reads) ----
336
+ const localContents = new Map<string, Buffer>();
337
+ const remoteContents = new Map<string, Buffer>();
338
+ const localBufferOf = (rel: string): Buffer | undefined => {
339
+ if (localContents.has(rel)) return localContents.get(rel);
340
+ try {
341
+ const d = fsMod.readFileSync(path.join(this.localDsh, rel));
342
+ const buf = Buffer.isBuffer(d) ? Buffer.from(d) : Buffer.from(String(d), 'utf-8');
343
+ localContents.set(rel, buf);
344
+ return buf;
345
+ } catch {
346
+ return undefined;
347
+ }
348
+ };
349
+
350
+ let stagingDir: string | null = null;
351
+ let cleanup: () => void = () => {};
352
+ const ensureStaging = () => {
353
+ if (stagingDir !== null) return stagingDir;
354
+ stagingDir = path.join(os.tmpdir(), `maestro-sync-stage-${process.pid}-${Date.now()}-${randomBytes(4).toString('hex')}`);
355
+ try {
356
+ if (typeof fsMod.mkdirSync === 'function') fsMod.mkdirSync(stagingDir, { recursive: true });
357
+ else nodeFs.mkdirSync(stagingDir, { recursive: true });
358
+ } catch (e: any) {
359
+ throw syncFailure('snapshot', 'STAGE_CREATE_FAILED', `cannot create staging dir: ${e?.message}`);
360
+ }
361
+ cleanup = () => {
362
+ try {
363
+ if (typeof fsMod.rmSync === 'function') fsMod.rmSync(stagingDir!, { recursive: true, force: true });
364
+ else nodeFs.rmSync(stagingDir!, { recursive: true, force: true });
365
+ } catch {}
366
+ };
367
+ return stagingDir;
368
+ };
369
+ const readStaged = (rel: string): Buffer => {
370
+ const stagedPath = path.join(ensureStaging(), rel);
371
+ const data = typeof fsMod.readFileSync === 'function' ? fsMod.readFileSync(stagedPath) : nodeFs.readFileSync(stagedPath);
372
+ return Buffer.isBuffer(data) ? Buffer.from(data) : Buffer.from(String(data), 'utf-8');
373
+ };
374
+
375
+ const sessionChanged = changed.filter(isSession);
376
+ const stageChanged = changed.filter((p) => !isSession(p) && remoteSet.has(p)); // only paths the remote actually has
377
+ // Apply (non count-only) needs real session bytes: both-side merges AND
378
+ // remote-only copies. Count-only previews count sessions from the manifest.
379
+ const stageSessions = opts.sessionsCountOnly ? [] : sessionChanged.filter((p) => remoteSet.has(p));
380
+
381
+ if (stageChanged.length > 0) {
382
+ stop();
383
+ ensureStaging();
384
+ progress('staging', 0, stageChanged.length);
385
+ try {
386
+ await this.transport.stage(target, stageChanged, stagingDir!);
387
+ stop();
388
+ } catch (e: any) {
389
+ throw syncFailure('snapshot', 'STAGE_FAILED', `remote staging failed: ${e?.message ?? String(e)}`);
390
+ }
391
+ for (const p of stageChanged) {
392
+ try {
393
+ remoteContents.set(p, readStaged(p));
394
+ } catch (e: any) {
395
+ throw syncFailure('snapshot', 'STAGE_READ_FAILED', `cannot read staged file ${p}: ${e?.message}`, p);
396
+ }
397
+ }
398
+ }
399
+ if (stageSessions.length > 0) {
400
+ // Apply (non count-only) needs real session bytes for merges and copies.
401
+ stop();
402
+ ensureStaging();
403
+ try {
404
+ await this.transport.stage(target, stageSessions, stagingDir!);
405
+ } catch (e: any) {
406
+ throw syncFailure('snapshot', 'STAGE_FAILED', `remote session staging failed: ${e?.message ?? String(e)}`);
407
+ }
408
+ for (const p of stageSessions) remoteContents.set(p, readStaged(p));
409
+ }
410
+ // Local content for changed files: only read what a plan/merge may touch.
411
+ for (const p of changed) {
412
+ if (localMap.has(p)) localBufferOf(p);
413
+ }
414
+
415
+ return { target, localSnapshots, remoteSnapshots, localContents, remoteContents, cleanup };
416
+ }
417
+
418
+ /**
419
+ * Read-only preview: exact plan with copy/merge/skip/conflict and real added
420
+ * counts — except sessions under `sessionsCountOnly`, which are counted by
421
+ * path+checksum (added/updated/deleted/identical) without staging content.
422
+ * `onProgress` receives per-phase ticks (hashing emits one per session file).
423
+ * No preview path may copy, backup, restore or publish.
424
+ */
425
+
426
+ /**
427
+ * Wrap a multi-spawn operation in one SSH ControlMaster link (Task 6 + follow-up).
428
+ * Fail-open: if the master cannot start (MUX_FAILED) or the transport does not
429
+ * support mux (fakes, rehearsal), run unmuxed — a link optimization, never a
430
+ * correctness requirement. Preview stays read-only; the mux teardown runs in
431
+ * finally.
432
+ */
433
+ private async withMux<T>(run: () => Promise<T>): Promise<T> {
434
+ const transportAny = this.transport as any;
435
+ if (typeof transportAny?.setMux !== 'function') return run();
436
+ const baseDir = path.join(this.localDsh, 'dsh-maestro-sync', 'ssh-mux');
437
+ const { openSshMux } = await import('./ssh-mux.js');
438
+ let mux: any = null;
439
+ try {
440
+ mux = await openSshMux({ host: this.remote, baseDir, runner: this.runner });
441
+ } catch (e: any) {
442
+ if (e?.code === 'MUX_FAILED') return run(); // fail-open → unmuxed
443
+ throw e;
444
+ }
445
+ try {
446
+ transportAny.setMux(mux);
447
+ return await run();
448
+ } finally {
449
+ transportAny.setMux(null);
450
+ await mux.dispose();
451
+ }
452
+ }
453
+
454
+ async preview(opts: { direction: SyncDirection; scope?: SyncScope; sessionsCountOnly?: boolean; onProgress?: (p: SyncProgress) => void; shouldStop?: () => boolean }): Promise<PreviewResult> {
455
+ return this.withMux(() => this.previewInner(opts));
456
+ }
457
+
458
+ private async previewInner(opts: { direction: SyncDirection; scope?: SyncScope; sessionsCountOnly?: boolean; onProgress?: (p: SyncProgress) => void; shouldStop?: () => boolean }): Promise<PreviewResult> {
459
+ const direction: SyncDirection = opts.direction === 'push' ? 'push' : 'pull';
460
+ const connection = await this.requireConnection();
461
+ const { localSnapshots, remoteSnapshots, localContents, remoteContents, cleanup } = await this.snapshotBoth({
462
+ scope: opts.scope,
463
+ sessionsCountOnly: opts.sessionsCountOnly,
464
+ onProgress: opts.onProgress,
465
+ shouldStop: opts.shouldStop,
466
+ });
467
+ try {
468
+ opts.onProgress?.({ phase: 'planning', current: 0, total: 1 });
469
+ const preview = await buildPreview(localSnapshots, remoteSnapshots, direction, localContents, remoteContents, { countOnlySessions: opts.sessionsCountOnly });
470
+ // persist so a separate CLI apply process can consume this preview
471
+ storePreview(preview, direction, this.previewDir);
472
+ opts.onProgress?.({ phase: 'planning', current: 1, total: 1 });
473
+ return { ...preview, connection, remoteHost: this.remote };
474
+ } finally {
475
+ cleanup();
476
+ }
477
+ }
478
+
479
+ private assertApplyRequest(req: ApplyRequest): void {
480
+ if (!req || typeof req.previewId !== 'string' || req.previewId.length === 0) {
481
+ throw syncFailure('validate', 'INVALID_PREVIEW_ID', 'apply requires previewId');
482
+ }
483
+ if ((req as any).confirm !== true) {
484
+ throw syncFailure('validate', 'CONFIRM_REQUIRED', 'apply requires confirm:true');
485
+ }
486
+ if (req.direction !== 'pull' && req.direction !== 'push') {
487
+ throw syncFailure('validate', 'INVALID_DIRECTION', 'apply requires direction pull|push');
488
+ }
489
+ }
490
+
491
+ /** Merge dispatcher — bytes stay bytes for zstd; md/jsonl use deterministic unions. */
492
+ private mergeBuffer(
493
+ act: PlannedAction,
494
+ localContents: Map<string, Buffer>,
495
+ remoteContents: Map<string, Buffer>,
496
+ direction: SyncDirection,
497
+ ): Buffer {
498
+ const localBuf = localContents.get(act.path);
499
+ const remoteBuf = remoteContents.get(act.path);
500
+ if (!localBuf || !remoteBuf) {
501
+ throw syncFailure('plan', 'MISSING_CONTENT', `missing content for merge ${act.path}`, act.path);
502
+ }
503
+ if (act.path.endsWith('.zstd')) {
504
+ const { merged } = direction === 'pull' ? mergeSessionBuffers(localBuf, remoteBuf) : mergeSessionBuffers(remoteBuf, localBuf);
505
+ return merged;
506
+ }
507
+ if (act.path.endsWith('.jsonl')) {
508
+ const base = direction === 'pull' ? localBuf : remoteBuf;
509
+ const incoming = direction === 'pull' ? remoteBuf : localBuf;
510
+ const baseLines = base.toString('utf-8').split('\n').filter((l) => l.length > 0);
511
+ const incomingLines = incoming.toString('utf-8').split('\n').filter((l) => l.length > 0);
512
+ const seen = new Set(baseLines);
513
+ const mergedArr = [...baseLines];
514
+ for (const line of incomingLines) if (!seen.has(line)) { seen.add(line); mergedArr.push(line); }
515
+ return Buffer.from(mergedArr.join('\n') + (mergedArr.length ? '\n' : ''), 'utf-8');
516
+ }
517
+ if (act.path.endsWith('.md')) {
518
+ const localStr = localBuf.toString('utf-8');
519
+ const remoteStr = remoteBuf.toString('utf-8');
520
+ const { mergedText } = direction === 'pull' ? mergeDelimited(localStr, remoteStr) : mergeDelimited(remoteStr, localStr);
521
+ return Buffer.from(mergedText, 'utf-8');
522
+ }
523
+ throw syncFailure('plan', 'UNKNOWN_KIND', `unknown kind for ${act.path}`, act.path);
524
+ }
525
+
526
+ private async atomicWriteWithBackup(fullPath: string, content: Buffer): Promise<void> {
527
+ const fsMod = this.fs;
528
+ const dir = path.dirname(fullPath);
529
+ try {
530
+ if (fsMod.mkdirSync) fsMod.mkdirSync(dir, { recursive: true });
531
+ else if (fsMod.promises?.mkdir) await fsMod.promises.mkdir(dir, { recursive: true });
532
+ } catch {
533
+ // ignore mkdir errors
534
+ }
535
+ // backup existing bytes — per-file atomic publication requires a recoverable copy
536
+ try {
537
+ const exists = fsMod.existsSync ? fsMod.existsSync(fullPath) : false;
538
+ if (exists) {
539
+ const bak = `${fullPath}.bak.${Date.now()}.${randomBytes(4).toString('hex')}`;
540
+ if (typeof fsMod.copyFileSync === 'function') fsMod.copyFileSync(fullPath, bak);
541
+ else if (typeof fsMod.writeFileSync === 'function' && typeof fsMod.readFileSync === 'function') fsMod.writeFileSync(bak, fsMod.readFileSync(fullPath));
542
+ }
543
+ } catch {
544
+ // backup best-effort (failure to back up is not a publish failure, but we must not lose the write)
545
+ }
546
+ const tmp = `${fullPath}.tmp.${randomBytes(4).toString('hex')}`;
547
+ try {
548
+ if (typeof fsMod.writeFileSync === 'function') fsMod.writeFileSync(tmp, content);
549
+ else nodeFs.writeFileSync(tmp, content);
550
+ // fsync the temp file
551
+ try {
552
+ if (typeof fsMod.openSync === 'function' && typeof fsMod.fsyncSync === 'function' && typeof fsMod.closeSync === 'function') {
553
+ const fd = fsMod.openSync(tmp, 'r');
554
+ try {
555
+ fsMod.fsyncSync(fd);
556
+ } finally {
557
+ fsMod.closeSync(fd);
558
+ }
559
+ }
560
+ } catch {}
561
+ if (typeof fsMod.renameSync === 'function') fsMod.renameSync(tmp, fullPath);
562
+ else {
563
+ if (typeof fsMod.writeFileSync === 'function') fsMod.writeFileSync(fullPath, content);
564
+ else nodeFs.writeFileSync(fullPath, content);
565
+ try {
566
+ if (fsMod.existsSync && fsMod.existsSync(tmp) && fsMod.unlinkSync) fsMod.unlinkSync(tmp);
567
+ } catch {}
568
+ }
569
+ // fsync the directory
570
+ try {
571
+ if (typeof fsMod.openSync === 'function' && typeof fsMod.fsyncSync === 'function' && typeof fsMod.closeSync === 'function') {
572
+ const dfd = fsMod.openSync(dir, 'r');
573
+ try {
574
+ fsMod.fsyncSync(dfd);
575
+ } finally {
576
+ fsMod.closeSync(dfd);
577
+ }
578
+ }
579
+ } catch {}
580
+ } catch (e: any) {
581
+ throw syncFailure('publish', 'ATOMIC_WRITE_FAILED', `atomic publish failed for ${fullPath}: ${e?.message}`);
582
+ }
583
+ }
584
+
585
+ /**
586
+ * Apply a previously generated preview (the only mutation route).
587
+ * Re-inventories both sides and applies the FRESHEST plan — DSH homes change
588
+ * continuously (session logs are appended every turn), so a byte-for-byte
589
+ * inventory comparison would reject nearly every live apply (STALE_PREVIEW).
590
+ * Safety stays fail-closed without it: each file publish carries the
591
+ * expected target sha (CAS) and a preview is single-use, so a concurrent
592
+ * modification during the write is still rejected and nothing is overwritten
593
+ * silently. Pull publishes atomically per local file; push materializes,
594
+ * uploads and commits through the remote CAS helper.
595
+ */
596
+ async apply(req: ApplyRequest): Promise<ApplyResult> {
597
+ return this.withMux(() => this.applyInner(req));
598
+ }
599
+
600
+ private async applyInner(req: ApplyRequest): Promise<ApplyResult> {
601
+ this.assertApplyRequest(req);
602
+ const preview = getPreview(req.previewId, this.previewDir);
603
+ if (!preview) throw syncFailure('validate', 'STALE_PREVIEW', 'preview not found or expired (60s)');
604
+ const storedDir = getPreviewDirection(req.previewId);
605
+ if (storedDir && storedDir !== req.direction) {
606
+ throw syncFailure('validate', 'DIRECTION_MISMATCH', `preview is ${storedDir} but apply direction is ${req.direction}`);
607
+ }
608
+ await this.requireConnection();
609
+
610
+ const { target, localSnapshots, remoteSnapshots, localContents, remoteContents, cleanup } = await this.snapshotBoth({ scope: req.scope });
611
+ try {
612
+ const fresh = await buildPlan(localSnapshots, remoteSnapshots, req.direction, localContents, remoteContents);
613
+
614
+ const committed: string[] = [];
615
+ const failures: SyncFailure[] = [];
616
+ const targetSide: 'local' | 'remote' = req.direction === 'pull' ? 'local' : 'remote';
617
+ const toPublish = fresh.actions.filter((a) => a.target === targetSide && (a.action === 'copy' || a.action === 'merge'));
618
+
619
+ if (req.direction === 'pull') {
620
+ for (const act of toPublish) {
621
+ try {
622
+ normalizeEligiblePath(act.path);
623
+ let buf: Buffer;
624
+ if (act.action === 'copy') {
625
+ const remoteBuf = remoteContents.get(act.path);
626
+ if (!remoteBuf) throw syncFailure('publish', 'MISSING_REMOTE', `missing remote content for ${act.path}`, act.path);
627
+ buf = remoteBuf;
628
+ } else {
629
+ buf = this.mergeBuffer(act, localContents, remoteContents, 'pull');
630
+ }
631
+ await this.atomicWriteWithBackup(path.join(this.localDsh, act.path), buf);
632
+ committed.push(act.path);
633
+ } catch (e: any) {
634
+ failures.push(syncFailure('publish', e?.code ?? 'PUBLISH_FAILED', String(e?.message ?? e), act.path) as SyncFailure);
635
+ }
636
+ }
637
+ } else {
638
+ if (toPublish.length > 0) {
639
+ const operationId = randomBytes(8).toString('hex');
640
+ const stagingDir = path.join(os.tmpdir(), `maestro-push-stage-${process.pid}-${operationId}`);
641
+ const fsMod = this.fs;
642
+ try {
643
+ if (typeof fsMod.mkdirSync === 'function') fsMod.mkdirSync(stagingDir, { recursive: true });
644
+ else nodeFs.mkdirSync(stagingDir, { recursive: true });
645
+ } catch (e: any) {
646
+ throw syncFailure('publish', 'STAGE_CREATE_FAILED', `cannot create push staging dir: ${e?.message}`);
647
+ }
648
+ const cleanupStaging = () => {
649
+ try {
650
+ if (typeof fsMod.rmSync === 'function') fsMod.rmSync(stagingDir, { recursive: true, force: true });
651
+ else nodeFs.rmSync(stagingDir, { recursive: true, force: true });
652
+ } catch {}
653
+ };
654
+ try {
655
+ // Materialize every output first; a failure here publishes nothing.
656
+ const paths: string[] = [];
657
+ for (const act of toPublish) {
658
+ normalizeEligiblePath(act.path);
659
+ let buf: Buffer;
660
+ if (act.action === 'copy') {
661
+ const localBuf = localContents.get(act.path);
662
+ if (!localBuf) throw syncFailure('publish', 'MISSING_LOCAL', `missing local content for ${act.path}`, act.path);
663
+ buf = localBuf;
664
+ } else {
665
+ buf = this.mergeBuffer(act, localContents, remoteContents, 'push');
666
+ }
667
+ const dest = path.join(stagingDir, act.path);
668
+ const fsMod2 = this.fs;
669
+ try {
670
+ if (typeof fsMod2.mkdirSync === 'function') fsMod2.mkdirSync(path.dirname(dest), { recursive: true });
671
+ else nodeFs.mkdirSync(path.dirname(dest), { recursive: true });
672
+ } catch {}
673
+ if (typeof fsMod2.writeFileSync === 'function') fsMod2.writeFileSync(dest, buf);
674
+ else nodeFs.writeFileSync(dest, buf);
675
+ paths.push(act.path);
676
+ }
677
+
678
+ try {
679
+ await this.transport.ensureAgent(target);
680
+ } catch (e: any) {
681
+ throw syncFailure('publish', 'AGENT_INSTALL_FAILED', `remote agent install failed: ${e?.message ?? String(e)}`);
682
+ }
683
+ try {
684
+ await this.transport.upload(target, stagingDir, paths, operationId);
685
+ } catch (e: any) {
686
+ for (const p of paths) failures.push(syncFailure('publish', 'UPLOAD_FAILED', `upload failed: ${e?.message ?? String(e)}`, p) as SyncFailure);
687
+ }
688
+ if (failures.length === 0) {
689
+ const manifest = Buffer.from(toPublish.map((a) => JSON.stringify({ path: a.path, expected: a.expectedTargetSha256 ?? 'absent' }) + '\n').join(''), 'utf-8');
690
+ try {
691
+ await this.transport.commit(target, operationId, manifest);
692
+ committed.push(...paths);
693
+ // Best-effort remote fingerprint-cache refresh AFTER the commit
694
+ // succeeded. Preview stays strictly read-only: the cache is
695
+ // written only here (or by an explicit warm command). A warm
696
+ // failure must never fail an already-committed apply.
697
+ try {
698
+ await this.transport.warmCache(target);
699
+ } catch (w: any) {
700
+ failures.push(syncFailure('publish', 'WARM_FAILED', `fingerprint cache refresh failed (non-fatal): ${w?.message ?? String(w)}`) as SyncFailure);
701
+ }
702
+ } catch (e: any) {
703
+ const code = e?.code && e.code !== 'TRANSPORT_ERROR' ? e.code : 'COMMIT_FAILED';
704
+ for (const p of paths) failures.push(syncFailure('publish', code, `remote commit failed: ${e?.message ?? String(e)}`, p) as SyncFailure);
705
+ }
706
+ }
707
+ } finally {
708
+ cleanupStaging();
709
+ }
710
+ }
711
+ }
712
+
713
+ // A preview is invalidated by any apply attempt that passed validation.
714
+ deletePreview(req.previewId, this.previewDir);
715
+ return { ok: failures.length === 0, revision: fresh.revision, summary: fresh.summary, committed, failures };
716
+ } finally {
717
+ cleanup();
718
+ }
719
+ }
720
+
721
+ // ---- legacy preview-only compatibility (never writes) ----
722
+
723
+ /** Deprecated: preview-only alias. `dryRun` is ignored; nothing is ever applied here. */
724
+ async pull(_opts: { dryRun?: boolean } = {}): Promise<PullResult> {
725
+ const preview = await this.preview({ direction: 'pull' });
726
+ return { copied: preview.summary.copied, merged: preview.summary.merged, added: preview.summary.added, conflicts: preview.summary.conflicts };
727
+ }
728
+
729
+ /** Deprecated: preview-only alias. `dryRun` is ignored; nothing is ever applied here. */
730
+ async push(_opts: { dryRun?: boolean } = {}): Promise<PushResult> {
731
+ const preview = await this.preview({ direction: 'push' });
732
+ return { copied: preview.summary.copied, merged: preview.summary.merged, added: preview.summary.added, conflicts: preview.summary.conflicts };
733
+ }
734
+
735
+ // ---- status ----
736
+
737
+ // Manifest memo for STATUS DISPLAY ONLY (30 s TTL). Preview/apply always
738
+ // fetch a fresh manifest — the memo never influences a plan or a write.
739
+ private manifestMemo: { at: number; key: string; entries: RemoteManifestEntry[] } | null = null;
740
+ private async statusManifest(target: RemoteTarget): Promise<RemoteManifestEntry[]> {
741
+ const key = `${target.host}:${target.dshRoot}`;
742
+ const now = Date.now();
743
+ if (this.manifestMemo && this.manifestMemo.key === key && now - this.manifestMemo.at < 30_000) {
744
+ return this.manifestMemo.entries;
745
+ }
746
+ const entries = await this.transport.manifest(target);
747
+ this.manifestMemo = { at: now, key, entries };
748
+ return entries;
749
+ }
750
+
751
+ /** Local eligible paths with their sha256 (fingerprint cache fast-path; stale files stream-hashed). */
752
+ private async localSnapshotsWithHashes(localFiles: string[], onProgress?: (current: number, total: number, file: string) => void): Promise<Map<string, string>> {
753
+ const fsMod = this.fs;
754
+ const index = loadIndex(this.cacheDir);
755
+ const stale: string[] = [];
756
+ const out = new Map<string, string>();
757
+ for (const p of localFiles) {
758
+ const entry = probeIndex(p, index);
759
+ let st: any = null;
760
+ try {
761
+ st = typeof fsMod.statSync === 'function' ? fsMod.statSync(path.join(this.localDsh, p), { bigint: true } as any) : null;
762
+ } catch {
763
+ st = null;
764
+ }
765
+ if (entry && st && matchesStat(entry, st)) out.set(p, entry.sha256);
766
+ else stale.push(p);
767
+ }
768
+ if (stale.length > 0) {
769
+ let i = 0;
770
+ const hashed = await hashFiles(fsMod, this.localDsh, stale, {
771
+ onFile: (h) => {
772
+ i++;
773
+ onProgress?.(i, stale.length, h.path);
774
+ },
775
+ });
776
+ for (const h of hashed) {
777
+ out.set(h.path, h.sha256);
778
+ try {
779
+ const st = typeof fsMod.statSync === 'function' ? fsMod.statSync(path.join(this.localDsh, h.path), { bigint: true } as any) : null;
780
+ if (st) index.entries[h.path] = { ...statFingerprint(st), sha256: h.sha256 };
781
+ } catch {}
782
+ }
783
+ if (hashed.length > 0) saveIndex(this.cacheDir, index);
784
+ }
785
+ return out;
786
+ }
787
+
788
+ async status(): Promise<StatusResult> {
789
+ const connection = await this.checkConnection();
790
+ const localFiles = this.listLocalFiles();
791
+ if (!connection.ok) {
792
+ return { localOnly: localFiles.length, remoteOnly: 0, both: 0, localOnlyFiles: localFiles, remoteOnlyFiles: [], bothFiles: [], connection, remoteHost: this.remote };
793
+ }
794
+ let remoteFiles: string[] = [];
795
+ try {
796
+ const target = await this.requireTarget();
797
+ remoteFiles = (await this.statusManifest(target)).map((e) => e.path);
798
+ } catch {
799
+ remoteFiles = [];
800
+ }
801
+ const localSet = new Set(localFiles);
802
+ const remoteSet = new Set(remoteFiles);
803
+ const bothFiles = localFiles.filter((f) => remoteSet.has(f));
804
+ const localOnlyFiles = localFiles.filter((f) => !remoteSet.has(f));
805
+ const remoteOnlyFiles = remoteFiles.filter((f) => !localSet.has(f));
806
+ return {
807
+ localOnly: localOnlyFiles.length,
808
+ remoteOnly: remoteOnlyFiles.length,
809
+ both: bothFiles.length,
810
+ localOnlyFiles,
811
+ remoteOnlyFiles,
812
+ bothFiles,
813
+ connection,
814
+ remoteHost: this.remote,
815
+ };
816
+ }
817
+
818
+ /**
819
+ * Cursor-paged status page — bounded output.
820
+ * Buckets are ACTION-based (like preview): `remoteOnly` lists every file a
821
+ * pull would bring in (remote-only paths + both-side content differences),
822
+ * `localOnly` lists what a push would send (local-only paths + content
823
+ * differences). One manifest + one local stat/hash pass; no rsync compare.
824
+ */
825
+ async statusPage(opts: { bucket?: string; cursor?: number; limit?: number } = {}): Promise<StatusPage> {
826
+ const bucket = opts.bucket === 'remoteOnly' || opts.bucket === 'localOnly' ? opts.bucket : 'localOnly';
827
+ const offset = Math.max(0, Math.trunc(opts.cursor ?? 0));
828
+ const limit = Math.min(500, Math.max(1, Math.trunc(opts.limit ?? 100)));
829
+ const connection = await this.checkConnection();
830
+ if (!connection.ok) {
831
+ return { total: 0, offset, limit, files: [], nextCursor: null, connection, remoteHost: this.remote };
832
+ }
833
+ let all: string[] = [];
834
+ try {
835
+ const target = await this.requireTarget();
836
+ const remoteEntries = await this.statusManifest(target);
837
+ const localFiles = this.listLocalFiles();
838
+ const localSha = await this.localSnapshotsWithHashes(localFiles);
839
+ if (bucket === 'remoteOnly') {
840
+ // pull brings: remote-only paths (copy) + both-side content diffs (merge)
841
+ all = remoteEntries.filter((r) => localSha.get(r.path) === undefined || localSha.get(r.path) !== r.sha256).map((r) => r.path);
842
+ } else {
843
+ // push sends: local-only paths (copy) + content diffs on shared paths (merge)
844
+ const remoteSha = new Map(remoteEntries.map((r) => [r.path, r.sha256]));
845
+ all = localFiles.filter((p) => remoteSha.get(p) === undefined || remoteSha.get(p) !== localSha.get(p));
846
+ }
847
+ all = [...new Set(all)].sort();
848
+ } catch {
849
+ all = [];
850
+ }
851
+ const files = all.slice(offset, offset + limit);
852
+ const nextCursor = offset + files.length < all.length ? offset + files.length : null;
853
+ return { total: all.length, offset, limit, files, nextCursor, connection, remoteHost: this.remote };
854
+ }
855
+ }