@ddtcorex/dsh-maestro-core 0.10.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +31 -12
  2. package/lib/cli.js +0 -2
  3. package/lib/client.js +69 -93
  4. package/lib/config/index.d.ts +11 -4
  5. package/lib/config/index.js +26 -9
  6. package/lib/config/service.d.ts +2 -2
  7. package/lib/config/service.js +2 -2
  8. package/lib/debug-agent.js +1 -1
  9. package/lib/paths.d.ts +8 -0
  10. package/lib/paths.js +22 -0
  11. package/lib/plugin.d.ts +21 -1
  12. package/lib/plugin.js +153 -42
  13. package/lib/restart-guards.js +1 -1
  14. package/lib/restart-tool.js +13 -4
  15. package/lib/resume-log.d.ts +4 -0
  16. package/lib/resume-log.js +13 -4
  17. package/lib/snapshot.d.ts +3 -2
  18. package/lib/snapshot.js +3 -2
  19. package/lib/store/index.js +119 -45
  20. package/lib/supervisor.js +5 -7
  21. package/lib/types/client/config/MaestroSettings.d.ts.map +1 -1
  22. package/package.json +4 -2
  23. package/scripts/build-client.mjs +53 -0
  24. package/scripts/install-systemd.sh +55 -0
  25. package/scripts/sync/bench-preview.mjs +43 -0
  26. package/scripts/sync/cdp-sync-probe.mjs +200 -0
  27. package/scripts/sync/cdp-sync-verify.mjs +169 -0
  28. package/scripts/vendor-store.mjs +104 -0
  29. package/skills/dsh-safe-restart/SKILL.md +2 -2
  30. package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +2 -2
  31. package/src/client/config/MaestroSettings.tsx +8 -139
  32. package/src/client/sync/SyncPanel.tsx +1 -1
  33. package/src/client/sync/index.tsx +4 -4
  34. package/src/host/cli.ts +0 -2
  35. package/src/host/config/index.ts +27 -10
  36. package/src/host/config/service.ts +2 -2
  37. package/src/host/debug-agent.ts +1 -1
  38. package/src/host/paths.ts +21 -0
  39. package/src/host/plugin.ts +140 -30
  40. package/src/host/restart-guards.ts +1 -1
  41. package/src/host/restart-tool.ts +12 -4
  42. package/src/host/resume-log.ts +20 -5
  43. package/src/host/snapshot.ts +3 -2
  44. package/src/host/store/index.ts +120 -33
  45. package/src/host/supervisor.ts +6 -8
  46. package/systemd/dsh-web-keepalive.service.template +12 -0
  47. package/systemd/dsh-web-supervisor.service.template +20 -0
  48. package/systemd/dsh-web.service.template +30 -0
@@ -23,12 +23,19 @@ declare module '@deepseek-ai/cordis' {
23
23
  };
24
24
  }
25
25
  }
26
+ /**
27
+ * Domains this channel may touch: exactly the ones the core Settings card reads
28
+ * and writes (Guard and Supervisor tabs). The store is shared with every other
29
+ * plugin (gitlab token, webhook secret, Telegram bot token, tunnel credentials
30
+ * path), and this channel is reachable from any logged-in browser session, so
31
+ * the allowlist is applied to ALL four endpoints, `list` included. Foreign
32
+ * domains are owned and validated by their own plugins.
33
+ */
34
+ export declare const RPC_DOMAINS: readonly string[];
26
35
  /**
27
36
  * Publish maestroConfig over the shared store + loopback RPC for clients.
28
- * Exposes guard/guardBlacklist/supervisor/notifier domains (Task 1 validators)
29
- * via generic get/set — validation is delegated to the lib's domain validators.
30
- * Host also handles '/dsh-maestro-config/get' and '/dsh-maestro-config/set'
31
- * style calls through the single channel with endpoint dispatch.
37
+ * The RPC serves only RPC_DOMAINS; in-process consumers of `ctx.maestroConfig`
38
+ * keep the full service. Validation is delegated to the store's domain validators.
32
39
  */
33
40
  export declare function apply(ctx: Context): void;
34
41
  export {};
@@ -17,12 +17,25 @@ function fail(message) {
17
17
  },
18
18
  };
19
19
  }
