@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,340 @@
|
|
|
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 } from 'node:fs';
|
|
6
|
+
const EMPTY_DOC = { version: 1, domains: {} };
|
|
7
|
+
const domainValidators = new Map();
|
|
8
|
+
const changeCbs = new Set();
|
|
9
|
+
let cached = null;
|
|
10
|
+
function resolveDshHome(explicit) {
|
|
11
|
+
return explicit ?? process.env.DSH_HOME ?? join(homedir(), '.dsh');
|
|
12
|
+
}
|
|
13
|
+
function storePath(opts) {
|
|
14
|
+
return join(resolveDshHome(opts?.dshHome), 'dsh-maestro-config', 'settings.json');
|
|
15
|
+
}
|
|
16
|
+
/** Register a validator for a domain you own. Writes to it are validated on every set(). */
|
|
17
|
+
export function defineDomain(name, validator) {
|
|
18
|
+
domainValidators.set(name, validator);
|
|
19
|
+
}
|
|
20
|
+
// ---------------------------------------------------------------------------
|
|
21
|
+
// change notification
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
/**
|
|
24
|
+
* Every plugin embeds its own copy of this module, so a listener has to hear
|
|
25
|
+
* writes made by another copy (or by another process), not only writes made
|
|
26
|
+
* through the copy that owns it. While at least one listener exists we watch
|
|
27
|
+
* the settings file and compare every domain against `snapshot`; a local write
|
|
28
|
+
* refreshes `snapshot` before it fires the callbacks, so it never fires twice.
|
|
29
|
+
*
|
|
30
|
+
* The watcher resolves DSH_HOME once, when it starts. A store pinned to an
|
|
31
|
+
* explicit `dshHome` therefore stays out of the watched home and neither fires
|
|
32
|
+
* nor receives notifications for writes that go somewhere else.
|
|
33
|
+
*/
|
|
34
|
+
const WATCH_DEBOUNCE_MS = 50;
|
|
35
|
+
const POLL_MS = 2_000;
|
|
36
|
+
const FILE_BASENAME = 'settings.json';
|
|
37
|
+
let watcher = null;
|
|
38
|
+
let pollTimer = null;
|
|
39
|
+
let debounceTimer = null;
|
|
40
|
+
let snapshot = {};
|
|
41
|
+
let watchedHome = null;
|
|
42
|
+
let checking = false;
|
|
43
|
+
/** JSON text per domain, so a value change is a cheap string comparison. */
|
|
44
|
+
function fingerprint(doc) {
|
|
45
|
+
const out = {};
|
|
46
|
+
for (const [domain, value] of Object.entries(doc.domains)) {
|
|
47
|
+
out[domain] = JSON.stringify(value) ?? 'undefined';
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Seed the snapshot synchronously so a write racing `onChange` cannot slip
|
|
53
|
+
* between "listener registered" and "snapshot taken" and go unnoticed.
|
|
54
|
+
*/
|
|
55
|
+
function readSnapshotSync(home) {
|
|
56
|
+
try {
|
|
57
|
+
return fingerprint(parseDoc(readFileSync(storePath({ dshHome: home }), 'utf8')));
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return {}; // no store on disk yet: every domain is new
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
async function checkExternal() {
|
|
64
|
+
if (changeCbs.size === 0 || watchedHome === null || checking)
|
|
65
|
+
return;
|
|
66
|
+
checking = true;
|
|
67
|
+
try {
|
|
68
|
+
// load() invalidates its own cache on an mtime change, so this sees other
|
|
69
|
+
// writers' values without an extra stat.
|
|
70
|
+
const next = fingerprint(await load({ dshHome: watchedHome }));
|
|
71
|
+
const changed = [];
|
|
72
|
+
for (const domain of new Set([...Object.keys(snapshot), ...Object.keys(next)])) {
|
|
73
|
+
// A domain that disappeared compares against undefined and counts as changed.
|
|
74
|
+
if (snapshot[domain] !== next[domain])
|
|
75
|
+
changed.push(domain);
|
|
76
|
+
}
|
|
77
|
+
snapshot = next;
|
|
78
|
+
for (const domain of changed)
|
|
79
|
+
for (const cb of [...changeCbs])
|
|
80
|
+
cb(domain);
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
// A transient read failure must never break boot; the next tick retries.
|
|
84
|
+
}
|
|
85
|
+
finally {
|
|
86
|
+
checking = false;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function scheduleCheck() {
|
|
90
|
+
if (debounceTimer)
|
|
91
|
+
clearTimeout(debounceTimer);
|
|
92
|
+
debounceTimer = setTimeout(() => {
|
|
93
|
+
debounceTimer = null;
|
|
94
|
+
void checkExternal();
|
|
95
|
+
}, WATCH_DEBOUNCE_MS);
|
|
96
|
+
debounceTimer.unref();
|
|
97
|
+
}
|
|
98
|
+
function stopWatching() {
|
|
99
|
+
watcher?.close();
|
|
100
|
+
watcher = null;
|
|
101
|
+
if (pollTimer)
|
|
102
|
+
clearInterval(pollTimer);
|
|
103
|
+
pollTimer = null;
|
|
104
|
+
if (debounceTimer)
|
|
105
|
+
clearTimeout(debounceTimer);
|
|
106
|
+
debounceTimer = null;
|
|
107
|
+
snapshot = {};
|
|
108
|
+
watchedHome = null;
|
|
109
|
+
}
|
|
110
|
+
function startWatching() {
|
|
111
|
+
if (watcher || pollTimer)
|
|
112
|
+
return;
|
|
113
|
+
const home = resolveDshHome();
|
|
114
|
+
const path = storePath({ dshHome: home });
|
|
115
|
+
watchedHome = home;
|
|
116
|
+
snapshot = readSnapshotSync(home);
|
|
117
|
+
try {
|
|
118
|
+
// fs.watch is not recursive, so it only sees the file when its own
|
|
119
|
+
// directory exists; the store is the only writer of that path either way.
|
|
120
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
121
|
+
watcher = watch(dirname(path), { persistent: false }, (_event, filename) => {
|
|
122
|
+
if (filename === null || filename === FILE_BASENAME)
|
|
123
|
+
scheduleCheck();
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
watcher = null; // polling below still covers the change
|
|
128
|
+
}
|
|
129
|
+
pollTimer = setInterval(() => void checkExternal(), POLL_MS);
|
|
130
|
+
pollTimer.unref();
|
|
131
|
+
}
|
|
132
|
+
/** Fire callbacks registered through this instance after a successful set(). */
|
|
133
|
+
export function onChange(cb) {
|
|
134
|
+
changeCbs.add(cb);
|
|
135
|
+
startWatching();
|
|
136
|
+
let disposed = false;
|
|
137
|
+
return () => {
|
|
138
|
+
if (disposed)
|
|
139
|
+
return;
|
|
140
|
+
disposed = true;
|
|
141
|
+
changeCbs.delete(cb);
|
|
142
|
+
if (changeCbs.size === 0)
|
|
143
|
+
stopWatching();
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/** Test seam: drop the memoized document and listeners (schemas are kept). */
|
|
147
|
+
export function resetForTests() {
|
|
148
|
+
cached = null;
|
|
149
|
+
changeCbs.clear();
|
|
150
|
+
stopWatching();
|
|
151
|
+
}
|
|
152
|
+
// ---------------------------------------------------------------------------
|
|
153
|
+
// locking + io
|
|
154
|
+
// ---------------------------------------------------------------------------
|
|
155
|
+
async function withLock(path, fn) {
|
|
156
|
+
await mkdir(dirname(path), { recursive: true }); // the store dir may not exist on first write
|
|
157
|
+
const lockPath = `${path}.lock`;
|
|
158
|
+
const deadline = Date.now() + 5_000;
|
|
159
|
+
let handle = null;
|
|
160
|
+
for (;;) {
|
|
161
|
+
try {
|
|
162
|
+
handle = await open(lockPath, 'wx');
|
|
163
|
+
break;
|
|
164
|
+
}
|
|
165
|
+
catch (err) {
|
|
166
|
+
if (err?.code !== 'EEXIST')
|
|
167
|
+
throw err;
|
|
168
|
+
// Break stale locks left behind by a crashed writer.
|
|
169
|
+
try {
|
|
170
|
+
const st = await stat(lockPath);
|
|
171
|
+
if (Date.now() - st.mtimeMs > 5_000) {
|
|
172
|
+
await rm(lockPath, { force: true });
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
/* lock vanished between stat and now — just retry */
|
|
178
|
+
}
|
|
179
|
+
if (Date.now() > deadline)
|
|
180
|
+
throw new Error(`config-lib: lock timeout at ${lockPath}`);
|
|
181
|
+
await new Promise((r) => setTimeout(r, 20));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
return await fn();
|
|
186
|
+
}
|
|
187
|
+
finally {
|
|
188
|
+
await unlink(lockPath).catch(() => { });
|
|
189
|
+
void handle; // closed fd via unlink; keep handle referenced for GC clarity
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
function parseDoc(raw) {
|
|
193
|
+
const parsed = JSON.parse(raw);
|
|
194
|
+
if (typeof parsed !== 'object' || parsed === null || typeof parsed.version !== 'number') {
|
|
195
|
+
throw new Error('config-lib: malformed settings document');
|
|
196
|
+
}
|
|
197
|
+
return { version: 1, domains: parsed.domains ?? {} };
|
|
198
|
+
}
|
|
199
|
+
async function readDoc(path) {
|
|
200
|
+
let raw;
|
|
201
|
+
try {
|
|
202
|
+
raw = await readFile(path, 'utf8');
|
|
203
|
+
}
|
|
204
|
+
catch (err) {
|
|
205
|
+
if (err?.code === 'ENOENT')
|
|
206
|
+
return { ...EMPTY_DOC, domains: {} };
|
|
207
|
+
throw err;
|
|
208
|
+
}
|
|
209
|
+
return parseDoc(raw);
|
|
210
|
+
}
|
|
211
|
+
function deepMerge(base, patch) {
|
|
212
|
+
if (base !== null && typeof base === 'object' && !Array.isArray(base) &&
|
|
213
|
+
patch !== null && typeof patch === 'object' && !Array.isArray(patch)) {
|
|
214
|
+
const out = { ...base };
|
|
215
|
+
for (const [k, v] of Object.entries(patch)) {
|
|
216
|
+
out[k] = k in out ? deepMerge(out[k], v) : v;
|
|
217
|
+
}
|
|
218
|
+
return out;
|
|
219
|
+
}
|
|
220
|
+
return patch;
|
|
221
|
+
}
|
|
222
|
+
async function writeDocLocked(path, doc) {
|
|
223
|
+
await mkdir(dirname(path), { recursive: true });
|
|
224
|
+
const tmp = `${path}.tmp-${Math.random().toString(16).slice(2, 10)}`;
|
|
225
|
+
await writeFile(tmp, JSON.stringify(doc, null, 2) + '\n', { mode: 0o600 });
|
|
226
|
+
await rename(tmp, path); // atomic on the same filesystem; rename carries the 600 mode
|
|
227
|
+
}
|
|
228
|
+
// ---------------------------------------------------------------------------
|
|
229
|
+
// public API
|
|
230
|
+
// ---------------------------------------------------------------------------
|
|
231
|
+
export async function load(opts) {
|
|
232
|
+
const path = storePath(opts);
|
|
233
|
+
const homeKey = resolveDshHome(opts?.dshHome);
|
|
234
|
+
if (cached && cached.key === homeKey) {
|
|
235
|
+
// One stat per load: out-of-band edits (other processes) must surface
|
|
236
|
+
// without a restart.
|
|
237
|
+
try {
|
|
238
|
+
const st = await stat(path);
|
|
239
|
+
if (st.mtimeMs === cached.mtimeMs)
|
|
240
|
+
return cached.doc;
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
return cached.doc; // stat failed (vanished/locked) — serve stale, never break boot
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
const doc = await readDoc(path);
|
|
247
|
+
let mtimeMs = 0;
|
|
248
|
+
try {
|
|
249
|
+
mtimeMs = (await stat(path)).mtimeMs;
|
|
250
|
+
}
|
|
251
|
+
catch { }
|
|
252
|
+
cached = { key: homeKey, doc, mtimeMs };
|
|
253
|
+
return doc;
|
|
254
|
+
}
|
|
255
|
+
export async function get(domain, opts) {
|
|
256
|
+
const doc = await load(opts);
|
|
257
|
+
return doc.domains[domain];
|
|
258
|
+
}
|
|
259
|
+
export async function set(domain, patch, opts) {
|
|
260
|
+
const path = storePath(opts);
|
|
261
|
+
const key = resolveDshHome(opts?.dshHome);
|
|
262
|
+
let written;
|
|
263
|
+
await withLock(path, async () => {
|
|
264
|
+
const doc = await readDoc(path);
|
|
265
|
+
const validator = domainValidators.get(domain);
|
|
266
|
+
const merged = deepMerge(doc.domains[domain], patch);
|
|
267
|
+
if (validator) {
|
|
268
|
+
const res = validator.parse(merged);
|
|
269
|
+
if (!res.ok)
|
|
270
|
+
throw new Error(`config-lib: validation failed for '${domain}': ${res.error}`);
|
|
271
|
+
}
|
|
272
|
+
doc.domains[domain] = merged;
|
|
273
|
+
written = merged;
|
|
274
|
+
await writeDocLocked(path, doc);
|
|
275
|
+
let mtimeMs = 0;
|
|
276
|
+
try {
|
|
277
|
+
mtimeMs = (await stat(path)).mtimeMs;
|
|
278
|
+
}
|
|
279
|
+
catch { }
|
|
280
|
+
cached = { key, doc, mtimeMs };
|
|
281
|
+
});
|
|
282
|
+
// Refresh the watched copy first so the watcher sees no diff for this write.
|
|
283
|
+
if (watchedHome === key)
|
|
284
|
+
snapshot[domain] = JSON.stringify(written) ?? 'undefined';
|
|
285
|
+
for (const cb of [...changeCbs])
|
|
286
|
+
cb(domain);
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Delete one TOP-LEVEL key of a domain — the delete operation `set()` cannot
|
|
290
|
+
* express (a merge patch has no delete signal: `null` persists as null).
|
|
291
|
+
* Dotted paths are rejected to keep the semantics exactly one key. No-op
|
|
292
|
+
* (`false`, no write, no callbacks) when the domain is absent/not an object
|
|
293
|
+
* or the key is absent. Otherwise the resulting domain is validated like a
|
|
294
|
+
* `set()` before the atomic write; `true` means the key is gone.
|
|
295
|
+
*/
|
|
296
|
+
export async function unset(domain, key, opts) {
|
|
297
|
+
if (typeof key !== 'string' || key === '' || key.includes('.')) {
|
|
298
|
+
throw new Error(`config-lib: unset key must be a top-level name, got ${JSON.stringify(key)}`);
|
|
299
|
+
}
|
|
300
|
+
const path = storePath(opts);
|
|
301
|
+
const homeKey = resolveDshHome(opts?.dshHome);
|
|
302
|
+
let written;
|
|
303
|
+
const deleted = await withLock(path, async () => {
|
|
304
|
+
const doc = await readDoc(path);
|
|
305
|
+
const bucket = doc.domains[domain];
|
|
306
|
+
if (typeof bucket !== 'object' || bucket === null || Array.isArray(bucket))
|
|
307
|
+
return false;
|
|
308
|
+
if (!(key in bucket))
|
|
309
|
+
return false;
|
|
310
|
+
const next = { ...bucket };
|
|
311
|
+
delete next[key];
|
|
312
|
+
const validator = domainValidators.get(domain);
|
|
313
|
+
if (validator) {
|
|
314
|
+
const res = validator.parse(next);
|
|
315
|
+
if (!res.ok)
|
|
316
|
+
throw new Error(`config-lib: validation failed for '${domain}': ${res.error}`);
|
|
317
|
+
}
|
|
318
|
+
doc.domains[domain] = next;
|
|
319
|
+
written = next;
|
|
320
|
+
await writeDocLocked(path, doc);
|
|
321
|
+
let mtimeMs = 0;
|
|
322
|
+
try {
|
|
323
|
+
mtimeMs = (await stat(path)).mtimeMs;
|
|
324
|
+
}
|
|
325
|
+
catch { }
|
|
326
|
+
cached = { key: homeKey, doc, mtimeMs };
|
|
327
|
+
return true;
|
|
328
|
+
});
|
|
329
|
+
if (deleted) {
|
|
330
|
+
if (watchedHome === homeKey)
|
|
331
|
+
snapshot[domain] = JSON.stringify(written) ?? 'undefined';
|
|
332
|
+
for (const cb of [...changeCbs])
|
|
333
|
+
cb(domain);
|
|
334
|
+
}
|
|
335
|
+
return deleted;
|
|
336
|
+
}
|
|
337
|
+
/** Names of domains registered via defineDomain (schema owners). */
|
|
338
|
+
export function definedDomains() {
|
|
339
|
+
return [...domainValidators.keys()];
|
|
340
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare const DOMAIN_KEY_MAP: Record<string, string>;
|
|
2
|
+
/** Machine runtime state — never settings; owning adapters persist these in their own sidecar. */
|
|
3
|
+
export declare const RUNTIME_KEYS: readonly string[];
|
|
4
|
+
export interface DomainWrite {
|
|
5
|
+
domain: string;
|
|
6
|
+
patch: Record<string, unknown>;
|
|
7
|
+
}
|
|
8
|
+
/** Route a flat legacy-keyed patch into per-domain writes; runtime keys are skipped. */
|
|
9
|
+
export declare function splitLegacyPatch(patch: Record<string, unknown>): DomainWrite[];
|
|
10
|
+
/** Write a flat legacy-keyed patch through the domain store (multiple atomic set()s). */
|
|
11
|
+
export declare function writeLegacyPatch(patch: Record<string, unknown>, opts?: {
|
|
12
|
+
dshHome?: string;
|
|
13
|
+
}): Promise<void>;
|
|
14
|
+
/** Inverse view: domains flattened back into legacy key names (undefined keys omitted). */
|
|
15
|
+
export declare function readFlat(opts?: {
|
|
16
|
+
dshHome?: string;
|
|
17
|
+
}): Promise<Record<string, unknown>>;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { load, set } from './index.js';
|
|
2
|
+
// ---------------------------------------------------------------------------
|
|
3
|
+
// flat-key adapter map (live: remote/review/supervisor read through readFlat)
|
|
4
|
+
// ---------------------------------------------------------------------------
|
|
5
|
+
export const DOMAIN_KEY_MAP = {
|
|
6
|
+
gitlabBaseUrl: 'gitlab.baseUrl',
|
|
7
|
+
gitlabToken: 'gitlab.token',
|
|
8
|
+
botUsername: 'gitlab.botUsername',
|
|
9
|
+
webhookSecret: 'gitlab.webhookSecret',
|
|
10
|
+
webhookPort: 'gitlab.webhookPort',
|
|
11
|
+
projectMappings: 'gitlab.projectMappings',
|
|
12
|
+
autoRereviewOnPush: 'gitlab.autoRereviewOnPush',
|
|
13
|
+
autoReviewOnAssign: 'gitlab.autoReviewOnAssign',
|
|
14
|
+
reviewModel: 'review.model',
|
|
15
|
+
agentTimeoutMs: 'review.agentTimeoutMs',
|
|
16
|
+
reviewSessionRetentionDays: 'review.sessionRetentionDays',
|
|
17
|
+
tunnelHostname: 'tunnel.hostname',
|
|
18
|
+
tunnelCredentialsFile: 'tunnel.credentialsFile',
|
|
19
|
+
tunnelId: 'tunnel.id',
|
|
20
|
+
tunnelMode: 'tunnel.mode',
|
|
21
|
+
quickTarget: 'tunnel.quickTarget',
|
|
22
|
+
proxyPort: 'tunnel.proxyPort',
|
|
23
|
+
proxyHost: 'tunnel.proxyHost',
|
|
24
|
+
lanPinEnabled: 'tunnel.lanPinEnabled',
|
|
25
|
+
lanPort: 'tunnel.lanPort',
|
|
26
|
+
lanHost: 'tunnel.lanHost',
|
|
27
|
+
/** Login-cookie lifetime in hours for the remote PIN gate (0 = session cookie). */
|
|
28
|
+
pinSessionTtlHours: 'tunnel.pinSessionTtlHours',
|
|
29
|
+
telegramBotToken: 'notifier.telegram.botToken',
|
|
30
|
+
telegramChatId: 'notifier.telegram.chatId',
|
|
31
|
+
telegramReviewNotifications: 'notifier.policy.reviewNotifications',
|
|
32
|
+
};
|
|
33
|
+
/** Machine runtime state — never settings; owning adapters persist these in their own sidecar. */
|
|
34
|
+
export const RUNTIME_KEYS = ['lastTunnelRunning'];
|
|
35
|
+
function setIn(obj, dotted, value) {
|
|
36
|
+
const parts = dotted.split('.');
|
|
37
|
+
let cur = obj;
|
|
38
|
+
for (const part of parts.slice(0, -1)) {
|
|
39
|
+
if (typeof cur[part] !== 'object' || cur[part] === null)
|
|
40
|
+
cur[part] = {};
|
|
41
|
+
cur = cur[part];
|
|
42
|
+
}
|
|
43
|
+
cur[parts[parts.length - 1]] = value;
|
|
44
|
+
}
|
|
45
|
+
/** Route a flat legacy-keyed patch into per-domain writes; runtime keys are skipped. */
|
|
46
|
+
export function splitLegacyPatch(patch) {
|
|
47
|
+
const byDomain = new Map();
|
|
48
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
49
|
+
if (RUNTIME_KEYS.includes(key))
|
|
50
|
+
continue;
|
|
51
|
+
const dotted = DOMAIN_KEY_MAP[key];
|
|
52
|
+
if (!dotted)
|
|
53
|
+
continue;
|
|
54
|
+
const domain = dotted.split('.')[0];
|
|
55
|
+
const group = byDomain.get(domain) ?? {};
|
|
56
|
+
setIn(group, dotted.slice(domain.length + 1), value);
|
|
57
|
+
byDomain.set(domain, group);
|
|
58
|
+
}
|
|
59
|
+
return [...byDomain].map(([domain, patch]) => ({ domain, patch }));
|
|
60
|
+
}
|
|
61
|
+
/** Write a flat legacy-keyed patch through the domain store (multiple atomic set()s). */
|
|
62
|
+
export async function writeLegacyPatch(patch, opts) {
|
|
63
|
+
for (const { domain, patch: group } of splitLegacyPatch(patch)) {
|
|
64
|
+
await set(domain, group, opts);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** Inverse view: domains flattened back into legacy key names (undefined keys omitted). */
|
|
68
|
+
export async function readFlat(opts) {
|
|
69
|
+
const doc = await load(opts);
|
|
70
|
+
const flat = {};
|
|
71
|
+
for (const [key, dotted] of Object.entries(DOMAIN_KEY_MAP)) {
|
|
72
|
+
let cur = doc.domains;
|
|
73
|
+
for (const part of dotted.split('.')) {
|
|
74
|
+
if (cur !== null && typeof cur === 'object')
|
|
75
|
+
cur = cur[part];
|
|
76
|
+
else {
|
|
77
|
+
cur = undefined;
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (cur !== undefined)
|
|
82
|
+
flat[key] = cur;
|
|
83
|
+
}
|
|
84
|
+
return flat;
|
|
85
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { type HealthState } from './health-poller.js';
|
|
2
|
+
import type { RestartRequest } from './restart-guards.js';
|
|
3
|
+
import { type RestartOutcome } from './intents.js';
|
|
4
|
+
import { type MintCookieOpts } from './dsh-session.js';
|
|
5
|
+
/** Partial-restore report a rollback may hand back (cli.ts wires RestoreResult). */
|
|
6
|
+
export interface RollbackSummary {
|
|
7
|
+
target?: string;
|
|
8
|
+
restored?: number;
|
|
9
|
+
skipped?: Array<{
|
|
10
|
+
path: string;
|
|
11
|
+
reason: string;
|
|
12
|
+
}>;
|
|
13
|
+
}
|
|
14
|
+
export interface SupervisorDeps {
|
|
15
|
+
pollHealth: () => Promise<HealthState>;
|
|
16
|
+
writeLKG: () => Promise<{
|
|
17
|
+
ts: string;
|
|
18
|
+
manifest?: any;
|
|
19
|
+
}>;
|
|
20
|
+
writeFailed: () => Promise<{
|
|
21
|
+
ts: string;
|
|
22
|
+
manifest?: any;
|
|
23
|
+
}>;
|
|
24
|
+
writeReport: (opts: {
|
|
25
|
+
ts: string;
|
|
26
|
+
health: HealthState;
|
|
27
|
+
action: string;
|
|
28
|
+
logTail?: string;
|
|
29
|
+
gitDiff?: string;
|
|
30
|
+
}) => Promise<string>;
|
|
31
|
+
rollback: (ts?: string) => Promise<RollbackSummary | void>;
|
|
32
|
+
restartWeb?: () => Promise<void>;
|
|
33
|
+
notify: (msg: string) => Promise<void>;
|
|
34
|
+
intervalMs?: number;
|
|
35
|
+
debounceMs?: number;
|
|
36
|
+
downThreshold?: number;
|
|
37
|
+
bootGraceMs?: number;
|
|
38
|
+
getTime?: () => number;
|
|
39
|
+
isPlannedRestartActive?: () => boolean | Promise<boolean>;
|
|
40
|
+
writePlannedRestart?: (ttlMs?: number) => void;
|
|
41
|
+
checkPlannedRestart?: () => boolean;
|
|
42
|
+
clearPlannedRestart?: () => void;
|
|
43
|
+
runDebugAgent?: (opts: {
|
|
44
|
+
reportPath: string;
|
|
45
|
+
health: HealthState;
|
|
46
|
+
}) => Promise<{
|
|
47
|
+
fixed: boolean;
|
|
48
|
+
reason: string;
|
|
49
|
+
}>;
|
|
50
|
+
findInterrupted?: () => Promise<{
|
|
51
|
+
scanned: number;
|
|
52
|
+
interrupted: string[];
|
|
53
|
+
}>;
|
|
54
|
+
resumeSessions?: (ids: string[]) => Promise<{
|
|
55
|
+
resumed: string[];
|
|
56
|
+
}>;
|
|
57
|
+
readRestartRequest?: () => RestartRequest | undefined;
|
|
58
|
+
onRestartRequestHandled?: (req: RestartRequest) => void;
|
|
59
|
+
writeOutcome?: (sessionId: string, outcome: RestartOutcome) => void;
|
|
60
|
+
listenerPid?: (port: number) => number | undefined;
|
|
61
|
+
}
|
|
62
|
+
/** PID holding a 127.0.0.1 listener on the port, or undefined. Never throws. */
|
|
63
|
+
export declare function defaultListenerPid(port: number): number | undefined;
|
|
64
|
+
export declare function resumeViaRpc(ids: string[], fetchFn?: (url: string, init: RequestInit) => Promise<Response>, extraHeaders?: Record<string, string>): Promise<{
|
|
65
|
+
resumed: string[];
|
|
66
|
+
}>;
|
|
67
|
+
/**
|
|
68
|
+
* Daemon default resume path: mint the `dsh-auth-*` session cookie first (the
|
|
69
|
+
* `/resume` RPC sits behind the raw webserver's browser-trust fence, which 401s
|
|
70
|
+
* cookie-less loopback calls since the local-pin-gate topology moved the
|
|
71
|
+
* webserver behind the PIN proxies) and attach it to the POST. Falls back to an
|
|
72
|
+
* unauthenticated POST when no boot token is readable — old behavior preserved.
|
|
73
|
+
*/
|
|
74
|
+
export declare function resumeViaRpcWithSession(ids: string[], fetchFn?: (url: string, init: RequestInit) => Promise<Response>, opts?: MintCookieOpts): Promise<{
|
|
75
|
+
resumed: string[];
|
|
76
|
+
}>;
|
|
77
|
+
export declare class Supervisor {
|
|
78
|
+
private deps;
|
|
79
|
+
private lastRollback;
|
|
80
|
+
private rollingBack;
|
|
81
|
+
private lastLKGWrite;
|
|
82
|
+
private lastDegradedNotify;
|
|
83
|
+
private consecutiveDown;
|
|
84
|
+
private consecutiveDegraded;
|
|
85
|
+
private timer;
|
|
86
|
+
private restartRequestHandled;
|
|
87
|
+
private restartRequestTimer;
|
|
88
|
+
private awaitingHealthyBoot;
|
|
89
|
+
private pendingRestartRequest;
|
|
90
|
+
constructor(deps: SupervisorDeps);
|
|
91
|
+
private getWritePlannedRestart;
|
|
92
|
+
private getCheckPlannedRestart;
|
|
93
|
+
private getClearPlannedRestart;
|
|
94
|
+
restartWeb(): Promise<void>;
|
|
95
|
+
private getRunDebugAgent;
|
|
96
|
+
private getFindInterrupted;
|
|
97
|
+
private getResumeSessions;
|
|
98
|
+
private getAutoResumeEnabled;
|
|
99
|
+
private getResumeWithinMs;
|
|
100
|
+
private getEffectiveIntervalMs;
|
|
101
|
+
private getEffectiveDownThreshold;
|
|
102
|
+
private getEffectiveDegradedThreshold;
|
|
103
|
+
private getEffectivePollTimeoutMs;
|
|
104
|
+
private getEffectiveBootGraceMs;
|
|
105
|
+
private findInterruptedRecent;
|
|
106
|
+
private collectGitDiff;
|
|
107
|
+
private attemptAutoResume;
|
|
108
|
+
/**
|
|
109
|
+
* D4: a restore that could not put every entry back must be surfaced loudly.
|
|
110
|
+
* Without this, a half-restored tree reads exactly like a clean recovery in
|
|
111
|
+
* the log and in the operator's Telegram feed.
|
|
112
|
+
*/
|
|
113
|
+
private reportRollbackResult;
|
|
114
|
+
private handleDebugResult;
|
|
115
|
+
tick(): Promise<void>;
|
|
116
|
+
start(): Promise<void>;
|
|
117
|
+
startSync(): void;
|
|
118
|
+
stop(): void;
|
|
119
|
+
}
|