@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.
Files changed (285) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +209 -0
  3. package/cordis.patch.yml +43 -0
  4. package/lib/bin.d.ts +2 -0
  5. package/lib/bin.js +3 -0
  6. package/lib/boot-guard.d.ts +33 -0
  7. package/lib/boot-guard.js +68 -0
  8. package/lib/boot-lock.d.ts +56 -0
  9. package/lib/boot-lock.js +155 -0
  10. package/lib/cli.d.ts +31 -0
  11. package/lib/cli.js +336 -0
  12. package/lib/client.js +2901 -0
  13. package/lib/config/index.d.ts +34 -0
  14. package/lib/config/index.js +62 -0
  15. package/lib/config/service.d.ts +18 -0
  16. package/lib/config/service.js +28 -0
  17. package/lib/config.d.ts +1 -0
  18. package/lib/config.js +19 -0
  19. package/lib/daemon-freshness.d.ts +48 -0
  20. package/lib/daemon-freshness.js +122 -0
  21. package/lib/debug-agent.d.ts +17 -0
  22. package/lib/debug-agent.js +144 -0
  23. package/lib/dsh-session.d.ts +26 -0
  24. package/lib/dsh-session.js +45 -0
  25. package/lib/guard/config.d.ts +82 -0
  26. package/lib/guard/config.js +211 -0
  27. package/lib/guard/decide.d.ts +30 -0
  28. package/lib/guard/decide.js +38 -0
  29. package/lib/guard/full-scan-tool.d.ts +6 -0
  30. package/lib/guard/full-scan-tool.js +65 -0
  31. package/lib/guard/index.d.ts +85 -0
  32. package/lib/guard/index.js +254 -0
  33. package/lib/guard/journal.d.ts +146 -0
  34. package/lib/guard/journal.js +398 -0
  35. package/lib/guard/migrate.d.ts +15 -0
  36. package/lib/guard/migrate.js +42 -0
  37. package/lib/guard/parse.d.ts +193 -0
  38. package/lib/guard/parse.js +1103 -0
  39. package/lib/guard/paths.d.ts +104 -0
  40. package/lib/guard/paths.js +254 -0
  41. package/lib/guard/permission-policy.d.ts +10 -0
  42. package/lib/guard/permission-policy.js +21 -0
  43. package/lib/guard/redact.d.ts +25 -0
  44. package/lib/guard/redact.js +52 -0
  45. package/lib/guard/rules.d.ts +65 -0
  46. package/lib/guard/rules.js +832 -0
  47. package/lib/guard/status-tool.d.ts +54 -0
  48. package/lib/guard/status-tool.js +195 -0
  49. package/lib/guard/tiers.d.ts +2 -0
  50. package/lib/guard/tiers.js +1 -0
  51. package/lib/guard/validators.d.ts +4 -0
  52. package/lib/guard/validators.js +45 -0
  53. package/lib/health-poller.d.ts +90 -0
  54. package/lib/health-poller.js +430 -0
  55. package/lib/index.d.ts +7 -0
  56. package/lib/index.js +7 -0
  57. package/lib/intents.d.ts +32 -0
  58. package/lib/intents.js +49 -0
  59. package/lib/notifier.d.ts +12 -0
  60. package/lib/notifier.js +62 -0
  61. package/lib/paths.d.ts +13 -0
  62. package/lib/paths.js +70 -0
  63. package/lib/plugin.d.ts +250 -0
  64. package/lib/plugin.js +1126 -0
  65. package/lib/preset.d.ts +73 -0
  66. package/lib/preset.js +158 -0
  67. package/lib/report.d.ts +11 -0
  68. package/lib/report.js +58 -0
  69. package/lib/restart-exec.d.ts +35 -0
  70. package/lib/restart-exec.js +60 -0
  71. package/lib/restart-guards.d.ts +39 -0
  72. package/lib/restart-guards.js +150 -0
  73. package/lib/restart-tool.d.ts +124 -0
  74. package/lib/restart-tool.js +539 -0
  75. package/lib/restart-web.d.ts +26 -0
  76. package/lib/restart-web.js +58 -0
  77. package/lib/resume-log.d.ts +24 -0
  78. package/lib/resume-log.js +18 -0
  79. package/lib/resume-tools.d.ts +131 -0
  80. package/lib/resume-tools.js +337 -0
  81. package/lib/resume.d.ts +33 -0
  82. package/lib/resume.js +221 -0
  83. package/lib/scan.d.ts +20 -0
  84. package/lib/scan.js +71 -0
  85. package/lib/self-kill-guard.d.ts +81 -0
  86. package/lib/self-kill-guard.js +208 -0
  87. package/lib/session-health.d.ts +89 -0
  88. package/lib/session-health.js +274 -0
  89. package/lib/session-log-file.d.ts +22 -0
  90. package/lib/session-log-file.js +74 -0
  91. package/lib/skill-provider.d.ts +6 -0
  92. package/lib/skill-provider.js +73 -0
  93. package/lib/snapshot.d.ts +59 -0
  94. package/lib/snapshot.js +358 -0
  95. package/lib/source.d.ts +19 -0
  96. package/lib/source.js +19 -0
  97. package/lib/store/index.d.ts +42 -0
  98. package/lib/store/index.js +340 -0
  99. package/lib/store/legacy.d.ts +17 -0
  100. package/lib/store/legacy.js +85 -0
  101. package/lib/supervisor.d.ts +119 -0
  102. package/lib/supervisor.js +741 -0
  103. package/lib/sync/backup-config.d.ts +55 -0
  104. package/lib/sync/backup-config.js +119 -0
  105. package/lib/sync/backup-service.d.ts +110 -0
  106. package/lib/sync/backup-service.js +440 -0
  107. package/lib/sync/bidirectional.d.ts +39 -0
  108. package/lib/sync/bidirectional.js +25 -0
  109. package/lib/sync/cli.d.ts +38 -0
  110. package/lib/sync/cli.js +536 -0
  111. package/lib/sync/config.d.ts +77 -0
  112. package/lib/sync/config.js +90 -0
  113. package/lib/sync/fingerprint.d.ts +29 -0
  114. package/lib/sync/fingerprint.js +65 -0
  115. package/lib/sync/hashing.d.ts +9 -0
  116. package/lib/sync/hashing.js +47 -0
  117. package/lib/sync/index.d.ts +6 -0
  118. package/lib/sync/index.js +634 -0
  119. package/lib/sync/machine-id.d.ts +29 -0
  120. package/lib/sync/machine-id.js +66 -0
  121. package/lib/sync/merge.d.ts +33 -0
  122. package/lib/sync/merge.js +88 -0
  123. package/lib/sync/peer-host.d.ts +22 -0
  124. package/lib/sync/peer-host.js +62 -0
  125. package/lib/sync/process-runner.d.ts +31 -0
  126. package/lib/sync/process-runner.js +161 -0
  127. package/lib/sync/remote-agent.d.ts +42 -0
  128. package/lib/sync/remote-agent.js +217 -0
  129. package/lib/sync/remote-cache.d.ts +18 -0
  130. package/lib/sync/remote-cache.js +60 -0
  131. package/lib/sync/remote-manifest.d.ts +8 -0
  132. package/lib/sync/remote-manifest.js +64 -0
  133. package/lib/sync/s3-object-store.d.ts +38 -0
  134. package/lib/sync/s3-object-store.js +126 -0
  135. package/lib/sync/session-merge.d.ts +18 -0
  136. package/lib/sync/session-merge.js +191 -0
  137. package/lib/sync/session-plan.d.ts +29 -0
  138. package/lib/sync/session-plan.js +213 -0
  139. package/lib/sync/sigv4.d.ts +20 -0
  140. package/lib/sync/sigv4.js +57 -0
  141. package/lib/sync/snapshot.d.ts +21 -0
  142. package/lib/sync/snapshot.js +176 -0
  143. package/lib/sync/ssh-mux.d.ts +12 -0
  144. package/lib/sync/ssh-mux.js +48 -0
  145. package/lib/sync/sync-plan.d.ts +24 -0
  146. package/lib/sync/sync-plan.js +366 -0
  147. package/lib/sync/sync-service.d.ts +177 -0
  148. package/lib/sync/sync-service.js +819 -0
  149. package/lib/sync/sync-types.d.ts +87 -0
  150. package/lib/sync/sync-types.js +1 -0
  151. package/lib/sync/transport.d.ts +75 -0
  152. package/lib/sync/transport.js +200 -0
  153. package/lib/sync/tunnel-restore.d.ts +77 -0
  154. package/lib/sync/tunnel-restore.js +142 -0
  155. package/lib/sync/validation.d.ts +10 -0
  156. package/lib/sync/validation.js +83 -0
  157. package/lib/tool-view.d.ts +62 -0
  158. package/lib/tool-view.js +70 -0
  159. package/lib/types/client/auto-reload.d.ts +8 -0
  160. package/lib/types/client/auto-reload.d.ts.map +1 -0
  161. package/lib/types/client/config/MaestroSettings.d.ts +25 -0
  162. package/lib/types/client/config/MaestroSettings.d.ts.map +1 -0
  163. package/lib/types/client/config/components/BrandMark.d.ts +50 -0
  164. package/lib/types/client/config/components/BrandMark.d.ts.map +1 -0
  165. package/lib/types/client/config/guard-view.d.ts +83 -0
  166. package/lib/types/client/config/guard-view.d.ts.map +1 -0
  167. package/lib/types/client/config/index.d.ts +20 -0
  168. package/lib/types/client/config/index.d.ts.map +1 -0
  169. package/lib/types/client/config/maestro-mark.d.ts +29 -0
  170. package/lib/types/client/config/maestro-mark.d.ts.map +1 -0
  171. package/lib/types/client/config/settings-nav-icon.d.ts +21 -0
  172. package/lib/types/client/config/settings-nav-icon.d.ts.map +1 -0
  173. package/lib/types/client/index.d.ts +16 -0
  174. package/lib/types/client/index.d.ts.map +1 -0
  175. package/lib/types/client/sync/R2SyncPanel.d.ts +6 -0
  176. package/lib/types/client/sync/R2SyncPanel.d.ts.map +1 -0
  177. package/lib/types/client/sync/SyncPanel.d.ts +12 -0
  178. package/lib/types/client/sync/SyncPanel.d.ts.map +1 -0
  179. package/lib/types/client/sync/confirm-dialog.d.ts +43 -0
  180. package/lib/types/client/sync/confirm-dialog.d.ts.map +1 -0
  181. package/lib/types/client/sync/index.d.ts +10 -0
  182. package/lib/types/client/sync/index.d.ts.map +1 -0
  183. package/lib/types/client/sync/ui.d.ts +79 -0
  184. package/lib/types/client/sync/ui.d.ts.map +1 -0
  185. package/lib/types/client/sync/use-backup.d.ts +50 -0
  186. package/lib/types/client/sync/use-backup.d.ts.map +1 -0
  187. package/lib/types/client/sync/use-sync.d.ts +88 -0
  188. package/lib/types/client/sync/use-sync.d.ts.map +1 -0
  189. package/package.json +89 -0
  190. package/skills/dsh-safe-restart/SKILL.md +206 -0
  191. package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +468 -0
  192. package/src/client/auto-reload.ts +104 -0
  193. package/src/client/config/MaestroSettings.tsx +892 -0
  194. package/src/client/config/components/BrandMark.tsx +94 -0
  195. package/src/client/config/guard-view.ts +187 -0
  196. package/src/client/config/index.tsx +109 -0
  197. package/src/client/config/maestro-mark.ts +37 -0
  198. package/src/client/config/settings-nav-icon.ts +68 -0
  199. package/src/client/index.tsx +33 -0
  200. package/src/client/sync/R2SyncPanel.tsx +260 -0
  201. package/src/client/sync/SyncPanel.tsx +422 -0
  202. package/src/client/sync/confirm-dialog.tsx +202 -0
  203. package/src/client/sync/index.tsx +336 -0
  204. package/src/client/sync/ui.tsx +313 -0
  205. package/src/client/sync/use-backup.ts +207 -0
  206. package/src/client/sync/use-sync.ts +502 -0
  207. package/src/host/bin.ts +3 -0
  208. package/src/host/boot-guard.ts +76 -0
  209. package/src/host/boot-lock.ts +155 -0
  210. package/src/host/cli.ts +288 -0
  211. package/src/host/config/index.ts +78 -0
  212. package/src/host/config/service.ts +40 -0
  213. package/src/host/config.ts +18 -0
  214. package/src/host/daemon-freshness.ts +143 -0
  215. package/src/host/debug-agent.ts +145 -0
  216. package/src/host/dsh-session.ts +56 -0
  217. package/src/host/dsh-skill.d.ts +44 -0
  218. package/src/host/guard/augment.d.ts +33 -0
  219. package/src/host/guard/config.ts +244 -0
  220. package/src/host/guard/decide.ts +40 -0
  221. package/src/host/guard/full-scan-tool.ts +61 -0
  222. package/src/host/guard/index.ts +281 -0
  223. package/src/host/guard/journal.ts +440 -0
  224. package/src/host/guard/migrate.ts +41 -0
  225. package/src/host/guard/parse.ts +1150 -0
  226. package/src/host/guard/paths.ts +239 -0
  227. package/src/host/guard/permission-policy.ts +15 -0
  228. package/src/host/guard/redact.ts +64 -0
  229. package/src/host/guard/rules.ts +891 -0
  230. package/src/host/guard/status-tool.ts +229 -0
  231. package/src/host/guard/tiers.ts +2 -0
  232. package/src/host/guard/validators.ts +29 -0
  233. package/src/host/health-poller.ts +446 -0
  234. package/src/host/index.ts +7 -0
  235. package/src/host/intents.ts +67 -0
  236. package/src/host/notifier.ts +71 -0
  237. package/src/host/paths.ts +70 -0
  238. package/src/host/plugin.ts +1097 -0
  239. package/src/host/preset.ts +170 -0
  240. package/src/host/report.ts +71 -0
  241. package/src/host/restart-exec.ts +81 -0
  242. package/src/host/restart-guards.ts +150 -0
  243. package/src/host/restart-tool.ts +483 -0
  244. package/src/host/restart-web.ts +72 -0
  245. package/src/host/resume-log.ts +39 -0
  246. package/src/host/resume-tools.ts +385 -0
  247. package/src/host/resume.ts +204 -0
  248. package/src/host/scan.ts +61 -0
  249. package/src/host/self-kill-guard.ts +216 -0
  250. package/src/host/session-health.ts +236 -0
  251. package/src/host/session-log-file.ts +77 -0
  252. package/src/host/skill-provider.ts +69 -0
  253. package/src/host/snapshot.ts +337 -0
  254. package/src/host/source.ts +19 -0
  255. package/src/host/store/index.ts +348 -0
  256. package/src/host/store/legacy.ts +96 -0
  257. package/src/host/supervisor.ts +720 -0
  258. package/src/host/sync/backup-config.ts +159 -0
  259. package/src/host/sync/backup-service.ts +453 -0
  260. package/src/host/sync/bidirectional.ts +66 -0
  261. package/src/host/sync/cli.ts +539 -0
  262. package/src/host/sync/config.ts +119 -0
  263. package/src/host/sync/fingerprint.ts +83 -0
  264. package/src/host/sync/hashing.ts +58 -0
  265. package/src/host/sync/index.ts +737 -0
  266. package/src/host/sync/machine-id.ts +81 -0
  267. package/src/host/sync/merge.ts +102 -0
  268. package/src/host/sync/peer-host.ts +65 -0
  269. package/src/host/sync/process-runner.ts +177 -0
  270. package/src/host/sync/remote-agent.ts +213 -0
  271. package/src/host/sync/remote-cache.ts +68 -0
  272. package/src/host/sync/remote-manifest.ts +70 -0
  273. package/src/host/sync/s3-object-store.ts +144 -0
  274. package/src/host/sync/session-merge.ts +220 -0
  275. package/src/host/sync/session-plan.ts +237 -0
  276. package/src/host/sync/sigv4.ts +81 -0
  277. package/src/host/sync/snapshot.ts +162 -0
  278. package/src/host/sync/ssh-mux.ts +56 -0
  279. package/src/host/sync/sync-plan.ts +366 -0
  280. package/src/host/sync/sync-service.ts +855 -0
  281. package/src/host/sync/sync-types.ts +102 -0
  282. package/src/host/sync/transport.ts +261 -0
  283. package/src/host/sync/tunnel-restore.ts +160 -0
  284. package/src/host/sync/validation.ts +91 -0
  285. package/src/host/tool-view.ts +98 -0
