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