@ddtcorex/dsh-maestro-core 0.12.0 → 0.13.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.
@@ -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,7 +13,7 @@
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'
@@ -197,79 +196,18 @@ export function dryBootFailureDetail(tail: string, exitCode: number): string {
197
196
  export interface FileStat { mtimeMs: number }
198
197
 
199
198
  /**
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.
199
+ * Whether the live plugin tree differs from the last boot. There is no
200
+ * snapshot baseline anymore, so this always reports "changed" and the caller
201
+ * always runs the dry-boot gate. `pluginChanged: false` still skips the gate
202
+ * explicitly; anything else boots the candidate first.
221
203
  */
222
204
  export function isPluginTreeChanged(
223
205
  harnessRoot: string,
224
- lkgDir = join(homedir(), '.dsh/.supervisor/lkg'),
225
- opts: { statFile?: (p: string) => FileStat } = {},
206
+ _baselineDir?: string,
207
+ _opts: { statFile?: (p: string) => FileStat } = {},
226
208
  ): boolean {
227
209
  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
210
+ return true
273
211
  }
274
212
 
275
213
  function currentSessionId(exec: any, fallback?: (exec: any) => string | undefined): string | undefined {
@@ -315,7 +253,7 @@ export function registerRestartTool(ctx: any, deps: {
315
253
  if (typeof tools?.register !== 'function') throw new Error('tools service unavailable')
316
254
  dispose = tools.register({
317
255
  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.',
256
+ 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
257
  parameters: {
320
258
  type: 'object',
321
259
  properties: {
@@ -346,8 +284,7 @@ export function registerRestartTool(ctx: any, deps: {
346
284
  return { ok: false, detail: `restart already in progress (requested by ${by}${why}) — check dsh_web_restart_status instead of scheduling another` }
347
285
  }
348
286
  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))
287
+ const changed = args.pluginChanged === true || (args.pluginChanged !== false && isPluginTreeChanged(harnessRoot))
351
288
  if (changed) {
352
289
  const gate = await doDryBoot(harnessRoot)
353
290
  if (!gate.ok) return { ok: false, detail: `dry-boot failed — restart refused. ${gate.detail}` }
@@ -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> {
@@ -12,27 +12,17 @@ import { writeRestartOutcome as defaultWriteOutcome, type RestartOutcome } from
12
12
  import { execFileSync } from 'node:child_process'
13
13
  import { mintDshSessionCookie, type MintCookieOpts } from './dsh-session.js'
14
14
 
15
- /** Partial-restore report a rollback may hand back (cli.ts wires RestoreResult). */
16
- export interface RollbackSummary {
17
- target?: string
18
- restored?: number
19
- skipped?: Array<{ path: string; reason: string }>
20
- }
21
-
22
15
  export interface SupervisorDeps {
23
- pollHealth: () => Promise<HealthState>
24
- writeLKG: () => Promise<{ ts: string; manifest?: any }>
25
- writeFailed: () => Promise<{ ts: string; manifest?: any }>
26
- writeReport: (opts: { ts: string; health: HealthState; action: string; logTail?: string; gitDiff?: string }) => Promise<string>
27
- rollback: (ts?: string) => Promise<RollbackSummary | void>
28
- restartWeb?: () => Promise<void>
16
+ pollHealth: () => Promise<HealthState>;
17
+ writeReport: (opts: { ts: string; health: HealthState; action: string; logTail?: string; gitDiff?: string }) => Promise<string>;
18
+ restartWeb?: () => Promise<void>;
29
19
  notify: (msg: string) => Promise<void>
30
20
  intervalMs?: number
31
21
  debounceMs?: number
32
22
  // Number of consecutive "down" polls required before a crash is confirmed
33
- // and rollback/restart fires. A single transient poll failure (e.g. a
23
+ // and restart fires. A single transient poll failure (e.g. a
34
24
  // fetch timeout while the plugin tree is still booting) must not trigger
35
- // a full rollback — that restart itself produces transient errors on the
25
+ // a restart — that restart itself produces transient errors on the
36
26
  // next poll, which would otherwise re-trigger endlessly. Default 3 (at the
37
27
  // daemon's 3s interval, ~9s of continuous down before acting).
38
28
  downThreshold?: number
@@ -44,7 +34,7 @@ export interface SupervisorDeps {
44
34
  // Checks the dsh-safe-web-update marker (see
45
35
  // <workspace-root>/docs/specs/2026-09-13-supervisor-restart-resilience-design.md): a down poll
46
36
  // while this resolves true is an intentional restart in progress, not a
47
- // crash — skip rollback/restartWeb entirely rather than racing it.
37
+ // crash — skip restartWeb entirely rather than racing it.
48
38
  isPlannedRestartActive?: () => boolean | Promise<boolean>
49
39
  // 30s planned-restart marker (restart-guards.ts): single owner for restart
50
40
  // decisions. Injected for tests so tick/restartWeb can be verified without
@@ -125,9 +115,8 @@ export async function resumeViaRpcWithSession(
125
115
 
126
116
  export class Supervisor {
127
117
  private deps: SupervisorDeps
128
- private lastRollback = 0
129
- private rollingBack = false
130
- private lastLKGWrite = 0
118
+ private lastRestart = 0
119
+ private restarting = false
131
120
  private lastDegradedNotify = 0
132
121
  private consecutiveDown = 0
133
122
  private consecutiveDegraded = 0
@@ -157,7 +146,7 @@ export class Supervisor {
157
146
  const grace = await this.getEffectiveBootGraceMs()
158
147
  // Marker first, and its TTL is the boot budget — not 30 s. The observed
159
148
  // boot took 1m52s: after +30 s every poll was judged as a crash, which is
160
- // exactly how the 2026-09-13 rollback report was produced (D5).
149
+ // exactly how the 2026-09-13 crash report was produced (D5).
161
150
  this.getWritePlannedRestart()(grace)
162
151
  if (this.deps.restartWeb) {
163
152
  // Injected implementation (cli.ts daemon wiring, tests): it owns the
@@ -359,19 +348,6 @@ export class Supervisor {
359
348
  }
360
349
  }
361
350
 
362
- /**
363
- * D4: a restore that could not put every entry back must be surfaced loudly.
364
- * Without this, a half-restored tree reads exactly like a clean recovery in
365
- * the log and in the operator's Telegram feed.
366
- */
367
- private async reportRollbackResult(summary: RollbackSummary | void, reportPath: string): Promise<void> {
368
- if (!summary || !summary.skipped?.length) return
369
- const first = summary.skipped.slice(0, 3).map(s => `${s.path} (${s.reason})`).join('; ')
370
- await this.deps.notify(
371
- `ROLLBACK PARTIAL: ${summary.restored ?? 0} restored, ${summary.skipped.length} skipped — ${first} (report: ${reportPath})`,
372
- ).catch(() => {})
373
- }
374
-
375
351
  private handleDebugResult(reportPath: string, res: { fixed: boolean; reason: string }): void {
376
352
  if (res.fixed) {
377
353
  void this.deps.notify(`FIXED: debug-agent fixed ${reportPath} — ${res.reason}`).catch(() => {})
@@ -397,7 +373,7 @@ export class Supervisor {
397
373
  // grace timer → restartWeb once → notify. The suppression marker and the
398
374
  // single-flight latch are held until a post-restart health.up tick clears
399
375
  // them, so the in-flight down of our own restart can never be mistaken for
400
- // a crash and raced with a rollback + second restart by the crash path.
376
+ // a crash and raced with a second restart by the crash path.
401
377
  const restartReq = this.deps.readRestartRequest ? this.deps.readRestartRequest() : undefined
402
378
  if (restartReq?.callerSessionId && !this.restartRequestHandled) {
403
379
  this.restartRequestHandled = true
@@ -405,10 +381,10 @@ export class Supervisor {
405
381
  void (async () => {
406
382
  try {
407
383
  // Debounce crash handling from the moment the restart is issued —
408
- // the crash path sets lastRollback the same way. A slow boot must
384
+ // the crash path sets lastRestart the same way. A slow boot must
409
385
  // not be classified as a crash even after the suppression marker's
410
386
  // own 30s TTL runs out.
411
- this.lastRollback = this.deps.getTime ? this.deps.getTime() : Date.now()
387
+ this.lastRestart = this.deps.getTime ? this.deps.getTime() : Date.now()
412
388
  await this.restartWeb()
413
389
  // restartWeb() already wrote the marker with the boot budget as its
414
390
  // TTL; the marker is cleared on the first healthy poll instead.
@@ -438,12 +414,12 @@ export class Supervisor {
438
414
  return
439
415
  }
440
416
 
441
- // DEGRADED: http 200 but log has plugin error → report + notify, rollback after consecutive threshold
417
+ // DEGRADED: http 200 but log has plugin error → report + notify, restart after consecutive threshold
442
418
  if (health.degraded) {
443
419
  this.consecutiveDown = 0
444
420
  // D1: a degraded verdict while the current boot is unproven is a boot
445
421
  // transient, not a plugin error — the incident's report line
446
- // "rollback — degraded: This operation was aborted" was produced exactly
422
+ // "restart — degraded: This operation was aborted" was produced exactly
447
423
  // here, five polls after a slow boot.
448
424
  if (health.bootPhase === 'booting') {
449
425
  this.consecutiveDegraded = 0
@@ -494,32 +470,27 @@ export class Supervisor {
494
470
  } catch {}
495
471
  return
496
472
  }
497
- // consecutive degraded threshold reached → treat as down: rollback + restart
473
+ // consecutive degraded threshold reached → treat as down: report + restart
498
474
  this.consecutiveDegraded = 0
499
475
  const degradedError = health.error ?? 'degraded plugin error'
500
- if (this.rollingBack) return
476
+ if (this.restarting) return
501
477
  const now2 = this.deps.getTime ? this.deps.getTime() : Date.now()
502
478
  const debounceMs2 = this.deps.debounceMs ?? 60000
503
- if (now2 - this.lastRollback < debounceMs2) return
504
- this.rollingBack = true
505
- this.lastRollback = now2
479
+ if (now2 - this.lastRestart < debounceMs2) return
480
+ this.restarting = true
481
+ this.lastRestart = now2
506
482
  try {
507
- const failed = await this.deps.writeFailed().catch(() => ({ ts: new Date().toISOString().replace(/[:.]/g, '-'), manifest: null }))
508
- const ts2 = (failed as any)?.ts ?? new Date().toISOString().replace(/[:.]/g, '-')
483
+ const ts2 = new Date().toISOString().replace(/[:.]/g, '-')
509
484
  const logTail2 = (health as any).logTail ?? ''
510
485
  const gitDiff2 = await this.collectGitDiff().catch(() => '')
511
486
  const degradedHealth: HealthState = { up: false, httpCode: health.httpCode, error: `degraded → down: ${degradedError}`, logTail: logTail2, degraded: false }
512
- const reportPath2 = await this.deps.writeReport({ ts: ts2, health: degradedHealth, action: `rollback — degraded: ${degradedError}`, logTail: logTail2, gitDiff: gitDiff2 }).catch(() => '')
513
- try {
514
- const summary = await this.deps.rollback()
515
- await this.reportRollbackResult(summary, reportPath2)
516
- } catch (e: any) { await this.deps.notify(`rollback failed: ${e?.message ?? String(e)} (report: ${reportPath2})`).catch(() => {}) }
487
+ const reportPath2 = await this.deps.writeReport({ ts: ts2, health: degradedHealth, action: `restart — degraded: ${degradedError}`, logTail: logTail2, gitDiff: gitDiff2 }).catch(() => '')
517
488
  if (this.deps.restartWeb) {
518
- try { await this.deps.restartWeb(); await this.deps.notify(`restarted dsh-web after rollback (report: ${reportPath2})`).catch(() => {}) } catch (e: any) { await this.deps.notify(`restart dsh-web failed: ${e?.message ?? String(e)} (report: ${reportPath2})`).catch(() => {}) }
489
+ try { await this.deps.restartWeb(); await this.deps.notify(`restarted dsh-web (report: ${reportPath2})`).catch(() => {}) } catch (e: any) { await this.deps.notify(`restart dsh-web failed: ${e?.message ?? String(e)} (report: ${reportPath2})`).catch(() => {}) }
519
490
  }
520
- await this.deps.notify(`DEGRADED → rollback (report: ${reportPath2}, error: ${degradedError})`).catch(() => {})
491
+ await this.deps.notify(`DEGRADED → restart (report: ${reportPath2}, error: ${degradedError})`).catch(() => {})
521
492
  try { await this.deps.notify(`🔄 dsh web auto-restart — degraded: ${degradedError} — ${new Date().toISOString()}`).catch(() => {}) } catch {}
522
- } finally { this.rollingBack = false }
493
+ } finally { this.restarting = false }
523
494
  return
524
495
  }
525
496
 
@@ -565,21 +536,11 @@ export class Supervisor {
565
536
  }
566
537
  }
567
538
  }
568
- // Throttle LKG writes to at most once per 5 minutes
569
- const now = this.deps.getTime ? this.deps.getTime() : Date.now()
570
- if (now - this.lastLKGWrite > 5 * 60 * 1000) {
571
- try {
572
- await this.deps.writeLKG()
573
- this.lastLKGWrite = now
574
- } catch {
575
- // ignore snapshot errors
576
- }
577
- }
578
539
  return
579
540
  }
580
541
 
581
542
  // Single-owner 30s marker: planned restart in progress — suppress crash
582
- // handling entirely for 30s (no writeFailed/writeReport/rollback).
543
+ // handling entirely for 30s (no writeReport/restart).
583
544
  // Check both the new JSON marker (writePlannedRestart) and the legacy
584
545
  // isPlannedRestartActive (dsh-safe-web-update plain file) for compat.
585
546
  let suppressedByMarker = false
@@ -591,7 +552,7 @@ export class Supervisor {
591
552
 
592
553
  // Down while an intentional restart (e.g. dsh-safe-web-update) is in
593
554
  // flight is expected, not a crash — never race it with our own
594
- // rollback/restartWeb.
555
+ // restartWeb.
595
556
  if (this.deps.isPlannedRestartActive) {
596
557
  let planned = false
597
558
  try { planned = await Promise.resolve(this.deps.isPlannedRestartActive()) } catch { planned = false }
@@ -603,7 +564,7 @@ export class Supervisor {
603
564
 
604
565
  // Down — require consecutive confirmations before treating as a crash.
605
566
  // A lone timed-out poll (e.g. a slow plugin-tree boot) must not trigger
606
- // rollback/restart: that restart produces its own transient errors on
567
+ // restart: that restart produces its own transient errors on
607
568
  // the next poll, which would otherwise re-trigger this same path forever.
608
569
  // D1/D2: while the boot is unproven only a refused connection may advance
609
570
  // the down counter — nothing is listening, so the process is gone. A
@@ -626,38 +587,31 @@ export class Supervisor {
626
587
  } catch {}
627
588
  if (this.consecutiveDown < downThreshold) return
628
589
 
629
- // Down — check debounce and rolling state
630
- if (this.rollingBack) return
590
+ // Down — check debounce and restarting state
591
+ if (this.restarting) return
631
592
  const now = this.deps.getTime ? this.deps.getTime() : Date.now()
632
593
  const debounceMs = this.deps.debounceMs ?? 60000
633
- if (now - this.lastRollback < debounceMs) return
594
+ if (now - this.lastRestart < debounceMs) return
634
595
 
635
- this.rollingBack = true
596
+ this.restarting = true
636
597
  this.consecutiveDown = 0
637
- this.lastRollback = now
598
+ this.lastRestart = now
638
599
 
639
600
  try {
640
- const failed = await this.deps.writeFailed().catch(() => ({ ts: new Date().toISOString().replace(/[:.]/g, '-'), manifest: null }))
641
- const ts = (failed as any)?.ts ?? new Date().toISOString().replace(/[:.]/g, '-')
601
+ const ts = new Date().toISOString().replace(/[:.]/g, '-')
642
602
  const logTail = (health as any).logTail ?? ''
643
603
  const gitDiff = await this.collectGitDiff().catch(() => '')
644
- const reportPath = await this.deps.writeReport({ ts, health, action: `rollback — ${health.error ?? 'down'}`, logTail, gitDiff }).catch(() => '')
645
- try {
646
- const summary = await this.deps.rollback()
647
- await this.reportRollbackResult(summary, reportPath)
648
- } catch (e: any) {
649
- await this.deps.notify(`rollback failed: ${e?.message ?? String(e)} (report: ${reportPath})`).catch(() => {})
650
- }
651
- // Always attempt to (re)start dsh web — survives reboot even when rollback is a no-op
604
+ const reportPath = await this.deps.writeReport({ ts, health, action: `restart — ${health.error ?? 'down'}`, logTail, gitDiff }).catch(() => '')
605
+ // Always attempt to (re)start dsh web — survives reboot even when the previous boot left nothing behind
652
606
  if (this.deps.restartWeb) {
653
607
  try {
654
608
  await this.deps.restartWeb()
655
- await this.deps.notify(`restarted dsh-web after rollback (report: ${reportPath})`).catch(() => {})
609
+ await this.deps.notify(`restarted dsh-web (report: ${reportPath})`).catch(() => {})
656
610
  } catch (e: any) {
657
611
  await this.deps.notify(`restart dsh-web failed: ${e?.message ?? String(e)} (report: ${reportPath})`).catch(() => {})
658
612
  }
659
613
  }
660
- await this.deps.notify(`CRASH detected → rollback (report: ${reportPath}, error: ${health.error ?? 'down'})`).catch(() => {})
614
+ await this.deps.notify(`CRASH detected → restart (report: ${reportPath}, error: ${health.error ?? 'down'})`).catch(() => {})
661
615
  const runner = this.getRunDebugAgent()
662
616
  const isInjected = !!this.deps.runDebugAgent
663
617
  if (isInjected) {
@@ -676,7 +630,7 @@ export class Supervisor {
676
630
  }, 0)
677
631
  }
678
632
  } finally {
679
- this.rollingBack = false
633
+ this.restarting = false
680
634
  }
681
635
  }
682
636
 
package/lib/snapshot.d.ts DELETED
@@ -1,60 +0,0 @@
1
- export interface SnapshotResult {
2
- ts: string;
3
- /** Files (and symlinks) copied into this snapshot. */
4
- files: number;
5
- /** Entries that could not be copied; the snapshot stays usable either way. */
6
- skipped: Array<{
7
- path: string;
8
- reason: string;
9
- }>;
10
- }
11
- export interface SnapshotDeps {
12
- /**
13
- * Copy one regular file, preserving `mode`. Injectable so a failing entry
14
- * (the EACCES a read-only attachment object produces) can be table-tested
15
- * without depending on the host's uid or filesystem quirks.
16
- */
17
- copyFile?: (src: string, dest: string, mode: number) => void;
18
- }
19
- /**
20
- * Entries under the harness home directory that the last-known-good snapshot
21
- * deliberately never copies.
22
- *
23
- * The LKG exists to recover a boot that fails while loading the plugin tree, so
24
- * it holds boot **configuration**: `profiles/` (the plugin tree with its
25
- * lockfile, `cordis.patch.yml` and sidecars), the per-plugin config directories
26
- * and the settings documents. Everything below is runtime **data** — it is
27
- * written continuously while `dsh web` runs, so restoring a snapshot of it can
28
- * only lose newer state, and some of it is hostile to a bulk copy:
29
- *
30
- * - `sessions/` — append-only transcripts. Restoring a stale copy over live
31
- * sessions drops every turn recorded after the snapshot, i.e. the recovery
32
- * path would lose the log it is supposed to protect.
33
- * - `attachments/` — content-addressed blobs stored mode `0400`. That read-only
34
- * bit is exactly what made the 2026-09-13 rollback abort with
35
- * `EACCES: Permission denied '.../attachments/v1/objects/f8'`.
36
- * - `plugins-src/` — plugin source cache, re-fetched on demand (~400 MB host).
37
- * - `.supervisor/` — the LKG root itself lives inside the DSH home, so copying
38
- * it would recurse into every retained snapshot.
39
- *
40
- * This list is data, not a heuristic: the copy loop and the restore loop both
41
- * consult `isLkgExcluded()`, and the table test pins the rule.
42
- */
43
- export declare const LKG_EXCLUDED_ENTRIES: readonly string[];
44
- /**
45
- * True when a path relative to the harness home must never enter (or leave) the LKG.
46
- *
47
- * The named entries match the first path segment; `*.log` matches by basename
48
- * anywhere, because append-only logs are data at any depth and a restored stale
49
- * `dsh-web.log` would poison the boot-boundary scan.
50
- */
51
- export declare function isLkgExcluded(relPath: string): boolean;
52
- /** Human-readable, bounded reason for a per-entry copy failure. */
53
- export declare function failureReason(e: unknown): string;
54
- export declare function writeLKG(dshHome: string, lkgRoot: string, deps?: SnapshotDeps): Promise<SnapshotResult>;
55
- export declare function pruneByAge(root: string, maxAgeMs: number): Promise<void>;
56
- export declare function pruneBySize(root: string, maxBytes: number): Promise<void>;
57
- export declare function isDuplicateLKG(dshHome: string, lkgRoot: string): Promise<boolean>;
58
- export declare function verifyLKG(lkgPath: string): Promise<boolean>;
59
- export declare function rotateLKG(lkgRoot: string, keep?: number): Promise<void>;
60
- export declare function writeFailed(dshHome: string, failedRoot: string): Promise<SnapshotResult>;