20
+ /**
21
+ * Domains this channel may touch: exactly the ones the core Settings card reads
22
+ * and writes (Guard and Supervisor tabs). The store is shared with every other
23
+ * plugin (gitlab token, webhook secret, Telegram bot token, tunnel credentials
24
+ * path), and this channel is reachable from any logged-in browser session, so
25
+ * the allowlist is applied to ALL four endpoints, `list` included. Foreign
26
+ * domains are owned and validated by their own plugins.
27
+ */
28
+ export const RPC_DOMAINS = ['guard', 'guardBlacklist', 'supervisor'];
29
+ function isAllowed(domain) {
30
+ return RPC_DOMAINS.includes(domain);
31
+ }
32
+ function refuse(domain) {
33
+ return fail(`domain '${domain}' is not available through this channel`);
34
+ }
20
35
  /**
21
36
  * Publish maestroConfig over the shared store + loopback RPC for clients.
22
- * Exposes guard/guardBlacklist/supervisor/notifier domains (Task 1 validators)
23
- * via generic get/set — validation is delegated to the lib's domain validators.
24
- * Host also handles '/dsh-maestro-config/get' and '/dsh-maestro-config/set'
25
- * style calls through the single channel with endpoint dispatch.
37
+ * The RPC serves only RPC_DOMAINS; in-process consumers of `ctx.maestroConfig`
38
+ * keep the full service. Validation is delegated to the store's domain validators.
26
39
  */