@@ -0,0 +1,217 @@
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_NAME = 'maestro-sync-commit';
36
+ export const REMOTE_AGENT_REL = '.maestro-sync/bin/maestro-sync-commit';
37
+ export function remoteAgentSource() {
38
+ return `#!/bin/sh
39
+ # maestro-sync-commit — fixed remote CAS publisher for dsh-maestro-sync.
40
+ # Usage: maestro-sync-commit <operationId> | machine-id | tunnel-patch <profile>
41
+ # Commit path reads a JSONL manifest from stdin. Each line is one object:
42
+ # {"path":"<eligible rel path>","expected":"<sha256 hex>|absent"}
43
+ # Staged artifacts live under <dshRoot>/.maestro-sync/stage/<operationId>/<path>.
44
+ # Publishes to <dshRoot>/<path> only after compare-and-swap; on mismatch it
45
+ # reports CONCURRENT_MODIFICATION and never overwrites. Committed targets are
46
+ # backed up beside the file as <path>.bak.<ts>.<pid>. Any failure exits non-zero.
47
+ # machine-id prints <dshRoot>/machine-id. tunnel-patch rewrites only
48
+ # domains.tunnel in <dshRoot>/dsh-maestro-config/settings.json from the named
49
+ # profile (see header comment); both print machine-readable lines and never touch stdin.
50
+ set -u
51
+
52
+ die() { echo "maestro-sync-commit: $*" >&2; exit 1; }
53
+
54
+ [ "$#" -ge 1 ] || die "usage: maestro-sync-commit <operationId> | machine-id | tunnel-patch <profile>"
55
+
56
+ # The helper lives at <dshRoot>/.maestro-sync/bin/maestro-sync-commit, so the
57
+ # DSH root is two levels up from $0 (no local shell ever expands it).
58
+ self="$0"
59
+ dsh_root=$(CDPATH= cd -- "$(dirname -- "$self")/../.." 2>/dev/null && pwd) || die "cannot resolve dsh root from $self"
60
+ [ -n "$dsh_root" ] || die "empty dsh root"
61
+
62
+ cmd="$1"
63
+
64
+ # --- op: machine-id ---
65
+ if [ "$cmd" = "machine-id" ]; then
66
+ [ "$#" -eq 1 ] || die "usage: maestro-sync-commit machine-id"
67
+ id_file="$dsh_root/machine-id"
68
+ [ -f "$id_file" ] || die "no machine-id under $dsh_root"
69
+ id=$(tr -d ' \\t\\r\\n' < "$id_file")
70
+ [ -n "$id" ] || die "empty machine-id"
71
+ printf '%s\\n' "$id"
72
+ exit 0
73
+ fi
74
+
75
+ # --- op: tunnel-patch ---
76
+ if [ "$cmd" = "tunnel-patch" ]; then
77
+ [ "$#" -eq 2 ] || die "usage: maestro-sync-commit tunnel-patch <profile>"
78
+ profile="$2"
79
+ case "$profile" in
80
+ ''|*/*|*..*|*' '*|*'"'*|*"'"'*|*'\\'*|.*) die "unsafe profile name" ;;
81
+ esac
82
+ command -v python3 >/dev/null 2>&1 || die "TUNNEL_PATCH_UNSUPPORTED: python3 not found on remote"
83
+ profile_settings="$dsh_root/dsh-maestro-remote/tunnel-profiles/$profile/settings-tunnel.json"
84
+ settings="$dsh_root/dsh-maestro-config/settings.json"
85
+ [ -f "$profile_settings" ] || die "no tunnel profile: $profile"
86
+ [ -f "$settings" ] || die "no settings.json under $dsh_root/dsh-maestro-config"
87
+ # JSON-aware object assignment of domains.tunnel only; every other key is
88
+ # preserved. The profile value MUST be a named-tunnel object (mode/hostname)
89
+ # — a bare string fails closed instead of clobbering the object shape.
90
+ out=$(python3 - "$profile_settings" "$settings" <<'PYEOF'
91
+ import hashlib, json, os, sys
92
+ prof_path, settings_path = sys.argv[1], sys.argv[2]
93
+ try:
94
+ prof = json.load(open(prof_path, encoding='utf-8'))
95
+ doc = json.load(open(settings_path, encoding='utf-8'))
96
+ except Exception as e:
97
+ sys.exit('invalid JSON: %s' % e)
98
+ tunnel = (prof.get('domains') or {}).get('tunnel')
99
+ if not isinstance(tunnel, dict) or not tunnel.get('mode') or not tunnel.get('hostname'):
100
+ sys.exit('profile tunnel is not a named-tunnel object')
101
+ if not isinstance(doc.get('domains'), dict):
102
+ sys.exit('settings has no domains object')
103
+ if doc['domains'].get('tunnel') == tunnel:
104
+ raw = open(settings_path, encoding='utf-8').read()
105
+ print('UNCHANGED ' + hashlib.sha256(raw.encode('utf-8')).hexdigest())
106
+ else:
107
+ doc['domains']['tunnel'] = tunnel
108
+ new = json.dumps(doc, indent=2) + '\\n'
109
+ tmp = settings_path + '.tmp.' + str(os.getpid())
110
+ with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), 'w', encoding='utf-8') as f:
111
+ f.write(new)
112
+ f.flush()
113
+ os.fsync(f.fileno())
114
+ os.replace(tmp, settings_path)
115
+ print('PATCHED ' + hashlib.sha256(new.encode('utf-8')).hexdigest())
116
+ PYEOF
117
+ ) || die "tunnel-patch failed"
118
+ printf '%s\\n' "$out"
119
+ exit 0
120
+ fi
121
+
122
+ # --- op: commit (default) ---
123
+ [ "$#" -eq 1 ] || die "usage: maestro-sync-commit <operationId>"
124
+ op="$1"
125
+
126
+ stage_dir="$dsh_root/.maestro-sync/stage/$op"
127
+ [ -d "$stage_dir" ] || die "no staged operation $op under $dsh_root/.maestro-sync"
128
+
129
+ # sha256sum is coreutils; fall back to macOS shasum for dev hosts.
130
+ if ! command -v sha256sum >/dev/null 2>&1; then
131
+ sha256sum() { shasum -a 256 "$1" | awk '{print $1}'; }
132
+ fi
133
+
134
+ fail=0
135
+ while IFS= read -r line; do
136
+ [ -n "$line" ] || continue
137
+ case "$line" in
138
+ '{'*) ;;
139
+ *) echo "maestro-sync-commit: invalid manifest line" >&2; fail=1; continue ;;
140
+ esac
141
+ rel=$(printf '%s' "$line" | sed -n 's/^.*"path":"\\([^"]*\\)".*$/\\1/p')
142
+ expected=$(printf '%s' "$line" | sed -n 's/^.*"expected":"\\([^"]*\\)".*$/\\1/p')
143
+ [ -n "$rel" ] || { echo "maestro-sync-commit: manifest line without path" >&2; fail=1; continue; }
144
+ case "$rel" in
145
+ /*|*..*|*' '*|*'"'*|*"'"'*|*'\\'*)
146
+ echo "maestro-sync-commit: unsafe path in manifest: $rel" >&2; fail=1; continue ;;
147
+ esac
148
+ staged="$stage_dir/$rel"
149
+ [ -f "$staged" ] || { echo "maestro-sync-commit: missing staged artifact: $rel" >&2; fail=1; continue; }
150
+ target="$dsh_root/$rel"
151
+ if [ "$expected" = "absent" ]; then
152
+ if [ -e "$target" ]; then
153
+ echo "CONCURRENT_MODIFICATION: $rel (target exists, expected absent)" >&2
154
+ fail=1
155
+ continue
156
+ fi
157
+ else
158
+ case "$expected" in
159
+ [0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]*) ;;
160
+ *) echo "maestro-sync-commit: invalid expected hash for $rel" >&2; fail=1; continue ;;
161
+ esac
162
+ if [ -f "$target" ]; then
163
+ actual=$(sha256sum "$target" 2>/dev/null | awk '{print $1}') || { echo "maestro-sync-commit: cannot hash $rel" >&2; fail=1; continue; }
164
+ if [ "$actual" != "$expected" ]; then
165
+ echo "CONCURRENT_MODIFICATION: $rel (target sha256 $actual != expected $expected)" >&2
166
+ fail=1
167
+ continue
168
+ fi
169
+ else
170
+ echo "CONCURRENT_MODIFICATION: $rel (target vanished)" >&2
171
+ fail=1
172
+ continue
173
+ fi
174
+ fi
175
+ if [ -f "$target" ]; then
176
+ bak="$target.bak.$(date +%s).$$"
177
+ if ! cp -p "$target" "$bak" 2>/dev/null; then
178
+ echo "maestro-sync-commit: backup failed for $rel" >&2
179
+ fail=1
180
+ continue
181
+ fi
182
+ fi
183
+ if ! mkdir -p "$(dirname -- "$target")" 2>/dev/null; then
184
+ echo "maestro-sync-commit: cannot create target dir for $rel" >&2
185
+ fail=1
186
+ continue
187
+ fi
188
+ if ! mv "$staged" "$target" 2>/dev/null; then
189
+ echo "maestro-sync-commit: publish failed for $rel" >&2
190
+ fail=1
191
+ continue
192
+ fi
193
+ echo "committed $rel"
194
+ done
195
+ [ "$fail" -eq 0 ] || exit 1
196
+ exit 0
197
+ `;
198
+ }
199
+ /**
200
+ * Structural verification of the helper source — used by tests and by
201
+ * `ensureAgent` before shipping the script to the remote host.
202
+ */
203
+ export function verifyRemoteAgentSource(src) {
204
+ if (!src.startsWith('#!/bin/sh'))
205
+ throw new Error('remote agent must be POSIX sh');
206
+ if (src.includes('[[ '))
207
+ throw new Error('remote agent must not use bash [[ ]]');
208
+ if (/\bfunction\s+/.test(src))
209
+ throw new Error('remote agent must not use bash function keyword');
210
+ if (!src.includes('CONCURRENT_MODIFICATION'))
211
+ throw new Error('remote agent must implement CAS');
212
+ if (!src.includes('.maestro-sync/stage/'))
213
+ throw new Error('remote agent must read staged artifacts');
214
+ if (!src.includes('sha256'))
215
+ throw new Error('remote agent must hash targets');
216
+ return src;
217
+ }
@@ -0,0 +1,18 @@
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;
@@ -0,0 +1,60 @@
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}/dsh-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
+ }
@@ -0,0 +1,8 @@
1
+ export interface RemoteManifestEntry {
2
+ path: string;
3
+ sha256: string;
4
+ size: number;
5
+ mtimeSec: number;
6
+ }
7
+ export declare function buildRemoteManifestScript(dshRoot: string): string;
8
+ export declare function parseRemoteManifest(buf: Buffer): RemoteManifestEntry[];
@@ -0,0 +1,64 @@
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
+ export function buildRemoteManifestScript(dshRoot) {
12
+ // Fixed script; dshRoot is the validated absolute root (same trust rule as transport.list).
13
+ // Cache-aware, READ-ONLY (spec §4.7 clarification, decision C): it consults
14
+ // <root>/.maestro-sync/fp.tsv and reuses a cached sha256 when the file's
15
+ // ino+size+mtimeNs+ctimeNs triple (GNU stat '%.Y'/'%.Z' ns fractions) still
16
+ // matches, skipping sha256sum for unchanged files. The cache is loaded ONCE
17
+ // in a single awk pass, read straight from the file inside awk (getline — a
18
+ // `-v cache=...` copy exceeds the 128 KiB per-arg limit once fp.tsv grows,
19
+ // E2BIG "Argument list too long", measured 2026-09-02); only MISS records are
20
+ // sha256sum'd in the bash loop. NEVER writes.
21
+ // Every loop-body statement must end with ';' — space-separated assignments
22
+ // inside a `do...done` one-liner break bash's parser (verified 2026-09-02).
23
+ const cache = remoteCachePath(dshRoot);
24
+ return [
25
+ `find ${dshRoot}/dsh-maestro-memory ${dshRoot}/sessions`,
26
+ `\\( -name node_modules -o -name .git -o -name .supervisor -o -name profiles \\) -prune -o -type f -print0`,
27
+ `| xargs -0 stat --printf='%i %s %.Y %.Z\\t%n\\n' 2>/dev/null`,
28
+ `| 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;}'`,
29
+ `| while IFS= read -r rec; do`,
30
+ `tag=\${rec%%$'\\t'*}; rest=\${rec#*$'\\t'};`,
31
+ `if [ "$tag" = "H" ]; then`,
32
+ `rel=\${rest%%$'\\t'*}; rest=\${rest#*$'\\t'}; sha=\${rest%%$'\\t'*}; rest=\${rest#*$'\\t'}; size=\${rest%%$'\\t'*}; mtime=\${rest#*$'\\t'};`,
33
+ `printf '%s\\t%s\\t%s\\t%s\\0' "$sha" "$size" "$mtime" "$rel";`,
34
+ `else`,
35
+ `rel=\${rest%%$'\\t'*}; st=\${rest#*$'\\t'};`,
36
+ `sha=$(sha256sum -- "${dshRoot}/$rel" 2>/dev/null | awk '{print $1}');`,
37
+ `set -- $st;`,
38
+ `printf '%s\\t%s\\t%s\\t%s\\0' "$sha" "$2" "$3" "$rel";`,
39
+ `fi;`,
40
+ `done`,
41
+ ].join(' ');
42
+ }
43
+ export function parseRemoteManifest(buf) {
44
+ const out = [];
45
+ const parts = buf.toString('utf-8').split('\0');
46
+ for (const part of parts) {
47
+ if (!part)
48
+ continue;
49
+ const [sha, sizeRaw, mtimeRaw, ...rest] = part.split('\t');
50
+ const p = rest.join('\t');
51
+ const size = Number(sizeRaw);
52
+ const mtimeSec = Number(mtimeRaw);
53
+ if (!sha || !p || !Number.isFinite(size) || !Number.isFinite(mtimeSec))
54
+ continue;
55
+ try {
56
+ normalizeEligiblePath(p);
57
+ }
58
+ catch {
59
+ continue; // ineligible — never enters the plan
60
+ }
61
+ out.push({ path: p, sha256: sha, size, mtimeSec });
62
+ }
63
+ return out.sort((a, b) => a.path.localeCompare(b.path));
64
+ }
@@ -0,0 +1,38 @@
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
+ }
@@ -0,0 +1,126 @@
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
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Union JSONL lines (or any line-delimited text) by exact line equality.
3
+ * Preserves local order then appends remote-only lines.
4
+ * Ensures trailing newline when result is non-empty.
5
+ */
6
+ export declare function mergeZstdLines(localText: string, remoteText: string): {
7
+ merged: string;
8
+ added: number;
9
+ };
10
+ /**
11
+ * Merge two valid DSH Zstandard session artifacts into the local artifact.
12
+ * The original local bytes are copied to a timestamped backup before the
13
+ * atomic publish. Invalid, missing, plaintext, or mismatched input never
14
+ * replaces the local file.
15
+ */
16
+ export declare function mergeZstdFiles(localPath: string, remotePath: string): Promise<{
17
+ added: number;
18
+ }>;