@ddtcorex/dsh-maestro-core 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +7 -7
  2. package/assets/icon.svg +4 -0
  3. package/cordis.patch.yml +0 -12
  4. package/lib/client.js +3 -1744
  5. package/lib/health-poller.js +1 -1
  6. package/lib/self-kill-guard.d.ts +25 -8
  7. package/lib/self-kill-guard.js +81 -27
  8. package/lib/types/client/config/components/BrandMark.d.ts +3 -3
  9. package/lib/types/client/index.d.ts.map +1 -1
  10. package/locale/en.json +6 -0
  11. package/package.json +9 -5
  12. package/src/client/config/components/BrandMark.tsx +3 -3
  13. package/src/client/index.tsx +0 -2
  14. package/src/host/health-poller.ts +1 -1
  15. package/src/host/self-kill-guard.ts +84 -26
  16. package/lib/sync/backup-config.d.ts +0 -55
  17. package/lib/sync/backup-config.js +0 -119
  18. package/lib/sync/backup-service.d.ts +0 -123
  19. package/lib/sync/backup-service.js +0 -486
  20. package/lib/sync/bidirectional.d.ts +0 -39
  21. package/lib/sync/bidirectional.js +0 -25
  22. package/lib/sync/cli.d.ts +0 -38
  23. package/lib/sync/cli.js +0 -528
  24. package/lib/sync/config.d.ts +0 -59
  25. package/lib/sync/config.js +0 -72
  26. package/lib/sync/fingerprint.d.ts +0 -29
  27. package/lib/sync/fingerprint.js +0 -65
  28. package/lib/sync/hashing.d.ts +0 -22
  29. package/lib/sync/hashing.js +0 -77
  30. package/lib/sync/index.d.ts +0 -6
  31. package/lib/sync/index.js +0 -619
  32. package/lib/sync/machine-id.d.ts +0 -29
  33. package/lib/sync/machine-id.js +0 -66
  34. package/lib/sync/merge.d.ts +0 -31
  35. package/lib/sync/merge.js +0 -86
  36. package/lib/sync/peer-host.d.ts +0 -22
  37. package/lib/sync/peer-host.js +0 -62
  38. package/lib/sync/process-runner.d.ts +0 -31
  39. package/lib/sync/process-runner.js +0 -161
  40. package/lib/sync/remote-agent.d.ts +0 -41
  41. package/lib/sync/remote-agent.js +0 -227
  42. package/lib/sync/remote-cache.d.ts +0 -18
  43. package/lib/sync/remote-cache.js +0 -60
  44. package/lib/sync/remote-manifest.d.ts +0 -33
  45. package/lib/sync/remote-manifest.js +0 -111
  46. package/lib/sync/s3-object-store.d.ts +0 -38
  47. package/lib/sync/s3-object-store.js +0 -126
  48. package/lib/sync/session-plan.d.ts +0 -29
  49. package/lib/sync/session-plan.js +0 -213
  50. package/lib/sync/sigv4.d.ts +0 -20
  51. package/lib/sync/sigv4.js +0 -57
  52. package/lib/sync/snapshot.d.ts +0 -16
  53. package/lib/sync/snapshot.js +0 -143
  54. package/lib/sync/ssh-mux.d.ts +0 -12
  55. package/lib/sync/ssh-mux.js +0 -48
  56. package/lib/sync/store-root.d.ts +0 -44
  57. package/lib/sync/store-root.js +0 -67
  58. package/lib/sync/sync-plan.d.ts +0 -24
  59. package/lib/sync/sync-plan.js +0 -366
  60. package/lib/sync/sync-service.d.ts +0 -181
  61. package/lib/sync/sync-service.js +0 -911
  62. package/lib/sync/sync-types.d.ts +0 -87
  63. package/lib/sync/sync-types.js +0 -1
  64. package/lib/sync/transport.d.ts +0 -75
  65. package/lib/sync/transport.js +0 -196
  66. package/lib/sync/tunnel-restore.d.ts +0 -77
  67. package/lib/sync/tunnel-restore.js +0 -142
  68. package/lib/sync/validation.d.ts +0 -12
  69. package/lib/sync/validation.js +0 -96
  70. package/lib/types/client/sync/R2SyncPanel.d.ts +0 -6
  71. package/lib/types/client/sync/R2SyncPanel.d.ts.map +0 -1
  72. package/lib/types/client/sync/SyncPanel.d.ts +0 -12
  73. package/lib/types/client/sync/SyncPanel.d.ts.map +0 -1
  74. package/lib/types/client/sync/confirm-dialog.d.ts +0 -43
  75. package/lib/types/client/sync/confirm-dialog.d.ts.map +0 -1
  76. package/lib/types/client/sync/index.d.ts +0 -10
  77. package/lib/types/client/sync/index.d.ts.map +0 -1
  78. package/lib/types/client/sync/ui.d.ts +0 -75
  79. package/lib/types/client/sync/ui.d.ts.map +0 -1
  80. package/lib/types/client/sync/use-backup.d.ts +0 -50
  81. package/lib/types/client/sync/use-backup.d.ts.map +0 -1
  82. package/lib/types/client/sync/use-sync.d.ts +0 -88
  83. package/lib/types/client/sync/use-sync.d.ts.map +0 -1
  84. package/src/client/sync/R2SyncPanel.tsx +0 -260
  85. package/src/client/sync/SyncPanel.tsx +0 -422
  86. package/src/client/sync/confirm-dialog.tsx +0 -202
  87. package/src/client/sync/index.tsx +0 -286
  88. package/src/client/sync/ui.tsx +0 -297
  89. package/src/client/sync/use-backup.ts +0 -207
  90. package/src/client/sync/use-sync.ts +0 -502
  91. package/src/host/sync/backup-config.ts +0 -158
  92. package/src/host/sync/backup-service.ts +0 -506
  93. package/src/host/sync/bidirectional.ts +0 -66
  94. package/src/host/sync/cli.ts +0 -530
  95. package/src/host/sync/config.ts +0 -96
  96. package/src/host/sync/fingerprint.ts +0 -83
  97. package/src/host/sync/hashing.ts +0 -91
  98. package/src/host/sync/index.ts +0 -697
  99. package/src/host/sync/machine-id.ts +0 -81
  100. package/src/host/sync/merge.ts +0 -99
  101. package/src/host/sync/peer-host.ts +0 -65
  102. package/src/host/sync/process-runner.ts +0 -177
  103. package/src/host/sync/remote-agent.ts +0 -223
  104. package/src/host/sync/remote-cache.ts +0 -68
  105. package/src/host/sync/remote-manifest.ts +0 -117
  106. package/src/host/sync/s3-object-store.ts +0 -144
  107. package/src/host/sync/session-plan.ts +0 -237
  108. package/src/host/sync/sigv4.ts +0 -81
  109. package/src/host/sync/snapshot.ts +0 -132
  110. package/src/host/sync/ssh-mux.ts +0 -55
  111. package/src/host/sync/store-root.ts +0 -83
  112. package/src/host/sync/sync-plan.ts +0 -366
  113. package/src/host/sync/sync-service.ts +0 -944
  114. package/src/host/sync/sync-types.ts +0 -102
  115. package/src/host/sync/transport.ts +0 -256
  116. package/src/host/sync/tunnel-restore.ts +0 -160
  117. package/src/host/sync/validation.ts +0 -104
