@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.
- package/LICENSE +21 -0
- package/README.md +209 -0
- package/cordis.patch.yml +43 -0
- package/lib/bin.d.ts +2 -0
- package/lib/bin.js +3 -0
- package/lib/boot-guard.d.ts +33 -0
- package/lib/boot-guard.js +68 -0
- package/lib/boot-lock.d.ts +56 -0
- package/lib/boot-lock.js +155 -0
- package/lib/cli.d.ts +31 -0
- package/lib/cli.js +336 -0
- package/lib/client.js +2901 -0
- package/lib/config/index.d.ts +34 -0
- package/lib/config/index.js +62 -0
- package/lib/config/service.d.ts +18 -0
- package/lib/config/service.js +28 -0
- package/lib/config.d.ts +1 -0
- package/lib/config.js +19 -0
- package/lib/daemon-freshness.d.ts +48 -0
- package/lib/daemon-freshness.js +122 -0
- package/lib/debug-agent.d.ts +17 -0
- package/lib/debug-agent.js +144 -0
- package/lib/dsh-session.d.ts +26 -0
- package/lib/dsh-session.js +45 -0
- package/lib/guard/config.d.ts +82 -0
- package/lib/guard/config.js +211 -0
- package/lib/guard/decide.d.ts +30 -0
- package/lib/guard/decide.js +38 -0
- package/lib/guard/full-scan-tool.d.ts +6 -0
- package/lib/guard/full-scan-tool.js +65 -0
- package/lib/guard/index.d.ts +85 -0
- package/lib/guard/index.js +254 -0
- package/lib/guard/journal.d.ts +146 -0
- package/lib/guard/journal.js +398 -0
- package/lib/guard/migrate.d.ts +15 -0
- package/lib/guard/migrate.js +42 -0
- package/lib/guard/parse.d.ts +193 -0
- package/lib/guard/parse.js +1103 -0
- package/lib/guard/paths.d.ts +104 -0
- package/lib/guard/paths.js +254 -0
- package/lib/guard/permission-policy.d.ts +10 -0
- package/lib/guard/permission-policy.js +21 -0
- package/lib/guard/redact.d.ts +25 -0
- package/lib/guard/redact.js +52 -0
- package/lib/guard/rules.d.ts +65 -0
- package/lib/guard/rules.js +832 -0
- package/lib/guard/status-tool.d.ts +54 -0
- package/lib/guard/status-tool.js +195 -0
- package/lib/guard/tiers.d.ts +2 -0
- package/lib/guard/tiers.js +1 -0
- package/lib/guard/validators.d.ts +4 -0
- package/lib/guard/validators.js +45 -0
- package/lib/health-poller.d.ts +90 -0
- package/lib/health-poller.js +430 -0
- package/lib/index.d.ts +7 -0
- package/lib/index.js +7 -0
- package/lib/intents.d.ts +32 -0
- package/lib/intents.js +49 -0
- package/lib/notifier.d.ts +12 -0
- package/lib/notifier.js +62 -0
- package/lib/paths.d.ts +13 -0
- package/lib/paths.js +70 -0
- package/lib/plugin.d.ts +250 -0
- package/lib/plugin.js +1126 -0
- package/lib/preset.d.ts +73 -0
- package/lib/preset.js +158 -0
- package/lib/report.d.ts +11 -0
- package/lib/report.js +58 -0
- package/lib/restart-exec.d.ts +35 -0
- package/lib/restart-exec.js +60 -0
- package/lib/restart-guards.d.ts +39 -0
- package/lib/restart-guards.js +150 -0
- package/lib/restart-tool.d.ts +124 -0
- package/lib/restart-tool.js +539 -0
- package/lib/restart-web.d.ts +26 -0
- package/lib/restart-web.js +58 -0
- package/lib/resume-log.d.ts +24 -0
- package/lib/resume-log.js +18 -0
- package/lib/resume-tools.d.ts +131 -0
- package/lib/resume-tools.js +337 -0
- package/lib/resume.d.ts +33 -0
- package/lib/resume.js +221 -0
- package/lib/scan.d.ts +20 -0
- package/lib/scan.js +71 -0
- package/lib/self-kill-guard.d.ts +81 -0
- package/lib/self-kill-guard.js +208 -0
- package/lib/session-health.d.ts +89 -0
- package/lib/session-health.js +274 -0
- package/lib/session-log-file.d.ts +22 -0
- package/lib/session-log-file.js +74 -0
- package/lib/skill-provider.d.ts +6 -0
- package/lib/skill-provider.js +73 -0
- package/lib/snapshot.d.ts +59 -0
- package/lib/snapshot.js +358 -0
- package/lib/source.d.ts +19 -0
- package/lib/source.js +19 -0
- package/lib/store/index.d.ts +42 -0
- package/lib/store/index.js +340 -0
- package/lib/store/legacy.d.ts +17 -0
- package/lib/store/legacy.js +85 -0
- package/lib/supervisor.d.ts +119 -0
- package/lib/supervisor.js +741 -0
- package/lib/sync/backup-config.d.ts +55 -0
- package/lib/sync/backup-config.js +119 -0
- package/lib/sync/backup-service.d.ts +110 -0
- package/lib/sync/backup-service.js +440 -0
- package/lib/sync/bidirectional.d.ts +39 -0
- package/lib/sync/bidirectional.js +25 -0
- package/lib/sync/cli.d.ts +38 -0
- package/lib/sync/cli.js +536 -0
- package/lib/sync/config.d.ts +77 -0
- package/lib/sync/config.js +90 -0
- package/lib/sync/fingerprint.d.ts +29 -0
- package/lib/sync/fingerprint.js +65 -0
- package/lib/sync/hashing.d.ts +9 -0
- package/lib/sync/hashing.js +47 -0
- package/lib/sync/index.d.ts +6 -0
- package/lib/sync/index.js +634 -0
- package/lib/sync/machine-id.d.ts +29 -0
- package/lib/sync/machine-id.js +66 -0
- package/lib/sync/merge.d.ts +33 -0
- package/lib/sync/merge.js +88 -0
- package/lib/sync/peer-host.d.ts +22 -0
- package/lib/sync/peer-host.js +62 -0
- package/lib/sync/process-runner.d.ts +31 -0
- package/lib/sync/process-runner.js +161 -0
- package/lib/sync/remote-agent.d.ts +42 -0
- package/lib/sync/remote-agent.js +217 -0
- package/lib/sync/remote-cache.d.ts +18 -0
- package/lib/sync/remote-cache.js +60 -0
- package/lib/sync/remote-manifest.d.ts +8 -0
- package/lib/sync/remote-manifest.js +64 -0
- package/lib/sync/s3-object-store.d.ts +38 -0
- package/lib/sync/s3-object-store.js +126 -0
- package/lib/sync/session-merge.d.ts +18 -0
- package/lib/sync/session-merge.js +191 -0
- package/lib/sync/session-plan.d.ts +29 -0
- package/lib/sync/session-plan.js +213 -0
- package/lib/sync/sigv4.d.ts +20 -0
- package/lib/sync/sigv4.js +57 -0
- package/lib/sync/snapshot.d.ts +21 -0
- package/lib/sync/snapshot.js +176 -0
- package/lib/sync/ssh-mux.d.ts +12 -0
- package/lib/sync/ssh-mux.js +48 -0
- package/lib/sync/sync-plan.d.ts +24 -0
- package/lib/sync/sync-plan.js +366 -0
- package/lib/sync/sync-service.d.ts +177 -0
- package/lib/sync/sync-service.js +819 -0
- package/lib/sync/sync-types.d.ts +87 -0
- package/lib/sync/sync-types.js +1 -0
- package/lib/sync/transport.d.ts +75 -0
- package/lib/sync/transport.js +200 -0
- package/lib/sync/tunnel-restore.d.ts +77 -0
- package/lib/sync/tunnel-restore.js +142 -0
- package/lib/sync/validation.d.ts +10 -0
- package/lib/sync/validation.js +83 -0
- package/lib/tool-view.d.ts +62 -0
- package/lib/tool-view.js +70 -0
- package/lib/types/client/auto-reload.d.ts +8 -0
- package/lib/types/client/auto-reload.d.ts.map +1 -0
- package/lib/types/client/config/MaestroSettings.d.ts +25 -0
- package/lib/types/client/config/MaestroSettings.d.ts.map +1 -0
- package/lib/types/client/config/components/BrandMark.d.ts +50 -0
- package/lib/types/client/config/components/BrandMark.d.ts.map +1 -0
- package/lib/types/client/config/guard-view.d.ts +83 -0
- package/lib/types/client/config/guard-view.d.ts.map +1 -0
- package/lib/types/client/config/index.d.ts +20 -0
- package/lib/types/client/config/index.d.ts.map +1 -0
- package/lib/types/client/config/maestro-mark.d.ts +29 -0
- package/lib/types/client/config/maestro-mark.d.ts.map +1 -0
- package/lib/types/client/config/settings-nav-icon.d.ts +21 -0
- package/lib/types/client/config/settings-nav-icon.d.ts.map +1 -0
- package/lib/types/client/index.d.ts +16 -0
- package/lib/types/client/index.d.ts.map +1 -0
- package/lib/types/client/sync/R2SyncPanel.d.ts +6 -0
- package/lib/types/client/sync/R2SyncPanel.d.ts.map +1 -0
- package/lib/types/client/sync/SyncPanel.d.ts +12 -0
- package/lib/types/client/sync/SyncPanel.d.ts.map +1 -0
- package/lib/types/client/sync/confirm-dialog.d.ts +43 -0
- package/lib/types/client/sync/confirm-dialog.d.ts.map +1 -0
- package/lib/types/client/sync/index.d.ts +10 -0
- package/lib/types/client/sync/index.d.ts.map +1 -0
- package/lib/types/client/sync/ui.d.ts +79 -0
- package/lib/types/client/sync/ui.d.ts.map +1 -0
- package/lib/types/client/sync/use-backup.d.ts +50 -0
- package/lib/types/client/sync/use-backup.d.ts.map +1 -0
- package/lib/types/client/sync/use-sync.d.ts +88 -0
- package/lib/types/client/sync/use-sync.d.ts.map +1 -0
- package/package.json +89 -0
- package/skills/dsh-safe-restart/SKILL.md +206 -0
- package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +468 -0
- package/src/client/auto-reload.ts +104 -0
- package/src/client/config/MaestroSettings.tsx +892 -0
- package/src/client/config/components/BrandMark.tsx +94 -0
- package/src/client/config/guard-view.ts +187 -0
- package/src/client/config/index.tsx +109 -0
- package/src/client/config/maestro-mark.ts +37 -0
- package/src/client/config/settings-nav-icon.ts +68 -0
- package/src/client/index.tsx +33 -0
- package/src/client/sync/R2SyncPanel.tsx +260 -0
- package/src/client/sync/SyncPanel.tsx +422 -0
- package/src/client/sync/confirm-dialog.tsx +202 -0
- package/src/client/sync/index.tsx +336 -0
- package/src/client/sync/ui.tsx +313 -0
- package/src/client/sync/use-backup.ts +207 -0
- package/src/client/sync/use-sync.ts +502 -0
- package/src/host/bin.ts +3 -0
- package/src/host/boot-guard.ts +76 -0
- package/src/host/boot-lock.ts +155 -0
- package/src/host/cli.ts +288 -0
- package/src/host/config/index.ts +78 -0
- package/src/host/config/service.ts +40 -0
- package/src/host/config.ts +18 -0
- package/src/host/daemon-freshness.ts +143 -0
- package/src/host/debug-agent.ts +145 -0
- package/src/host/dsh-session.ts +56 -0
- package/src/host/dsh-skill.d.ts +44 -0
- package/src/host/guard/augment.d.ts +33 -0
- package/src/host/guard/config.ts +244 -0
- package/src/host/guard/decide.ts +40 -0
- package/src/host/guard/full-scan-tool.ts +61 -0
- package/src/host/guard/index.ts +281 -0
- package/src/host/guard/journal.ts +440 -0
- package/src/host/guard/migrate.ts +41 -0
- package/src/host/guard/parse.ts +1150 -0
- package/src/host/guard/paths.ts +239 -0
- package/src/host/guard/permission-policy.ts +15 -0
- package/src/host/guard/redact.ts +64 -0
- package/src/host/guard/rules.ts +891 -0
- package/src/host/guard/status-tool.ts +229 -0
- package/src/host/guard/tiers.ts +2 -0
- package/src/host/guard/validators.ts +29 -0
- package/src/host/health-poller.ts +446 -0
- package/src/host/index.ts +7 -0
- package/src/host/intents.ts +67 -0
- package/src/host/notifier.ts +71 -0
- package/src/host/paths.ts +70 -0
- package/src/host/plugin.ts +1097 -0
- package/src/host/preset.ts +170 -0
- package/src/host/report.ts +71 -0
- package/src/host/restart-exec.ts +81 -0
- package/src/host/restart-guards.ts +150 -0
- package/src/host/restart-tool.ts +483 -0
- package/src/host/restart-web.ts +72 -0
- package/src/host/resume-log.ts +39 -0
- package/src/host/resume-tools.ts +385 -0
- package/src/host/resume.ts +204 -0
- package/src/host/scan.ts +61 -0
- package/src/host/self-kill-guard.ts +216 -0
- package/src/host/session-health.ts +236 -0
- package/src/host/session-log-file.ts +77 -0
- package/src/host/skill-provider.ts +69 -0
- package/src/host/snapshot.ts +337 -0
- package/src/host/source.ts +19 -0
- package/src/host/store/index.ts +348 -0
- package/src/host/store/legacy.ts +96 -0
- package/src/host/supervisor.ts +720 -0
- package/src/host/sync/backup-config.ts +159 -0
- package/src/host/sync/backup-service.ts +453 -0
- package/src/host/sync/bidirectional.ts +66 -0
- package/src/host/sync/cli.ts +539 -0
- package/src/host/sync/config.ts +119 -0
- package/src/host/sync/fingerprint.ts +83 -0
- package/src/host/sync/hashing.ts +58 -0
- package/src/host/sync/index.ts +737 -0
- package/src/host/sync/machine-id.ts +81 -0
- package/src/host/sync/merge.ts +102 -0
- package/src/host/sync/peer-host.ts +65 -0
- package/src/host/sync/process-runner.ts +177 -0
- package/src/host/sync/remote-agent.ts +213 -0
- package/src/host/sync/remote-cache.ts +68 -0
- package/src/host/sync/remote-manifest.ts +70 -0
- package/src/host/sync/s3-object-store.ts +144 -0
- package/src/host/sync/session-merge.ts +220 -0
- package/src/host/sync/session-plan.ts +237 -0
- package/src/host/sync/sigv4.ts +81 -0
- package/src/host/sync/snapshot.ts +162 -0
- package/src/host/sync/ssh-mux.ts +56 -0
- package/src/host/sync/sync-plan.ts +366 -0
- package/src/host/sync/sync-service.ts +855 -0
- package/src/host/sync/sync-types.ts +102 -0
- package/src/host/sync/transport.ts +261 -0
- package/src/host/sync/tunnel-restore.ts +160 -0
- package/src/host/sync/validation.ts +91 -0
- package/src/host/tool-view.ts +98 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import * as nodeFs from 'node:fs';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import type { ProcessRunner } from './process-runner.js';
|
|
4
|
+
|
|
5
|
+
export type MachineMode = 'pull' | 'push' | 'bidirectional';
|
|
6
|
+
|
|
7
|
+
export interface MachineCheck {
|
|
8
|
+
mode: MachineMode;
|
|
9
|
+
from: string;
|
|
10
|
+
to: string;
|
|
11
|
+
localId: string | null;
|
|
12
|
+
remoteId: string | null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type MachineVerdict =
|
|
16
|
+
| { ok: true; localId: string | null; remoteId: string | null }
|
|
17
|
+
| { ok: false; code: 'WRONG_MACHINE'; message: string };
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* A machine id is whatever that machine wrote to `$DSH_HOME/machine-id` — it
|
|
21
|
+
* is data, never a fixed name. The shape stays narrow so an id can be echoed in
|
|
22
|
+
* logs and reused as a profile name without quoting surprises.
|
|
23
|
+
*/
|
|
24
|
+
const MACHINE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
25
|
+
|
|
26
|
+
export function isMachineId(id: string): boolean {
|
|
27
|
+
return MACHINE_ID_RE.test(id);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The other side's id, derived from the ids actually read from the two
|
|
32
|
+
* machines (`readLocalMachineId`/`readRemoteMachineId`). Returns null when the
|
|
33
|
+
* caller's id matches neither side: an underivable peer must be asked for with
|
|
34
|
+
* `--to`, never guessed from a name table.
|
|
35
|
+
*/
|
|
36
|
+
export function peerMachineId(from: string, localId: string | null, remoteId: string | null): string | null {
|
|
37
|
+
const known = (v: string | null): v is string => typeof v === 'string' && v.length > 0;
|
|
38
|
+
if (known(localId) && from === localId) return known(remoteId) ? remoteId : null;
|
|
39
|
+
if (known(remoteId) && from === remoteId) return known(localId) ? localId : null;
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function readLocalMachineId(fsMod: any = nodeFs, dshHome?: string): Promise<string | null> {
|
|
44
|
+
try {
|
|
45
|
+
const home = dshHome ?? process.env.DSH_HOME ?? '';
|
|
46
|
+
if (!home) return null;
|
|
47
|
+
const raw = typeof fsMod.readFileSync === 'function' ? fsMod.readFileSync(path.join(home, 'machine-id'), 'utf-8') : null;
|
|
48
|
+
const id = String(raw ?? '').trim();
|
|
49
|
+
return id.length > 0 ? id : null;
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function readRemoteMachineId(runner: ProcessRunner, host: string, remoteDsh: string): Promise<string | null> {
|
|
56
|
+
try {
|
|
57
|
+
const r = await (runner as any).run('ssh', [host, 'cat', `${remoteDsh}/machine-id`], { timeoutMs: 8000 });
|
|
58
|
+
if (r.exitCode !== 0) return null;
|
|
59
|
+
const id = Buffer.concat([r.stdout]).toString('utf-8').trim();
|
|
60
|
+
return id.length > 0 ? id : null;
|
|
61
|
+
} catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function checkMachines(c: MachineCheck): MachineVerdict {
|
|
67
|
+
if (c.from === c.to) {
|
|
68
|
+
return { ok: false, code: 'WRONG_MACHINE', message: `[wrong-machine] --from (${c.from}) equals --to (${c.to}); refusing` };
|
|
69
|
+
}
|
|
70
|
+
const known = (v: string | null): v is string => typeof v === 'string' && v.length > 0;
|
|
71
|
+
if (c.mode === 'pull' && known(c.remoteId) && c.from !== c.remoteId) {
|
|
72
|
+
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}` };
|
|
73
|
+
}
|
|
74
|
+
if (c.mode === 'push' && known(c.localId) && c.from !== c.localId) {
|
|
75
|
+
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}` };
|
|
76
|
+
}
|
|
77
|
+
if (c.mode === 'bidirectional' && known(c.localId) && known(c.remoteId) && (c.from !== c.localId || c.to !== c.remoteId)) {
|
|
78
|
+
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` };
|
|
79
|
+
}
|
|
80
|
+
return { ok: true, localId: c.localId, remoteId: c.remoteId };
|
|
81
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
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
|
+
|
|
7
|
+
/** Entry delimiter, byte-compatible with Hermes MEMORY.md / USER.md. */
|
|
8
|
+
export const ENTRY_DELIMITER = '\n§\n';
|
|
9
|
+
|
|
10
|
+
/** Regex for entry ID prefix (space after colon allowed, case-insensitive). */
|
|
11
|
+
export const ENTRY_ID_RE = /^\[id:\s*[0-9a-f]{8}\]\s*/i;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Strip the `[id:xxxxxxxx]` prefix from an entry, if present.
|
|
15
|
+
*/
|
|
16
|
+
export function stripId(entry: string): string {
|
|
17
|
+
return String(entry ?? '').replace(ENTRY_ID_RE, '');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Alias for compatibility. */
|
|
21
|
+
export const stripEntryId = stripId;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Extract leading HTML comment header `<!--...-->` if present at start of text.
|
|
25
|
+
* Returns header (trimmed) and remaining body.
|
|
26
|
+
*/
|
|
27
|
+
function extractHeader(text: string): { header: string; body: string } {
|
|
28
|
+
const raw = String(text ?? '');
|
|
29
|
+
const match = /^\s*<!--[\s\S]*?-->\s*/.exec(raw);
|
|
30
|
+
if (match) {
|
|
31
|
+
const header = match[0].trim();
|
|
32
|
+
const body = raw.slice(match[0].length);
|
|
33
|
+
return { header, body };
|
|
34
|
+
}
|
|
35
|
+
return { header: '', body: raw };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Split raw file text into trimmed, non-empty entries.
|
|
40
|
+
* Strips leading `<!--...-->` header before splitting.
|
|
41
|
+
*/
|
|
42
|
+
export function parseEntries(text: string): string[] {
|
|
43
|
+
const { body } = extractHeader(String(text ?? ''));
|
|
44
|
+
// Split strictly by ENTRY_DELIMITER, then trim and filter.
|
|
45
|
+
// For robustness, also handle cases where delimiter may have surrounding spaces
|
|
46
|
+
// by normalizing split result via trim.
|
|
47
|
+
return body
|
|
48
|
+
.split(ENTRY_DELIMITER)
|
|
49
|
+
.map((e) => e.trim())
|
|
50
|
+
.filter((e) => e.length > 0);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Serialize entries into canonical file text.
|
|
55
|
+
*/
|
|
56
|
+
export function serializeEntries(entries: string[]): string {
|
|
57
|
+
return entries.length === 0 ? '' : entries.join(ENTRY_DELIMITER) + '\n';
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Merge two delimited texts, dedup by stripId, preserve local order then remote-only appended.
|
|
62
|
+
* Header comment (`<!--...-->`) is preserved from local if present, otherwise from remote.
|
|
63
|
+
* @returns merged text and count of added entries.
|
|
64
|
+
*/
|
|
65
|
+
export function mergeDelimited(
|
|
66
|
+
localText: string,
|
|
67
|
+
remoteText: string,
|
|
68
|
+
): { mergedText: string; added: number } {
|
|
69
|
+
const localHeader = extractHeader(String(localText ?? '')).header;
|
|
70
|
+
const remoteHeader = extractHeader(String(remoteText ?? '')).header;
|
|
71
|
+
const header = localHeader || remoteHeader || '';
|
|
72
|
+
|
|
73
|
+
const localEntries = parseEntries(String(localText ?? ''));
|
|
74
|
+
const remoteEntries = parseEntries(String(remoteText ?? ''));
|
|
75
|
+
|
|
76
|
+
const seen = new Set<string>(localEntries.map((e) => stripId(e)));
|
|
77
|
+
const merged = [...localEntries];
|
|
78
|
+
let added = 0;
|
|
79
|
+
|
|
80
|
+
for (const entry of remoteEntries) {
|
|
81
|
+
const key = stripId(entry);
|
|
82
|
+
if (!seen.has(key)) {
|
|
83
|
+
seen.add(key);
|
|
84
|
+
merged.push(entry);
|
|
85
|
+
added++;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const body = serializeEntries(merged);
|
|
90
|
+
let mergedText: string;
|
|
91
|
+
if (header) {
|
|
92
|
+
if (body === '') {
|
|
93
|
+
mergedText = header + '\n';
|
|
94
|
+
} else {
|
|
95
|
+
mergedText = header + '\n' + body;
|
|
96
|
+
}
|
|
97
|
+
} else {
|
|
98
|
+
mergedText = body;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return { mergedText, added };
|
|
102
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
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
|
+
/**
|
|
7
|
+
* The peer SSH target as THIS machine sees it. `remoteHost` in the shared
|
|
8
|
+
* settings store travels between the two machines (it is written by whichever
|
|
9
|
+
* machine saved it and copied with the rest of the store), so a machine can
|
|
10
|
+
* inherit the other machine's address — which resolves to itself there. This
|
|
11
|
+
* file is machine-local and outranks the shared store, exactly like the tunnel
|
|
12
|
+
* profile owns `domains.tunnel`.
|
|
13
|
+
*/
|
|
14
|
+
export const PEER_HOST_REL = 'dsh-maestro-sync/peer.json';
|
|
15
|
+
|
|
16
|
+
/** DSH home the host resolves when no explicit one is given. */
|
|
17
|
+
export function defaultDshHome(): string {
|
|
18
|
+
return process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function peerHostPath(dshHome: string): string {
|
|
22
|
+
return path.join(dshHome, PEER_HOST_REL);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* This machine's own peer target, or null when it was never set (callers then
|
|
27
|
+
* fall back to the shared store). An unreadable or invalid file is null, never
|
|
28
|
+
* a throw: the peer of a machine that has none is simply not known yet.
|
|
29
|
+
*/
|
|
30
|
+
export function readPeerHost(dshHome?: string): string | null {
|
|
31
|
+
const home = dshHome ?? defaultDshHome();
|
|
32
|
+
try {
|
|
33
|
+
const parsed = JSON.parse(fs.readFileSync(peerHostPath(home), 'utf-8'));
|
|
34
|
+
const host = (parsed as Record<string, unknown> | null)?.remoteHost;
|
|
35
|
+
return typeof host === 'string' && host.length > 0 ? validateHost(host.trim()) : null;
|
|
36
|
+
} catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Record this machine's peer target; returns the validated host. */
|
|
42
|
+
export function writePeerHost(dshHome: string, host: string): string {
|
|
43
|
+
const valid = validateHost(host.trim());
|
|
44
|
+
const file = peerHostPath(dshHome);
|
|
45
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
46
|
+
const tmp = `${file}.tmp.${process.pid}`;
|
|
47
|
+
fs.writeFileSync(tmp, `${JSON.stringify({ remoteHost: valid, writtenAt: new Date().toISOString() }, null, 2)}\n`, { mode: 0o600 });
|
|
48
|
+
fs.renameSync(tmp, file);
|
|
49
|
+
try {
|
|
50
|
+
fs.chmodSync(file, 0o600);
|
|
51
|
+
} catch {
|
|
52
|
+
/* best effort on filesystems without POSIX modes */
|
|
53
|
+
}
|
|
54
|
+
return valid;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Drop this machine's peer target; the shared store takes over again. */
|
|
58
|
+
export function clearPeerHost(dshHome: string): boolean {
|
|
59
|
+
try {
|
|
60
|
+
fs.unlinkSync(peerHostPath(dshHome));
|
|
61
|
+
return true;
|
|
62
|
+
} catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
export interface ProcessResult {
|
|
4
|
+
stdout: Buffer;
|
|
5
|
+
stderr: Buffer;
|
|
6
|
+
exitCode: number;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface ProcessRunner {
|
|
10
|
+
run(file: string, args: readonly string[], options?: { input?: Buffer; timeoutMs?: number; onLine?: (line: string) => void }): Promise<ProcessResult>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Maximum combined output before we kill the child (fail-closed, avoids OOM). */
|
|
14
|
+
const MAX_BUFFER_BYTES = 20 * 1024 * 1024;
|
|
15
|
+
|
|
16
|
+
export interface NodeProcessRunnerOptions {
|
|
17
|
+
/**
|
|
18
|
+
* Injectable spawn. Tests need a child that never emits `'close'` (a
|
|
19
|
+
* grandchild holding the stdio pipes does that for real), which no real
|
|
20
|
+
* process can reproduce deterministically.
|
|
21
|
+
*/
|
|
22
|
+
spawn?: typeof spawn;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export class NodeProcessRunner implements ProcessRunner {
|
|
26
|
+
private readonly spawnChild: typeof spawn;
|
|
27
|
+
|
|
28
|
+
constructor(options: NodeProcessRunnerOptions = {}) {
|
|
29
|
+
this.spawnChild = options.spawn ?? spawn;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async run(file: string, args: readonly string[], options?: { input?: Buffer; timeoutMs?: number; onLine?: (line: string) => void }): Promise<ProcessResult> {
|
|
33
|
+
return new Promise<ProcessResult>((resolve, reject) => {
|
|
34
|
+
// argv-only, never shell — caller may pass filenames with spaces/metachars as single argv items
|
|
35
|
+
// Detached on POSIX so the child leads its own process group; killTree() needs
|
|
36
|
+
// that to reach the grandchildren it spawns.
|
|
37
|
+
const child = this.spawnChild(file, args as string[], {
|
|
38
|
+
shell: false,
|
|
39
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
40
|
+
detached: process.platform !== 'win32',
|
|
41
|
+
});
|
|
42
|
+
const stdoutChunks: Buffer[] = [];
|
|
43
|
+
const stderrChunks: Buffer[] = [];
|
|
44
|
+
let stdoutLen = 0;
|
|
45
|
+
let stderrLen = 0;
|
|
46
|
+
let timeout: NodeJS.Timeout | undefined;
|
|
47
|
+
let settled = false;
|
|
48
|
+
// line-buffered stdout delivery for progress callbacks (ssh sha256sum streaming)
|
|
49
|
+
let lineBuf = '';
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Single owner of the promise's fate.
|
|
53
|
+
*
|
|
54
|
+
* The timeout, `'error'` and `'close'` race for it and the first caller
|
|
55
|
+
* wins; later ones are dropped. Without that, a child that finally closes
|
|
56
|
+
* after a timeout kill would resolve a promise the caller was already told
|
|
57
|
+
* failed. Every path clears the timer here, so no branch can leave one
|
|
58
|
+
* armed.
|
|
59
|
+
*/
|
|
60
|
+
const settle = (finish: () => void) => {
|
|
61
|
+
if (settled) return;
|
|
62
|
+
settled = true;
|
|
63
|
+
if (timeout) clearTimeout(timeout);
|
|
64
|
+
finish();
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Kill the child and the processes it spawned.
|
|
69
|
+
*
|
|
70
|
+
* SIGKILL to the direct child alone leaves its grandchildren alive while
|
|
71
|
+
* they keep the inherited stdio open — ssh's `ProxyCommand cloudflared
|
|
72
|
+
* access ssh` and git's `git-remote-https` are the real cases — so the
|
|
73
|
+
* timeout stops bounding anything. POSIX: the child is spawned detached,
|
|
74
|
+
* so it leads its own process group and `-pid` reaches the whole tree.
|
|
75
|
+
* Windows has no process-group signal and no SIGKILL semantics, so only
|
|
76
|
+
* the child is killed there: the caller is still never stuck, but a
|
|
77
|
+
* grandchild may outlive the call.
|
|
78
|
+
*/
|
|
79
|
+
const killTree = () => {
|
|
80
|
+
if (process.platform !== 'win32' && typeof child.pid === 'number' && child.pid > 0) {
|
|
81
|
+
try { process.kill(-child.pid, 'SIGKILL'); return; } catch { /* fall through to the direct kill */ }
|
|
82
|
+
}
|
|
83
|
+
try { child.kill('SIGKILL'); } catch {}
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Kill, then release the pipes. Order is load-bearing: destroying the
|
|
88
|
+
* stdio streams can make Node emit `'close'`, so the outcome must already
|
|
89
|
+
* be settled or that `'close'` would resolve a fake success.
|
|
90
|
+
*/
|
|
91
|
+
const teardown = () => {
|
|
92
|
+
killTree();
|
|
93
|
+
child.stdout?.destroy();
|
|
94
|
+
child.stderr?.destroy();
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const killForBounds = () => {
|
|
98
|
+
if (settled) return;
|
|
99
|
+
settle(() => reject(new Error(`process "${file}" output exceeded ${MAX_BUFFER_BYTES} bytes`)));
|
|
100
|
+
teardown();
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
if (options?.timeoutMs) {
|
|
104
|
+
const timeoutMs = options.timeoutMs;
|
|
105
|
+
timeout = setTimeout(() => {
|
|
106
|
+
// Reject at the deadline instead of waiting for `'close'`: a grandchild
|
|
107
|
+
// that inherited the pipes keeps `'close'` from firing at all, which is
|
|
108
|
+
// what made this "timeout" unbounded.
|
|
109
|
+
settle(() => reject(new Error(`process "${file} ${args.join(' ')}" timed out after ${timeoutMs}ms`)));
|
|
110
|
+
teardown();
|
|
111
|
+
}, timeoutMs);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const deliverLines = () => {
|
|
115
|
+
if (!options?.onLine) return;
|
|
116
|
+
let idx: number;
|
|
117
|
+
while ((idx = lineBuf.indexOf('\n')) !== -1) {
|
|
118
|
+
const line = lineBuf.slice(0, idx).replace(/\r$/, '');
|
|
119
|
+
lineBuf = lineBuf.slice(idx + 1);
|
|
120
|
+
if (line.trim()) options.onLine?.(line);
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
child.stdout?.on('data', (chunk: Buffer) => {
|
|
125
|
+
const buf = Buffer.from(chunk);
|
|
126
|
+
stdoutLen += buf.length;
|
|
127
|
+
if (stdoutLen > MAX_BUFFER_BYTES) {
|
|
128
|
+
killForBounds();
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
stdoutChunks.push(buf);
|
|
132
|
+
if (options?.onLine) {
|
|
133
|
+
lineBuf += buf.toString('utf-8');
|
|
134
|
+
deliverLines();
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
child.stderr?.on('data', (chunk: Buffer) => {
|
|
138
|
+
const buf = Buffer.from(chunk);
|
|
139
|
+
stderrLen += buf.length;
|
|
140
|
+
if (stdoutLen + stderrLen > MAX_BUFFER_BYTES) {
|
|
141
|
+
killForBounds();
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
stderrChunks.push(buf);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
child.on('error', (err) => {
|
|
148
|
+
settle(() => reject(err));
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
child.on('close', (code) => {
|
|
152
|
+
settle(() => resolve({
|
|
153
|
+
stdout: Buffer.concat(stdoutChunks),
|
|
154
|
+
stderr: Buffer.concat(stderrChunks),
|
|
155
|
+
exitCode: code ?? 0,
|
|
156
|
+
}));
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
// A stdin pipe whose reader already exited reports EPIPE as an
|
|
160
|
+
// asynchronous stream `'error'` event, not as a throw — and an unhandled
|
|
161
|
+
// stream error becomes a process-level uncaughtException, which the boot
|
|
162
|
+
// guard turns into `proc.exit(1)`. Swallowing it here is correct: the
|
|
163
|
+
// child is gone, and its exit status (not the failed write) is what the
|
|
164
|
+
// caller acts on. Measured before this listener: a 1 MiB write into
|
|
165
|
+
// `bash -c 'exit 0'` escaped as EPIPE on 20/20 attempts.
|
|
166
|
+
child.stdin?.on('error', () => {});
|
|
167
|
+
if (options?.input) {
|
|
168
|
+
try { child.stdin?.write(options.input); } catch {}
|
|
169
|
+
}
|
|
170
|
+
try { child.stdin?.end(); } catch {}
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function createProcessRunner(): ProcessRunner {
|
|
176
|
+
return new NodeProcessRunner();
|
|
177
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remote commit agent for dsh-maestro-sync.
|
|
3
|
+
*
|
|
4
|
+
* The only remote code executed by the transport is this fixed, versioned
|
|
5
|
+
* POSIX sh helper. It is installed under `<dshRoot>/.maestro-sync/bin/`
|
|
6
|
+
* (`ensureAgent`) and invoked as a fixed protocol command. Three ops:
|
|
7
|
+
* - `maestro-sync-commit <operationId>` (commit path): reads a JSONL
|
|
8
|
+
* manifest from stdin, whose paths were validated as eligible beforehand;
|
|
9
|
+
* the only dynamic data that crosses to the remote is that manifest.
|
|
10
|
+
* - `maestro-sync-commit machine-id`: prints `<dshRoot>/machine-id`.
|
|
11
|
+
* - `maestro-sync-commit tunnel-patch <profile>`: reads the tunnel domain
|
|
12
|
+
* from `<dshRoot>/dsh-maestro-remote/tunnel-profiles/<profile>/`
|
|
13
|
+
* `settings-tunnel.json` on the remote itself and rewrites ONLY the
|
|
14
|
+
* `domains.tunnel` value inside `<dshRoot>/dsh-maestro-config/settings.json`
|
|
15
|
+
* (JSON-aware object assignment, atomic tmp+rename, mode 0600). The
|
|
16
|
+
* tunnel domain is a named-tunnel OBJECT, never a bare string — a
|
|
17
|
+
* 2026-09-09 string write clobbered the object shape and took a tunnel
|
|
18
|
+
* down, so non-object values fail closed on both sides.
|
|
19
|
+
* No settings bytes ever cross the wire in
|
|
20
|
+
* either direction; prints `PATCHED <sha256>` or `UNCHANGED <sha256>`.
|
|
21
|
+
* Single-writer discipline (runs post-sync, operator-serialized) plus
|
|
22
|
+
* the already-equal no-op check make expected-sha CAS unnecessary here:
|
|
23
|
+
* concurrent writers can only converge on the same profile value.
|
|
24
|
+
*
|
|
25
|
+
* CAS semantics (compare-and-swap, fail closed):
|
|
26
|
+
* - expected `<sha256>`: the current target must hash to exactly that value;
|
|
27
|
+
* any mismatch (or a vanished target) is CONCURRENT_MODIFICATION and the
|
|
28
|
+
* target is never overwritten.
|
|
29
|
+
* - expected `absent`: the target must not exist; if it appeared concurrently
|
|
30
|
+
* the publish is rejected.
|
|
31
|
+
* - On success the helper backs the target up beside the file, then atomically
|
|
32
|
+
* renames the staged artifact into place (`mv` on the same filesystem).
|
|
33
|
+
* - Any failure exits non-zero; no partial overwrite ever occurs.
|
|
34
|
+
*/
|
|
35
|
+
export const REMOTE_AGENT_NAME = 'maestro-sync-commit';
|
|
36
|
+
export const REMOTE_AGENT_REL = '.maestro-sync/bin/maestro-sync-commit';
|
|
37
|
+
|
|
38
|
+
export function remoteAgentSource(): string {
|
|
39
|
+
return `#!/bin/sh
|
|
40
|
+
# maestro-sync-commit — fixed remote CAS publisher for dsh-maestro-sync.
|
|
41
|
+
# Usage: maestro-sync-commit <operationId> | machine-id | tunnel-patch <profile>
|
|
42
|
+
# Commit path reads a JSONL manifest from stdin. Each line is one object:
|
|
43
|
+
# {"path":"<eligible rel path>","expected":"<sha256 hex>|absent"}
|
|
44
|
+
# Staged artifacts live under <dshRoot>/.maestro-sync/stage/<operationId>/<path>.
|
|
45
|
+
# Publishes to <dshRoot>/<path> only after compare-and-swap; on mismatch it
|
|
46
|
+
# reports CONCURRENT_MODIFICATION and never overwrites. Committed targets are
|
|
47
|
+
# backed up beside the file as <path>.bak.<ts>.<pid>. Any failure exits non-zero.
|
|
48
|
+
# machine-id prints <dshRoot>/machine-id. tunnel-patch rewrites only
|
|
49
|
+
# domains.tunnel in <dshRoot>/dsh-maestro-config/settings.json from the named
|
|
50
|
+
# profile (see header comment); both print machine-readable lines and never touch stdin.
|
|
51
|
+
set -u
|
|
52
|
+
|
|
53
|
+
die() { echo "maestro-sync-commit: $*" >&2; exit 1; }
|
|
54
|
+
|
|
55
|
+
[ "$#" -ge 1 ] || die "usage: maestro-sync-commit <operationId> | machine-id | tunnel-patch <profile>"
|
|
56
|
+
|
|
57
|
+
# The helper lives at <dshRoot>/.maestro-sync/bin/maestro-sync-commit, so the
|
|
58
|
+
# DSH root is two levels up from $0 (no local shell ever expands it).
|
|
59
|
+
self="$0"
|
|
60
|
+
dsh_root=$(CDPATH= cd -- "$(dirname -- "$self")/../.." 2>/dev/null && pwd) || die "cannot resolve dsh root from $self"
|
|
61
|
+
[ -n "$dsh_root" ] || die "empty dsh root"
|
|
62
|
+
|
|
63
|
+
cmd="$1"
|
|
64
|
+
|
|
65
|
+
# --- op: machine-id ---
|
|
66
|
+
if [ "$cmd" = "machine-id" ]; then
|
|
67
|
+
[ "$#" -eq 1 ] || die "usage: maestro-sync-commit machine-id"
|
|
68
|
+
id_file="$dsh_root/machine-id"
|
|
69
|
+
[ -f "$id_file" ] || die "no machine-id under $dsh_root"
|
|
70
|
+
id=$(tr -d ' \\t\\r\\n' < "$id_file")
|
|
71
|
+
[ -n "$id" ] || die "empty machine-id"
|
|
72
|
+
printf '%s\\n' "$id"
|
|
73
|
+
exit 0
|
|
74
|
+
fi
|
|
75
|
+
|
|
76
|
+
# --- op: tunnel-patch ---
|
|
77
|
+
if [ "$cmd" = "tunnel-patch" ]; then
|
|
78
|
+
[ "$#" -eq 2 ] || die "usage: maestro-sync-commit tunnel-patch <profile>"
|
|
79
|
+
profile="$2"
|
|
80
|
+
case "$profile" in
|
|
81
|
+
''|*/*|*..*|*' '*|*'"'*|*"'"'*|*'\\'*|.*) die "unsafe profile name" ;;
|
|
82
|
+
esac
|
|
83
|
+
command -v python3 >/dev/null 2>&1 || die "TUNNEL_PATCH_UNSUPPORTED: python3 not found on remote"
|
|
84
|
+
profile_settings="$dsh_root/dsh-maestro-remote/tunnel-profiles/$profile/settings-tunnel.json"
|
|
85
|
+
settings="$dsh_root/dsh-maestro-config/settings.json"
|
|
86
|
+
[ -f "$profile_settings" ] || die "no tunnel profile: $profile"
|
|
87
|
+
[ -f "$settings" ] || die "no settings.json under $dsh_root/dsh-maestro-config"
|
|
88
|
+
# JSON-aware object assignment of domains.tunnel only; every other key is
|
|
89
|
+
# preserved. The profile value MUST be a named-tunnel object (mode/hostname)
|
|
90
|
+
# — a bare string fails closed instead of clobbering the object shape.
|
|
91
|
+
out=$(python3 - "$profile_settings" "$settings" <<'PYEOF'
|
|
92
|
+
import hashlib, json, os, sys
|
|
93
|
+
prof_path, settings_path = sys.argv[1], sys.argv[2]
|
|
94
|
+
try:
|
|
95
|
+
prof = json.load(open(prof_path, encoding='utf-8'))
|
|
96
|
+
doc = json.load(open(settings_path, encoding='utf-8'))
|
|
97
|
+
except Exception as e:
|
|
98
|
+
sys.exit('invalid JSON: %s' % e)
|
|
99
|
+
tunnel = (prof.get('domains') or {}).get('tunnel')
|
|
100
|
+
if not isinstance(tunnel, dict) or not tunnel.get('mode') or not tunnel.get('hostname'):
|
|
101
|
+
sys.exit('profile tunnel is not a named-tunnel object')
|
|
102
|
+
if not isinstance(doc.get('domains'), dict):
|
|
103
|
+
sys.exit('settings has no domains object')
|
|
104
|
+
if doc['domains'].get('tunnel') == tunnel:
|
|
105
|
+
raw = open(settings_path, encoding='utf-8').read()
|
|
106
|
+
print('UNCHANGED ' + hashlib.sha256(raw.encode('utf-8')).hexdigest())
|
|
107
|
+
else:
|
|
108
|
+
doc['domains']['tunnel'] = tunnel
|
|
109
|
+
new = json.dumps(doc, indent=2) + '\\n'
|
|
110
|
+
tmp = settings_path + '.tmp.' + str(os.getpid())
|
|
111
|
+
with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), 'w', encoding='utf-8') as f:
|
|
112
|
+
f.write(new)
|
|
113
|
+
f.flush()
|
|
114
|
+
os.fsync(f.fileno())
|
|
115
|
+
os.replace(tmp, settings_path)
|
|
116
|
+
print('PATCHED ' + hashlib.sha256(new.encode('utf-8')).hexdigest())
|
|
117
|
+
PYEOF
|
|
118
|
+
) || die "tunnel-patch failed"
|
|
119
|
+
printf '%s\\n' "$out"
|
|
120
|
+
exit 0
|
|
121
|
+
fi
|
|
122
|
+
|
|
123
|
+
# --- op: commit (default) ---
|
|
124
|
+
[ "$#" -eq 1 ] || die "usage: maestro-sync-commit <operationId>"
|
|
125
|
+
op="$1"
|
|
126
|
+
|
|
127
|
+
stage_dir="$dsh_root/.maestro-sync/stage/$op"
|
|
128
|
+
[ -d "$stage_dir" ] || die "no staged operation $op under $dsh_root/.maestro-sync"
|
|
129
|
+
|
|
130
|
+
# sha256sum is coreutils; fall back to macOS shasum for dev hosts.
|
|
131
|
+
if ! command -v sha256sum >/dev/null 2>&1; then
|
|
132
|
+
sha256sum() { shasum -a 256 "$1" | awk '{print $1}'; }
|
|
133
|
+
fi
|
|
134
|
+
|
|
135
|
+
fail=0
|
|
136
|
+
while IFS= read -r line; do
|
|
137
|
+
[ -n "$line" ] || continue
|
|
138
|
+
case "$line" in
|
|
139
|
+
'{'*) ;;
|
|
140
|
+
*) echo "maestro-sync-commit: invalid manifest line" >&2; fail=1; continue ;;
|
|
141
|
+
esac
|
|
142
|
+
rel=$(printf '%s' "$line" | sed -n 's/^.*"path":"\\([^"]*\\)".*$/\\1/p')
|
|
143
|
+
expected=$(printf '%s' "$line" | sed -n 's/^.*"expected":"\\([^"]*\\)".*$/\\1/p')
|
|
144
|
+
[ -n "$rel" ] || { echo "maestro-sync-commit: manifest line without path" >&2; fail=1; continue; }
|
|
145
|
+
case "$rel" in
|
|
146
|
+
/*|*..*|*' '*|*'"'*|*"'"'*|*'\\'*)
|
|
147
|
+
echo "maestro-sync-commit: unsafe path in manifest: $rel" >&2; fail=1; continue ;;
|
|
148
|
+
esac
|
|
149
|
+
staged="$stage_dir/$rel"
|
|
150
|
+
[ -f "$staged" ] || { echo "maestro-sync-commit: missing staged artifact: $rel" >&2; fail=1; continue; }
|
|
151
|
+
target="$dsh_root/$rel"
|
|
152
|
+
if [ "$expected" = "absent" ]; then
|
|
153
|
+
if [ -e "$target" ]; then
|
|
154
|
+
echo "CONCURRENT_MODIFICATION: $rel (target exists, expected absent)" >&2
|
|
155
|
+
fail=1
|
|
156
|
+
continue
|
|
157
|
+
fi
|
|
158
|
+
else
|
|
159
|
+
case "$expected" in
|
|
160
|
+
[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]*) ;;
|
|
161
|
+
*) echo "maestro-sync-commit: invalid expected hash for $rel" >&2; fail=1; continue ;;
|
|
162
|
+
esac
|
|
163
|
+
if [ -f "$target" ]; then
|
|
164
|
+
actual=$(sha256sum "$target" 2>/dev/null | awk '{print $1}') || { echo "maestro-sync-commit: cannot hash $rel" >&2; fail=1; continue; }
|
|
165
|
+
if [ "$actual" != "$expected" ]; then
|
|
166
|
+
echo "CONCURRENT_MODIFICATION: $rel (target sha256 $actual != expected $expected)" >&2
|
|
167
|
+
fail=1
|
|
168
|
+
continue
|
|
169
|
+
fi
|
|
170
|
+
else
|
|
171
|
+
echo "CONCURRENT_MODIFICATION: $rel (target vanished)" >&2
|
|
172
|
+
fail=1
|
|
173
|
+
continue
|
|
174
|
+
fi
|
|
175
|
+
fi
|
|
176
|
+
if [ -f "$target" ]; then
|
|
177
|
+
bak="$target.bak.$(date +%s).$$"
|
|
178
|
+
if ! cp -p "$target" "$bak" 2>/dev/null; then
|
|
179
|
+
echo "maestro-sync-commit: backup failed for $rel" >&2
|
|
180
|
+
fail=1
|
|
181
|
+
continue
|
|
182
|
+
fi
|
|
183
|
+
fi
|
|
184
|
+
if ! mkdir -p "$(dirname -- "$target")" 2>/dev/null; then
|
|
185
|
+
echo "maestro-sync-commit: cannot create target dir for $rel" >&2
|
|
186
|
+
fail=1
|
|
187
|
+
continue
|
|
188
|
+
fi
|
|
189
|
+
if ! mv "$staged" "$target" 2>/dev/null; then
|
|
190
|
+
echo "maestro-sync-commit: publish failed for $rel" >&2
|
|
191
|
+
fail=1
|
|
192
|
+
continue
|
|
193
|
+
fi
|
|
194
|
+
echo "committed $rel"
|
|
195
|
+
done
|
|
196
|
+
[ "$fail" -eq 0 ] || exit 1
|
|
197
|
+
exit 0
|
|
198
|
+
`;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Structural verification of the helper source — used by tests and by
|
|
203
|
+
* `ensureAgent` before shipping the script to the remote host.
|
|
204
|
+
*/
|
|
205
|
+
export function verifyRemoteAgentSource(src: string): string {
|
|
206
|
+
if (!src.startsWith('#!/bin/sh')) throw new Error('remote agent must be POSIX sh');
|
|
207
|
+
if (src.includes('[[ ')) throw new Error('remote agent must not use bash [[ ]]');
|
|
208
|
+
if (/\bfunction\s+/.test(src)) throw new Error('remote agent must not use bash function keyword');
|
|
209
|
+
if (!src.includes('CONCURRENT_MODIFICATION')) throw new Error('remote agent must implement CAS');
|
|
210
|
+
if (!src.includes('.maestro-sync/stage/')) throw new Error('remote agent must read staged artifacts');
|
|
211
|
+
if (!src.includes('sha256')) throw new Error('remote agent must hash targets');
|
|
212
|
+
return src;
|
|
213
|
+
}
|