@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,29 @@
1
+ import type { ProcessRunner } from './process-runner.js';
2
+ export type MachineMode = 'pull' | 'push' | 'bidirectional';
3
+ export interface MachineCheck {
4
+ mode: MachineMode;
5
+ from: string;
6
+ to: string;
7
+ localId: string | null;
8
+ remoteId: string | null;
9
+ }
10
+ export type MachineVerdict = {
11
+ ok: true;
12
+ localId: string | null;
13
+ remoteId: string | null;
14
+ } | {
15
+ ok: false;
16
+ code: 'WRONG_MACHINE';
17
+ message: string;
18
+ };
19
+ export declare function isMachineId(id: string): boolean;
20
+ /**
21
+ * The other side's id, derived from the ids actually read from the two
22
+ * machines (`readLocalMachineId`/`readRemoteMachineId`). Returns null when the
23
+ * caller's id matches neither side: an underivable peer must be asked for with
24
+ * `--to`, never guessed from a name table.
25
+ */
26
+ export declare function peerMachineId(from: string, localId: string | null, remoteId: string | null): string | null;
27
+ export declare function readLocalMachineId(fsMod?: any, dshHome?: string): Promise<string | null>;
28
+ export declare function readRemoteMachineId(runner: ProcessRunner, host: string, remoteDsh: string): Promise<string | null>;
29
+ export declare function checkMachines(c: MachineCheck): MachineVerdict;
@@ -0,0 +1,66 @@
1
+ import * as nodeFs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ /**
4
+ * A machine id is whatever that machine wrote to `$DSH_HOME/machine-id` — it
5
+ * is data, never a fixed name. The shape stays narrow so an id can be echoed in
6
+ * logs and reused as a profile name without quoting surprises.
7
+ */
8
+ const MACHINE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
9
+ export function isMachineId(id) {
10
+ return MACHINE_ID_RE.test(id);
11
+ }
12
+ /**
13
+ * The other side's id, derived from the ids actually read from the two
14
+ * machines (`readLocalMachineId`/`readRemoteMachineId`). Returns null when the
15
+ * caller's id matches neither side: an underivable peer must be asked for with
16
+ * `--to`, never guessed from a name table.
17
+ */
18
+ export function peerMachineId(from, localId, remoteId) {
19
+ const known = (v) => typeof v === 'string' && v.length > 0;
20
+ if (known(localId) && from === localId)
21
+ return known(remoteId) ? remoteId : null;
22
+ if (known(remoteId) && from === remoteId)
23
+ return known(localId) ? localId : null;
24
+ return null;
25
+ }
26
+ export async function readLocalMachineId(fsMod = nodeFs, dshHome) {
27
+ try {
28
+ const home = dshHome ?? process.env.DSH_HOME ?? '';
29
+ if (!home)
30
+ return null;
31
+ const raw = typeof fsMod.readFileSync === 'function' ? fsMod.readFileSync(path.join(home, 'machine-id'), 'utf-8') : null;
32
+ const id = String(raw ?? '').trim();
33
+ return id.length > 0 ? id : null;
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ }
39
+ export async function readRemoteMachineId(runner, host, remoteDsh) {
40
+ try {
41
+ const r = await runner.run('ssh', [host, 'cat', `${remoteDsh}/machine-id`], { timeoutMs: 8000 });
42
+ if (r.exitCode !== 0)
43
+ return null;
44
+ const id = Buffer.concat([r.stdout]).toString('utf-8').trim();
45
+ return id.length > 0 ? id : null;
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ }
51
+ export function checkMachines(c) {
52
+ if (c.from === c.to) {
53
+ return { ok: false, code: 'WRONG_MACHINE', message: `[wrong-machine] --from (${c.from}) equals --to (${c.to}); refusing` };
54
+ }
55
+ const known = (v) => typeof v === 'string' && v.length > 0;
56
+ if (c.mode === 'pull' && known(c.remoteId) && c.from !== c.remoteId) {
57
+ return { ok: false, code: 'WRONG_MACHINE', message: `[wrong-machine] --pull with --from=${c.from} but remote reports ${c.remoteId}; re-run with --from=${c.remoteId} --to=${c.localId ?? c.to}` };
58
+ }
59
+ if (c.mode === 'push' && known(c.localId) && c.from !== c.localId) {
60
+ return { ok: false, code: 'WRONG_MACHINE', message: `[wrong-machine] --push with --from=${c.from} but you are on ${c.localId}; re-run with --from=${c.localId} --to=${c.remoteId ?? c.to}` };
61
+ }
62
+ if (c.mode === 'bidirectional' && known(c.localId) && known(c.remoteId) && (c.from !== c.localId || c.to !== c.remoteId)) {
63
+ return { ok: false, code: 'WRONG_MACHINE', message: `[wrong-machine] --bidirectional needs --from=${c.localId} --to=${c.remoteId} (invoke from the source side); re-run accordingly` };
64
+ }
65
+ return { ok: true, localId: c.localId, remoteId: c.remoteId };
66
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Core delimited merge for daily/projects/global memory.
3
+ * Ported from packages/dsh-maestro-memory/src/host/storage/atomic-store.ts
4
+ * with header-aware parsing for DSH sync.
5
+ */
6
+ /** Entry delimiter, byte-compatible with Hermes MEMORY.md / USER.md. */
7
+ export declare const ENTRY_DELIMITER = "\n\u00A7\n";
8
+ /** Regex for entry ID prefix (space after colon allowed, case-insensitive). */
9
+ export declare const ENTRY_ID_RE: RegExp;
10
+ /**
11
+ * Strip the `[id:xxxxxxxx]` prefix from an entry, if present.
12
+ */
13
+ export declare function stripId(entry: string): string;
14
+ /** Alias for compatibility. */
15
+ export declare const stripEntryId: typeof stripId;
16
+ /**
17
+ * Split raw file text into trimmed, non-empty entries.
18
+ * Strips leading `<!--...-->` header before splitting.
19
+ */
20
+ export declare function parseEntries(text: string): string[];
21
+ /**
22
+ * Serialize entries into canonical file text.
23
+ */
24
+ export declare function serializeEntries(entries: string[]): string;
25
+ /**
26
+ * Merge two delimited texts, dedup by stripId, preserve local order then remote-only appended.
27
+ * Header comment (`<!--...-->`) is preserved from local if present, otherwise from remote.
28
+ * @returns merged text and count of added entries.
29
+ */
30
+ export declare function mergeDelimited(localText: string, remoteText: string): {
31
+ mergedText: string;
32
+ added: number;
33
+ };
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Core delimited merge for daily/projects/global memory.
3
+ * Ported from packages/dsh-maestro-memory/src/host/storage/atomic-store.ts
4
+ * with header-aware parsing for DSH sync.
5
+ */
6
+ /** Entry delimiter, byte-compatible with Hermes MEMORY.md / USER.md. */
7
+ export const ENTRY_DELIMITER = '\n§\n';
8
+ /** Regex for entry ID prefix (space after colon allowed, case-insensitive). */
9
+ export const ENTRY_ID_RE = /^\[id:\s*[0-9a-f]{8}\]\s*/i;
10
+ /**
11
+ * Strip the `[id:xxxxxxxx]` prefix from an entry, if present.
12
+ */
13
+ export function stripId(entry) {
14
+ return String(entry ?? '').replace(ENTRY_ID_RE, '');
15
+ }
16
+ /** Alias for compatibility. */
17
+ export const stripEntryId = stripId;
18
+ /**
19
+ * Extract leading HTML comment header `<!--...-->` if present at start of text.
20
+ * Returns header (trimmed) and remaining body.
21
+ */
22
+ function extractHeader(text) {
23
+ const raw = String(text ?? '');
24
+ const match = /^\s*<!--[\s\S]*?-->\s*/.exec(raw);
25
+ if (match) {
26
+ const header = match[0].trim();
27
+ const body = raw.slice(match[0].length);
28
+ return { header, body };
29
+ }
30
+ return { header: '', body: raw };
31
+ }
32
+ /**
33
+ * Split raw file text into trimmed, non-empty entries.
34
+ * Strips leading `<!--...-->` header before splitting.
35
+ */
36
+ export function parseEntries(text) {
37
+ const { body } = extractHeader(String(text ?? ''));
38
+ // Split strictly by ENTRY_DELIMITER, then trim and filter.
39
+ // For robustness, also handle cases where delimiter may have surrounding spaces
40
+ // by normalizing split result via trim.
41
+ return body
42
+ .split(ENTRY_DELIMITER)
43
+ .map((e) => e.trim())
44
+ .filter((e) => e.length > 0);
45
+ }
46
+ /**
47
+ * Serialize entries into canonical file text.
48
+ */
49
+ export function serializeEntries(entries) {
50
+ return entries.length === 0 ? '' : entries.join(ENTRY_DELIMITER) + '\n';
51
+ }
52
+ /**
53
+ * Merge two delimited texts, dedup by stripId, preserve local order then remote-only appended.
54
+ * Header comment (`<!--...-->`) is preserved from local if present, otherwise from remote.
55
+ * @returns merged text and count of added entries.
56
+ */
57
+ export function mergeDelimited(localText, remoteText) {
58
+ const localHeader = extractHeader(String(localText ?? '')).header;
59
+ const remoteHeader = extractHeader(String(remoteText ?? '')).header;
60
+ const header = localHeader || remoteHeader || '';
61
+ const localEntries = parseEntries(String(localText ?? ''));
62
+ const remoteEntries = parseEntries(String(remoteText ?? ''));
63
+ const seen = new Set(localEntries.map((e) => stripId(e)));
64
+ const merged = [...localEntries];
65
+ let added = 0;
66
+ for (const entry of remoteEntries) {
67
+ const key = stripId(entry);
68
+ if (!seen.has(key)) {
69
+ seen.add(key);
70
+ merged.push(entry);
71
+ added++;
72
+ }
73
+ }
74
+ const body = serializeEntries(merged);
75
+ let mergedText;
76
+ if (header) {
77
+ if (body === '') {
78
+ mergedText = header + '\n';
79
+ }
80
+ else {
81
+ mergedText = header + '\n' + body;
82
+ }
83
+ }
84
+ else {
85
+ mergedText = body;
86
+ }
87
+ return { mergedText, added };
88
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The peer SSH target as THIS machine sees it. `remoteHost` in the shared
3
+ * settings store travels between the two machines (it is written by whichever
4
+ * machine saved it and copied with the rest of the store), so a machine can
5
+ * inherit the other machine's address — which resolves to itself there. This
6
+ * file is machine-local and outranks the shared store, exactly like the tunnel
7
+ * profile owns `domains.tunnel`.
8
+ */
9
+ export declare const PEER_HOST_REL = "dsh-maestro-sync/peer.json";
10
+ /** DSH home the host resolves when no explicit one is given. */
11
+ export declare function defaultDshHome(): string;
12
+ export declare function peerHostPath(dshHome: string): string;
13
+ /**
14
+ * This machine's own peer target, or null when it was never set (callers then
15
+ * fall back to the shared store). An unreadable or invalid file is null, never
16
+ * a throw: the peer of a machine that has none is simply not known yet.
17
+ */
18
+ export declare function readPeerHost(dshHome?: string): string | null;
19
+ /** Record this machine's peer target; returns the validated host. */
20
+ export declare function writePeerHost(dshHome: string, host: string): string;
21
+ /** Drop this machine's peer target; the shared store takes over again. */
22
+ export declare function clearPeerHost(dshHome: string): boolean;
@@ -0,0 +1,62 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import * as os from 'node:os';
4
+ import { validateHost } from './validation.js';
5
+ /**
6
+ * The peer SSH target as THIS machine sees it. `remoteHost` in the shared
7
+ * settings store travels between the two machines (it is written by whichever
8
+ * machine saved it and copied with the rest of the store), so a machine can
9
+ * inherit the other machine's address — which resolves to itself there. This
10
+ * file is machine-local and outranks the shared store, exactly like the tunnel
11
+ * profile owns `domains.tunnel`.
12
+ */
13
+ export const PEER_HOST_REL = 'dsh-maestro-sync/peer.json';
14
+ /** DSH home the host resolves when no explicit one is given. */
15
+ export function defaultDshHome() {
16
+ return process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
17
+ }
18
+ export function peerHostPath(dshHome) {
19
+ return path.join(dshHome, PEER_HOST_REL);
20
+ }
21
+ /**
22
+ * This machine's own peer target, or null when it was never set (callers then
23
+ * fall back to the shared store). An unreadable or invalid file is null, never
24
+ * a throw: the peer of a machine that has none is simply not known yet.
25
+ */
26
+ export function readPeerHost(dshHome) {
27
+ const home = dshHome ?? defaultDshHome();
28
+ try {
29
+ const parsed = JSON.parse(fs.readFileSync(peerHostPath(home), 'utf-8'));
30
+ const host = parsed?.remoteHost;
31
+ return typeof host === 'string' && host.length > 0 ? validateHost(host.trim()) : null;
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ /** Record this machine's peer target; returns the validated host. */
38
+ export function writePeerHost(dshHome, host) {
39
+ const valid = validateHost(host.trim());
40
+ const file = peerHostPath(dshHome);
41
+ fs.mkdirSync(path.dirname(file), { recursive: true });
42
+ const tmp = `${file}.tmp.${process.pid}`;
43
+ fs.writeFileSync(tmp, `${JSON.stringify({ remoteHost: valid, writtenAt: new Date().toISOString() }, null, 2)}\n`, { mode: 0o600 });
44
+ fs.renameSync(tmp, file);
45
+ try {
46
+ fs.chmodSync(file, 0o600);
47
+ }
48
+ catch {
49
+ /* best effort on filesystems without POSIX modes */
50
+ }
51
+ return valid;
52
+ }
53
+ /** Drop this machine's peer target; the shared store takes over again. */
54
+ export function clearPeerHost(dshHome) {
55
+ try {
56
+ fs.unlinkSync(peerHostPath(dshHome));
57
+ return true;
58
+ }
59
+ catch {
60
+ return false;
61
+ }
62
+ }
@@ -0,0 +1,31 @@
1
+ import { spawn } from 'node:child_process';
2
+ export interface ProcessResult {
3
+ stdout: Buffer;
4
+ stderr: Buffer;
5
+ exitCode: number;
6
+ }
7
+ export interface ProcessRunner {
8
+ run(file: string, args: readonly string[], options?: {
9
+ input?: Buffer;
10
+ timeoutMs?: number;
11
+ onLine?: (line: string) => void;
12
+ }): Promise<ProcessResult>;
13
+ }
14
+ export interface NodeProcessRunnerOptions {
15
+ /**
16
+ * Injectable spawn. Tests need a child that never emits `'close'` (a
17
+ * grandchild holding the stdio pipes does that for real), which no real
18
+ * process can reproduce deterministically.
19
+ */
20
+ spawn?: typeof spawn;
21
+ }
22
+ export declare class NodeProcessRunner implements ProcessRunner {
23
+ private readonly spawnChild;
24
+ constructor(options?: NodeProcessRunnerOptions);
25
+ run(file: string, args: readonly string[], options?: {
26
+ input?: Buffer;
27
+ timeoutMs?: number;
28
+ onLine?: (line: string) => void;
29
+ }): Promise<ProcessResult>;
30
+ }
31
+ export declare function createProcessRunner(): ProcessRunner;
@@ -0,0 +1,161 @@
1
+ import { spawn } from 'node:child_process';
2
+ /** Maximum combined output before we kill the child (fail-closed, avoids OOM). */
3
+ const MAX_BUFFER_BYTES = 20 * 1024 * 1024;
4
+ export class NodeProcessRunner {
5
+ spawnChild;
6
+ constructor(options = {}) {
7
+ this.spawnChild = options.spawn ?? spawn;
8
+ }
9
+ async run(file, args, options) {
10
+ return new Promise((resolve, reject) => {
11
+ // argv-only, never shell — caller may pass filenames with spaces/metachars as single argv items
12
+ // Detached on POSIX so the child leads its own process group; killTree() needs
13
+ // that to reach the grandchildren it spawns.
14
+ const child = this.spawnChild(file, args, {
15
+ shell: false,
16
+ stdio: ['pipe', 'pipe', 'pipe'],
17
+ detached: process.platform !== 'win32',
18
+ });
19
+ const stdoutChunks = [];
20
+ const stderrChunks = [];
21
+ let stdoutLen = 0;
22
+ let stderrLen = 0;
23
+ let timeout;
24
+ let settled = false;
25
+ // line-buffered stdout delivery for progress callbacks (ssh sha256sum streaming)
26
+ let lineBuf = '';
27
+ /**
28
+ * Single owner of the promise's fate.
29
+ *
30
+ * The timeout, `'error'` and `'close'` race for it and the first caller
31
+ * wins; later ones are dropped. Without that, a child that finally closes
32
+ * after a timeout kill would resolve a promise the caller was already told
33
+ * failed. Every path clears the timer here, so no branch can leave one
34
+ * armed.
35
+ */
36
+ const settle = (finish) => {
37
+ if (settled)
38
+ return;
39
+ settled = true;
40
+ if (timeout)
41
+ clearTimeout(timeout);
42
+ finish();
43
+ };
44
+ /**
45
+ * Kill the child and the processes it spawned.
46
+ *
47
+ * SIGKILL to the direct child alone leaves its grandchildren alive while
48
+ * they keep the inherited stdio open — ssh's `ProxyCommand cloudflared
49
+ * access ssh` and git's `git-remote-https` are the real cases — so the
50
+ * timeout stops bounding anything. POSIX: the child is spawned detached,
51
+ * so it leads its own process group and `-pid` reaches the whole tree.
52
+ * Windows has no process-group signal and no SIGKILL semantics, so only
53
+ * the child is killed there: the caller is still never stuck, but a
54
+ * grandchild may outlive the call.
55
+ */
56
+ const killTree = () => {
57
+ if (process.platform !== 'win32' && typeof child.pid === 'number' && child.pid > 0) {
58
+ try {
59
+ process.kill(-child.pid, 'SIGKILL');
60
+ return;
61
+ }
62
+ catch { /* fall through to the direct kill */ }
63
+ }
64
+ try {
65
+ child.kill('SIGKILL');
66
+ }
67
+ catch { }
68
+ };
69
+ /**
70
+ * Kill, then release the pipes. Order is load-bearing: destroying the
71
+ * stdio streams can make Node emit `'close'`, so the outcome must already
72
+ * be settled or that `'close'` would resolve a fake success.
73
+ */
74
+ const teardown = () => {
75
+ killTree();
76
+ child.stdout?.destroy();
77
+ child.stderr?.destroy();
78
+ };
79
+ const killForBounds = () => {
80
+ if (settled)
81
+ return;
82
+ settle(() => reject(new Error(`process "${file}" output exceeded ${MAX_BUFFER_BYTES} bytes`)));
83
+ teardown();
84
+ };
85
+ if (options?.timeoutMs) {
86
+ const timeoutMs = options.timeoutMs;
87
+ timeout = setTimeout(() => {
88
+ // Reject at the deadline instead of waiting for `'close'`: a grandchild
89
+ // that inherited the pipes keeps `'close'` from firing at all, which is
90
+ // what made this "timeout" unbounded.
91
+ settle(() => reject(new Error(`process "${file} ${args.join(' ')}" timed out after ${timeoutMs}ms`)));
92
+ teardown();
93
+ }, timeoutMs);
94
+ }
95
+ const deliverLines = () => {
96
+ if (!options?.onLine)
97
+ return;
98
+ let idx;
99
+ while ((idx = lineBuf.indexOf('\n')) !== -1) {
100
+ const line = lineBuf.slice(0, idx).replace(/\r$/, '');
101
+ lineBuf = lineBuf.slice(idx + 1);
102
+ if (line.trim())
103
+ options.onLine?.(line);
104
+ }
105
+ };
106
+ child.stdout?.on('data', (chunk) => {
107
+ const buf = Buffer.from(chunk);
108
+ stdoutLen += buf.length;
109
+ if (stdoutLen > MAX_BUFFER_BYTES) {
110
+ killForBounds();
111
+ return;
112
+ }
113
+ stdoutChunks.push(buf);
114
+ if (options?.onLine) {
115
+ lineBuf += buf.toString('utf-8');
116
+ deliverLines();
117
+ }
118
+ });
119
+ child.stderr?.on('data', (chunk) => {
120
+ const buf = Buffer.from(chunk);
121
+ stderrLen += buf.length;
122
+ if (stdoutLen + stderrLen > MAX_BUFFER_BYTES) {
123
+ killForBounds();
124
+ return;
125
+ }
126
+ stderrChunks.push(buf);
127
+ });
128
+ child.on('error', (err) => {
129
+ settle(() => reject(err));
130
+ });
131
+ child.on('close', (code) => {
132
+ settle(() => resolve({
133
+ stdout: Buffer.concat(stdoutChunks),
134
+ stderr: Buffer.concat(stderrChunks),
135
+ exitCode: code ?? 0,
136
+ }));
137
+ });
138
+ // A stdin pipe whose reader already exited reports EPIPE as an
139
+ // asynchronous stream `'error'` event, not as a throw — and an unhandled
140
+ // stream error becomes a process-level uncaughtException, which the boot
141
+ // guard turns into `proc.exit(1)`. Swallowing it here is correct: the
142
+ // child is gone, and its exit status (not the failed write) is what the
143
+ // caller acts on. Measured before this listener: a 1 MiB write into
144
+ // `bash -c 'exit 0'` escaped as EPIPE on 20/20 attempts.
145
+ child.stdin?.on('error', () => { });
146
+ if (options?.input) {
147
+ try {
148
+ child.stdin?.write(options.input);
149
+ }
150
+ catch { }
151
+ }
152
+ try {
153
+ child.stdin?.end();
154
+ }
155
+ catch { }
156
+ });
157
+ }
158
+ }
159
+ export function createProcessRunner() {
160
+ return new NodeProcessRunner();
161
+ }
@@ -0,0 +1,42 @@
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 declare const REMOTE_AGENT_NAME = "maestro-sync-commit";
36
+ export declare const REMOTE_AGENT_REL = ".maestro-sync/bin/maestro-sync-commit";
37
+ export declare function remoteAgentSource(): string;
38
+ /**
39
+ * Structural verification of the helper source — used by tests and by
40
+ * `ensureAgent` before shipping the script to the remote host.
41
+ */
42
+ export declare function verifyRemoteAgentSource(src: string): string;