@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,741 @@
|
|
|
1
|
+
import { classifyFetchFailure } from './health-poller.js';
|
|
2
|
+
import { runDebugAgent } from './debug-agent.js';
|
|
3
|
+
import { findInterrupted as defaultFindInterrupted, parseDuration } from './resume.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 { readSupervisorConfig } from './config.js';
|
|
9
|
+
import { writePlannedRestart as defaultWritePlannedRestart, checkPlannedRestart as defaultCheckPlannedRestart, clearPlannedRestart } from './restart-guards.js';
|
|
10
|
+
import { writeRestartOutcome as defaultWriteOutcome } from './intents.js';
|
|
11
|
+
import { execFileSync } from 'node:child_process';
|
|
12
|
+
import { mintDshSessionCookie } from './dsh-session.js';
|
|
13
|
+
/** PID holding a 127.0.0.1 listener on the port, or undefined. Never throws. */
|
|
14
|
+
export function defaultListenerPid(port) {
|
|
15
|
+
try {
|
|
16
|
+
const out = execFileSync('ss', ['-tlnp'], { encoding: 'utf8' });
|
|
17
|
+
for (const line of out.split('\n')) {
|
|
18
|
+
const m = new RegExp(`127\\.0\\.0\\.1:${port}\\s[^]*?pid=(\\d+)`).exec(line);
|
|
19
|
+
if (m)
|
|
20
|
+
return Number(m[1]);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
catch { }
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
export async function resumeViaRpc(ids, fetchFn = globalThis.fetch, extraHeaders = {}) {
|
|
27
|
+
const rpcId = crypto.randomUUID();
|
|
28
|
+
const response = await fetchFn('http://127.0.0.1:3080/dsh-maestro-supervisor-resume/resume', {
|
|
29
|
+
method: 'POST',
|
|
30
|
+
headers: { 'content-type': 'application/json', ...extraHeaders },
|
|
31
|
+
body: JSON.stringify({ type: 'client-request', rpcId, method: 'resume', payload: { ids } }),
|
|
32
|
+
});
|
|
33
|
+
if (!response.ok)
|
|
34
|
+
throw new Error(`resume RPC returned HTTP ${response.status}`);
|
|
35
|
+
const envelope = await response.json();
|
|
36
|
+
const resumed = envelope?.type === 'server-response'
|
|
37
|
+
&& envelope?.rpcId === rpcId
|
|
38
|
+
&& envelope?.result?.ok === true
|
|
39
|
+
&& Array.isArray(envelope?.result?.value?.resumed)
|
|
40
|
+
? envelope.result.value.resumed.filter((id) => typeof id === 'string')
|
|
41
|
+
: undefined;
|
|
42
|
+
if (resumed === undefined)
|
|
43
|
+
throw new Error('resume RPC returned an invalid result');
|
|
44
|
+
return { resumed };
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Daemon default resume path: mint the `dsh-auth-*` session cookie first (the
|
|
48
|
+
* `/resume` RPC sits behind the raw webserver's browser-trust fence, which 401s
|
|
49
|
+
* cookie-less loopback calls since the local-pin-gate topology moved the
|
|
50
|
+
* webserver behind the PIN proxies) and attach it to the POST. Falls back to an
|
|
51
|
+
* unauthenticated POST when no boot token is readable — old behavior preserved.
|
|
52
|
+
*/
|
|
53
|
+
export async function resumeViaRpcWithSession(ids, fetchFn = globalThis.fetch, opts = {}) {
|
|
54
|
+
let cookie;
|
|
55
|
+
try {
|
|
56
|
+
cookie = await mintDshSessionCookie(fetchFn, opts);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
cookie = undefined;
|
|
60
|
+
}
|
|
61
|
+
return resumeViaRpc(ids, fetchFn, cookie === undefined ? {} : { cookie });
|
|
62
|
+
}
|
|
63
|
+
export class Supervisor {
|
|
64
|
+
deps;
|
|
65
|
+
lastRollback = 0;
|
|
66
|
+
rollingBack = false;
|
|
67
|
+
lastLKGWrite = 0;
|
|
68
|
+
lastDegradedNotify = 0;
|
|
69
|
+
consecutiveDown = 0;
|
|
70
|
+
consecutiveDegraded = 0;
|
|
71
|
+
timer = null;
|
|
72
|
+
restartRequestHandled = false;
|
|
73
|
+
restartRequestTimer = null;
|
|
74
|
+
awaitingHealthyBoot = false;
|
|
75
|
+
pendingRestartRequest;
|
|
76
|
+
constructor(deps) {
|
|
77
|
+
this.deps = deps;
|
|
78
|
+
}
|
|
79
|
+
getWritePlannedRestart() {
|
|
80
|
+
return this.deps.writePlannedRestart ?? defaultWritePlannedRestart;
|
|
81
|
+
}
|
|
82
|
+
getCheckPlannedRestart() {
|
|
83
|
+
return this.deps.checkPlannedRestart ?? defaultCheckPlannedRestart;
|
|
84
|
+
}
|
|
85
|
+
getClearPlannedRestart() {
|
|
86
|
+
return this.deps.clearPlannedRestart ?? clearPlannedRestart;
|
|
87
|
+
}
|
|
88
|
+
async restartWeb() {
|
|
89
|
+
const grace = await this.getEffectiveBootGraceMs();
|
|
90
|
+
// Marker first, and its TTL is the boot budget — not 30 s. The observed
|
|
91
|
+
// boot took 1m52s: after +30 s every poll was judged as a crash, which is
|
|
92
|
+
// exactly how the 2026-09-13 rollback report was produced (D5).
|
|
93
|
+
this.getWritePlannedRestart()(grace);
|
|
94
|
+
if (this.deps.restartWeb) {
|
|
95
|
+
// Injected implementation (cli.ts daemon wiring, tests): it owns the
|
|
96
|
+
// boot lock, so the single-flight guarantee stays in one place.
|
|
97
|
+
await this.deps.restartWeb();
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const { performSingleBootRestart } = await import('./restart-web.js');
|
|
101
|
+
const res = await performSingleBootRestart({ bootGraceMs: grace });
|
|
102
|
+
if (!res.restarted) {
|
|
103
|
+
await this.deps.notify(`restart skipped: ${res.reason ?? 'boot lock held'}`).catch(() => { });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
getRunDebugAgent() {
|
|
107
|
+
return this.deps.runDebugAgent ?? runDebugAgent;
|
|
108
|
+
}
|
|
109
|
+
getFindInterrupted() {
|
|
110
|
+
return this.deps.findInterrupted ?? defaultFindInterrupted;
|
|
111
|
+
}
|
|
112
|
+
getResumeSessions() {
|
|
113
|
+
return this.deps.resumeSessions ?? resumeViaRpcWithSession;
|
|
114
|
+
}
|
|
115
|
+
getAutoResumeEnabled() {
|
|
116
|
+
// Priority: env > supervisor config.json > maestro settings.json > default true (enabled)
|
|
117
|
+
// Configures whether interrupted sessions are auto-resumed after restart (vs only notify).
|
|
118
|
+
// For Settings UI: boolean toggle — true = auto-resume within window, false = notify only.
|
|
119
|
+
const env = process.env.DSH_SUPERVISOR_AUTO_RESUME;
|
|
120
|
+
if (env !== undefined) {
|
|
121
|
+
const v = env.trim().toLowerCase();
|
|
122
|
+
if (['1', 'true', 'yes', 'on', 'enabled'].includes(v))
|
|
123
|
+
return true;
|
|
124
|
+
if (['0', 'false', 'no', 'off', 'disabled'].includes(v))
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
try {
|
|
128
|
+
const cfgPath = path.join(os.homedir(), '.dsh/.supervisor/config.json');
|
|
129
|
+
if (fs.existsSync(cfgPath)) {
|
|
130
|
+
const cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf-8'));
|
|
131
|
+
const raw = cfg.autoResumeEnabled ?? cfg.autoResume;
|
|
132
|
+
if (typeof raw === 'boolean')
|
|
133
|
+
return raw;
|
|
134
|
+
if (typeof raw === 'string') {
|
|
135
|
+
const v = raw.trim().toLowerCase();
|
|
136
|
+
if (['1', 'true', 'yes', 'on'].includes(v))
|
|
137
|
+
return true;
|
|
138
|
+
if (['0', 'false', 'no', 'off'].includes(v))
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const maestroPath = path.join(os.homedir(), '.dsh/maestro/settings.json');
|
|
143
|
+
if (fs.existsSync(maestroPath)) {
|
|
144
|
+
const j = JSON.parse(fs.readFileSync(maestroPath, 'utf-8'));
|
|
145
|
+
const raw = j?.domains?.supervisor?.autoResumeEnabled ?? j?.supervisor?.autoResumeEnabled ?? j?.domains?.supervisor?.autoResume ?? j?.supervisor?.autoResume;
|
|
146
|
+
if (typeof raw === 'boolean')
|
|
147
|
+
return raw;
|
|
148
|
+
if (typeof raw === 'string') {
|
|
149
|
+
const v = raw.trim().toLowerCase();
|
|
150
|
+
if (['1', 'true', 'yes', 'on'].includes(v))
|
|
151
|
+
return true;
|
|
152
|
+
if (['0', 'false', 'no', 'off'].includes(v))
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
catch { }
|
|
158
|
+
return true; // default enabled
|
|
159
|
+
}
|
|
160
|
+
getResumeWithinMs() {
|
|
161
|
+
// Priority: env > supervisor config.json > maestro settings.json > default 5 (minutes)
|
|
162
|
+
// Note: config value is in MINUTES (number 5 = 5 minutes). String "5m"/"30s"/"1h" also supported via parseDuration.
|
|
163
|
+
const env = process.env.DSH_SUPERVISOR_RESUME_WITHIN;
|
|
164
|
+
if (env) {
|
|
165
|
+
// Bare number in env like "5" → treat as minutes for ergonomics
|
|
166
|
+
if (/^\d+$/.test(env.trim())) {
|
|
167
|
+
const n = parseInt(env.trim(), 10);
|
|
168
|
+
if (!isNaN(n))
|
|
169
|
+
return n * 60 * 1000;
|
|
170
|
+
}
|
|
171
|
+
const v = parseDuration(env);
|
|
172
|
+
if (v !== undefined)
|
|
173
|
+
return v;
|
|
174
|
+
const n = parseInt(env, 10);
|
|
175
|
+
if (!isNaN(n))
|
|
176
|
+
return n;
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
const cfgPath = path.join(os.homedir(), '.dsh/.supervisor/config.json');
|
|
180
|
+
if (fs.existsSync(cfgPath)) {
|
|
181
|
+
const cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf-8'));
|
|
182
|
+
const raw = cfg.autoResumeWithin ?? cfg.resumeWithin;
|
|
183
|
+
if (typeof raw === 'string') {
|
|
184
|
+
if (/^\d+$/.test(raw.trim()))
|
|
185
|
+
return parseInt(raw.trim(), 10) * 60 * 1000; // bare string digits → minutes
|
|
186
|
+
const v = parseDuration(raw);
|
|
187
|
+
if (v !== undefined)
|
|
188
|
+
return v;
|
|
189
|
+
}
|
|
190
|
+
else if (typeof raw === 'number')
|
|
191
|
+
return raw * 60 * 1000; // number is MINUTES
|
|
192
|
+
}
|
|
193
|
+
const maestroPath = path.join(os.homedir(), '.dsh/maestro/settings.json');
|
|
194
|
+
if (fs.existsSync(maestroPath)) {
|
|
195
|
+
const j = JSON.parse(fs.readFileSync(maestroPath, 'utf-8'));
|
|
196
|
+
const raw = j?.domains?.supervisor?.autoResumeWithin ?? j?.supervisor?.autoResumeWithin;
|
|
197
|
+
if (typeof raw === 'string') {
|
|
198
|
+
if (/^\d+$/.test(raw.trim()))
|
|
199
|
+
return parseInt(raw.trim(), 10) * 60 * 1000;
|
|
200
|
+
const v = parseDuration(raw);
|
|
201
|
+
if (v !== undefined)
|
|
202
|
+
return v;
|
|
203
|
+
}
|
|
204
|
+
else if (typeof raw === 'number')
|
|
205
|
+
return raw * 60 * 1000;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
catch { }
|
|
209
|
+
return 5 * 60 * 1000; // default 5 minutes
|
|
210
|
+
}
|
|
211
|
+
async getEffectiveIntervalMs() {
|
|
212
|
+
if (this.deps.intervalMs !== undefined)
|
|
213
|
+
return this.deps.intervalMs;
|
|
214
|
+
try {
|
|
215
|
+
const cfg = await readSupervisorConfig();
|
|
216
|
+
if (typeof cfg.intervalMs === 'number' && cfg.intervalMs > 0)
|
|
217
|
+
return cfg.intervalMs;
|
|
218
|
+
}
|
|
219
|
+
catch { }
|
|
220
|
+
return 5000;
|
|
221
|
+
}
|
|
222
|
+
async getEffectiveDownThreshold() {
|
|
223
|
+
if (this.deps.downThreshold !== undefined)
|
|
224
|
+
return this.deps.downThreshold;
|
|
225
|
+
try {
|
|
226
|
+
const cfg = await readSupervisorConfig();
|
|
227
|
+
if (typeof cfg.downThreshold === 'number' && cfg.downThreshold > 0)
|
|
228
|
+
return cfg.downThreshold;
|
|
229
|
+
}
|
|
230
|
+
catch { }
|
|
231
|
+
return 6;
|
|
232
|
+
}
|
|
233
|
+
async getEffectiveDegradedThreshold() {
|
|
234
|
+
try {
|
|
235
|
+
const cfg = await readSupervisorConfig();
|
|
236
|
+
if (typeof cfg.degradedThreshold === 'number' && cfg.degradedThreshold > 0)
|
|
237
|
+
return cfg.degradedThreshold;
|
|
238
|
+
}
|
|
239
|
+
catch { }
|
|
240
|
+
return 5;
|
|
241
|
+
}
|
|
242
|
+
async getEffectivePollTimeoutMs() {
|
|
243
|
+
try {
|
|
244
|
+
const cfg = await readSupervisorConfig();
|
|
245
|
+
if (typeof cfg.pollTimeoutMs === 'number' && cfg.pollTimeoutMs > 0)
|
|
246
|
+
return cfg.pollTimeoutMs;
|
|
247
|
+
}
|
|
248
|
+
catch { }
|
|
249
|
+
return 20000;
|
|
250
|
+
}
|
|
251
|
+
async getEffectiveBootGraceMs() {
|
|
252
|
+
if (this.deps.bootGraceMs !== undefined)
|
|
253
|
+
return this.deps.bootGraceMs;
|
|
254
|
+
try {
|
|
255
|
+
const cfg = await readSupervisorConfig();
|
|
256
|
+
if (typeof cfg.bootGraceMs === 'number' && cfg.bootGraceMs > 0)
|
|
257
|
+
return cfg.bootGraceMs;
|
|
258
|
+
}
|
|
259
|
+
catch { }
|
|
260
|
+
return 180_000;
|
|
261
|
+
}
|
|
262
|
+
async findInterruptedRecent(withinMs) {
|
|
263
|
+
const ms = withinMs ?? this.getResumeWithinMs();
|
|
264
|
+
// Prefer injected mock for testability
|
|
265
|
+
if (this.deps.findInterrupted) {
|
|
266
|
+
try {
|
|
267
|
+
const res = await this.deps.findInterrupted();
|
|
268
|
+
// If mock doesn't filter by time, we still return as-is (test expects all)
|
|
269
|
+
// For real filtering when mock is not time-aware, try to filter via resume module if possible
|
|
270
|
+
if (ms !== undefined && res.interrupted.length) {
|
|
271
|
+
try {
|
|
272
|
+
const { findInterrupted } = await import('./resume.js');
|
|
273
|
+
// Re-query with time filter for real filesystem; if mock was used for test, keep mock result
|
|
274
|
+
if (process.env.VITEST)
|
|
275
|
+
return res;
|
|
276
|
+
return findInterrupted(undefined, { withinMs: ms });
|
|
277
|
+
}
|
|
278
|
+
catch { }
|
|
279
|
+
}
|
|
280
|
+
return res;
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
// fallback to real
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
try {
|
|
287
|
+
const { findInterrupted } = await import('./resume.js');
|
|
288
|
+
return findInterrupted(undefined, { withinMs: ms });
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
return this.getFindInterrupted()();
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
async collectGitDiff() {
|
|
295
|
+
try {
|
|
296
|
+
const { execSync } = await import('node:child_process');
|
|
297
|
+
const ws = resolveHarnessRoot();
|
|
298
|
+
try {
|
|
299
|
+
const out = execSync(`git -C ${JSON.stringify(ws)} status --porcelain 2>/dev/null | head -n 50`, { encoding: 'utf-8', timeout: 2000 });
|
|
300
|
+
if (out.trim()) {
|
|
301
|
+
const diff = execSync(`git -C ${JSON.stringify(ws)} diff 2>/dev/null | head -n 200`, { encoding: 'utf-8', timeout: 2000 });
|
|
302
|
+
return diff || out;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
catch { }
|
|
306
|
+
const diff = execSync('git diff 2>/dev/null | head -n 200', { encoding: 'utf-8', timeout: 2000 });
|
|
307
|
+
return diff.trim() ? diff : '';
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
return '';
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
async attemptAutoResume(ids) {
|
|
314
|
+
if (!ids.length)
|
|
315
|
+
return;
|
|
316
|
+
if (!this.getAutoResumeEnabled()) {
|
|
317
|
+
await this.deps.notify(`RESUME: ${ids.length} interrupted sessions (${ids.slice(0, 3).join(', ')}) — auto-resume disabled`).catch(() => { });
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
try {
|
|
321
|
+
const { resumed } = await this.getResumeSessions()(ids);
|
|
322
|
+
if (!resumed.length) {
|
|
323
|
+
await this.deps.notify(`RESUME SKIPPED: no interrupted sessions could be re-attached (${ids.slice(0, 3).join(', ')})`).catch(() => { });
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
await this.deps.notify(`RESUME: ${resumed.length} interrupted sessions — continue triggered (${resumed.slice(0, 3).join(', ')})`).catch(() => { });
|
|
327
|
+
}
|
|
328
|
+
catch (e) {
|
|
329
|
+
await this.deps.notify(`RESUME FAILED: ${ids.length} interrupted sessions (${ids.slice(0, 3).join(', ')}) — ${e?.message ?? String(e)}`).catch(() => { });
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* D4: a restore that could not put every entry back must be surfaced loudly.
|
|
334
|
+
* Without this, a half-restored tree reads exactly like a clean recovery in
|
|
335
|
+
* the log and in the operator's Telegram feed.
|
|
336
|
+
*/
|
|
337
|
+
async reportRollbackResult(summary, reportPath) {
|
|
338
|
+
if (!summary || !summary.skipped?.length)
|
|
339
|
+
return;
|
|
340
|
+
const first = summary.skipped.slice(0, 3).map(s => `${s.path} (${s.reason})`).join('; ');
|
|
341
|
+
await this.deps.notify(`ROLLBACK PARTIAL: ${summary.restored ?? 0} restored, ${summary.skipped.length} skipped — ${first} (report: ${reportPath})`).catch(() => { });
|
|
342
|
+
}
|
|
343
|
+
handleDebugResult(reportPath, res) {
|
|
344
|
+
if (res.fixed) {
|
|
345
|
+
void this.deps.notify(`FIXED: debug-agent fixed ${reportPath} — ${res.reason}`).catch(() => { });
|
|
346
|
+
// After fix, try to resume interrupted sessions (only recent, default 5 from config, in minutes)
|
|
347
|
+
void this.findInterruptedRecent().then(r => {
|
|
348
|
+
if (r.interrupted.length)
|
|
349
|
+
void this.attemptAutoResume(r.interrupted).catch(() => { });
|
|
350
|
+
}).catch(() => { });
|
|
351
|
+
}
|
|
352
|
+
else if (res.reason.includes('max attempts')) {
|
|
353
|
+
void this.deps.notify(`FIX FAILED after 3 attempts — needs human (report: ${reportPath}, reason: ${res.reason})`).catch(() => { });
|
|
354
|
+
}
|
|
355
|
+
else if (res.reason.includes('cooldown')) {
|
|
356
|
+
// silent — cooldown, no notify
|
|
357
|
+
}
|
|
358
|
+
else {
|
|
359
|
+
// non-fixed but not max attempts — still surface for visibility
|
|
360
|
+
void this.deps.notify(`FIX FAILED: ${res.reason} (report: ${reportPath})`).catch(() => { });
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
async tick() {
|
|
364
|
+
const health = await this.deps.pollHealth();
|
|
365
|
+
// dsh_web_restart hand-off: the tool wrote a caller marker and handed the
|
|
366
|
+
// restart to the daemon (out-of-band). Honor one request per marker — one
|
|
367
|
+
// grace timer → restartWeb once → notify. The suppression marker and the
|
|
368
|
+
// single-flight latch are held until a post-restart health.up tick clears
|
|
369
|
+
// them, so the in-flight down of our own restart can never be mistaken for
|
|
370
|
+
// a crash and raced with a rollback + second restart by the crash path.
|
|
371
|
+
const restartReq = this.deps.readRestartRequest ? this.deps.readRestartRequest() : undefined;
|
|
372
|
+
if (restartReq?.callerSessionId && !this.restartRequestHandled) {
|
|
373
|
+
this.restartRequestHandled = true;
|
|
374
|
+
this.restartRequestTimer = setTimeout(() => {
|
|
375
|
+
void (async () => {
|
|
376
|
+
try {
|
|
377
|
+
// Debounce crash handling from the moment the restart is issued —
|
|
378
|
+
// the crash path sets lastRollback the same way. A slow boot must
|
|
379
|
+
// not be classified as a crash even after the suppression marker's
|
|
380
|
+
// own 30s TTL runs out.
|
|
381
|
+
this.lastRollback = this.deps.getTime ? this.deps.getTime() : Date.now();
|
|
382
|
+
await this.restartWeb();
|
|
383
|
+
// restartWeb() already wrote the marker with the boot budget as its
|
|
384
|
+
// TTL; the marker is cleared on the first healthy poll instead.
|
|
385
|
+
await this.deps.notify(`restarted dsh-web after self-restart by session ${restartReq.callerSessionId}`);
|
|
386
|
+
}
|
|
387
|
+
catch (e) {
|
|
388
|
+
await this.deps.notify(`self-restart dsh-web failed: ${e?.message ?? String(e)}`).catch(() => { });
|
|
389
|
+
if (restartReq.callerSessionId) {
|
|
390
|
+
try {
|
|
391
|
+
;
|
|
392
|
+
(this.deps.writeOutcome ?? defaultWriteOutcome)(restartReq.callerSessionId, {
|
|
393
|
+
state: 'failed',
|
|
394
|
+
oldPid: restartReq.oldPid,
|
|
395
|
+
swappedAt: this.deps.getTime ? this.deps.getTime() : Date.now(),
|
|
396
|
+
error: e?.message ?? String(e),
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
catch { }
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
finally {
|
|
403
|
+
// Hold the marker and latch until health.up: clearing here would
|
|
404
|
+
// drop crash suppression mid-restart, and re-arming here would let
|
|
405
|
+
// a still-present marker re-fire into a second restart.
|
|
406
|
+
this.awaitingHealthyBoot = true;
|
|
407
|
+
this.pendingRestartRequest = restartReq;
|
|
408
|
+
this.restartRequestTimer = null;
|
|
409
|
+
}
|
|
410
|
+
})();
|
|
411
|
+
}, 5000);
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
// DEGRADED: http 200 but log has plugin error → report + notify, rollback after consecutive threshold
|
|
415
|
+
if (health.degraded) {
|
|
416
|
+
this.consecutiveDown = 0;
|
|
417
|
+
// D1: a degraded verdict while the current boot is unproven is a boot
|
|
418
|
+
// transient, not a plugin error — the incident's report line
|
|
419
|
+
// "rollback — degraded: This operation was aborted" was produced exactly
|
|
420
|
+
// here, five polls after a slow boot.
|
|
421
|
+
if (health.bootPhase === 'booting') {
|
|
422
|
+
this.consecutiveDegraded = 0;
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
// Check suppression first — don't count degraded during planned restart grace
|
|
426
|
+
let suppressedByMarkerDeg = false;
|
|
427
|
+
try {
|
|
428
|
+
suppressedByMarkerDeg = this.getCheckPlannedRestart()();
|
|
429
|
+
}
|
|
430
|
+
catch {
|
|
431
|
+
suppressedByMarkerDeg = false;
|
|
432
|
+
}
|
|
433
|
+
if (suppressedByMarkerDeg) {
|
|
434
|
+
this.consecutiveDegraded = 0;
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
if (this.deps.isPlannedRestartActive) {
|
|
438
|
+
let planned = false;
|
|
439
|
+
try {
|
|
440
|
+
planned = await Promise.resolve(this.deps.isPlannedRestartActive());
|
|
441
|
+
}
|
|
442
|
+
catch {
|
|
443
|
+
planned = false;
|
|
444
|
+
}
|
|
445
|
+
if (planned) {
|
|
446
|
+
this.consecutiveDegraded = 0;
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
const now = this.deps.getTime ? this.deps.getTime() : Date.now();
|
|
451
|
+
// degraded needs consecutive hits to avoid flapping — Option A 2026-09-03: 3→5 (via config)
|
|
452
|
+
const degradedThreshold = await this.getEffectiveDegradedThreshold();
|
|
453
|
+
this.consecutiveDegraded++;
|
|
454
|
+
if (this.consecutiveDegraded < degradedThreshold) {
|
|
455
|
+
if (now - this.lastDegradedNotify < 60000)
|
|
456
|
+
return;
|
|
457
|
+
this.lastDegradedNotify = now;
|
|
458
|
+
try {
|
|
459
|
+
const ts = new Date().toISOString().replace(/[:.]/g, '-');
|
|
460
|
+
const logTail = health.logTail ?? '';
|
|
461
|
+
const gitDiff = await this.collectGitDiff().catch(() => '');
|
|
462
|
+
const reportPath = await this.deps.writeReport({ ts, health, action: `degraded — ${health.error ?? 'plugin'}`, logTail, gitDiff }).catch(() => '');
|
|
463
|
+
await this.deps.notify(`DEGRADED: ${health.error ?? 'plugin'} (report: ${reportPath})`).catch(() => { });
|
|
464
|
+
const runner = this.getRunDebugAgent();
|
|
465
|
+
const isInjected = !!this.deps.runDebugAgent;
|
|
466
|
+
if (isInjected) {
|
|
467
|
+
void runner({ reportPath, health }).then(res => this.handleDebugResult(reportPath, res)).catch(() => { });
|
|
468
|
+
setTimeout(() => {
|
|
469
|
+
this.findInterruptedRecent().then(r => {
|
|
470
|
+
if (r.interrupted.length)
|
|
471
|
+
void this.attemptAutoResume(r.interrupted).catch(() => { });
|
|
472
|
+
}).catch(() => { });
|
|
473
|
+
}, 0);
|
|
474
|
+
}
|
|
475
|
+
else if (!process.env.VITEST) {
|
|
476
|
+
void runner({ reportPath, health }).then(res => this.handleDebugResult(reportPath, res)).catch(() => { });
|
|
477
|
+
setTimeout(() => {
|
|
478
|
+
this.findInterruptedRecent().then(r => {
|
|
479
|
+
if (r.interrupted.length)
|
|
480
|
+
void this.attemptAutoResume(r.interrupted).catch(() => { });
|
|
481
|
+
}).catch(() => { });
|
|
482
|
+
}, 0);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
catch { }
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
// consecutive degraded threshold reached → treat as down: rollback + restart
|
|
489
|
+
this.consecutiveDegraded = 0;
|
|
490
|
+
const degradedError = health.error ?? 'degraded plugin error';
|
|
491
|
+
if (this.rollingBack)
|
|
492
|
+
return;
|
|
493
|
+
const now2 = this.deps.getTime ? this.deps.getTime() : Date.now();
|
|
494
|
+
const debounceMs2 = this.deps.debounceMs ?? 60000;
|
|
495
|
+
if (now2 - this.lastRollback < debounceMs2)
|
|
496
|
+
return;
|
|
497
|
+
this.rollingBack = true;
|
|
498
|
+
this.lastRollback = now2;
|
|
499
|
+
try {
|
|
500
|
+
const failed = await this.deps.writeFailed().catch(() => ({ ts: new Date().toISOString().replace(/[:.]/g, '-'), manifest: null }));
|
|
501
|
+
const ts2 = failed?.ts ?? new Date().toISOString().replace(/[:.]/g, '-');
|
|
502
|
+
const logTail2 = health.logTail ?? '';
|
|
503
|
+
const gitDiff2 = await this.collectGitDiff().catch(() => '');
|
|
504
|
+
const degradedHealth = { up: false, httpCode: health.httpCode, error: `degraded → down: ${degradedError}`, logTail: logTail2, degraded: false };
|
|
505
|
+
const reportPath2 = await this.deps.writeReport({ ts: ts2, health: degradedHealth, action: `rollback — degraded: ${degradedError}`, logTail: logTail2, gitDiff: gitDiff2 }).catch(() => '');
|
|
506
|
+
try {
|
|
507
|
+
const summary = await this.deps.rollback();
|
|
508
|
+
await this.reportRollbackResult(summary, reportPath2);
|
|
509
|
+
}
|
|
510
|
+
catch (e) {
|
|
511
|
+
await this.deps.notify(`rollback failed: ${e?.message ?? String(e)} (report: ${reportPath2})`).catch(() => { });
|
|
512
|
+
}
|
|
513
|
+
if (this.deps.restartWeb) {
|
|
514
|
+
try {
|
|
515
|
+
await this.deps.restartWeb();
|
|
516
|
+
await this.deps.notify(`restarted dsh-web after rollback (report: ${reportPath2})`).catch(() => { });
|
|
517
|
+
}
|
|
518
|
+
catch (e) {
|
|
519
|
+
await this.deps.notify(`restart dsh-web failed: ${e?.message ?? String(e)} (report: ${reportPath2})`).catch(() => { });
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
await this.deps.notify(`DEGRADED → rollback (report: ${reportPath2}, error: ${degradedError})`).catch(() => { });
|
|
523
|
+
try {
|
|
524
|
+
await this.deps.notify(`🔄 dsh web auto-restart — degraded: ${degradedError} — ${new Date().toISOString()}`).catch(() => { });
|
|
525
|
+
}
|
|
526
|
+
catch { }
|
|
527
|
+
}
|
|
528
|
+
finally {
|
|
529
|
+
this.rollingBack = false;
|
|
530
|
+
}
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
if (health.up) {
|
|
534
|
+
this.consecutiveDown = 0;
|
|
535
|
+
this.consecutiveDegraded = 0;
|
|
536
|
+
// D5: a healthy poll is the authoritative "the restart succeeded"
|
|
537
|
+
// signal — clear the suppression marker here instead of waiting for its
|
|
538
|
+
// TTL, so a stale marker can never mute a later real crash.
|
|
539
|
+
let markerClearedThisTick = false;
|
|
540
|
+
try {
|
|
541
|
+
if (this.getCheckPlannedRestart()()) {
|
|
542
|
+
this.getClearPlannedRestart()();
|
|
543
|
+
markerClearedThisTick = true;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
catch { }
|
|
547
|
+
// Post-self-restart boot proved healthy: run the post-restart
|
|
548
|
+
// session-scan hook and re-arm the single-flight latch. A failed clear
|
|
549
|
+
// keeps the latch set so the same marker is never re-handled into a
|
|
550
|
+
// second restart.
|
|
551
|
+
if (this.awaitingHealthyBoot) {
|
|
552
|
+
this.awaitingHealthyBoot = false;
|
|
553
|
+
const req = this.pendingRestartRequest;
|
|
554
|
+
this.pendingRestartRequest = undefined;
|
|
555
|
+
let cleared = markerClearedThisTick;
|
|
556
|
+
if (!cleared) {
|
|
557
|
+
try {
|
|
558
|
+
this.getClearPlannedRestart()();
|
|
559
|
+
cleared = true;
|
|
560
|
+
}
|
|
561
|
+
catch { }
|
|
562
|
+
}
|
|
563
|
+
if (cleared)
|
|
564
|
+
this.restartRequestHandled = false;
|
|
565
|
+
if (req) {
|
|
566
|
+
try {
|
|
567
|
+
this.deps.onRestartRequestHandled?.(req);
|
|
568
|
+
}
|
|
569
|
+
catch { }
|
|
570
|
+
if (req.callerSessionId) {
|
|
571
|
+
try {
|
|
572
|
+
const listen = this.deps.listenerPid ?? defaultListenerPid;
|
|
573
|
+
(this.deps.writeOutcome ?? defaultWriteOutcome)(req.callerSessionId, {
|
|
574
|
+
state: 'ok',
|
|
575
|
+
oldPid: req.oldPid,
|
|
576
|
+
newPid: listen(3082),
|
|
577
|
+
httpStatus: health?.httpCode ?? 200,
|
|
578
|
+
swappedAt: this.deps.getTime ? this.deps.getTime() : Date.now(),
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
catch { }
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
// Throttle LKG writes to at most once per 5 minutes
|
|
586
|
+
const now = this.deps.getTime ? this.deps.getTime() : Date.now();
|
|
587
|
+
if (now - this.lastLKGWrite > 5 * 60 * 1000) {
|
|
588
|
+
try {
|
|
589
|
+
await this.deps.writeLKG();
|
|
590
|
+
this.lastLKGWrite = now;
|
|
591
|
+
}
|
|
592
|
+
catch {
|
|
593
|
+
// ignore snapshot errors
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
// Single-owner 30s marker: planned restart in progress — suppress crash
|
|
599
|
+
// handling entirely for 30s (no writeFailed/writeReport/rollback).
|
|
600
|
+
// Check both the new JSON marker (writePlannedRestart) and the legacy
|
|
601
|
+
// isPlannedRestartActive (dsh-safe-web-update plain file) for compat.
|
|
602
|
+
let suppressedByMarker = false;
|
|
603
|
+
try {
|
|
604
|
+
suppressedByMarker = this.getCheckPlannedRestart()();
|
|
605
|
+
}
|
|
606
|
+
catch {
|
|
607
|
+
suppressedByMarker = false;
|
|
608
|
+
}
|
|
609
|
+
if (suppressedByMarker) {
|
|
610
|
+
this.consecutiveDown = 0;
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
// Down while an intentional restart (e.g. dsh-safe-web-update) is in
|
|
614
|
+
// flight is expected, not a crash — never race it with our own
|
|
615
|
+
// rollback/restartWeb.
|
|
616
|
+
if (this.deps.isPlannedRestartActive) {
|
|
617
|
+
let planned = false;
|
|
618
|
+
try {
|
|
619
|
+
planned = await Promise.resolve(this.deps.isPlannedRestartActive());
|
|
620
|
+
}
|
|
621
|
+
catch {
|
|
622
|
+
planned = false;
|
|
623
|
+
}
|
|
624
|
+
if (planned) {
|
|
625
|
+
this.consecutiveDown = 0;
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
// Down — require consecutive confirmations before treating as a crash.
|
|
630
|
+
// A lone timed-out poll (e.g. a slow plugin-tree boot) must not trigger
|
|
631
|
+
// rollback/restart: that restart produces its own transient errors on
|
|
632
|
+
// the next poll, which would otherwise re-trigger this same path forever.
|
|
633
|
+
// D1/D2: while the boot is unproven only a refused connection may advance
|
|
634
|
+
// the down counter — nothing is listening, so the process is gone. A
|
|
635
|
+
// timeout/abort (or anything unattributable) is a slow boot, not a crash.
|
|
636
|
+
if (health.bootPhase === 'booting' && classifyFetchFailure(health.error) !== 'refused') {
|
|
637
|
+
this.consecutiveDown = 0;
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
this.consecutiveDown++;
|
|
641
|
+
let downThreshold = await this.getEffectiveDownThreshold();
|
|
642
|
+
// When a planned restart marker is active, double the threshold (3→6 at
|
|
643
|
+
// 3s interval ≈ 9s→18s). Health-poller already suppresses fetch failed in
|
|
644
|
+
// this window, but supervisor also doubles so a transient that escapes
|
|
645
|
+
// health still needs longer to trigger. The early return above already
|
|
646
|
+
// suppresses fully for 30s; doubling remains for the legacy
|
|
647
|
+
// isPlannedRestartActive path and for any race where the marker was
|
|
648
|
+
// written between the early check and this line.
|
|
649
|
+
try {
|
|
650
|
+
if (this.getCheckPlannedRestart()())
|
|
651
|
+
downThreshold *= 2;
|
|
652
|
+
}
|
|
653
|
+
catch { }
|
|
654
|
+
if (this.consecutiveDown < downThreshold)
|
|
655
|
+
return;
|
|
656
|
+
// Down — check debounce and rolling state
|
|
657
|
+
if (this.rollingBack)
|
|
658
|
+
return;
|
|
659
|
+
const now = this.deps.getTime ? this.deps.getTime() : Date.now();
|
|
660
|
+
const debounceMs = this.deps.debounceMs ?? 60000;
|
|
661
|
+
if (now - this.lastRollback < debounceMs)
|
|
662
|
+
return;
|
|
663
|
+
this.rollingBack = true;
|
|
664
|
+
this.consecutiveDown = 0;
|
|
665
|
+
this.lastRollback = now;
|
|
666
|
+
try {
|
|
667
|
+
const failed = await this.deps.writeFailed().catch(() => ({ ts: new Date().toISOString().replace(/[:.]/g, '-'), manifest: null }));
|
|
668
|
+
const ts = failed?.ts ?? new Date().toISOString().replace(/[:.]/g, '-');
|
|
669
|
+
const logTail = health.logTail ?? '';
|
|
670
|
+
const gitDiff = await this.collectGitDiff().catch(() => '');
|
|
671
|
+
const reportPath = await this.deps.writeReport({ ts, health, action: `rollback — ${health.error ?? 'down'}`, logTail, gitDiff }).catch(() => '');
|
|
672
|
+
try {
|
|
673
|
+
const summary = await this.deps.rollback();
|
|
674
|
+
await this.reportRollbackResult(summary, reportPath);
|
|
675
|
+
}
|
|
676
|
+
catch (e) {
|
|
677
|
+
await this.deps.notify(`rollback failed: ${e?.message ?? String(e)} (report: ${reportPath})`).catch(() => { });
|
|
678
|
+
}
|
|
679
|
+
// Always attempt to (re)start dsh web — survives reboot even when rollback is a no-op
|
|
680
|
+
if (this.deps.restartWeb) {
|
|
681
|
+
try {
|
|
682
|
+
await this.deps.restartWeb();
|
|
683
|
+
await this.deps.notify(`restarted dsh-web after rollback (report: ${reportPath})`).catch(() => { });
|
|
684
|
+
}
|
|
685
|
+
catch (e) {
|
|
686
|
+
await this.deps.notify(`restart dsh-web failed: ${e?.message ?? String(e)} (report: ${reportPath})`).catch(() => { });
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
await this.deps.notify(`CRASH detected → rollback (report: ${reportPath}, error: ${health.error ?? 'down'})`).catch(() => { });
|
|
690
|
+
const runner = this.getRunDebugAgent();
|
|
691
|
+
const isInjected = !!this.deps.runDebugAgent;
|
|
692
|
+
if (isInjected) {
|
|
693
|
+
void runner({ reportPath, health }).then(res => this.handleDebugResult(reportPath, res)).catch(() => { });
|
|
694
|
+
setTimeout(() => {
|
|
695
|
+
this.findInterruptedRecent().then(r => {
|
|
696
|
+
if (r.interrupted.length)
|
|
697
|
+
void this.attemptAutoResume(r.interrupted).catch(() => { });
|
|
698
|
+
}).catch(() => { });
|
|
699
|
+
}, 0);
|
|
700
|
+
}
|
|
701
|
+
else if (!process.env.VITEST) {
|
|
702
|
+
void runner({ reportPath, health }).then(res => this.handleDebugResult(reportPath, res)).catch(() => { });
|
|
703
|
+
setTimeout(() => {
|
|
704
|
+
this.findInterruptedRecent().then(r => {
|
|
705
|
+
if (r.interrupted.length)
|
|
706
|
+
void this.attemptAutoResume(r.interrupted).catch(() => { });
|
|
707
|
+
}).catch(() => { });
|
|
708
|
+
}, 0);
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
finally {
|
|
712
|
+
this.rollingBack = false;
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
async start() {
|
|
716
|
+
if (this.timer)
|
|
717
|
+
return;
|
|
718
|
+
const intervalMs = await this.getEffectiveIntervalMs();
|
|
719
|
+
this.timer = setInterval(() => { this.tick().catch(() => { }); }, intervalMs);
|
|
720
|
+
// Immediate tick so a reboot is recovered in ~0-3s, not 3s
|
|
721
|
+
this.tick().catch(() => { });
|
|
722
|
+
}
|
|
723
|
+
// Synchronous start wrapper for callers that do not await (daemon cli fire-and-forget)
|
|
724
|
+
startSync() {
|
|
725
|
+
// The caller never observes this promise: an escaping rejection would reach
|
|
726
|
+
// the host's unhandled-rejection path and exit the daemon.
|
|
727
|
+
void this.start().catch((err) => {
|
|
728
|
+
console.error('dsh-web-supervisor: start failed:', err instanceof Error ? err.message : err);
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
stop() {
|
|
732
|
+
if (this.timer) {
|
|
733
|
+
clearInterval(this.timer);
|
|
734
|
+
this.timer = null;
|
|
735
|
+
}
|
|
736
|
+
if (this.restartRequestTimer) {
|
|
737
|
+
clearTimeout(this.restartRequestTimer);
|
|
738
|
+
this.restartRequestTimer = null;
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
}
|