@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
package/src/host/bin.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import * as path from 'node:path'
|
|
2
|
+
import { acquireBootLock, releaseBootLock, type BootLockDeps } from './boot-lock.js'
|
|
3
|
+
import { markBootBoundary, dshWebLogPath } from './restart-guards.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* D6 — one restart implementation per concern.
|
|
7
|
+
*
|
|
8
|
+
* `performSingleBootRestart` (the daemon's path) takes `boot.lock` and appends
|
|
9
|
+
* the `[supervisor] boot-boundary` sentinel through `markBootBoundary()`. The
|
|
10
|
+
* manual skill script (`skills/dsh-safe-restart/scripts/restart-dsh-web.sh`)
|
|
11
|
+
* must do exactly the same, or a human restart is neither serialized with a
|
|
12
|
+
* supervised one (two boots racing for :3082) nor scoped in the append-only log
|
|
13
|
+
* (the poller reads the previous boot's crash as this boot's).
|
|
14
|
+
*
|
|
15
|
+
* This module is that shared entry point: the script shells out to
|
|
16
|
+
* `lib/bin.js boot-guard acquire|release --pid <shell pid>` instead of writing
|
|
17
|
+
* either marker itself.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** Log the boundary sentinel belongs to (isolated home wins when set, for rehearsals). */
|
|
21
|
+
export function bootBoundaryLogPath(env: NodeJS.ProcessEnv = process.env): string {
|
|
22
|
+
if (env.DSH_WEB_LOG) return env.DSH_WEB_LOG
|
|
23
|
+
if (env.DSH_HOME) return path.join(env.DSH_HOME, 'dsh-web.log')
|
|
24
|
+
return dshWebLogPath()
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface BootGuard {
|
|
28
|
+
acquired: boolean
|
|
29
|
+
release: () => void
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Acquire the shared boot lock for `deps.pid` and append the boundary sentinel.
|
|
34
|
+
* The sentinel is written first-thing after the lock, matching
|
|
35
|
+
* `performSingleBootRestart` (marker before the port goes down).
|
|
36
|
+
*/
|
|
37
|
+
export function acquireBootGuard(deps: BootLockDeps = {}, logPath?: string): BootGuard {
|
|
38
|
+
const lock = acquireBootLock(deps)
|
|
39
|
+
if (!lock) return { acquired: false, release: () => {} }
|
|
40
|
+
markBootBoundary(logPath ?? bootBoundaryLogPath())
|
|
41
|
+
return { acquired: true, release: lock.release }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Release the lock only if `pid` still owns it (see releaseBootLock). */
|
|
45
|
+
export function releaseBootGuard(pid: number, deps: BootLockDeps = {}): boolean {
|
|
46
|
+
return releaseBootLock(pid, deps)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export const BOOT_GUARD_BUSY_EXIT = 3
|
|
50
|
+
export const BOOT_GUARD_USAGE_EXIT = 64
|
|
51
|
+
|
|
52
|
+
/** CLI used by the skill script; returns the process exit code. */
|
|
53
|
+
export function runBootGuardCli(args: string[], deps: BootLockDeps = {}, logPath?: string): number {
|
|
54
|
+
const action = args[0]
|
|
55
|
+
const pidIdx = args.indexOf('--pid')
|
|
56
|
+
const pid = pidIdx === -1 ? Number.NaN : Number(args[pidIdx + 1])
|
|
57
|
+
if (!Number.isInteger(pid) || pid <= 0) {
|
|
58
|
+
console.error('boot-guard: --pid <owner pid> is required (pass the shell PID: $$)')
|
|
59
|
+
return BOOT_GUARD_USAGE_EXIT
|
|
60
|
+
}
|
|
61
|
+
if (action === 'acquire') {
|
|
62
|
+
const guard = acquireBootGuard({ ...deps, pid }, logPath)
|
|
63
|
+
if (!guard.acquired) {
|
|
64
|
+
console.error('busy: another boot holds boot.lock')
|
|
65
|
+
return BOOT_GUARD_BUSY_EXIT
|
|
66
|
+
}
|
|
67
|
+
console.log('acquired')
|
|
68
|
+
return 0
|
|
69
|
+
}
|
|
70
|
+
if (action === 'release') {
|
|
71
|
+
releaseBootGuard(pid, deps)
|
|
72
|
+
return 0
|
|
73
|
+
}
|
|
74
|
+
console.error(`boot-guard: unknown action: ${action ?? ''} (expected acquire|release)`)
|
|
75
|
+
return BOOT_GUARD_USAGE_EXIT
|
|
76
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import * as fs from 'node:fs'
|
|
2
|
+
import * as path from 'node:path'
|
|
3
|
+
import * as os from 'node:os'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* One-boot-at-a-time guard (spec D4, incident 2026-09-13). Every path that
|
|
7
|
+
* starts dsh web takes this lock from the moment the restart is issued until
|
|
8
|
+
* the port answers, so a racing tick, the dsh_web_restart hand-off, or a
|
|
9
|
+
* rollback that fires while the first boot is still coming up skips instead of
|
|
10
|
+
* producing the second systemd start that made the incident's log tail toxic.
|
|
11
|
+
*
|
|
12
|
+
* The lock is an atomically created file (`O_EXCL`) carrying `{pid, ts}`. An
|
|
13
|
+
* existing lock is honored unless its owner is gone or it has outlived
|
|
14
|
+
* `staleMs` (the boot budget). Node exposes no flock(2) binding; O_EXCL plus
|
|
15
|
+
* PID liveness gives the same mutual exclusion deterministically, and every
|
|
16
|
+
* side effect is injectable so tests never touch the real ~/.dsh/.supervisor.
|
|
17
|
+
*/
|
|
18
|
+
export const DEFAULT_BOOT_LOCK_STALE_MS = 180_000
|
|
19
|
+
|
|
20
|
+
export interface BootLockDeps {
|
|
21
|
+
lockPath?: string
|
|
22
|
+
createExclusive?: (p: string, body: string) => boolean
|
|
23
|
+
readLock?: (p: string) => string | undefined
|
|
24
|
+
remove?: (p: string) => void
|
|
25
|
+
pidAlive?: (pid: number) => boolean
|
|
26
|
+
now?: () => number
|
|
27
|
+
staleMs?: number
|
|
28
|
+
sleep?: (ms: number) => Promise<void>
|
|
29
|
+
portUp?: () => Promise<boolean>
|
|
30
|
+
waitTimeoutMs?: number
|
|
31
|
+
pollMs?: number
|
|
32
|
+
/**
|
|
33
|
+
* Owner recorded in the lock file; defaults to this process. The skill script
|
|
34
|
+
* (D6) holds the lock with the shell's own PID, so liveness stays meaningful
|
|
35
|
+
* while the shell performs the restart.
|
|
36
|
+
*/
|
|
37
|
+
pid?: number
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface BootLock {
|
|
41
|
+
path: string
|
|
42
|
+
release: () => void
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function bootLockPath(): string {
|
|
46
|
+
return process.env.DSH_SUPERVISOR_BOOT_LOCK ?? path.join(os.homedir(), '.dsh/.supervisor/boot.lock')
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function resolved(deps: BootLockDeps) {
|
|
50
|
+
return {
|
|
51
|
+
lockPath: deps.lockPath ?? bootLockPath(),
|
|
52
|
+
createExclusive: deps.createExclusive ?? ((p: string, body: string) => {
|
|
53
|
+
try {
|
|
54
|
+
fs.mkdirSync(path.dirname(p), { recursive: true })
|
|
55
|
+
fs.writeFileSync(p, body, { flag: 'wx', mode: 0o600 })
|
|
56
|
+
return true
|
|
57
|
+
} catch { return false }
|
|
58
|
+
}),
|
|
59
|
+
readLock: deps.readLock ?? ((p: string) => {
|
|
60
|
+
try { return fs.readFileSync(p, 'utf8') } catch { return undefined }
|
|
61
|
+
}),
|
|
62
|
+
remove: deps.remove ?? ((p: string) => { try { fs.unlinkSync(p) } catch {} }),
|
|
63
|
+
pidAlive: deps.pidAlive ?? ((pid: number) => {
|
|
64
|
+
if (!Number.isInteger(pid) || pid <= 0) return false
|
|
65
|
+
if (pid === process.pid) return true
|
|
66
|
+
try { process.kill(pid, 0); return true } catch { return false }
|
|
67
|
+
}),
|
|
68
|
+
now: deps.now ?? (() => Date.now()),
|
|
69
|
+
staleMs: deps.staleMs ?? DEFAULT_BOOT_LOCK_STALE_MS,
|
|
70
|
+
sleep: deps.sleep ?? ((ms: number) => new Promise<void>(r => setTimeout(r, ms))),
|
|
71
|
+
portUp: deps.portUp ?? defaultPortUp,
|
|
72
|
+
waitTimeoutMs: deps.waitTimeoutMs ?? DEFAULT_BOOT_LOCK_STALE_MS,
|
|
73
|
+
pollMs: deps.pollMs ?? 3_000,
|
|
74
|
+
pid: deps.pid ?? process.pid,
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function parseLock(raw: string | undefined): { pid: number; ts: number } | undefined {
|
|
79
|
+
if (!raw) return undefined
|
|
80
|
+
try {
|
|
81
|
+
const j = JSON.parse(raw)
|
|
82
|
+
if (typeof j?.pid === 'number' && typeof j?.ts === 'number') return { pid: j.pid, ts: j.ts }
|
|
83
|
+
} catch {}
|
|
84
|
+
return undefined
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Take the boot lock, or return undefined when another live boot owns it. */
|
|
88
|
+
export function acquireBootLock(deps: BootLockDeps = {}): BootLock | undefined {
|
|
89
|
+
const d = resolved(deps)
|
|
90
|
+
const body = JSON.stringify({ pid: d.pid, ts: d.now() })
|
|
91
|
+
const take = (): BootLock | undefined =>
|
|
92
|
+
d.createExclusive(d.lockPath, body) ? { path: d.lockPath, release: () => d.remove(d.lockPath) } : undefined
|
|
93
|
+
const first = take()
|
|
94
|
+
if (first) return first
|
|
95
|
+
const existing = parseLock(d.readLock(d.lockPath))
|
|
96
|
+
const stale = existing === undefined || !d.pidAlive(existing.pid) || d.now() - existing.ts > d.staleMs
|
|
97
|
+
if (!stale) return undefined
|
|
98
|
+
d.remove(d.lockPath)
|
|
99
|
+
return take()
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Release the lock only when `pid` still owns it. A boot that lost the race (or
|
|
104
|
+
* whose stale lock was taken over) must never delete the winner's lock file.
|
|
105
|
+
*/
|
|
106
|
+
export function releaseBootLock(pid: number, deps: BootLockDeps = {}): boolean {
|
|
107
|
+
const d = resolved(deps)
|
|
108
|
+
const existing = parseLock(d.readLock(d.lockPath))
|
|
109
|
+
if (existing === undefined || existing.pid !== pid) return false
|
|
110
|
+
d.remove(d.lockPath)
|
|
111
|
+
return true
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function defaultPortUp(): Promise<boolean> {
|
|
115
|
+
try {
|
|
116
|
+
const ctrl = new AbortController()
|
|
117
|
+
const t = setTimeout(() => ctrl.abort(), 2000)
|
|
118
|
+
try {
|
|
119
|
+
// Any HTTP answer (200/303/401) means the boot is serving.
|
|
120
|
+
await fetch('http://127.0.0.1:3080/', { signal: ctrl.signal })
|
|
121
|
+
return true
|
|
122
|
+
} finally { clearTimeout(t) }
|
|
123
|
+
} catch { return false }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Poll the port until it answers or the boot budget expires. */
|
|
127
|
+
export async function waitForPort(deps: BootLockDeps = {}): Promise<boolean> {
|
|
128
|
+
const d = resolved(deps)
|
|
129
|
+
const deadline = d.now() + d.waitTimeoutMs
|
|
130
|
+
for (;;) {
|
|
131
|
+
try { if (await d.portUp()) return true } catch {}
|
|
132
|
+
if (d.now() >= deadline) return false
|
|
133
|
+
await d.sleep(d.pollMs)
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Run `fn` under the boot lock, then hold the lock until the port answers (or
|
|
139
|
+
* the boot budget expires). Returns `{ acquired: false }` — without running
|
|
140
|
+
* `fn` — when another boot already owns the lock.
|
|
141
|
+
*/
|
|
142
|
+
export async function withBootLock<T>(
|
|
143
|
+
fn: () => Promise<T>,
|
|
144
|
+
deps: BootLockDeps = {},
|
|
145
|
+
): Promise<{ acquired: boolean; value?: T }> {
|
|
146
|
+
const lock = acquireBootLock(deps)
|
|
147
|
+
if (!lock) return { acquired: false }
|
|
148
|
+
try {
|
|
149
|
+
const value = await fn()
|
|
150
|
+
await waitForPort(deps)
|
|
151
|
+
return { acquired: true, value }
|
|
152
|
+
} finally {
|
|
153
|
+
lock.release()
|
|
154
|
+
}
|
|
155
|
+
}
|
package/src/host/cli.ts
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
import { Supervisor } from './supervisor.js'
|
|
2
|
+
import { pollHealth } from './health-poller.js'
|
|
3
|
+
import { writeLKG, verifyLKG, isLkgExcluded, failureReason } from './snapshot.js'
|
|
4
|
+
import * as fs from 'node:fs'
|
|
5
|
+
import * as path from 'node:path'
|
|
6
|
+
import * as os from 'node:os'
|
|
7
|
+
import { resolveHarnessRoot } from './paths.js'
|
|
8
|
+
import { isSelfCopyError, checkPlannedRestart, readRestartRequest, clearPlannedRestart } from './restart-guards.js'
|
|
9
|
+
import { readSupervisorConfig } from './config.js'
|
|
10
|
+
|
|
11
|
+
export interface RestoreResult {
|
|
12
|
+
/** Snapshot id that was restored. */
|
|
13
|
+
target: string
|
|
14
|
+
/** Files (and symlinks) restored into the live DSH home. */
|
|
15
|
+
restored: number
|
|
16
|
+
/** Entries that were not restored, each with a reason. Never silent. */
|
|
17
|
+
skipped: Array<{ path: string; reason: string }>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Make a destination (recursively) writable before overwriting it (D3).
|
|
22
|
+
*
|
|
23
|
+
* `fs.cpSync` copies into an existing destination file with
|
|
24
|
+
* `O_WRONLY|O_CREAT|O_TRUNC`, so a mode-`0400` object fails with EACCES and
|
|
25
|
+
* aborts the whole restore — the exact 2026-09-13 failure
|
|
26
|
+
* (`EACCES, Permission denied '.../attachments/v1/objects/f8'`). Only entries
|
|
27
|
+
* that actually lack the needed bit are chmod-ed, so a healthy tree costs
|
|
28
|
+
* stats, not a chmod per file.
|
|
29
|
+
*/
|
|
30
|
+
function makeWritable(target: string): void {
|
|
31
|
+
let st: fs.Stats
|
|
32
|
+
try {
|
|
33
|
+
st = fs.lstatSync(target)
|
|
34
|
+
} catch {
|
|
35
|
+
return
|
|
36
|
+
}
|
|
37
|
+
if (st.isSymbolicLink()) return
|
|
38
|
+
if (st.isDirectory()) {
|
|
39
|
+
if ((st.mode & 0o300) !== 0o300) {
|
|
40
|
+
try { fs.chmodSync(target, st.mode | 0o300) } catch {}
|
|
41
|
+
}
|
|
42
|
+
let names: string[] = []
|
|
43
|
+
try { names = fs.readdirSync(target) } catch { return }
|
|
44
|
+
for (const name of names) makeWritable(path.join(target, name))
|
|
45
|
+
return
|
|
46
|
+
}
|
|
47
|
+
if ((st.mode & 0o200) === 0) {
|
|
48
|
+
try { fs.chmodSync(target, st.mode | 0o200) } catch {}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Files (and symlinks) a restore of this source entry would write. */
|
|
53
|
+
function countRestorable(srcPath: string): number {
|
|
54
|
+
try {
|
|
55
|
+
const st = fs.lstatSync(srcPath)
|
|
56
|
+
if (st.isDirectory()) return walkFiles(srcPath).length
|
|
57
|
+
return 1
|
|
58
|
+
} catch {
|
|
59
|
+
return 0
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function walkFiles(dir: string, base: string = dir): string[] {
|
|
64
|
+
const out: string[] = []
|
|
65
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
66
|
+
const full = path.join(dir, entry.name)
|
|
67
|
+
if (entry.isDirectory()) out.push(...walkFiles(full, base))
|
|
68
|
+
else if (entry.isFile()) out.push(path.relative(base, full))
|
|
69
|
+
}
|
|
70
|
+
return out
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Copy a chosen LKG snapshot back into the DSH home. Recent snapshots are
|
|
75
|
+
* tried newest-first, skipping any that still carry a failing plugin so a
|
|
76
|
+
* broken bundle is not restored. `sessions/` and every other runtime-data entry
|
|
77
|
+
* is deliberately NOT restored (D1) — session logs are append-only truth and
|
|
78
|
+
* rolling them back to a snapshot would drop every turn recorded after that
|
|
79
|
+
* snapshot.
|
|
80
|
+
*
|
|
81
|
+
* Never throws for a per-entry failure: the failures are collected into
|
|
82
|
+
* `skipped` and the caller reports them (D2/D4). The only throw left is "there
|
|
83
|
+
* is no snapshot at all", which the caller must know about.
|
|
84
|
+
*
|
|
85
|
+
* @returns the restore summary (snapshot id + what was/was not restored).
|
|
86
|
+
*/
|
|
87
|
+
export async function rollbackLKG(opts: { dshHome: string; lkgRoot: string; failingPlugin?: string }): Promise<RestoreResult> {
|
|
88
|
+
const { dshHome, lkgRoot, failingPlugin } = opts
|
|
89
|
+
const entries = fs.existsSync(lkgRoot) ? fs.readdirSync(lkgRoot).sort() : []
|
|
90
|
+
if (!entries.length) throw new Error('no LKG to rollback to')
|
|
91
|
+
const candidates = [...entries].reverse().slice(0, 3)
|
|
92
|
+
let chosen: string | undefined
|
|
93
|
+
for (const cand of candidates) {
|
|
94
|
+
if (!failingPlugin) { chosen = cand; break }
|
|
95
|
+
try {
|
|
96
|
+
const pkgPath = path.join(lkgRoot, cand, 'profiles/web/package.json')
|
|
97
|
+
if (!fs.existsSync(pkgPath)) { chosen = cand; break }
|
|
98
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
|
|
99
|
+
const bundles: string[] = pkg?.dsh?.profile?.bundles ?? []
|
|
100
|
+
const deps = pkg?.dependencies ?? {}
|
|
101
|
+
const hasFailing = bundles.some((b: string) => b.includes(failingPlugin)) || Object.keys(deps).some(k => k.includes(failingPlugin))
|
|
102
|
+
if (!hasFailing) { chosen = cand; break }
|
|
103
|
+
console.log(`[supervisor] skipping LKG ${cand} still contains failing plugin ${failingPlugin}`)
|
|
104
|
+
} catch { chosen = cand; break }
|
|
105
|
+
}
|
|
106
|
+
const target = chosen ?? entries[entries.length - 1]
|
|
107
|
+
const src = path.join(lkgRoot, target)
|
|
108
|
+
const skipped: RestoreResult['skipped'] = []
|
|
109
|
+
let restored = 0
|
|
110
|
+
for (const entry of fs.readdirSync(src)) {
|
|
111
|
+
if (entry === 'manifest.json') continue
|
|
112
|
+
if (isLkgExcluded(entry)) {
|
|
113
|
+
// Legacy snapshots (taken before D1) still carry runtime data. Restoring
|
|
114
|
+
// a stale sessions/ over live sessions can lose a log, and a 0400
|
|
115
|
+
// attachment blob is what aborted this very path — report, never restore.
|
|
116
|
+
skipped.push({ path: entry, reason: 'runtime data excluded from the LKG scope (not required to boot)' })
|
|
117
|
+
continue
|
|
118
|
+
}
|
|
119
|
+
const srcPath = path.join(src, entry)
|
|
120
|
+
const destPath = path.join(dshHome, entry)
|
|
121
|
+
try {
|
|
122
|
+
// Skip if src and dest are the same file (e.g. symlink to same target like ~/.dsh/AGENTS.md)
|
|
123
|
+
try {
|
|
124
|
+
if (fs.existsSync(srcPath) && fs.existsSync(destPath) && fs.realpathSync(srcPath) === fs.realpathSync(destPath)) continue
|
|
125
|
+
} catch {}
|
|
126
|
+
makeWritable(destPath)
|
|
127
|
+
fs.cpSync(srcPath, destPath, { recursive: true, force: true })
|
|
128
|
+
restored += countRestorable(srcPath)
|
|
129
|
+
} catch (e: any) {
|
|
130
|
+
if (isSelfCopyError(String(e?.message ?? ''))) continue
|
|
131
|
+
skipped.push({ path: entry, reason: failureReason(e) })
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return { target, restored, skipped }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export async function runCli(args: string[]): Promise<void> {
|
|
138
|
+
const cmd = args[2] ?? '--help'
|
|
139
|
+
if (cmd === '--help' || cmd === '-h' || cmd === 'help') {
|
|
140
|
+
console.log(`Usage: dsh-web-supervisor <command>
|
|
141
|
+
|
|
142
|
+
Commands:
|
|
143
|
+
daemon Run supervisor daemon (poll every 3s)
|
|
144
|
+
status Show health + LKG status
|
|
145
|
+
logs Tail supervisor reports
|
|
146
|
+
rollback --to <ts> Rollback to LKG <ts>
|
|
147
|
+
resume [--within <dur>] List interrupted sessions (filter by time, e.g. 5m, 30s, 1h)
|
|
148
|
+
boot-guard acquire|release --pid <pid> Take/release boot.lock + boot-boundary (used by the safe-restart script)
|
|
149
|
+
`)
|
|
150
|
+
return
|
|
151
|
+
}
|
|
152
|
+
if (cmd === 'boot-guard') {
|
|
153
|
+
const { runBootGuardCli } = await import('./boot-guard.js')
|
|
154
|
+
process.exit(runBootGuardCli(args.slice(3)))
|
|
155
|
+
}
|
|
156
|
+
if (cmd === 'status') {
|
|
157
|
+
const health = await pollHealth()
|
|
158
|
+
console.log(`up: ${health.up}, httpCode: ${health.httpCode}, error: ${health.error ?? 'none'}`)
|
|
159
|
+
const lkgRoot = path.join(os.homedir(), '.dsh/.supervisor/lkg')
|
|
160
|
+
if (fs.existsSync(lkgRoot)) {
|
|
161
|
+
const entries = fs.readdirSync(lkgRoot).sort()
|
|
162
|
+
console.log(`LKG: ${entries.length} snapshots, latest: ${entries[entries.length - 1] ?? 'none'}`)
|
|
163
|
+
if (entries.length) {
|
|
164
|
+
const ok = await verifyLKG(path.join(lkgRoot, entries[entries.length - 1])).catch(() => false)
|
|
165
|
+
console.log(`latest LKG valid: ${ok}`)
|
|
166
|
+
}
|
|
167
|
+
} else {
|
|
168
|
+
console.log('LKG: none')
|
|
169
|
+
}
|
|
170
|
+
return
|
|
171
|
+
}
|
|
172
|
+
if (cmd === 'resume') {
|
|
173
|
+
const withinIdx = args.indexOf('--within')
|
|
174
|
+
let withinMs: number | undefined
|
|
175
|
+
if (withinIdx !== -1) {
|
|
176
|
+
const raw = args[withinIdx + 1] ?? ''
|
|
177
|
+
const { parseDuration } = await import('./resume.js')
|
|
178
|
+
withinMs = parseDuration(raw)
|
|
179
|
+
if (withinMs === undefined) {
|
|
180
|
+
console.error(`invalid --within value: ${raw} (use e.g. 5m, 30s, 1h)`)
|
|
181
|
+
process.exit(1)
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
const { findInterrupted } = await import('./resume.js')
|
|
185
|
+
const res = await findInterrupted(undefined, withinMs !== undefined ? { withinMs } : undefined)
|
|
186
|
+
if (withinMs !== undefined) {
|
|
187
|
+
console.log(`interrupted within ${args[withinIdx + 1]}: ${res.interrupted.length}/${res.scanned}`)
|
|
188
|
+
} else {
|
|
189
|
+
console.log(`interrupted: ${res.interrupted.length}/${res.scanned}`)
|
|
190
|
+
}
|
|
191
|
+
for (const id of res.interrupted) console.log(id)
|
|
192
|
+
return
|
|
193
|
+
}
|
|
194
|
+
if (cmd === 'daemon') {
|
|
195
|
+
console.log('[supervisor] starting daemon — poll every 3s, Ctrl+C to stop')
|
|
196
|
+
const dshHome = path.join(os.homedir(), '.dsh')
|
|
197
|
+
const lkgRoot = path.join(os.homedir(), '.dsh/.supervisor/lkg')
|
|
198
|
+
const failedRoot = path.join(os.homedir(), '.dsh/.supervisor/failed')
|
|
199
|
+
const reportsRoot = path.join(os.homedir(), '.dsh/.supervisor/reports')
|
|
200
|
+
const supervisor = new Supervisor({
|
|
201
|
+
pollHealth: () => pollHealth(),
|
|
202
|
+
writeLKG: () => writeLKG(dshHome, lkgRoot),
|
|
203
|
+
writeFailed: () => writeLKG(dshHome, failedRoot),
|
|
204
|
+
writeReport: async ({ ts, health, action, logTail, gitDiff }: any) => {
|
|
205
|
+
const { writeReport, collectGitDiff } = await import('./report.js')
|
|
206
|
+
const { collectLogTail } = await import('./health-poller.js')
|
|
207
|
+
// Prefer supervisor-provided tail/diff (from health.logTail); fallback to live collect
|
|
208
|
+
let tail: string = logTail ?? (health as any).logTail ?? ''
|
|
209
|
+
if (!tail) {
|
|
210
|
+
try { tail = await collectLogTail() } catch { tail = '' }
|
|
211
|
+
}
|
|
212
|
+
let diff: string = gitDiff ?? ''
|
|
213
|
+
if (!diff) {
|
|
214
|
+
try {
|
|
215
|
+
const harnessRoot = resolveHarnessRoot()
|
|
216
|
+
diff = await collectGitDiff(harnessRoot).catch(() => '')
|
|
217
|
+
if (!diff) {
|
|
218
|
+
// fallback: try git diff in cwd
|
|
219
|
+
const { execSync } = await import('node:child_process')
|
|
220
|
+
try { diff = execSync('git diff 2>/dev/null | head -n 200', { encoding: 'utf-8', timeout: 2000 }) } catch { diff = '' }
|
|
221
|
+
}
|
|
222
|
+
} catch { diff = '' }
|
|
223
|
+
}
|
|
224
|
+
return writeReport({ reportsRoot, ts, health, gitDiff: diff, logTail: tail, action })
|
|
225
|
+
},
|
|
226
|
+
rollback: async () => {
|
|
227
|
+
const { execSync } = await import('node:child_process')
|
|
228
|
+
// Extract failing plugin from current log tail if possible
|
|
229
|
+
let failingPlugin: string | undefined
|
|
230
|
+
try {
|
|
231
|
+
const tail = fs.readFileSync(path.join(os.homedir(), '.dsh/dsh-web.log'), 'utf8').slice(-5000)
|
|
232
|
+
const m = tail.match(/@ddtcorex\/dsh-maestro-[a-z0-9_-]+/i) ?? tail.match(/dsh-maestro-[a-z0-9_-]+/i)
|
|
233
|
+
if (m) failingPlugin = m[0].replace(/^@ddtcorex\//, '')
|
|
234
|
+
} catch {}
|
|
235
|
+
const res = await rollbackLKG({ dshHome, lkgRoot, failingPlugin })
|
|
236
|
+
console.log(`[supervisor] rolled back to ${res.target} — ${res.restored} file(s) restored${failingPlugin ? ` (avoiding ${failingPlugin})` : ''}`)
|
|
237
|
+
// D4: a partial restore is surfaced loudly, never silently.
|
|
238
|
+
if (res.skipped.length) {
|
|
239
|
+
console.log(`[supervisor] ROLLBACK PARTIAL: ${res.skipped.length} entr(ies) not restored`)
|
|
240
|
+
for (const s of res.skipped.slice(0, 10)) console.log(`[supervisor] skipped ${s.path}: ${s.reason}`)
|
|
241
|
+
if (res.skipped.length > 10) console.log(`[supervisor] … ${res.skipped.length - 10} more`)
|
|
242
|
+
}
|
|
243
|
+
// Reconcile node_modules from restored package.json (critical for link: deps)
|
|
244
|
+
try {
|
|
245
|
+
execSync('pnpm --dir ~/.dsh/profiles/web install --silent', { timeout: 30000, stdio: 'pipe' })
|
|
246
|
+
console.log('[supervisor] pnpm install reconciled profiles/web')
|
|
247
|
+
} catch (e: any) {
|
|
248
|
+
console.log(`[supervisor] pnpm install failed: ${e?.message ?? String(e)}`)
|
|
249
|
+
}
|
|
250
|
+
return res
|
|
251
|
+
},
|
|
252
|
+
restartWeb: async () => {
|
|
253
|
+
// One implementation of the single-boot restart: marker (TTL = boot
|
|
254
|
+
// budget) → boot.lock → serialized systemd start → direct-node nohup
|
|
255
|
+
// only on hosts where the unit does not exist (D4/D5).
|
|
256
|
+
const { performSingleBootRestart, DEFAULT_BOOT_GRACE_MS } = await import('./restart-web.js')
|
|
257
|
+
let grace = DEFAULT_BOOT_GRACE_MS
|
|
258
|
+
try {
|
|
259
|
+
const cfg = await readSupervisorConfig()
|
|
260
|
+
if (typeof (cfg as any).bootGraceMs === 'number' && (cfg as any).bootGraceMs > 0) grace = (cfg as any).bootGraceMs
|
|
261
|
+
} catch {}
|
|
262
|
+
const res = await performSingleBootRestart({ bootGraceMs: grace })
|
|
263
|
+
if (!res.restarted) console.log(`[supervisor] restart skipped: ${res.reason ?? 'boot lock held'}`)
|
|
264
|
+
},
|
|
265
|
+
notify: async (msg) => console.log(`[notify] ${msg}`),
|
|
266
|
+
isPlannedRestartActive: () => checkPlannedRestart(),
|
|
267
|
+
// dsh_web_restart marker ownership: the daemon acts on the marker. After
|
|
268
|
+
// the restart, scan recent session logs for torn tails (an in-flight
|
|
269
|
+
// session truncated by the restart) and report; the marker is cleared in
|
|
270
|
+
// the supervisor's own finally block and again here as a safety net.
|
|
271
|
+
readRestartRequest: () => readRestartRequest(),
|
|
272
|
+
onRestartRequestHandled: async () => {
|
|
273
|
+
const { scanSessions } = await import('./scan.js')
|
|
274
|
+
const res = await scanSessions(path.join(os.homedir(), '.dsh'), { withinMs: 10 * 60 * 1000 }).catch(() => ({ scanned: 0, torn: [] }))
|
|
275
|
+
if (res.torn.length) {
|
|
276
|
+
console.log(`[supervisor] post-self-restart scan: ${res.torn.length} torn session log(s)`)
|
|
277
|
+
} else {
|
|
278
|
+
console.log('[supervisor] post-self-restart scan: clean')
|
|
279
|
+
}
|
|
280
|
+
void clearPlannedRestart()
|
|
281
|
+
},
|
|
282
|
+
})
|
|
283
|
+
await supervisor.start()
|
|
284
|
+
// keep process alive
|
|
285
|
+
await new Promise(() => {})
|
|
286
|
+
}
|
|
287
|
+
console.log(`unknown command: ${cmd} — try --help`)
|
|
288
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
2
|
+
|
|
3
|
+
type RpcResult<T> = { ok: true; value: T } | { ok: false; error: { code: string; message: string; details: object } }
|
|
4
|
+
type RpcErrorDetailsMap = { 'bad-request': { issues: object[] } }
|
|
5
|
+
import { createMaestroConfigService, type MaestroConfigService } from './service.js'
|
|
6
|
+
|
|
7
|
+
export const name = 'maestro-config'
|
|
8
|
+
export const inject = ['connection']
|
|
9
|
+
|
|
10
|
+
const RPC_CHANNEL = '/dsh-maestro-config'
|
|
11
|
+
|
|
12
|
+
declare module '@deepseek-ai/cordis' {
|
|
13
|
+
interface Context {
|
|
14
|
+
maestroConfig: MaestroConfigService
|
|
15
|
+
connection: { rpc: { handle: (channel: string, handler: (endpoint: string, payload: unknown) => Promise<RpcResult<unknown>>, opts?: unknown) => () => void } }
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function ok<T>(value: T): RpcResult<T> {
|
|
20
|
+
return { ok: true, value }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function fail(message: string): RpcResult<never> {
|
|
24
|
+
return {
|
|
25
|
+
ok: false,
|
|
26
|
+
error: {
|
|
27
|
+
code: 'bad-request',
|
|
28
|
+
message,
|
|
29
|
+
// Synthetic details: app-level validation error shoehorned into DSH's
|
|
30
|
+
// shared RPC error taxonomy (same approach across maestro packages).
|
|
31
|
+
details: { issues: [{ message }] } as RpcErrorDetailsMap['bad-request'],
|
|
32
|
+
},
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Publish maestroConfig over the shared store + loopback RPC for clients.
|
|
38
|
+
* Exposes guard/guardBlacklist/supervisor/notifier domains (Task 1 validators)
|
|
39
|
+
* via generic get/set — validation is delegated to the lib's domain validators.
|
|
40
|
+
* Host also handles '/dsh-maestro-config/get' and '/dsh-maestro-config/set'
|
|
41
|
+
* style calls through the single channel with endpoint dispatch.
|
|
42
|
+
*/
|
|
43
|
+
export function apply(ctx: Context): void {
|
|
44
|
+
const svc = createMaestroConfigService()
|
|
45
|
+
ctx.provide('maestroConfig', svc)
|
|
46
|
+
ctx.effect(() =>
|
|
47
|
+
ctx.connection.rpc.handle(RPC_CHANNEL, async (endpoint: string, payload: unknown): Promise<RpcResult<unknown>> => {
|
|
48
|
+
const body = (payload ?? {}) as { domain?: string; patch?: object }
|
|
49
|
+
if (endpoint === 'list') {
|
|
50
|
+
return ok({ domains: await svc.listDomains() })
|
|
51
|
+
}
|
|
52
|
+
if (endpoint === 'get') {
|
|
53
|
+
if (typeof body.domain !== 'string') return fail('domain (string) is required')
|
|
54
|
+
// guard / guardBlacklist / supervisor / notifier are all valid domains here
|
|
55
|
+
return ok(await svc.get(body.domain))
|
|
56
|
+
}
|
|
57
|
+
if (endpoint === 'set') {
|
|
58
|
+
if (typeof body.domain !== 'string' || typeof body.patch !== 'object' || body.patch === null) {
|
|
59
|
+
return fail('domain (string) and patch (object) are required')
|
|
60
|
+
}
|
|
61
|
+
await svc.set(body.domain, body.patch)
|
|
62
|
+
return ok(null)
|
|
63
|
+
}
|
|
64
|
+
if (endpoint === 'unset') {
|
|
65
|
+
const key = (payload ?? {}) as { key?: unknown }
|
|
66
|
+
if (typeof body.domain !== 'string' || typeof key.key !== 'string') {
|
|
67
|
+
return fail('domain (string) and key (string) are required')
|
|
68
|
+
}
|
|
69
|
+
try {
|
|
70
|
+
return ok({ deleted: await svc.unset(body.domain, key.key) })
|
|
71
|
+
} catch (e: any) {
|
|
72
|
+
return fail(e?.message ?? String(e))
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return fail(`unknown endpoint: ${String(endpoint)}`)
|
|
76
|
+
})
|
|
77
|
+
)
|
|
78
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import * as lib from '../store/index.js'
|
|
2
|
+
// Guard and guardBlacklist writes through the Settings card must always be validated.
|
|
3
|
+
import '../guard/validators.js'
|
|
4
|
+
|
|
5
|
+
export interface MaestroConfigService {
|
|
6
|
+
/** Union of schema-registered domains and domains present in the store file. */
|
|
7
|
+
listDomains(): Promise<string[]>
|
|
8
|
+
get(domain: string): Promise<unknown>
|
|
9
|
+
/** Deep-merges the patch into the domain (same semantics as the lib). */
|
|
10
|
+
set(domain: string, patch: object): Promise<void>
|
|
11
|
+
/** Deletes one top-level key of a domain; false when there was nothing to delete. */
|
|
12
|
+
unset(domain: string, key: string): Promise<boolean>
|
|
13
|
+
onChange(cb: (domain: string) => void): () => void
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Thin facade over @ddtcorex/dsh-maestro-config-lib. `dshHome` defaults to the
|
|
18
|
+
* lib's resolution (explicit > DSH_HOME env > ~/.dsh); tests inject a tmpdir.
|
|
19
|
+
*/
|
|
20
|
+
export function createMaestroConfigService(opts?: { dshHome?: string }): MaestroConfigService {
|
|
21
|
+
const libOpts = opts?.dshHome ? { dshHome: opts.dshHome } : undefined
|
|
22
|
+
return {
|
|
23
|
+
async listDomains() {
|
|
24
|
+
const doc = await lib.load(libOpts)
|
|
25
|
+
return [...new Set([...lib.definedDomains(), ...Object.keys(doc.domains)])]
|
|
26
|
+
},
|
|
27
|
+
async get(domain) {
|
|
28
|
+
return lib.get(domain, libOpts)
|
|
29
|
+
},
|
|
30
|
+
async set(domain, patch) {
|
|
31
|
+
await lib.set(domain, patch, libOpts)
|
|
32
|
+
},
|
|
33
|
+
async unset(domain, key) {
|
|
34
|
+
return lib.unset(domain, key, libOpts)
|
|
35
|
+
},
|
|
36
|
+
onChange(cb) {
|
|
37
|
+
return lib.onChange(cb)
|
|
38
|
+
},
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { load } from './store/index.js'
|
|
2
|
+
import { readFlat } from './store/legacy.js'
|
|
3
|
+
|
|
4
|
+
export async function readSupervisorConfig(): Promise<Record<string, any>> {
|
|
5
|
+
try {
|
|
6
|
+
const doc: any = await load()
|
|
7
|
+
if (doc?.domains?.supervisor && typeof doc.domains.supervisor === 'object' && !Array.isArray(doc.domains.supervisor)) {
|
|
8
|
+
return doc.domains.supervisor as Record<string, any>
|
|
9
|
+
}
|
|
10
|
+
} catch {}
|
|
11
|
+
try {
|
|
12
|
+
const f: any = await readFlat().catch(() => ({}))
|
|
13
|
+
if (f?.supervisor && typeof f.supervisor === 'object' && !Array.isArray(f.supervisor)) {
|
|
14
|
+
return f.supervisor as Record<string, any>
|
|
15
|
+
}
|
|
16
|
+
} catch {}
|
|
17
|
+
return {}
|
|
18
|
+
}
|