@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,68 @@
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
+
13
+ export const REMOTE_CACHE_REL = '.maestro-sync/fp.tsv';
14
+
15
+ export function remoteCachePath(dshRoot: string): string {
16
+ return `${dshRoot}/${REMOTE_CACHE_REL}`;
17
+ }
18
+
19
+ export interface FpCacheEntry {
20
+ ino: number;
21
+ size: number;
22
+ mtimeNs: string;
23
+ ctimeNs: string;
24
+ sha256: string;
25
+ }
26
+
27
+ /** Parse fp.tsv lines: `rel<TAB>ino<TAB>size<TAB>mtimeNs<TAB>ctimeNs<TAB>sha256`. */
28
+ export function parseFpCache(buf: Buffer): Map<string, FpCacheEntry> {
29
+ const out = new Map<string, FpCacheEntry>();
30
+ for (const line of buf.toString('utf-8').split('\n')) {
31
+ if (!line.trim()) continue;
32
+ const [rel, inoRaw, sizeRaw, mtimeNs, ctimeNs, sha256] = line.split('\t');
33
+ if (!rel || !sha256) continue;
34
+ try {
35
+ normalizeEligiblePath(rel);
36
+ } catch {
37
+ continue;
38
+ }
39
+ const ino = Number(inoRaw);
40
+ const size = Number(sizeRaw);
41
+ if (!Number.isFinite(ino) || !Number.isFinite(size)) continue;
42
+ out.set(rel, { ino, size, mtimeNs, ctimeNs, sha256 });
43
+ }
44
+ return out;
45
+ }
46
+
47
+ /**
48
+ * Warm script: re-hash every eligible file fresh and rewrite fp.tsv atomically
49
+ * (tmp + rename). Run ONLY from the push-apply path or an explicit warm
50
+ * command — never from preview. One stat batch via xargs keeps fork counts low;
51
+ * `set -- $st` splits the four stat fields (none contain whitespace).
52
+ */
53
+ export function buildWarmCacheScript(dshRoot: string): string {
54
+ const cache = remoteCachePath(dshRoot);
55
+ return [
56
+ `mkdir -p "${dshRoot}/.maestro-sync";`,
57
+ `find ${dshRoot}/dsh-maestro-memory ${dshRoot}/sessions`,
58
+ `\\( -name node_modules -o -name .git -o -name .supervisor -o -name profiles \\) -prune -o -type f -print0`,
59
+ `| xargs -0 stat --printf='%i %s %.Y %.Z\\t%n\\0' 2>/dev/null`,
60
+ `| while IFS= read -r -d '' rec; do`,
61
+ `st=\${rec%%$'\\t'*}; abs=\${rec#*$'\\t'}; rel=\${abs#${dshRoot}/};`,
62
+ `set -- $st;`,
63
+ `sha=$(sha256sum -- "${dshRoot}/$rel" 2>/dev/null | awk '{print $1}');`,
64
+ `printf '%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n' "$rel" "$1" "$2" "$3" "$4" "$sha";`,
65
+ `done > "${cache}.tmp.$$";`,
66
+ `mv "${cache}.tmp.$$" "${cache}";`,
67
+ ].join(' ');
68
+ }
@@ -0,0 +1,70 @@
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
+ export interface RemoteManifestEntry {
13
+ path: string;
14
+ sha256: string;
15
+ size: number;
16
+ mtimeSec: number;
17
+ }
18
+
19
+ export function buildRemoteManifestScript(dshRoot: string): string {
20
+ // Fixed script; dshRoot is the validated absolute root (same trust rule as transport.list).
21
+ // Cache-aware, READ-ONLY (spec §4.7 clarification, decision C): it consults
22
+ // <root>/.maestro-sync/fp.tsv and reuses a cached sha256 when the file's
23
+ // ino+size+mtimeNs+ctimeNs triple (GNU stat '%.Y'/'%.Z' ns fractions) still
24
+ // matches, skipping sha256sum for unchanged files. The cache is loaded ONCE
25
+ // in a single awk pass, read straight from the file inside awk (getline — a
26
+ // `-v cache=...` copy exceeds the 128 KiB per-arg limit once fp.tsv grows,
27
+ // E2BIG "Argument list too long", measured 2026-09-02); only MISS records are
28
+ // sha256sum'd in the bash loop. NEVER writes.
29
+ // Every loop-body statement must end with ';' — space-separated assignments
30
+ // inside a `do...done` one-liner break bash's parser (verified 2026-09-02).
31
+ const cache = remoteCachePath(dshRoot);
32
+ return [
33
+ `find ${dshRoot}/dsh-maestro-memory ${dshRoot}/sessions`,
34
+ `\\( -name node_modules -o -name .git -o -name .supervisor -o -name profiles \\) -prune -o -type f -print0`,
35
+ `| xargs -0 stat --printf='%i %s %.Y %.Z\\t%n\\n' 2>/dev/null`,
36
+ `| 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;}'`,
37
+ `| while IFS= read -r rec; do`,
38
+ `tag=\${rec%%$'\\t'*}; rest=\${rec#*$'\\t'};`,
39
+ `if [ "$tag" = "H" ]; then`,
40
+ `rel=\${rest%%$'\\t'*}; rest=\${rest#*$'\\t'}; sha=\${rest%%$'\\t'*}; rest=\${rest#*$'\\t'}; size=\${rest%%$'\\t'*}; mtime=\${rest#*$'\\t'};`,
41
+ `printf '%s\\t%s\\t%s\\t%s\\0' "$sha" "$size" "$mtime" "$rel";`,
42
+ `else`,
43
+ `rel=\${rest%%$'\\t'*}; st=\${rest#*$'\\t'};`,
44
+ `sha=$(sha256sum -- "${dshRoot}/$rel" 2>/dev/null | awk '{print $1}');`,
45
+ `set -- $st;`,
46
+ `printf '%s\\t%s\\t%s\\t%s\\0' "$sha" "$2" "$3" "$rel";`,
47
+ `fi;`,
48
+ `done`,
49
+ ].join(' ');
50
+ }
51
+
52
+ export function parseRemoteManifest(buf: Buffer): RemoteManifestEntry[] {
53
+ const out: RemoteManifestEntry[] = [];
54
+ const parts = buf.toString('utf-8').split('\0');
55
+ for (const part of parts) {
56
+ if (!part) continue;
57
+ const [sha, sizeRaw, mtimeRaw, ...rest] = part.split('\t');
58
+ const p = rest.join('\t');
59
+ const size = Number(sizeRaw);
60
+ const mtimeSec = Number(mtimeRaw);
61
+ if (!sha || !p || !Number.isFinite(size) || !Number.isFinite(mtimeSec)) continue;
62
+ try {
63
+ normalizeEligiblePath(p);
64
+ } catch {
65
+ continue; // ineligible — never enters the plan
66
+ }
67
+ out.push({ path: p, sha256: sha, size, mtimeSec });
68
+ }
69
+ return out.sort((a, b) => a.path.localeCompare(b.path));
70
+ }
@@ -0,0 +1,144 @@
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
+
12
+ export interface S3Config {
13
+ endpoint: string;
14
+ region: string;
15
+ accessKeyId: string;
16
+ secretAccessKey: string;
17
+ timeoutMs?: number;
18
+ }
19
+
20
+ export interface S3ListEntry {
21
+ key: string;
22
+ size: number;
23
+ lastModified: string;
24
+ }
25
+
26
+ export interface S3HeadResult {
27
+ size: number;
28
+ etag: string; // quotes stripped — a CAS token, not a content checksum
29
+ }
30
+
31
+ const EMPTY_SHA = sha256Hex('');
32
+
33
+ export class S3ObjectStore {
34
+ constructor(private readonly cfg: S3Config, private readonly f: typeof fetch = fetch) {}
35
+
36
+ private async request(
37
+ method: string,
38
+ bucket: string,
39
+ key: string,
40
+ opts: { query?: string; body?: Buffer; etag?: string; ifNoneMatch?: boolean } = {},
41
+ ): Promise<{ status: number; headers: Record<string, string>; body: Buffer }> {
42
+ const url = `${this.cfg.endpoint}/${bucket}${key ? '/' + key : ''}${opts.query ? '?' + opts.query : ''}`;
43
+ const host = new URL(this.cfg.endpoint).host;
44
+ const bodySha = opts.body ? sha256Hex(opts.body) : EMPTY_SHA;
45
+ const headers: Record<string, string> = { 'Content-Type': 'application/octet-stream' };
46
+ if (opts.body) headers['Content-Length'] = String(opts.body.length);
47
+ if (opts.etag) headers['If-Match'] = opts.etag;
48
+ if (opts.ifNoneMatch) headers['If-None-Match'] = '*';
49
+ const signed = signRequest({
50
+ method, host, path: `/${bucket}${key ? '/' + key : ''}`, query: opts.query,
51
+ headers, bodySha256: bodySha,
52
+ region: this.cfg.region, service: 's3',
53
+ accessKeyId: this.cfg.accessKeyId, secretAccessKey: this.cfg.secretAccessKey,
54
+ now: new Date(),
55
+ });
56
+ const controller = new AbortController();
57
+ const timer = setTimeout(() => controller.abort(), this.cfg.timeoutMs ?? 30_000);
58
+ try {
59
+ const res = await this.f(url, {
60
+ method,
61
+ headers: { ...headers, Authorization: signed.authorization, 'X-Amz-Date': signed.amzDate, 'X-Amz-Content-Sha256': signed.xAmzContentSha256 },
62
+ // Buffer satisfies BodyInit at runtime (undici accepts it); the TS overloads
63
+ // only admit Blob/string/URLSearchParams/ArrayBuffer — cast is intentional.
64
+ body: (opts.body as unknown as BodyInit) ?? undefined,
65
+ signal: controller.signal,
66
+ });
67
+ if (res.status === 412) {
68
+ return { status: 412, headers: {}, body: Buffer.alloc(0) };
69
+ }
70
+ if (res.status === 404 && method !== 'DELETE') {
71
+ return { status: 404, headers: {}, body: Buffer.alloc(0) };
72
+ }
73
+ if (res.status < 200 || res.status > 299) {
74
+ throw Object.assign(new Error(`S3 ${method} ${key} failed: ${res.status}`), { phase: 'backup', code: 'S3_ERROR' });
75
+ }
76
+ const body = Buffer.from(await res.arrayBuffer());
77
+ return { status: res.status, headers: Object.fromEntries(res.headers.entries()) as Record<string, string>, body };
78
+ } finally {
79
+ clearTimeout(timer);
80
+ }
81
+ }
82
+
83
+ async list(bucket: string, prefix: string): Promise<S3ListEntry[]> {
84
+ const out: S3ListEntry[] = [];
85
+ let token: string | undefined;
86
+ for (;;) {
87
+ const q = `list-type=2&prefix=${encodeURIComponent(prefix)}&max-keys=1000${token ? `&continuation-token=${encodeURIComponent(token)}` : ''}`;
88
+ const r = await this.request('GET', bucket, '', { query: q });
89
+ const xml = r.body.toString('utf-8');
90
+ const keys = [...xml.matchAll(/<Contents><Key>([^<]+)<\/Key><Size>(\d+)<\/Size><LastModified>([^<]+)<\/LastModified>/g)];
91
+ for (const m of keys) out.push({ key: m[1]!, size: Number(m[2]!), lastModified: m[3]! });
92
+ if (!xml.includes('<IsTruncated>true</IsTruncated>')) break;
93
+ const next = xml.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1];
94
+ if (!next) break;
95
+ token = next;
96
+ }
97
+ return out;
98
+ }
99
+
100
+ async head(bucket: string, key: string): Promise<S3HeadResult | null> {
101
+ const r = await this.request('HEAD', bucket, key);
102
+ if (r.status === 404) return null;
103
+ const etag = (r.headers['etag'] ?? '""').replace(/"/g, '');
104
+ return { size: Number(r.headers['content-length'] ?? 0), etag };
105
+ }
106
+
107
+ async get(bucket: string, key: string, destDir: string): Promise<S3HeadResult> {
108
+ const r = await this.request('GET', bucket, key);
109
+ const full = path.join(destDir, key);
110
+ fsMod.mkdirSync(path.dirname(full), { recursive: true });
111
+ fsMod.writeFileSync(full, r.body);
112
+ return { size: r.body.length, etag: (r.headers['etag'] ?? '""').replace(/"/g, '') };
113
+ }
114
+
115
+ /**
116
+ * If-None-Match:* put — idempotent blob semantics: a 412 (already present)
117
+ * is a silent no-op because blobs are content-addressed (same key ⇒ same
118
+ * bytes), so a retry never corrupts.
119
+ */
120
+ async putIfAbsent(bucket: string, key: string, body: Buffer): Promise<void> {
121
+ const r = await this.request('PUT', bucket, key, { body, ifNoneMatch: true });
122
+ if (r.status === 412) return;
123
+ }
124
+
125
+ /** CAS put: If-Match (or If-None-Match when the object must be absent); a 412 ⇒ CONCURRENT_MODIFICATION. */
126
+ async putConditional(bucket: string, key: string, body: Buffer, opts: { ifMatch?: string; ifNoneMatch?: boolean } = {}): Promise<void> {
127
+ const r = await this.request('PUT', bucket, key, { body, etag: opts.ifMatch, ifNoneMatch: opts.ifNoneMatch });
128
+ if (r.status === 412) {
129
+ throw Object.assign(new Error(`CONCURRENT_MODIFICATION: ${key}`), { phase: 'backup', code: 'CONCURRENT_MODIFICATION', detail: key });
130
+ }
131
+ }
132
+
133
+ /** Batched DeleteObjects (≤1000 keys per request). */
134
+ async deleteKeys(bucket: string, keys: string[]): Promise<void> {
135
+ for (let i = 0; i < keys.length; i += 1000) {
136
+ const batch = keys.slice(i, i + 1000);
137
+ const xml = `<?xml version="1.0"?><Delete>${batch
138
+ .map((k) => `<Object><Key>${k.replace(/&/g, '&amp;').replace(/</g, '&lt;')}</Key></Object>`)
139
+ .join('')}<Quiet>false</Quiet></Delete>`;
140
+ const r = await this.request('POST', bucket, '', { query: 'delete', body: Buffer.from(xml) });
141
+ if (r.status !== 200) throw Object.assign(new Error(`DeleteObjects failed: ${r.status}`), { phase: 'gc', code: 'S3_ERROR' });
142
+ }
143
+ }
144
+ }
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Session Zstandard line union. DSH session artifacts require the first
3
+ * checksummed Zstandard frame to contain exactly their JSONL header line.
4
+ * Binary-safe: .jsonl.zstd is staged and merged only through validated Zstd artifact API.
5
+ * Zstd bytes remain Buffer and are never converted to UTF-8 string; only decompressed
6
+ * plaintext is stringified for line union. The standalone checksummed header frame is preserved.
7
+ */
8
+ import { copyFile, open, readFile, rename, unlink } from 'node:fs/promises';
9
+ import { existsSync } from 'node:fs';
10
+ import { randomBytes } from 'node:crypto';
11
+ import { dirname } from 'node:path';
12
+ import { constants, zstdCompress, zstdDecompress } from 'node:zlib';
13
+ import { promisify } from 'node:util';
14
+
15
+ const ZSTD_MAGIC = 0xFD2FB528;
16
+ const compressZstd = promisify(zstdCompress);
17
+ const decompressZstd = promisify(zstdDecompress);
18
+ const ZSTD_CHECKSUM_OPTIONS = {
19
+ params: { [constants.ZSTD_c_checksumFlag]: 1 },
20
+ };
21
+
22
+ interface ZstdFrameRange {
23
+ start: number;
24
+ end: number;
25
+ }
26
+
27
+ interface SessionArtifact {
28
+ header: string;
29
+ text: string;
30
+ }
31
+
32
+ /**
33
+ * Union JSONL lines (or any line-delimited text) by exact line equality.
34
+ * Preserves local order then appends remote-only lines.
35
+ * Ensures trailing newline when result is non-empty.
36
+ */
37
+ export function mergeZstdLines(
38
+ localText: string,
39
+ remoteText: string,
40
+ ): { merged: string; added: number } {
41
+ const localLines = String(localText ?? '')
42
+ .split('\n')
43
+ .filter((line) => line.length > 0);
44
+ const remoteLines = String(remoteText ?? '')
45
+ .split('\n')
46
+ .filter((line) => line.length > 0);
47
+
48
+ const seen = new Set<string>(localLines);
49
+ const mergedArr = [...localLines];
50
+ let added = 0;
51
+
52
+ for (const line of remoteLines) {
53
+ if (!seen.has(line)) {
54
+ seen.add(line);
55
+ mergedArr.push(line);
56
+ added++;
57
+ }
58
+ }
59
+
60
+ const merged = mergedArr.length > 0 ? mergedArr.join('\n') + '\n' : '';
61
+ return { merged, added };
62
+ }
63
+
64
+ /** Locate complete normal Zstandard frames in a concatenated DSH artifact. */
65
+ function scanZstdFrames(source: Buffer): ZstdFrameRange[] {
66
+ const frames: ZstdFrameRange[] = [];
67
+ let offset = 0;
68
+
69
+ while (offset < source.length) {
70
+ const start = offset;
71
+ if (source.length - offset < 5 || source.readUInt32LE(offset) !== ZSTD_MAGIC) {
72
+ throw new Error('corrupt Zstandard session artifact');
73
+ }
74
+ offset += 4;
75
+ const descriptor = source.readUInt8(offset++);
76
+ if ((descriptor & 0x18) !== 0) throw new Error('corrupt Zstandard frame descriptor');
77
+
78
+ const contentSizeFlag = descriptor >>> 6;
79
+ const singleSegment = (descriptor & 0x20) !== 0;
80
+ const dictionaryFlag = descriptor & 0x03;
81
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag;
82
+ const contentSizeBytes = contentSizeFlag === 0
83
+ ? (singleSegment ? 1 : 0)
84
+ : 1 << contentSizeFlag;
85
+ const frameHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes;
86
+ if (source.length - offset < frameHeaderBytes) throw new Error('incomplete Zstandard frame header');
87
+ offset += frameHeaderBytes;
88
+
89
+ for (;;) {
90
+ if (source.length - offset < 3) throw new Error('incomplete Zstandard frame block');
91
+ const blockHeader = source.readUIntLE(offset, 3);
92
+ offset += 3;
93
+ const lastBlock = (blockHeader & 1) !== 0;
94
+ const blockType = (blockHeader >>> 1) & 0x03;
95
+ const blockSize = blockHeader >>> 3;
96
+ if (blockType === 3) throw new Error('corrupt Zstandard frame block');
97
+ const payloadBytes = blockType === 1 ? 1 : blockSize;
98
+ if (source.length - offset < payloadBytes) throw new Error('incomplete Zstandard frame payload');
99
+ offset += payloadBytes;
100
+ if (lastBlock) break;
101
+ }
102
+
103
+ if ((descriptor & 0x04) !== 0) {
104
+ if (source.length - offset < 4) throw new Error('incomplete Zstandard frame checksum');
105
+ offset += 4;
106
+ }
107
+ frames.push({ start, end: offset });
108
+ }
109
+
110
+ return frames;
111
+ }
112
+
113
+ function parseSessionHeader(header: Buffer, label: string): string {
114
+ if (header.length === 0 || header.indexOf(0x0A) !== header.length - 1) {
115
+ throw new Error(`${label} session artifact has no standalone header frame`);
116
+ }
117
+
118
+ const line = header.subarray(0, -1).toString('utf8');
119
+ let value: unknown;
120
+ try {
121
+ value = JSON.parse(line);
122
+ } catch {
123
+ throw new Error(`${label} session artifact has an invalid session header`);
124
+ }
125
+
126
+ const record = value as Record<string, unknown> | null;
127
+ const hasValidInteger = (field: 'createdAt' | 'delegationDepth') => {
128
+ const value = record?.[field];
129
+ return typeof value === 'number'
130
+ && Number.isSafeInteger(value)
131
+ && value >= 0
132
+ && !Object.is(value, -0);
133
+ };
134
+ if (
135
+ record === null
136
+ || typeof record !== 'object'
137
+ || record.type !== 'session'
138
+ || typeof record.version !== 'number'
139
+ || typeof record.id !== 'string'
140
+ || !hasValidInteger('createdAt')
141
+ || !hasValidInteger('delegationDepth')
142
+ || (record.origin !== undefined && record.origin !== 'subagent')
143
+ || (record.agentPreset !== undefined && typeof record.agentPreset !== 'string')
144
+ ) {
145
+ throw new Error(`${label} session artifact has an invalid session header`);
146
+ }
147
+ return line;
148
+ }
149
+
150
+ async function readSessionArtifact(filePath: string, label: string): Promise<SessionArtifact> {
151
+ if (!existsSync(filePath)) throw new Error(`${label} session artifact does not exist`);
152
+
153
+ const source = await readFile(filePath);
154
+ const frames = scanZstdFrames(source);
155
+ if (frames.length === 0) throw new Error(`${label} session artifact has no Zstandard frames`);
156
+
157
+ const headerBytes = await decompressZstd(source.subarray(frames[0]!.start, frames[0]!.end));
158
+ const header = parseSessionHeader(headerBytes, label);
159
+ const plaintext = await Promise.all(
160
+ frames.map(async ({ start, end }) => decompressZstd(source.subarray(start, end))),
161
+ );
162
+ return { header, text: Buffer.concat(plaintext).toString('utf8') };
163
+ }
164
+
165
+ async function writeAtomically(filePath: string, content: Buffer): Promise<void> {
166
+ const temporaryPath = `${filePath}.${randomBytes(12).toString('hex')}.tmp`;
167
+ const handle = await open(temporaryPath, 'wx', 0o600);
168
+ try {
169
+ await handle.writeFile(content);
170
+ await handle.sync();
171
+ } finally {
172
+ await handle.close();
173
+ }
174
+
175
+ try {
176
+ await rename(temporaryPath, filePath);
177
+ } catch (error) {
178
+ await unlink(temporaryPath).catch(() => undefined);
179
+ throw error;
180
+ }
181
+
182
+ const directory = await open(dirname(filePath), 'r');
183
+ try {
184
+ await directory.sync();
185
+ } finally {
186
+ await directory.close();
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Merge two valid DSH Zstandard session artifacts into the local artifact.
192
+ * The original local bytes are copied to a timestamped backup before the
193
+ * atomic publish. Invalid, missing, plaintext, or mismatched input never
194
+ * replaces the local file.
195
+ */
196
+ export async function mergeZstdFiles(
197
+ localPath: string,
198
+ remotePath: string,
199
+ ): Promise<{ added: number }> {
200
+ const local = await readSessionArtifact(localPath, 'local');
201
+ const remote = await readSessionArtifact(remotePath, 'remote');
202
+ if (local.header !== remote.header) {
203
+ throw new Error('cannot merge session artifacts with different headers');
204
+ }
205
+
206
+ const { merged, added } = mergeZstdLines(local.text, remote.text);
207
+ if (added === 0) return { added: 0 };
208
+ if (!merged.startsWith(local.header + '\n')) {
209
+ throw new Error('merged session artifact lost its header');
210
+ }
211
+
212
+ const body = merged.slice(local.header.length + 1);
213
+ const frames = [await compressZstd(local.header + '\n', ZSTD_CHECKSUM_OPTIONS)];
214
+ if (body.length > 0) frames.push(await compressZstd(body, ZSTD_CHECKSUM_OPTIONS));
215
+ const backupPath = `${localPath}.bak.${Date.now()}.${randomBytes(6).toString('hex')}`;
216
+ await copyFile(localPath, backupPath);
217
+ await writeAtomically(localPath, Buffer.concat(frames));
218
+
219
+ return { added };
220
+ }