@ddtcorex/dsh-maestro-core 0.12.1 → 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.
@@ -9,7 +9,7 @@ export const DEFAULT_BOOT_GRACE_MS = 180_000;
9
9
  /**
10
10
  * The single implementation of a supervised dsh web restart. Single-flight:
11
11
  * boot.lock is held from before the marker is written until the port answers,
12
- * so a racing tick or a second rollback skips instead of producing the second
12
+ * so a racing tick or a second restart skips instead of producing the second
13
13
  * systemd start that turned the incident's log tail toxic (2026-09-13).
14
14
  */
15
15
  export async function performSingleBootRestart(deps = {}) {
@@ -2,25 +2,8 @@ import { type HealthState } from './health-poller.js';
2
2
  import type { RestartRequest } from './restart-guards.js';
3
3
  import { type RestartOutcome } from './intents.js';
4
4
  import { type MintCookieOpts } from './dsh-session.js';
5
- /** Partial-restore report a rollback may hand back (cli.ts wires RestoreResult). */
6
- export interface RollbackSummary {
7
- target?: string;
8
- restored?: number;
9
- skipped?: Array<{
10
- path: string;
11
- reason: string;
12
- }>;
13
- }
14
5
  export interface SupervisorDeps {
15
6
  pollHealth: () => Promise<HealthState>;
16
- writeLKG: () => Promise<{
17
- ts: string;
18
- manifest?: any;
19
- }>;
20
- writeFailed: () => Promise<{
21
- ts: string;
22
- manifest?: any;
23
- }>;
24
7
  writeReport: (opts: {
25
8
  ts: string;
26
9
  health: HealthState;
@@ -28,7 +11,6 @@ export interface SupervisorDeps {
28
11
  logTail?: string;
29
12
  gitDiff?: string;
30
13
  }) => Promise<string>;
31
- rollback: (ts?: string) => Promise<RollbackSummary | void>;
32
14
  restartWeb?: () => Promise<void>;
33
15
  notify: (msg: string) => Promise<void>;
34
16
  intervalMs?: number;
@@ -76,9 +58,8 @@ export declare function resumeViaRpcWithSession(ids: string[], fetchFn?: (url: s
76
58
  }>;
77
59
  export declare class Supervisor {
78
60
  private deps;
79
- private lastRollback;
80
- private rollingBack;
81
- private lastLKGWrite;
61
+ private lastRestart;
62
+ private restarting;
82
63
  private lastDegradedNotify;
83
64
  private consecutiveDown;
84
65
  private consecutiveDegraded;
@@ -104,12 +85,6 @@ export declare class Supervisor {
104
85
  private findInterruptedRecent;
105
86
  private collectGitDiff;
106
87
  private attemptAutoResume;
107
- /**
108
- * D4: a restore that could not put every entry back must be surfaced loudly.
109
- * Without this, a half-restored tree reads exactly like a clean recovery in
110
- * the log and in the operator's Telegram feed.
111
- */
112
- private reportRollbackResult;
113
88
  private handleDebugResult;
114
89
  tick(): Promise<void>;
115
90
  start(): Promise<void>;
package/lib/supervisor.js CHANGED
@@ -62,9 +62,8 @@ export async function resumeViaRpcWithSession(ids, fetchFn = globalThis.fetch, o
62
62
  }
63
63
  export class Supervisor {
64
64
  deps;
65
- lastRollback = 0;
66
- rollingBack = false;
67
- lastLKGWrite = 0;
65
+ lastRestart = 0;
66
+ restarting = false;
68
67
  lastDegradedNotify = 0;
69
68
  consecutiveDown = 0;
70
69
  consecutiveDegraded = 0;
@@ -89,7 +88,7 @@ export class Supervisor {
89
88
  const grace = await this.getEffectiveBootGraceMs();
90
89
  // Marker first, and its TTL is the boot budget — not 30 s. The observed
91
90
  // boot took 1m52s: after +30 s every poll was judged as a crash, which is
92
- // exactly how the 2026-09-13 rollback report was produced (D5).
91
+ // exactly how the 2026-09-13 crash report was produced (D5).
93
92
  this.getWritePlannedRestart()(grace);
94
93
  if (this.deps.restartWeb) {
95
94
  // Injected implementation (cli.ts daemon wiring, tests): it owns the
@@ -318,17 +317,6 @@ export class Supervisor {
318
317
  await this.deps.notify(`RESUME FAILED: ${ids.length} interrupted sessions (${ids.slice(0, 3).join(', ')}) — ${e?.message ?? String(e)}`).catch(() => { });
319
318
  }
320
319
  }
321
- /**
322
- * D4: a restore that could not put every entry back must be surfaced loudly.
323
- * Without this, a half-restored tree reads exactly like a clean recovery in
324
- * the log and in the operator's Telegram feed.
325
- */
326
- async reportRollbackResult(summary, reportPath) {
327
- if (!summary || !summary.skipped?.length)
328
- return;
329
- const first = summary.skipped.slice(0, 3).map(s => `${s.path} (${s.reason})`).join('; ');
330
- await this.deps.notify(`ROLLBACK PARTIAL: ${summary.restored ?? 0} restored, ${summary.skipped.length} skipped — ${first} (report: ${reportPath})`).catch(() => { });
331
- }
332
320
  handleDebugResult(reportPath, res) {
333
321
  if (res.fixed) {
334
322
  void this.deps.notify(`FIXED: debug-agent fixed ${reportPath} — ${res.reason}`).catch(() => { });
@@ -356,7 +344,7 @@ export class Supervisor {
356
344
  // grace timer → restartWeb once → notify. The suppression marker and the
357
345
  // single-flight latch are held until a post-restart health.up tick clears
358
346
  // them, so the in-flight down of our own restart can never be mistaken for
359
- // a crash and raced with a rollback + second restart by the crash path.
347
+ // a crash and raced with a second restart by the crash path.
360
348
  const restartReq = this.deps.readRestartRequest ? this.deps.readRestartRequest() : undefined;
361
349
  if (restartReq?.callerSessionId && !this.restartRequestHandled) {
362
350
  this.restartRequestHandled = true;
@@ -364,10 +352,10 @@ export class Supervisor {
364
352
  void (async () => {
365
353
  try {
366
354
  // Debounce crash handling from the moment the restart is issued —
367
- // the crash path sets lastRollback the same way. A slow boot must
355
+ // the crash path sets lastRestart the same way. A slow boot must
368
356
  // not be classified as a crash even after the suppression marker's
369
357
  // own 30s TTL runs out.
370
- this.lastRollback = this.deps.getTime ? this.deps.getTime() : Date.now();
358
+ this.lastRestart = this.deps.getTime ? this.deps.getTime() : Date.now();
371
359
  await this.restartWeb();
372
360
  // restartWeb() already wrote the marker with the boot budget as its
373
361
  // TTL; the marker is cleared on the first healthy poll instead.
@@ -400,12 +388,12 @@ export class Supervisor {
400
388
  }, 5000);
401
389
  return;
402
390
  }
403
- // DEGRADED: http 200 but log has plugin error → report + notify, rollback after consecutive threshold
391
+ // DEGRADED: http 200 but log has plugin error → report + notify, restart after consecutive threshold
404
392
  if (health.degraded) {
405
393
  this.consecutiveDown = 0;
406
394
  // D1: a degraded verdict while the current boot is unproven is a boot
407
395
  // transient, not a plugin error — the incident's report line
408
- // "rollback — degraded: This operation was aborted" was produced exactly
396
+ // "restart — degraded: This operation was aborted" was produced exactly
409
397
  // here, five polls after a slow boot.
410
398
  if (health.bootPhase === 'booting') {
411
399
  this.consecutiveDegraded = 0;
@@ -474,48 +462,40 @@ export class Supervisor {
474
462
  catch { }
475
463
  return;
476
464
  }
477
- // consecutive degraded threshold reached → treat as down: rollback + restart
465
+ // consecutive degraded threshold reached → treat as down: report + restart
478
466
  this.consecutiveDegraded = 0;
479
467
  const degradedError = health.error ?? 'degraded plugin error';
480
- if (this.rollingBack)
468
+ if (this.restarting)
481
469
  return;
482
470
  const now2 = this.deps.getTime ? this.deps.getTime() : Date.now();
483
471
  const debounceMs2 = this.deps.debounceMs ?? 60000;
484
- if (now2 - this.lastRollback < debounceMs2)
472
+ if (now2 - this.lastRestart < debounceMs2)
485
473
  return;
486
- this.rollingBack = true;
487
- this.lastRollback = now2;
474
+ this.restarting = true;
475
+ this.lastRestart = now2;
488
476
  try {
489
- const failed = await this.deps.writeFailed().catch(() => ({ ts: new Date().toISOString().replace(/[:.]/g, '-'), manifest: null }));
490
- const ts2 = failed?.ts ?? new Date().toISOString().replace(/[:.]/g, '-');
477
+ const ts2 = new Date().toISOString().replace(/[:.]/g, '-');
491
478
  const logTail2 = health.logTail ?? '';
492
479
  const gitDiff2 = await this.collectGitDiff().catch(() => '');
493
480
  const degradedHealth = { up: false, httpCode: health.httpCode, error: `degraded → down: ${degradedError}`, logTail: logTail2, degraded: false };
494
- const reportPath2 = await this.deps.writeReport({ ts: ts2, health: degradedHealth, action: `rollback — degraded: ${degradedError}`, logTail: logTail2, gitDiff: gitDiff2 }).catch(() => '');
495
- try {
496
- const summary = await this.deps.rollback();
497
- await this.reportRollbackResult(summary, reportPath2);
498
- }
499
- catch (e) {
500
- await this.deps.notify(`rollback failed: ${e?.message ?? String(e)} (report: ${reportPath2})`).catch(() => { });
501
- }
481
+ const reportPath2 = await this.deps.writeReport({ ts: ts2, health: degradedHealth, action: `restart — degraded: ${degradedError}`, logTail: logTail2, gitDiff: gitDiff2 }).catch(() => '');
502
482
  if (this.deps.restartWeb) {
503
483
  try {
504
484
  await this.deps.restartWeb();
505
- await this.deps.notify(`restarted dsh-web after rollback (report: ${reportPath2})`).catch(() => { });
485
+ await this.deps.notify(`restarted dsh-web (report: ${reportPath2})`).catch(() => { });
506
486
  }
507
487
  catch (e) {
508
488
  await this.deps.notify(`restart dsh-web failed: ${e?.message ?? String(e)} (report: ${reportPath2})`).catch(() => { });
509
489
  }
510
490
  }
511
- await this.deps.notify(`DEGRADED → rollback (report: ${reportPath2}, error: ${degradedError})`).catch(() => { });
491
+ await this.deps.notify(`DEGRADED → restart (report: ${reportPath2}, error: ${degradedError})`).catch(() => { });
512
492
  try {
513
493
  await this.deps.notify(`🔄 dsh web auto-restart — degraded: ${degradedError} — ${new Date().toISOString()}`).catch(() => { });
514
494
  }
515
495
  catch { }
516
496
  }
517
497
  finally {
518
- this.rollingBack = false;
498
+ this.restarting = false;
519
499
  }
520
500
  return;
521
501
  }
@@ -571,21 +551,10 @@ export class Supervisor {
571
551
  }
572
552
  }
573
553
  }
574
- // Throttle LKG writes to at most once per 5 minutes
575
- const now = this.deps.getTime ? this.deps.getTime() : Date.now();
576
- if (now - this.lastLKGWrite > 5 * 60 * 1000) {
577
- try {
578
- await this.deps.writeLKG();
579
- this.lastLKGWrite = now;
580
- }
581
- catch {
582
- // ignore snapshot errors
583
- }
584
- }
585
554
  return;
586
555
  }
587
556
  // Single-owner 30s marker: planned restart in progress — suppress crash
588
- // handling entirely for 30s (no writeFailed/writeReport/rollback).
557
+ // handling entirely for 30s (no writeReport/restart).
589
558
  // Check both the new JSON marker (writePlannedRestart) and the legacy
590
559
  // isPlannedRestartActive (dsh-safe-web-update plain file) for compat.
591
560
  let suppressedByMarker = false;
@@ -601,7 +570,7 @@ export class Supervisor {
601
570
  }
602
571
  // Down while an intentional restart (e.g. dsh-safe-web-update) is in
603
572
  // flight is expected, not a crash — never race it with our own
604
- // rollback/restartWeb.
573
+ // restartWeb.
605
574
  if (this.deps.isPlannedRestartActive) {
606
575
  let planned = false;
607
576
  try {
@@ -617,7 +586,7 @@ export class Supervisor {
617
586
  }
618
587
  // Down — require consecutive confirmations before treating as a crash.
619
588
  // A lone timed-out poll (e.g. a slow plugin-tree boot) must not trigger
620
- // rollback/restart: that restart produces its own transient errors on
589
+ // restart: that restart produces its own transient errors on
621
590
  // the next poll, which would otherwise re-trigger this same path forever.
622
591
  // D1/D2: while the boot is unproven only a refused connection may advance
623
592
  // the down counter — nothing is listening, so the process is gone. A
@@ -642,40 +611,32 @@ export class Supervisor {
642
611
  catch { }
643
612
  if (this.consecutiveDown < downThreshold)
644
613
  return;
645
- // Down — check debounce and rolling state
646
- if (this.rollingBack)
614
+ // Down — check debounce and restarting state
615
+ if (this.restarting)
647
616
  return;
648
617
  const now = this.deps.getTime ? this.deps.getTime() : Date.now();
649
618
  const debounceMs = this.deps.debounceMs ?? 60000;
650
- if (now - this.lastRollback < debounceMs)
619
+ if (now - this.lastRestart < debounceMs)
651
620
  return;
652
- this.rollingBack = true;
621
+ this.restarting = true;
653
622
  this.consecutiveDown = 0;
654
- this.lastRollback = now;
623
+ this.lastRestart = now;
655
624
  try {
656
- const failed = await this.deps.writeFailed().catch(() => ({ ts: new Date().toISOString().replace(/[:.]/g, '-'), manifest: null }));
657
- const ts = failed?.ts ?? new Date().toISOString().replace(/[:.]/g, '-');
625
+ const ts = new Date().toISOString().replace(/[:.]/g, '-');
658
626
  const logTail = health.logTail ?? '';
659
627
  const gitDiff = await this.collectGitDiff().catch(() => '');
660
- const reportPath = await this.deps.writeReport({ ts, health, action: `rollback — ${health.error ?? 'down'}`, logTail, gitDiff }).catch(() => '');
661
- try {
662
- const summary = await this.deps.rollback();
663
- await this.reportRollbackResult(summary, reportPath);
664
- }
665
- catch (e) {
666
- await this.deps.notify(`rollback failed: ${e?.message ?? String(e)} (report: ${reportPath})`).catch(() => { });
667
- }
668
- // Always attempt to (re)start dsh web — survives reboot even when rollback is a no-op
628
+ const reportPath = await this.deps.writeReport({ ts, health, action: `restart — ${health.error ?? 'down'}`, logTail, gitDiff }).catch(() => '');
629
+ // Always attempt to (re)start dsh web — survives reboot even when the previous boot left nothing behind
669
630
  if (this.deps.restartWeb) {
670
631
  try {
671
632
  await this.deps.restartWeb();
672
- await this.deps.notify(`restarted dsh-web after rollback (report: ${reportPath})`).catch(() => { });
633
+ await this.deps.notify(`restarted dsh-web (report: ${reportPath})`).catch(() => { });
673
634
  }
674
635
  catch (e) {
675
636
  await this.deps.notify(`restart dsh-web failed: ${e?.message ?? String(e)} (report: ${reportPath})`).catch(() => { });
676
637
  }
677
638
  }
678
- await this.deps.notify(`CRASH detected → rollback (report: ${reportPath}, error: ${health.error ?? 'down'})`).catch(() => { });
639
+ await this.deps.notify(`CRASH detected → restart (report: ${reportPath}, error: ${health.error ?? 'down'})`).catch(() => { });
679
640
  const runner = this.getRunDebugAgent();
680
641
  const isInjected = !!this.deps.runDebugAgent;
681
642
  if (isInjected) {
@@ -698,7 +659,7 @@ export class Supervisor {
698
659
  }
699
660
  }
700
661
  finally {
701
- this.rollingBack = false;
662
+ this.restarting = false;
702
663
  }
703
664
  }
704
665
  async start() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ddtcorex/dsh-maestro-core",
3
- "version": "0.12.1",
3
+ "version": "0.13.0",
4
4
  "description": "DSH Web supervisor, settings store, tool guard and sync engine",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -53,8 +53,8 @@ validate first and get explicit user consent before a real swap.
53
53
  Keep the live process and its sessions/settings untouched. If the review
54
54
  webhook conflicts on a bound port, exclude that provider for the candidate
55
55
  or run a no-server composition check instead.
56
- 4. Verify HTTP 200 and the new marker on the candidate. Retain last-known-good
57
- assets until the real swap has passed post-swap checks.
56
+ 4. Verify HTTP 200 and the new marker on the candidate. Keep the previous working tree available
57
+ until the real swap has passed post-swap checks.
58
58
  5. Check the **second** long-lived process, not only `dsh web`: the standalone
59
59
  `dsh-web-supervisor` daemon also caches this package's `lib/*.js` in RAM at
60
60
  start, and it is the process that judges the new boot. A daemon older than
@@ -178,8 +178,8 @@ Do not read the top of an old append-only log as liveness evidence. Instead:
178
178
  3. Check served bytes contain the **new**, unique marker; or make a fresh
179
179
  browser/Playwright probe for the changed UI. Shared third-party markers are
180
180
  not sufficient proof.
181
- 4. If a marker or live behaviour is wrong, restore the retained last-known-good
182
- assets and relaunch with the same guarded process.
181
+ 4. If a marker or live behaviour is wrong, restore the previous working tree
182
+ and relaunch with the same guarded process.
183
183
 
184
184
  ## Never do these
185
185
 
@@ -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
@@ -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