@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,87 @@
1
+ export type SyncDirection = 'pull' | 'push';
2
+ export type SyncPhase = 'validate' | 'snapshot' | 'stage' | 'plan' | 'publish' | 'cleanup';
3
+ export interface RemoteTarget {
4
+ host: string;
5
+ dshRoot: string;
6
+ }
7
+ export interface SyncRequest {
8
+ direction: SyncDirection;
9
+ dryRun: boolean;
10
+ localRoot: string;
11
+ remote: RemoteTarget;
12
+ }
13
+ export interface SyncFailure {
14
+ phase: SyncPhase;
15
+ code: string;
16
+ detail: string;
17
+ path?: string;
18
+ }
19
+ export interface SyncSummary {
20
+ copied: number;
21
+ merged: number;
22
+ skipped: number;
23
+ conflicts: number;
24
+ added: number;
25
+ }
26
+ export interface FileSnapshot {
27
+ path: string;
28
+ sha256: string;
29
+ size: number;
30
+ kind: 'memory' | 'jsonl' | 'session';
31
+ }
32
+ export interface PlannedAction {
33
+ path: string;
34
+ action: 'copy' | 'merge' | 'skip' | 'conflict';
35
+ target: 'local' | 'remote';
36
+ added: number;
37
+ reason: string;
38
+ expectedTargetSha256?: string;
39
+ }
40
+ export interface SyncPlan {
41
+ revision: string;
42
+ actions: PlannedAction[];
43
+ summary: SyncSummary;
44
+ /** present when sessions were counted by checksum instead of staged */
45
+ sessionCounts?: SessionCounts;
46
+ }
47
+ /** Session-only preview counts (computed from path+checksum, no content staged). */
48
+ export interface SessionCounts {
49
+ /** files that only exist on the incoming side (will be copied) */
50
+ added: number;
51
+ /** files present on both sides with different checksums (will be merged) */
52
+ updated: number;
53
+ /** files that exist locally but the remote has dropped (pull keeps them; counted only) */
54
+ deleted: number;
55
+ /** files byte-identical on both sides (skipped) */
56
+ identical: number;
57
+ }
58
+ export interface SyncPreview extends SyncPlan {
59
+ previewId: string;
60
+ expiresAt: string;
61
+ /** present when sessions were counted by checksum instead of staged */
62
+ sessionCounts?: SessionCounts;
63
+ }
64
+ /** Per-file progress tick for async preview. */
65
+ export interface SyncProgress {
66
+ phase: 'listing' | 'hashing' | 'staging' | 'planning';
67
+ current: number;
68
+ total: number;
69
+ file?: string;
70
+ }
71
+ /** Job state exposed by RPC while a preview runs in the background. */
72
+ export interface PreviewJobState {
73
+ status: 'running' | 'done' | 'error' | 'cancelled';
74
+ progress: SyncProgress;
75
+ preview?: SyncPreview;
76
+ error?: string;
77
+ }
78
+ export interface PreviewRequest {
79
+ direction: SyncDirection;
80
+ }
81
+ export interface ApplyRequest {
82
+ previewId: string;
83
+ direction: SyncDirection;
84
+ confirm: true;
85
+ }
86
+ /** Inventory scope: 'memory' covers dsh-maestro-memory only, 'all' adds sessions/. */
87
+ export type SyncScope = 'memory' | 'all';
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,75 @@
1
+ import type { RemoteTarget } from './sync-types.js';
2
+ import type { ProcessRunner } from './process-runner.js';
3
+ import { type RemoteManifestEntry } from './remote-manifest.js';
4
+ import { type SshMux } from './ssh-mux.js';
5
+ export interface SyncTransport {
6
+ /** Resolve the remote user's $HOME as raw bytes (preflight, never shell ~ expansion). */
7
+ remoteHome(target: {
8
+ host: string;
9
+ }): Promise<string>;
10
+ /** Rsync one batched --files-from stage of validated relative paths into `destination`. */
11
+ stage(target: RemoteTarget, paths: readonly string[], destination: string): Promise<void>;
12
+ /**
13
+ * One-pass remote inventory: a single ssh runs the fixed NUL-framed manifest
14
+ * script and returns validated eligible entries (path/sha256/size/mtimeSec)
15
+ * — replaces find + rsync -rcn compare + session hashes for inventory.
16
+ */
17
+ manifest(target: RemoteTarget): Promise<RemoteManifestEntry[]>;
18
+ /**
19
+ * Refresh the remote fingerprint cache (<root>/.maestro-sync/fp.tsv, atomic
20
+ * tmp+rename). NEVER called from preview — only from the push-apply path
21
+ * (which already writes the remote) or an explicit warm command.
22
+ */
23
+ warmCache(target: RemoteTarget): Promise<void>;
24
+ /** Upload materialized bytes for one operation into the remote private stage dir. */
25
+ upload(target: RemoteTarget, source: string, paths: readonly string[], operationId: string): Promise<void>;
26
+ /** Install the fixed remote CAS helper under `<root>/.maestro-sync/bin`. */
27
+ ensureAgent(target: RemoteTarget): Promise<void>;
28
+ /** Run the fixed remote helper with `operationId`; the JSONL manifest is the only input. */
29
+ commit(target: RemoteTarget, operationId: string, manifest: Buffer): Promise<void>;
30
+ /** Read `<root>/machine-id` via the fixed helper; null when missing/unreadable (lenient unknown). */
31
+ readMachineId(target: RemoteTarget): Promise<string | null>;
32
+ /**
33
+ * Rewrite only `domains.tunnel` in the remote settings from the named
34
+ * profile via the fixed helper. No settings bytes cross the wire.
35
+ * Caller runs `ensureAgent` first. Returns changed flag + new settings sha.
36
+ */
37
+ patchRemoteTunnel(target: RemoteTarget, profile: string): Promise<{
38
+ changed: boolean;
39
+ sha256: string;
40
+ }>;
41
+ }
42
+ export declare class SshRsyncTransport implements SyncTransport {
43
+ private readonly runner;
44
+ private mux;
45
+ constructor(runner: ProcessRunner);
46
+ /** Attach an SSH ControlMaster for this operation (preview/apply wrapper). */
47
+ setMux(mux: SshMux | null): void;
48
+ private sshArgs;
49
+ private rsyncSSHArgs;
50
+ remoteHome(target: {
51
+ host: string;
52
+ }): Promise<string>;
53
+ stage(target: RemoteTarget, paths: readonly string[], destination: string): Promise<void>;
54
+ manifest(target: RemoteTarget): Promise<RemoteManifestEntry[]>;
55
+ warmCache(target: RemoteTarget): Promise<void>;
56
+ upload(target: RemoteTarget, source: string, paths: readonly string[], operationId: string): Promise<void>;
57
+ ensureAgent(target: RemoteTarget): Promise<void>;
58
+ commit(target: RemoteTarget, operationId: string, manifest: Buffer): Promise<void>;
59
+ /**
60
+ * Read-only identity probe. The deployed helper answers `machine-id` too,
61
+ * but only a MUTATING sync installs it (`ensureAgent`), and this probe runs
62
+ * before any mutation — so depending on it made the id unreadable (null) on
63
+ * a machine that had never synced, which is exactly when the direction has
64
+ * to be resolved. Read `<dshRoot>/machine-id` directly first (validated
65
+ * absolute path, argv-only ssh), then fall back to the helper, whose
66
+ * self-resolved root is authoritative when the deployed copy disagrees.
67
+ */
68
+ readMachineId(target: RemoteTarget): Promise<string | null>;
69
+ private readIdOverSsh;
70
+ patchRemoteTunnel(target: RemoteTarget, profile: string): Promise<{
71
+ changed: boolean;
72
+ sha256: string;
73
+ }>;
74
+ }
75
+ export declare function createTransport(runner: ProcessRunner): SyncTransport;
@@ -0,0 +1,200 @@
1
+ import { mkdtemp, writeFile, rm } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { validateRemoteTarget } from './validation.js';
5
+ import { REMOTE_AGENT_REL, remoteAgentSource, verifyRemoteAgentSource } from './remote-agent.js';
6
+ import { buildRemoteManifestScript, parseRemoteManifest } from './remote-manifest.js';
7
+ import { buildWarmCacheScript } from './remote-cache.js';
8
+ function failure(phase, code, detail, path) {
9
+ return { phase, code, detail, path };
10
+ }
11
+ function toFailure(phase, result, file) {
12
+ const detail = result.stderr.toString('utf-8') || `exit ${result.exitCode}`;
13
+ return failure(phase, 'TRANSPORT_ERROR', `${file} failed: ${detail}`);
14
+ }
15
+ export class SshRsyncTransport {
16
+ runner;
17
+ mux = null;
18
+ constructor(runner) {
19
+ this.runner = runner;
20
+ }
21
+ /** Attach an SSH ControlMaster for this operation (preview/apply wrapper). */
22
+ setMux(mux) {
23
+ this.mux = mux;
24
+ }
25
+ sshArgs(host) {
26
+ return this.mux ? [...this.mux.sshArgs, host] : [host];
27
+ }
28
+ rsyncSSHArgs() {
29
+ return this.mux ? ['-e', this.mux.rsyncRsh] : [];
30
+ }
31
+ async remoteHome(target) {
32
+ if (!target || typeof target.host !== 'string' || target.host.length === 0) {
33
+ throw Object.assign(new Error('remoteHome requires a non-empty host'), failure('validate', 'INVALID_HOST', 'remoteHome requires a non-empty host'));
34
+ }
35
+ // Preflight: `printf %s '$HOME'` over ssh returns the remote home as bytes.
36
+ // SSH-over-Cloudflare handshakes flake transiently (bad-handshake races),
37
+ // so one retry on spawn/timeout throw; exit-code and content failures are
38
+ // deterministic and fail fast. Still throws after the retry is exhausted.
39
+ let lastErr = null;
40
+ for (let attempt = 0; attempt < 2; attempt++) {
41
+ let result;
42
+ try {
43
+ result = await this.runner.run('ssh', [...this.sshArgs(target.host), 'printf', '%s', '$HOME'], { timeoutMs: 8000 });
44
+ }
45
+ catch (e) {
46
+ lastErr = e;
47
+ continue;
48
+ }
49
+ if (result.exitCode !== 0) {
50
+ throw Object.assign(new Error(`remoteHome failed: ${result.stderr.toString()}`), failure('validate', 'REMOTE_HOME_FAILED', result.stderr.toString()));
51
+ }
52
+ const home = result.stdout.toString('utf-8').trim();
53
+ if (!home || !home.startsWith('/')) {
54
+ throw Object.assign(new Error(`invalid remote home: ${JSON.stringify(home)}`), failure('validate', 'INVALID_REMOTE_HOME', String(home)));
55
+ }
56
+ return home;
57
+ }
58
+ throw lastErr instanceof Error ? lastErr : new Error(`remoteHome failed after retry: ${String(lastErr)}`);
59
+ }
60
+ async stage(target, paths, destination) {
61
+ const validated = validateRemoteTarget(target);
62
+ if (paths.length === 0)
63
+ return;
64
+ const tmp = await mkdtemp(join(tmpdir(), 'maestro-stage-'));
65
+ try {
66
+ const listFile = join(tmp, 'files.txt');
67
+ await writeFile(listFile, paths.join('\n') + '\n', 'utf-8');
68
+ const result = await this.runner.run('rsync', [...this.rsyncSSHArgs(), '-az', '--files-from=' + listFile, `${validated.host}:${validated.dshRoot}/`, destination + '/'],
69
+ // SSH transfers of hundreds of small session files need more than 2 min
70
+ // on real links (3.5s latency × N round-trips); 5 min keeps preview/apply
71
+ // usable while still failing closed when the link is actually down.
72
+ { timeoutMs: 300000 });
73
+ if (result.exitCode !== 0) {
74
+ throw Object.assign(new Error(`stage failed: ${result.stderr.toString()}`), failure('stage', 'STAGE_FAILED', result.stderr.toString()));
75
+ }
76
+ }
77
+ finally {
78
+ await rm(tmp, { recursive: true, force: true }).catch(() => { });
79
+ }
80
+ }
81
+ async manifest(target) {
82
+ const validated = validateRemoteTarget(target);
83
+ // One ssh runs the fixed NUL-framed manifest script (find + sha256sum +
84
+ // stat in a single pass); every returned path is validated by the parser
85
+ // before it can enter a plan. This replaces list + compare + hashes for
86
+ // inventory: one remote byte pass, one spawn.
87
+ const result = await this.runner.run('ssh', [...this.sshArgs(validated.host), buildRemoteManifestScript(validated.dshRoot)], { timeoutMs: 300000 });
88
+ if (result.exitCode !== 0) {
89
+ throw Object.assign(new Error(`manifest failed: ${result.stderr.toString()}`), failure('snapshot', 'MANIFEST_FAILED', result.stderr.toString()));
90
+ }
91
+ return parseRemoteManifest(result.stdout);
92
+ }
93
+ async warmCache(target) {
94
+ const validated = validateRemoteTarget(target);
95
+ // Refreshes <root>/.maestro-sync/fp.tsv atomically on the remote. Only the
96
+ // push-apply path (post-commit) or an explicit warm command calls this —
97
+ // preview must stay strictly read-only.
98
+ const result = await this.runner.run('ssh', [...this.sshArgs(validated.host), buildWarmCacheScript(validated.dshRoot)], { timeoutMs: 300000 });
99
+ if (result.exitCode !== 0) {
100
+ throw Object.assign(new Error(`warmCache failed: ${result.stderr.toString()}`), failure('snapshot', 'WARM_FAILED', result.stderr.toString()));
101
+ }
102
+ }
103
+ async upload(target, source, paths, operationId) {
104
+ const validated = validateRemoteTarget(target);
105
+ if (paths.length === 0)
106
+ return;
107
+ const remoteStage = `${validated.dshRoot}/.maestro-sync/stage/${operationId}`;
108
+ const mkdirResult = await this.runner.run('ssh', [...this.sshArgs(validated.host), 'mkdir', '-p', remoteStage], { timeoutMs: 8000 });
109
+ if (mkdirResult.exitCode !== 0) {
110
+ throw Object.assign(new Error(`mkdir failed: ${mkdirResult.stderr.toString()}`), failure('publish', 'UPLOAD_FAILED', mkdirResult.stderr.toString()));
111
+ }
112
+ const tmp = await mkdtemp(join(tmpdir(), 'maestro-upload-'));
113
+ try {
114
+ const listFile = join(tmp, 'files.txt');
115
+ await writeFile(listFile, paths.join('\n') + '\n', 'utf-8');
116
+ const result = await this.runner.run('rsync', [...this.rsyncSSHArgs(), '-az', '--files-from=' + listFile, source + '/', `${validated.host}:${remoteStage}/`], { timeoutMs: 300000 });
117
+ if (result.exitCode !== 0) {
118
+ throw Object.assign(new Error(`upload failed: ${result.stderr.toString()}`), failure('publish', 'UPLOAD_FAILED', result.stderr.toString()));
119
+ }
120
+ }
121
+ finally {
122
+ await rm(tmp, { recursive: true, force: true }).catch(() => { });
123
+ }
124
+ }
125
+ async ensureAgent(target) {
126
+ const validated = validateRemoteTarget(target);
127
+ const agentPath = `${validated.dshRoot}/${REMOTE_AGENT_REL}`;
128
+ const agentDir = `${validated.dshRoot}/.maestro-sync/bin`;
129
+ const source = verifyRemoteAgentSource(remoteAgentSource());
130
+ // mkdir -p the private bin dir, then stream the fixed helper via stdin (argv-only).
131
+ const mkdirResult = await this.runner.run('ssh', [...this.sshArgs(validated.host), 'mkdir', '-p', agentDir], { timeoutMs: 8000 });
132
+ if (mkdirResult.exitCode !== 0) {
133
+ throw Object.assign(new Error(`ensureAgent mkdir failed: ${mkdirResult.stderr.toString()}`), failure('publish', 'AGENT_INSTALL_FAILED', mkdirResult.stderr.toString()));
134
+ }
135
+ const installResult = await this.runner.run('ssh', [...this.sshArgs(validated.host), `cat > ${agentPath}`], { input: Buffer.from(source, 'utf-8'), timeoutMs: 8000 });
136
+ if (installResult.exitCode !== 0) {
137
+ throw Object.assign(new Error(`ensureAgent install failed: ${installResult.stderr.toString()}`), failure('publish', 'AGENT_INSTALL_FAILED', installResult.stderr.toString()));
138
+ }
139
+ const chmodResult = await this.runner.run('ssh', [...this.sshArgs(validated.host), 'chmod', '700', agentPath], { timeoutMs: 8000 });
140
+ if (chmodResult.exitCode !== 0) {
141
+ throw Object.assign(new Error(`ensureAgent chmod failed: ${chmodResult.stderr.toString()}`), failure('publish', 'AGENT_INSTALL_FAILED', chmodResult.stderr.toString()));
142
+ }
143
+ }
144
+ async commit(target, operationId, manifest) {
145
+ const validated = validateRemoteTarget(target);
146
+ // Fixed protocol command: the helper path is a validated constant under the
147
+ // validated root; operationId is a locally generated hex id. The manifest on
148
+ // stdin is the only carrier of discovered paths.
149
+ const result = await this.runner.run('ssh', [validated.host, `${validated.dshRoot}/${REMOTE_AGENT_REL}`, operationId], { input: manifest, timeoutMs: 15000 });
150
+ if (result.exitCode !== 0) {
151
+ const stderr = result.stderr.toString('utf-8');
152
+ const code = stderr.includes('CONCURRENT_MODIFICATION') ? 'CONCURRENT_MODIFICATION' : 'COMMIT_FAILED';
153
+ throw Object.assign(new Error(`commit failed: ${stderr || `exit ${result.exitCode}`}`), failure('publish', code, stderr || `exit ${result.exitCode}`));
154
+ }
155
+ }
156
+ /**
157
+ * Read-only identity probe. The deployed helper answers `machine-id` too,
158
+ * but only a MUTATING sync installs it (`ensureAgent`), and this probe runs
159
+ * before any mutation — so depending on it made the id unreadable (null) on
160
+ * a machine that had never synced, which is exactly when the direction has
161
+ * to be resolved. Read `<dshRoot>/machine-id` directly first (validated
162
+ * absolute path, argv-only ssh), then fall back to the helper, whose
163
+ * self-resolved root is authoritative when the deployed copy disagrees.
164
+ */
165
+ async readMachineId(target) {
166
+ const validated = validateRemoteTarget(target);
167
+ const direct = await this.readIdOverSsh(validated.host, ['cat', `${validated.dshRoot}/machine-id`]);
168
+ if (direct !== null)
169
+ return direct;
170
+ return await this.readIdOverSsh(validated.host, [`${validated.dshRoot}/${REMOTE_AGENT_REL}`, 'machine-id']);
171
+ }
172
+ async readIdOverSsh(host, argv) {
173
+ try {
174
+ const result = await this.runner.run('ssh', [host, ...argv], { timeoutMs: 8000 });
175
+ if (result.exitCode !== 0)
176
+ return null;
177
+ const id = result.stdout.toString('utf-8').trim();
178
+ return id.length > 0 ? id : null;
179
+ }
180
+ catch {
181
+ return null;
182
+ }
183
+ }
184
+ async patchRemoteTunnel(target, profile) {
185
+ const validated = validateRemoteTarget(target);
186
+ // Fixed protocol command: profile is a validated name, never a path.
187
+ // Caller runs ensureAgent first (same contract as commit).
188
+ const result = await this.runner.run('ssh', [validated.host, `${validated.dshRoot}/${REMOTE_AGENT_REL}`, 'tunnel-patch', profile], { timeoutMs: 15000 });
189
+ const line = result.stdout.toString('utf-8').trim();
190
+ const m = /^(PATCHED|UNCHANGED) ([0-9a-f]{64})$/.exec(line);
191
+ if (result.exitCode !== 0 || !m) {
192
+ const stderr = result.stderr.toString('utf-8');
193
+ throw Object.assign(new Error(`tunnel patch failed: ${stderr || line || `exit ${result.exitCode}`}`), failure('publish', 'TUNNEL_PATCH_FAILED', stderr || line || `exit ${result.exitCode}`));
194
+ }
195
+ return { changed: m[1] === 'PATCHED', sha256: m[2] };
196
+ }
197
+ }
198
+ export function createTransport(runner) {
199
+ return new SshRsyncTransport(runner);
200
+ }
@@ -0,0 +1,77 @@
1
+ import type { SyncTransport } from './transport.js';
2
+ import type { RemoteTarget } from './sync-types.js';
3
+ export type LocalRestoreResult = {
4
+ ok: true;
5
+ profile: string;
6
+ } | {
7
+ ok: false;
8
+ code: 'NO_PROFILE' | 'INVALID_PROFILE';
9
+ };
10
+ export type RemoteRestoreResult = {
11
+ ok: true;
12
+ profile: string;
13
+ changed: boolean;
14
+ sha256: string;
15
+ } | {
16
+ ok: false;
17
+ code: 'BAD_PROFILE';
18
+ };
19
+ /** Everything a caller needs to DESCRIBE (not perform) a local restore. */
20
+ export type LocalTunnelProfile = {
21
+ ok: true;
22
+ profile: string;
23
+ /** the named-tunnel OBJECT read from the profile, already shape-checked */
24
+ tunnel: Record<string, unknown>;
25
+ cloudflaredSrc: string;
26
+ cloudflaredDst: string;
27
+ settingsPath: string;
28
+ } | {
29
+ ok: false;
30
+ code: 'NO_PROFILE' | 'INVALID_PROFILE';
31
+ };
32
+ /** Profile names are single path segments; mirrors the remote-agent allowlist. */
33
+ export declare function isSafeProfileName(name: string): boolean;
34
+ /**
35
+ * The tunnel domain is a named-tunnel OBJECT (mode/hostname/...), never a
36
+ * bare string. A string write clobbered the object shape on 2026-09-09 and
37
+ * took a machine's tunnel down (HTTP 530) — so a non-object profile value
38
+ * fails closed here before anything is written.
39
+ */
40
+ export declare function isValidTunnelDomain(v: unknown): v is Record<string, unknown>;
41
+ /**
42
+ * Local tunnel profile restore: re-patches the moved shared store
43
+ * (<dsh>/dsh-maestro-config/settings.json via config-lib) domains.tunnel
44
+ * from this machine's own profile dir. Never throws; profiles may not
45
+ * exist on CI.
46
+ */
47
+ /**
48
+ * Read-only resolution of this machine's tunnel profile: which profile would
49
+ * be restored, and the named-tunnel object it carries. Performs no write, so a
50
+ * read-only preview can show the operator exactly what a restore would change
51
+ * before anything touches the shared store. Never throws.
52
+ */
53
+ export declare function readLocalTunnelProfile(opts?: {
54
+ dshHome?: string;
55
+ profileName?: string;
56
+ }): LocalTunnelProfile;
57
+ /**
58
+ * Local tunnel profile restore: re-patches the moved shared store
59
+ * (<dsh>/dsh-maestro-config/settings.json via config-lib) domains.tunnel
60
+ * from this machine's own profile dir. Never throws; profiles may not
61
+ * exist on CI.
62
+ *
63
+ * The mutation itself lives here; the decision to run it belongs to the
64
+ * caller's preview/confirm contract (see the `tunnelRestorePreview` /
65
+ * `tunnelRestore` RPC pair in `index.ts`) — this function is never called
66
+ * from a bare click.
67
+ */
68
+ export declare function restoreLocalTunnel(opts?: {
69
+ dshHome?: string;
70
+ profileName?: string;
71
+ }): Promise<LocalRestoreResult>;
72
+ /**
73
+ * Remote tunnel restore via the fixed agent op: the profile is read on the
74
+ * remote itself and only `domains.tunnel` is rewritten. No settings bytes
75
+ * cross the wire. Transport errors propagate (fail closed, typed failure).
76
+ */
77
+ export declare function restoreRemoteTunnel(transport: Pick<SyncTransport, 'patchRemoteTunnel'>, target: RemoteTarget, profileName: string): Promise<RemoteRestoreResult>;
@@ -0,0 +1,142 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import * as os from 'node:os';
4
+ /** Profile names are single path segments; mirrors the remote-agent allowlist. */
5
+ export function isSafeProfileName(name) {
6
+ if (!name || name.startsWith('.') || name.includes('..') || name.includes('/'))
7
+ return false;
8
+ return /^[A-Za-z0-9._-]+$/.test(name);
9
+ }
10
+ /**
11
+ * The tunnel domain is a named-tunnel OBJECT (mode/hostname/...), never a
12
+ * bare string. A string write clobbered the object shape on 2026-09-09 and
13
+ * took a machine's tunnel down (HTTP 530) — so a non-object profile value
14
+ * fails closed here before anything is written.
15
+ */
16
+ export function isValidTunnelDomain(v) {
17
+ if (!v || typeof v !== 'object' || Array.isArray(v))
18
+ return false;
19
+ const t = v;
20
+ return typeof t.mode === 'string' && t.mode.length > 0 && typeof t.hostname === 'string' && t.hostname.length > 0;
21
+ }
22
+ /**
23
+ * Local tunnel profile restore: re-patches the moved shared store
24
+ * (<dsh>/dsh-maestro-config/settings.json via config-lib) domains.tunnel
25
+ * from this machine's own profile dir. Never throws; profiles may not
26
+ * exist on CI.
27
+ */
28
+ /**
29
+ * Read-only resolution of this machine's tunnel profile: which profile would
30
+ * be restored, and the named-tunnel object it carries. Performs no write, so a
31
+ * read-only preview can show the operator exactly what a restore would change
32
+ * before anything touches the shared store. Never throws.
33
+ */
34
+ export function readLocalTunnelProfile(opts) {
35
+ try {
36
+ const dshHome = opts?.dshHome ?? process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh');
37
+ const profilesRoot = path.join(dshHome, 'dsh-maestro-remote', 'tunnel-profiles');
38
+ if (!fs.existsSync(profilesRoot))
39
+ return { ok: false, code: 'NO_PROFILE' };
40
+ let profiles = [];
41
+ try {
42
+ profiles = fs.readdirSync(profilesRoot).filter((n) => {
43
+ try {
44
+ return fs.statSync(path.join(profilesRoot, n)).isDirectory();
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ });
50
+ }
51
+ catch {
52
+ return { ok: false, code: 'NO_PROFILE' };
53
+ }
54
+ if (profiles.length === 0)
55
+ return { ok: false, code: 'NO_PROFILE' };
56
+ const envProfile = process.env.LOCAL_TUNNEL_PROFILE || process.env.TUNNEL_PROFILE;
57
+ const wanted = opts?.profileName ?? (envProfile && profiles.includes(envProfile) ? envProfile : undefined);
58
+ const profileName = wanted ?? profiles[0];
59
+ if (!profileName)
60
+ return { ok: false, code: 'NO_PROFILE' };
61
+ const profileDir = path.join(profilesRoot, profileName);
62
+ const tunnelSettingsPath = path.join(profileDir, 'settings-tunnel.json');
63
+ const cloudflaredSrc = path.join(profileDir, 'cloudflared-config.yml');
64
+ const cloudflaredDst = path.join(dshHome, 'dsh-maestro-remote', 'cloudflared-config.yml');
65
+ const settingsPath = path.join(dshHome, 'dsh-maestro-config', 'settings.json');
66
+ // Gate only on the profile source: the store file itself may be absent
67
+ // (config-lib recreates it); a missing store must not skip the restore.
68
+ if (!fs.existsSync(tunnelSettingsPath))
69
+ return { ok: false, code: 'NO_PROFILE' };
70
+ const tunnelJson = JSON.parse(fs.readFileSync(tunnelSettingsPath, 'utf-8'));
71
+ const tunnelDomain = tunnelJson?.domains?.tunnel;
72
+ if (!isValidTunnelDomain(tunnelDomain))
73
+ return { ok: false, code: 'INVALID_PROFILE' };
74
+ return { ok: true, profile: profileName, tunnel: tunnelDomain, cloudflaredSrc, cloudflaredDst, settingsPath };
75
+ }
76
+ catch {
77
+ return { ok: false, code: 'NO_PROFILE' };
78
+ }
79
+ }
80
+ /**
81
+ * Local tunnel profile restore: re-patches the moved shared store
82
+ * (<dsh>/dsh-maestro-config/settings.json via config-lib) domains.tunnel
83
+ * from this machine's own profile dir. Never throws; profiles may not
84
+ * exist on CI.
85
+ *
86
+ * The mutation itself lives here; the decision to run it belongs to the
87
+ * caller's preview/confirm contract (see the `tunnelRestorePreview` /
88
+ * `tunnelRestore` RPC pair in `index.ts`) — this function is never called
89
+ * from a bare click.
90
+ */
91
+ export async function restoreLocalTunnel(opts) {
92
+ const found = readLocalTunnelProfile(opts);
93
+ if (!found.ok)
94
+ return { ok: false, code: found.code };
95
+ const { profile, tunnel, cloudflaredSrc, cloudflaredDst, settingsPath } = found;
96
+ try {
97
+ if (fs.existsSync(cloudflaredSrc) && fs.existsSync(path.dirname(cloudflaredDst))) {
98
+ fs.copyFileSync(cloudflaredSrc, cloudflaredDst);
99
+ try {
100
+ fs.chmodSync(cloudflaredDst, 0o600);
101
+ }
102
+ catch { }
103
+ }
104
+ }
105
+ catch { }
106
+ try {
107
+ try {
108
+ const cfgLib = await import('../store/index.js');
109
+ if (typeof cfgLib.set === 'function') {
110
+ await cfgLib.set('tunnel', tunnel);
111
+ return { ok: true, profile };
112
+ }
113
+ }
114
+ catch { }
115
+ const raw = fs.readFileSync(settingsPath, 'utf-8');
116
+ const doc = JSON.parse(raw);
117
+ doc.domains = doc.domains || {};
118
+ doc.domains.tunnel = tunnel;
119
+ const tmp = settingsPath + '.tmp.' + Math.random().toString(16).slice(2, 6);
120
+ fs.writeFileSync(tmp, JSON.stringify(doc, null, 2) + '\n', 'utf-8');
121
+ fs.renameSync(tmp, settingsPath);
122
+ try {
123
+ fs.chmodSync(settingsPath, 0o600);
124
+ }
125
+ catch { }
126
+ return { ok: true, profile };
127
+ }
128
+ catch {
129
+ return { ok: false, code: 'NO_PROFILE' };
130
+ }
131
+ }
132
+ /**
133
+ * Remote tunnel restore via the fixed agent op: the profile is read on the
134
+ * remote itself and only `domains.tunnel` is rewritten. No settings bytes
135
+ * cross the wire. Transport errors propagate (fail closed, typed failure).
136
+ */
137
+ export async function restoreRemoteTunnel(transport, target, profileName) {
138
+ if (!isSafeProfileName(profileName))
139
+ return { ok: false, code: 'BAD_PROFILE' };
140
+ const out = await transport.patchRemoteTunnel(target, profileName);
141
+ return { ok: true, profile: profileName, changed: out.changed, sha256: out.sha256 };
142
+ }
@@ -0,0 +1,10 @@
1
+ import type { RemoteTarget } from './sync-types.js';
2
+ export declare const HOST_RE: RegExp;
3
+ export declare const ABSOLUTE_RE: RegExp;
4
+ export declare const ELIGIBLE_RE: RegExp;
5
+ export declare const HOST: RegExp;
6
+ export declare const ABSOLUTE: RegExp;
7
+ export declare const ELIGIBLE: RegExp;
8
+ export declare function validateHost(host: string): string;
9
+ export declare function validateRemoteTarget(value: RemoteTarget): RemoteTarget;
10
+ export declare function normalizeEligiblePath(value: string): string;