@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.
package/README.md CHANGED
@@ -4,7 +4,7 @@ Supervisor for DSH Web resilience — **Phase 1 Guard & Report + Phase 3 Auto-Re
4
4
 
5
5
  Runs **outside** the `pnpm → sh → node` tree (systemd daemon) to survive tree crashes, plus **inside** `dsh web` as a host+client Cordis plugin to auto-resume interrupted sessions and auto-reload the browser after restart.
6
6
 
7
- - **Daemon:** Polls `:3080` every 3s, keeps last-known-good (LKG) snapshots (`~/.dsh/.supervisor/lkg/`, `rotate 3`, `sha256` verify, `df` >500MB guard), auto-rollbacks on crash (`debounce 60s`, `flock` lock), writes `report-<ts>.md` (health + `git diff` + log tail), and notifies via Telegram (loose, never blocks).
7
+ - **Daemon:** Polls `:3080` every 3s, restarts on crash (`debounce 60s`, `flock` lock), writes `report-<ts>.md` (health + `git diff` + log tail), and notifies via Telegram (loose, never blocks).
8
8
  - **Host plugin:** `runAutoResume()` 8s after boot — `findInterrupted` (tail 100) + `findDanglingOpenTurns` (full scan for recent sessions) within `autoResumeWithin` (default 5m) → `agents.resume({resumeSessionId, agentOptions: {provider,model}})` recovered from `request/context` → `followup('continue')`. Loopback RPC `POST /dsh-maestro-supervisor-resume/{scan,resume}` (reachable from loopback; `connection.isLoopback` reports it) for the daemon (`resumeViaRpc`).
9
9
  - **Client plugin:** Hybrid auto-reload — `fetch HEAD /` polling 1s on `offline`/`WebSocket close`/`visibilitychange` → `200` → `location.reload()`. Served as `window.__ModuleLoader__.load` bundle at `/plugins/@ddtcorex/dsh-maestro-core/client.js` via `dsh.client`.
10
10
 
@@ -14,7 +14,7 @@ One package, four host rows and one client bundle.
14
14
 
15
15
  | Module | Source | Row id | Channel | What it does |
16
16
  |---|---|---|---|---|
17
- | Supervisor | `src/host/*.ts` | `maestro-supervisor` | `/dsh-maestro-supervisor-resume` (loopback-reachable) | Crash polling, LKG snapshots, auto-resume, auto-reload |
17
+ | Supervisor | `src/host/*.ts` | `maestro-supervisor` | `/dsh-maestro-supervisor-resume` (loopback-reachable) | Crash polling, restart on crash, auto-resume, auto-reload |
18
18
  | Store | `src/host/store/` | — | — | The namespaced `settings.json` every other module reads and writes |
19
19
  | Config | `src/host/config/` | `maestro-config` | `/dsh-maestro-config` | `maestroConfig` service over the store, backing the Maestro settings card |
20
20
  | Guard | `src/host/guard/` | `dsh-maestro-guard` | `/dsh-maestro-guard` | Rule classification, the approval gate and its journal |
@@ -2,7 +2,7 @@
2
2
  * One-boot-at-a-time guard (spec D4, incident 2026-09-13). Every path that
3
3
  * starts dsh web takes this lock from the moment the restart is issued until
4
4
  * the port answers, so a racing tick, the dsh_web_restart hand-off, or a
5
- * rollback that fires while the first boot is still coming up skips instead of
5
+ * restart that fires while the first boot is still coming up skips instead of
6
6
  * producing the second systemd start that made the incident's log tail toxic.
7
7
  *
8
8
  * The lock is an atomically created file (`O_EXCL`) carrying `{pid, ts}`. An
package/lib/boot-lock.js CHANGED
@@ -5,7 +5,7 @@ import * as os from 'node:os';
5
5
  * One-boot-at-a-time guard (spec D4, incident 2026-09-13). Every path that
6
6
  * starts dsh web takes this lock from the moment the restart is issued until
7
7
  * the port answers, so a racing tick, the dsh_web_restart hand-off, or a
