@ddtcorex/dsh-maestro-core 0.15.0 → 0.16.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 (117) hide show
  1. package/README.md +7 -7
  2. package/assets/icon.svg +4 -0
  3. package/cordis.patch.yml +0 -12
  4. package/lib/client.js +3 -1744
  5. package/lib/health-poller.js +1 -1
  6. package/lib/self-kill-guard.d.ts +25 -8
  7. package/lib/self-kill-guard.js +81 -27
  8. package/lib/types/client/config/components/BrandMark.d.ts +3 -3
  9. package/lib/types/client/index.d.ts.map +1 -1
  10. package/locale/en.json +6 -0
  11. package/package.json +9 -5
  12. package/src/client/config/components/BrandMark.tsx +3 -3
  13. package/src/client/index.tsx +0 -2
  14. package/src/host/health-poller.ts +1 -1
  15. package/src/host/self-kill-guard.ts +84 -26
  16. package/lib/sync/backup-config.d.ts +0 -55
  17. package/lib/sync/backup-config.js +0 -119
  18. package/lib/sync/backup-service.d.ts +0 -123
  19. package/lib/sync/backup-service.js +0 -486
  20. package/lib/sync/bidirectional.d.ts +0 -39
  21. package/lib/sync/bidirectional.js +0 -25
  22. package/lib/sync/cli.d.ts +0 -38
  23. package/lib/sync/cli.js +0 -528
  24. package/lib/sync/config.d.ts +0 -59
  25. package/lib/sync/config.js +0 -72
  26. package/lib/sync/fingerprint.d.ts +0 -29
  27. package/lib/sync/fingerprint.js +0 -65
  28. package/lib/sync/hashing.d.ts +0 -22
  29. package/lib/sync/hashing.js +0 -77
  30. package/lib/sync/index.d.ts +0 -6
  31. package/lib/sync/index.js +0 -619
  32. package/lib/sync/machine-id.d.ts +0 -29
  33. package/lib/sync/machine-id.js +0 -66
  34. package/lib/sync/merge.d.ts +0 -31
  35. package/lib/sync/merge.js +0 -86
  36. package/lib/sync/peer-host.d.ts +0 -22
  37. package/lib/sync/peer-host.js +0 -62
  38. package/lib/sync/process-runner.d.ts +0 -31
  39. package/lib/sync/process-runner.js +0 -161
  40. package/lib/sync/remote-agent.d.ts +0 -41
  41. package/lib/sync/remote-agent.js +0 -227
  42. package/lib/sync/remote-cache.d.ts +0 -18
  43. package/lib/sync/remote-cache.js +0 -60
  44. package/lib/sync/remote-manifest.d.ts +0 -33
  45. package/lib/sync/remote-manifest.js +0 -111
  46. package/lib/sync/s3-object-store.d.ts +0 -38
  47. package/lib/sync/s3-object-store.js +0 -126
  48. package/lib/sync/session-plan.d.ts +0 -29
  49. package/lib/sync/session-plan.js +0 -213
  50. package/lib/sync/sigv4.d.ts +0 -20
  51. package/lib/sync/sigv4.js +0 -57
  52. package/lib/sync/snapshot.d.ts +0 -16
  53. package/lib/sync/snapshot.js +0 -143
  54. package/lib/sync/ssh-mux.d.ts +0 -12
  55. package/lib/sync/ssh-mux.js +0 -48
  56. package/lib/sync/store-root.d.ts +0 -44
  57. package/lib/sync/store-root.js +0 -67
  58. package/lib/sync/sync-plan.d.ts +0 -24
  59. package/lib/sync/sync-plan.js +0 -366
  60. package/lib/sync/sync-service.d.ts +0 -181
  61. package/lib/sync/sync-service.js +0 -911
  62. package/lib/sync/sync-types.d.ts +0 -87
  63. package/lib/sync/sync-types.js +0 -1
  64. package/lib/sync/transport.d.ts +0 -75
  65. package/lib/sync/transport.js +0 -196
  66. package/lib/sync/tunnel-restore.d.ts +0 -77
  67. package/lib/sync/tunnel-restore.js +0 -142
  68. package/lib/sync/validation.d.ts +0 -12
  69. package/lib/sync/validation.js +0 -96
  70. package/lib/types/client/sync/R2SyncPanel.d.ts +0 -6
  71. package/lib/types/client/sync/R2SyncPanel.d.ts.map +0 -1
  72. package/lib/types/client/sync/SyncPanel.d.ts +0 -12
  73. package/lib/types/client/sync/SyncPanel.d.ts.map +0 -1
  74. package/lib/types/client/sync/confirm-dialog.d.ts +0 -43
  75. package/lib/types/client/sync/confirm-dialog.d.ts.map +0 -1
  76. package/lib/types/client/sync/index.d.ts +0 -10
  77. package/lib/types/client/sync/index.d.ts.map +0 -1
  78. package/lib/types/client/sync/ui.d.ts +0 -75
  79. package/lib/types/client/sync/ui.d.ts.map +0 -1
  80. package/lib/types/client/sync/use-backup.d.ts +0 -50
  81. package/lib/types/client/sync/use-backup.d.ts.map +0 -1
  82. package/lib/types/client/sync/use-sync.d.ts +0 -88
  83. package/lib/types/client/sync/use-sync.d.ts.map +0 -1
  84. package/src/client/sync/R2SyncPanel.tsx +0 -260
  85. package/src/client/sync/SyncPanel.tsx +0 -422
  86. package/src/client/sync/confirm-dialog.tsx +0 -202
  87. package/src/client/sync/index.tsx +0 -286
  88. package/src/client/sync/ui.tsx +0 -297
  89. package/src/client/sync/use-backup.ts +0 -207
  90. package/src/client/sync/use-sync.ts +0 -502
  91. package/src/host/sync/backup-config.ts +0 -158
  92. package/src/host/sync/backup-service.ts +0 -506
  93. package/src/host/sync/bidirectional.ts +0 -66
  94. package/src/host/sync/cli.ts +0 -530
  95. package/src/host/sync/config.ts +0 -96
  96. package/src/host/sync/fingerprint.ts +0 -83
  97. package/src/host/sync/hashing.ts +0 -91
  98. package/src/host/sync/index.ts +0 -697
  99. package/src/host/sync/machine-id.ts +0 -81
  100. package/src/host/sync/merge.ts +0 -99
  101. package/src/host/sync/peer-host.ts +0 -65
  102. package/src/host/sync/process-runner.ts +0 -177
  103. package/src/host/sync/remote-agent.ts +0 -223
  104. package/src/host/sync/remote-cache.ts +0 -68
  105. package/src/host/sync/remote-manifest.ts +0 -117
  106. package/src/host/sync/s3-object-store.ts +0 -144
  107. package/src/host/sync/session-plan.ts +0 -237
  108. package/src/host/sync/sigv4.ts +0 -81
  109. package/src/host/sync/snapshot.ts +0 -132
  110. package/src/host/sync/ssh-mux.ts +0 -55
  111. package/src/host/sync/store-root.ts +0 -83
  112. package/src/host/sync/sync-plan.ts +0 -366
  113. package/src/host/sync/sync-service.ts +0 -944
  114. package/src/host/sync/sync-types.ts +0 -102
  115. package/src/host/sync/transport.ts +0 -256
  116. package/src/host/sync/tunnel-restore.ts +0 -160
  117. package/src/host/sync/validation.ts +0 -104