27
40
  export function apply(ctx) {
28
41
  const svc = createMaestroConfigService();
@@ -30,28 +43,32 @@ export function apply(ctx) {
30
43
  ctx.effect(() => ctx.connection.rpc.handle(RPC_CHANNEL, async (endpoint, payload) => {
31
44
  const body = (payload ?? {});
32
45
  if (endpoint === 'list') {
33
- return ok({ domains: await svc.listDomains() });
46
+ return ok({ domains: (await svc.listDomains()).filter(isAllowed) });
34
47
  }
35
48
  if (endpoint === 'get') {
36
49
  if (typeof body.domain !== 'string')
37
50
  return fail('domain (string) is required');
38
- // guard / guardBlacklist / supervisor / notifier are all valid domains here
51
+ if (!isAllowed(body.domain))
52
+ return refuse(body.domain);
39
53
  return ok(await svc.get(body.domain));
40
54
  }
41
55
  if (endpoint === 'set') {
42
56
  if (typeof body.domain !== 'string' || typeof body.patch !== 'object' || body.patch === null) {
43
57
  return fail('domain (string) and patch (object) are required');
44
58
  }
59
+ if (!isAllowed(body.domain))
60
+ return refuse(body.domain);
45
61
  await svc.set(body.domain, body.patch);
46
62
  return ok(null);
47
63
  }
48
64
  if (endpoint === 'unset') {
49
- const key = (payload ?? {});
50
- if (typeof body.domain !== 'string' || typeof key.key !== 'string') {
65
+ if (typeof body.domain !== 'string' || typeof body.key !== 'string') {
51
66
  return fail('domain (string) and key (string) are required');
52
67
  }
68
+ if (!isAllowed(body.domain))
69
+ return refuse(body.domain);
53
70
  try {
54
- return ok({ deleted: await svc.unset(body.domain, key.key) });
71
+ return ok({ deleted: await svc.unset(body.domain, body.key) });
55
72
  }
56
73
  catch (e) {
57
74
  return fail(e?.message ?? String(e));
@@ -10,8 +10,8 @@ export interface MaestroConfigService {
10
10
  onChange(cb: (domain: string) => void): () => void;
11
11
  }
12
12
  /**
13
- * Thin facade over @ddtcorex/dsh-maestro-config-lib. `dshHome` defaults to the
14
- * lib's resolution (explicit > DSH_HOME env > ~/.dsh); tests inject a tmpdir.
13
+ * Thin facade over the embedded settings store (`../store`). `dshHome` defaults to the
14
+ * the store's resolution (explicit > DSH_HOME env > ~/.dsh); tests inject a tmpdir.
15
15
  */
16
16
  export declare function createMaestroConfigService(opts?: {
17
17
  dshHome?: string;
@@ -2,8 +2,8 @@ import * as lib from '../store/index.js';
2
2
  // Guard and guardBlacklist writes through the Settings card must always be validated.
3
3
  import '../guard/validators.js';
4
4
  /**
5
- * Thin facade over @ddtcorex/dsh-maestro-config-lib. `dshHome` defaults to the
6
- * lib's resolution (explicit > DSH_HOME env > ~/.dsh); tests inject a tmpdir.
5
+ * Thin facade over the embedded settings store (`../store`). `dshHome` defaults to the
6
+ * the store's resolution (explicit > DSH_HOME env > ~/.dsh); tests inject a tmpdir.
7
7
  */
8
8
  export function createMaestroConfigService(opts) {
9
9
  const libOpts = opts?.dshHome ? { dshHome: opts.dshHome } : undefined;
@@ -81,7 +81,7 @@ async function autoFixKnownPatterns(err, exec, readFile, writeFile) {
81
81
  if (lower.includes('syntaxerror') || lower.includes('yamlparseerror') || lower.includes('json')) {
82
82
  // corrupted settings.json — try restore from bak
83
83
  try {
84
- exec('ls ~/.dsh/maestro/*.bak 2>&1 | head -5', { timeout: 5000 });
84
+ exec('ls ~/.dsh/dsh-maestro-config/*.bak 2>&1 | head -5', { timeout: 5000 });
85
85
  }
86
86
  catch { }
87
87
  return;
package/lib/paths.d.ts CHANGED
@@ -11,3 +11,11 @@ export declare function resolveDeepseekHarnessDir(): string;
11
11
  * — so no call site has to assume a workspace layout.
12
12
  */
13
13
  export declare function resolveSupervisorPackageDir(): string;
14
+ /**
15
+ * Read the shared settings document synchronously from the canonical store
16
+ * path, `<dsh home>/dsh-maestro-config/settings.json` (`DSH_HOME` wins over
17
+ * `~/.dsh`, matching the store). The retired `<dsh home>/maestro/settings.json`
18
+ * is consulted only when the canonical file does not exist. Returns `undefined`
19
+ * when neither file is present or the chosen one is unreadable.
20
+ */
21
+ export declare function readSettingsDocSync(): any;
package/lib/paths.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import * as fs from 'node:fs';
2
2
  import * as path from 'node:path';
3
+ import * as os from 'node:os';
3
4
  /**
4
5
  * Resolve Maestro Harness root without hardcoding a machine-specific home path.
5
6
  * Priority: env > walk up from current file > cwd check > homedir fallback (last resort).
@@ -68,3 +69,24 @@ export function resolveSupervisorPackageDir() {
68
69
  // production, `src/host/` from vitest. Only used when the walk above fails.
69
70
  return path.resolve(here, '..');
70
71
  }
72
+ /**
73
+ * Read the shared settings document synchronously from the canonical store
74
+ * path, `<dsh home>/dsh-maestro-config/settings.json` (`DSH_HOME` wins over
75
+ * `~/.dsh`, matching the store). The retired `<dsh home>/maestro/settings.json`
76
+ * is consulted only when the canonical file does not exist. Returns `undefined`
77
+ * when neither file is present or the chosen one is unreadable.
78
+ */
79
+ export function readSettingsDocSync() {
80
+ const home = process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh');
81
+ const canonical = path.join(home, 'dsh-maestro-config', 'settings.json');
82
+ const legacy = path.join(home, 'maestro', 'settings.json');
83
+ const chosen = fs.existsSync(canonical) ? canonical : fs.existsSync(legacy) ? legacy : undefined;
84
+ if (!chosen)
85
+ return undefined;
86
+ try {
87
+ return JSON.parse(fs.readFileSync(chosen, 'utf-8'));
88
+ }
89
+ catch {
90
+ return undefined;
91
+ }
92
+ }
package/lib/plugin.d.ts CHANGED
@@ -14,7 +14,22 @@ import { type ToolViewProbeFn, type ToolScopeResolver } from './tool-view.js';
14
14
  export * from './tool-view.js';
15
15
  import { type RepairOutcome } from './preset.js';
16
16
  export * from './preset.js';
17
- export declare const inject: readonly ["sessions", "agents", "connection", "tools", "skills"];
17
+ /**
18
+ * Declared service dependencies.
19
+ *
20
+ * Kept EMPTY on purpose. Every service this plugin uses is resolved lazily with
21
+ * `ctx.get?.(…)`, so a declared `inject` entry buys nothing and costs boot
22
+ * latency: Cordis holds activation of the whole plugin until every named
23
+ * service exists.
24
+ *
25
+ * Measured 2026-10-05 on the live host: with
26
+ * inject: ['sessions','agents','connection','tools','skills'] the boot resume
27
+ * scan fired 343s after the process started — the row waited for the LAST of
28
+ * the five. The scan itself needs none of them (it reads session log files),
29
+ * and the resume path reads sessionController/agents/agentPresets/
30
+ * sessionPersistence optionally and degrades to a journalled skip.
31
+ */
32
+ export declare const inject: readonly ["sessions"];
18
33
  export interface SupervisorPluginConfig {
19
34
  autoResumeWithin?: number | string;
20
35
  autoResumeEnabled?: boolean;
@@ -42,12 +57,17 @@ export type ResumeCoreToolPolicy = 'warn' | 'park';
42
57
  */
43
58
  export declare function isAutoResumePinned(config?: SupervisorPluginConfig): boolean;
44
59
  export declare function getAutoResumeEnabledExported(config?: SupervisorPluginConfig): boolean;
60
+ export declare function processStartedAtMs(): number | undefined;
45
61
  export declare function runAutoResume(ctx: any, opts?: {
46
62
  findInterrupted?: typeof defaultFindInterrupted;
47
63
  findDanglingOpenTurns?: typeof defaultFindDanglingOpenTurns;
48
64
  resumeInterrupted?: typeof resumeInterrupted;
49
65
  logResume?: (entry: ResumeLogEntry) => void;
50
66
  config?: SupervisorPluginConfig;
67
+ /** Boot anchor for the resume window; defaults to this process's own start. */
68
+ processStartedAtMs?: number;
69
+ /** Clock seam for tests. */
70
+ nowMs?: number;
51
71
  }): Promise<void>;
52
72
  export interface RecoveredRoute {
53
73
  provider: string;
package/lib/plugin.js CHANGED
@@ -25,7 +25,22 @@ import { resolveSessionPresetId, makePresetSetup, composedPresetId, repairAgentP
25
25
  export * from './preset.js';
26
26
  import { SUPERVISOR_SOURCE_KIND } from './source.js';
27
27
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
28
- export const inject = ['sessions', 'agents', 'connection', 'tools', 'skills'];
28
+ /**
29
+ * Declared service dependencies.
30
+ *
31
+ * Kept EMPTY on purpose. Every service this plugin uses is resolved lazily with
32
+ * `ctx.get?.(…)`, so a declared `inject` entry buys nothing and costs boot
33
+ * latency: Cordis holds activation of the whole plugin until every named
34
+ * service exists.
35
+ *
36
+ * Measured 2026-10-05 on the live host: with
37
+ * inject: ['sessions','agents','connection','tools','skills'] the boot resume
38
+ * scan fired 343s after the process started — the row waited for the LAST of
39
+ * the five. The scan itself needs none of them (it reads session log files),
40
+ * and the resume path reads sessionController/agents/agentPresets/
41
+ * sessionPersistence optionally and degrades to a journalled skip.
42
+ */
43
+ export const inject = [];
29
44
  function parseDuration(s) {
30
45
  if (!s)
31
46
  return undefined;
@@ -240,6 +255,28 @@ export function isAutoResumePinned(config) {
240
255
  export function getAutoResumeEnabledExported(config) {
241
256
  return getAutoResumeEnabled(config);
242
257
  }
258
+ /**
259
+ * Wall-clock ms at which THIS process started, or `undefined` when it cannot
260
+ * be established.
261
+ *
262
+ * `process.uptime()` is captured once at module load: the plugin module is
263
+ * imported during plugin-tree load, which is the earliest point the supervisor
264
+ * has, and the value never needs refreshing. A restart replaces the process, so
265
+ * the anchor moves with the boot by construction.
266
+ */
267
+ const PROCESS_STARTED_AT_MS = (() => {
268
+ try {
269
+ const up = process.uptime();
270
+ if (typeof up === 'number' && Number.isFinite(up) && up >= 0) {
271
+ return Date.now() - Math.round(up * 1000);
272
+ }
273
+ }
274
+ catch { }
275
+ return undefined;
276
+ })();
277
+ export function processStartedAtMs() {
278
+ return PROCESS_STARTED_AT_MS;
279
+ }
243
280
  export async function runAutoResume(ctx, opts = {}) {
244
281
  try {
245
282
  const doFind = opts.findInterrupted ?? defaultFindInterrupted;
@@ -255,7 +292,29 @@ export async function runAutoResume(ctx, opts = {}) {
255
292
  return;
256
293
  }
257
294
  const withinMs = getResumeWithinMs(opts?.config);
258
- const { scanned, interrupted } = await doFind(undefined, { withinMs });
295
+ // The window must be anchored to the BOOT, not to the moment the scan
296
+ // runs. `withinMs` alone cannot do this: findInterrupted and
297
+ // findDanglingOpenTurns each compute `sinceMs = Date.now() - withinMs` from
298
+ // their own clock, so on a host that takes minutes to finish loading
299
+ // plugins the boundary drifts forward and ages every candidate out before
300
+ // the scan reads it.
301
+ //
302
+ // Measured 2026-10-05: interruption at 18:10:55, new host at 18:11:02,
303
+ // scan at 18:16:45 (343s after boot). The interruption was then 349s old
304
+ // against `autoResumeWithin = 5min`, so nothing was resumed — while the
305
+ // scan itself costs only 130ms for 234 sessions. Passing an explicit
306
+ // `sinceMs` is the only way to pin the boundary, which is what this does.
307
+ const nowMs = opts?.nowMs ?? Date.now();
308
+ const startedAt = opts?.processStartedAtMs ?? PROCESS_STARTED_AT_MS;
309
+ // A caller that cannot supply a boot anchor (the daemon's RPC scan endpoint)
310
+ // keeps the old behaviour, computed here against the injected clock so the
311
+ // boundary is identical rather than left to each scan's own Date.now().
312
+ const anchorMs = (typeof startedAt === 'number' && Number.isFinite(startedAt) && startedAt > 0)
313
+ ? startedAt
314
+ : nowMs;
315
+ const sinceMs = anchorMs - withinMs;
316
+ const scanOpts = { withinMs, sinceMs };
317
+ const { scanned, interrupted } = await doFind(undefined, scanOpts);
259
318
  // Only safe to treat a dangling open turn as crashed right after a fresh
260
319
  // boot, when this process is the sole live owner of these sessions —
261
320
  // exactly the context runAutoResume runs in (called once, 8s after
@@ -263,13 +322,19 @@ export async function runAutoResume(ctx, opts = {}) {
263
322
  // protects any id that happens to be live in *this* process already.
264
323
  let dangling = [];
265
324
  try {
266
- dangling = (await doFindDangling(undefined, { withinMs })).interrupted;
325
+ dangling = (await doFindDangling(undefined, scanOpts)).interrupted;
267
326
  }
268
327
  catch (e) {
269
328
  ctx.logger?.warn?.(`[supervisor] auto-resume: dangling-open-turn scan failed, continuing with closed-turn results only: ${e?.message ?? String(e)}`);
270
329
  }
271
330
  const merged = Array.from(new Set([...interrupted, ...dangling]));
272
- doLog({ ts: Date.now(), kind: 'scan', scanned, interrupted: merged, detail: `withinMs=${withinMs}` });
331
+ doLog({
332
+ ts: Date.now(),
333
+ kind: 'scan',
334
+ scanned,
335
+ interrupted: merged,
336
+ detail: `withinMs=${withinMs} sinceMs=${sinceMs} anchoredAtBoot=${startedAt === anchorMs ? 1 : 0} bootAgeMs=${Math.max(0, nowMs - anchorMs)}`,
337
+ });
273
338
  if (!merged.length) {
274
339
  ctx.logger?.info?.(`[supervisor] auto-resume: 0/${scanned} interrupted within ${withinMs}ms — nothing to do`);
275
340
  return;
@@ -894,8 +959,11 @@ export function registerSessionHealthService(ctx, config = {}) {
894
959
  catch { }
895
960
  }
896
961
  try {
897
- if (typeof ctx.tools?.register === 'function') {
898
- disposers.push(ctx.tools.register(makeSessionHealthToolDef(config)));
962
+ // Resolved lazily (see the `inject` note): a declared 'tools' would hold
963
+ // this plugin's activation until the tools service exists.
964
+ const tools = ctx.get?.('tools') ?? ctx.tools;
965
+ if (typeof tools?.register === 'function') {
966
+ disposers.push(tools.register(makeSessionHealthToolDef(config)));
899
967
  }
900
968
  }
901
969
  catch (e) {
@@ -1005,6 +1073,48 @@ function ensureSystemdKeepalive(ctx) {
1005
1073
  }
1006
1074
  catch { }
1007
1075
  }
1076
+ /**
1077
+ * Run `body` once every service in `names` is active, without holding up this row.
1078
+ *
1079
+ * `inject` is empty on purpose (see its declaration), so the row activates as soon
1080
+ * as its entry loads — before the `tools` and `skills` fibers are active.
1081
+ * `ctx.get` is strict: ReflectService resolves a service only while the fiber
1082
+ * providing it is active, so reading those services during `apply()` returned
1083
+ * undefined and every tool and skill registration was dropped — silently, because
1084
+ * each registration guards on the lookup answering. A child fiber carries its own
1085
+ * inject list and activates on those services independently, which keeps them off
1086
+ * the boot resume scan's dependency path. A host without the registry mixin has no
1087
+ * child-fiber primitive and registers immediately, which is correct when the
1088
+ * services are already active.
1089
+ *
1090
+ * @param ctx — the row's context.
1091
+ * @param names — service names the body needs; each is a separate child fiber's
1092
+ * dependency list, so one absent service cannot suppress the others.
1093
+ * @param body — registration callback, receiving the scoped child context.
1094
+ */
1095
+ function whenServicesActive(ctx, names, body) {
1096
+ try {
1097
+ if (typeof ctx.inject === 'function') {
1098
+ ctx.inject(names, body);
1099
+ return;
1100
+ }
1101
+ }
1102
+ catch (e) {
1103
+ try {
1104
+ ctx.logger?.warn?.(`[supervisor] ${names.join('/')} fiber failed: ${e?.message ?? String(e)}`);
1105
+ }
1106
+ catch { }
1107
+ }
1108
+ try {
1109
+ body(ctx);
1110
+ }
1111
+ catch (e) {
1112
+ try {
1113
+ ctx.logger?.warn?.(`[supervisor] ${names.join('/')} registration failed: ${e?.message ?? String(e)}`);
1114
+ }
1115
+ catch { }
1116
+ }
1117
+ }
1008
1118
  export function apply(ctx, config = {}) {
1009
1119
  // The whole body is wrapped: per AGENTS.md, apply() must never throw
1010
1120
  // synchronously or let a rejected promise escape, no matter what fails
@@ -1015,36 +1125,46 @@ export function apply(ctx, config = {}) {
1015
1125
  ensureSystemdKeepalive(ctx);
1016
1126
  }
1017
1127
  catch { }
1018
- try {
1019
- const skills = ctx.get?.('skills');
1020
- if (skills?.registerProvider) {
1021
- ctx.effect(() => {
1022
- let unregister;
1023
- try {
1024
- // Package-root skills/ is resolved at runtime by walking to the
1025
- // nearest package.json (robust to lib/ vs src/host/ layouts).
1026
- unregister = skills.registerProvider(() => makeSkillProvider(resolveSkillsDir(__dirname)));
1027
- }
1028
- catch (e) {
1029
- ctx.logger?.warn?.(`[supervisor] skill provider failed: ${e?.message ?? String(e)}`);
1030
- }
1031
- return () => { try {
1032
- unregister?.();
1033
- }
1034
- catch { } };
1035
- }, 'supervisor:skill');
1128
+ whenServicesActive(ctx, ['skills'], (scoped) => {
1129
+ const skills = scoped.get?.('skills') ?? scoped.skills;
1130
+ if (!skills?.registerProvider)
1131
+ return;
1132
+ scoped.effect(() => {
1133
+ let unregister;
1134
+ try {
1135
+ // Package-root skills/ is resolved at runtime by walking to the
1136
+ // nearest package.json (robust to lib/ vs src/host/ layouts).
1137
+ unregister = skills.registerProvider(() => makeSkillProvider(resolveSkillsDir(__dirname)));
1138
+ }
1139
+ catch (e) {
1140
+ scoped.logger?.warn?.(`[supervisor] skill provider failed: ${e?.message ?? String(e)}`);
1141
+ }
1142
+ return () => { try {
1143
+ unregister?.();
1144
+ }
1145
+ catch { } };
1146
+ }, 'supervisor:skill');
1147
+ });
1148
+ whenServicesActive(ctx, ['tools'], (scoped) => {
1149
+ try {
1150
+ scoped.effect(() => registerRestartTool(scoped), 'supervisor:restart-tool');
1151
+ }
1152
+ catch (e) {
1153
+ try {
1154
+ scoped.logger?.warn?.(`[supervisor] restart tool effect failed: ${e?.message ?? String(e)}`);
1155
+ }
1156
+ catch { }
1036
1157
  }
1037
- }
1038
- catch { }
1039
- try {
1040
- ctx.effect(() => registerRestartTool(ctx), 'supervisor:restart-tool');
1041
- }
1042
- catch (e) {
1043
1158
  try {
1044
- ctx.logger?.warn?.(`[supervisor] restart tool effect failed: ${e?.message ?? String(e)}`);
1159
+ scoped.effect(() => registerResumeToolHealthService(scoped), 'supervisor:resume-tool-health');
1045
1160
  }
1046
- catch { }
1047
- }
1161
+ catch (e) {
1162
+ try {
1163
+ scoped.logger?.warn?.(`[supervisor] resume-tool-health effect failed: ${e?.message ?? String(e)}`);
1164
+ }
1165
+ catch { }
1166
+ }
1167
+ });
1048
1168
  try {
1049
1169
  ctx.effect(() => registerSessionHealthService(ctx, config), 'supervisor:session-health');
1050
1170
  }
@@ -1054,15 +1174,6 @@ export function apply(ctx, config = {}) {
1054
1174
  }
1055
1175
  catch { }
1056
1176
  }
1057
- try {
1058
- ctx.effect(() => registerResumeToolHealthService(ctx), 'supervisor:resume-tool-health');
1059
- }
1060
- catch (e) {
1061
- try {
1062
- ctx.logger?.warn?.(`[supervisor] resume-tool-health effect failed: ${e?.message ?? String(e)}`);
1063
- }
1064
- catch { }
1065
- }
1066
1177
  ctx.effect(() => {
1067
1178
  let disposed = false;
1068
1179
  let timer = null;
@@ -52,7 +52,7 @@ export function isSelfCopyError(message) {
52
52
  return lower.includes('cannot be the same') || lower.includes('subdirectory of');
53
53
  }
54
54
  // Coordination contract with dsh-safe-web-update's restart-dsh-web.sh (see
55
- // <workspace-root>/docs/specs/2026-08-28-supervisor-planned-restart-design.md):
55
+ // <workspace-root>/docs/specs/2026-09-13-supervisor-restart-resilience-design.md):
56
56
  // that script writes this marker right before it intentionally takes dsh-web
57
57
  // down, so the supervisor's own health poll does not mistake a deliberate
58
58
  // restart (kill -> dry-boot -> relaunch, up to ~130s) for a crash and race it
@@ -310,12 +310,21 @@ export function registerRestartTool(ctx, deps = {}) {
310
310
  const doRead = deps.readRestartRequest ?? readRestartRequest;
311
311
  const doSessionId = deps.sessionIdOf ?? currentSessionId;
312
312
  const readDaemonState = deps.daemonState ?? supervisorDaemonState;
313
+ // `tools` is resolved through ctx.get rather than read off ctx directly.
314
+ // A declared `inject` entry blocks the whole plugin's activation until that
315
+ // service exists, and 'tools' was one of the five that delayed the boot
316
+ // resume scan by minutes on a real host (measured 2026-10-05: 343s). The
317
+ // lookup below works from an already-activated plugin, so the tool can
318
+ // register as soon as `tools` exists without the scan waiting for it.
319
+ const tools = ctx.get?.('tools') ?? ctx.tools;
313
320
  let dispose;
314
321
  let disposeDryboot;
315
322
  let disposeGc;
316
323
  let disposeStatus;
317
324
  try {
318
- dispose = ctx.tools.register({
325
+ if (typeof tools?.register !== 'function')
326
+ throw new Error('tools service unavailable');
327
+ dispose = tools.register({
319
328
  name: 'dsh_web_restart',
320
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.',
321
330
  parameters: {
@@ -389,7 +398,7 @@ export function registerRestartTool(ctx, deps = {}) {
389
398
  catch { }
390
399
  }
391
400
  try {
392
- disposeDryboot = ctx.tools.register({
401
+ disposeDryboot = tools.register({
393
402
  name: 'dsh_web_dryboot',
394
403
  description: 'Validate the plugin tree by booting a copy of the live profile on an ephemeral port. Never schedules or performs a restart; temp home removed afterwards.',
395
404
  parameters: {
@@ -418,7 +427,7 @@ export function registerRestartTool(ctx, deps = {}) {
418
427
  }
419
428
  try {
420
429
  const doKill = deps.killPid ?? ((pid, sig) => process.kill(pid, sig));
421
- disposeGc = ctx.tools.register({
430
+ disposeGc = tools.register({
422
431
  name: 'dsh_web_gc',
423
432
  description: 'Reap orphaned dry-boot dsh web processes (temp DSH_HOME + ephemeral port). Preview-first: returns candidates without killing unless confirm:true.',
424
433
  parameters: {
@@ -463,7 +472,7 @@ export function registerRestartTool(ctx, deps = {}) {
463
472
  catch { }
464
473
  }
465
474
  try {
466
- disposeStatus = ctx.tools.register({
475
+ disposeStatus = tools.register({
467
476
  name: 'dsh_web_restart_status',
468
477
  description: 'Read the outcome of the calling session\u2019s latest scheduled dsh web restart (pending until the daemon swaps and health-checks).',
469
478
  parameters: {
@@ -9,6 +9,10 @@
9
9
  * session logs. This append-only JSONL sidecar gives a machine-local audit
10
10
  * trail of resume outcomes that survives no matter where plugin logs land.
11
11
  * Never throws: a write failure must not break the resume path.
12
+ * The path honours `DSH_HOME`. Resolving `homedir()` alone meant every test
13
+ * touching the resume path appended fixture rows to the OPERATOR's journal —
14
+ * `interrupted: ['proj/a-1', 'proj/shared', 'proj/b-2']`, session ids no machine
15
+ * has. Same trap that overwrote the notifier domain's botToken once already.
12
16
  */
13
17
  export interface ResumeLogEntry {
14
18
  ts: number;
package/lib/resume-log.js CHANGED
@@ -1,14 +1,23 @@
1
1
  import { appendFileSync, mkdirSync, chmodSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { homedir } from 'node:os';
4
+ /** The supervisor's own directory under the active DSH home. */
5
+ function supervisorDir() {
6
+ return join(process.env.DSH_HOME ?? join(homedir(), '.dsh'), '.supervisor');
7
+ }
4
8
  export function resumeLogPath() {
5
- return join(homedir(), '.dsh', '.supervisor', 'resume.log.jsonl');
9
+ return join(supervisorDir(), 'resume.log.jsonl');
6
10
  }
7
11
  export function appendResumeLog(entry) {
8
12
  try {
9
- const p = resumeLogPath();
10
- mkdirSync(join(homedir(), '.dsh', '.supervisor'), { recursive: true });
11
- appendFileSync(p, JSON.stringify(entry) + '\n', 'utf8');
13
+ const dir = supervisorDir();
14
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
15
+ const p = join(dir, 'resume.log.jsonl');
16
+ // The mode goes on the CREATE, not only on the chmod afterwards: a first
17
+ // write would otherwise leave the journal readable by the process umask
18
+ // (0664 measured at umask 002) for as long as the append took. The entry
19
+ // records session ids, so it is never group- or world-readable.
20
+ appendFileSync(p, JSON.stringify(entry) + '\n', { encoding: 'utf8', mode: 0o600 });
12
21
  try {
13
22
  chmodSync(p, 0o600);
14
23
  }
package/lib/snapshot.d.ts CHANGED
@@ -17,7 +17,8 @@ export interface SnapshotDeps {
17
17
  copyFile?: (src: string, dest: string, mode: number) => void;
18
18
  }
19
19
  /**
20
- * DSH-home entries the last-known-good snapshot deliberately never copies.
20
+ * Entries under the harness home directory that the last-known-good snapshot
21
+ * deliberately never copies.
21
22
  *
22
23
  * The LKG exists to recover a boot that fails while loading the plugin tree, so
23
24
  * it holds boot **configuration**: `profiles/` (the plugin tree with its
@@ -41,7 +42,7 @@ export interface SnapshotDeps {
41
42
  */
42
43
  export declare const LKG_EXCLUDED_ENTRIES: readonly string[];
43
44
  /**
44
- * True when a DSH-home-relative path must never enter (or leave) the LKG.
45
+ * True when a path relative to the harness home must never enter (or leave) the LKG.
45
46
  *
46
47
  * The named entries match the first path segment; `*.log` matches by basename
47
48
  * anywhere, because append-only logs are data at any depth and a restored stale
package/lib/snapshot.js CHANGED
@@ -2,7 +2,8 @@ import * as fs from 'node:fs';
2
2
  import * as path from 'node:path';
3
3
  import * as crypto from 'node:crypto';
4
4
  /**
5
- * DSH-home entries the last-known-good snapshot deliberately never copies.
5
+ * Entries under the harness home directory that the last-known-good snapshot
6
+ * deliberately never copies.
6
7
  *
7
8
  * The LKG exists to recover a boot that fails while loading the plugin tree, so
8
9
  * it holds boot **configuration**: `profiles/` (the plugin tree with its
@@ -31,7 +32,7 @@ export const LKG_EXCLUDED_ENTRIES = [
31
32
  '.supervisor',
32
33
  ];
33
34
  /**
34
- * True when a DSH-home-relative path must never enter (or leave) the LKG.
35
+ * True when a path relative to the harness home must never enter (or leave) the LKG.
35
36
  *
36
37
  * The named entries match the first path segment; `*.log` matches by basename
37
38
  * anywhere, because append-only logs are data at any depth and a restored stale