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