@@ -1,227 +0,0 @@
1
- /**
2
- * Remote commit agent for dsh-maestro-sync.
3
- *
4
- * The only remote code executed by the transport is this fixed, versioned
5
- * POSIX sh helper. It is installed under `<dshRoot>/.maestro-sync/bin/`
6
- * (`ensureAgent`) and invoked as a fixed protocol command. Three ops:
7
- * - `maestro-sync-commit <operationId>` (commit path): reads a JSONL
8
- * manifest from stdin, whose paths were validated as eligible beforehand;
9
- * the only dynamic data that crosses to the remote is that manifest.
10
- * - `maestro-sync-commit machine-id`: prints `<dshRoot>/machine-id`.
11
- * - `maestro-sync-commit tunnel-patch <profile>`: reads the tunnel domain
12
- * from `<dshRoot>/dsh-maestro-remote/tunnel-profiles/<profile>/`
13
- * `settings-tunnel.json` on the remote itself and rewrites ONLY the
14
- * `domains.tunnel` value inside `<dshRoot>/dsh-maestro-config/settings.json`
15
- * (JSON-aware object assignment, atomic tmp+rename, mode 0600). The
16
- * tunnel domain is a named-tunnel OBJECT, never a bare string — a
17
- * 2026-09-09 string write clobbered the object shape and took a tunnel
18
- * down, so non-object values fail closed on both sides.
19
- * No settings bytes ever cross the wire in
20
- * either direction; prints `PATCHED <sha256>` or `UNCHANGED <sha256>`.
21
- * Single-writer discipline (runs post-sync, operator-serialized) plus
22
- * the already-equal no-op check make expected-sha CAS unnecessary here:
23
- * concurrent writers can only converge on the same profile value.
24
- *
25
- * CAS semantics (compare-and-swap, fail closed):
26
- * - expected `<sha256>`: the current target must hash to exactly that value;
27
- * any mismatch (or a vanished target) is CONCURRENT_MODIFICATION and the
28
- * target is never overwritten.
29
- * - expected `absent`: the target must not exist; if it appeared concurrently
30
- * the publish is rejected.
31
- * - On success the helper backs the target up beside the file, then atomically
32
- * renames the staged artifact into place (`mv` on the same filesystem).
33
- * - Any failure exits non-zero; no partial overwrite ever occurs.
34
- */
35
- export const REMOTE_AGENT_REL = '.maestro-sync/bin/maestro-sync-commit';
36
- export function remoteAgentSource() {
37
- return `#!/bin/sh
38
- # maestro-sync-commit — fixed remote CAS publisher for dsh-maestro-sync.
39
- # Usage: maestro-sync-commit <operationId> | machine-id | tunnel-patch <profile>
40
- # Commit path reads a JSONL manifest from stdin. Each line is one object:
41
- # {"path":"<eligible rel path>","expected":"<sha256 hex>|absent"}
42
- # Staged artifacts live under <dshRoot>/.maestro-sync/stage/<operationId>/<path>.
43
- # Publishes to <dshRoot>/<path> only after compare-and-swap; on mismatch it
44
- # reports CONCURRENT_MODIFICATION and never overwrites. Committed targets are
45
- # backed up beside the file as <path>.bak.<ts>.<pid>. Any failure exits non-zero.
46
- # machine-id prints <dshRoot>/machine-id. tunnel-patch rewrites only
47
- # domains.tunnel in <dshRoot>/dsh-maestro-config/settings.json from the named
48
- # profile (see header comment); both print machine-readable lines and never touch stdin.
49
- set -u
50
-
51
- die() { echo "maestro-sync-commit: $*" >&2; exit 1; }
52
-
53
- [ "$#" -ge 1 ] || die "usage: maestro-sync-commit <operationId> | machine-id | tunnel-patch <profile>"
54
-
55
- # The helper lives at <dshRoot>/.maestro-sync/bin/maestro-sync-commit, so the
56
- # DSH root is two levels up from $0 (no local shell ever expands it).
57
- self="$0"
58
- dsh_root=$(CDPATH= cd -- "$(dirname -- "$self")/../.." 2>/dev/null && pwd) || die "cannot resolve dsh root from $self"
59
- [ -n "$dsh_root" ] || die "empty dsh root"
60
-
61
- cmd="$1"
62
-
63
- # --- op: machine-id ---
64
- if [ "$cmd" = "machine-id" ]; then
65
- [ "$#" -eq 1 ] || die "usage: maestro-sync-commit machine-id"
66
- id_file="$dsh_root/machine-id"
67
- [ -f "$id_file" ] || die "no machine-id under $dsh_root"
68
- id=$(tr -d ' \\t\\r\\n' < "$id_file")
69
- [ -n "$id" ] || die "empty machine-id"
70
- printf '%s\\n' "$id"
71
- exit 0
72
- fi
73
-
74
- # --- op: tunnel-patch ---
75
- if [ "$cmd" = "tunnel-patch" ]; then
76
- [ "$#" -eq 2 ] || die "usage: maestro-sync-commit tunnel-patch <profile>"
77
- profile="$2"
78
- case "$profile" in
79
- ''|*/*|*..*|*' '*|*'"'*|*"'"'*|*'\\'*|.*) die "unsafe profile name" ;;
80
- esac
81
- command -v python3 >/dev/null 2>&1 || die "TUNNEL_PATCH_UNSUPPORTED: python3 not found on remote"
82
- profile_settings="$dsh_root/dsh-maestro-remote/tunnel-profiles/$profile/settings-tunnel.json"
83
- settings="$dsh_root/dsh-maestro-config/settings.json"
84
- [ -f "$profile_settings" ] || die "no tunnel profile: $profile"
85
- [ -f "$settings" ] || die "no settings.json under $dsh_root/dsh-maestro-config"
86
- # JSON-aware object assignment of domains.tunnel only; every other key is
87
- # preserved. The profile value MUST be a named-tunnel object (mode/hostname)
88
- # — a bare string fails closed instead of clobbering the object shape.
89
- out=$(python3 - "$profile_settings" "$settings" <<'PYEOF'
90
- import hashlib, json, os, sys
91
- prof_path, settings_path = sys.argv[1], sys.argv[2]
92
- try:
93
- prof = json.load(open(prof_path, encoding='utf-8'))
94
- doc = json.load(open(settings_path, encoding='utf-8'))
95
- except Exception as e:
96
- sys.exit('invalid JSON: %s' % e)
97
- tunnel = (prof.get('domains') or {}).get('tunnel')
98
- if not isinstance(tunnel, dict) or not tunnel.get('mode') or not tunnel.get('hostname'):
99
- sys.exit('profile tunnel is not a named-tunnel object')
100
- if not isinstance(doc.get('domains'), dict):
101
- sys.exit('settings has no domains object')
102
- if doc['domains'].get('tunnel') == tunnel:
103
- raw = open(settings_path, encoding='utf-8').read()
104
- print('UNCHANGED ' + hashlib.sha256(raw.encode('utf-8')).hexdigest())
105
- else:
106
- doc['domains']['tunnel'] = tunnel
107
- new = json.dumps(doc, indent=2) + '\\n'
108
- tmp = settings_path + '.tmp.' + str(os.getpid())
109
- with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), 'w', encoding='utf-8') as f:
110
- f.write(new)
111
- f.flush()
112
- os.fsync(f.fileno())
113
- os.replace(tmp, settings_path)
114
- print('PATCHED ' + hashlib.sha256(new.encode('utf-8')).hexdigest())
115
- PYEOF
116
- ) || die "tunnel-patch failed"
117
- printf '%s\\n' "$out"
118
- exit 0
119
- fi
120
-
121
- # --- op: commit (default) ---
122
- [ "$#" -eq 1 ] || die "usage: maestro-sync-commit <operationId>"
123
- op="$1"
124
-
125
- stage_dir="$dsh_root/.maestro-sync/stage/$op"
126
- [ -d "$stage_dir" ] || die "no staged operation $op under $dsh_root/.maestro-sync"
127
-
128
- # sha256sum is coreutils; fall back to macOS shasum for dev hosts.
129
- if ! command -v sha256sum >/dev/null 2>&1; then
130
- sha256sum() { shasum -a 256 "$1" | awk '{print $1}'; }
131
- fi
132
-
133
- fail=0
134
- while IFS= read -r line; do
135
- [ -n "$line" ] || continue
136
- case "$line" in
137
- '{'*) ;;
138
- *) echo "maestro-sync-commit: invalid manifest line" >&2; fail=1; continue ;;
139
- esac
140
- rel=$(printf '%s' "$line" | sed -n 's/^.*"path":"\\([^"]*\\)".*$/\\1/p')
141
- expected=$(printf '%s' "$line" | sed -n 's/^.*"expected":"\\([^"]*\\)".*$/\\1/p')
142
- [ -n "$rel" ] || { echo "maestro-sync-commit: manifest line without path" >&2; fail=1; continue; }
143
- case "$rel" in
144
- /*|*..*|*' '*|*'"'*|*"'"'*|*'\\'*)
145
- echo "maestro-sync-commit: unsafe path in manifest: $rel" >&2; fail=1; continue ;;
146
- esac
147
- staged="$stage_dir/$rel"
148
- [ -f "$staged" ] || { echo "maestro-sync-commit: missing staged artifact: $rel" >&2; fail=1; continue; }
149
- # The peer's store may live outside its DSH home since 5.0. Memory wire paths land in
150
- # whichever store root that peer actually reads; everything else stays under the DSH
151
- # home. Resolved once per commit from the peer's own marker, never assumed.
152
- case "$rel" in
153
- maestro-memory/*)
154
- if [ -f "$HOME/.maestro-memory/.maestro-memory/migrated-v5.json" ]; then
155
- target="$HOME/.maestro-memory/\${rel#maestro-memory/}"
156
- else
157
- target="$dsh_root/$rel"
158
- fi ;;
159
- *) target="$dsh_root/$rel" ;;
160
- esac
161
- if [ "$expected" = "absent" ]; then
162
- if [ -e "$target" ]; then
163
- echo "CONCURRENT_MODIFICATION: $rel (target exists, expected absent)" >&2
164
- fail=1
165
- continue
166
- fi
167
- else
168
- case "$expected" in
169
- [0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]*) ;;
170
- *) echo "maestro-sync-commit: invalid expected hash for $rel" >&2; fail=1; continue ;;
171
- esac
172
- if [ -f "$target" ]; then
173
- actual=$(sha256sum "$target" 2>/dev/null | awk '{print $1}') || { echo "maestro-sync-commit: cannot hash $rel" >&2; fail=1; continue; }
174
- if [ "$actual" != "$expected" ]; then
175
- echo "CONCURRENT_MODIFICATION: $rel (target sha256 $actual != expected $expected)" >&2
176
- fail=1
177
- continue
178
- fi
179
- else
180
- echo "CONCURRENT_MODIFICATION: $rel (target vanished)" >&2
181
- fail=1
182
- continue
183
- fi
184
- fi
185
- if [ -f "$target" ]; then
186
- bak="$target.bak.$(date +%s).$$"
187
- if ! cp -p "$target" "$bak" 2>/dev/null; then
188
- echo "maestro-sync-commit: backup failed for $rel" >&2
189
- fail=1
190
- continue
191
- fi
192
- fi
193
- if ! mkdir -p "$(dirname -- "$target")" 2>/dev/null; then
194
- echo "maestro-sync-commit: cannot create target dir for $rel" >&2
195
- fail=1
196
- continue
197
- fi
198
- if ! mv "$staged" "$target" 2>/dev/null; then
199
- echo "maestro-sync-commit: publish failed for $rel" >&2
200
- fail=1
201
- continue
202
- fi
203
- echo "committed $rel"
204
- done
205
- [ "$fail" -eq 0 ] || exit 1
206
- exit 0
207
- `;
208
- }
209
- /**
210
- * Structural verification of the helper source — used by tests and by
211
- * `ensureAgent` before shipping the script to the remote host.
212
- */
213
- export function verifyRemoteAgentSource(src) {
214
- if (!src.startsWith('#!/bin/sh'))
215
- throw new Error('remote agent must be POSIX sh');
216
- if (src.includes('[[ '))
217
- throw new Error('remote agent must not use bash [[ ]]');
218
- if (/\bfunction\s+/.test(src))
219
- throw new Error('remote agent must not use bash function keyword');
220
- if (!src.includes('CONCURRENT_MODIFICATION'))
221
- throw new Error('remote agent must implement CAS');
222
- if (!src.includes('.maestro-sync/stage/'))
223
- throw new Error('remote agent must read staged artifacts');
224
- if (!src.includes('sha256'))
225
- throw new Error('remote agent must hash targets');
226
- return src;
227
- }
@@ -1,18 +0,0 @@
1
- export declare const REMOTE_CACHE_REL = ".maestro-sync/fp.tsv";
2
- export declare function remoteCachePath(dshRoot: string): string;
3
- export interface FpCacheEntry {
4
- ino: number;
5
- size: number;
6
- mtimeNs: string;
7
- ctimeNs: string;
8
- sha256: string;
9
- }
10
- /** Parse fp.tsv lines: `rel<TAB>ino<TAB>size<TAB>mtimeNs<TAB>ctimeNs<TAB>sha256`. */
11
- export declare function parseFpCache(buf: Buffer): Map<string, FpCacheEntry>;
12
- /**
13
- * Warm script: re-hash every eligible file fresh and rewrite fp.tsv atomically
14
- * (tmp + rename). Run ONLY from the push-apply path or an explicit warm
15
- * command — never from preview. One stat batch via xargs keeps fork counts low;
16
- * `set -- $st` splits the four stat fields (none contain whitespace).
17
- */
18
- export declare function buildWarmCacheScript(dshRoot: string): string;
@@ -1,60 +0,0 @@
1
- // src/host/remote-cache.ts — remote stat-keyed fingerprint cache (fp.tsv).
2
- //
3
- // The REMOTE-side counterpart of the local fingerprint index (§4.2, spec §4.7
4
- // clarification, operator decision C 2026-09-02). It is a pure speed hint:
5
- // - the manifest script READS fp.tsv and skips sha256sum when the file's
6
- // ino+size+mtimeNs+ctimeNs triple matches (GNU stat %.Y/%.Z ns fractions);
7
- // - preview NEVER writes it — only push-apply or an explicit warm command runs
8
- // buildWarmCacheScript, which hashes misses and atomically renames the cache.
9
- // Exactness never depends on the cache: a miss re-hashes; every write target is
10
- // verified by CAS at publish.
11
- import { normalizeEligiblePath } from './validation.js';
12
- export const REMOTE_CACHE_REL = '.maestro-sync/fp.tsv';
13
- export function remoteCachePath(dshRoot) {
14
- return `${dshRoot}/${REMOTE_CACHE_REL}`;
15
- }
16
- /** Parse fp.tsv lines: `rel<TAB>ino<TAB>size<TAB>mtimeNs<TAB>ctimeNs<TAB>sha256`. */
17
- export function parseFpCache(buf) {
18
- const out = new Map();
19
- for (const line of buf.toString('utf-8').split('\n')) {
20
- if (!line.trim())
21
- continue;
22
- const [rel, inoRaw, sizeRaw, mtimeNs, ctimeNs, sha256] = line.split('\t');
23
- if (!rel || !sha256)
24
- continue;
25
- try {
26
- normalizeEligiblePath(rel);
27
- }
28
- catch {
29
- continue;
30
- }
31
- const ino = Number(inoRaw);
32
- const size = Number(sizeRaw);
33
- if (!Number.isFinite(ino) || !Number.isFinite(size))
34
- continue;
35
- out.set(rel, { ino, size, mtimeNs, ctimeNs, sha256 });
36
- }
37
- return out;
38
- }
39
- /**
40
- * Warm script: re-hash every eligible file fresh and rewrite fp.tsv atomically
41
- * (tmp + rename). Run ONLY from the push-apply path or an explicit warm
42
- * command — never from preview. One stat batch via xargs keeps fork counts low;
43
- * `set -- $st` splits the four stat fields (none contain whitespace).
44
- */
45
- export function buildWarmCacheScript(dshRoot) {
46
- const cache = remoteCachePath(dshRoot);
47
- return [
48
- `mkdir -p "${dshRoot}/.maestro-sync";`,
49
- `find ${dshRoot}/maestro-memory ${dshRoot}/sessions`,
50
- `\\( -name node_modules -o -name .git -o -name .supervisor -o -name profiles \\) -prune -o -type f -print0`,
51
- `| xargs -0 stat --printf='%i %s %.Y %.Z\\t%n\\0' 2>/dev/null`,
52
- `| while IFS= read -r -d '' rec; do`,
53
- `st=\${rec%%$'\\t'*}; abs=\${rec#*$'\\t'}; rel=\${abs#${dshRoot}/};`,
54
- `set -- $st;`,
55
- `sha=$(sha256sum -- "${dshRoot}/$rel" 2>/dev/null | awk '{print $1}');`,
56
- `printf '%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n' "$rel" "$1" "$2" "$3" "$4" "$sha";`,
57
- `done > "${cache}.tmp.$$";`,
58
- `mv "${cache}.tmp.$$" "${cache}";`,
59
- ].join(' ');
60
- }
@@ -1,33 +0,0 @@
1
- export interface RemoteManifestEntry {
2
- path: string;
3
- sha256: string;
4
- size: number;
5
- mtimeSec: number;
6
- }
7
- /**
8
- * Raised when the peer has not moved its store to the 4.0 root yet.
9
- *
10
- * Before this guard the peer's `find` simply matched nothing, the plan read as
11
- * "the peer has no memory", and the next push would have looked like the first
12
- * one. A named refusal is worth more than a silent empty inventory.
13
- */
14
- /**
15
- * Raised when the peer has moved its store out of the DSH home.
16
- *
17
- * Sync still addresses memory as `<dshRoot>/maestro-memory` on the sending side, so a
18
- * push to a moved peer writes into the directory that peer no longer reads, and the
19
- * transfer reports success. Until the remote scripts learn a second base path, the only
20
- * honest thing is to refuse: a named refusal is worth more than memories that vanish.
21
- */
22
- export declare class PeerStoreMovedError extends Error {
23
- readonly remotePath: string;
24
- readonly code = "PEER_STORE_MOVED";
25
- constructor(remotePath: string);
26
- }
27
- export declare class StoreNotMigratedError extends Error {
28
- readonly remotePath: string;
29
- readonly code = "STORE_NOT_MIGRATED";
30
- constructor(remotePath: string);
31
- }
32
- export declare function buildRemoteManifestScript(dshRoot: string): string;
33
- export declare function parseRemoteManifest(buf: Buffer): RemoteManifestEntry[];
@@ -1,111 +0,0 @@
1
- // src/host/remote-manifest.ts — one-pass remote inventory of eligible files.
2
- //
3
- // The fixed remote script walks only the eligible subtrees (same prune rules
4
- // as transport.list), emits "sha<TAB>size<TAB>mtime<TAB>rel\0" per file, and
5
- // the parser validates every relative path via normalizeEligiblePath before it
6
- // can enter a plan. NUL framing keeps any discovered name safe on the wire;
7
- // the parser sorts deterministically. mtimeSec is informational only — it is
8
- // never an equality proof (equality uses sha256+size).
9
- import { normalizeEligiblePath } from './validation.js';
10
- import { remoteCachePath } from './remote-cache.js';
11
- /**
12
- * Raised when the peer has not moved its store to the 4.0 root yet.
13
- *
14
- * Before this guard the peer's `find` simply matched nothing, the plan read as
15
- * "the peer has no memory", and the next push would have looked like the first
16
- * one. A named refusal is worth more than a silent empty inventory.
17
- */
18
- /**
19
- * Raised when the peer has moved its store out of the DSH home.
20
- *
21
- * Sync still addresses memory as `<dshRoot>/maestro-memory` on the sending side, so a
22
- * push to a moved peer writes into the directory that peer no longer reads, and the
23
- * transfer reports success. Until the remote scripts learn a second base path, the only
24
- * honest thing is to refuse: a named refusal is worth more than memories that vanish.
25
- */
26
- export class PeerStoreMovedError extends Error {
27
- remotePath;
28
- code = 'PEER_STORE_MOVED';
29
- constructor(remotePath) {
30
- super(`peer store moved to ${remotePath}: this sync can only write <dshRoot>/maestro-memory, so publishing would be lost. Upgrade this machine's sync before transferring`);
31
- this.remotePath = remotePath;
32
- this.name = 'PeerStoreMovedError';
33
- }
34
- }
35
- export class StoreNotMigratedError extends Error {
36
- remotePath;
37
- code = 'STORE_NOT_MIGRATED';
38
- constructor(remotePath) {
39
- super(`remote store not migrated: ${remotePath} has no migrated-v4 marker; run the new build on that machine first`);
40
- this.remotePath = remotePath;
41
- this.name = 'StoreNotMigratedError';
42
- }
43
- }
44
- export function buildRemoteManifestScript(dshRoot) {
45
- // Fixed script; dshRoot is the validated absolute root (same trust rule as transport.list).
46
- // Cache-aware, READ-ONLY (spec §4.7 clarification, decision C): it consults
47
- // <root>/.maestro-sync/fp.tsv and reuses a cached sha256 when the file's
48
- // ino+size+mtimeNs+ctimeNs triple (GNU stat '%.Y'/'%.Z' ns fractions) still
49
- // matches, skipping sha256sum for unchanged files. The cache is loaded ONCE
50
- // in a single awk pass, read straight from the file inside awk (getline — a
51
- // `-v cache=...` copy exceeds the 128 KiB per-arg limit once fp.tsv grows,
52
- // E2BIG "Argument list too long", measured 2026-09-02); only MISS records are
53
- // sha256sum'd in the bash loop. NEVER writes.
54
- // Every loop-body statement must end with ';' — space-separated assignments
55
- // inside a `do...done` one-liner break bash's parser (verified 2026-09-02).
56
- const cache = remoteCachePath(dshRoot);
57
- return [
58
- // Preflight sentinel: no 4.0 marker means the peer still holds the old
59
- // root, so an empty inventory must not be mistaken for an empty store.
60
- `if [ ! -f ${dshRoot}/maestro-memory/.maestro-memory/migrated-v4 ] && [ -d ${dshRoot}/dsh-maestro-memory ]; then printf 'STORE_NOT_MIGRATED\\t0\\t0\\t%s\\0' ${dshRoot}/dsh-maestro-memory; exit 0; fi;`,
61
- // 5.0 moved the store out of the DSH home on the peer. Its `find` below would match
62
- // nothing and read as "the peer has no memory", exactly the failure the v4 sentinel
63
- // above exists to prevent.
64
- `mem_root=${dshRoot}/maestro-memory; if [ -f "$HOME/.maestro-memory/.maestro-memory/migrated-v5.json" ]; then mem_root="$HOME/.maestro-memory"; fi;`,
65
- `find "$mem_root" ${dshRoot}/sessions`,
66
- `\\( -name node_modules -o -name .git -o -name .supervisor -o -name profiles \\) -prune -o -type f -print0`,
67
- `| xargs -0 stat --printf='%i %s %.Y %.Z\\t%n\\n' 2>/dev/null`,
68
- `| awk -F '\\t' -v root='${dshRoot}/' -v cachefile='${cache}' 'BEGIN{while((getline line < cachefile) > 0){if(line=="")continue; m=split(line,a,"\\t"); if(m>=6){c[a[1]]=(a[2]" "a[3]" "a[4]" "a[5])"\\t"a[6]"\\t"a[3]"\\t"a[4];}} close(cachefile);} {st=$1; rel=$2; sub(root,"",rel); if(rel in c){split(c[rel],e,"\\t"); if(e[1]==st){print "H\\t"rel"\\t"e[2]"\\t"e[3]"\\t"e[4]; next;}} print "M\\t"rel"\\t"st;}'`,
69
- `| while IFS= read -r rec; do`,
70
- `tag=\${rec%%$'\\t'*}; rest=\${rec#*$'\\t'};`,
71
- `if [ "$tag" = "H" ]; then`,
72
- `rel=\${rest%%$'\\t'*}; rest=\${rest#*$'\\t'}; sha=\${rest%%$'\\t'*}; rest=\${rest#*$'\\t'}; size=\${rest%%$'\\t'*}; mtime=\${rest#*$'\\t'};`,
73
- `printf '%s\\t%s\\t%s\\t%s\\0' "$sha" "$size" "$mtime" "$rel";`,
74
- `else`,
75
- `rel=\${rest%%$'\\t'*}; st=\${rest#*$'\\t'};`,
76
- `case "$rel" in maestro-memory/*) if [ "$mem_root" != "${dshRoot}/maestro-memory" ]; then full="$mem_root/\${rel#maestro-memory/}"; else full="${dshRoot}/$rel"; fi;; *) full="${dshRoot}/$rel";; esac;`,
77
- `sha=$(sha256sum -- "$full" 2>/dev/null | awk '{print $1}');`,
78
- `set -- $st;`,
79
- `printf '%s\\t%s\\t%s\\t%s\\0' "$sha" "$2" "$3" "$rel";`,
80
- `fi;`,
81
- `done`,
82
- ].join(' ');
83
- }
84
- export function parseRemoteManifest(buf) {
85
- const out = [];
86
- const parts = buf.toString('utf-8').split('\0');
87
- for (const part of parts) {
88
- if (!part)
89
- continue;
90
- if (part.startsWith('STORE_NOT_MIGRATED\t')) {
91
- throw new StoreNotMigratedError(part.split('\t').slice(3).join('\t'));
92
- }
93
- if (part.startsWith('PEER_STORE_MOVED\t')) {
94
- throw new PeerStoreMovedError(part.split('\t').slice(3).join('\t'));
95
- }
96
- const [sha, sizeRaw, mtimeRaw, ...rest] = part.split('\t');
97
- const p = rest.join('\t');
98
- const size = Number(sizeRaw);
99
- const mtimeSec = Number(mtimeRaw);
100
- if (!sha || !p || !Number.isFinite(size) || !Number.isFinite(mtimeSec))
101
- continue;
102
- try {
103
- normalizeEligiblePath(p);
104
- }
105
- catch {
106
- continue; // ineligible — never enters the plan
107
- }
108
- out.push({ path: p, sha256: sha, size, mtimeSec });
109
- }
110
- return out.sort((a, b) => a.path.localeCompare(b.path));
111
- }
@@ -1,38 +0,0 @@
1
- export interface S3Config {
2
- endpoint: string;
3
- region: string;
4
- accessKeyId: string;
5
- secretAccessKey: string;
6
- timeoutMs?: number;
7
- }
8
- export interface S3ListEntry {
9
- key: string;
10
- size: number;
11
- lastModified: string;
12
- }
13
- export interface S3HeadResult {
14
- size: number;
15
- etag: string;
16
- }
17
- export declare class S3ObjectStore {
18
- private readonly cfg;
19
- private readonly f;
20
- constructor(cfg: S3Config, f?: typeof fetch);
21
- private request;
22
- list(bucket: string, prefix: string): Promise<S3ListEntry[]>;
23
- head(bucket: string, key: string): Promise<S3HeadResult | null>;
24
- get(bucket: string, key: string, destDir: string): Promise<S3HeadResult>;
25
- /**
26
- * If-None-Match:* put — idempotent blob semantics: a 412 (already present)
27
- * is a silent no-op because blobs are content-addressed (same key ⇒ same
28
- * bytes), so a retry never corrupts.
29
- */
30
- putIfAbsent(bucket: string, key: string, body: Buffer): Promise<void>;
31
- /** CAS put: If-Match (or If-None-Match when the object must be absent); a 412 ⇒ CONCURRENT_MODIFICATION. */
32
- putConditional(bucket: string, key: string, body: Buffer, opts?: {
33
- ifMatch?: string;
34
- ifNoneMatch?: boolean;
35
- }): Promise<void>;
36
- /** Batched DeleteObjects (≤1000 keys per request). */
37
- deleteKeys(bucket: string, keys: string[]): Promise<void>;
38
- }
@@ -1,126 +0,0 @@
1
- // src/host/s3-object-store.ts — dependency-free S3 object store client
2
- // (SigV4 + global fetch) for Cloudflare R2 / AWS S3 backup (spec §5.2).
3
- //
4
- // Path-style URLs ({endpoint}/{bucket}/{key}) work for R2, AWS (with
5
- // forcePathStyle) and the hermetic fake. ETag is a CAS token, stripped of the
6
- // wrapping quotes S3 returns; content integrity lives in SHA-256 (blob keys +
7
- // manifest metadata), never in the ETag (multipart/encryption break it).
8
- import * as fsMod from 'node:fs';
9
- import * as path from 'node:path';
10
- import { sha256Hex, signRequest } from './sigv4.js';
11
- const EMPTY_SHA = sha256Hex('');
12
- export class S3ObjectStore {
13
- cfg;
14
- f;
15
- constructor(cfg, f = fetch) {
16
- this.cfg = cfg;
17
- this.f = f;
18
- }
19
- async request(method, bucket, key, opts = {}) {
20
- const url = `${this.cfg.endpoint}/${bucket}${key ? '/' + key : ''}${opts.query ? '?' + opts.query : ''}`;
21
- const host = new URL(this.cfg.endpoint).host;
22
- const bodySha = opts.body ? sha256Hex(opts.body) : EMPTY_SHA;
23
- const headers = { 'Content-Type': 'application/octet-stream' };
24
- if (opts.body)
25
- headers['Content-Length'] = String(opts.body.length);
26
- if (opts.etag)
27
- headers['If-Match'] = opts.etag;
28
- if (opts.ifNoneMatch)
29
- headers['If-None-Match'] = '*';
30
- const signed = signRequest({
31
- method, host, path: `/${bucket}${key ? '/' + key : ''}`, query: opts.query,
32
- headers, bodySha256: bodySha,
33
- region: this.cfg.region, service: 's3',
34
- accessKeyId: this.cfg.accessKeyId, secretAccessKey: this.cfg.secretAccessKey,
35
- now: new Date(),
36
- });
37
- const controller = new AbortController();
38
- const timer = setTimeout(() => controller.abort(), this.cfg.timeoutMs ?? 30_000);
39
- try {
40
- const res = await this.f(url, {
41
- method,
42
- headers: { ...headers, Authorization: signed.authorization, 'X-Amz-Date': signed.amzDate, 'X-Amz-Content-Sha256': signed.xAmzContentSha256 },
43
- // Buffer satisfies BodyInit at runtime (undici accepts it); the TS overloads
44
- // only admit Blob/string/URLSearchParams/ArrayBuffer — cast is intentional.
45
- body: opts.body ?? undefined,
46
- signal: controller.signal,
47
- });
48
- if (res.status === 412) {
49
- return { status: 412, headers: {}, body: Buffer.alloc(0) };
50
- }
51
- if (res.status === 404 && method !== 'DELETE') {
52
- return { status: 404, headers: {}, body: Buffer.alloc(0) };
53
- }
54
- if (res.status < 200 || res.status > 299) {
55
- throw Object.assign(new Error(`S3 ${method} ${key} failed: ${res.status}`), { phase: 'backup', code: 'S3_ERROR' });
56
- }
57
- const body = Buffer.from(await res.arrayBuffer());
58
- return { status: res.status, headers: Object.fromEntries(res.headers.entries()), body };
59
- }
60
- finally {
61
- clearTimeout(timer);
62
- }
63
- }
64
- async list(bucket, prefix) {
65
- const out = [];
66
- let token;
67
- for (;;) {
68
- const q = `list-type=2&prefix=${encodeURIComponent(prefix)}&max-keys=1000${token ? `&continuation-token=${encodeURIComponent(token)}` : ''}`;
69
- const r = await this.request('GET', bucket, '', { query: q });
70
- const xml = r.body.toString('utf-8');
71
- const keys = [...xml.matchAll(/<Contents><Key>([^<]+)<\/Key><Size>(\d+)<\/Size><LastModified>([^<]+)<\/LastModified>/g)];
72
- for (const m of keys)
73
- out.push({ key: m[1], size: Number(m[2]), lastModified: m[3] });
74
- if (!xml.includes('<IsTruncated>true</IsTruncated>'))
75
- break;
76
- const next = xml.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1];
77
- if (!next)
78
- break;
79
- token = next;
80
- }
81
- return out;
82
- }
83
- async head(bucket, key) {
84
- const r = await this.request('HEAD', bucket, key);
85
- if (r.status === 404)
86
- return null;
87
- const etag = (r.headers['etag'] ?? '""').replace(/"/g, '');
88
- return { size: Number(r.headers['content-length'] ?? 0), etag };
89
- }
90
- async get(bucket, key, destDir) {
91
- const r = await this.request('GET', bucket, key);
92
- const full = path.join(destDir, key);
93
- fsMod.mkdirSync(path.dirname(full), { recursive: true });
94
- fsMod.writeFileSync(full, r.body);
95
- return { size: r.body.length, etag: (r.headers['etag'] ?? '""').replace(/"/g, '') };
96
- }
97
- /**
98
- * If-None-Match:* put — idempotent blob semantics: a 412 (already present)
99
- * is a silent no-op because blobs are content-addressed (same key ⇒ same
100
- * bytes), so a retry never corrupts.
101
- */
102
- async putIfAbsent(bucket, key, body) {
103
- const r = await this.request('PUT', bucket, key, { body, ifNoneMatch: true });
104
- if (r.status === 412)
105
- return;
106
- }
107
- /** CAS put: If-Match (or If-None-Match when the object must be absent); a 412 ⇒ CONCURRENT_MODIFICATION. */
108
- async putConditional(bucket, key, body, opts = {}) {
109
- const r = await this.request('PUT', bucket, key, { body, etag: opts.ifMatch, ifNoneMatch: opts.ifNoneMatch });
110
- if (r.status === 412) {
111
- throw Object.assign(new Error(`CONCURRENT_MODIFICATION: ${key}`), { phase: 'backup', code: 'CONCURRENT_MODIFICATION', detail: key });
112
- }
113
- }
114
- /** Batched DeleteObjects (≤1000 keys per request). */
115
- async deleteKeys(bucket, keys) {
116
- for (let i = 0; i < keys.length; i += 1000) {
117
- const batch = keys.slice(i, i + 1000);
118
- const xml = `<?xml version="1.0"?><Delete>${batch
119
- .map((k) => `<Object><Key>${k.replace(/&/g, '&amp;').replace(/</g, '&lt;')}</Key></Object>`)
120
- .join('')}<Quiet>false</Quiet></Delete>`;
121
- const r = await this.request('POST', bucket, '', { query: 'delete', body: Buffer.from(xml) });
122
- if (r.status !== 200)
123
- throw Object.assign(new Error(`DeleteObjects failed: ${r.status}`), { phase: 'gc', code: 'S3_ERROR' });
124
- }
125
- }
126
- }
@@ -1,29 +0,0 @@
1
- export interface SessionIdentity {
2
- /** decompressed header line Buffer (UTF-8 without trailing newline) */
3
- header: Buffer;
4
- sessionId: string;
5
- cwd: string;
6
- }
7
- /**
8
- * Validates Zstd header frame and extracts identity.
9
- * - Validates Zstd magic and frame structure via checksum-aware decompression.
10
- * - Decompresses only the first frame (standalone header) and validates JSONL header.
11
- * - Never converts raw Zstd bytes to UTF-8 string.
12
- */
13
- export declare function parseSessionIdentity(buffer: Buffer): SessionIdentity;
14
- /**
15
- * Compare header identity, not just path.
16
- * Returns true if both buffers represent the same session (same id, cwd, and header line).
17
- */
18
- export declare function isSameSession(a: Buffer, b: Buffer): boolean;
19
- /**
20
- * Merge two valid session buffers via binary path and return merged Buffer with added count.
21
- * - Validates both buffers via validated Zstd artifact API (checksum, header frame).
22
- * - Preserves DSH standalone checksummed Zstd header frame (first frame is header alone).
23
- * - Never converts Zstd bytes to UTF-8 string; only decompressed plaintext is stringified for line union.
24
- * - Throws if headers differ (conflict) or either buffer is invalid/truncated.
25
- */
26
- export declare function mergeSessionBuffers(local: Buffer, remote: Buffer): {
27
- merged: Buffer;
28
- added: number;
29
- };