@ddtcorex/dsh-maestro-core 0.12.1 → 0.14.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.
Files changed (45) hide show
  1. package/README.md +5 -5
  2. package/lib/boot-lock.d.ts +1 -1
  3. package/lib/boot-lock.js +1 -1
  4. package/lib/cli.d.ts +0 -30
  5. package/lib/cli.js +2 -202
  6. package/lib/daemon-freshness.d.ts +4 -4
  7. package/lib/daemon-freshness.js +4 -4
  8. package/lib/debug-agent.d.ts +7 -0
  9. package/lib/debug-agent.js +13 -4
  10. package/lib/dsh-launch.d.ts +26 -0
  11. package/lib/dsh-launch.js +27 -0
  12. package/lib/health-poller.js +3 -3
  13. package/lib/notifier.js +1 -1
  14. package/lib/report.js +0 -2
  15. package/lib/restart-exec.d.ts +1 -1
  16. package/lib/restart-exec.js +1 -1
  17. package/lib/restart-guards.d.ts +0 -1
  18. package/lib/restart-guards.js +1 -11
  19. package/lib/restart-tool.d.ts +10 -26
  20. package/lib/restart-tool.js +19 -89
  21. package/lib/restart-web.d.ts +4 -1
  22. package/lib/restart-web.js +8 -4
  23. package/lib/supervisor.d.ts +2 -27
  24. package/lib/supervisor.js +32 -71
  25. package/package.json +1 -1
  26. package/skills/dsh-safe-restart/SKILL.md +8 -7
  27. package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +20 -36
  28. package/src/host/boot-lock.ts +1 -1
  29. package/src/host/cli.ts +2 -172
  30. package/src/host/daemon-freshness.ts +4 -4
  31. package/src/host/debug-agent.ts +15 -7
  32. package/src/host/dsh-launch.ts +48 -0
  33. package/src/host/health-poller.ts +3 -3
  34. package/src/host/notifier.ts +1 -1
  35. package/src/host/report.ts +0 -2
  36. package/src/host/restart-exec.ts +1 -1
  37. package/src/host/restart-guards.ts +1 -12
  38. package/src/host/restart-tool.ts +20 -79
  39. package/src/host/restart-web.ts +9 -7
  40. package/src/host/supervisor.ts +38 -84
  41. package/systemd/dsh-web-supervisor.service.template +2 -0
  42. package/systemd/dsh-web.service.template +8 -2
  43. package/lib/snapshot.d.ts +0 -60
  44. package/lib/snapshot.js +0 -359
  45. package/src/host/snapshot.ts +0 -338
@@ -6,7 +6,7 @@ import * as os from 'node:os'
6
6
  * One-boot-at-a-time guard (spec D4, incident 2026-09-13). Every path that
7
7
  * starts dsh web takes this lock from the moment the restart is issued until
8
8
  * the port answers, so a racing tick, the dsh_web_restart hand-off, or a
9
- * rollback that fires while the first boot is still coming up skips instead of
9
+ * restart that fires while the first boot is still coming up skips instead of
10
10
  * producing the second systemd start that made the incident's log tail toxic.
11
11
  *
12
12
  * The lock is an atomically created file (`O_EXCL`) carrying `{pid, ts}`. An
package/src/host/cli.ts CHANGED
@@ -1,139 +1,11 @@
1
1
  import { Supervisor } from './supervisor.js'
2
2
  import { pollHealth } from './health-poller.js'
3
- import { writeLKG, verifyLKG, isLkgExcluded, failureReason } from './snapshot.js'
4
- import * as fs from 'node:fs'
5
3
  import * as path from 'node:path'
6
4
  import * as os from 'node:os'
7
5
  import { resolveHarnessRoot } from './paths.js'
8
- import { isSelfCopyError, checkPlannedRestart, readRestartRequest, clearPlannedRestart } from './restart-guards.js'
6
+ import { checkPlannedRestart, readRestartRequest, clearPlannedRestart } from './restart-guards.js'
9
7
  import { readSupervisorConfig } from './config.js'
10
8
 
