@ddtcorex/dsh-maestro-core 0.10.0 → 0.11.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/README.md +31 -12
- package/lib/cli.js +0 -2
- package/lib/client.js +58 -83
- package/lib/config/index.d.ts +11 -4
- package/lib/config/index.js +26 -9
- package/lib/config/service.d.ts +2 -2
- package/lib/config/service.js +2 -2
- package/lib/debug-agent.js +1 -1
- package/lib/paths.d.ts +8 -0
- package/lib/paths.js +22 -0
- package/lib/plugin.d.ts +21 -1
- package/lib/plugin.js +74 -6
- package/lib/restart-guards.js +1 -1
- package/lib/restart-tool.js +13 -4
- package/lib/resume-log.d.ts +4 -0
- package/lib/resume-log.js +13 -4
- package/lib/store/index.js +119 -45
- package/lib/supervisor.js +5 -7
- package/lib/types/client/config/MaestroSettings.d.ts.map +1 -1
- package/package.json +4 -2
- package/scripts/build-client.mjs +53 -0
- package/scripts/install-systemd.sh +55 -0
- package/scripts/sync/bench-preview.mjs +43 -0
- package/scripts/sync/cdp-sync-probe.mjs +200 -0
- package/scripts/sync/cdp-sync-verify.mjs +169 -0
- package/scripts/vendor-store.mjs +104 -0
- package/skills/dsh-safe-restart/SKILL.md +2 -2
- package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +2 -2
- package/src/client/config/MaestroSettings.tsx +4 -137
- package/src/host/cli.ts +0 -2
- package/src/host/config/index.ts +27 -10
- package/src/host/config/service.ts +2 -2
- package/src/host/debug-agent.ts +1 -1
- package/src/host/paths.ts +21 -0
- package/src/host/plugin.ts +79 -6
- package/src/host/restart-guards.ts +1 -1
- package/src/host/restart-tool.ts +12 -4
- package/src/host/resume-log.ts +20 -5
- package/src/host/store/index.ts +120 -33
- package/src/host/supervisor.ts +6 -8
- package/systemd/dsh-web-keepalive.service.template +12 -0
- package/systemd/dsh-web-supervisor.service.template +20 -0
- package/systemd/dsh-web.service.template +30 -0
package/src/host/plugin.ts
CHANGED
|
@@ -49,7 +49,22 @@ import { SUPERVISOR_SOURCE_KIND } from './source.js'
|
|
|
49
49
|
|
|
50
50
|
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
|
51
51
|
|
|
52
|
-
|
|
52
|
+
/**
|
|
53
|
+
* Declared service dependencies.
|
|
54
|
+
*
|
|
55
|
+
* Kept EMPTY on purpose. Every service this plugin uses is resolved lazily with
|
|
56
|
+
* `ctx.get?.(…)`, so a declared `inject` entry buys nothing and costs boot
|
|
57
|
+
* latency: Cordis holds activation of the whole plugin until every named
|
|
58
|
+
* service exists.
|
|
59
|
+
*
|
|
60
|
+
* Measured 2026-10-05 on the live host: with
|
|
61
|
+
* inject: ['sessions','agents','connection','tools','skills'] the boot resume
|
|
62
|
+
* scan fired 343s after the process started — the row waited for the LAST of
|
|
63
|
+
* the five. The scan itself needs none of them (it reads session log files),
|
|
64
|
+
* and the resume path reads sessionController/agents/agentPresets/
|
|
65
|
+
* sessionPersistence optionally and degrades to a journalled skip.
|
|
66
|
+
*/
|
|
67
|
+
export const inject = [] as unknown as readonly ['sessions']
|
|
53
68
|
|
|
54
69
|
export interface SupervisorPluginConfig {
|
|
55
70
|
autoResumeWithin?: number | string // in MINUTES if number, or "5m"/"30s"/"1h" string
|
|
@@ -253,6 +268,29 @@ export function getAutoResumeEnabledExported(config?: SupervisorPluginConfig): b
|
|
|
253
268
|
return getAutoResumeEnabled(config)
|
|
254
269
|
}
|
|
255
270
|
|
|
271
|
+
/**
|
|
272
|
+
* Wall-clock ms at which THIS process started, or `undefined` when it cannot
|
|
273
|
+
* be established.
|
|
274
|
+
*
|
|
275
|
+
* `process.uptime()` is captured once at module load: the plugin module is
|
|
276
|
+
* imported during plugin-tree load, which is the earliest point the supervisor
|
|
277
|
+
* has, and the value never needs refreshing. A restart replaces the process, so
|
|
278
|
+
* the anchor moves with the boot by construction.
|
|
279
|
+
*/
|
|
280
|
+
const PROCESS_STARTED_AT_MS: number | undefined = (() => {
|
|
281
|
+
try {
|
|
282
|
+
const up = process.uptime()
|
|
283
|
+
if (typeof up === 'number' && Number.isFinite(up) && up >= 0) {
|
|
284
|
+
return Date.now() - Math.round(up * 1000)
|
|
285
|
+
}
|
|
286
|
+
} catch {}
|
|
287
|
+
return undefined
|
|
288
|
+
})()
|
|
289
|
+
|
|
290
|
+
export function processStartedAtMs(): number | undefined {
|
|
291
|
+
return PROCESS_STARTED_AT_MS
|
|
292
|
+
}
|
|
293
|
+
|
|
256
294
|
export async function runAutoResume(
|
|
257
295
|
ctx: any,
|
|
258
296
|
opts: {
|
|
@@ -261,6 +299,10 @@ export async function runAutoResume(
|
|
|
261
299
|
resumeInterrupted?: typeof resumeInterrupted
|
|
262
300
|
logResume?: (entry: ResumeLogEntry) => void
|
|
263
301
|
config?: SupervisorPluginConfig
|
|
302
|
+
/** Boot anchor for the resume window; defaults to this process's own start. */
|
|
303
|
+
processStartedAtMs?: number
|
|
304
|
+
/** Clock seam for tests. */
|
|
305
|
+
nowMs?: number
|
|
264
306
|
} = {}
|
|
265
307
|
): Promise<void> {
|
|
266
308
|
try {
|
|
@@ -274,7 +316,29 @@ export async function runAutoResume(
|
|
|
274
316
|
return
|
|
275
317
|
}
|
|
276
318
|
const withinMs = getResumeWithinMs(opts?.config)
|
|
277
|
-
|
|
319
|
+
// The window must be anchored to the BOOT, not to the moment the scan
|
|
320
|
+
// runs. `withinMs` alone cannot do this: findInterrupted and
|
|
321
|
+
// findDanglingOpenTurns each compute `sinceMs = Date.now() - withinMs` from
|
|
322
|
+
// their own clock, so on a host that takes minutes to finish loading
|
|
323
|
+
// plugins the boundary drifts forward and ages every candidate out before
|
|
324
|
+
// the scan reads it.
|
|
325
|
+
//
|
|
326
|
+
// Measured 2026-10-05: interruption at 18:10:55, new host at 18:11:02,
|
|
327
|
+
// scan at 18:16:45 (343s after boot). The interruption was then 349s old
|
|
328
|
+
// against `autoResumeWithin = 5min`, so nothing was resumed — while the
|
|
329
|
+
// scan itself costs only 130ms for 234 sessions. Passing an explicit
|
|
330
|
+
// `sinceMs` is the only way to pin the boundary, which is what this does.
|
|
331
|
+
const nowMs = opts?.nowMs ?? Date.now()
|
|
332
|
+
const startedAt = opts?.processStartedAtMs ?? PROCESS_STARTED_AT_MS
|
|
333
|
+
// A caller that cannot supply a boot anchor (the daemon's RPC scan endpoint)
|
|
334
|
+
// keeps the old behaviour, computed here against the injected clock so the
|
|
335
|
+
// boundary is identical rather than left to each scan's own Date.now().
|
|
336
|
+
const anchorMs = (typeof startedAt === 'number' && Number.isFinite(startedAt) && startedAt > 0)
|
|
337
|
+
? startedAt
|
|
338
|
+
: nowMs
|
|
339
|
+
const sinceMs = anchorMs - withinMs
|
|
340
|
+
const scanOpts = { withinMs, sinceMs }
|
|
341
|
+
const { scanned, interrupted } = await doFind(undefined, scanOpts)
|
|
278
342
|
// Only safe to treat a dangling open turn as crashed right after a fresh
|
|
279
343
|
// boot, when this process is the sole live owner of these sessions —
|
|
280
344
|
// exactly the context runAutoResume runs in (called once, 8s after
|
|
@@ -282,12 +346,18 @@ export async function runAutoResume(
|
|
|
282
346
|
// protects any id that happens to be live in *this* process already.
|
|
283
347
|
let dangling: string[] = []
|
|
284
348
|
try {
|
|
285
|
-
dangling = (await doFindDangling(undefined,
|
|
349
|
+
dangling = (await doFindDangling(undefined, scanOpts)).interrupted
|
|
286
350
|
} catch (e: any) {
|
|
287
351
|
ctx.logger?.warn?.(`[supervisor] auto-resume: dangling-open-turn scan failed, continuing with closed-turn results only: ${e?.message ?? String(e)}`)
|
|
288
352
|
}
|
|
289
353
|
const merged = Array.from(new Set([...interrupted, ...dangling]))
|
|
290
|
-
doLog({
|
|
354
|
+
doLog({
|
|
355
|
+
ts: Date.now(),
|
|
356
|
+
kind: 'scan',
|
|
357
|
+
scanned,
|
|
358
|
+
interrupted: merged,
|
|
359
|
+
detail: `withinMs=${withinMs} sinceMs=${sinceMs} anchoredAtBoot=${startedAt === anchorMs ? 1 : 0} bootAgeMs=${Math.max(0, nowMs - anchorMs)}`,
|
|
360
|
+
})
|
|
291
361
|
if (!merged.length) {
|
|
292
362
|
ctx.logger?.info?.(`[supervisor] auto-resume: 0/${scanned} interrupted within ${withinMs}ms — nothing to do`)
|
|
293
363
|
return
|
|
@@ -933,8 +1003,11 @@ export function registerSessionHealthService(ctx: any, config: SupervisorPluginC
|
|
|
933
1003
|
try { ctx.logger?.warn?.(`[supervisor] session-health RPC registration failed: ${e?.message ?? String(e)}`) } catch {}
|
|
934
1004
|
}
|
|
935
1005
|
try {
|
|
936
|
-
|
|
937
|
-
|
|
1006
|
+
// Resolved lazily (see the `inject` note): a declared 'tools' would hold
|
|
1007
|
+
// this plugin's activation until the tools service exists.
|
|
1008
|
+
const tools: any = (ctx.get?.('tools') as any) ?? ctx.tools
|
|
1009
|
+
if (typeof tools?.register === 'function') {
|
|
1010
|
+
disposers.push(tools.register(makeSessionHealthToolDef(config)))
|
|
938
1011
|
}
|
|
939
1012
|
} catch (e: any) {
|
|
940
1013
|
try { ctx.logger?.warn?.(`[supervisor] session-health tool registration failed: ${e?.message ?? String(e)}`) } catch {}
|
|
@@ -56,7 +56,7 @@ export function isSelfCopyError(message: string): boolean {
|
|
|
56
56
|
}
|
|
57
57
|
|
|
58
58
|
// Coordination contract with dsh-safe-web-update's restart-dsh-web.sh (see
|
|
59
|
-
// <workspace-root>/docs/specs/2026-
|
|
59
|
+
// <workspace-root>/docs/specs/2026-09-13-supervisor-restart-resilience-design.md):
|
|
60
60
|
// that script writes this marker right before it intentionally takes dsh-web
|
|
61
61
|
// down, so the supervisor's own health poll does not mistake a deliberate
|
|
62
62
|
// restart (kill -> dry-boot -> relaunch, up to ~130s) for a crash and race it
|
package/src/host/restart-tool.ts
CHANGED
|
@@ -300,12 +300,20 @@ export function registerRestartTool(ctx: any, deps: {
|
|
|
300
300
|
const doRead = deps.readRestartRequest ?? readRestartRequest
|
|
301
301
|
const doSessionId = deps.sessionIdOf ?? currentSessionId
|
|
302
302
|
const readDaemonState = deps.daemonState ?? supervisorDaemonState
|
|
303
|
+
// `tools` is resolved through ctx.get rather than read off ctx directly.
|
|
304
|
+
// A declared `inject` entry blocks the whole plugin's activation until that
|
|
305
|
+
// service exists, and 'tools' was one of the five that delayed the boot
|
|
306
|
+
// resume scan by minutes on a real host (measured 2026-10-05: 343s). The
|
|
307
|
+
// lookup below works from an already-activated plugin, so the tool can
|
|
308
|
+
// register as soon as `tools` exists without the scan waiting for it.
|
|
309
|
+
const tools: any = (ctx.get?.('tools') as any) ?? ctx.tools
|
|
303
310
|
let dispose: (() => void) | undefined
|
|
304
311
|
let disposeDryboot: (() => void) | undefined
|
|
305
312
|
let disposeGc: (() => void) | undefined
|
|
306
313
|
let disposeStatus: (() => void) | undefined
|
|
307
314
|
try {
|
|
308
|
-
|
|
315
|
+
if (typeof tools?.register !== 'function') throw new Error('tools service unavailable')
|
|
316
|
+
dispose = tools.register({
|
|
309
317
|
name: 'dsh_web_restart',
|
|
310
318
|
description: 'Schedule a safe restart of the dsh web host: dry-boots the plugin tree when it changed, records an intent for the calling session, and hands the swap to the supervisor daemon (out-of-band — it never restarts in-tree). Returns immediately; the swap lands ~1-5 min later and kills the calling turn, so call this as the LAST action of the turn and verify with dsh_web_restart_status in the NEXT one (never sleep here). Do not call dsh_web_dryboot first — this tool already dry-boots. The result carries the supervisor daemon verdict: a "stale" line means run its `kill -TERM <pid>` before the swap lands.',
|
|
311
319
|
parameters: {
|
|
@@ -373,7 +381,7 @@ export function registerRestartTool(ctx: any, deps: {
|
|
|
373
381
|
try { ctx.logger?.warn?.(`[supervisor] dsh_web_restart tool failed: ${e?.message ?? String(e)}`) } catch {}
|
|
374
382
|
}
|
|
375
383
|
try {
|
|
376
|
-
disposeDryboot =
|
|
384
|
+
disposeDryboot = tools.register({
|
|
377
385
|
name: 'dsh_web_dryboot',
|
|
378
386
|
description: 'Validate the plugin tree by booting a copy of the live profile on an ephemeral port. Never schedules or performs a restart; temp home removed afterwards.',
|
|
379
387
|
parameters: {
|
|
@@ -398,7 +406,7 @@ export function registerRestartTool(ctx: any, deps: {
|
|
|
398
406
|
}
|
|
399
407
|
try {
|
|
400
408
|
const doKill = deps.killPid ?? ((pid: number, sig: string) => process.kill(pid, sig as NodeJS.Signals))
|
|
401
|
-
disposeGc =
|
|
409
|
+
disposeGc = tools.register({
|
|
402
410
|
name: 'dsh_web_gc',
|
|
403
411
|
description: 'Reap orphaned dry-boot dsh web processes (temp DSH_HOME + ephemeral port). Preview-first: returns candidates without killing unless confirm:true.',
|
|
404
412
|
parameters: {
|
|
@@ -434,7 +442,7 @@ export function registerRestartTool(ctx: any, deps: {
|
|
|
434
442
|
try { ctx.logger?.warn?.(`[supervisor] dsh_web_gc tool failed: ${e?.message ?? String(e)}`) } catch {}
|
|
435
443
|
}
|
|
436
444
|
try {
|
|
437
|
-
disposeStatus =
|
|
445
|
+
disposeStatus = tools.register({
|
|
438
446
|
name: 'dsh_web_restart_status',
|
|
439
447
|
description: 'Read the outcome of the calling session\u2019s latest scheduled dsh web restart (pending until the daemon swaps and health-checks).',
|
|
440
448
|
parameters: {
|
package/src/host/resume-log.ts
CHANGED
|
@@ -13,6 +13,10 @@ import { homedir } from 'node:os'
|
|
|
13
13
|
* session logs. This append-only JSONL sidecar gives a machine-local audit
|
|
14
14
|
* trail of resume outcomes that survives no matter where plugin logs land.
|
|
15
15
|
* Never throws: a write failure must not break the resume path.
|
|
16
|
+
* The path honours `DSH_HOME`. Resolving `homedir()` alone meant every test
|
|
17
|
+
* touching the resume path appended fixture rows to the OPERATOR's journal —
|
|
18
|
+
* `interrupted: ['proj/a-1', 'proj/shared', 'proj/b-2']`, session ids no machine
|
|
19
|
+
* has. Same trap that overwrote the notifier domain's botToken once already.
|
|
16
20
|
*/
|
|
17
21
|
export interface ResumeLogEntry {
|
|
18
22
|
ts: number
|
|
@@ -25,15 +29,26 @@ export interface ResumeLogEntry {
|
|
|
25
29
|
interrupted?: string[]
|
|
26
30
|
}
|
|
27
31
|
|
|
32
|
+
/** The supervisor's own directory under the active DSH home. */
|
|
33
|
+
function supervisorDir(): string {
|
|
34
|
+
return join(process.env.DSH_HOME ?? join(homedir(), '.dsh'), '.supervisor')
|
|
35
|
+
}
|
|
36
|
+
|
|
28
37
|
export function resumeLogPath(): string {
|
|
29
|
-
return join(
|
|
38
|
+
return join(supervisorDir(), 'resume.log.jsonl')
|
|
30
39
|
}
|
|
31
40
|
|
|
32
41
|
export function appendResumeLog(entry: ResumeLogEntry): void {
|
|
33
42
|
try {
|
|
34
|
-
const
|
|
35
|
-
mkdirSync(
|
|
36
|
-
|
|
43
|
+
const dir = supervisorDir()
|
|
44
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
45
|
+
const p = join(dir, 'resume.log.jsonl')
|
|
46
|
+
// The mode goes on the CREATE, not only on the chmod afterwards: a first
|
|
47
|
+
// write would otherwise leave the journal readable by the process umask
|
|
48
|
+
// (0664 measured at umask 002) for as long as the append took. The entry
|
|
49
|
+
// records session ids, so it is never group- or world-readable.
|
|
50
|
+
appendFileSync(p, JSON.stringify(entry) + '\n', { encoding: 'utf8', mode: 0o600 })
|
|
37
51
|
try { chmodSync(p, 0o600) } catch {}
|
|
38
52
|
} catch {}
|
|
39
|
-
}
|
|
53
|
+
}
|
|
54
|
+
|
package/src/host/store/index.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { homedir } from 'node:os'
|
|
2
|
+
import { randomBytes } from 'node:crypto'
|
|
2
3
|
import { dirname, join } from 'node:path'
|
|
3
|
-
import { mkdir, open, readFile, rename, unlink, stat, rm, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { mkdir, open, readFile, rename, unlink, stat, rm, writeFile, link } from 'node:fs/promises'
|
|
4
5
|
import { mkdirSync, readFileSync } from 'node:fs'
|
|
5
6
|
import { watch, type FSWatcher } from 'node:fs'
|
|
6
7
|
|
|
@@ -19,7 +20,29 @@ const EMPTY_DOC: SettingsDoc = { version: 1, domains: {} }
|
|
|
19
20
|
const domainValidators = new Map<string, DomainValidator>()
|
|
20
21
|
const changeCbs = new Set<(domain: string) => void>()
|
|
21
22
|
|
|
22
|
-
|
|
23
|
+
/**
|
|
24
|
+
* Identity of the settings file a cached document was read from. mtime alone is
|
|
25
|
+
* not enough: two copies writing within one filesystem timestamp tick, or an
|
|
26
|
+
* editor that restores the mtime, would leave a stale document in the cache.
|
|
27
|
+
* Every store write is a temp file + rename, so a changed inode is the reliable
|
|
28
|
+
* signal; size catches an in-place edit that kept the mtime.
|
|
29
|
+
*/
|
|
30
|
+
interface FileSig { mtimeMs: number; ino: number; size: number }
|
|
31
|
+
|
|
32
|
+
let cached: { key: string; doc: SettingsDoc; sig: FileSig | null } | null = null
|
|
33
|
+
|
|
34
|
+
async function fileSig(path: string): Promise<FileSig | null> {
|
|
35
|
+
try {
|
|
36
|
+
const st = await stat(path)
|
|
37
|
+
return { mtimeMs: st.mtimeMs, ino: st.ino, size: st.size }
|
|
38
|
+
} catch {
|
|
39
|
+
return null
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function sameSig(a: FileSig | null, b: FileSig | null): boolean {
|
|
44
|
+
return a !== null && b !== null && a.mtimeMs === b.mtimeMs && a.ino === b.ino && a.size === b.size
|
|
45
|
+
}
|
|
23
46
|
|
|
24
47
|
function resolveDshHome(explicit?: string): string {
|
|
25
48
|
return explicit ?? process.env.DSH_HOME ?? join(homedir(), '.dsh')
|
|
@@ -81,6 +104,21 @@ function readSnapshotSync(home: string): Record<string, string> {
|
|
|
81
104
|
}
|
|
82
105
|
}
|
|
83
106
|
|
|
107
|
+
/**
|
|
108
|
+
* Run every listener for one domain. Each callback gets its own try/catch: a
|
|
109
|
+
* throwing listener must neither reject the write that already committed nor
|
|
110
|
+
* hide the change from the listeners registered after it.
|
|
111
|
+
*/
|
|
112
|
+
function fire(domain: string): void {
|
|
113
|
+
for (const cb of [...changeCbs]) {
|
|
114
|
+
try {
|
|
115
|
+
cb(domain)
|
|
116
|
+
} catch (err) {
|
|
117
|
+
console.warn(`config-lib: onChange callback for '${domain}' threw: ${err instanceof Error ? err.message : String(err)}`)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
84
122
|
async function checkExternal(): Promise<void> {
|
|
85
123
|
if (changeCbs.size === 0 || watchedHome === null || checking) return
|
|
86
124
|
checking = true
|
|
@@ -94,7 +132,7 @@ async function checkExternal(): Promise<void> {
|
|
|
94
132
|
if (snapshot[domain] !== next[domain]) changed.push(domain)
|
|
95
133
|
}
|
|
96
134
|
snapshot = next
|
|
97
|
-
for (const domain of changed)
|
|
135
|
+
for (const domain of changed) fire(domain)
|
|
98
136
|
} catch {
|
|
99
137
|
// A transient read failure must never break boot; the next tick retries.
|
|
100
138
|
} finally {
|
|
@@ -131,10 +169,17 @@ function startWatching(): void {
|
|
|
131
169
|
try {
|
|
132
170
|
// fs.watch is not recursive, so it only sees the file when its own
|
|
133
171
|
// directory exists; the store is the only writer of that path either way.
|
|
134
|
-
mkdirSync(dirname(path), { recursive: true })
|
|
135
|
-
|
|
172
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
|
|
173
|
+
const w = watch(dirname(path), { persistent: false }, (_event, filename) => {
|
|
136
174
|
if (filename === null || filename === FILE_BASENAME) scheduleCheck()
|
|
137
175
|
})
|
|
176
|
+
// An unhandled 'error' event (EMFILE, directory removed, ...) would crash
|
|
177
|
+
// the host. Drop the watcher and let the poll below carry on alone.
|
|
178
|
+
w.on('error', () => {
|
|
179
|
+
try { w.close() } catch { /* already closed */ }
|
|
180
|
+
if (watcher === w) watcher = null
|
|
181
|
+
})
|
|
182
|
+
watcher = w
|
|
138
183
|
} catch {
|
|
139
184
|
watcher = null // polling below still covers the change
|
|
140
185
|
}
|
|
@@ -166,22 +211,62 @@ export function resetForTests(): void {
|
|
|
166
211
|
// locking + io
|
|
167
212
|
// ---------------------------------------------------------------------------
|
|
168
213
|
|
|
214
|
+
/**
|
|
215
|
+
* Lock timing. A lock is only stolen once it is older than STALE_MS, which is
|
|
216
|
+
* deliberately longer than the time a waiter is willing to wait: a live writer
|
|
217
|
+
* that is merely slow must time its waiters out, never get robbed.
|
|
218
|
+
*/
|
|
219
|
+
const LOCK_TIMEOUT_MS = 5_000
|
|
220
|
+
const LOCK_STALE_MS = 30_000
|
|
221
|
+
|
|
222
|
+
/** Settings directory: created 0700, lock file 0600 (the settings file is 0600 too). Modes apply at creation only; existing paths are never chmod-ed. */
|
|
223
|
+
const DIR_MODE = 0o700
|
|
224
|
+
const FILE_MODE = 0o600
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Move a stale lock aside and delete it. rename() is atomic, so of several
|
|
228
|
+
* waiters only one moves the file. If the moved file turns out not to be the
|
|
229
|
+
* one we judged stale (a new owner took the path between our stat and the
|
|
230
|
+
* rename), it is put back with link(), which refuses to overwrite.
|
|
231
|
+
*/
|
|
232
|
+
async function stealStaleLock(lockPath: string, observedIno: number): Promise<void> {
|
|
233
|
+
const aside = `${lockPath}.stale-${randomBytes(4).toString('hex')}`
|
|
234
|
+
try {
|
|
235
|
+
await rename(lockPath, aside)
|
|
236
|
+
} catch {
|
|
237
|
+
return // someone else removed or stole it first
|
|
238
|
+
}
|
|
239
|
+
try {
|
|
240
|
+
const moved = await stat(aside)
|
|
241
|
+
if (moved.ino !== observedIno) await link(aside, lockPath).catch(() => {})
|
|
242
|
+
} catch {
|
|
243
|
+
/* nothing to restore */
|
|
244
|
+
} finally {
|
|
245
|
+
await rm(aside, { force: true }).catch(() => {})
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
169
249
|
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
|
|
250
|
+
await mkdir(dirname(path), { recursive: true, mode: DIR_MODE }) // the store dir may not exist on first write
|
|
171
251
|
const lockPath = `${path}.lock`
|
|
172
|
-
const
|
|
173
|
-
|
|
252
|
+
const token = `${process.pid}-${randomBytes(8).toString('hex')}`
|
|
253
|
+
const deadline = Date.now() + LOCK_TIMEOUT_MS
|
|
174
254
|
for (;;) {
|
|
175
255
|
try {
|
|
176
|
-
handle = await open(lockPath, 'wx')
|
|
256
|
+
const handle = await open(lockPath, 'wx', FILE_MODE)
|
|
257
|
+
try {
|
|
258
|
+
await handle.writeFile(token)
|
|
259
|
+
} finally {
|
|
260
|
+
await handle.close()
|
|
261
|
+
}
|
|
177
262
|
break
|
|
178
263
|
} catch (err: any) {
|
|
179
264
|
if (err?.code !== 'EEXIST') throw err
|
|
180
265
|
// Break stale locks left behind by a crashed writer.
|
|
181
266
|
try {
|
|
182
267
|
const st = await stat(lockPath)
|
|
183
|
-
if (Date.now() - st.mtimeMs >
|
|
184
|
-
await
|
|
268
|
+
if (Date.now() - st.mtimeMs > LOCK_STALE_MS) {
|
|
269
|
+
await stealStaleLock(lockPath, st.ino)
|
|
185
270
|
continue
|
|
186
271
|
}
|
|
187
272
|
} catch {
|
|
@@ -194,8 +279,13 @@ async function withLock<T>(path: string, fn: () => Promise<T>): Promise<T> {
|
|
|
194
279
|
try {
|
|
195
280
|
return await fn()
|
|
196
281
|
} finally {
|
|
197
|
-
|
|
198
|
-
|
|
282
|
+
// Only release a lock that is still ours: if it was stolen and re-acquired
|
|
283
|
+
// meanwhile, deleting it would break the new owner's mutual exclusion.
|
|
284
|
+
try {
|
|
285
|
+
if ((await readFile(lockPath, 'utf8')) === token) await unlink(lockPath)
|
|
286
|
+
} catch {
|
|
287
|
+
/* already gone */
|
|
288
|
+
}
|
|
199
289
|
}
|
|
200
290
|
}
|
|
201
291
|
|
|
@@ -233,10 +323,16 @@ function deepMerge(base: unknown, patch: unknown): unknown {
|
|
|
233
323
|
}
|
|
234
324
|
|
|
235
325
|
async function writeDocLocked(path: string, doc: SettingsDoc): Promise<void> {
|
|
236
|
-
await mkdir(dirname(path), { recursive: true })
|
|
326
|
+
await mkdir(dirname(path), { recursive: true, mode: DIR_MODE })
|
|
237
327
|
const tmp = `${path}.tmp-${Math.random().toString(16).slice(2, 10)}`
|
|
238
|
-
|
|
239
|
-
|
|
328
|
+
try {
|
|
329
|
+
await writeFile(tmp, JSON.stringify(doc, null, 2) + '\n', { mode: FILE_MODE })
|
|
330
|
+
await rename(tmp, path) // atomic on the same filesystem; rename carries the 600 mode
|
|
331
|
+
} finally {
|
|
332
|
+
// After a successful rename the temp name is gone and this is a no-op; after
|
|
333
|
+
// a failed write or rename it removes the orphan instead of leaking one per try.
|
|
334
|
+
await rm(tmp, { force: true }).catch(() => {})
|
|
335
|
+
}
|
|
240
336
|
}
|
|
241
337
|
|
|
242
338
|
// ---------------------------------------------------------------------------
|
|
@@ -249,17 +345,12 @@ export async function load(opts?: { dshHome?: string }): Promise<SettingsDoc> {
|
|
|
249
345
|
if (cached && cached.key === homeKey) {
|
|
250
346
|
// One stat per load: out-of-band edits (other processes) must surface
|
|
251
347
|
// without a restart.
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
} catch {
|
|
256
|
-
return cached.doc // stat failed (vanished/locked) — serve stale, never break boot
|
|
257
|
-
}
|
|
348
|
+
const now = await fileSig(path)
|
|
349
|
+
if (now === null) return cached.doc // stat failed (vanished/locked) — serve stale, never break boot
|
|
350
|
+
if (sameSig(now, cached.sig)) return cached.doc
|
|
258
351
|
}
|
|
259
352
|
const doc = await readDoc(path)
|
|
260
|
-
|
|
261
|
-
try { mtimeMs = (await stat(path)).mtimeMs } catch {}
|
|
262
|
-
cached = { key: homeKey, doc, mtimeMs }
|
|
353
|
+
cached = { key: homeKey, doc, sig: await fileSig(path) }
|
|
263
354
|
return doc
|
|
264
355
|
}
|
|
265
356
|
|
|
@@ -287,13 +378,11 @@ export async function set(
|
|
|
287
378
|
doc.domains[domain] = merged
|
|
288
379
|
written = merged
|
|
289
380
|
await writeDocLocked(path, doc)
|
|
290
|
-
|
|
291
|
-
try { mtimeMs = (await stat(path)).mtimeMs } catch {}
|
|
292
|
-
cached = { key, doc, mtimeMs }
|
|
381
|
+
cached = { key, doc, sig: await fileSig(path) }
|
|
293
382
|
})
|
|
294
383
|
// Refresh the watched copy first so the watcher sees no diff for this write.
|
|
295
384
|
if (watchedHome === key) snapshot[domain] = JSON.stringify(written) ?? 'undefined'
|
|
296
|
-
|
|
385
|
+
fire(domain)
|
|
297
386
|
}
|
|
298
387
|
|
|
299
388
|
/**
|
|
@@ -330,14 +419,12 @@ export async function unset(
|
|
|
330
419
|
doc.domains[domain] = next
|
|
331
420
|
written = next
|
|
332
421
|
await writeDocLocked(path, doc)
|
|
333
|
-
|
|
334
|
-
try { mtimeMs = (await stat(path)).mtimeMs } catch {}
|
|
335
|
-
cached = { key: homeKey, doc, mtimeMs }
|
|
422
|
+
cached = { key: homeKey, doc, sig: await fileSig(path) }
|
|
336
423
|
return true
|
|
337
424
|
})
|
|
338
425
|
if (deleted) {
|
|
339
426
|
if (watchedHome === homeKey) snapshot[domain] = JSON.stringify(written) ?? 'undefined'
|
|
340
|
-
|
|
427
|
+
fire(domain)
|
|
341
428
|
}
|
|
342
429
|
return deleted
|
|
343
430
|
}
|
package/src/host/supervisor.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { findInterrupted as defaultFindInterrupted, parseDuration } from './resu
|
|
|
4
4
|
import * as fs from 'node:fs'
|
|
5
5
|
import * as path from 'node:path'
|
|
6
6
|
import * as os from 'node:os'
|
|
7
|
-
import { resolveHarnessRoot } from './paths.js'
|
|
7
|
+
import { resolveHarnessRoot, readSettingsDocSync } from './paths.js'
|
|
8
8
|
import { readSupervisorConfig } from './config.js'
|
|
9
9
|
import { writePlannedRestart as defaultWritePlannedRestart, checkPlannedRestart as defaultCheckPlannedRestart, clearPlannedRestart } from './restart-guards.js'
|
|
10
10
|
import type { RestartRequest } from './restart-guards.js'
|
|
@@ -42,7 +42,7 @@ export interface SupervisorDeps {
|
|
|
42
42
|
bootGraceMs?: number
|
|
43
43
|
getTime?: () => number
|
|
44
44
|
// Checks the dsh-safe-web-update marker (see
|
|
45
|
-
// docs/specs/2026-
|
|
45
|
+
// <workspace-root>/docs/specs/2026-09-13-supervisor-restart-resilience-design.md): a down poll
|
|
46
46
|
// while this resolves true is an intentional restart in progress, not a
|
|
47
47
|
// crash — skip rollback/restartWeb entirely rather than racing it.
|
|
48
48
|
isPlannedRestartActive?: () => boolean | Promise<boolean>
|
|
@@ -206,9 +206,8 @@ export class Supervisor {
|
|
|
206
206
|
if (['0','false','no','off'].includes(v)) return false
|
|
207
207
|
}
|
|
208
208
|
}
|
|
209
|
-
const
|
|
210
|
-
if (
|
|
211
|
-
const j = JSON.parse(fs.readFileSync(maestroPath, 'utf-8'))
|
|
209
|
+
const j = readSettingsDocSync()
|
|
210
|
+
if (j) {
|
|
212
211
|
const raw = j?.domains?.supervisor?.autoResumeEnabled ?? j?.supervisor?.autoResumeEnabled ?? j?.domains?.supervisor?.autoResume ?? j?.supervisor?.autoResume
|
|
213
212
|
if (typeof raw === 'boolean') return raw
|
|
214
213
|
if (typeof raw === 'string') {
|
|
@@ -247,9 +246,8 @@ export class Supervisor {
|
|
|
247
246
|
if (v !== undefined) return v
|
|
248
247
|
} else if (typeof raw === 'number') return raw * 60 * 1000 // number is MINUTES
|
|
249
248
|
}
|
|
250
|
-
const
|
|
251
|
-
if (
|
|
252
|
-
const j = JSON.parse(fs.readFileSync(maestroPath, 'utf-8'))
|
|
249
|
+
const j = readSettingsDocSync()
|
|
250
|
+
if (j) {
|
|
253
251
|
const raw = j?.domains?.supervisor?.autoResumeWithin ?? j?.supervisor?.autoResumeWithin
|
|
254
252
|
if (typeof raw === 'string') {
|
|
255
253
|
if (/^\d+$/.test(raw.trim())) return parseInt(raw.trim(), 10) * 60 * 1000
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
[Unit]
|
|
2
|
+
Description=Keepalive for user manager linger — prevents systemd --user exit on manager session close
|
|
3
|
+
After=default.target
|
|
4
|
+
|
|
5
|
+
[Service]
|
|
6
|
+
Type=simple
|
|
7
|
+
ExecStart=/bin/sleep infinity
|
|
8
|
+
Restart=always
|
|
9
|
+
RestartSec=3
|
|
10
|
+
|
|
11
|
+
[Install]
|
|
12
|
+
WantedBy=default.target
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
[Unit]
|
|
2
|
+
Description=DSH Web Supervisor — auto-rollback for dsh web crashes
|
|
3
|
+
After=network.target dsh-web.service
|
|
4
|
+
Wants=dsh-web.service
|
|
5
|
+
|
|
6
|
+
[Service]
|
|
7
|
+
Type=simple
|
|
8
|
+
# Portable: sources nvm directly (bash -lc alone fails — ~/.bashrc guard),
|
|
9
|
+
# then execs node (works for nvm, fnm, volta, system via PATH fallback)
|
|
10
|
+
ExecStart=/bin/bash -c 'export NVM_DIR="$HOME/.nvm"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"; exec node %MAESTRO_ROOT%/packages/dsh-maestro-core/lib/bin.js daemon'
|
|
11
|
+
Restart=always
|
|
12
|
+
RestartSec=2
|
|
13
|
+
Environment=DSH_HOME=%h/.dsh
|
|
14
|
+
# Optional Telegram — loose mode: set these if you want Telegram alerts, otherwise daemon logs only
|
|
15
|
+
# Environment=TELEGRAM_BOT_TOKEN=your_bot_token
|
|
16
|
+
# Environment=TELEGRAM_CHAT_ID=your_chat_id
|
|
17
|
+
# For hard dependency (workspace:^), ensure notifier is installed: pnpm add @ddtcorex/dsh-maestro-notifier
|
|
18
|
+
|
|
19
|
+
[Install]
|
|
20
|
+
WantedBy=default.target
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
[Unit]
|
|
2
|
+
Description=DSH Web — main harness web UI + webhook (:3080/:3000)
|
|
3
|
+
After=network.target
|
|
4
|
+
Wants=network.target
|
|
5
|
+
# Cap boot crash loops: if the unit fails to start more than 3 times within 60s,
|
|
6
|
+
# systemd stops retrying until the interval elapses (avoids a tight restart storm).
|
|
7
|
+
StartLimitIntervalSec=60
|
|
8
|
+
StartLimitBurst=3
|
|
9
|
+
|
|
10
|
+
[Service]
|
|
11
|
+
Type=simple
|
|
12
|
+
WorkingDirectory=%MAESTRO_ROOT%/deepseek-harness
|
|
13
|
+
# Portable: sources nvm directly (bash -lc alone fails — ~/.bashrc exits early for
|
|
14
|
+
# non-interactive shells via `case $- in *i*) ;; *) return;; esac`, so nvm never loads).
|
|
15
|
+
# Falls back to system node for machines without nvm — no hardcoded /v24.19.0 version.
|
|
16
|
+
ExecStart=/bin/bash -c 'export NVM_DIR="$HOME/.nvm"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"; exec node --import tsx/esm apps/cli/src/bin.ts web --no-open'
|
|
17
|
+
Restart=always
|
|
18
|
+
RestartSec=5
|
|
19
|
+
# Wait (up to 30 x 5s) for the previous instance to release the raw webserver
|
|
20
|
+
# port before starting, so a restart never races its predecessor into EADDRINUSE.
|
|
21
|
+
# Fails the start (exit 1) if the port is still held after the wait.
|
|
22
|
+
ExecStartPre=/bin/bash -c "for i in {1..30}; do ss -tln 2>/dev/null | grep -q 127.0.0.1:3082 || exit 0; sleep 5; done; exit 1"
|
|
23
|
+
Environment=DSH_HOME=%h/.dsh
|
|
24
|
+
Environment=NODE_ENV=production
|
|
25
|
+
# Log to file for supervisor health tail (append keeps history across restarts)
|
|
26
|
+
StandardOutput=append:%h/.dsh/dsh-web.log
|
|
27
|
+
StandardError=append:%h/.dsh/dsh-web.log
|
|
28
|
+
|
|
29
|
+
[Install]
|
|
30
|
+
WantedBy=default.target
|