@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,337 @@
|
|
|
1
|
+
import * as fs from 'node:fs'
|
|
2
|
+
import * as path from 'node:path'
|
|
3
|
+
import * as crypto from 'node:crypto'
|
|
4
|
+
|
|
5
|
+
interface ManifestEntry { path: string; sha256: string }
|
|
6
|
+
interface Manifest { ts: string; files: ManifestEntry[] }
|
|
7
|
+
|
|
8
|
+
export interface SnapshotResult {
|
|
9
|
+
ts: string
|
|
10
|
+
/** Files (and symlinks) copied into this snapshot. */
|
|
11
|
+
files: number
|
|
12
|
+
/** Entries that could not be copied; the snapshot stays usable either way. */
|
|
13
|
+
skipped: Array<{ path: string; reason: string }>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface SnapshotDeps {
|
|
17
|
+
/**
|
|
18
|
+
* Copy one regular file, preserving `mode`. Injectable so a failing entry
|
|
19
|
+
* (the EACCES a read-only attachment object produces) can be table-tested
|
|
20
|
+
* without depending on the host's uid or filesystem quirks.
|
|
21
|
+
*/
|
|
22
|
+
copyFile?: (src: string, dest: string, mode: number) => void
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* DSH-home entries the last-known-good snapshot deliberately never copies.
|
|
27
|
+
*
|
|
28
|
+
* The LKG exists to recover a boot that fails while loading the plugin tree, so
|
|
29
|
+
* it holds boot **configuration**: `profiles/` (the plugin tree with its
|
|
30
|
+
* lockfile, `cordis.patch.yml` and sidecars), the per-plugin config directories
|
|
31
|
+
* and the settings documents. Everything below is runtime **data** — it is
|
|
32
|
+
* written continuously while `dsh web` runs, so restoring a snapshot of it can
|
|
33
|
+
* only lose newer state, and some of it is hostile to a bulk copy:
|
|
34
|
+
*
|
|
35
|
+
* - `sessions/` — append-only transcripts. Restoring a stale copy over live
|
|
36
|
+
* sessions drops every turn recorded after the snapshot, i.e. the recovery
|
|
37
|
+
* path would lose the log it is supposed to protect.
|
|
38
|
+
* - `attachments/` — content-addressed blobs stored mode `0400`. That read-only
|
|
39
|
+
* bit is exactly what made the 2026-09-13 rollback abort with
|
|
40
|
+
* `EACCES: Permission denied '.../attachments/v1/objects/f8'`.
|
|
41
|
+
* - `plugins-src/` — plugin source cache, re-fetched on demand (~400 MB host).
|
|
42
|
+
* - `.supervisor/` — the LKG root itself lives inside the DSH home, so copying
|
|
43
|
+
* it would recurse into every retained snapshot.
|
|
44
|
+
*
|
|
45
|
+
* This list is data, not a heuristic: the copy loop and the restore loop both
|
|
46
|
+
* consult `isLkgExcluded()`, and the table test pins the rule.
|
|
47
|
+
*/
|
|
48
|
+
export const LKG_EXCLUDED_ENTRIES: readonly string[] = [
|
|
49
|
+
'sessions',
|
|
50
|
+
'attachments',
|
|
51
|
+
'plugins-src',
|
|
52
|
+
'.supervisor',
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* True when a DSH-home-relative path must never enter (or leave) the LKG.
|
|
57
|
+
*
|
|
58
|
+
* The named entries match the first path segment; `*.log` matches by basename
|
|
59
|
+
* anywhere, because append-only logs are data at any depth and a restored stale
|
|
60
|
+
* `dsh-web.log` would poison the boot-boundary scan.
|
|
61
|
+
*/
|
|
62
|
+
export function isLkgExcluded(relPath: string): boolean {
|
|
63
|
+
const normalized = relPath.replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+/, '')
|
|
64
|
+
const segments = normalized.split('/').filter(s => s.length > 0 && s !== '.')
|
|
65
|
+
if (!segments.length) return false
|
|
66
|
+
if (LKG_EXCLUDED_ENTRIES.includes(segments[0]!)) return true
|
|
67
|
+
return segments[segments.length - 1]!.endsWith('.log')
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function sha256File(filePath: string): string {
|
|
71
|
+
const data = fs.readFileSync(filePath)
|
|
72
|
+
return crypto.createHash('sha256').update(data).digest('hex')
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function walkFiles(dir: string, base: string = dir): string[] {
|
|
76
|
+
const out: string[] = []
|
|
77
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
78
|
+
const full = path.join(dir, entry.name)
|
|
79
|
+
if (entry.isDirectory()) out.push(...walkFiles(full, base))
|
|
80
|
+
else if (entry.isFile()) out.push(path.relative(base, full))
|
|
81
|
+
}
|
|
82
|
+
return out
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Human-readable, bounded reason for a per-entry copy failure. */
|
|
86
|
+
export function failureReason(e: unknown): string {
|
|
87
|
+
const err = e as any
|
|
88
|
+
const code = typeof err?.code === 'string' && err.code ? `${err.code}: ` : ''
|
|
89
|
+
const message = typeof err?.message === 'string' ? err.message : String(e)
|
|
90
|
+
return `${code}${message}`.slice(0, 300)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface CopyState {
|
|
94
|
+
dshHome: string
|
|
95
|
+
copyFile: (src: string, dest: string, mode: number) => void
|
|
96
|
+
copied: number
|
|
97
|
+
skipped: Array<{ path: string; reason: string }>
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Copy one snapshot entry, collecting — never throwing — per-entry failures
|
|
102
|
+
* (D2). `fs.cpSync` aborts the whole snapshot on the first unreadable object,
|
|
103
|
+
* which is precisely how one 0400 attachment file stopped the rollback that
|
|
104
|
+
* exists to rescue a broken boot.
|
|
105
|
+
*/
|
|
106
|
+
function copyEntry(state: CopyState, src: string, dest: string, rel: string): void {
|
|
107
|
+
if (isLkgExcluded(rel)) return
|
|
108
|
+
let st: fs.Stats
|
|
109
|
+
try {
|
|
110
|
+
st = fs.lstatSync(src)
|
|
111
|
+
} catch (e) {
|
|
112
|
+
state.skipped.push({ path: rel, reason: failureReason(e) })
|
|
113
|
+
return
|
|
114
|
+
}
|
|
115
|
+
if (st.isDirectory()) {
|
|
116
|
+
let names: string[]
|
|
117
|
+
try {
|
|
118
|
+
// Directory modes are replicated only in their permission-to-traverse
|
|
119
|
+
// sense: the snapshot itself must stay readable/removable even when the
|
|
120
|
+
// source directory is not (a 0000 source dir must not produce a snapshot
|
|
121
|
+
// that nothing — including retention — can delete).
|
|
122
|
+
fs.mkdirSync(dest, { recursive: true, mode: (st.mode & 0o7777) | 0o700 })
|
|
123
|
+
names = fs.readdirSync(src)
|
|
124
|
+
} catch (e) {
|
|
125
|
+
state.skipped.push({ path: rel, reason: failureReason(e) })
|
|
126
|
+
return
|
|
127
|
+
}
|
|
128
|
+
for (const name of names) {
|
|
129
|
+
copyEntry(state, path.join(src, name), path.join(dest, name), rel ? `${rel}/${name}` : name)
|
|
130
|
+
}
|
|
131
|
+
return
|
|
132
|
+
}
|
|
133
|
+
if (st.isSymbolicLink()) {
|
|
134
|
+
try {
|
|
135
|
+
const link = fs.readlinkSync(src)
|
|
136
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true })
|
|
137
|
+
try { fs.unlinkSync(dest) } catch {}
|
|
138
|
+
fs.symlinkSync(link, dest)
|
|
139
|
+
state.copied++
|
|
140
|
+
} catch (e) {
|
|
141
|
+
state.skipped.push({ path: rel, reason: failureReason(e) })
|
|
142
|
+
}
|
|
143
|
+
return
|
|
144
|
+
}
|
|
145
|
+
if (st.isFile()) {
|
|
146
|
+
try {
|
|
147
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true })
|
|
148
|
+
state.copyFile(src, dest, st.mode & 0o7777)
|
|
149
|
+
state.copied++
|
|
150
|
+
} catch (e) {
|
|
151
|
+
state.skipped.push({ path: rel, reason: failureReason(e) })
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
// Sockets/FIFOs/devices are not boot configuration: ignored on purpose.
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export async function writeLKG(dshHome: string, lkgRoot: string, deps: SnapshotDeps = {}): Promise<SnapshotResult> {
|
|
158
|
+
// Dedupe: skip snapshot if current state identical to latest LKG (prevents 5-min unconditional growth)
|
|
159
|
+
try {
|
|
160
|
+
if (await isDuplicateLKG(dshHome, lkgRoot)) {
|
|
161
|
+
const entries = fs.readdirSync(lkgRoot).filter((n: string) => {
|
|
162
|
+
try { return fs.statSync(path.join(lkgRoot, n)).isDirectory() } catch { return false }
|
|
163
|
+
}).sort()
|
|
164
|
+
const latest = entries[entries.length - 1]
|
|
165
|
+
const manifestPath = path.join(lkgRoot, latest, 'manifest.json')
|
|
166
|
+
const manifest: Manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'))
|
|
167
|
+
return { ts: latest, files: manifest.files?.length ?? 0, skipped: [] }
|
|
168
|
+
}
|
|
169
|
+
} catch {}
|
|
170
|
+
|
|
171
|
+
const ts = new Date().toISOString().replace(/[:.]/g, '-')
|
|
172
|
+
const dest = path.join(lkgRoot, ts)
|
|
173
|
+
try {
|
|
174
|
+
fs.mkdirSync(dest, { recursive: true })
|
|
175
|
+
} catch (e) {
|
|
176
|
+
// No snapshot is better than an exception thrown into the rollback path.
|
|
177
|
+
return { ts, files: 0, skipped: [{ path: lkgRoot, reason: failureReason(e) }] }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const state: CopyState = {
|
|
181
|
+
dshHome,
|
|
182
|
+
copyFile: deps.copyFile ?? ((src, dst, mode) => {
|
|
183
|
+
fs.copyFileSync(src, dst)
|
|
184
|
+
try { fs.chmodSync(dst, mode) } catch {}
|
|
185
|
+
}),
|
|
186
|
+
copied: 0,
|
|
187
|
+
skipped: [],
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Copy only the boot configuration (D1), one entry at a time so a single
|
|
191
|
+
// unreadable file is recorded and skipped instead of aborting the snapshot (D2).
|
|
192
|
+
let topLevel: string[] = []
|
|
193
|
+
try {
|
|
194
|
+
if (fs.existsSync(dshHome)) topLevel = fs.readdirSync(dshHome)
|
|
195
|
+
} catch (e) {
|
|
196
|
+
state.skipped.push({ path: '.', reason: failureReason(e) })
|
|
197
|
+
}
|
|
198
|
+
for (const entry of topLevel) {
|
|
199
|
+
copyEntry(state, path.join(dshHome, entry), path.join(dest, entry), entry)
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
let fileList: string[] = []
|
|
203
|
+
try {
|
|
204
|
+
fileList = fs.existsSync(dest) ? walkFiles(dest) : []
|
|
205
|
+
} catch (e) {
|
|
206
|
+
state.skipped.push({ path: 'manifest', reason: failureReason(e) })
|
|
207
|
+
}
|
|
208
|
+
const manifest: Manifest = {
|
|
209
|
+
ts,
|
|
210
|
+
files: fileList
|
|
211
|
+
.filter(f => f !== 'manifest.json')
|
|
212
|
+
.map(f => ({ path: f, sha256: sha256File(path.join(dest, f)) })),
|
|
213
|
+
}
|
|
214
|
+
try {
|
|
215
|
+
fs.writeFileSync(path.join(dest, 'manifest.json'), JSON.stringify(manifest, null, 2))
|
|
216
|
+
} catch (e) {
|
|
217
|
+
state.skipped.push({ path: 'manifest.json', reason: failureReason(e) })
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Retention: keep only 3 most recent, plus age (7d) and size (5GB) caps — prevents unbounded 40GB+ growth
|
|
221
|
+
await rotateLKG(lkgRoot, 3).catch(() => {})
|
|
222
|
+
await pruneByAge(lkgRoot, 7 * 24 * 60 * 60 * 1000).catch(() => {})
|
|
223
|
+
await pruneBySize(lkgRoot, 5 * 1024 * 1024 * 1024).catch(() => {})
|
|
224
|
+
|
|
225
|
+
return { ts, files: state.copied, skipped: state.skipped }
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export async function pruneByAge(root: string, maxAgeMs: number): Promise<void> {
|
|
229
|
+
if (!fs.existsSync(root)) return
|
|
230
|
+
const now = Date.now()
|
|
231
|
+
const entries = fs.readdirSync(root).filter((n: string) => {
|
|
232
|
+
try { return fs.statSync(path.join(root, n)).isDirectory() } catch { return false }
|
|
233
|
+
})
|
|
234
|
+
for (const name of entries) {
|
|
235
|
+
try {
|
|
236
|
+
const tsStr = name.replace(/^(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d+)Z$/, '$1-$2-$3T$4:$5:$6.$7Z')
|
|
237
|
+
const ts = Date.parse(tsStr)
|
|
238
|
+
if (!isNaN(ts) && now - ts > maxAgeMs) {
|
|
239
|
+
fs.rmSync(path.join(root, name), { recursive: true, force: true })
|
|
240
|
+
}
|
|
241
|
+
} catch {}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export async function pruneBySize(root: string, maxBytes: number): Promise<void> {
|
|
246
|
+
if (!fs.existsSync(root)) return
|
|
247
|
+
const entries = fs.readdirSync(root).filter((n: string) => {
|
|
248
|
+
try { return fs.statSync(path.join(root, n)).isDirectory() } catch { return false }
|
|
249
|
+
}).sort()
|
|
250
|
+
let total = 0
|
|
251
|
+
const sizes: Array<{ name: string; size: number }> = []
|
|
252
|
+
for (const name of entries) {
|
|
253
|
+
try {
|
|
254
|
+
const p = path.join(root, name)
|
|
255
|
+
let size = 0
|
|
256
|
+
for (const f of walkFiles(p)) {
|
|
257
|
+
try { size += fs.statSync(path.join(p, f)).size } catch {}
|
|
258
|
+
}
|
|
259
|
+
sizes.push({ name, size })
|
|
260
|
+
total += size
|
|
261
|
+
} catch {}
|
|
262
|
+
}
|
|
263
|
+
for (const { name, size } of sizes) {
|
|
264
|
+
if (total <= maxBytes) break
|
|
265
|
+
try {
|
|
266
|
+
fs.rmSync(path.join(root, name), { recursive: true, force: true })
|
|
267
|
+
total -= size
|
|
268
|
+
} catch {}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export async function isDuplicateLKG(dshHome: string, lkgRoot: string): Promise<boolean> {
|
|
273
|
+
// Lightweight dedupe: if latest snapshot is <5 minutes old, skip (prevents 5-min unconditional growth)
|
|
274
|
+
// Full hash check is too heavy (would read 500MB+ each tick) and caused status timeouts
|
|
275
|
+
if (!fs.existsSync(lkgRoot)) return false
|
|
276
|
+
const entries = fs.readdirSync(lkgRoot).filter((n: string) => {
|
|
277
|
+
try { return fs.statSync(path.join(lkgRoot, n)).isDirectory() } catch { return false }
|
|
278
|
+
}).sort()
|
|
279
|
+
if (!entries.length) return false
|
|
280
|
+
const latestName = entries[entries.length - 1]
|
|
281
|
+
try {
|
|
282
|
+
const tsStr = latestName.replace(/^(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d+)Z$/, '$1-$2-$3T$4:$5:$6.$7Z')
|
|
283
|
+
const ts = Date.parse(tsStr)
|
|
284
|
+
if (!isNaN(ts) && Date.now() - ts < 5 * 60 * 1000) {
|
|
285
|
+
// If latest is recent and DSH home hasn't changed in mtime, consider duplicate
|
|
286
|
+
// Quick check: compare latest snapshot's mtime vs DSH home's newest file mtime
|
|
287
|
+
const latestPath = path.join(lkgRoot, latestName)
|
|
288
|
+
const latestMtime = fs.statSync(latestPath).mtimeMs
|
|
289
|
+
let newestFileMtime = 0
|
|
290
|
+
if (fs.existsSync(dshHome)) {
|
|
291
|
+
for (const entry of fs.readdirSync(dshHome)) {
|
|
292
|
+
// Same scope as the copy loop: runtime data changes constantly and
|
|
293
|
+
// must not defeat the dedupe for the configuration being snapshotted.
|
|
294
|
+
if (isLkgExcluded(entry)) continue
|
|
295
|
+
try {
|
|
296
|
+
const s = fs.statSync(path.join(dshHome, entry))
|
|
297
|
+
if (s.mtimeMs > newestFileMtime) newestFileMtime = s.mtimeMs
|
|
298
|
+
} catch {}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
if (newestFileMtime > 0 && newestFileMtime < latestMtime) return true
|
|
302
|
+
}
|
|
303
|
+
} catch {}
|
|
304
|
+
return false
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export async function verifyLKG(lkgPath: string): Promise<boolean> {
|
|
308
|
+
const manifestPath = path.join(lkgPath, 'manifest.json')
|
|
309
|
+
if (!fs.existsSync(manifestPath)) return false
|
|
310
|
+
try {
|
|
311
|
+
const manifest: Manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'))
|
|
312
|
+
for (const entry of manifest.files) {
|
|
313
|
+
const filePath = path.join(lkgPath, entry.path)
|
|
314
|
+
if (!fs.existsSync(filePath)) return false
|
|
315
|
+
const hash = sha256File(filePath)
|
|
316
|
+
if (hash !== entry.sha256) return false
|
|
317
|
+
}
|
|
318
|
+
return true
|
|
319
|
+
} catch {
|
|
320
|
+
return false
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
export async function rotateLKG(lkgRoot: string, keep = 3): Promise<void> {
|
|
325
|
+
if (!fs.existsSync(lkgRoot)) return
|
|
326
|
+
const entries = fs.readdirSync(lkgRoot).filter((n: string) => {
|
|
327
|
+
try { return fs.statSync(path.join(lkgRoot, n)).isDirectory() } catch { return false }
|
|
328
|
+
}).sort()
|
|
329
|
+
const toDelete = entries.slice(0, Math.max(0, entries.length - keep))
|
|
330
|
+
for (const name of toDelete) {
|
|
331
|
+
fs.rmSync(path.join(lkgRoot, name), { recursive: true, force: true })
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export async function writeFailed(dshHome: string, failedRoot: string): Promise<SnapshotResult> {
|
|
336
|
+
return writeLKG(dshHome, failedRoot)
|
|
337
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The producer-owned source kind this plugin stamps on every message it injects
|
|
3
|
+
* into a session.
|
|
4
|
+
*
|
|
5
|
+
* Session format v4 requires the producer to name itself (`plugin:<package>`)
|
|
6
|
+
* and rejects the retired bare `kind: 'plugin'` outright. `kind: 'user'` is
|
|
7
|
+
* admissible but false: these turns are machine-initiated, and consumers
|
|
8
|
+
* classify a turn by this kind — dsh-maestro-memory's write guard documents
|
|
9
|
+
* that plugin-initiated turns carry no per-turn write duty and can only honour
|
|
10
|
+
* that when the producer says who it is.
|
|
11
|
+
*
|
|
12
|
+
* Scope, so the claim stays honest: this covers the two `agent.followup`
|
|
13
|
+
* injections in `plugin.ts` and `resume-tools.ts`. The third delivery path —
|
|
14
|
+
* `promptOwnedSession` through `sessionController.prompt` — cannot carry a kind
|
|
15
|
+
* because the controller hardcodes `'user'`; that gap is documented at the call
|
|
16
|
+
* site and tracked as a follow-up in
|
|
17
|
+
* `docs/specs/2026-09-28-cross-repo-upstream-v4-lessons-design.md`.
|
|
18
|
+
*/
|
|
19
|
+
export const SUPERVISOR_SOURCE_KIND = 'plugin:@ddtcorex/dsh-maestro-core'
|
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
import { homedir } from 'node:os'
|
|
2
|
+
import { dirname, join } from 'node:path'
|
|
3
|
+
import { mkdir, open, readFile, rename, unlink, stat, rm, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { mkdirSync, readFileSync } from 'node:fs'
|
|
5
|
+
import { watch, type FSWatcher } from 'node:fs'
|
|
6
|
+
|
|
7
|
+
export interface SettingsDoc {
|
|
8
|
+
version: 1
|
|
9
|
+
domains: Record<string, unknown>
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Minimal structural validator a domain owner supplies (schemastery/zod adapters fit). */
|
|
13
|
+
export interface DomainValidator {
|
|
14
|
+
parse(value: unknown): { ok: true; value?: unknown } | { ok: false; error: string }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const EMPTY_DOC: SettingsDoc = { version: 1, domains: {} }
|
|
18
|
+
|
|
19
|
+
const domainValidators = new Map<string, DomainValidator>()
|
|
20
|
+
const changeCbs = new Set<(domain: string) => void>()
|
|
21
|
+
|
|
22
|
+
let cached: { key: string; doc: SettingsDoc; mtimeMs: number } | null = null
|
|
23
|
+
|
|
24
|
+
function resolveDshHome(explicit?: string): string {
|
|
25
|
+
return explicit ?? process.env.DSH_HOME ?? join(homedir(), '.dsh')
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function storePath(opts?: { dshHome?: string }): string {
|
|
29
|
+
return join(resolveDshHome(opts?.dshHome), 'dsh-maestro-config', 'settings.json')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Register a validator for a domain you own. Writes to it are validated on every set(). */
|
|
33
|
+
export function defineDomain(name: string, validator: DomainValidator): void {
|
|
34
|
+
domainValidators.set(name, validator)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
// change notification
|
|
39
|
+
// ---------------------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Every plugin embeds its own copy of this module, so a listener has to hear
|
|
43
|
+
* writes made by another copy (or by another process), not only writes made
|
|
44
|
+
* through the copy that owns it. While at least one listener exists we watch
|
|
45
|
+
* the settings file and compare every domain against `snapshot`; a local write
|
|
46
|
+
* refreshes `snapshot` before it fires the callbacks, so it never fires twice.
|
|
47
|
+
*
|
|
48
|
+
* The watcher resolves DSH_HOME once, when it starts. A store pinned to an
|
|
49
|
+
* explicit `dshHome` therefore stays out of the watched home and neither fires
|
|
50
|
+
* nor receives notifications for writes that go somewhere else.
|
|
51
|
+
*/
|
|
52
|
+
const WATCH_DEBOUNCE_MS = 50
|
|
53
|
+
const POLL_MS = 2_000
|
|
54
|
+
const FILE_BASENAME = 'settings.json'
|
|
55
|
+
|
|
56
|
+
let watcher: FSWatcher | null = null
|
|
57
|
+
let pollTimer: NodeJS.Timeout | null = null
|
|
58
|
+
let debounceTimer: NodeJS.Timeout | null = null
|
|
59
|
+
let snapshot: Record<string, string> = {}
|
|
60
|
+
let watchedHome: string | null = null
|
|
61
|
+
let checking = false
|
|
62
|
+
|
|
63
|
+
/** JSON text per domain, so a value change is a cheap string comparison. */
|
|
64
|
+
function fingerprint(doc: SettingsDoc): Record<string, string> {
|
|
65
|
+
const out: Record<string, string> = {}
|
|
66
|
+
for (const [domain, value] of Object.entries(doc.domains)) {
|
|
67
|
+
out[domain] = JSON.stringify(value) ?? 'undefined'
|
|
68
|
+
}
|
|
69
|
+
return out
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Seed the snapshot synchronously so a write racing `onChange` cannot slip
|
|
74
|
+
* between "listener registered" and "snapshot taken" and go unnoticed.
|
|
75
|
+
*/
|
|
76
|
+
function readSnapshotSync(home: string): Record<string, string> {
|
|
77
|
+
try {
|
|
78
|
+
return fingerprint(parseDoc(readFileSync(storePath({ dshHome: home }), 'utf8')))
|
|
79
|
+
} catch {
|
|
80
|
+
return {} // no store on disk yet: every domain is new
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function checkExternal(): Promise<void> {
|
|
85
|
+
if (changeCbs.size === 0 || watchedHome === null || checking) return
|
|
86
|
+
checking = true
|
|
87
|
+
try {
|
|
88
|
+
// load() invalidates its own cache on an mtime change, so this sees other
|
|
89
|
+
// writers' values without an extra stat.
|
|
90
|
+
const next = fingerprint(await load({ dshHome: watchedHome }))
|
|
91
|
+
const changed: string[] = []
|
|
92
|
+
for (const domain of new Set([...Object.keys(snapshot), ...Object.keys(next)])) {
|
|
93
|
+
// A domain that disappeared compares against undefined and counts as changed.
|
|
94
|
+
if (snapshot[domain] !== next[domain]) changed.push(domain)
|
|
95
|
+
}
|
|
96
|
+
snapshot = next
|
|
97
|
+
for (const domain of changed) for (const cb of [...changeCbs]) cb(domain)
|
|
98
|
+
} catch {
|
|
99
|
+
// A transient read failure must never break boot; the next tick retries.
|
|
100
|
+
} finally {
|
|
101
|
+
checking = false
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function scheduleCheck(): void {
|
|
106
|
+
if (debounceTimer) clearTimeout(debounceTimer)
|
|
107
|
+
debounceTimer = setTimeout(() => {
|
|
108
|
+
debounceTimer = null
|
|
109
|
+
void checkExternal()
|
|
110
|
+
}, WATCH_DEBOUNCE_MS)
|
|
111
|
+
debounceTimer.unref()
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function stopWatching(): void {
|
|
115
|
+
watcher?.close()
|
|
116
|
+
watcher = null
|
|
117
|
+
if (pollTimer) clearInterval(pollTimer)
|
|
118
|
+
pollTimer = null
|
|
119
|
+
if (debounceTimer) clearTimeout(debounceTimer)
|
|
120
|
+
debounceTimer = null
|
|
121
|
+
snapshot = {}
|
|
122
|
+
watchedHome = null
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function startWatching(): void {
|
|
126
|
+
if (watcher || pollTimer) return
|
|
127
|
+
const home = resolveDshHome()
|
|
128
|
+
const path = storePath({ dshHome: home })
|
|
129
|
+
watchedHome = home
|
|
130
|
+
snapshot = readSnapshotSync(home)
|
|
131
|
+
try {
|
|
132
|
+
// fs.watch is not recursive, so it only sees the file when its own
|
|
133
|
+
// directory exists; the store is the only writer of that path either way.
|
|
134
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
135
|
+
watcher = watch(dirname(path), { persistent: false }, (_event, filename) => {
|
|
136
|
+
if (filename === null || filename === FILE_BASENAME) scheduleCheck()
|
|
137
|
+
})
|
|
138
|
+
} catch {
|
|
139
|
+
watcher = null // polling below still covers the change
|
|
140
|
+
}
|
|
141
|
+
pollTimer = setInterval(() => void checkExternal(), POLL_MS)
|
|
142
|
+
pollTimer.unref()
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Fire callbacks registered through this instance after a successful set(). */
|
|
146
|
+
export function onChange(cb: (domain: string) => void): () => void {
|
|
147
|
+
changeCbs.add(cb)
|
|
148
|
+
startWatching()
|
|
149
|
+
let disposed = false
|
|
150
|
+
return () => {
|
|
151
|
+
if (disposed) return
|
|
152
|
+
disposed = true
|
|
153
|
+
changeCbs.delete(cb)
|
|
154
|
+
if (changeCbs.size === 0) stopWatching()
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Test seam: drop the memoized document and listeners (schemas are kept). */
|
|
159
|
+
export function resetForTests(): void {
|
|
160
|
+
cached = null
|
|
161
|
+
changeCbs.clear()
|
|
162
|
+
stopWatching()
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// ---------------------------------------------------------------------------
|
|
166
|
+
// locking + io
|
|
167
|
+
// ---------------------------------------------------------------------------
|
|
168
|
+
|
|
169
|
+
async function withLock<T>(path: string, fn: () => Promise<T>): Promise<T> {
|
|
170
|
+
await mkdir(dirname(path), { recursive: true }) // the store dir may not exist on first write
|
|
171
|
+
const lockPath = `${path}.lock`
|
|
172
|
+
const deadline = Date.now() + 5_000
|
|
173
|
+
let handle: Awaited<ReturnType<typeof open>> | null = null
|
|
174
|
+
for (;;) {
|
|
175
|
+
try {
|
|
176
|
+
handle = await open(lockPath, 'wx')
|
|
177
|
+
break
|
|
178
|
+
} catch (err: any) {
|
|
179
|
+
if (err?.code !== 'EEXIST') throw err
|
|
180
|
+
// Break stale locks left behind by a crashed writer.
|
|
181
|
+
try {
|
|
182
|
+
const st = await stat(lockPath)
|
|
183
|
+
if (Date.now() - st.mtimeMs > 5_000) {
|
|
184
|
+
await rm(lockPath, { force: true })
|
|
185
|
+
continue
|
|
186
|
+
}
|
|
187
|
+
} catch {
|
|
188
|
+
/* lock vanished between stat and now — just retry */
|
|
189
|
+
}
|
|
190
|
+
if (Date.now() > deadline) throw new Error(`config-lib: lock timeout at ${lockPath}`)
|
|
191
|
+
await new Promise((r) => setTimeout(r, 20))
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
try {
|
|
195
|
+
return await fn()
|
|
196
|
+
} finally {
|
|
197
|
+
await unlink(lockPath).catch(() => {})
|
|
198
|
+
void handle // closed fd via unlink; keep handle referenced for GC clarity
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function parseDoc(raw: string): SettingsDoc {
|
|
203
|
+
const parsed = JSON.parse(raw) as Partial<SettingsDoc>
|
|
204
|
+
if (typeof parsed !== 'object' || parsed === null || typeof parsed.version !== 'number') {
|
|
205
|
+
throw new Error('config-lib: malformed settings document')
|
|
206
|
+
}
|
|
207
|
+
return { version: 1, domains: (parsed.domains as Record<string, unknown>) ?? {} }
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async function readDoc(path: string): Promise<SettingsDoc> {
|
|
211
|
+
let raw: string
|
|
212
|
+
try {
|
|
213
|
+
raw = await readFile(path, 'utf8')
|
|
214
|
+
} catch (err: any) {
|
|
215
|
+
if (err?.code === 'ENOENT') return { ...EMPTY_DOC, domains: {} }
|
|
216
|
+
throw err
|
|
217
|
+
}
|
|
218
|
+
return parseDoc(raw)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function deepMerge(base: unknown, patch: unknown): unknown {
|
|
222
|
+
if (
|
|
223
|
+
base !== null && typeof base === 'object' && !Array.isArray(base) &&
|
|
224
|
+
patch !== null && typeof patch === 'object' && !Array.isArray(patch)
|
|
225
|
+
) {
|
|
226
|
+
const out: Record<string, unknown> = { ...(base as Record<string, unknown>) }
|
|
227
|
+
for (const [k, v] of Object.entries(patch as Record<string, unknown>)) {
|
|
228
|
+
out[k] = k in out ? deepMerge(out[k], v) : v
|
|
229
|
+
}
|
|
230
|
+
return out
|
|
231
|
+
}
|
|
232
|
+
return patch
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async function writeDocLocked(path: string, doc: SettingsDoc): Promise<void> {
|
|
236
|
+
await mkdir(dirname(path), { recursive: true })
|
|
237
|
+
const tmp = `${path}.tmp-${Math.random().toString(16).slice(2, 10)}`
|
|
238
|
+
await writeFile(tmp, JSON.stringify(doc, null, 2) + '\n', { mode: 0o600 })
|
|
239
|
+
await rename(tmp, path) // atomic on the same filesystem; rename carries the 600 mode
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ---------------------------------------------------------------------------
|
|
243
|
+
// public API
|
|
244
|
+
// ---------------------------------------------------------------------------
|
|
245
|
+
|
|
246
|
+
export async function load(opts?: { dshHome?: string }): Promise<SettingsDoc> {
|
|
247
|
+
const path = storePath(opts)
|
|
248
|
+
const homeKey = resolveDshHome(opts?.dshHome)
|
|
249
|
+
if (cached && cached.key === homeKey) {
|
|
250
|
+
// One stat per load: out-of-band edits (other processes) must surface
|
|
251
|
+
// without a restart.
|
|
252
|
+
try {
|
|
253
|
+
const st = await stat(path)
|
|
254
|
+
if (st.mtimeMs === cached.mtimeMs) return cached.doc
|
|
255
|
+
} catch {
|
|
256
|
+
return cached.doc // stat failed (vanished/locked) — serve stale, never break boot
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
const doc = await readDoc(path)
|
|
260
|
+
let mtimeMs = 0
|
|
261
|
+
try { mtimeMs = (await stat(path)).mtimeMs } catch {}
|
|
262
|
+
cached = { key: homeKey, doc, mtimeMs }
|
|
263
|
+
return doc
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export async function get(domain: string, opts?: { dshHome?: string }): Promise<unknown> {
|
|
267
|
+
const doc = await load(opts)
|
|
268
|
+
return doc.domains[domain]
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export async function set(
|
|
272
|
+
domain: string,
|
|
273
|
+
patch: object,
|
|
274
|
+
opts?: { dshHome?: string },
|
|
275
|
+
): Promise<void> {
|
|
276
|
+
const path = storePath(opts)
|
|
277
|
+
const key = resolveDshHome(opts?.dshHome)
|
|
278
|
+
let written: unknown
|
|
279
|
+
await withLock(path, async () => {
|
|
280
|
+
const doc = await readDoc(path)
|
|
281
|
+
const validator = domainValidators.get(domain)
|
|
282
|
+
const merged = deepMerge(doc.domains[domain], patch)
|
|
283
|
+
if (validator) {
|
|
284
|
+
const res = validator.parse(merged)
|
|
285
|
+
if (!res.ok) throw new Error(`config-lib: validation failed for '${domain}': ${res.error}`)
|
|
286
|
+
}
|
|
287
|
+
doc.domains[domain] = merged
|
|
288
|
+
written = merged
|
|
289
|
+
await writeDocLocked(path, doc)
|
|
290
|
+
let mtimeMs = 0
|
|
291
|
+
try { mtimeMs = (await stat(path)).mtimeMs } catch {}
|
|
292
|
+
cached = { key, doc, mtimeMs }
|
|
293
|
+
})
|
|
294
|
+
// Refresh the watched copy first so the watcher sees no diff for this write.
|
|
295
|
+
if (watchedHome === key) snapshot[domain] = JSON.stringify(written) ?? 'undefined'
|
|
296
|
+
for (const cb of [...changeCbs]) cb(domain)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Delete one TOP-LEVEL key of a domain — the delete operation `set()` cannot
|
|
301
|
+
* express (a merge patch has no delete signal: `null` persists as null).
|
|
302
|
+
* Dotted paths are rejected to keep the semantics exactly one key. No-op
|
|
303
|
+
* (`false`, no write, no callbacks) when the domain is absent/not an object
|
|
304
|
+
* or the key is absent. Otherwise the resulting domain is validated like a
|
|
305
|
+
* `set()` before the atomic write; `true` means the key is gone.
|
|
306
|
+
*/
|
|
307
|
+
export async function unset(
|
|
308
|
+
domain: string,
|
|
309
|
+
key: string,
|
|
310
|
+
opts?: { dshHome?: string },
|
|
311
|
+
): Promise<boolean> {
|
|
312
|
+
if (typeof key !== 'string' || key === '' || key.includes('.')) {
|
|
313
|
+
throw new Error(`config-lib: unset key must be a top-level name, got ${JSON.stringify(key)}`)
|
|
314
|
+
}
|
|
315
|
+
const path = storePath(opts)
|
|
316
|
+
const homeKey = resolveDshHome(opts?.dshHome)
|
|
317
|
+
let written: Record<string, unknown> | undefined
|
|
318
|
+
const deleted = await withLock(path, async () => {
|
|
319
|
+
const doc = await readDoc(path)
|
|
320
|
+
const bucket = doc.domains[domain]
|
|
321
|
+
if (typeof bucket !== 'object' || bucket === null || Array.isArray(bucket)) return false
|
|
322
|
+
if (!(key in bucket)) return false
|
|
323
|
+
const next = { ...(bucket as Record<string, unknown>) }
|
|
324
|
+
delete next[key]
|
|
325
|
+
const validator = domainValidators.get(domain)
|
|
326
|
+
if (validator) {
|
|
327
|
+
const res = validator.parse(next)
|
|
328
|
+
if (!res.ok) throw new Error(`config-lib: validation failed for '${domain}': ${res.error}`)
|
|
329
|
+
}
|
|
330
|
+
doc.domains[domain] = next
|
|
331
|
+
written = next
|
|
332
|
+
await writeDocLocked(path, doc)
|
|
333
|
+
let mtimeMs = 0
|
|
334
|
+
try { mtimeMs = (await stat(path)).mtimeMs } catch {}
|
|
335
|
+
cached = { key: homeKey, doc, mtimeMs }
|
|
336
|
+
return true
|
|
337
|
+
})
|
|
338
|
+
if (deleted) {
|
|
339
|
+
if (watchedHome === homeKey) snapshot[domain] = JSON.stringify(written) ?? 'undefined'
|
|
340
|
+
for (const cb of [...changeCbs]) cb(domain)
|
|
341
|
+
}
|
|
342
|
+
return deleted
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Names of domains registered via defineDomain (schema owners). */
|
|
346
|
+
export function definedDomains(): string[] {
|
|
347
|
+
return [...domainValidators.keys()]
|
|
348
|
+
}
|