@ddtcorex/dsh-maestro-core 0.10.0 → 0.11.1

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.
Files changed (48) hide show
  1. package/README.md +31 -12
  2. package/lib/cli.js +0 -2
  3. package/lib/client.js +69 -93
  4. package/lib/config/index.d.ts +11 -4
  5. package/lib/config/index.js +26 -9
  6. package/lib/config/service.d.ts +2 -2
  7. package/lib/config/service.js +2 -2
  8. package/lib/debug-agent.js +1 -1
  9. package/lib/paths.d.ts +8 -0
  10. package/lib/paths.js +22 -0
  11. package/lib/plugin.d.ts +21 -1
  12. package/lib/plugin.js +153 -42
  13. package/lib/restart-guards.js +1 -1
  14. package/lib/restart-tool.js +13 -4
  15. package/lib/resume-log.d.ts +4 -0
  16. package/lib/resume-log.js +13 -4
  17. package/lib/snapshot.d.ts +3 -2
  18. package/lib/snapshot.js +3 -2
  19. package/lib/store/index.js +119 -45
  20. package/lib/supervisor.js +5 -7
  21. package/lib/types/client/config/MaestroSettings.d.ts.map +1 -1
  22. package/package.json +4 -2
  23. package/scripts/build-client.mjs +53 -0
  24. package/scripts/install-systemd.sh +55 -0
  25. package/scripts/sync/bench-preview.mjs +43 -0
  26. package/scripts/sync/cdp-sync-probe.mjs +200 -0
  27. package/scripts/sync/cdp-sync-verify.mjs +169 -0
  28. package/scripts/vendor-store.mjs +104 -0
  29. package/skills/dsh-safe-restart/SKILL.md +2 -2
  30. package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +2 -2
  31. package/src/client/config/MaestroSettings.tsx +8 -139
  32. package/src/client/sync/SyncPanel.tsx +1 -1
  33. package/src/client/sync/index.tsx +4 -4
  34. package/src/host/cli.ts +0 -2
  35. package/src/host/config/index.ts +27 -10
  36. package/src/host/config/service.ts +2 -2
  37. package/src/host/debug-agent.ts +1 -1
  38. package/src/host/paths.ts +21 -0
  39. package/src/host/plugin.ts +140 -30
  40. package/src/host/restart-guards.ts +1 -1
  41. package/src/host/restart-tool.ts +12 -4
  42. package/src/host/resume-log.ts +20 -5
  43. package/src/host/snapshot.ts +3 -2
  44. package/src/host/store/index.ts +120 -33
  45. package/src/host/supervisor.ts +6 -8
  46. package/systemd/dsh-web-keepalive.service.template +12 -0
  47. package/systemd/dsh-web-supervisor.service.template +20 -0
  48. package/systemd/dsh-web.service.template +30 -0
package/src/host/paths.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import * as fs from 'node:fs'
2
2
  import * as path from 'node:path'
3
+ import * as os from 'node:os'
3
4
 
4
5
  /**
5
6
  * Resolve Maestro Harness root without hardcoding a machine-specific home path.
@@ -68,3 +69,23 @@ export function resolveSupervisorPackageDir(): string {
68
69
  // production, `src/host/` from vitest. Only used when the walk above fails.
69
70
  return path.resolve(here, '..')
70
71
  }
72
+
73
+ /**
74
+ * Read the shared settings document synchronously from the canonical store
75
+ * path, `<dsh home>/dsh-maestro-config/settings.json` (`DSH_HOME` wins over
76
+ * `~/.dsh`, matching the store). The retired `<dsh home>/maestro/settings.json`
77
+ * is consulted only when the canonical file does not exist. Returns `undefined`
78
+ * when neither file is present or the chosen one is unreadable.
79
+ */
80
+ export function readSettingsDocSync(): any {
81
+ const home = process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh')
82
+ const canonical = path.join(home, 'dsh-maestro-config', 'settings.json')
83
+ const legacy = path.join(home, 'maestro', 'settings.json')
84
+ const chosen = fs.existsSync(canonical) ? canonical : fs.existsSync(legacy) ? legacy : undefined
85
+ if (!chosen) return undefined
86
+ try {
87
+ return JSON.parse(fs.readFileSync(chosen, 'utf-8'))
88
+ } catch {
89
+ return undefined
90
+ }
91
+ }
@@ -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
- export const inject = ['sessions', 'agents', 'connection', 'tools', 'skills'] as const
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
- const { scanned, interrupted } = await doFind(undefined, { withinMs })
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, { withinMs })).interrupted
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({ ts: Date.now(), kind: 'scan', scanned, interrupted: merged, detail: `withinMs=${withinMs}` })
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
- if (typeof ctx.tools?.register === 'function') {
937
- disposers.push(ctx.tools.register(makeSessionHealthToolDef(config)))
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 {}
@@ -1003,6 +1076,41 @@ function ensureSystemdKeepalive(ctx: any): void {
1003
1076
  } catch {}
1004
1077
  }
