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