8
- * rollback that fires while the first boot is still coming up skips instead of
8
+ * restart that fires while the first boot is still coming up skips instead of
9
9
  * producing the second systemd start that made the incident's log tail toxic.
10
10
  *
11
11
  * The lock is an atomically created file (`O_EXCL`) carrying `{pid, ts}`. An
package/lib/cli.d.ts CHANGED
@@ -1,31 +1 @@
1
- export interface RestoreResult {
2
- /** Snapshot id that was restored. */
3
- target: string;
4
- /** Files (and symlinks) restored into the live DSH home. */
5
- restored: number;
6
- /** Entries that were not restored, each with a reason. Never silent. */
7
- skipped: Array<{
8
- path: string;
9
- reason: string;
10
- }>;
11
- }
12
- /**
13
- * Copy a chosen LKG snapshot back into the DSH home. Recent snapshots are
14
- * tried newest-first, skipping any that still carry a failing plugin so a
15
- * broken bundle is not restored. `sessions/` and every other runtime-data entry
16
- * is deliberately NOT restored (D1) — session logs are append-only truth and
17
- * rolling them back to a snapshot would drop every turn recorded after that
18
- * snapshot.
19
- *
20
- * Never throws for a per-entry failure: the failures are collected into
21
- * `skipped` and the caller reports them (D2/D4). The only throw left is "there
22
- * is no snapshot at all", which the caller must know about.
23
- *
24
- * @returns the restore summary (snapshot id + what was/was not restored).
25
- */
26
- export declare function rollbackLKG(opts: {
27
- dshHome: string;
28
- lkgRoot: string;
29
- failingPlugin?: string;
30
- }): Promise<RestoreResult>;
31
1
  export declare function runCli(args: string[]): Promise<void>;
