@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,159 @@
1
+ // src/host/backup-config.ts — backup target config + secret resolution.
2
+ //
3
+ // Non-secret config comes from the shared settings store (domains.sync.r2.*);
4
+ // secret material never lives in settings, never is logged, and never crosses
5
+ // RPC/tools — resolution order: environment first, then a private 0600 sidecar
6
+ // in the plugin's own runtime directory (outside the eligible data boundary,
7
+ // so the merge CLI never reads or syncs it). Status surfaces only the source
8
+ // label, the bucket, the prefix and the provider.
9
+ import { createHash } from 'node:crypto';
10
+ import * as os from 'node:os';
11
+ import * as nodeFs from 'node:fs';
12
+ import * as nodePath from 'node:path';
13
+ import { load } from '../store/index.js';
14
+
15
+ export interface BackupProviderConfig {
16
+ provider: 'r2' | 'aws';
17
+ endpoint: string;
18
+ region: string;
19
+ bucket: string;
20
+ prefix: string;
21
+ }
22
+
23
+ export interface BackupSecrets {
24
+ accessKeyId: string;
25
+ secretAccessKey: string;
26
+ }
27
+
28
+ export interface BackupTarget {
29
+ provider: 'r2' | 'aws';
30
+ bucket: string;
31
+ prefix: string;
32
+ hostId: string;
33
+ }
34
+
35
+ export type SecretSource = 'env' | 'file' | 'none';
36
+
37
+ export const BACKUP_SIDECAR_REL = 'dsh-maestro-sync/backup-secrets.json';
38
+
39
+ export function describeSecretSource(env: Record<string, string | undefined>, sidecarPath: string): SecretSource {
40
+ if ((env.R2_ACCESS_KEY_ID && env.R2_SECRET_ACCESS_KEY) || (env.AWS_ACCESS_KEY_ID && env.AWS_SECRET_ACCESS_KEY)) return 'env';
41
+ try {
42
+ if (nodeFs.existsSync(sidecarPath)) return 'file';
43
+ } catch {}
44
+ return 'none';
45
+ }
46
+
47
+ export async function resolveBackupTarget(
48
+ doc: { domains?: { sync?: { r2?: Record<string, unknown> } } } = {},
49
+ env: Record<string, string | undefined> = process.env as any,
50
+ dshHome: string = process.env.DSH_HOME || nodePath.join(os.homedir(), '.dsh'),
51
+ ): Promise<{ config: BackupProviderConfig; secrets: BackupSecrets; source: SecretSource }> {
52
+ const sync = doc.domains?.sync as Record<string, any> | undefined;
53
+ const r2 = (sync?.r2 ?? {}) as Record<string, any>;
54
+ const provider = (r2.provider as string | undefined) === 'aws' ? 'aws' : 'r2';
55
+ const accountId = (r2.accountId as string | undefined) ?? '';
56
+ const bucket = (r2.bucket as string | undefined) ?? 'maestro-backup';
57
+ const hostId = createHash('sha256').update(os.hostname()).digest('hex').slice(0, 12);
58
+ const prefix = (r2.prefix as string | undefined) ?? `v1/hosts/${hostId}/`;
59
+ const region = (r2.region as string | undefined) ?? (provider === 'r2' ? 'auto' : '');
60
+ const endpoint = (r2.endpoint as string | undefined) ?? (provider === 'r2' ? `https://${accountId}.r2.cloudflarestorage.com` : '');
61
+
62
+ const sidecar = nodePath.join(dshHome, BACKUP_SIDECAR_REL);
63
+ let secrets: BackupSecrets | null = null;
64
+ let source: SecretSource = 'none';
65
+ if (env.R2_ACCESS_KEY_ID && env.R2_SECRET_ACCESS_KEY) {
66
+ secrets = { accessKeyId: env.R2_ACCESS_KEY_ID, secretAccessKey: env.R2_SECRET_ACCESS_KEY };
67
+ source = 'env';
68
+ } else if (env.AWS_ACCESS_KEY_ID && env.AWS_SECRET_ACCESS_KEY) {
69
+ secrets = { accessKeyId: env.AWS_ACCESS_KEY_ID, secretAccessKey: env.AWS_SECRET_ACCESS_KEY };
70
+ source = 'env';
71
+ } else {
72
+ try {
73
+ const raw = nodeFs.readFileSync(sidecar, 'utf-8') as string;
74
+ const parsed = JSON.parse(raw) as { accessKeyId?: string; secretAccessKey?: string };
75
+ if (parsed.accessKeyId && parsed.secretAccessKey) {
76
+ secrets = { accessKeyId: parsed.accessKeyId, secretAccessKey: parsed.secretAccessKey };
77
+ source = 'file';
78
+ }
79
+ } catch {}
80
+ }
81
+ if (!secrets) {
82
+ throw Object.assign(
83
+ new Error(
84
+ 'backup requires access key secret material: set R2_ACCESS_KEY_ID + R2_SECRET_ACCESS_KEY '
85
+ + '(or AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY) in the environment, '
86
+ + `or write a 0600 ${sidecar}`,
87
+ ),
88
+ {
89
+ phase: 'validate',
90
+ code: 'MISSING_BACKUP_SECRETS',
91
+ },
92
+ );
93
+ }
94
+ return { config: { provider, endpoint, region, bucket, prefix }, secrets, source };
95
+ }
96
+
97
+ export interface R2ConfigInput {
98
+ provider?: unknown;
99
+ accountId?: unknown;
100
+ endpoint?: unknown;
101
+ region?: unknown;
102
+ bucket?: unknown;
103
+ prefix?: unknown;
104
+ }
105
+
106
+ export interface NormalizedR2Config {
107
+ provider: 'r2' | 'aws';
108
+ accountId: string;
109
+ endpoint: string;
110
+ region: string;
111
+ bucket: string;
112
+ prefix: string;
113
+ }
114
+
115
+ const SHELL_META_RE = /[;`$|&><*?'"\\(){}!\s=]/;
116
+ const BUCKET_RE = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/;
117
+ const REGION_RE = /^[A-Za-z0-9-]{1,32}$/;
118
+ const ACCOUNT_RE = /^[0-9a-f]{32}$/i;
119
+ const PREFIX_SEG_RE = /^[A-Za-z0-9._-]{1,64}$/;
120
+
121
+ /**
122
+ * Validate + normalize non-secret R2/S3 config from the Settings UI.
123
+ * Fail-closed: throws on the first invalid field. Empty strings mean
124
+ * "use the default" and are stripped so built-in fallbacks keep working.
125
+ * Secret material is never accepted here — keys live in env or the 0600
126
+ * sidecar only.
127
+ */
128
+ export function validateR2ConfigInput(input: R2ConfigInput): NormalizedR2Config {
129
+ const str = (v: unknown): string => (typeof v === 'string' ? v.trim() : '');
130
+ const provider = str(input.provider) || 'r2';
131
+ if (provider !== 'r2' && provider !== 'aws') throw new Error(`invalid provider: ${JSON.stringify(provider)} (want 'r2'|'aws')`);
132
+ const accountId = str(input.accountId);
133
+ if (accountId && !ACCOUNT_RE.test(accountId)) throw new Error('invalid accountId: want 32 hex chars');
134
+ if (provider === 'aws' && accountId) throw new Error('invalid accountId: only meaningful for provider r2');
135
+ const endpoint = str(input.endpoint);
136
+ if (endpoint) {
137
+ if (SHELL_META_RE.test(endpoint) || endpoint.length > 256) throw new Error('invalid endpoint: illegal characters');
138
+ if (!/^https:\/\/[A-Za-z0-9.-]+(?::\d+)?(?:\/[A-Za-z0-9._~:/?#[\]@!$&'()*+,;=-]*)?$/.test(endpoint)) {
139
+ throw new Error('invalid endpoint: want an https:// URL');
140
+ }
141
+ }
142
+ const region = str(input.region);
143
+ if (region && !REGION_RE.test(region)) throw new Error(`invalid region: ${JSON.stringify(region)}`);
144
+ const bucket = str(input.bucket);
145
+ if (!bucket) throw new Error('bucket is required');
146
+ if (!BUCKET_RE.test(bucket)) throw new Error(`invalid bucket: ${JSON.stringify(bucket)} (3-63 lowercase letters/digits/dots/hyphens)`);
147
+ let prefix = str(input.prefix);
148
+ if (!prefix) throw new Error('prefix is required');
149
+ if (prefix.startsWith('/') || prefix.includes('\\') || prefix.includes('..') || /[\u0000-\u001f\u007f]/.test(prefix)) {
150
+ throw new Error(`invalid prefix: ${JSON.stringify(prefix)}`);
151
+ }
152
+ if (!prefix.endsWith('/')) prefix += '/';
153
+ const segs = prefix.split('/').filter((s) => s.length > 0);
154
+ if (segs.length === 0 || segs.length > 8 || !segs.every((s) => PREFIX_SEG_RE.test(s))) {
155
+ throw new Error(`invalid prefix: ${JSON.stringify(prefix)}`);
156
+ }
157
+ if (prefix.length > 200) throw new Error('invalid prefix: too long');
158
+ return { provider, accountId, endpoint, region, bucket, prefix };
159
+ }
@@ -0,0 +1,453 @@
1
+ // src/host/backup-service.ts — R2/S3 backup engine (spec §5.4–§5.6, decision C).
2
+ //
3
+ // Layout: blobs/sha256/<sha> (immutable, content-addressed) + manifests/<ts>-<id>
4
+ // (immutable snapshot) + HEAD (CAS pointer). preview() is READ-ONLY: it compares
5
+ // the current eligible local hashes against the HEAD manifest (no object
6
+ // download, no upload). apply() is the only bucket-mutation route: PUT missing
7
+ // blobs (idempotent by sha) → PUT a fresh immutable manifest → CAS-advance HEAD.
8
+ // Restore and GC arrive in later tasks of the same module.
9
+ import * as nodeFs from 'node:fs';
10
+ import * as path from 'node:path';
11
+ import { randomBytes, createHash } from 'node:crypto';
12
+ import { normalizeEligiblePath } from './validation.js';
13
+ import { hashFiles } from './hashing.js';
14
+ import { loadIndex, saveIndex, probeIndex, matchesStat, statFingerprint } from './fingerprint.js';
15
+ import type { S3ObjectStore } from './s3-object-store.js';
16
+ import type { BackupTarget } from './backup-config.js';
17
+
18
+ export interface BackupManifestFile {
19
+ path: string;
20
+ sha256: string;
21
+ size: number;
22
+ blobKey: string;
23
+ }
24
+
25
+ export interface BackupManifest {
26
+ schema: 1;
27
+ hostId: string;
28
+ createdAt: string;
29
+ files: BackupManifestFile[];
30
+ }
31
+
32
+ export interface BackupPreview {
33
+ previewId: string;
34
+ revision: string;
35
+ expiresAt: string;
36
+ summary: { identical: number; missing: number; addedBytes: number };
37
+ }
38
+
39
+ export interface BackupApplyResult {
40
+ ok: boolean;
41
+ revision: string;
42
+ committed: string[];
43
+ failures: SyncFailureLike[];
44
+ }
45
+
46
+ // Minimal failure shape (mirrors SyncFailure without importing the sync module graph).
47
+ export interface SyncFailureLike {
48
+ phase: string;
49
+ code: string;
50
+ detail: string;
51
+ path?: string;
52
+ }
53
+
54
+ const TTL_MS = 60_000;
55
+
56
+ export class BackupService {
57
+ constructor(private readonly opts: { localDsh: string; store: S3ObjectStore; target: BackupTarget; previewDir: string; cacheDir: string; fs?: any }) {}
58
+
59
+ blobKey(sha: string): string {
60
+ return `blobs/sha256/${sha}`;
61
+ }
62
+
63
+ listEligibleFiles(): string[] {
64
+ const root = this.opts.localDsh;
65
+ const fsMod = this.opts.fs ?? nodeFs;
66
+ const out: string[] = [];
67
+ const walk = (dir: string) => {
68
+ let ents: any[];
69
+ try {
70
+ ents = fsMod.readdirSync(dir, { withFileTypes: true });
71
+ } catch {
72
+ return;
73
+ }
74
+ for (const ent of ents) {
75
+ const full = path.join(dir, ent.name);
76
+ if (typeof ent.isDirectory === 'function' && ent.isDirectory()) {
77
+ if (!['node_modules', '.git', '.supervisor', 'profiles'].includes(ent.name)) walk(full);
78
+ } else {
79
+ const rel = full.slice(root.length + 1).split(path.sep).join('/');
80
+ try {
81
+ normalizeEligiblePath(rel);
82
+ out.push(rel);
83
+ } catch {}
84
+ }
85
+ }
86
+ };
87
+ try {
88
+ walk(path.join(root, 'dsh-maestro-memory'));
89
+ walk(path.join(root, 'sessions'));
90
+ } catch {}
91
+ return out.sort();
92
+ }
93
+
94
+ async readHeadManifest(): Promise<{ key: string; manifest: BackupManifest } | null> {
95
+ const headKey = `${this.opts.target.prefix}HEAD`;
96
+ const head = await this.opts.store.head(this.opts.target.bucket, headKey);
97
+ if (!head) return null;
98
+ const tmp = path.join(require('node:os').tmpdir(), `bk-head-${randomBytes(4).toString('hex')}`);
99
+ nodeFs.mkdirSync(tmp, { recursive: true });
100
+ try {
101
+ await this.opts.store.get(this.opts.target.bucket, headKey, tmp);
102
+ const headBody = JSON.parse(nodeFs.readFileSync(path.join(tmp, headKey), 'utf-8')) as { manifestKey: string };
103
+ await this.opts.store.get(this.opts.target.bucket, headBody.manifestKey, tmp);
104
+ const manifest = JSON.parse(nodeFs.readFileSync(path.join(tmp, headBody.manifestKey), 'utf-8')) as BackupManifest;
105
+ return { key: headBody.manifestKey, manifest };
106
+ } finally {
107
+ try {
108
+ nodeFs.rmSync(tmp, { recursive: true, force: true });
109
+ } catch {}
110
+ }
111
+ }
112
+
113
+ private async localHashes(): Promise<{ path: string; sha256: string; size: number }[]> {
114
+ const fsMod = this.opts.fs ?? nodeFs;
115
+ const paths = this.listEligibleFiles();
116
+ const index = loadIndex(this.opts.cacheDir);
117
+ const stale: string[] = [];
118
+ const local: { path: string; sha256: string; size: number }[] = [];
119
+ for (const rel of paths) {
120
+ const full = path.join(this.opts.localDsh, rel);
121
+ try {
122
+ const st = fsMod.statSync(full, { bigint: true } as any);
123
+ const e = probeIndex(rel, index);
124
+ if (e && matchesStat(e, st)) local.push({ path: rel, sha256: e.sha256, size: e.size });
125
+ else stale.push(rel);
126
+ } catch {
127
+ stale.push(rel);
128
+ }
129
+ }
130
+ const hashed = await hashFiles(fsMod, this.opts.localDsh, stale);
131
+ for (const f of hashed) {
132
+ local.push({ path: f.path, sha256: f.sha256, size: f.size });
133
+ try {
134
+ const st = fsMod.statSync(path.join(this.opts.localDsh, f.path), { bigint: true } as any);
135
+ index.entries[f.path] = { ...statFingerprint(st), sha256: f.sha256 };
136
+ } catch {}
137
+ }
138
+ if (hashed.length > 0) saveIndex(this.opts.cacheDir, index);
139
+ return local.sort((a, b) => a.path.localeCompare(b.path));
140
+ }
141
+
142
+ async preview(fileList?: { path: string; sha256: string; size: number }[]): Promise<BackupPreview> {
143
+ // fileList override exists for tests; production uses the fresh local hashes.
144
+ const local = fileList ?? (await this.localHashes());
145
+ const prev = await this.readHeadManifest();
146
+ const prevByPath = new Map((prev?.manifest.files ?? []).map((f) => [f.path, f]));
147
+ let identical = 0;
148
+ let missing = 0;
149
+ let addedBytes = 0;
150
+ for (const f of local) {
151
+ const p = prevByPath.get(f.path);
152
+ if (p && p.sha256 === f.sha256) identical++;
153
+ else {
154
+ missing++;
155
+ addedBytes += f.size;
156
+ }
157
+ }
158
+ const previewId = randomBytes(16).toString('hex');
159
+ const preview: BackupPreview = {
160
+ previewId,
161
+ revision: createHash('sha256').update(JSON.stringify(local)).digest('hex').slice(0, 16),
162
+ expiresAt: new Date(Date.now() + TTL_MS).toISOString(),
163
+ summary: { identical, missing, addedBytes },
164
+ };
165
+ nodeFs.mkdirSync(this.opts.previewDir, { recursive: true, mode: 0o700 });
166
+ nodeFs.writeFileSync(path.join(this.opts.previewDir, `${previewId}.backup.json`), JSON.stringify(preview), 'utf-8');
167
+ return preview;
168
+ }
169
+
170
+ /**
171
+ * Backup apply — the ONLY bucket-mutation route (spec §5.5):
172
+ * 1. load the persisted preview (single-use, 60s TTL);
173
+ * 2. re-hash local (freshest) and compare against the current HEAD manifest;
174
+ * 3. PUT missing blobs (putIfAbsent — idempotent by content-addressing);
175
+ * 4. PUT a new immutable manifest (unique key);
176
+ * 5. CAS-advance HEAD (If-Match old etag / If-None-Match when absent).
177
+ * ok:true only after HEAD advances; blob PUTs are retry-safe.
178
+ */
179
+ async apply(req: { previewId: string; confirm: true }): Promise<BackupApplyResult> {
180
+ if (req.confirm !== true) {
181
+ throw Object.assign(new Error('backup apply requires confirm:true'), { phase: 'validate', code: 'CONFIRM_REQUIRED' });
182
+ }
183
+ const pvPath = path.join(this.opts.previewDir, `${req.previewId}.backup.json`);
184
+ let saved: BackupPreview;
185
+ try {
186
+ saved = JSON.parse(nodeFs.readFileSync(pvPath, 'utf-8')) as BackupPreview;
187
+ } catch {
188
+ throw Object.assign(new Error('backup preview not found or expired'), { phase: 'validate', code: 'STALE_PREVIEW' });
189
+ }
190
+ if (new Date(saved.expiresAt).getTime() <= Date.now()) {
191
+ try {
192
+ nodeFs.rmSync(pvPath, { force: true });
193
+ } catch {}
194
+ throw Object.assign(new Error('backup preview expired'), { phase: 'validate', code: 'STALE_PREVIEW' });
195
+ }
196
+
197
+ const failures: SyncFailureLike[] = [];
198
+ const committed: string[] = [];
199
+ let fresh: BackupPreview;
200
+ try {
201
+ fresh = await this.preview();
202
+ } catch (e: any) {
203
+ // The store is unreachable/broken: fail closed with a structured journal —
204
+ // apply must never throw a raw network error after the preview gate.
205
+ try {
206
+ nodeFs.rmSync(pvPath, { force: true });
207
+ } catch {}
208
+ return { ok: false, revision: saved.revision, committed: [], failures: [{ phase: 'backup', code: 'PREVIEW_REFRESH_FAILED', detail: e?.message ?? String(e) }] };
209
+ }
210
+ const prev = await this.readHeadManifest();
211
+ const prevByPath = new Map((prev?.manifest.files ?? []).map((f) => [f.path, f]));
212
+ const localPaths = this.listEligibleFiles();
213
+ const files: BackupManifestFile[] = [];
214
+ const fsMod = this.opts.fs ?? nodeFs;
215
+ for (const rel of localPaths) {
216
+ const prevFile = prevByPath.get(rel);
217
+ // Fast path: bytes already backed up under the same sha — reuse, skip read+PUT.
218
+ const index = loadIndex(this.opts.cacheDir);
219
+ const entry = probeIndex(rel, index);
220
+ let sha: string | null = null;
221
+ let size = 0;
222
+ if (entry && prevFile && entry.sha256 === prevFile.sha256) {
223
+ sha = entry.sha256;
224
+ size = entry.size;
225
+ }
226
+ if (sha === null) {
227
+ try {
228
+ const buf = fsMod.readFileSync(path.join(this.opts.localDsh, rel));
229
+ const b = Buffer.isBuffer(buf) ? buf : Buffer.from(String(buf), 'utf-8');
230
+ sha = createHash('sha256').update(b).digest('hex');
231
+ size = b.length;
232
+ const key = `${this.opts.target.prefix}${this.blobKey(sha)}`;
233
+ try {
234
+ await this.opts.store.putIfAbsent(this.opts.target.bucket, key, b);
235
+ } catch (e: any) {
236
+ failures.push({ phase: 'backup', code: 'UPLOAD_FAILED', detail: e?.message ?? String(e), path: rel });
237
+ continue;
238
+ }
239
+ } catch (e: any) {
240
+ failures.push({ phase: 'backup', code: 'READ_FAILED', detail: e?.message ?? String(e), path: rel });
241
+ continue;
242
+ }
243
+ }
244
+ files.push({ path: rel, sha256: sha, size, blobKey: this.blobKey(sha) });
245
+ }
246
+ void fresh;
247
+
248
+ if (failures.length === 0) {
249
+ const ts = new Date().toISOString().replace(/[:.]/g, '-');
250
+ const manifest: BackupManifest = { schema: 1, hostId: this.opts.target.hostId, createdAt: new Date().toISOString(), files };
251
+ const manifestKey = `${this.opts.target.prefix}manifests/${ts}-${randomBytes(4).toString('hex')}.json`;
252
+ try {
253
+ await this.opts.store.putIfAbsent(this.opts.target.bucket, manifestKey, Buffer.from(JSON.stringify(manifest)));
254
+ } catch (e: any) {
255
+ failures.push({ phase: 'backup', code: 'MANIFEST_PUT_FAILED', detail: e?.message ?? String(e), path: manifestKey });
256
+ }
257
+ if (failures.length === 0) {
258
+ const headKey = `${this.opts.target.prefix}HEAD`;
259
+ const old = await this.opts.store.head(this.opts.target.bucket, headKey);
260
+ try {
261
+ await this.opts.store.putConditional(this.opts.target.bucket, headKey, Buffer.from(JSON.stringify({ manifestKey })), old ? { ifMatch: old.etag } : { ifNoneMatch: true });
262
+ committed.push(...files.map((f) => f.path));
263
+ } catch (e: any) {
264
+ failures.push({ phase: 'backup', code: e?.code === 'CONCURRENT_MODIFICATION' ? 'CONCURRENT_MODIFICATION' : 'HEAD_UPDATE_FAILED', detail: e?.message ?? String(e), path: headKey });
265
+ }
266
+ }
267
+ }
268
+ try {
269
+ nodeFs.rmSync(pvPath, { force: true });
270
+ } catch {}
271
+ return { ok: failures.length === 0, revision: saved.revision, committed, failures };
272
+ }
273
+
274
+ // ---- restore (spec §5.6): preview read-only; apply is the only mutation ----
275
+
276
+ async restorePreview(opts: { mode: 'new-dir' | 'in-place' }): Promise<{ previewId: string; expiresAt: string; mode: 'new-dir' | 'in-place'; summary: { copied: number; merged: number; skipped: number; conflicts: number } }> {
277
+ const head = await this.readHeadManifest();
278
+ if (!head) throw Object.assign(new Error('no backup to restore (no HEAD)'), { phase: 'restore', code: 'NO_BACKUP' });
279
+ const fsMod = this.opts.fs ?? nodeFs;
280
+ let copied = 0;
281
+ let merged = 0;
282
+ let skipped = 0;
283
+ let conflicts = 0;
284
+ for (const f of head.manifest.files) {
285
+ if (opts.mode === 'new-dir') {
286
+ copied++;
287
+ continue;
288
+ }
289
+ const full = path.join(this.opts.localDsh, f.path);
290
+ let cur: string | null = null;
291
+ try {
292
+ cur = createHash('sha256').update(fsMod.readFileSync(full)).digest('hex');
293
+ } catch {}
294
+ if (cur === f.sha256) skipped++;
295
+ else if (cur === null) copied++;
296
+ else merged++;
297
+ }
298
+ const previewId = randomBytes(16).toString('hex');
299
+ const preview = { previewId, expiresAt: new Date(Date.now() + TTL_MS).toISOString(), mode: opts.mode, summary: { copied, merged, skipped, conflicts } };
300
+ nodeFs.writeFileSync(path.join(this.opts.previewDir, `${previewId}.restore.json`), JSON.stringify(preview), 'utf-8');
301
+ return preview;
302
+ }
303
+
304
+ async restoreApply(req: { previewId: string; mode: 'new-dir' | 'in-place'; destDir?: string; confirm: true }): Promise<BackupApplyResult> {
305
+ if (req.confirm !== true) throw Object.assign(new Error('restore apply requires confirm:true'), { phase: 'validate', code: 'CONFIRM_REQUIRED' });
306
+ const pvPath = path.join(this.opts.previewDir, `${req.previewId}.restore.json`);
307
+ let saved: { mode: 'new-dir' | 'in-place' };
308
+ try {
309
+ saved = JSON.parse(nodeFs.readFileSync(pvPath, 'utf-8')) as { mode: 'new-dir' | 'in-place' };
310
+ } catch {
311
+ throw Object.assign(new Error('restore preview not found or expired'), { phase: 'validate', code: 'STALE_PREVIEW' });
312
+ }
313
+ if (saved.mode !== req.mode) throw Object.assign(new Error('restore preview mode mismatch'), { phase: 'validate', code: 'DIRECTION_MISMATCH' });
314
+ const head = await this.readHeadManifest();
315
+ if (!head) throw Object.assign(new Error('no backup to restore (no HEAD)'), { phase: 'restore', code: 'NO_BACKUP' });
316
+ const fsMod = this.opts.fs ?? nodeFs;
317
+ const tmp = path.join(require('node:os').tmpdir(), `restore-${randomBytes(4).toString('hex')}`);
318
+ nodeFs.mkdirSync(tmp, { recursive: true });
319
+ const failures: SyncFailureLike[] = [];
320
+ const committed: string[] = [];
321
+ try {
322
+ for (const f of head.manifest.files) {
323
+ try {
324
+ const destBase = req.mode === 'new-dir' ? req.destDir ?? path.join(this.opts.localDsh, 'restored') : this.opts.localDsh;
325
+ const outFull = path.join(destBase, f.path);
326
+ if (req.mode === 'in-place') {
327
+ try {
328
+ const cur = createHash('sha256').update(fsMod.readFileSync(outFull)).digest('hex');
329
+ if (cur === f.sha256) continue; // byte-identical: skip
330
+ } catch {}
331
+ }
332
+ const fullKey = `${this.opts.target.prefix}${f.blobKey}`;
333
+ await this.opts.store.get(this.opts.target.bucket, fullKey, tmp);
334
+ const staged = path.join(tmp, fullKey);
335
+ const buf = fsMod.readFileSync(staged);
336
+ if (createHash('sha256').update(buf).digest('hex') !== f.sha256) {
337
+ throw Object.assign(new Error('blob checksum mismatch'), { phase: 'restore', code: 'CHECKSUM_MISMATCH' });
338
+ }
339
+ // In-place: keep a timestamped backup of the target before overwrite.
340
+ if (req.mode === 'in-place' && fsMod.existsSync(outFull)) {
341
+ const bak = `${outFull}.bak.${Date.now()}.${randomBytes(4).toString('hex')}`;
342
+ fsMod.writeFileSync(bak, fsMod.readFileSync(outFull));
343
+ }
344
+ fsMod.mkdirSync(path.dirname(outFull), { recursive: true });
345
+ const tmpFile = `${outFull}.tmp.${randomBytes(4).toString('hex')}`;
346
+ fsMod.writeFileSync(tmpFile, buf);
347
+ try {
348
+ const fd = fsMod.openSync(tmpFile, 'r');
349
+ try {
350
+ fsMod.fsyncSync(fd);
351
+ } finally {
352
+ fsMod.closeSync(fd);
353
+ }
354
+ } catch {}
355
+ fsMod.renameSync(tmpFile, outFull);
356
+ committed.push(f.path);
357
+ } catch (e: any) {
358
+ failures.push({ phase: 'restore', code: e?.code ?? 'RESTORE_FAILED', detail: e?.message ?? String(e), path: f.path });
359
+ }
360
+ }
361
+ } finally {
362
+ try {
363
+ nodeFs.rmSync(tmp, { recursive: true, force: true });
364
+ } catch {}
365
+ }
366
+ try {
367
+ nodeFs.rmSync(pvPath, { force: true });
368
+ } catch {}
369
+ return { ok: failures.length === 0, revision: '', committed, failures };
370
+ }
371
+
372
+ // ---- retention GC (spec §5.7): preview read-only; apply deletes unreachable blobs ----
373
+
374
+ async gcPreview(opts: { keepDaily?: number; keepMonthly?: number } = {}): Promise<{
375
+ retainedManifests: number;
376
+ trashManifests: number;
377
+ deletableBlobs: string[];
378
+ freedBytes: number;
379
+ previewId: string;
380
+ }> {
381
+ const prefix = this.opts.target.prefix;
382
+ const all = (await this.opts.store.list(this.opts.target.bucket, `${prefix}manifests/`)).map((e) => e.key);
383
+ const byDay = new Map<string, string>();
384
+ const byMonth = new Map<string, string>();
385
+ for (const key of all) {
386
+ const head = await this.readManifestKey(key);
387
+ const d = head.createdAt;
388
+ const day = d.slice(0, 10);
389
+ const month = d.slice(0, 7);
390
+ const curDay = byDay.get(day);
391
+ if (!curDay || key > curDay) byDay.set(day, key);
392
+ const curMonth = byMonth.get(month);
393
+ if (!curMonth || key > curMonth) byMonth.set(month, key);
394
+ }
395
+ const keepDaily = opts.keepDaily ?? 30;
396
+ const keepMonthly = opts.keepMonthly ?? 12;
397
+ const days = [...byDay.keys()].sort().slice(-keepDaily);
398
+ const months = [...byMonth.keys()].sort().slice(-keepMonthly);
399
+ const retained = new Set<string>();
400
+ for (const d of days) retained.add(byDay.get(d)!);
401
+ for (const m of months) retained.add(byMonth.get(m)!);
402
+
403
+ const reachable = new Set<string>();
404
+ for (const key of retained) {
405
+ const m = await this.readManifestKey(key);
406
+ for (const f of m.files) reachable.add(this.blobKey(f.sha256));
407
+ }
408
+ const allBlobs = (await this.opts.store.list(this.opts.target.bucket, `${prefix}blobs/`)).map((e) => e.key.replace(prefix, ''));
409
+ const deletable = allBlobs.filter((k) => !reachable.has(k));
410
+ let freedBytes = 0;
411
+ for (const k of deletable) {
412
+ const head = await this.opts.store.head(this.opts.target.bucket, `${prefix}${k}`);
413
+ freedBytes += head?.size ?? 0;
414
+ }
415
+ const previewId = randomBytes(16).toString('hex');
416
+ nodeFs.writeFileSync(
417
+ path.join(this.opts.previewDir, `${previewId}.gc.json`),
418
+ JSON.stringify({ previewId, deletable, freedBytes, ts: Date.now() }),
419
+ 'utf-8',
420
+ );
421
+ return { retainedManifests: retained.size, trashManifests: all.length - retained.size, deletableBlobs: deletable, freedBytes, previewId };
422
+ }
423
+
424
+ async gcApply(req: { previewId: string; confirm: true }): Promise<{ ok: boolean; deleted: number; freedBytes: number }> {
425
+ if (req.confirm !== true) throw Object.assign(new Error('gc apply requires confirm:true'), { phase: 'validate', code: 'CONFIRM_REQUIRED' });
426
+ const pvPath = path.join(this.opts.previewDir, `${req.previewId}.gc.json`);
427
+ let saved: { deletable: string[]; freedBytes: number };
428
+ try {
429
+ saved = JSON.parse(nodeFs.readFileSync(pvPath, 'utf-8')) as { deletable: string[]; freedBytes: number };
430
+ } catch {
431
+ throw Object.assign(new Error('gc preview not found or expired'), { phase: 'validate', code: 'STALE_PREVIEW' });
432
+ }
433
+ const prefix = this.opts.target.prefix;
434
+ await this.opts.store.deleteKeys(this.opts.target.bucket, saved.deletable.map((k) => `${prefix}${k}`));
435
+ try {
436
+ nodeFs.rmSync(pvPath, { force: true });
437
+ } catch {}
438
+ return { ok: true, deleted: saved.deletable.length, freedBytes: saved.freedBytes };
439
+ }
440
+
441
+ private async readManifestKey(key: string): Promise<BackupManifest> {
442
+ const tmp = path.join(require('node:os').tmpdir(), `bk-mf-${randomBytes(4).toString('hex')}`);
443
+ nodeFs.mkdirSync(tmp, { recursive: true });
444
+ try {
445
+ await this.opts.store.get(this.opts.target.bucket, key, tmp);
446
+ return JSON.parse(nodeFs.readFileSync(path.join(tmp, key), 'utf-8')) as BackupManifest;
447
+ } finally {
448
+ try {
449
+ nodeFs.rmSync(tmp, { recursive: true, force: true });
450
+ } catch {}
451
+ }
452
+ }
453
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Bidirectional orchestration — one push-then-pull operation built from the
3
+ * existing per-direction preview/apply primitives.
4
+ *
5
+ * Each phase keeps the full safety contract (single-use preview, per-file
6
+ * CAS, fail closed); this module adds no new mutation route. The pull
7
+ * preview is minted only AFTER the push apply has landed, so it is exact.
8
+ * No auto-retry: the operator re-runs after reading the journal (union
9
+ * idempotence makes a re-run resume the unfinished phase).
10
+ */
11
+ import type { SyncService, ApplyResult } from './sync-service.js';
12
+ import type { SyncScope, SyncPreview, SyncSummary, SyncFailure } from './sync-types.js';
13
+
14
+ export interface BidirectionalPreview {
15
+ /** Combined id — the push preview's id; the pull phase mints its own. */
16
+ previewId: string;
17
+ expiresAt: string;
18
+ /** Exact push plan. */
19
+ push: SyncPreview;
20
+ /** Pull plan projected BEFORE the push lands; recomputed exact at apply time. */
21
+ pullProjected: SyncPreview;
22
+ }
23
+
24
+ export interface BidirectionalResult {
25
+ ok: boolean;
26
+ push: ApplyResult;
27
+ /** Null when the push failed — pull never runs. */
28
+ pull: ApplyResult | null;
29
+ /** Final pull dry-run summary; all-skip means converged. Null when pull never ran. */
30
+ verification: SyncSummary | null;
31
+ committed: string[];
32
+ failures: SyncFailure[];
33
+ }
34
+
35
+ export async function runBidirectionalPreview(
36
+ svc: SyncService,
37
+ opts: { scope: SyncScope },
38
+ ): Promise<BidirectionalPreview> {
39
+ const push = await svc.preview({ direction: 'push', scope: opts.scope });
40
+ const pullProjected = await svc.preview({ direction: 'pull', scope: opts.scope });
41
+ return { previewId: push.previewId, expiresAt: push.expiresAt, push, pullProjected };
42
+ }
43
+
44
+ export async function runBidirectionalApply(
45
+ svc: SyncService,
46
+ opts: { previewId: string; confirm: true; scope: SyncScope },
47
+ ): Promise<BidirectionalResult> {
48
+ if ((opts as { confirm?: unknown }).confirm !== true) {
49
+ throw Object.assign(new Error('bidirectional apply requires confirm:true'), { phase: 'validate', code: 'CONFIRM_REQUIRED' });
50
+ }
51
+ const push = await svc.apply({ previewId: opts.previewId, direction: 'push', confirm: true, scope: opts.scope });
52
+ if (!push.ok) {
53
+ return { ok: false, push, pull: null, verification: null, committed: [...push.committed], failures: [...push.failures] };
54
+ }
55
+ const pullPreview = await svc.preview({ direction: 'pull', scope: opts.scope });
56
+ const pull = await svc.apply({ previewId: pullPreview.previewId, direction: 'pull', confirm: true, scope: opts.scope });
57
+ const verify = await svc.preview({ direction: 'pull', scope: opts.scope });
58
+ return {
59
+ ok: pull.ok,
60
+ push,
61
+ pull,
62
+ verification: verify.summary,
63
+ committed: [...push.committed, ...pull.committed],
64
+ failures: [...push.failures, ...pull.failures],
65
+ };
66
+ }