package/lib/sync/cli.d.ts DELETED
@@ -1,38 +0,0 @@
1
- #!/usr/bin/env node
2
- import { type SyncConfig } from './config.js';
3
- import { SyncService } from './sync-service.js';
4
- interface CliDeps {
5
- stdout?: (s: string) => void;
6
- stderr?: (s: string) => void;
7
- makeService?: (cfg: SyncConfig) => Promise<SyncService>;
8
- /** Hermetic seam for the machine-identity reads (defaults hit real fs/ssh). */
9
- identity?: {
10
- readLocal?: (dshHome: string) => Promise<string | null>;
11
- readRemote?: (host: string, remoteDsh: string) => Promise<string | null>;
12
- };
13
- }
14
- interface CliOpts {
15
- mode: 'pull' | 'push' | 'bidirectional' | null;
16
- subcommand: 'check-machines' | 'tunnel-restore' | 'set-peer-host' | null;
17
- dryRun: boolean;
18
- hasApplyFlag: boolean;
19
- applyPreviewId?: string;
20
- confirm: boolean;
21
- includeSessions: boolean;
22
- from?: string;
23
- to?: string;
24
- side?: string;
25
- profile?: string;
26
- peerHost?: string;
27
- clearPeer?: boolean;
28
- localDsh?: string;
29
- remote?: string;
30
- remoteDsh?: string;
31
- backupRoot?: string;
32
- strategy: 'merge' | 'override';
33
- ackOverride: boolean;
34
- help: boolean;
35
- }
36
- export declare function parseArgs(argv: string[], err: (s: string) => void): CliOpts | null;
37
- export declare function runCli(argv: string[], deps?: CliDeps): Promise<number>;
38
- export {};
package/lib/sync/cli.js DELETED
@@ -1,528 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * dsh-maestro-sync CLI — validated, preview-first wrapper for sync operations.
4
- *
5
- * node lib/cli.js --pull [--dry-run] -> preview only (default)
6
- * node lib/cli.js --pull --apply --preview-id ID --confirm -> apply a preview
7
- *
8
- * No omitted boolean can apply a sync: `--apply` requires BOTH `--preview-id`
9
- * and `--confirm`. `--strategy=override` is a destructive escape hatch and
10
- * requires a separate `--ack-override` flag. The CLI emits one final JSON
11
- * result to stdout and human progress to stderr. Executable via:
12
- * node lib/cli.js --pull --dry-run
13
- */
14
- import * as path from 'node:path';
15
- import * as os from 'node:os';
16
- import { DEFAULT_REMOTE_HOST, loadSyncConfig } from './config.js';
17
- import { validateHost } from './validation.js';
18
- import { SyncService } from './sync-service.js';
19
- import { runBidirectionalApply, runBidirectionalPreview } from './bidirectional.js';
20
- import { checkMachines, isMachineId, peerMachineId, readLocalMachineId } from './machine-id.js';
21
- import { restoreLocalTunnel, restoreRemoteTunnel } from './tunnel-restore.js';
22
- import { clearPeerHost, writePeerHost } from './peer-host.js';
23
- import { NodeProcessRunner } from './process-runner.js';
24
- import { SshRsyncTransport } from './transport.js';
25
- function printHelp(prog) {
26
- return `
27
- dsh-maestro-sync CLI — merge memory & sessions across machines
28
-
29
- USAGE
30
- node ${prog} --pull|--push [--dry-run] preview (default, read-only)
31
- node ${prog} --pull|--push --apply --preview-id ID --confirm apply a preview
32
- node ${prog} --bidirectional [--dry-run] [--include-sessions] push-then-pull in one operation
33
- node ${prog} --bidirectional --apply --preview-id ID --confirm apply it
34
- node ${prog} check-machines [--pull|--push|--bidirectional] [--from X --to Y]
35
- node ${prog} tunnel-restore --side local|remote [--profile NAME] --confirm
36
- node ${prog} set-peer-host --host HOST | --clear
37
-
38
- OPTIONS
39
- --pull pull merge: remote -> local
40
- --push push merge: local -> remote
41
- --bidirectional push then pull, one operation (merge strategy only)
42
- --include-sessions with --bidirectional: also sync sessions/ (default: memories only)
43
- --from/--to <id> absolute machines, by the id each side wrote to its
44
- $DSH_HOME/machine-id; identity is enforced before
45
- any preview/apply (from defaults to the local
46
- machine-id, to defaults to its peer)
47
- --dry-run, -n preview only (default); never writes
48
- --apply apply a previous preview — REQUIRES --preview-id and --confirm
49
- --preview-id <id> preview id returned by --dry-run
50
- --confirm explicit confirmation that the preview may be applied
51
- --local-dsh <path> local DSH home (default: DSH_HOME or ~/.dsh)
52
- --host <host> with set-peer-host: this machine's peer ssh target
53
- --clear with set-peer-host: drop the machine-local peer
54
- --remote <host> ssh remote host (default: from config/REMOTE_HOST)
55
- --remote-dsh <path> remote DSH path; must be absolute (e.g. /home/user/.dsh);
56
- a '~/.dsh' default is resolved to an absolute remote home
57
- path by the transport preflight, never shell ~ expansion
58
- --strategy <merge|override> merge (default): union dedup, no --delete.
59
- override: destructive rsync --delete mirror — REQUIRES --ack-override
60
- --ack-override acknowledge that --strategy=override is destructive
61
- --backup-root <path> accepted for compatibility; DSH publishes .bak.<ts> beside each file
62
- --side <local|remote> with tunnel-restore: which side to restore (default local)
63
- --profile <name> with tunnel-restore: profile name (required for remote)
64
- --help, -h this help
65
-
66
- EXIT CODES
67
- 0 success (including a dry-run preview), 1 error / apply partial failure
68
- `.trim();
69
- }
70
- export function parseArgs(argv, err) {
71
- const opts = {
72
- mode: null,
73
- subcommand: null,
74
- dryRun: true,
75
- hasApplyFlag: false,
76
- confirm: false,
77
- includeSessions: false,
78
- strategy: 'merge',
79
- ackOverride: false,
80
- help: false,
81
- };
82
- const fail = (msg) => {
83
- err(`[err] ${msg}`);
84
- return null;
85
- };
86
- // Subcommands come first (check-machines, tunnel-restore); the rest are flags.
87
- const rest = [...argv];
88
- if (rest.length > 0 && (rest[0] === 'check-machines' || rest[0] === 'tunnel-restore' || rest[0] === 'set-peer-host')) {
89
- opts.subcommand = rest.shift();
90
- }
91
- for (let i = 0; i < rest.length; i++) {
92
- const a = rest[i];
93
- if (a === '--pull' || a === '--push' || a === '--bidirectional') {
94
- if (opts.mode)
95
- return fail('Specify only one of --pull, --push or --bidirectional');
96
- opts.mode = a === '--pull' ? 'pull' : a === '--push' ? 'push' : 'bidirectional';
97
- }
98
- else if (a === '--include-sessions') {
99
- opts.includeSessions = true;
100
- }
101
- else if (a === '--dry-run' || a === '-n') {
102
- opts.dryRun = true;
103
- }
104
- else if (a === '--apply') {
105
- opts.hasApplyFlag = true;
106
- opts.dryRun = false;
107
- }
108
- else if (a === '--confirm') {
109
- opts.confirm = true;
110
- }
111
- else if (a === '--preview-id') {
112
- const v = rest[++i];
113
- if (!v || v.startsWith('-'))
114
- return fail('--preview-id requires a value');
115
- opts.applyPreviewId = v;
116
- }
117
- else if (a.startsWith('--preview-id=')) {
118
- opts.applyPreviewId = a.slice('--preview-id='.length);
119
- }
120
- else if (a === '--help' || a === '-h') {
121
- opts.help = true;
122
- }
123
- else if (a === '--local-dsh' || a === '--localDsh') {
124
- const v = rest[++i];
125
- if (!v || v.startsWith('-'))
126
- return fail('--local-dsh requires a path value');
127
- opts.localDsh = v;
128
- }
129
- else if (a === '--remote') {
130
- const v = rest[++i];
131
- if (!v || v.startsWith('-'))
132
- return fail('--remote requires a host value');
133
- opts.remote = v;
134
- }
135
- else if (a.startsWith('--remote=')) {
136
- opts.remote = a.slice('--remote='.length);
137
- }
138
- else if (a === '--remote-dsh' || a === '--remoteDsh') {
139
- const v = rest[++i];
140
- if (!v || v.startsWith('-'))
141
- return fail('--remote-dsh requires a path value');
142
- opts.remoteDsh = v;
143
- }
144
- else if (a.startsWith('--remote-dsh=')) {
145
- opts.remoteDsh = a.slice('--remote-dsh='.length);
146
- }
147
- else if (a === '--backup-root' || a === '--backupRoot') {
148
- const v = rest[++i];
149
- if (!v || v.startsWith('-'))
150
- return fail('--backup-root requires a path value');
151
- opts.backupRoot = v;
152
- }
153
- else if (a === '--strategy') {
154
- const v = rest[++i];
155
- if (!v || (v !== 'merge' && v !== 'override'))
156
- return fail('--strategy must be merge or override');
157
- opts.strategy = v;
158
- }
159
- else if (a.startsWith('--strategy=')) {
160
- const v = a.slice('--strategy='.length);
161
- if (v !== 'merge' && v !== 'override')
162
- return fail('--strategy must be merge or override');
163
- opts.strategy = v;
164
- }
165
- else if (a === '--ack-override') {
166
- opts.ackOverride = true;
167
- }
168
- else if (a === '--from') {
169
- const v = rest[++i];
170
- if (!v || v.startsWith('-'))
171
- return fail('--from requires a value (a machine id)');
172
- opts.from = v;
173
- }
174
- else if (a.startsWith('--from=')) {
175
- opts.from = a.slice('--from='.length);
176
- }
177
- else if (a === '--to') {
178
- const v = rest[++i];
179
- if (!v || v.startsWith('-'))
180
- return fail('--to requires a value (a machine id)');
181
- opts.to = v;
182
- }
183
- else if (a.startsWith('--to=')) {
184
- opts.to = a.slice('--to='.length);
185
- }
186
- else if (a === '--side') {
187
- const v = rest[++i];
188
- if (!v || v.startsWith('-'))
189
- return fail('--side requires local or remote');
190
- opts.side = v;
191
- }
192
- else if (a.startsWith('--side=')) {
193
- opts.side = a.slice('--side='.length);
194
- }
195
- else if (a === '--host') {
196
- const v = rest[++i];
197
- // A host, never a flag: `user@host` and bare hostnames are both legal.
198
- if (!v || v.startsWith('--'))
199
- return fail('--host requires a value');
200
- opts.peerHost = v;
201
- }
202
- else if (a.startsWith('--host=')) {
203
- opts.peerHost = a.slice('--host='.length);
204
- }
205
- else if (a === '--clear') {
206
- opts.clearPeer = true;
207
- }
208
- else if (a === '--profile') {
209
- const v = rest[++i];
210
- if (!v || v.startsWith('-'))
211
- return fail('--profile requires a value');
212
- opts.profile = v;
213
- }
214
- else if (a.startsWith('--profile=')) {
215
- opts.profile = a.slice('--profile='.length);
216
- }
217
- else if (a === '--') {
218
- break;
219
- }
220
- else if (a.startsWith('-')) {
221
- return fail(`Unknown option: ${a} (see --help)`);
222
- }
223
- else {
224
- return fail(`Unexpected arg: ${a} (see --help)`);
225
- }
226
- }
227
- if (opts.strategy === 'override' && !opts.ackOverride) {
228
- return fail('--strategy=override is destructive and requires --ack-override');
229
- }
230
- if (opts.mode === 'bidirectional' && opts.strategy === 'override') {
231
- return fail('--bidirectional requires the merge strategy (override is a one-direction destructive mirror)');
232
- }
233
- if (opts.from !== undefined && !isMachineId(opts.from))
234
- return fail('--from must be a machine id (letters, digits, . _ -)');
235
- if (opts.to !== undefined && !isMachineId(opts.to))
236
- return fail('--to must be a machine id (letters, digits, . _ -)');
237
- if (opts.subcommand === 'set-peer-host') {
238
- if (opts.mode)
239
- return fail('set-peer-host takes no --pull/--push/--bidirectional flag');
240
- if (opts.clearPeer === true && opts.peerHost !== undefined)
241
- return fail('set-peer-host takes either --host or --clear, not both');
242
- if (opts.clearPeer !== true && !opts.peerHost)
243
- return fail('set-peer-host requires --host <host> or --clear');
244
- }
245
- if (opts.subcommand === 'tunnel-restore') {
246
- if (opts.mode)
247
- return fail('tunnel-restore takes no --pull/--push/--bidirectional flag');
248
- const side = opts.side ?? 'local';
249
- if (side !== 'local' && side !== 'remote')
250
- return fail('--side must be local or remote');
251
- if (opts.confirm !== true)
252
- return fail('tunnel-restore requires --confirm');
253
- if (side === 'remote' && !opts.profile)
254
- return fail('tunnel-restore --side remote requires --profile <name>');
255
- }
256
- if (opts.hasApplyFlag) {
257
- if (!opts.applyPreviewId)
258
- return fail('--apply requires --preview-id <id> from a previous --dry-run preview');
259
- if (opts.confirm !== true)
260
- return fail('--apply requires --confirm');
261
- }
262
- return opts;
263
- }
264
- async function runBidirectional(svc, opts, out, err) {
265
- const scope = opts.includeSessions ? 'all' : 'memory';
266
- if (opts.hasApplyFlag) {
267
- err(`[sync] apply bidirectional preview ${opts.applyPreviewId} (scope ${scope})`);
268
- let result;
269
- try {
270
- result = await runBidirectionalApply(svc, { previewId: opts.applyPreviewId, confirm: true, scope });
271
- }
272
- catch (e) {
273
- out(JSON.stringify({ ok: false, error: e?.message ?? String(e), code: e?.code, phase: e?.phase }) + '\n');
274
- err(`[err] bidirectional apply failed: ${e?.message ?? String(e)}`);
275
- return 1;
276
- }
277
- out(JSON.stringify({ ok: result.ok, push: result.push, pull: result.pull, verification: result.verification, committed: result.committed, failures: result.failures }) + '\n');
278
- if (!result.ok) {
279
- err(`[err] bidirectional partially failed: ${result.failures.map((f) => f.path ?? f.code).join(',')}`);
280
- return 1;
281
- }
282
- err(`[sync] bidirectional applied: committed ${result.committed.length}, failures ${result.failures.length}`);
283
- return 0;
284
- }
285
- // default: dry-run combined preview (read-only). The pull plan is projected:
286
- // it is recomputed exact after the push lands at apply time.
287
- err(`[sync] preview bidirectional (dry-run, scope ${scope})`);
288
- let combined;
289
- try {
290
- combined = await runBidirectionalPreview(svc, { scope });
291
- }
292
- catch (e) {
293
- out(JSON.stringify({ ok: false, error: e?.message ?? String(e), code: e?.code, phase: e?.phase }) + '\n');
294
- err(`[err] bidirectional preview failed: ${e?.message ?? String(e)}`);
295
- return 1;
296
- }
297
- out(JSON.stringify({
298
- ok: true,
299
- previewId: combined.previewId,
300
- expiresAt: combined.expiresAt,
301
- push: { summary: combined.push.summary, actions: combined.push.actions },
302
- pullProjected: { summary: combined.pullProjected.summary, actions: combined.pullProjected.actions },
303
- note: 'pull plan is projected; recomputed exact at apply time',
304
- }) + '\n');
305
- err(`[sync] bidirectional preview ${combined.previewId}: push merged=${combined.push.summary.merged} copied=${combined.push.summary.copied} / pull merged=${combined.pullProjected.summary.merged} copied=${combined.pullProjected.summary.copied}`);
306
- return 0;
307
- }
308
- /** Resolve a `~/.dsh`-style placeholder to an absolute remote path (read-only preflight). */
309
- async function resolveAbsoluteRemoteDsh(transport, host, remoteDsh) {
310
- if (remoteDsh !== '~/.dsh' && !remoteDsh.startsWith('~/'))
311
- return remoteDsh;
312
- const home = await transport.remoteHome({ host });
313
- return home + remoteDsh.slice(1);
314
- }
315
- /** Default remote machine-id read: agent op over the existing ssh transport (no new binary). */
316
- async function defaultReadRemoteId(host, remoteDsh) {
317
- try {
318
- const transport = new SshRsyncTransport(new NodeProcessRunner());
319
- const root = await resolveAbsoluteRemoteDsh(transport, host, remoteDsh);
320
- return await transport.readMachineId({ host, dshRoot: root });
321
- }
322
- catch {
323
- return null;
324
- }
325
- }
326
- export async function runCli(argv, deps = {}) {
327
- const out = deps.stdout ?? ((s) => process.stdout.write(s));
328
- const err = deps.stderr ?? ((s) => process.stderr.write(s));
329
- const opts = parseArgs(argv, err);
330
- if (!opts)
331
- return 1;
332
- if (opts.help) {
333
- out(printHelp(path.basename(process.argv[1] || 'cli.js')) + '\n');
334
- return 0;
335
- }
336
- if (!opts.mode && !opts.subcommand) {
337
- err('[err] Missing required --pull, --push, --bidirectional, check-machines or tunnel-restore (see --help)');
338
- return 1;
339
- }
340
- const resolvedLocalDsh = opts.localDsh ?? process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh');
341
- let cfg;
342
- try {
343
- cfg = await loadSyncConfig({ dshHome: resolvedLocalDsh });
344
- }
345
- catch {
346
- cfg = { remoteHost: process.env.REMOTE_HOST || DEFAULT_REMOTE_HOST, remoteDshPath: '~/.dsh', strategy: 'merge' };
347
- }
348
- const resolvedRemote = opts.remote ?? cfg.remoteHost;
349
- try {
350
- validateHost(resolvedRemote);
351
- }
352
- catch (e) {
353
- err(`[err] invalid --remote host: ${e?.message ?? String(e)}`);
354
- return 1;
355
- }
356
- const resolvedRemoteDsh = opts.remoteDsh ?? cfg.remoteDshPath;
357
- // Machine identity: resolved before any service/preview/apply work.
358
- const readLocal = deps.identity?.readLocal ?? ((home) => readLocalMachineId(undefined, home));
359
- const readRemote = deps.identity?.readRemote ?? defaultReadRemoteId;
360
- /**
361
- * --from/--to, defaulted from the ids actually read off the two machines
362
- * (`$DSH_HOME/machine-id`); an underivable peer is an error, never a guess.
363
- */
364
- const resolveMachines = (localId, remoteId, o) => {
365
- const from = o.from ?? localId ?? undefined;
366
- if (from === undefined)
367
- return { error: 'cannot read the local machine-id — pass --from <id>' };
368
- const to = o.to ?? peerMachineId(from, localId, remoteId) ?? undefined;
369
- if (to === undefined)
370
- return { error: 'cannot derive --to from the machine ids — pass --to <id>' };
371
- return { from, to };
372
- };
373
- if (opts.subcommand === 'check-machines') {
374
- const mode = opts.mode ?? 'bidirectional';
375
- const localId = await readLocal(resolvedLocalDsh);
376
- const remoteId = await readRemote(resolvedRemote, resolvedRemoteDsh);
377
- const machines = resolveMachines(localId, remoteId, opts);
378
- if ('error' in machines) {
379
- err(`[err] ${machines.error}\n`);
380
- return 1;
381
- }
382
- const { from, to } = machines;
383
- const verdict = checkMachines({ mode, from, to, localId, remoteId });
384
- if (!verdict.ok) {
385
- out(JSON.stringify({ ok: false, code: verdict.code, error: verdict.message, localId, remoteId, from, to }) + '\n');
386
- err(`[err] ${verdict.message}`);
387
- return 1;
388
- }
389
- out(JSON.stringify({ ok: true, mode, localId, remoteId, from, to }) + '\n');
390
- err(`[sync] machines ok: local=${localId ?? 'unknown'} remote=${remoteId ?? 'unknown'} from=${from} to=${to}`);
391
- return 0;
392
- }
393
- if (opts.subcommand === 'tunnel-restore') {
394
- const side = opts.side ?? 'local';
395
- if (side === 'local') {
396
- err(`[sync] tunnel-restore local (profile ${opts.profile ?? 'auto'})`);
397
- const r = await restoreLocalTunnel({ dshHome: resolvedLocalDsh, profileName: opts.profile });
398
- out(JSON.stringify({ ok: r.ok, side, ...(r.ok ? { profile: r.profile } : { code: r.code }) }) + '\n');
399
- if (!r.ok) {
400
- err('[err] tunnel-restore local: no profile found');
401
- return 1;
402
- }
403
- err(`[sync] tunnel restored from profile ${r.profile}`);
404
- return 0;
405
- }
406
- // remote: explicit profile required (validated in parseArgs); caller ensures the agent.
407
- err(`[sync] tunnel-restore remote (profile ${opts.profile})`);
408
- try {
409
- const runner = new NodeProcessRunner();
410
- const transport = new SshRsyncTransport(runner);
411
- await transport.ensureAgent({ host: resolvedRemote, dshRoot: await resolveAbsoluteRemoteDsh(transport, resolvedRemote, resolvedRemoteDsh) });
412
- const r = await restoreRemoteTunnel(transport, { host: resolvedRemote, dshRoot: await resolveAbsoluteRemoteDsh(transport, resolvedRemote, resolvedRemoteDsh) }, opts.profile);
413
- if (!r.ok) {
414
- out(JSON.stringify({ ok: false, side, code: r.code }) + '\n');
415
- err(`[err] tunnel-restore remote: ${r.code}`);
416
- return 1;
417
- }
418
- out(JSON.stringify({ ok: true, side, profile: r.profile, changed: r.changed, sha256: r.sha256 }) + '\n');
419
- err(`[sync] tunnel restored on remote from profile ${r.profile} (changed=${r.changed})`);
420
- return 0;
421
- }
422
- catch (e) {
423
- out(JSON.stringify({ ok: false, side, error: e?.message ?? String(e), code: e?.code }) + '\n');
424
- err(`[err] tunnel-restore remote failed: ${e?.message ?? String(e)}`);
425
- return 1;
426
- }
427
- }
428
- if (opts.subcommand === 'set-peer-host') {
429
- try {
430
- if (opts.clearPeer === true) {
431
- const removed = clearPeerHost(resolvedLocalDsh);
432
- out(JSON.stringify({ ok: true, action: 'clear', removed, dshHome: resolvedLocalDsh }) + '\n');
433
- err(`[sync] machine-local peer cleared (${removed ? 'removed' : 'nothing to remove'})`);
434
- }
435
- else {
436
- const host = writePeerHost(resolvedLocalDsh, opts.peerHost);
437
- out(JSON.stringify({ ok: true, action: 'set', remoteHost: host, dshHome: resolvedLocalDsh }) + '\n');
438
- err(`[sync] this machine's peer recorded: ${host}`);
439
- }
440
- return 0;
441
- }
442
- catch (e) {
443
- out(JSON.stringify({ ok: false, error: e?.message ?? String(e) }) + '\n');
444
- err(`[err] set-peer-host failed: ${e?.message ?? String(e)}`);
445
- return 1;
446
- }
447
- }
448
- // Mode flows: enforce identity before constructing the service.
449
- // (Subcommands return above, so a mode is always present here.)
450
- if (!opts.mode) {
451
- err('[err] Missing required --pull, --push or --bidirectional (see --help)');
452
- return 1;
453
- }
454
- {
455
- const mode = opts.mode;
456
- const localId = await readLocal(resolvedLocalDsh);
457
- const remoteId = await readRemote(resolvedRemote, resolvedRemoteDsh);
458
- const machines = resolveMachines(localId, remoteId, opts);
459
- if ('error' in machines) {
460
- err(`[err] ${machines.error}\n`);
461
- return 1;
462
- }
463
- const { from, to } = machines;
464
- const verdict = checkMachines({ mode, from, to, localId, remoteId });
465
- if (!verdict.ok) {
466
- err(`[err] ${verdict.message}`);
467
- return 1;
468
- }
469
- }
470
- let svc;
471
- if (deps.makeService) {
472
- svc = await deps.makeService({ ...cfg, remoteHost: resolvedRemote, remoteDshPath: resolvedRemoteDsh, strategy: opts.strategy });
473
- }
474
- else {
475
- svc = new SyncService({ localDsh: resolvedLocalDsh, remote: resolvedRemote, remoteDsh: resolvedRemoteDsh });
476
- }
477
- if (opts.mode === 'bidirectional') {
478
- return runBidirectional(svc, opts, out, err);
479
- }
480
- const direction = opts.mode;
481
- if (opts.hasApplyFlag) {
482
- err(`[sync] apply ${direction} preview ${opts.applyPreviewId} (strategy ${opts.strategy})`);
483
- let result;
484
- try {
485
- result = await svc.apply({ previewId: opts.applyPreviewId, direction, confirm: true });
486
- }
487
- catch (e) {
488
- out(JSON.stringify({ ok: false, error: e?.message ?? String(e), code: e?.code, phase: e?.phase }) + '\n');
489
- err(`[err] apply failed: ${e?.message ?? String(e)}`);
490
- return 1;
491
- }
492
- out(JSON.stringify({ ok: result.ok, revision: result.revision, summary: result.summary, committed: result.committed, failures: result.failures }) + '\n');
493
- if (!result.ok) {
494
- err(`[err] apply partially failed: ${result.failures.map((f) => f.path).join(',')}`);
495
- return 1;
496
- }
497
- err(`[sync] applied: committed ${result.committed.length}, failures ${result.failures.length}`);
498
- return 0;
499
- }
500
- // default: dry-run preview (read-only)
501
- err(`[sync] preview ${direction} (dry-run, strategy ${opts.strategy}) localDsh=${resolvedLocalDsh} remote=${resolvedRemote} remoteDsh=${resolvedRemoteDsh}`);
502
- let preview;
503
- try {
504
- preview = await svc.preview({ direction });
505
- }
506
- catch (e) {
507
- out(JSON.stringify({ ok: false, error: e?.message ?? String(e), code: e?.code, phase: e?.phase }) + '\n');
508
- err(`[err] preview failed: ${e?.message ?? String(e)}`);
509
- return 1;
510
- }
511
- out(JSON.stringify({ ok: true, previewId: preview.previewId, revision: preview.revision, expiresAt: preview.expiresAt, summary: preview.summary, actions: preview.actions }) + '\n');
512
- err(`[sync] preview ${preview.previewId}: copied=${preview.summary.copied} merged=${preview.summary.merged} skipped=${preview.summary.skipped} conflicts=${preview.summary.conflicts} added=${preview.summary.added}`);
513
- return 0;
514
- }
515
- async function main() {
516
- const code = await runCli(process.argv.slice(2));
517
- process.exitCode = code;
518
- }
519
- const isMain = import.meta.url === `file://${process.argv[1]}` ||
520
- process.argv[1]?.endsWith('/cli.js') ||
521
- process.argv[1]?.endsWith('/cli.mjs') ||
522
- process.argv[1]?.endsWith('lib/cli.js');
523
- if (isMain) {
524
- main().catch((e) => {
525
- console.error('[err] unhandled:', e?.message || String(e));
526
- process.exitCode = 1;
527
- });
528
- }
@@ -1,59 +0,0 @@
1
- import type { SyncDirection, SyncRequest } from './sync-types.js';
2
- export interface SyncConfig {
3
- remoteHost: string;
4
- remoteDshPath: string;
5
- strategy: string;
6
- }
7
- /** The built-in SSH target, reached only when nothing was ever configured. */
8
- export declare const DEFAULT_REMOTE_HOST = "kai@ssh.ddtcorex.com";
9
- /**
10
- * Effective peer host from the four sources, highest first:
11
- *
12
- * 1. This machine's own `peer.json` — machine-local truth (see peer-host.ts).
13
- * 2. The shared settings store `domains.sync.remoteHost` — UI-editable, but it
14
- * travels between machines, so on the mirrored machine it can name that
15
- * machine instead of its peer.
16
- * 3. `REMOTE_HOST` / `REMOTE` env.
17
- * 4. {@link DEFAULT_REMOTE_HOST}.
18
- *
19
- * The machine-local file deliberately outranks the shared store: a machine that
20
- * inherited the other machine's address must be able to state its own peer
21
- * without editing a file both machines share. Env stays below the store because
22
- * callers that need to force a target pass it explicitly (`--remote`), which
23
- * wins over this whole list.
24
- */
25
- export declare function resolveRemoteHost(sources: {
26
- env?: string;
27
- machineLocal?: string | null;
28
- stored?: string;
29
- fallback?: string;
30
- }): string;
31
- /**
32
- * Load sync config via @ddtcorex/dsh-maestro-config-lib load() -> domains.sync
33
- * Peer host precedence: see {@link resolveRemoteHost}.
34
- * remoteDshPath = sync.remoteDshPath || REMOTE_DSH_PATH env || '~/.dsh' (unresolved placeholder)
35
- * strategy = 'merge'
36
- *
37
- * NOTE: remoteDshPath may be '~/.dsh' as stored placeholder. It is NOT a validated
38
- * absolute path. Caller must validate via `validateRemoteTarget` / `buildSyncRequest`
39
- * before constructing a SyncRequest. The absolute remote home is resolved by the
40
- * transport preflight (ssh remoteHome), not by shell ~ expansion.
41
- *
42
- * @param opts.dshHome DSH home holding this machine's peer file; the caller's
43
- * own resolved home wins over the ambient default.
44
- */
45
- export declare function loadSyncConfig(opts?: {
46
- dshHome?: string;
47
- }): Promise<SyncConfig>;
48
- /**
49
- * Build a validated SyncRequest. Remote is validated via validateRemoteTarget;
50
- * localRoot is expected to be an absolute local path (lightly validated as absolute).
51
- * Throws on invalid host/path.
52
- */
53
- export declare function buildSyncRequest(params: {
54
- direction: SyncDirection;
55
- dryRun: boolean;
56
- localRoot: string;
57
- remoteHost: string;
58
- remoteDshPath: string;
59
- }): SyncRequest;