package/lib/cli.js CHANGED
@@ -1,162 +1,10 @@
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
- /**
11
- * Make a destination (recursively) writable before overwriting it (D3).
12
- *
13
- * `fs.cpSync` copies into an existing destination file with
14
- * `O_WRONLY|O_CREAT|O_TRUNC`, so a mode-`0400` object fails with EACCES and
15
- * aborts the whole restore — the exact 2026-09-13 failure
16
- * (`EACCES, Permission denied '.../attachments/v1/objects/f8'`). Only entries
17
- * that actually lack the needed bit are chmod-ed, so a healthy tree costs
18
- * stats, not a chmod per file.
19
- */
20
- function makeWritable(target) {
21
- let st;
22
- try {
23
- st = fs.lstatSync(target);
24
- }
25
- catch {
26
- return;
27
- }
28
- if (st.isSymbolicLink())
29
- return;
30
- if (st.isDirectory()) {
31
- if ((st.mode & 0o300) !== 0o300) {
32
- try {
33
- fs.chmodSync(target, st.mode | 0o300);
34
- }
35
- catch { }
36
- }
37
- let names = [];
38
- try {
39
- names = fs.readdirSync(target);
40
- }
41
- catch {
42
- return;
43
- }
44
- for (const name of names)
45
- makeWritable(path.join(target, name));
46
- return;
47
- }
48
- if ((st.mode & 0o200) === 0) {
49
- try {
50
- fs.chmodSync(target, st.mode | 0o200);
51
- }
52
- catch { }
53
- }
54
- }
55
- /** Files (and symlinks) a restore of this source entry would write. */
56
- function countRestorable(srcPath) {
57
- try {
58
- const st = fs.lstatSync(srcPath);
59
- if (st.isDirectory())
60
- return walkFiles(srcPath).length;
61
- return 1;
62
- }
63
- catch {
64
- return 0;
65
- }
66
- }
67
- function walkFiles(dir, base = dir) {
68
- const out = [];
69
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
70
- const full = path.join(dir, entry.name);
71
- if (entry.isDirectory())
72
- out.push(...walkFiles(full, base));
73
- else if (entry.isFile())
74
- out.push(path.relative(base, full));
75
- }
76
- return out;
77
- }
78
- /**
79
- * Copy a chosen LKG snapshot back into the DSH home. Recent snapshots are
80
- * tried newest-first, skipping any that still carry a failing plugin so a
81
- * broken bundle is not restored. `sessions/` and every other runtime-data entry
82
- * is deliberately NOT restored (D1) — session logs are append-only truth and
83
- * rolling them back to a snapshot would drop every turn recorded after that
84
- * snapshot.
85
- *
86
- * Never throws for a per-entry failure: the failures are collected into
87
- * `skipped` and the caller reports them (D2/D4). The only throw left is "there
88
- * is no snapshot at all", which the caller must know about.
89
- *
90
- * @returns the restore summary (snapshot id + what was/was not restored).
91
- */
92
- export async function rollbackLKG(opts) {
93
- const { dshHome, lkgRoot, failingPlugin } = opts;
94
- const entries = fs.existsSync(lkgRoot) ? fs.readdirSync(lkgRoot).sort() : [];
95
- if (!entries.length)
96
- throw new Error('no LKG to rollback to');
97
- const candidates = [...entries].reverse().slice(0, 3);
98
- let chosen;
99
- for (const cand of candidates) {
100
- if (!failingPlugin) {
101
- chosen = cand;
102
- break;
103
- }
104
- try {
105
- const pkgPath = path.join(lkgRoot, cand, 'profiles/web/package.json');
106
- if (!fs.existsSync(pkgPath)) {
107
- chosen = cand;
108
- break;
109
- }
110
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
111
- const bundles = pkg?.dsh?.profile?.bundles ?? [];
112
- const deps = pkg?.dependencies ?? {};
113
- const hasFailing = bundles.some((b) => b.includes(failingPlugin)) || Object.keys(deps).some(k => k.includes(failingPlugin));
114
- if (!hasFailing) {
115
- chosen = cand;
116
- break;
117
- }
118
- console.log(`[supervisor] skipping LKG ${cand} still contains failing plugin ${failingPlugin}`);
119
- }
120
- catch {
121
- chosen = cand;
122
- break;
123
- }
124
- }
125
- const target = chosen ?? entries[entries.length - 1];
126
- const src = path.join(lkgRoot, target);
127
- const skipped = [];
128
- let restored = 0;
129
- for (const entry of fs.readdirSync(src)) {
130
- if (entry === 'manifest.json')
131
- continue;
132
- if (isLkgExcluded(entry)) {
133
- // Legacy snapshots (taken before D1) still carry runtime data. Restoring
134
- // a stale sessions/ over live sessions can lose a log, and a 0400
135
- // attachment blob is what aborted this very path — report, never restore.
136
- skipped.push({ path: entry, reason: 'runtime data excluded from the LKG scope (not required to boot)' });
137
- continue;
138
- }
139
- const srcPath = path.join(src, entry);
140
- const destPath = path.join(dshHome, entry);
141
- try {
142
- // Skip if src and dest are the same file (e.g. symlink to same target like ~/.dsh/AGENTS.md)
143
- try {
144
- if (fs.existsSync(srcPath) && fs.existsSync(destPath) && fs.realpathSync(srcPath) === fs.realpathSync(destPath))
145
- continue;
146
- }
147
- catch { }
148
- makeWritable(destPath);
149
- fs.cpSync(srcPath, destPath, { recursive: true, force: true });
150
- restored += countRestorable(srcPath);
151
- }
152
- catch (e) {
153
- if (isSelfCopyError(String(e?.message ?? '')))
154
- continue;
155
- skipped.push({ path: entry, reason: failureReason(e) });
156
- }
157
- }
158
- return { target, restored, skipped };
159
- }
160
8
  export async function runCli(args) {
161
9
  const cmd = args[2] ?? '--help';
162
10
  if (cmd === '--help' || cmd === '-h' || cmd === 'help') {
@@ -164,7 +12,7 @@ export async function runCli(args) {
164
12
 
165
13
  Commands:
166
14
  daemon Run supervisor daemon (poll every 3s)
167
- status Show health + LKG status
15
+ status Show health
168
16
  resume [--within <dur>] List interrupted sessions (filter by time, e.g. 5m, 30s, 1h)
169
17
  boot-guard acquire|release --pid <pid> Take/release boot.lock + boot-boundary (used by the safe-restart script)
170
18
  `);
@@ -177,18 +25,6 @@ Commands:
177
25
  if (cmd === 'status') {
178
26
  const health = await pollHealth();
179
27
  console.log(`up: ${health.up}, httpCode: ${health.httpCode}, error: ${health.error ?? 'none'}`);
180
- const lkgRoot = path.join(os.homedir(), '.dsh/.supervisor/lkg');
181
- if (fs.existsSync(lkgRoot)) {
182
- const entries = fs.readdirSync(lkgRoot).sort();
183
- console.log(`LKG: ${entries.length} snapshots, latest: ${entries[entries.length - 1] ?? 'none'}`);
184
- if (entries.length) {
185
- const ok = await verifyLKG(path.join(lkgRoot, entries[entries.length - 1])).catch(() => false);
186
- console.log(`latest LKG valid: ${ok}`);
187
- }
188
- }
189
- else {
190
- console.log('LKG: none');
191
- }
192
28
  return;
193
29
  }
194
30
  if (cmd === 'resume') {
@@ -217,14 +53,9 @@ Commands:
217
53
  }
218
54
  if (cmd === 'daemon') {
219
55
  console.log('[supervisor] starting daemon — poll every 3s, Ctrl+C to stop');
220
- const dshHome = path.join(os.homedir(), '.dsh');
221
- const lkgRoot = path.join(os.homedir(), '.dsh/.supervisor/lkg');
222
- const failedRoot = path.join(os.homedir(), '.dsh/.supervisor/failed');
223
56
  const reportsRoot = path.join(os.homedir(), '.dsh/.supervisor/reports');
224
57
  const supervisor = new Supervisor({
225
58
  pollHealth: () => pollHealth(),
226
- writeLKG: () => writeLKG(dshHome, lkgRoot),
227
- writeFailed: () => writeLKG(dshHome, failedRoot),
228
59
  writeReport: async ({ ts, health, action, logTail, gitDiff }) => {
229
60
  const { writeReport, collectGitDiff } = await import('./report.js');
230
61
  const { collectLogTail } = await import('./health-poller.js');
@@ -260,37 +91,6 @@ Commands:
260
91
  }
261
92
  return writeReport({ reportsRoot, ts, health, gitDiff: diff, logTail: tail, action });
262
93
  },
263
- rollback: async () => {
264
- const { execSync } = await import('node:child_process');
265
- // Extract failing plugin from current log tail if possible
266
- let failingPlugin;
267
- try {
268
- const tail = fs.readFileSync(path.join(os.homedir(), '.dsh/dsh-web.log'), 'utf8').slice(-5000);
269
- const m = tail.match(/@ddtcorex\/dsh-maestro-[a-z0-9_-]+/i) ?? tail.match(/dsh-maestro-[a-z0-9_-]+/i);
270
- if (m)
271
- failingPlugin = m[0].replace(/^@ddtcorex\//, '');
272
- }
273
- catch { }
274
- const res = await rollbackLKG({ dshHome, lkgRoot, failingPlugin });
275
- console.log(`[supervisor] rolled back to ${res.target} — ${res.restored} file(s) restored${failingPlugin ? ` (avoiding ${failingPlugin})` : ''}`);
276
- // D4: a partial restore is surfaced loudly, never silently.
277
- if (res.skipped.length) {
278
- console.log(`[supervisor] ROLLBACK PARTIAL: ${res.skipped.length} entr(ies) not restored`);
279
- for (const s of res.skipped.slice(0, 10))
280
- console.log(`[supervisor] skipped ${s.path}: ${s.reason}`);
281
- if (res.skipped.length > 10)
282
- console.log(`[supervisor] … ${res.skipped.length - 10} more`);
283
- }
284
- // Reconcile node_modules from restored package.json (critical for link: deps)
285
- try {
286
- execSync('pnpm --dir ~/.dsh/profiles/web install --silent', { timeout: 30000, stdio: 'pipe' });
287
- console.log('[supervisor] pnpm install reconciled profiles/web');
288
- }
289
- catch (e) {
290
- console.log(`[supervisor] pnpm install failed: ${e?.message ?? String(e)}`);
291
- }
292
- return res;
293
- },
294
94
  restartWeb: async () => {
295
95
  // One implementation of the single-boot restart: marker (TTL = boot
296
96
  // 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
@@ -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
@@ -37,14 +37,12 @@ const FILE_TOOLS = new Set([
37
37
  'read',
38
38
  'write',
39
39
  'edit',
40
- 'maestro_read_file',
41
- 'maestro_write_file',
42
40
  'fs_read',
43
41
  'fs_write',
44
42
  'read_file',
45
43
  'write_file',
46
44
  ]);
47
- const WRITE_FILE_TOOLS = new Set(['write', 'edit', 'maestro_write_file', 'fs_write', 'write_file']);
45
+ const WRITE_FILE_TOOLS = new Set(['write', 'edit', 'fs_write', 'write_file']);
48
46
  /** Verbs that actually touch file contents — a protected path next to one is an access. */
49
47
  const ACCESS_VERBS = /\b(cat|bat|head|tail|less|more|cp|scp|rsync|curl|wget|source|tee|dd|install|xxd|base64|openssl|gpg|tar|zip)\b/;
50
48
  /**
@@ -27,7 +27,7 @@ export function getActiveEnterMs() {
27
27
  // Specific parse/boot-failure markers only. Bare 'JSON'/'YAML' were removed
28
28
  // (2026-08-31): they matched any line whose payload merely *contained* those
29
29
  // substrings — e.g. maestro-sync's status JSON listing session.jsonl.zstd /
30
- // settings.json paths — turning a healthy 401 into a rollback + restart.
30
+ // settings.json paths — turning a healthy 401 into a restart.
31
31
  const ERROR_PATTERNS = [
32
32
  'ERR_MODULE_NOT_FOUND',
33
33
  'ERR_PNPM',
@@ -212,7 +212,7 @@ export async function pollHealth(opts = {}) {
212
212
  // post-start crash. With no marker and no scope proving these lines are this
213
213
  // boot's, the scan is inconclusive (D3) instead of inheriting the previous
214
214
  // boot's crash text — that inheritance is what produced the 2026-09-13
215
- // rollback report ("rollback — degraded: This operation was aborted") from a
215
+ // crash report ("restart — degraded: This operation was aborted") from a
216
216
  // healthy, still-booting instance reading the previous boot's EADDRINUSE.
217
217
  const successIdx = lastSuccessMarkerIndex(bootLower);
218
218
  let scanLines;
@@ -293,7 +293,7 @@ export async function pollHealth(opts = {}) {
293
293
  // the same way a genuinely dead one does — but a real crash always frees
294
294
  // the port, while `ss` does not depend on the contended event loop to
295
295
  // answer. Downgrade to DEGRADED (still visible, still escalates after
296
- // repeated ticks) instead of forcing an immediate rollback + restartWeb
296
+ // repeated ticks) instead of forcing an immediate restartWeb
297
297
  // that would kill an in-flight review for nothing.
298
298
  let portAlive = false;
299
299
  try {
package/lib/notifier.js CHANGED
@@ -4,7 +4,7 @@ export async function notify(msg, opts = {}) {
4
4
  await send(msg);
5
5
  }
6
6
  catch {
7
- // never block caller — rollback/report must not fail due to notifier
7
+ // never block caller — restart/report must not fail due to notifier
8
8
  }
9
9
  }
10
10
  async function defaultSend(msg) {
package/lib/report.js CHANGED
@@ -29,8 +29,6 @@ ${opts.logTail.slice(-5000) || '(empty)'}
29
29
 
30
30
  ## Next Steps
31
31
 
32
- - Check \`~/.dsh/.supervisor/lkg/\` for last-known-good
33
- - Review \`failed/${opts.ts}/\` snapshot
34
32
  - If degraded, fix the listed plugin row and run \`pnpm verify\` + dry-boot
35
33
 
36
34
  ---
@@ -28,7 +28,7 @@ export declare function systemdUnitExists(unitPath?: string): boolean;
28
28
  * The direct-node `nohup` fallback exists for portable hosts that have no
29
29
  * systemd unit. When the unit exists, systemd owns the boot: spawning node
30
30
  * behind its back is how a second instance appears — the two starts / one
31
- * rollback report of 2026-09-13. Gate on "the unit does not exist", never on
31
+ * crash report of 2026-09-13. Gate on "the unit does not exist", never on
32
32
  * "this particular start failed".
33
33
  */
34
34
  export declare function shouldUseNohupFallback(unitExists: boolean): boolean;
@@ -51,7 +51,7 @@ export function systemdUnitExists(unitPath = dshWebUnitPath()) {
51
51
  * The direct-node `nohup` fallback exists for portable hosts that have no
52
52
  * systemd unit. When the unit exists, systemd owns the boot: spawning node
53
53
  * behind its back is how a second instance appears — the two starts / one
54
- * rollback report of 2026-09-13. Gate on "the unit does not exist", never on
54
+ * crash report of 2026-09-13. Gate on "the unit does not exist", never on
55
55
  * "this particular start failed".
56
56
  */
57
57
  export function shouldUseNohupFallback(unitExists) {
@@ -17,7 +17,6 @@ export declare function dshWebLogPath(): string;
17
17
  * deliberate no-op so a unit test can never append to the operator's real log.
18
18
  */
19
19
  export declare function markBootBoundary(logPath?: string): void;
20
- export declare function isSelfCopyError(message: string): boolean;
21
20
  export declare const PLANNED_RESTART_TTL_MS = 180000;
22
21
  export declare function isPlannedRestartFresh(mtimeMs: number, nowMs: number, ttlMs?: number): boolean;
23
22
  export declare function plannedRestartPath(): string;
@@ -41,22 +41,12 @@ export function markBootBoundary(logPath) {
41
41
  }
42
42
  catch { }
43
43
  }
44
- // LKG rollback copies each entry with fs.cpSync — an entry that resolves back
45
- // into itself (e.g. a symlink cycle reachable from ~/.dsh, observed in
46
- // production pointing into ~/.npm/_npx/.../node_modules/unist-util-position)
47
- // always throws here. Node's wording for this varies by version ("cannot be
48
- // the same", "subdirectory of itself"/"of self") — match all known phrasings
49
- // so the entry is skipped instead of aborting the whole rollback.
50
- export function isSelfCopyError(message) {
51
- const lower = message.toLowerCase();
52
- return lower.includes('cannot be the same') || lower.includes('subdirectory of');
53
- }
54
44
  // Coordination contract with dsh-safe-web-update's restart-dsh-web.sh (see
55
45
  // <workspace-root>/docs/specs/2026-09-13-supervisor-restart-resilience-design.md):
56
46
  // that script writes this marker right before it intentionally takes dsh-web
57
47
  // down, so the supervisor's own health poll does not mistake a deliberate
58
48
  // restart (kill -> dry-boot -> relaunch, up to ~130s) for a crash and race it
59
- // with its own rollback + restartWeb(). The marker is the JSON {ts, ttl}
49
+ // with its own restartWeb(). The marker is the JSON {ts, ttl}
60
50
  // document at planned-restart.json; a plain mtime-only file is no longer read.
61
51
  export const PLANNED_RESTART_TTL_MS = 180_000;
62
52
  export function isPlannedRestartFresh(mtimeMs, nowMs, ttlMs = PLANNED_RESTART_TTL_MS) {
@@ -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
@@ -82,29 +81,12 @@ export interface FileStat {
82
81
  mtimeMs: number;
83
82
  }
84
83
  /**
85
- * Whether the live plugin tree differs from the latest LKG snapshot. Three
86
- * signals are combined:
87
- *
88
- * 1. manifest drift — the live profile's web `package.json` text vs baseline;
89
- * 2. cordis patch drift — the live profile's web `cordis.patch.yml` text vs
90
- * baseline (a patch-only config edit changes the boot-time row wiring
91
- * without touching the manifest — the manifest check alone misses it);
92
- * 3. plugin-lib drift — any `@ddtcorex` plugin `lib/` file newer than the
93
- * snapshot moment. Link-installed plugins resolve to the same workspace
94
- * files in both live and LKG, so the stored copies cannot be compared
95
- * byte-wise; the snapshot itself is the meaningful baseline and a rebuilt
96
- * `lib/` bumps a file past it even when the manifest text is unchanged.
97
- * writeLKG writes `manifest.json` LAST, so its FILE mtime is the
98
- * authoritative snapshot moment; the snapshot dir mtime is only a
99
- * fallback for legacy snapshots without a manifest.
100
- *
101
- * `statFile` (default `statSync`) reads the metadata so tests can inject a
102
- * controlled reader instead of relying on filesystem utimes (which CI runners
103
- * do not reliably reflect). No LKG baseline, a missing file on either side, or
104
- * any stat/read error means "changed" — the caller falls back to the dry-boot
105
- * gate.
84
+ * Whether the live plugin tree differs from the last boot. There is no
85
+ * snapshot baseline anymore, so this always reports "changed" and the caller
86
+ * always runs the dry-boot gate. `pluginChanged: false` still skips the gate
87
+ * explicitly; anything else boots the candidate first.
106
88
  */
107
- export declare function isPluginTreeChanged(harnessRoot: string, lkgDir?: string, opts?: {
89
+ export declare function isPluginTreeChanged(harnessRoot: string, _baselineDir?: string, _opts?: {
108
90
  statFile?: (p: string) => FileStat;
109
91
  }): boolean;
110
92
  /**
@@ -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
@@ -13,7 +12,7 @@
13
12
  * (out-of-band). This tool NEVER restarts the host in-tree.
14
13
  */
15
14
  import { join, dirname, resolve } from 'node:path';
16
- import { mkdtempSync, rmSync, cpSync, existsSync, readFileSync, readdirSync, statSync, lstatSync, readlinkSync, symlinkSync, unlinkSync } from 'node:fs';
15
+ import { mkdtempSync, rmSync, cpSync, existsSync, readFileSync, readdirSync, lstatSync, readlinkSync, symlinkSync, unlinkSync } from 'node:fs';
17
16
  import { tmpdir, homedir } from 'node:os';
18
17
  import { spawn, execFileSync } from 'node:child_process';
19
18
  import { createRequire } from 'node:module';
@@ -211,86 +210,14 @@ export function dryBootFailureDetail(tail, exitCode) {
211
210
  return `dry-boot failed (exit ${exitCode})`;
212
211
  }
213
212
  /**
214
- * Whether the live plugin tree differs from the latest LKG snapshot. Three
215
- * signals are combined:
216
- *
217
- * 1. manifest drift — the live profile's web `package.json` text vs baseline;
218
- * 2. cordis patch drift — the live profile's web `cordis.patch.yml` text vs
219
- * baseline (a patch-only config edit changes the boot-time row wiring
220
- * without touching the manifest — the manifest check alone misses it);
221
- * 3. plugin-lib drift — any `@ddtcorex` plugin `lib/` file newer than the
222
- * snapshot moment. Link-installed plugins resolve to the same workspace
223
- * files in both live and LKG, so the stored copies cannot be compared
224
- * byte-wise; the snapshot itself is the meaningful baseline and a rebuilt
225
- * `lib/` bumps a file past it even when the manifest text is unchanged.
226
- * writeLKG writes `manifest.json` LAST, so its FILE mtime is the
227
- * authoritative snapshot moment; the snapshot dir mtime is only a
228
- * fallback for legacy snapshots without a manifest.
229
- *
230
- * `statFile` (default `statSync`) reads the metadata so tests can inject a
231
- * controlled reader instead of relying on filesystem utimes (which CI runners
232
- * do not reliably reflect). No LKG baseline, a missing file on either side, or
233
- * any stat/read error means "changed" — the caller falls back to the dry-boot
234
- * gate.
213
+ * Whether the live plugin tree differs from the last boot. There is no
214
+ * snapshot baseline anymore, so this always reports "changed" and the caller
215
+ * always runs the dry-boot gate. `pluginChanged: false` still skips the gate
216
+ * explicitly; anything else boots the candidate first.
235
217
  */
236
- export function isPluginTreeChanged(harnessRoot, lkgDir = join(homedir(), '.dsh/.supervisor/lkg'), opts = {}) {
218
+ export function isPluginTreeChanged(harnessRoot, _baselineDir, _opts = {}) {
237
219
  void harnessRoot;
238
- const statFile = opts.statFile ?? ((p) => statSync(p));
239
- try {
240
- const entries = existsSync(lkgDir) ? readdirSync(lkgDir).sort() : [];
241
- const latest = entries[entries.length - 1];
242
- if (!latest)
243
- return true; // no baseline → assume changed
244
- const lkgHome = join(lkgDir, latest, 'profiles', 'web');
245
- const live = join(homedir(), '.dsh', 'profiles', 'web');
246
- const lkgManifest = join(lkgHome, 'package.json');
247
- const liveManifest = join(live, 'package.json');
248
- if (!existsSync(lkgManifest) || !existsSync(liveManifest))
249
- return true;
250
- if (readFileSync(liveManifest, 'utf8') !== readFileSync(lkgManifest, 'utf8'))
251
- return true;
252
- // cordis.patch.yml — compare only when at least one side has it (profiles
253
- // without a patch are the baseline; a patch appearing on either side alone
254
- // is drift). The text compare keeps the check cheap and hermetic.
255
- const lkgPatch = join(lkgHome, 'cordis.patch.yml');
256
- const livePatch = join(live, 'cordis.patch.yml');
257
- if (existsSync(lkgPatch) || existsSync(livePatch)) {
258
- if (!existsSync(lkgPatch) || !existsSync(livePatch))
259
- return true;
260
- if (readFileSync(livePatch, 'utf8') !== readFileSync(lkgPatch, 'utf8'))
261
- return true;
262
- }
263
- const snapshotManifest = join(lkgDir, latest, 'manifest.json');
264
- const baseline = existsSync(snapshotManifest)
265
- ? statFile(snapshotManifest).mtimeMs
266
- : statFile(join(lkgDir, latest)).mtimeMs;
267
- const livePlugins = join(live, 'node_modules', '@ddtcorex');
268
- if (existsSync(livePlugins)) {
269
- for (const name of readdirSync(livePlugins)) {
270
- const libDir = join(livePlugins, name, 'lib');
271
- if (!existsSync(libDir))
272
- continue;
273
- if (newestFileMtime(libDir, statFile) > baseline)
274
- return true;
275
- }
276
- }
277
- return false;
278
- }
279
- catch {
280
- return true;
281
- }
282
- }
283
- /** Newest mtime under a directory; recursion threads the injected stat reader. */
284
- function newestFileMtime(dir, statFile) {
285
- let newest = 0;
286
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
287
- const p = join(dir, entry.name);
288
- if (entry.isDirectory())
289
- newest = Math.max(newest, newestFileMtime(p, statFile));
290
- else
291
- newest = Math.max(newest, statFile(p).mtimeMs);
292
- }
293
- return newest;
220
+ return true;
294
221
  }
295
222
  function currentSessionId(exec, fallback) {
296
223
  // dsh-tools dispatch hands a ToolRunContext — the exec itself has no
@@ -326,7 +253,7 @@ export function registerRestartTool(ctx, deps = {}) {
326
253
  throw new Error('tools service unavailable');
327
254
  dispose = tools.register({
328
255
  name: 'dsh_web_restart',
329
- 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.',
330
257
  parameters: {
331
258
  type: 'object',
332
259
  properties: {
@@ -358,8 +285,7 @@ export function registerRestartTool(ctx, deps = {}) {
358
285
  return { ok: false, detail: `restart already in progress (requested by ${by}${why}) — check dsh_web_restart_status instead of scheduling another` };
359
286
  }
360
287
  const harnessRoot = deps.harnessRoot ?? (await import('./paths.js')).resolveDeepseekHarnessDir();
361
- const lkgDir = join(homedir(), '.dsh/.supervisor/lkg');
362
- const changed = args.pluginChanged === true || (args.pluginChanged !== false && isPluginTreeChanged(harnessRoot, lkgDir));
288
+ const changed = args.pluginChanged === true || (args.pluginChanged !== false && isPluginTreeChanged(harnessRoot));
363
289
  if (changed) {
364
290
  const gate = await doDryBoot(harnessRoot);
365
291
  if (!gate.ok)