1005
1078
 
1079
+ /**
1080
+ * Run `body` once every service in `names` is active, without holding up this row.
1081
+ *
1082
+ * `inject` is empty on purpose (see its declaration), so the row activates as soon
1083
+ * as its entry loads — before the `tools` and `skills` fibers are active.
1084
+ * `ctx.get` is strict: ReflectService resolves a service only while the fiber
1085
+ * providing it is active, so reading those services during `apply()` returned
1086
+ * undefined and every tool and skill registration was dropped — silently, because
1087
+ * each registration guards on the lookup answering. A child fiber carries its own
1088
+ * inject list and activates on those services independently, which keeps them off
1089
+ * the boot resume scan's dependency path. A host without the registry mixin has no
1090
+ * child-fiber primitive and registers immediately, which is correct when the
1091
+ * services are already active.
1092
+ *
1093
+ * @param ctx — the row's context.
1094
+ * @param names — service names the body needs; each is a separate child fiber's
1095
+ * dependency list, so one absent service cannot suppress the others.
1096
+ * @param body — registration callback, receiving the scoped child context.
1097
+ */
1098
+ function whenServicesActive(ctx: any, names: string[], body: (scoped: any) => void): void {
1099
+ try {
1100
+ if (typeof ctx.inject === 'function') {
1101
+ ctx.inject(names, body)
1102
+ return
1103
+ }
1104
+ } catch (e: any) {
1105
+ try { ctx.logger?.warn?.(`[supervisor] ${names.join('/')} fiber failed: ${e?.message ?? String(e)}`) } catch {}
1106
+ }
1107
+ try {
1108
+ body(ctx)
1109
+ } catch (e: any) {
1110
+ try { ctx.logger?.warn?.(`[supervisor] ${names.join('/')} registration failed: ${e?.message ?? String(e)}`) } catch {}
1111
+ }
1112
+ }
1113
+
1006
1114
  export function apply(ctx: any, config: SupervisorPluginConfig = {}): void {
1007
1115
  // The whole body is wrapped: per AGENTS.md, apply() must never throw
1008
1116
  // synchronously or let a rejected promise escape, no matter what fails
@@ -1010,26 +1118,34 @@ export function apply(ctx: any, config: SupervisorPluginConfig = {}): void {
1010
1118
  // error-reporting logger call itself throwing).
1011
1119
  try {
1012
1120
  try { ensureSystemdKeepalive(ctx) } catch {}
1013
- try {
1014
- const skills: any = ctx.get?.('skills')
1015
- if (skills?.registerProvider) {
1016
- ctx.effect(() => {
1017
- let unregister: (() => void) | undefined
1018
- try {
1019
- // Package-root skills/ is resolved at runtime by walking to the
1020
- // nearest package.json (robust to lib/ vs src/host/ layouts).
1021
- unregister = skills.registerProvider(() => makeSkillProvider(resolveSkillsDir(__dirname)))
1022
- } catch (e: any) { ctx.logger?.warn?.(`[supervisor] skill provider failed: ${e?.message ?? String(e)}`) }
1023
- return () => { try { unregister?.() } catch {} }
1024
- }, 'supervisor:skill')
1121
+
1122
+ whenServicesActive(ctx, ['skills'], (scoped) => {
1123
+ const skills: any = scoped.get?.('skills') ?? scoped.skills
1124
+ if (!skills?.registerProvider) return
1125
+ scoped.effect(() => {
1126
+ let unregister: (() => void) | undefined
1127
+ try {
1128
+ // Package-root skills/ is resolved at runtime by walking to the
1129
+ // nearest package.json (robust to lib/ vs src/host/ layouts).
1130
+ unregister = skills.registerProvider(() => makeSkillProvider(resolveSkillsDir(__dirname)))
1131
+ } catch (e: any) { scoped.logger?.warn?.(`[supervisor] skill provider failed: ${e?.message ?? String(e)}`) }
1132
+ return () => { try { unregister?.() } catch {} }
1133
+ }, 'supervisor:skill')
1134
+ })
1135
+
1136
+ whenServicesActive(ctx, ['tools'], (scoped) => {
1137
+ try {
1138
+ scoped.effect(() => registerRestartTool(scoped), 'supervisor:restart-tool')
1139
+ } catch (e: any) {
1140
+ try { scoped.logger?.warn?.(`[supervisor] restart tool effect failed: ${e?.message ?? String(e)}`) } catch {}
1025
1141
  }
1026
- } catch {}
1027
1142
 
1028
- try {
1029
- ctx.effect(() => registerRestartTool(ctx), 'supervisor:restart-tool')
1030
- } catch (e: any) {
1031
- try { ctx.logger?.warn?.(`[supervisor] restart tool effect failed: ${e?.message ?? String(e)}`) } catch {}
1032
- }
1143
+ try {
1144
+ scoped.effect(() => registerResumeToolHealthService(scoped), 'supervisor:resume-tool-health')
1145
+ } catch (e: any) {
1146
+ try { scoped.logger?.warn?.(`[supervisor] resume-tool-health effect failed: ${e?.message ?? String(e)}`) } catch {}
1147
+ }
1148
+ })
1033
1149
 
1034
1150
  try {
1035
1151
  ctx.effect(() => registerSessionHealthService(ctx, config), 'supervisor:session-health')
@@ -1037,12 +1153,6 @@ export function apply(ctx: any, config: SupervisorPluginConfig = {}): void {
1037
1153
  try { ctx.logger?.warn?.(`[supervisor] session-health effect failed: ${e?.message ?? String(e)}`) } catch {}
1038
1154
  }
1039
1155
 
1040
- try {
1041
- ctx.effect(() => registerResumeToolHealthService(ctx), 'supervisor:resume-tool-health')
1042
- } catch (e: any) {
1043
- try { ctx.logger?.warn?.(`[supervisor] resume-tool-health effect failed: ${e?.message ?? String(e)}`) } catch {}
1044
- }
1045
-
1046
1156
  ctx.effect(() => {
1047
1157
  let disposed = false
1048
1158
  let timer: ReturnType<typeof setTimeout> | null = null
@@ -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-08-28-supervisor-planned-restart-design.md):
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
@@ -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
- dispose = ctx.tools.register({
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 = ctx.tools.register({
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 = ctx.tools.register({
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 = ctx.tools.register({
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: {
@@ -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(homedir(), '.dsh', '.supervisor', 'resume.log.jsonl')
38
+ return join(supervisorDir(), 'resume.log.jsonl')
30
39
  }
31
40
 
32
41
  export function appendResumeLog(entry: ResumeLogEntry): void {
33
42
  try {
34
- const p = resumeLogPath()
35
- mkdirSync(join(homedir(), '.dsh', '.supervisor'), { recursive: true })
36
- appendFileSync(p, JSON.stringify(entry) + '\n', 'utf8')
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
+
@@ -23,7 +23,8 @@ export interface SnapshotDeps {
23
23
  }
24
24
 
25
25
  /**
26
- * DSH-home entries the last-known-good snapshot deliberately never copies.
26
+ * Entries under the harness home directory that the last-known-good snapshot
27
+ * deliberately never copies.
27
28
  *
28
29
  * The LKG exists to recover a boot that fails while loading the plugin tree, so
29
30
  * it holds boot **configuration**: `profiles/` (the plugin tree with its
@@ -53,7 +54,7 @@ export const LKG_EXCLUDED_ENTRIES: readonly string[] = [
53
54
  ]
54
55
 
55
56
  /**
56
- * True when a DSH-home-relative path must never enter (or leave) the LKG.
57
+ * True when a path relative to the harness home must never enter (or leave) the LKG.
57
58
  *
58
59
  * The named entries match the first path segment; `*.log` matches by basename
59
60
  * anywhere, because append-only logs are data at any depth and a restored stale
@@ -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
- let cached: { key: string; doc: SettingsDoc; mtimeMs: number } | null = null
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) for (const cb of [...changeCbs]) cb(domain)
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
- watcher = watch(dirname(path), { persistent: false }, (_event, filename) => {
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 deadline = Date.now() + 5_000
173
- let handle: Awaited<ReturnType<typeof open>> | null = null
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 > 5_000) {
184
- await rm(lockPath, { force: true })
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
- await unlink(lockPath).catch(() => {})
198
- void handle // closed fd via unlink; keep handle referenced for GC clarity
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
- await writeFile(tmp, JSON.stringify(doc, null, 2) + '\n', { mode: 0o600 })
239
- await rename(tmp, path) // atomic on the same filesystem; rename carries the 600 mode
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
- try {
253
- const st = await stat(path)
254
- if (st.mtimeMs === cached.mtimeMs) return cached.doc
255
- } catch {
256
- return cached.doc // stat failed (vanished/locked) — serve stale, never break boot
257
- }
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
- let mtimeMs = 0
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
- let mtimeMs = 0
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
- for (const cb of [...changeCbs]) cb(domain)
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
- let mtimeMs = 0
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
- for (const cb of [...changeCbs]) cb(domain)
427
+ fire(domain)
341
428
  }
342
429
  return deleted
343
430
  }