@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
|
@@ -1,132 +0,0 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
2
|
-
import * as path from 'node:path';
|
|
3
|
-
import { normalizeEligiblePath } from './validation.js';
|
|
4
|
-
import type { FileSnapshot } from './sync-types.js';
|
|
5
|
-
|
|
6
|
-
export function hashBuffer(buf: Buffer): string {
|
|
7
|
-
return createHash('sha256').update(buf).digest('hex');
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
export function kindForPath(p: string): FileSnapshot['kind'] {
|
|
11
|
-
const normalized = p; // caller should have validated; we still dispatch by suffix
|
|
12
|
-
if (normalized.endsWith('.zstd')) return 'session';
|
|
13
|
-
if (normalized.endsWith('.jsonl')) return 'jsonl';
|
|
14
|
-
return 'memory';
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export function snapshotFile(validatedPath: string, content: Buffer): FileSnapshot {
|
|
18
|
-
const normalized = normalizeEligiblePath(validatedPath);
|
|
19
|
-
const sha256 = hashBuffer(content);
|
|
20
|
-
const kind = kindForPath(normalized);
|
|
21
|
-
return { path: normalized, sha256, size: content.length, kind };
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* Collect snapshots for all eligible files under root using the provided fs.
|
|
26
|
-
* - Walks recursively via fs.readdirSync/statSync/readFileSync when available.
|
|
27
|
-
* - Validates each discovered relative path via normalizeEligiblePath.
|
|
28
|
-
* - Hashes file bytes with SHA-256 and records kind.
|
|
29
|
-
* Returns sorted snapshots by path for determinism.
|
|
30
|
-
*/
|
|
31
|
-
export function collectSnapshots(root: string, fs: any): FileSnapshot[] {
|
|
32
|
-
const result: FileSnapshot[] = [];
|
|
33
|
-
if (!root || typeof root !== 'string') return result;
|
|
34
|
-
const fsMod = fs ?? {};
|
|
35
|
-
// Check root exists
|
|
36
|
-
try {
|
|
37
|
-
if (fsMod.existsSync && !fsMod.existsSync(root)) return [];
|
|
38
|
-
} catch {
|
|
39
|
-
return [];
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
const walk = (dir: string, base: string) => {
|
|
43
|
-
try {
|
|
44
|
-
if (typeof fsMod.readdirSync !== 'function') return;
|
|
45
|
-
const raw = fsMod.readdirSync(dir, { withFileTypes: true } as any);
|
|
46
|
-
if (!raw || raw.length === 0) return;
|
|
47
|
-
// handle string[] mode (no withFileTypes)
|
|
48
|
-
if (typeof raw[0] === 'string') {
|
|
49
|
-
for (const name of raw as unknown as string[]) {
|
|
50
|
-
const full = path.join(dir, name);
|
|
51
|
-
let st: any = null;
|
|
52
|
-
try {
|
|
53
|
-
st = fsMod.statSync ? fsMod.statSync(full) : null;
|
|
54
|
-
} catch {
|
|
55
|
-
continue;
|
|
56
|
-
}
|
|
57
|
-
const isDir = st && typeof st.isDirectory === 'function' ? st.isDirectory() : false;
|
|
58
|
-
if (isDir) walk(full, path.join(base, name));
|
|
59
|
-
else {
|
|
60
|
-
const relPosix = path.join(base, name).split(path.sep).join('/');
|
|
61
|
-
try {
|
|
62
|
-
normalizeEligiblePath(relPosix);
|
|
63
|
-
} catch {
|
|
64
|
-
continue;
|
|
65
|
-
}
|
|
66
|
-
try {
|
|
67
|
-
let buf: Buffer;
|
|
68
|
-
if (typeof fsMod.readFileSync === 'function') {
|
|
69
|
-
const data = fsMod.readFileSync(full);
|
|
70
|
-
buf = Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf-8');
|
|
71
|
-
} else {
|
|
72
|
-
continue;
|
|
73
|
-
}
|
|
74
|
-
result.push(snapshotFile(relPosix, buf));
|
|
75
|
-
} catch {
|
|
76
|
-
// skip unreadable
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
return;
|
|
81
|
-
}
|
|
82
|
-
for (const ent of raw as any[]) {
|
|
83
|
-
const name = ent.name ?? String(ent);
|
|
84
|
-
const full = path.join(dir, name);
|
|
85
|
-
const isDir = typeof ent.isDirectory === 'function' ? ent.isDirectory() : false;
|
|
86
|
-
if (isDir) {
|
|
87
|
-
walk(full, path.join(base, name));
|
|
88
|
-
} else {
|
|
89
|
-
const relPosix = path.join(base, name).split(path.sep).join('/');
|
|
90
|
-
try {
|
|
91
|
-
normalizeEligiblePath(relPosix);
|
|
92
|
-
} catch {
|
|
93
|
-
continue;
|
|
94
|
-
}
|
|
95
|
-
try {
|
|
96
|
-
let buf: Buffer;
|
|
97
|
-
if (typeof fsMod.readFileSync === 'function') {
|
|
98
|
-
const data = fsMod.readFileSync(full);
|
|
99
|
-
buf = Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf-8');
|
|
100
|
-
} else continue;
|
|
101
|
-
result.push(snapshotFile(relPosix, buf));
|
|
102
|
-
} catch {
|
|
103
|
-
// skip
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
} catch {
|
|
108
|
-
// walk errors are ignored
|
|
109
|
-
}
|
|
110
|
-
};
|
|
111
|
-
|
|
112
|
-
walk(root, '');
|
|
113
|
-
// Deterministic sort
|
|
114
|
-
result.sort((a, b) => a.path.localeCompare(b.path));
|
|
115
|
-
return result;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
/**
|
|
119
|
-
* Snapshot from an in-memory map of path -> Buffer (useful for testing staged remote).
|
|
120
|
-
*/
|
|
121
|
-
export function snapshotFromMap(contents: Map<string, Buffer>): FileSnapshot[] {
|
|
122
|
-
const out: FileSnapshot[] = [];
|
|
123
|
-
for (const [p, buf] of contents.entries()) {
|
|
124
|
-
try {
|
|
125
|
-
out.push(snapshotFile(p, buf));
|
|
126
|
-
} catch {
|
|
127
|
-
continue;
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
out.sort((a, b) => a.path.localeCompare(b.path));
|
|
131
|
-
return out;
|
|
132
|
-
}
|
package/src/host/sync/ssh-mux.ts
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
// src/host/ssh-mux.ts — per-operation SSH ControlMaster multiplexing.
|
|
2
|
-
//
|
|
3
|
-
// One backgrounded master (`ssh -S <socket> -o ControlMaster=yes -f -N`) owns
|
|
4
|
-
// the connection; every subsequent spawn in the operation passes `-S <socket>`
|
|
5
|
-
// (ssh slaves) or `rsync -e "ssh -S <socket>"` (single validated argv) so a
|
|
6
|
-
// multi-spawn flow pays one handshake. The socket lives in a private 0700 dir
|
|
7
|
-
// and is torn down with `-O exit`; a dead master degrades to a fresh handshake.
|
|
8
|
-
import * as fs from 'node:fs';
|
|
9
|
-
import * as path from 'node:path';
|
|
10
|
-
import type { ProcessRunner } from './process-runner.js';
|
|
11
|
-
|
|
12
|
-
export interface SshMux {
|
|
13
|
-
socketPath: string;
|
|
14
|
-
sshArgs: string[];
|
|
15
|
-
rsyncRsh: string;
|
|
16
|
-
dispose(): Promise<void>;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
function sanitizeHost(host: string): string {
|
|
20
|
-
return host.replace(/[^A-Za-z0-9._-]/g, '_');
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export async function openSshMux(opts: { host: string; baseDir: string; runner: ProcessRunner }): Promise<SshMux> {
|
|
24
|
-
const dir = path.join(opts.baseDir, `${sanitizeHost(opts.host)}-${Math.random().toString(16).slice(2, 6)}`);
|
|
25
|
-
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
26
|
-
const socketPath = path.join(dir, 'ssh.sock');
|
|
27
|
-
const connectOpts = ['-o', 'ConnectTimeout=5', '-o', 'BatchMode=yes'];
|
|
28
|
-
// -f backgrounds the master after auth and the process exits 0, so runner.run
|
|
29
|
-
// does not hang on a connection that is meant to stay alive.
|
|
30
|
-
const masterArgs = ['-S', socketPath, '-o', 'ControlMaster=yes', '-o', 'ControlPersist=60', ...connectOpts, opts.host, '-f', '-N'];
|
|
31
|
-
const res = await opts.runner.run('ssh', masterArgs, { timeoutMs: 8000 });
|
|
32
|
-
if (res.exitCode !== 0) {
|
|
33
|
-
try {
|
|
34
|
-
fs.rmSync(dir, { recursive: true, force: true });
|
|
35
|
-
} catch {}
|
|
36
|
-
throw Object.assign(new Error(`ssh mux master failed: ${res.stderr.toString()}`), {
|
|
37
|
-
phase: 'snapshot',
|
|
38
|
-
code: 'MUX_FAILED',
|
|
39
|
-
detail: res.stderr.toString() || `exit ${res.exitCode}`,
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
|
-
return {
|
|
43
|
-
socketPath,
|
|
44
|
-
sshArgs: ['-S', socketPath],
|
|
45
|
-
rsyncRsh: `ssh -S ${socketPath}`,
|
|
46
|
-
dispose: async () => {
|
|
47
|
-
try {
|
|
48
|
-
await opts.runner.run('ssh', ['-S', socketPath, '-O', 'exit', opts.host], { timeoutMs: 5000 });
|
|
49
|
-
} catch {}
|
|
50
|
-
try {
|
|
51
|
-
fs.rmSync(dir, { recursive: true, force: true });
|
|
52
|
-
} catch {}
|
|
53
|
-
},
|
|
54
|
-
};
|
|
55
|
-
}
|
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* sync/store-root.ts — where the memory store lives, resolved the same way the plugin
|
|
3
|
-
* resolves it.
|
|
4
|
-
*
|
|
5
|
-
* Core cannot import the plugin (separate package, separate release), so this is a
|
|
6
|
-
* deliberate second implementation. `tests/sync/store-root-parity.spec.ts` runs the
|
|
7
|
-
* shared fixture against it, and the plugin runs the same fixture against its own
|
|
8
|
-
* copy, so a rule change on one side fails on that side instead of drifting silently.
|
|
9
|
-
*
|
|
10
|
-
* The rules, in order:
|
|
11
|
-
* 1. `memoryDir` (explicit config) wins.
|
|
12
|
-
* 2. `MAESTRO_MEMORY_DIR` wins next.
|
|
13
|
-
* 3. A `DSH_HOME` that realpaths somewhere other than `<home>/.dsh` is an isolated run
|
|
14
|
-
* (dry-boot, test, second profile): the store stays inside it.
|
|
15
|
-
* 4. Otherwise the neutral root, `<home>/.maestro-memory`.
|
|
16
|
-
*/
|
|
17
|
-
|
|
18
|
-
import { realpathSync } from 'node:fs';
|
|
19
|
-
import { homedir } from 'node:os';
|
|
20
|
-
import { join } from 'node:path';
|
|
21
|
-
|
|
22
|
-
export type StoreRootMode = 'configured' | 'env' | 'isolated' | 'default';
|
|
23
|
-
|
|
24
|
-
export interface StoreRoot {
|
|
25
|
-
root: string;
|
|
26
|
-
mode: StoreRootMode;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function realpathOr(value: string): string {
|
|
30
|
-
try {
|
|
31
|
-
return realpathSync.native(value);
|
|
32
|
-
} catch {
|
|
33
|
-
return value;
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export function resolveStoreRoot(
|
|
38
|
-
opts: { memoryDir?: string | null; env?: NodeJS.ProcessEnv; home?: string } = {},
|
|
39
|
-
): StoreRoot {
|
|
40
|
-
if (opts.memoryDir) return { root: opts.memoryDir, mode: 'configured' };
|
|
41
|
-
const env = opts.env ?? process.env;
|
|
42
|
-
const envDir = typeof env.MAESTRO_MEMORY_DIR === 'string' ? env.MAESTRO_MEMORY_DIR.trim() : '';
|
|
43
|
-
if (envDir) return { root: envDir, mode: 'env' };
|
|
44
|
-
|
|
45
|
-
const home = realpathOr(opts.home ?? homedir());
|
|
46
|
-
const dshDefault = join(home, '.dsh');
|
|
47
|
-
const rawDsh = typeof env.DSH_HOME === 'string' && env.DSH_HOME.trim() ? env.DSH_HOME.trim() : '';
|
|
48
|
-
if (rawDsh && realpathOr(rawDsh) !== dshDefault) {
|
|
49
|
-
return { root: join(rawDsh, 'maestro-memory'), mode: 'isolated' };
|
|
50
|
-
}
|
|
51
|
-
return { root: join(home, '.maestro-memory'), mode: 'default' };
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/** Map a wire path onto the local filesystem. Wire paths never change; roots do. */
|
|
55
|
-
export function localPathForWirePath(
|
|
56
|
-
wirePath: string,
|
|
57
|
-
roots: { storeRoot: string; localDsh: string },
|
|
58
|
-
): string {
|
|
59
|
-
if (wirePath.startsWith('maestro-memory/')) {
|
|
60
|
-
return join(roots.storeRoot, wirePath.slice('maestro-memory/'.length));
|
|
61
|
-
}
|
|
62
|
-
return join(roots.localDsh, wirePath);
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* Group wire paths by the local root they resolve to, so a caller that hashes or stats
|
|
67
|
-
* many paths at once hashes each group against its own root instead of assuming the
|
|
68
|
-
* DSH home. After the store move, `maestro-memory/...` and `sessions/...` live in two
|
|
69
|
-
* different trees.
|
|
70
|
-
*/
|
|
71
|
-
export function partitionByWireRoot(
|
|
72
|
-
wirePaths: string[],
|
|
73
|
-
roots: { storeRoot: string; localDsh: string },
|
|
74
|
-
): Array<{ root: string; paths: string[] }> {
|
|
75
|
-
const groups = new Map<string, string[]>();
|
|
76
|
-
for (const wire of wirePaths) {
|
|
77
|
-
const root = wire.startsWith('maestro-memory/') ? roots.storeRoot : roots.localDsh;
|
|
78
|
-
const bucket = groups.get(root);
|
|
79
|
-
if (bucket) bucket.push(wire);
|
|
80
|
-
else groups.set(root, [wire]);
|
|
81
|
-
}
|
|
82
|
-
return [...groups.entries()].map(([root, paths]) => ({ root, paths }));
|
|
83
|
-
}
|
|
@@ -1,366 +0,0 @@
|
|
|
1
|
-
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
-
import * as path from 'node:path';
|
|
3
|
-
import * as fs from 'node:fs';
|
|
4
|
-
import type { FileSnapshot, PlannedAction, SyncPlan, SyncPreview, SyncSummary, SyncDirection, SessionCounts } from './sync-types.js';
|
|
5
|
-
import { mergeDelimited } from './merge.js';
|
|
6
|
-
import { isSameSession, mergeSessionBuffers } from './session-plan.js';
|
|
7
|
-
|
|
8
|
-
export const PREVIEW_TTL_MS = 60_000;
|
|
9
|
-
export const MAX_PREVIEWS = 50;
|
|
10
|
-
|
|
11
|
-
const previews = new Map<string, SyncPreview>();
|
|
12
|
-
const previewDirections = new Map<string, SyncDirection>();
|
|
13
|
-
|
|
14
|
-
function previewFile(id: string, dir: string): string {
|
|
15
|
-
return path.join(dir, `${id}.json`);
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/** Read a persisted preview record (null when missing/corrupt). */
|
|
19
|
-
function readPersisted(id: string, dir: string): { preview: SyncPreview; direction?: SyncDirection } | null {
|
|
20
|
-
try {
|
|
21
|
-
const parsed = JSON.parse(fs.readFileSync(previewFile(id, dir), 'utf-8')) as { preview?: SyncPreview; direction?: SyncDirection };
|
|
22
|
-
if (!parsed || typeof parsed !== 'object' || typeof parsed.preview?.previewId !== 'string') return null;
|
|
23
|
-
return { preview: parsed.preview, direction: parsed.direction };
|
|
24
|
-
} catch {
|
|
25
|
-
return null;
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function pruneExpired(): void {
|
|
30
|
-
const now = Date.now();
|
|
31
|
-
for (const [id, p] of previews.entries()) {
|
|
32
|
-
if (new Date(p.expiresAt).getTime() <= now) {
|
|
33
|
-
previews.delete(id);
|
|
34
|
-
previewDirections.delete(id);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
if (previews.size > MAX_PREVIEWS) {
|
|
38
|
-
const entries = [...previews.entries()].sort((a, b) => new Date(a[1].expiresAt).getTime() - new Date(b[1].expiresAt).getTime());
|
|
39
|
-
const toDelete = previews.size - MAX_PREVIEWS;
|
|
40
|
-
for (let i = 0; i < toDelete; i++) {
|
|
41
|
-
const delId = entries[i]![0];
|
|
42
|
-
previews.delete(delId);
|
|
43
|
-
previewDirections.delete(delId);
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* Persist a preview to disk so a later process (a separate CLI apply) can
|
|
50
|
-
* consume it. The file mirrors the in-memory record; the TTL is enforced on
|
|
51
|
-
* read. Sidecar only — a plain operational folder under DSH_HOME, never part
|
|
52
|
-
* of the eligible sync data.
|
|
53
|
-
*/
|
|
54
|
-
export function persistPreview(preview: SyncPreview, direction?: SyncDirection, dir?: string): string {
|
|
55
|
-
if (!dir) return '';
|
|
56
|
-
try {
|
|
57
|
-
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
58
|
-
const now = Date.now();
|
|
59
|
-
let files: string[] = [];
|
|
60
|
-
try {
|
|
61
|
-
files = fs.readdirSync(dir).filter((f) => f.endsWith('.json'));
|
|
62
|
-
} catch {
|
|
63
|
-
files = [];
|
|
64
|
-
}
|
|
65
|
-
// purge expired records, then cap at MAX_PREVIEWS (oldest first)
|
|
66
|
-
const keep: string[] = [];
|
|
67
|
-
for (const f of files) {
|
|
68
|
-
if (f === `${preview.previewId}.json`) continue;
|
|
69
|
-
const record = readPersisted(f.slice(0, -5), dir);
|
|
70
|
-
if (record && new Date(record.preview.expiresAt).getTime() > now) keep.push(f);
|
|
71
|
-
else {
|
|
72
|
-
try {
|
|
73
|
-
fs.unlinkSync(path.join(dir, f));
|
|
74
|
-
} catch {}
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
keep.sort();
|
|
78
|
-
while (keep.length >= MAX_PREVIEWS) {
|
|
79
|
-
const old = keep.shift()!;
|
|
80
|
-
try {
|
|
81
|
-
fs.unlinkSync(path.join(dir, old));
|
|
82
|
-
} catch {}
|
|
83
|
-
}
|
|
84
|
-
const target = previewFile(preview.previewId, dir);
|
|
85
|
-
const tmp = target + `.tmp.${randomBytes(4).toString('hex')}`;
|
|
86
|
-
fs.writeFileSync(tmp, JSON.stringify({ preview, direction }), 'utf-8');
|
|
87
|
-
fs.renameSync(tmp, target);
|
|
88
|
-
try {
|
|
89
|
-
fs.chmodSync(target, 0o600);
|
|
90
|
-
} catch {}
|
|
91
|
-
} catch {
|
|
92
|
-
// persistence is best-effort; the in-memory record still works in-process
|
|
93
|
-
}
|
|
94
|
-
return previewFile(preview.previewId, dir);
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/** Delete every persisted preview file under dir (cleanup helper). */
|
|
98
|
-
export function clearPreviewStore(dir: string): void {
|
|
99
|
-
if (!dir) return;
|
|
100
|
-
try {
|
|
101
|
-
for (const f of fs.readdirSync(dir)) {
|
|
102
|
-
if (f.endsWith('.json')) {
|
|
103
|
-
try {
|
|
104
|
-
fs.unlinkSync(path.join(dir, f));
|
|
105
|
-
} catch {}
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
} catch {}
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
export function storePreview(preview: SyncPreview, direction?: SyncDirection, dir?: string): void {
|
|
112
|
-
pruneExpired();
|
|
113
|
-
if (previews.size >= MAX_PREVIEWS) {
|
|
114
|
-
let oldestId: string | null = null;
|
|
115
|
-
let oldestTime = Infinity;
|
|
116
|
-
for (const [id, p] of previews.entries()) {
|
|
117
|
-
const t = new Date(p.expiresAt).getTime();
|
|
118
|
-
if (t < oldestTime) {
|
|
119
|
-
oldestTime = t;
|
|
120
|
-
oldestId = id;
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
if (oldestId) {
|
|
124
|
-
previews.delete(oldestId);
|
|
125
|
-
previewDirections.delete(oldestId);
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
previews.set(preview.previewId, preview);
|
|
129
|
-
if (direction) previewDirections.set(preview.previewId, direction);
|
|
130
|
-
if (dir) persistPreview(preview, direction, dir);
|
|
131
|
-
const ttl = Math.max(0, new Date(preview.expiresAt).getTime() - Date.now());
|
|
132
|
-
setTimeout(() => {
|
|
133
|
-
previews.delete(preview.previewId);
|
|
134
|
-
previewDirections.delete(preview.previewId);
|
|
135
|
-
}, ttl).unref?.();
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
export function getPreview(id: string, dir?: string): SyncPreview | undefined {
|
|
139
|
-
const cached = previews.get(id);
|
|
140
|
-
if (cached) {
|
|
141
|
-
if (new Date(cached.expiresAt).getTime() <= Date.now()) {
|
|
142
|
-
previews.delete(id);
|
|
143
|
-
previewDirections.delete(id);
|
|
144
|
-
return undefined;
|
|
145
|
-
}
|
|
146
|
-
return cached;
|
|
147
|
-
}
|
|
148
|
-
if (!dir) return undefined;
|
|
149
|
-
const record = readPersisted(id, dir);
|
|
150
|
-
if (!record) return undefined;
|
|
151
|
-
const p = record.preview;
|
|
152
|
-
if (new Date(p.expiresAt).getTime() <= Date.now()) {
|
|
153
|
-
try {
|
|
154
|
-
fs.unlinkSync(previewFile(id, dir));
|
|
155
|
-
} catch {}
|
|
156
|
-
return undefined;
|
|
157
|
-
}
|
|
158
|
-
// hydrate into memory for single-process idempotence
|
|
159
|
-
previews.set(p.previewId, p);
|
|
160
|
-
if (record.direction) previewDirections.set(p.previewId, record.direction);
|
|
161
|
-
return p;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
export function getPreviewDirection(id: string): SyncDirection | undefined {
|
|
165
|
-
return previewDirections.get(id);
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
export function deletePreview(id: string, dir?: string): void {
|
|
169
|
-
previews.delete(id);
|
|
170
|
-
previewDirections.delete(id);
|
|
171
|
-
if (dir) {
|
|
172
|
-
try {
|
|
173
|
-
fs.unlinkSync(previewFile(id, dir));
|
|
174
|
-
} catch {}
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
export function clearPreviews(): void {
|
|
179
|
-
previews.clear();
|
|
180
|
-
previewDirections.clear();
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
export function revisionFrom(snapshots: FileSnapshot[], direction: SyncDirection): string {
|
|
184
|
-
const h = createHash('sha256');
|
|
185
|
-
h.update(direction);
|
|
186
|
-
const sorted = [...snapshots].sort((a, b) => a.path.localeCompare(b.path));
|
|
187
|
-
for (const s of sorted) {
|
|
188
|
-
h.update(s.path + ':' + s.sha256 + ':' + String(s.size) + ':' + s.kind);
|
|
189
|
-
}
|
|
190
|
-
return h.digest('hex').slice(0, 16);
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
function unionJsonlAdded(localBuf: Buffer, remoteBuf: Buffer): number {
|
|
194
|
-
const localLines = localBuf.toString('utf-8').split('\n').filter((l) => l.length > 0);
|
|
195
|
-
const remoteLines = remoteBuf.toString('utf-8').split('\n').filter((l) => l.length > 0);
|
|
196
|
-
const seen = new Set(localLines);
|
|
197
|
-
let added = 0;
|
|
198
|
-
for (const line of remoteLines) {
|
|
199
|
-
if (!seen.has(line)) {
|
|
200
|
-
seen.add(line);
|
|
201
|
-
added++;
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
return added;
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
export async function buildPlan(
|
|
208
|
-
localSnapshots: FileSnapshot[],
|
|
209
|
-
remoteSnapshots: FileSnapshot[],
|
|
210
|
-
direction: SyncDirection,
|
|
211
|
-
localContents: Map<string, Buffer>,
|
|
212
|
-
remoteContents: Map<string, Buffer>,
|
|
213
|
-
opts: { countOnlySessions?: boolean } = {},
|
|
214
|
-
): Promise<SyncPlan> {
|
|
215
|
-
const localMap = new Map(localSnapshots.map((s) => [s.path, s]));
|
|
216
|
-
const remoteMap = new Map(remoteSnapshots.map((s) => [s.path, s]));
|
|
217
|
-
const allPaths = new Set<string>([...localMap.keys(), ...remoteMap.keys()]);
|
|
218
|
-
|
|
219
|
-
const actions: PlannedAction[] = [];
|
|
220
|
-
let copied = 0;
|
|
221
|
-
let merged = 0;
|
|
222
|
-
let skipped = 0;
|
|
223
|
-
let conflicts = 0;
|
|
224
|
-
let added = 0;
|
|
225
|
-
|
|
226
|
-
// Count-only sessions: preview reports added/updated/deleted/identical from
|
|
227
|
-
// path+checksum without staging content. These files never produce action
|
|
228
|
-
// rows — the UI shows the counts instead of per-file rows. Apply is untouched:
|
|
229
|
-
// it re-inventories with full content and builds a real merge plan.
|
|
230
|
-
let sessionCounts: SessionCounts = { added: 0, updated: 0, deleted: 0, identical: 0 };
|
|
231
|
-
const isSession = (p: string) => p.endsWith('.zstd');
|
|
232
|
-
|
|
233
|
-
const sortedPaths = [...allPaths].sort((a, b) => a.localeCompare(b));
|
|
234
|
-
|
|
235
|
-
for (const p of sortedPaths) {
|
|
236
|
-
const ls = localMap.get(p);
|
|
237
|
-
const rs = remoteMap.get(p);
|
|
238
|
-
const target: 'local' | 'remote' = direction === 'pull' ? 'local' : 'remote';
|
|
239
|
-
|
|
240
|
-
if (opts.countOnlySessions && isSession(p)) {
|
|
241
|
-
if (!ls && rs) {
|
|
242
|
-
if (direction === 'pull') sessionCounts.added++;
|
|
243
|
-
else sessionCounts.deleted++;
|
|
244
|
-
} else if (ls && !rs) {
|
|
245
|
-
if (direction === 'pull') sessionCounts.deleted++;
|
|
246
|
-
else sessionCounts.added++;
|
|
247
|
-
} else if (ls && rs) {
|
|
248
|
-
if (ls.sha256 === rs.sha256) sessionCounts.identical++;
|
|
249
|
-
else sessionCounts.updated++;
|
|
250
|
-
}
|
|
251
|
-
continue;
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
if (ls && !rs) {
|
|
255
|
-
if (direction === 'push') {
|
|
256
|
-
actions.push({ path: p, action: 'copy', target: 'remote', added: 0, reason: 'local only', expectedTargetSha256: undefined });
|
|
257
|
-
copied++;
|
|
258
|
-
} else {
|
|
259
|
-
actions.push({ path: p, action: 'skip', target: 'local', added: 0, reason: 'local only, pull skips' });
|
|
260
|
-
skipped++;
|
|
261
|
-
}
|
|
262
|
-
continue;
|
|
263
|
-
}
|
|
264
|
-
if (!ls && rs) {
|
|
265
|
-
if (direction === 'pull') {
|
|
266
|
-
actions.push({ path: p, action: 'copy', target: 'local', added: 0, reason: 'remote only' });
|
|
267
|
-
copied++;
|
|
268
|
-
} else {
|
|
269
|
-
actions.push({ path: p, action: 'skip', target: 'remote', added: 0, reason: 'remote only, push skips' });
|
|
270
|
-
skipped++;
|
|
271
|
-
}
|
|
272
|
-
continue;
|
|
273
|
-
}
|
|
274
|
-
if (ls && rs) {
|
|
275
|
-
if (ls.sha256 === rs.sha256) {
|
|
276
|
-
actions.push({ path: p, action: 'skip', target, added: 0, reason: 'identical bytes', expectedTargetSha256: ls.sha256 });
|
|
277
|
-
skipped++;
|
|
278
|
-
continue;
|
|
279
|
-
}
|
|
280
|
-
const localBuf = localContents.get(p);
|
|
281
|
-
const remoteBuf = remoteContents.get(p);
|
|
282
|
-
if (!localBuf || !remoteBuf) {
|
|
283
|
-
actions.push({ path: p, action: 'conflict', target, added: 0, reason: 'missing content for merge', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
|
|
284
|
-
conflicts++;
|
|
285
|
-
continue;
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
try {
|
|
289
|
-
if (p.endsWith('.md')) {
|
|
290
|
-
const localStr = localBuf.toString('utf-8');
|
|
291
|
-
const remoteStr = remoteBuf.toString('utf-8');
|
|
292
|
-
const { added: addedCount } = direction === 'pull' ? mergeDelimited(localStr, remoteStr) : mergeDelimited(remoteStr, localStr);
|
|
293
|
-
if (addedCount === 0) {
|
|
294
|
-
// same delimited entries, different bytes/order — nothing to add
|
|
295
|
-
actions.push({ path: p, action: 'skip', target, added: 0, reason: 'content-equal, no new entries', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
|
|
296
|
-
skipped++;
|
|
297
|
-
} else {
|
|
298
|
-
actions.push({ path: p, action: 'merge', target, added: addedCount, reason: 'content differs, merge', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
|
|
299
|
-
merged++;
|
|
300
|
-
added += addedCount;
|
|
301
|
-
}
|
|
302
|
-
} else if (p.endsWith('.jsonl')) {
|
|
303
|
-
const addedCount = direction === 'pull' ? unionJsonlAdded(localBuf, remoteBuf) : unionJsonlAdded(remoteBuf, localBuf);
|
|
304
|
-
if (addedCount === 0) {
|
|
305
|
-
actions.push({ path: p, action: 'skip', target, added: 0, reason: 'content-equal, no new lines', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
|
|
306
|
-
skipped++;
|
|
307
|
-
} else {
|
|
308
|
-
actions.push({ path: p, action: 'merge', target, added: addedCount, reason: 'content differs, merge', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
|
|
309
|
-
merged++;
|
|
310
|
-
added += addedCount;
|
|
311
|
-
}
|
|
312
|
-
} else if (p.endsWith('.zstd')) {
|
|
313
|
-
// Session handling is Buffer/path-only and preserves DSH standalone checksummed Zstd header frame.
|
|
314
|
-
// Never convert Zstd bytes to UTF-8 string; use validated Zstd artifact API via session-plan.
|
|
315
|
-
try {
|
|
316
|
-
if (!isSameSession(localBuf, remoteBuf)) {
|
|
317
|
-
actions.push({ path: p, action: 'conflict', target, added: 0, reason: 'session header mismatch', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
|
|
318
|
-
conflicts++;
|
|
319
|
-
} else {
|
|
320
|
-
const { added: addedCount } = direction === 'pull' ? mergeSessionBuffers(localBuf, remoteBuf) : mergeSessionBuffers(remoteBuf, localBuf);
|
|
321
|
-
if (addedCount === 0) {
|
|
322
|
-
// identical session lines under a (possibly different) zstd frame layout
|
|
323
|
-
actions.push({ path: p, action: 'skip', target, added: 0, reason: 'content-equal, no new entries', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
|
|
324
|
-
skipped++;
|
|
325
|
-
} else {
|
|
326
|
-
actions.push({ path: p, action: 'merge', target, added: addedCount, reason: 'session differs, merge', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
|
|
327
|
-
merged++;
|
|
328
|
-
added += addedCount;
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
} catch (e: any) {
|
|
332
|
-
actions.push({ path: p, action: 'conflict', target, added: 0, reason: e?.message ?? 'session merge failed', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
|
|
333
|
-
conflicts++;
|
|
334
|
-
}
|
|
335
|
-
} else {
|
|
336
|
-
actions.push({ path: p, action: 'conflict', target, added: 0, reason: 'unknown kind', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
|
|
337
|
-
conflicts++;
|
|
338
|
-
}
|
|
339
|
-
} catch (e: any) {
|
|
340
|
-
actions.push({ path: p, action: 'conflict', target, added: 0, reason: e?.message ?? 'merge failed', expectedTargetSha256: target === 'local' ? ls.sha256 : rs.sha256 });
|
|
341
|
-
conflicts++;
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
const revision = revisionFrom([...localSnapshots, ...remoteSnapshots], direction);
|
|
347
|
-
const summary: SyncSummary = { copied, merged, skipped, conflicts, added };
|
|
348
|
-
actions.sort((a, b) => a.path.localeCompare(b.path));
|
|
349
|
-
return { revision, actions, summary, sessionCounts: opts.countOnlySessions ? sessionCounts : undefined };
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
export async function buildPreview(
|
|
353
|
-
localSnapshots: FileSnapshot[],
|
|
354
|
-
remoteSnapshots: FileSnapshot[],
|
|
355
|
-
direction: SyncDirection,
|
|
356
|
-
localContents: Map<string, Buffer>,
|
|
357
|
-
remoteContents: Map<string, Buffer>,
|
|
358
|
-
opts: { countOnlySessions?: boolean } = {},
|
|
359
|
-
): Promise<SyncPreview> {
|
|
360
|
-
const plan = await buildPlan(localSnapshots, remoteSnapshots, direction, localContents, remoteContents, opts);
|
|
361
|
-
const previewId = randomBytes(16).toString('hex');
|
|
362
|
-
const expiresAt = new Date(Date.now() + PREVIEW_TTL_MS).toISOString();
|
|
363
|
-
const preview: SyncPreview = { ...plan, previewId, expiresAt };
|
|
364
|
-
storePreview(preview, direction);
|
|
365
|
-
return preview;
|
|
366
|
-
}
|