11
- export interface RestoreResult {
12
- /** Snapshot id that was restored. */
13
- target: string
14
- /** Files (and symlinks) restored into the live DSH home. */
15
- restored: number
16
- /** Entries that were not restored, each with a reason. Never silent. */
17
- skipped: Array<{ path: string; reason: string }>
18
- }
19
-
20
- /**
21
- * Make a destination (recursively) writable before overwriting it (D3).
22
- *
23
- * `fs.cpSync` copies into an existing destination file with
24
- * `O_WRONLY|O_CREAT|O_TRUNC`, so a mode-`0400` object fails with EACCES and
25
- * aborts the whole restore — the exact 2026-09-13 failure
26
- * (`EACCES, Permission denied '.../attachments/v1/objects/f8'`). Only entries
27
- * that actually lack the needed bit are chmod-ed, so a healthy tree costs
28
- * stats, not a chmod per file.
29
- */
30
- function makeWritable(target: string): void {
31
- let st: fs.Stats
32
- try {
33
- st = fs.lstatSync(target)
34
- } catch {
35
- return
36
- }
37
- if (st.isSymbolicLink()) return
38
- if (st.isDirectory()) {
39
- if ((st.mode & 0o300) !== 0o300) {
40
- try { fs.chmodSync(target, st.mode | 0o300) } catch {}
41
- }
42
- let names: string[] = []
43
- try { names = fs.readdirSync(target) } catch { return }
44
- for (const name of names) makeWritable(path.join(target, name))
45
- return
46
- }
47
- if ((st.mode & 0o200) === 0) {
48
- try { fs.chmodSync(target, st.mode | 0o200) } catch {}
49
- }
50
- }
51
-
52
- /** Files (and symlinks) a restore of this source entry would write. */
53
- function countRestorable(srcPath: string): number {
54
- try {
55
- const st = fs.lstatSync(srcPath)
56
- if (st.isDirectory()) return walkFiles(srcPath).length
57
- return 1
58
- } catch {
59
- return 0
60
- }
61
- }
62
-
63
- function walkFiles(dir: string, base: string = dir): string[] {
64
- const out: string[] = []
65
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
66
- const full = path.join(dir, entry.name)
67
- if (entry.isDirectory()) out.push(...walkFiles(full, base))
68
- else if (entry.isFile()) out.push(path.relative(base, full))
69
- }
70
- return out
71
- }
72
-
73
- /**
74
- * Copy a chosen LKG snapshot back into the DSH home. Recent snapshots are
75
- * tried newest-first, skipping any that still carry a failing plugin so a
76
- * broken bundle is not restored. `sessions/` and every other runtime-data entry
77
- * is deliberately NOT restored (D1) — session logs are append-only truth and
78
- * rolling them back to a snapshot would drop every turn recorded after that
79
- * snapshot.
80
- *
81
- * Never throws for a per-entry failure: the failures are collected into
82
- * `skipped` and the caller reports them (D2/D4). The only throw left is "there
83
- * is no snapshot at all", which the caller must know about.
84
- *
85
- * @returns the restore summary (snapshot id + what was/was not restored).
86
- */
87
- export async function rollbackLKG(opts: { dshHome: string; lkgRoot: string; failingPlugin?: string }): Promise<RestoreResult> {
88
- const { dshHome, lkgRoot, failingPlugin } = opts
89
- const entries = fs.existsSync(lkgRoot) ? fs.readdirSync(lkgRoot).sort() : []
90
- if (!entries.length) throw new Error('no LKG to rollback to')
91
- const candidates = [...entries].reverse().slice(0, 3)
92
- let chosen: string | undefined
93
- for (const cand of candidates) {
94
- if (!failingPlugin) { chosen = cand; break }
95
- try {
96
- const pkgPath = path.join(lkgRoot, cand, 'profiles/web/package.json')
97
- if (!fs.existsSync(pkgPath)) { chosen = cand; break }
98
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
99
- const bundles: string[] = pkg?.dsh?.profile?.bundles ?? []
100
- const deps = pkg?.dependencies ?? {}
101
- const hasFailing = bundles.some((b: string) => b.includes(failingPlugin)) || Object.keys(deps).some(k => k.includes(failingPlugin))
102
- if (!hasFailing) { chosen = cand; break }
103
- console.log(`[supervisor] skipping LKG ${cand} still contains failing plugin ${failingPlugin}`)
104
- } catch { chosen = cand; break }
105
- }
106
- const target = chosen ?? entries[entries.length - 1]
107
- const src = path.join(lkgRoot, target)
108
- const skipped: RestoreResult['skipped'] = []
109
- let restored = 0
110
- for (const entry of fs.readdirSync(src)) {
111
- if (entry === 'manifest.json') continue
112
- if (isLkgExcluded(entry)) {
113
- // Legacy snapshots (taken before D1) still carry runtime data. Restoring
114
- // a stale sessions/ over live sessions can lose a log, and a 0400
115
- // attachment blob is what aborted this very path — report, never restore.
116
- skipped.push({ path: entry, reason: 'runtime data excluded from the LKG scope (not required to boot)' })
117
- continue
118
- }
119
- const srcPath = path.join(src, entry)
120
- const destPath = path.join(dshHome, entry)
121
- try {
122
- // Skip if src and dest are the same file (e.g. symlink to same target like ~/.dsh/AGENTS.md)
123
- try {
124
- if (fs.existsSync(srcPath) && fs.existsSync(destPath) && fs.realpathSync(srcPath) === fs.realpathSync(destPath)) continue
125
- } catch {}
126
- makeWritable(destPath)
127
- fs.cpSync(srcPath, destPath, { recursive: true, force: true })
128
- restored += countRestorable(srcPath)
129
- } catch (e: any) {
130
- if (isSelfCopyError(String(e?.message ?? ''))) continue
131
- skipped.push({ path: entry, reason: failureReason(e) })
132
- }
133
- }
134
- return { target, restored, skipped }
135
- }
136
-
137
9
  export async function runCli(args: string[]): Promise<void> {
138
10
  const cmd = args[2] ?? '--help'
139
11
  if (cmd === '--help' || cmd === '-h' || cmd === 'help') {
@@ -141,7 +13,7 @@ export async function runCli(args: string[]): Promise<void> {
141
13
 
142
14
  Commands:
143
15
  daemon Run supervisor daemon (poll every 3s)
144
- status Show health + LKG status
16
+ status Show health
145
17
  resume [--within <dur>] List interrupted sessions (filter by time, e.g. 5m, 30s, 1h)
146
18
  boot-guard acquire|release --pid <pid> Take/release boot.lock + boot-boundary (used by the safe-restart script)
147
19
  `)
@@ -154,17 +26,6 @@ Commands:
154
26
  if (cmd === 'status') {
155
27
  const health = await pollHealth()
156
28
  console.log(`up: ${health.up}, httpCode: ${health.httpCode}, error: ${health.error ?? 'none'}`)
157
- const lkgRoot = path.join(os.homedir(), '.dsh/.supervisor/lkg')
158
- if (fs.existsSync(lkgRoot)) {
159
- const entries = fs.readdirSync(lkgRoot).sort()
160
- console.log(`LKG: ${entries.length} snapshots, latest: ${entries[entries.length - 1] ?? 'none'}`)
161
- if (entries.length) {
162
- const ok = await verifyLKG(path.join(lkgRoot, entries[entries.length - 1])).catch(() => false)
163
- console.log(`latest LKG valid: ${ok}`)
164
- }
165
- } else {
166
- console.log('LKG: none')
167
- }
168
29
  return
169
30
  }
170
31
  if (cmd === 'resume') {
@@ -191,14 +52,9 @@ Commands:
191
52
  }
192
53
  if (cmd === 'daemon') {
193
54
  console.log('[supervisor] starting daemon — poll every 3s, Ctrl+C to stop')
194
- const dshHome = path.join(os.homedir(), '.dsh')
195
- const lkgRoot = path.join(os.homedir(), '.dsh/.supervisor/lkg')
196
- const failedRoot = path.join(os.homedir(), '.dsh/.supervisor/failed')
197
55
  const reportsRoot = path.join(os.homedir(), '.dsh/.supervisor/reports')
198
56
  const supervisor = new Supervisor({
199
57
  pollHealth: () => pollHealth(),
200
- writeLKG: () => writeLKG(dshHome, lkgRoot),
201
- writeFailed: () => writeLKG(dshHome, failedRoot),
202
58
  writeReport: async ({ ts, health, action, logTail, gitDiff }: any) => {
203
59
  const { writeReport, collectGitDiff } = await import('./report.js')
204
60
  const { collectLogTail } = await import('./health-poller.js')
@@ -221,32 +77,6 @@ Commands:
221
77
  }
222
78
  return writeReport({ reportsRoot, ts, health, gitDiff: diff, logTail: tail, action })
223
79
  },
224
- rollback: async () => {
225
- const { execSync } = await import('node:child_process')
226
- // Extract failing plugin from current log tail if possible
227
- let failingPlugin: string | undefined
228
- try {
229
- const tail = fs.readFileSync(path.join(os.homedir(), '.dsh/dsh-web.log'), 'utf8').slice(-5000)
230
- const m = tail.match(/@ddtcorex\/dsh-maestro-[a-z0-9_-]+/i) ?? tail.match(/dsh-maestro-[a-z0-9_-]+/i)
231
- if (m) failingPlugin = m[0].replace(/^@ddtcorex\//, '')
232
- } catch {}
233
- const res = await rollbackLKG({ dshHome, lkgRoot, failingPlugin })
234
- console.log(`[supervisor] rolled back to ${res.target} — ${res.restored} file(s) restored${failingPlugin ? ` (avoiding ${failingPlugin})` : ''}`)
235
- // D4: a partial restore is surfaced loudly, never silently.
236
- if (res.skipped.length) {
237
- console.log(`[supervisor] ROLLBACK PARTIAL: ${res.skipped.length} entr(ies) not restored`)
238
- for (const s of res.skipped.slice(0, 10)) console.log(`[supervisor] skipped ${s.path}: ${s.reason}`)
239
- if (res.skipped.length > 10) console.log(`[supervisor] … ${res.skipped.length - 10} more`)
240
- }
241
- // Reconcile node_modules from restored package.json (critical for link: deps)
242
- try {
243
- execSync('pnpm --dir ~/.dsh/profiles/web install --silent', { timeout: 30000, stdio: 'pipe' })
244
- console.log('[supervisor] pnpm install reconciled profiles/web')
245
- } catch (e: any) {
246
- console.log(`[supervisor] pnpm install failed: ${e?.message ?? String(e)}`)
247
- }
248
- return res
249
- },
250
80
  restartWeb: async () => {
251
81
  // One implementation of the single-boot restart: marker (TTL = boot
252
82
  // budget) → boot.lock → serialized systemd start → direct-node nohup
@@ -3,10 +3,10 @@
3
3
  *
4
4
  * `dsh web` is not the only process that caches this package's `lib/*.js` in
5
5
  * RAM: the standalone `dsh-web-supervisor` daemon does too, and it is the
6
- * process that decides whether a fresh boot is healthy or must be rolled back.
7
- * A daemon started BEFORE the newest build keeps applying the OLD rollback
8
- * rules — on 2026-09-13 exactly that judged a slow boot as down and rolled
9
- * `dsh web` back in a loop while the port answered in 1.4ms.
6
+ * process that decides whether a fresh boot is healthy or must be restarted.
7
+ * A daemon started BEFORE the newest build keeps applying the OLD restart
8
+ * rules — on 2026-09-13 exactly that judged a slow boot as down and restarted
9
+ * `dsh web` in a loop while the port answered in 1.4ms.
10
10
  *
11
11
  * The bash helper (`skills/dsh-safe-restart/scripts/restart-dsh-web.sh`,
12
12
  * `supervisor_daemon_state`) owns the same judgement for out-of-session
@@ -1,3 +1,5 @@
1
+ import { resolveDshLaunch, type DshLaunchDeps } from './dsh-launch.js'
2
+
1
3
  export interface DebugAgentOpts {
2
4
  reportPath: string
3
5
  health: { error?: string; httpCode?: number }
@@ -109,20 +111,26 @@ function defaultWriteFile(p: string, c: string): void {
109
111
  writeFileSync(p, c, 'utf-8')
110
112
  }
111
113
 
114
+ /**
115
+ * The bounded dry-boot probe: boot `dsh web` on `tmp` as DSH_HOME and an
116
+ * ephemeral port, poll for 200, print ok/fail. The boot follows
117
+ * `resolveDshLaunch`, so a packaged host verifies the runtime it runs.
118
+ */
119
+ export function buildDryBootCommand(tmp: string, port: number, deps: DshLaunchDeps = {}): string {
120
+ const launch = resolveDshLaunch(['web', '--port', String(port), '--no-open'], deps)
121
+ const argv = [launch.command, ...launch.args].map(a => JSON.stringify(a)).join(' ')
122
+ const boot = `${launch.cwd ? `cd ${JSON.stringify(launch.cwd)} && ` : ''}DSH_HOME=${tmp} ${argv} >${tmp}/dsh.log 2>&1 &`
123
+ return `timeout 8 bash -c '${boot} pid=$!; for i in $(seq 1 5); do sleep 1; if curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:${port}/ 2>&1 | grep -q 200; then echo ok; exit 0; fi; done; echo fail; exit 1'`
124
+ }
125
+
112
126
  async function defaultDryBoot(): Promise<boolean> {
113
127
  const { execSync } = await import('node:child_process')
114
- const { resolveDeepseekHarnessDir } = await import('./paths.js')
115
128
  const { buildKillStalePortsCommand } = await import('./restart-guards.js')
116
129
  const port = Math.floor(19000 + Math.random() * 1000)
117
130
  let tmp = ''
118
131
  try {
119
- const deepseekDir = resolveDeepseekHarnessDir()
120
132
  tmp = execSync('mktemp -d', { encoding: 'utf-8' }).trim()
121
- // Use spawn-based dry-boot to avoid nested quoting hell (prev \\$! / \\$(seq) caused syntax error)
122
- const out = execSync(
123
- `timeout 8 bash -c 'DSH_HOME=${tmp} pnpm --dir ${deepseekDir} dsh web --port ${port} --no-open >${tmp}/dsh.log 2>&1 & pid=$!; for i in $(seq 1 5); do sleep 1; if curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:${port}/ 2>&1 | grep -q 200; then echo ok; exit 0; fi; done; echo fail; exit 1'`,
124
- { encoding: 'utf-8', timeout: 12000 },
125
- )
133
+ const out = execSync(buildDryBootCommand(tmp, port), { encoding: 'utf-8', timeout: 12000 })
126
134
  return out.includes('ok')
127
135
  } catch {
128
136
  return false
@@ -0,0 +1,48 @@
1
+ import { resolveDeepseekHarnessDir } from './paths.js'
2
+
3
+ /**
4
+ * How to start the `dsh` CLI on this host. `DSH_BIN` (the installed package's
5
+ * bin, e.g. `~/.local/share/dsh/current/bin/dsh`) is the single switch: set,
6
+ * the packaged runtime runs through the current node; unset, the source
7
+ * checkout runs through tsx, which is how hosts without a packaged install
8
+ * have always booted.
9
+ */
10
+ export interface DshLaunch {
11
+ command: string
12
+ args: string[]
13
+ cwd?: string
14
+ }
15
+
16
+ export interface DshLaunchDeps {
17
+ env?: Record<string, string | undefined>
18
+ execPath?: string
19
+ sourceDir?: string
20
+ }
21
+
22
+ export function resolveDshLaunch(args: string[], deps: DshLaunchDeps = {}): DshLaunch {
23
+ const env = deps.env ?? process.env
24
+ const command = deps.execPath ?? process.execPath
25
+ const bin = env.DSH_BIN?.trim()
26
+ if (bin) return { command, args: [bin, ...args] }
27
+ return {
28
+ command,
29
+ args: ['--import', 'tsx/esm', 'apps/cli/src/bin.ts', ...args],
30
+ cwd: deps.sourceDir ?? resolveDeepseekHarnessDir(),
31
+ }
32
+ }
33
+
34
+ /** The same launch as a shell fragment (`[cd <dir> && ]exec <argv>`), every word quoted. */
35
+ export function dshLaunchShell(args: string[], deps: DshLaunchDeps = {}): string {
36
+ const launch = resolveDshLaunch(args, deps)
37
+ const argv = [launch.command, ...launch.args].map(a => JSON.stringify(a)).join(' ')
38
+ return launch.cwd ? `cd ${JSON.stringify(launch.cwd)} && exec ${argv}` : `exec ${argv}`
39
+ }
40
+
41
+ /**
42
+ * Whether a process command line is a `dsh web` boot in either form: the
43
+ * source entry (`apps/cli/src/bin.ts web`), the package entry (`lib/bin.js
44
+ * web`) or the installed bin (`.../dsh web`).
45
+ */
46
+ export function isDshWebCommand(cmd: string): boolean {
47
+ return /(?:\bbin\.[jt]s|\/dsh)\s+web(?:\s|$)/.test(cmd)
48
+ }
@@ -49,7 +49,7 @@ export interface PollHealthOpts {
49
49
  // Specific parse/boot-failure markers only. Bare 'JSON'/'YAML' were removed
50
50
  // (2026-08-31): they matched any line whose payload merely *contained* those
51
51
  // substrings — e.g. maestro-sync's status JSON listing session.jsonl.zstd /
52
- // settings.json paths — turning a healthy 401 into a rollback + restart.
52
+ // settings.json paths — turning a healthy 401 into a restart.
53
53
  const ERROR_PATTERNS = [
54
54
  'ERR_MODULE_NOT_FOUND',
55
55
  'ERR_PNPM',
@@ -247,7 +247,7 @@ export async function pollHealth(opts: PollHealthOpts = {}): Promise<HealthState
247
247
  // post-start crash. With no marker and no scope proving these lines are this
248
248
  // boot's, the scan is inconclusive (D3) instead of inheriting the previous
249
249
  // boot's crash text — that inheritance is what produced the 2026-09-13
250
- // rollback report ("rollback — degraded: This operation was aborted") from a
250
+ // crash report ("restart — degraded: This operation was aborted") from a
251
251
  // healthy, still-booting instance reading the previous boot's EADDRINUSE.
252
252
  const successIdx = lastSuccessMarkerIndex(bootLower)
253
253
  let scanLines: string[]
@@ -318,7 +318,7 @@ export async function pollHealth(opts: PollHealthOpts = {}): Promise<HealthState
318
318
  // the same way a genuinely dead one does — but a real crash always frees
319
319
  // the port, while `ss` does not depend on the contended event loop to
320
320
  // answer. Downgrade to DEGRADED (still visible, still escalates after
321
- // repeated ticks) instead of forcing an immediate rollback + restartWeb
321
+ // repeated ticks) instead of forcing an immediate restartWeb
322
322
  // that would kill an in-flight review for nothing.
323
323
  let portAlive = false
324
324
  try { portAlive = await psAliveFn() } catch { portAlive = false }
@@ -7,7 +7,7 @@ export async function notify(msg: string, opts: NotifierOpts = {}): Promise<void
7
7
  try {
8
8
  await send(msg)
9
9
  } catch {
10
- // never block caller — rollback/report must not fail due to notifier
10
+ // never block caller — restart/report must not fail due to notifier
11
11
  }
12
12
  }
13
13
 
@@ -41,8 +41,6 @@ ${opts.logTail.slice(-5000) || '(empty)'}
41
41
 
42
42
  ## Next Steps
43
43
 
44
- - Check \`~/.dsh/.supervisor/lkg/\` for last-known-good
45
- - Review \`failed/${opts.ts}/\` snapshot
46
44
  - If degraded, fix the listed plugin row and run \`pnpm verify\` + dry-boot
47
45
 
48
46
  ---
@@ -71,7 +71,7 @@ export function systemdUnitExists(unitPath: string = dshWebUnitPath()): boolean
71
71
  * The direct-node `nohup` fallback exists for portable hosts that have no
72
72
  * systemd unit. When the unit exists, systemd owns the boot: spawning node
73
73
  * behind its back is how a second instance appears — the two starts / one
74
- * rollback report of 2026-09-13. Gate on "the unit does not exist", never on
74
+ * crash report of 2026-09-13. Gate on "the unit does not exist", never on
75
75
  * "this particular start failed".
76
76
  */
77
77
  export function shouldUseNohupFallback(unitExists: boolean): boolean {
@@ -44,23 +44,12 @@ export function markBootBoundary(logPath?: string): void {
44
44
  } catch {}
45
45
  }
46
46
 
47
- // LKG rollback copies each entry with fs.cpSync — an entry that resolves back
48
- // into itself (e.g. a symlink cycle reachable from ~/.dsh, observed in
49
- // production pointing into ~/.npm/_npx/.../node_modules/unist-util-position)
50
- // always throws here. Node's wording for this varies by version ("cannot be
51
- // the same", "subdirectory of itself"/"of self") — match all known phrasings
52
- // so the entry is skipped instead of aborting the whole rollback.
53
- export function isSelfCopyError(message: string): boolean {
54
- const lower = message.toLowerCase()
55
- return lower.includes('cannot be the same') || lower.includes('subdirectory of')
56
- }
57
-
58
47
  // Coordination contract with dsh-safe-web-update's restart-dsh-web.sh (see
59
48
  // <workspace-root>/docs/specs/2026-09-13-supervisor-restart-resilience-design.md):
60
49
  // that script writes this marker right before it intentionally takes dsh-web
61
50
  // down, so the supervisor's own health poll does not mistake a deliberate
62
51
  // restart (kill -> dry-boot -> relaunch, up to ~130s) for a crash and race it
63
- // with its own rollback + restartWeb(). The marker is the JSON {ts, ttl}
52
+ // with its own restartWeb(). The marker is the JSON {ts, ttl}
64
53
  // document at planned-restart.json; a plain mtime-only file is no longer read.
65
54
  export const PLANNED_RESTART_TTL_MS = 180_000
66
55
 
@@ -3,9 +3,8 @@
3
3
  * dsh web. Scheduling a restart through this tool instead of a raw kill keeps
4
4
  * the restart inside the supervisor's ownership loop:
5
5
  *
6
- * 1. dry-boot gate — if the plugin tree changed since the latest LKG, boot a
7
- * copy of the live profile on an ephemeral DSH_HOME first and only
8
- * schedule when that boot serves HTTP.
6
+ * 1. dry-boot gate — boot a copy of the live profile on an ephemeral
7
+ * DSH_HOME first and only schedule when that boot serves HTTP.
9
8
  * 2. intent sidecar — record the caller session + reason under
10
9
  * ~/.dsh/.supervisor/intents/ for attribution.
11
10
  * 3. hand-off — write the restart-request marker (planned-restart.json with
@@ -14,13 +13,14 @@
14
13
  */
15
14
 
16
15
  import { join, dirname, resolve } from 'node:path'
17
- import { mkdtempSync, rmSync, cpSync, existsSync, readFileSync, readdirSync, statSync, lstatSync, readlinkSync, symlinkSync, unlinkSync } from 'node:fs'
16
+ import { mkdtempSync, rmSync, cpSync, existsSync, readFileSync, readdirSync, lstatSync, readlinkSync, symlinkSync, unlinkSync } from 'node:fs'
18
17
  import { tmpdir, homedir } from 'node:os'
19
18
  import { spawn, execFileSync } from 'node:child_process'
20
19
  import { createRequire } from 'node:module'
21
20
  import { writeRestartRequest, readRestartRequest } from './restart-guards.js'
22
21
  import { intentPath, readIntent, readRestartOutcome } from './intents.js'
23
22
  import { supervisorDaemonState, describeDaemonState, type DaemonState } from './daemon-freshness.js'
23
+ import { resolveDshLaunch, isDshWebCommand } from './dsh-launch.js'
24
24
 
25
25
  /**
26
26
  * Copy a live profile tree for an isolated dry-boot. A naive recursive copy
@@ -110,7 +110,7 @@ export function listDryBootCandidates(readers: GcReaders = {}): DryBootCandidate
110
110
  const out: DryBootCandidate[] = []
111
111
  for (const p of readProc()) {
112
112
  if (p.pid === selfPid) continue
113
- if (!/bin\.ts web/.test(p.cmd)) continue
113
+ if (!isDshWebCommand(p.cmd)) continue
114
114
  const home = /^DSH_HOME=([^\0]*)/m.exec(p.env)?.[1] ?? ''
115
115
  if (!home.startsWith(join(tmpdir(), 'dsh-dryboot-'))) continue
116
116
  const ports = ssPortsOf(p.pid)
@@ -126,7 +126,9 @@ export function listDryBootCandidates(readers: GcReaders = {}): DryBootCandidate
126
126
  * Boot a copy of the live web profile on an isolated DSH_HOME and verify the
127
127
  * plugin tree loads and serves. Returns ok + a one-line detail for the tool
128
128
  * message. The spawned tree is killed (best-effort) and the temp home removed.
129
- * Unit tests mock this (never spawn a real node boot in tests).
129
+ * Unit tests mock this (never spawn a real node boot in tests). The boot uses
130
+ * `resolveDshLaunch`, so `harnessRoot` (the source checkout) only matters
131
+ * when `DSH_BIN` is unset.
130
132
  *
131
133
  * NOTE (bin.ts finding): the `web` alias already implies `--profile web`, and
132
134
  * the web app's own commander program (no allowUnknownOption) rejects a stray
@@ -145,8 +147,9 @@ export async function dryBootVerify(harnessRoot: string, opts: { timeoutMs?: num
145
147
  copyProfileForDryBoot(liveProfile, join(tmpHome, 'profiles', 'web'))
146
148
  const port = String(9000 + Math.floor(Math.random() * 1000))
147
149
  const url = `http://127.0.0.1:${port}/`
148
- child = spawn('node', ['--import', 'tsx/esm', 'apps/cli/src/bin.ts', 'web', '--no-open', '--port', port], {
149
- cwd: harnessRoot, env: { ...process.env, DSH_HOME: tmpHome }, stdio: ['ignore', 'pipe', 'pipe'],
150
+ const launch = resolveDshLaunch(['web', '--no-open', '--port', port], { sourceDir: harnessRoot })
151
+ child = spawn(launch.command, launch.args, {
152
+ cwd: launch.cwd, env: { ...process.env, DSH_HOME: tmpHome }, stdio: ['ignore', 'pipe', 'pipe'],
150
153
  })
151
154
  child.stdout?.on('data', (d: Buffer) => logs.push(d.toString()))
152
155
  child.stderr?.on('data', (d: Buffer) => logs.push(d.toString()))
@@ -197,79 +200,18 @@ export function dryBootFailureDetail(tail: string, exitCode: number): string {
197
200
  export interface FileStat { mtimeMs: number }
198
201
 
199
202
  /**
200
- * Whether the live plugin tree differs from the latest LKG snapshot. Three
201
- * signals are combined:
202
- *
203
- * 1. manifest drift — the live profile's web `package.json` text vs baseline;
204
- * 2. cordis patch drift — the live profile's web `cordis.patch.yml` text vs
205
- * baseline (a patch-only config edit changes the boot-time row wiring
206
- * without touching the manifest — the manifest check alone misses it);
207
- * 3. plugin-lib drift — any `@ddtcorex` plugin `lib/` file newer than the
208
- * snapshot moment. Link-installed plugins resolve to the same workspace
209
- * files in both live and LKG, so the stored copies cannot be compared
210
- * byte-wise; the snapshot itself is the meaningful baseline and a rebuilt
211
- * `lib/` bumps a file past it even when the manifest text is unchanged.
212
- * writeLKG writes `manifest.json` LAST, so its FILE mtime is the
213
- * authoritative snapshot moment; the snapshot dir mtime is only a
214
- * fallback for legacy snapshots without a manifest.
215
- *
216
- * `statFile` (default `statSync`) reads the metadata so tests can inject a
217
- * controlled reader instead of relying on filesystem utimes (which CI runners
218
- * do not reliably reflect). No LKG baseline, a missing file on either side, or
219
- * any stat/read error means "changed" — the caller falls back to the dry-boot
220
- * gate.
203
+ * Whether the live plugin tree differs from the last boot. There is no
204
+ * snapshot baseline anymore, so this always reports "changed" and the caller
205
+ * always runs the dry-boot gate. `pluginChanged: false` still skips the gate
206
+ * explicitly; anything else boots the candidate first.
221
207
  */
222
208
  export function isPluginTreeChanged(
223
209
  harnessRoot: string,
224
- lkgDir = join(homedir(), '.dsh/.supervisor/lkg'),
225
- opts: { statFile?: (p: string) => FileStat } = {},
210
+ _baselineDir?: string,
211
+ _opts: { statFile?: (p: string) => FileStat } = {},
226
212
  ): boolean {
227
213
  void harnessRoot
228
- const statFile = opts.statFile ?? ((p: string) => statSync(p))
229
- try {
230
- const entries = existsSync(lkgDir) ? readdirSync(lkgDir).sort() : []
231
- const latest = entries[entries.length - 1]
232
- if (!latest) return true // no baseline → assume changed
233
- const lkgHome = join(lkgDir, latest, 'profiles', 'web')
234
- const live = join(homedir(), '.dsh', 'profiles', 'web')
235
- const lkgManifest = join(lkgHome, 'package.json')
236
- const liveManifest = join(live, 'package.json')
237
- if (!existsSync(lkgManifest) || !existsSync(liveManifest)) return true
238
- if (readFileSync(liveManifest, 'utf8') !== readFileSync(lkgManifest, 'utf8')) return true
239
- // cordis.patch.yml — compare only when at least one side has it (profiles
240
- // without a patch are the baseline; a patch appearing on either side alone
241
- // is drift). The text compare keeps the check cheap and hermetic.
242
- const lkgPatch = join(lkgHome, 'cordis.patch.yml')
243
- const livePatch = join(live, 'cordis.patch.yml')
244
- if (existsSync(lkgPatch) || existsSync(livePatch)) {
245
- if (!existsSync(lkgPatch) || !existsSync(livePatch)) return true
246
- if (readFileSync(livePatch, 'utf8') !== readFileSync(lkgPatch, 'utf8')) return true
247
- }
248
- const snapshotManifest = join(lkgDir, latest, 'manifest.json')
249
- const baseline = existsSync(snapshotManifest)
250
- ? statFile(snapshotManifest).mtimeMs
251
- : statFile(join(lkgDir, latest)).mtimeMs
252
- const livePlugins = join(live, 'node_modules', '@ddtcorex')
253
- if (existsSync(livePlugins)) {
254
- for (const name of readdirSync(livePlugins)) {
255
- const libDir = join(livePlugins, name, 'lib')
256
- if (!existsSync(libDir)) continue
257
- if (newestFileMtime(libDir, statFile) > baseline) return true
258
- }
259
- }
260
- return false
261
- } catch { return true }
262
- }
263
-
264
- /** Newest mtime under a directory; recursion threads the injected stat reader. */
265
- function newestFileMtime(dir: string, statFile: (p: string) => FileStat): number {
266
- let newest = 0
267
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
268
- const p = join(dir, entry.name)
269
- if (entry.isDirectory()) newest = Math.max(newest, newestFileMtime(p, statFile))
270
- else newest = Math.max(newest, statFile(p).mtimeMs)
271
- }
272
- return newest
214
+ return true
273
215
  }
274
216
 
275
217
  function currentSessionId(exec: any, fallback?: (exec: any) => string | undefined): string | undefined {
@@ -315,7 +257,7 @@ export function registerRestartTool(ctx: any, deps: {
315
257
  if (typeof tools?.register !== 'function') throw new Error('tools service unavailable')
316
258
  dispose = tools.register({
317
259
  name: 'dsh_web_restart',
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.',
260
+ description: 'Schedule a safe restart of the dsh web host: dry-boots the plugin tree, 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.',
319
261
  parameters: {
320
262
  type: 'object',
321
263
  properties: {
@@ -346,8 +288,7 @@ export function registerRestartTool(ctx: any, deps: {
346
288
  return { ok: false, detail: `restart already in progress (requested by ${by}${why}) — check dsh_web_restart_status instead of scheduling another` }
347
289
  }
348
290
  const harnessRoot = deps.harnessRoot ?? (await import('./paths.js')).resolveDeepseekHarnessDir()
349
- const lkgDir = join(homedir(), '.dsh/.supervisor/lkg')
350
- const changed = args.pluginChanged === true || (args.pluginChanged !== false && isPluginTreeChanged(harnessRoot, lkgDir))
291
+ const changed = args.pluginChanged === true || (args.pluginChanged !== false && isPluginTreeChanged(harnessRoot))
351
292
  if (changed) {
352
293
  const gate = await doDryBoot(harnessRoot)
353
294
  if (!gate.ok) return { ok: false, detail: `dry-boot failed — restart refused. ${gate.detail}` }
@@ -3,7 +3,7 @@ import * as path from 'node:path'
3
3
  import { buildKillStalePortsCommand, writePlannedRestart } from './restart-guards.js'
4
4
  import { serializedSystemdRestart, shouldUseNohupFallback, systemdUnitExists } from './restart-exec.js'
5
5
  import { withBootLock, type BootLockDeps } from './boot-lock.js'
6
- import { resolveDeepseekHarnessDir } from './paths.js'
6
+ import { dshLaunchShell, type DshLaunchDeps } from './dsh-launch.js'
7
7
 
8
8
  /** Boot budget: how long a boot may take before its failures are judged. */
9
9
  export const DEFAULT_BOOT_GRACE_MS = 180_000
@@ -27,7 +27,7 @@ export interface RestartWebResult {
27
27
  /**
28
28
  * The single implementation of a supervised dsh web restart. Single-flight:
29
29
  * boot.lock is held from before the marker is written until the port answers,
30
- * so a racing tick or a second rollback skips instead of producing the second
30
+ * so a racing tick or a second restart skips instead of producing the second
31
31
  * systemd start that turned the incident's log tail toxic (2026-09-13).
32
32
  */
33
33
  export async function performSingleBootRestart(deps: RestartWebDeps = {}): Promise<RestartWebResult> {
@@ -61,12 +61,14 @@ export async function performSingleBootRestart(deps: RestartWebDeps = {}): Promi
61
61
  return { restarted: true }
62
62
  }
63
63
 
64
+ /** The detached last-resort start, appending to the web log. Exported for tests. */
65
+ export function buildNohupCommand(logPath: string, deps: DshLaunchDeps = {}): string {
66
+ const launch = dshLaunchShell(['web', '--no-open'], deps)
67
+ return `setsid nohup bash -c 'export NVM_DIR="$HOME/.nvm"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"; ${launch} >> ${JSON.stringify(logPath)} 2>&1' &`
68
+ }
69
+
64
70
  async function defaultNohup(): Promise<void> {
65
71
  const { execSync } = await import('node:child_process')
66
- const harnessRoot = resolveDeepseekHarnessDir()
67
72
  const logPath = path.join(os.homedir(), '.dsh/dsh-web.log')
68
- execSync(
69
- `setsid nohup bash -c 'export NVM_DIR="$HOME/.nvm"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"; cd ${JSON.stringify(harnessRoot)} && exec node --import tsx/esm apps/cli/src/bin.ts web --no-open >> ${JSON.stringify(logPath)} 2>&1' &`,
70
- { timeout: 5000 },
71
- )
73
+ execSync(buildNohupCommand(logPath), { timeout: 5000 })
72
74
  }