@ddtcorex/dsh-maestro-core 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +3 -3
  2. package/lib/client.js +4 -125
  3. package/lib/debug-agent.d.ts +7 -0
  4. package/lib/debug-agent.js +15 -5
  5. package/lib/dsh-launch.d.ts +26 -0
  6. package/lib/dsh-launch.js +27 -0
  7. package/lib/plugin.d.ts +1 -0
  8. package/lib/plugin.js +17 -4
  9. package/lib/restart-tool.d.ts +3 -1
  10. package/lib/restart-tool.js +8 -4
  11. package/lib/restart-web.d.ts +3 -0
  12. package/lib/restart-web.js +7 -3
  13. package/lib/resume.js +9 -1
  14. package/lib/sync/backup-service.d.ts +13 -0
  15. package/lib/sync/backup-service.js +60 -14
  16. package/lib/sync/hashing.d.ts +13 -0
  17. package/lib/sync/hashing.js +30 -0
  18. package/lib/sync/merge.d.ts +1 -1
  19. package/lib/sync/merge.js +1 -1
  20. package/lib/sync/remote-agent.js +12 -1
  21. package/lib/sync/remote-cache.js +1 -1
  22. package/lib/sync/remote-manifest.d.ts +25 -0
  23. package/lib/sync/remote-manifest.js +49 -2
  24. package/lib/sync/store-root.d.ts +44 -0
  25. package/lib/sync/store-root.js +67 -0
  26. package/lib/sync/sync-service.d.ts +25 -1
  27. package/lib/sync/sync-service.js +117 -12
  28. package/lib/sync/sync-types.d.ts +1 -1
  29. package/lib/sync/validation.d.ts +2 -0
  30. package/lib/sync/validation.js +15 -2
  31. package/lib/types/client/config/components/BrandMark.d.ts +1 -1
  32. package/lib/types/client/config/components/BrandMark.d.ts.map +1 -1
  33. package/lib/types/client/config/index.d.ts +0 -1
  34. package/lib/types/client/config/index.d.ts.map +1 -1
  35. package/lib/types/client/config/maestro-mark.d.ts +6 -16
  36. package/lib/types/client/config/maestro-mark.d.ts.map +1 -1
  37. package/lib/types/client/sync/index.d.ts.map +1 -1
  38. package/package.json +1 -1
  39. package/skills/dsh-safe-restart/SKILL.md +4 -3
  40. package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +20 -36
  41. package/src/client/config/components/BrandMark.tsx +0 -1
  42. package/src/client/config/index.tsx +5 -44
  43. package/src/client/config/maestro-mark.ts +6 -23
  44. package/src/client/sync/index.tsx +0 -50
  45. package/src/client/sync/ui.tsx +4 -4
  46. package/src/host/debug-agent.ts +17 -8
  47. package/src/host/dsh-launch.ts +48 -0
  48. package/src/host/plugin.ts +19 -5
  49. package/src/host/restart-tool.ts +8 -4
  50. package/src/host/restart-web.ts +8 -6
  51. package/src/host/resume.ts +10 -1
  52. package/src/host/sync/backup-service.ts +67 -14
  53. package/src/host/sync/hashing.ts +34 -1
  54. package/src/host/sync/merge.ts +1 -1
  55. package/src/host/sync/remote-agent.ts +12 -1
  56. package/src/host/sync/remote-cache.ts +1 -1
  57. package/src/host/sync/remote-manifest.ts +49 -2
  58. package/src/host/sync/store-root.ts +83 -0
  59. package/src/host/sync/sync-service.ts +131 -12
  60. package/src/host/sync/sync-types.ts +1 -1
  61. package/src/host/sync/validation.ts +15 -2
  62. package/systemd/dsh-web-supervisor.service.template +2 -0
  63. package/systemd/dsh-web.service.template +8 -2
  64. package/lib/types/client/config/settings-nav-icon.d.ts +0 -21
  65. package/lib/types/client/config/settings-nav-icon.d.ts.map +0 -1
  66. package/src/client/config/settings-nav-icon.ts +0 -68
@@ -12,54 +12,6 @@ import { SyncPanel } from './SyncPanel.js'
12
12
 
13
13
  export const inject = ['slots', 'connection'] as const
14
14
 
15
- const SETTINGS_NAV_MARKER = 'data-maestro-sync-settings-nav'
16
- const SETTINGS_NAV_CSS = `
17
- [${SETTINGS_NAV_MARKER}] > svg:first-child,
18
- [${SETTINGS_NAV_MARKER}] > svg.zWKi1a_navIcon {
19
- display: none !important;
20
- }
21
- [${SETTINGS_NAV_MARKER}]::before {
22
- content: '';
23
- flex: none;
24
- width: 16px;
25
- height: 16px;
26
- display: inline-block;
27
- background: currentColor;
28
- -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M2 11 L5 4 L8 9 L11 4 L14 11'/%3E%3C/svg%3E") center / contain no-repeat;
29
- mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M2 11 L5 4 L8 9 L11 4 L14 11'/%3E%3C/svg%3E") center / contain no-repeat;
30
- }
31
- `
32
-
33
- function registerSyncNavIcon(label: () => string, root?: any): () => void {
34
- if (typeof document === 'undefined' && root === undefined) return () => {}
35
- const scope: any = root ?? document
36
- let disposed = false
37
- const sync = () => {
38
- if (disposed) return
39
- const currentLabel = label().trim()
40
- const buttons = scope.querySelectorAll('[role="dialog"] nav button')
41
- for (const button of Array.from(buttons as any) as Element[]) {
42
- const el = button as any
43
- const matches = currentLabel.length > 0 && (button as Element).textContent != null && (button as Element).textContent!.trim() === currentLabel
44
- if (matches) el.setAttribute(SETTINGS_NAV_MARKER, '')
45
- else el.removeAttribute(SETTINGS_NAV_MARKER)
46
- }
47
- }
48
- sync()
49
- let observer: MutationObserver | null = null
50
- if (typeof MutationObserver !== 'undefined') {
51
- observer = new MutationObserver(sync)
52
- observer.observe(document.body, { childList: true, subtree: true, characterData: true })
53
- }
54
- return () => {
55
- disposed = true
56
- if (observer !== null) observer.disconnect()
57
- for (const element of Array.from(scope.querySelectorAll(`[${SETTINGS_NAV_MARKER}]`) as any)) {
58
- ;(element as any).removeAttribute(SETTINGS_NAV_MARKER)
59
- }
60
- }
61
- }
62
-
63
15
  function installStyleTag(css: string, pluginCss: string): () => void {
64
16
  if (typeof document === 'undefined') return () => {}
65
17
  const tag = document.createElement('style')
@@ -312,8 +264,6 @@ function apply(ctx: any): void {
312
264
  const slots = (ctx as any).slots ?? (ctx as any).get?.('slots')
313
265
  if (!slots?.inject || !slots?.register) return
314
266
 
315
- ctx.effect(() => registerSyncNavIcon(() => 'Maestro Sync'), 'maestro-sync: settings nav icon')
316
- ctx.effect(() => installStyleTag(SETTINGS_NAV_CSS, 'maestro-sync/settings-nav.css'), 'maestro-sync: settings nav css')
317
267
  ctx.effect(() => installStyleTag(SYNC_CSS, 'maestro-sync/settings.css'), 'maestro-sync: settings css')
318
268
 
319
269
  ctx.effect(() => {
@@ -241,19 +241,19 @@ export function formatLastSync(v: string | null): string {
241
241
  }
242
242
 
243
243
  export function formatFile(path: string): { icon: IconName; title: string; path: string; meta: string } {
244
- if (path.startsWith('dsh-maestro-memory/daily/')) {
245
- const date = path.replace('dsh-maestro-memory/daily/', '').replace('.md', '')
244
+ if (path.startsWith('maestro-memory/daily/')) {
245
+ const date = path.replace('maestro-memory/daily/', '').replace('.md', '')
246
246
  try {
247
247
  const d = new Date(date)
248
248
  if (!isNaN(d.getTime())) return { icon: 'calendar', title: `Daily notes — ${d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}`, path, meta: 'Daily' }
249
249
  } catch {}
250
250
  return { icon: 'calendar', title: `Daily notes — ${date}`, path, meta: 'Daily' }
251
251
  }
252
- if (path.startsWith('dsh-maestro-memory/projects/')) {
252
+ if (path.startsWith('maestro-memory/projects/')) {
253
253
  const hash = path.split('/')[2] ?? ''
254
254
  return { icon: 'folder', title: 'Project memory', path, meta: hash.slice(0, 7) }
255
255
  }
256
- if (path === 'dsh-maestro-memory/MEMORY.md') return { icon: 'star', title: 'Global memory', path, meta: 'Global' }
256
+ if (path === 'maestro-memory/MEMORY.md') return { icon: 'star', title: 'Global memory', path, meta: 'Global' }
257
257
  if (path.startsWith('sessions/')) {
258
258
  const hash = path.split('/')[1] ?? ''
259
259
  return { icon: 'message', title: 'Session', path, meta: hash.slice(0, 7) }
@@ -1,3 +1,5 @@
1
+ import { resolveDshLaunch, type DshLaunchDeps } from './dsh-launch.js'
2
+
1
3
  export interface DebugAgentOpts {
2
4
  reportPath: string
3
5
  health: { error?: string; httpCode?: number }
@@ -69,7 +71,8 @@ async function autoFixKnownPatterns(err: string, exec: (c: string, o?: any) => s
69
71
  return
70
72
  }
71
73
  if (err.includes('ERR_MODULE_NOT_FOUND') || err.includes('Cannot find module')) {
72
- const candidates = ['dsh-maestro-core', 'dsh-maestro-observe', 'dsh-maestro-memory']
74
+ // memory left the workspace on 2026-11-09 for ~/Work/htdocs/maestro-memory
75
+ const candidates = ['dsh-maestro-core', 'dsh-maestro-observe']
73
76
  for (const pkg of candidates) {
74
77
  try {
75
78
  const p = `${harnessRoot}/packages/${pkg}/lib/index.js`
@@ -109,20 +112,26 @@ function defaultWriteFile(p: string, c: string): void {
109
112
  writeFileSync(p, c, 'utf-8')
110
113
  }
111
114
 
115
+ /**
116
+ * The bounded dry-boot probe: boot `dsh web` on `tmp` as DSH_HOME and an
117
+ * ephemeral port, poll for 200, print ok/fail. The boot follows
118
+ * `resolveDshLaunch`, so a packaged host verifies the runtime it runs.
119
+ */
120
+ export function buildDryBootCommand(tmp: string, port: number, deps: DshLaunchDeps = {}): string {
121
+ const launch = resolveDshLaunch(['web', '--port', String(port), '--no-open'], deps)
122
+ const argv = [launch.command, ...launch.args].map(a => JSON.stringify(a)).join(' ')
123
+ const boot = `${launch.cwd ? `cd ${JSON.stringify(launch.cwd)} && ` : ''}DSH_HOME=${tmp} ${argv} >${tmp}/dsh.log 2>&1 &`
124
+ return `timeout 8 bash -c '${boot} pid=$!; for i in $(seq 1 5); do sleep 1; if curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:${port}/ 2>&1 | grep -q 200; then echo ok; exit 0; fi; done; echo fail; exit 1'`
125
+ }
126
+
112
127
  async function defaultDryBoot(): Promise<boolean> {
113
128
  const { execSync } = await import('node:child_process')
114
- const { resolveDeepseekHarnessDir } = await import('./paths.js')
115
129
  const { buildKillStalePortsCommand } = await import('./restart-guards.js')
116
130
  const port = Math.floor(19000 + Math.random() * 1000)
117
131
  let tmp = ''
118
132
  try {
119
- const deepseekDir = resolveDeepseekHarnessDir()
120
133
  tmp = execSync('mktemp -d', { encoding: 'utf-8' }).trim()
121
- // Use spawn-based dry-boot to avoid nested quoting hell (prev \\$! / \\$(seq) caused syntax error)
122
- const out = execSync(
123
- `timeout 8 bash -c 'DSH_HOME=${tmp} pnpm --dir ${deepseekDir} dsh web --port ${port} --no-open >${tmp}/dsh.log 2>&1 & pid=$!; for i in $(seq 1 5); do sleep 1; if curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:${port}/ 2>&1 | grep -q 200; then echo ok; exit 0; fi; done; echo fail; exit 1'`,
124
- { encoding: 'utf-8', timeout: 12000 },
125
- )
134
+ const out = execSync(buildDryBootCommand(tmp, port), { encoding: 'utf-8', timeout: 12000 })
126
135
  return out.includes('ok')
127
136
  } catch {
128
137
  return false
@@ -0,0 +1,48 @@
1
+ import { resolveDeepseekHarnessDir } from './paths.js'
2
+
3
+ /**
4
+ * How to start the `dsh` CLI on this host. `DSH_BIN` (the installed package's
5
+ * bin, e.g. `~/.local/share/dsh/current/bin/dsh`) is the single switch: set,
6
+ * the packaged runtime runs through the current node; unset, the source
7
+ * checkout runs through tsx, which is how hosts without a packaged install
8
+ * have always booted.
9
+ */
10
+ export interface DshLaunch {
11
+ command: string
12
+ args: string[]
13
+ cwd?: string
14
+ }
15
+
16
+ export interface DshLaunchDeps {
17
+ env?: Record<string, string | undefined>
18
+ execPath?: string
19
+ sourceDir?: string
20
+ }
21
+
22
+ export function resolveDshLaunch(args: string[], deps: DshLaunchDeps = {}): DshLaunch {
23
+ const env = deps.env ?? process.env
24
+ const command = deps.execPath ?? process.execPath
25
+ const bin = env.DSH_BIN?.trim()
26
+ if (bin) return { command, args: [bin, ...args] }
27
+ return {
28
+ command,
29
+ args: ['--import', 'tsx/esm', 'apps/cli/src/bin.ts', ...args],
30
+ cwd: deps.sourceDir ?? resolveDeepseekHarnessDir(),
31
+ }
32
+ }
33
+
34
+ /** The same launch as a shell fragment (`[cd <dir> && ]exec <argv>`), every word quoted. */
35
+ export function dshLaunchShell(args: string[], deps: DshLaunchDeps = {}): string {
36
+ const launch = resolveDshLaunch(args, deps)
37
+ const argv = [launch.command, ...launch.args].map(a => JSON.stringify(a)).join(' ')
38
+ return launch.cwd ? `cd ${JSON.stringify(launch.cwd)} && exec ${argv}` : `exec ${argv}`
39
+ }
40
+
41
+ /**
42
+ * Whether a process command line is a `dsh web` boot in either form: the
43
+ * source entry (`apps/cli/src/bin.ts web`), the package entry (`lib/bin.js
44
+ * web`) or the installed bin (`.../dsh web`).
45
+ */
46
+ export function isDshWebCommand(cmd: string): boolean {
47
+ return /(?:\bbin\.[jt]s|\/dsh)\s+web(?:\s|$)/.test(cmd)
48
+ }
@@ -597,7 +597,7 @@ export async function activateSessionAgent(
597
597
  ctx: any,
598
598
  sessionId: string,
599
599
  deps: { resolveSessionAgent?: (ctx: any, sessionId: string) => Promise<{ agent?: any; error?: any } | undefined> } = {},
600
- ): Promise<{ agent?: any; via: 'controller' | 'resume' }> {
600
+ ): Promise<{ agent?: any; via: 'controller' | 'resume'; controller: 'resolved' | 'declined' | 'absent' | 'threw' }> {
601
601
  const resolveViaController = deps.resolveSessionAgent ?? (async (c: any, id: string) => {
602
602
  const controller = c?.get?.('sessionController') ?? c?.sessionController
603
603
  if (typeof controller?.resolveAgent !== 'function') return undefined
@@ -605,11 +605,13 @@ export async function activateSessionAgent(
605
605
  })
606
606
  try {
607
607
  const resolved = await resolveViaController(ctx, sessionId)
608
- if (resolved?.agent !== undefined) return { agent: resolved.agent, via: 'controller' }
608
+ if (resolved?.agent !== undefined) return { agent: resolved.agent, via: 'controller', controller: 'resolved' }
609
+ const controller = (ctx?.get?.('sessionController') as any) ?? (ctx as any)?.sessionController
610
+ return { via: 'resume', controller: typeof controller?.resolveAgent === 'function' || deps.resolveSessionAgent !== undefined ? 'declined' : 'absent' }
609
611
  } catch {
610
612
  /* fall through: the resume path owns the ownership retry and prompt delivery */
611
613
  }
612
- return { via: 'resume' }
614
+ return { via: 'resume', controller: 'threw' }
613
615
  }
614
616
 
615
617
  export async function resumeInterrupted(
@@ -738,14 +740,21 @@ export async function resumeInterrupted(
738
740
  const sessionId = id.split('/').pop()!
739
741
  const agents = (ctx.get?.('agents') as any) ?? (ctx as any).agents
740
742
  let agent = agents?.get?.(sessionId)
743
+ // Which branch last produced the agent candidate. The no-agent journal
744
+ // entry reports it, so a silent miss (absent service, empty handle)
745
+ // cannot masquerade as a resume that returned a bad agent.
746
+ let source: 'live' | 'controller' | 'manual' | 'none' = agent === undefined ? 'none' : 'live'
747
+ let controllerState: 'resolved' | 'declined' | 'absent' | 'threw' | 'unprobed' = 'unprobed'
741
748
  if (agent === undefined) {
742
749
  // The activation owner runs FIRST and needs no recovered route: it
743
750
  // resolves provider/model itself while composing the session's preset.
744
751
  const activation = await activateSessionAgent(ctx, sessionId, {
745
752
  ...(deps.resolveSessionAgent !== undefined ? { resolveSessionAgent: deps.resolveSessionAgent } : {}),
746
753
  })
754
+ controllerState = activation.controller
747
755
  if (activation.agent !== undefined) {
748
756
  agent = activation.agent
757
+ source = 'controller'
749
758
  ctx.logger?.info?.(`[supervisor] auto-resume: resolved the agent for ${id} through sessionController`)
750
759
  } else {
751
760
  const { SessionId } = await import('@deepseek-ai/dsh-session' as any).catch(() => ({ SessionId: (s: string) => s as any }))
@@ -829,12 +838,17 @@ export async function resumeInterrupted(
829
838
  throw error
830
839
  }
831
840
  agent = handle?.agent
841
+ source = 'manual'
832
842
  if (agent !== undefined) ctx.logger?.info?.(`[supervisor] auto-resume: re-attached agent for ${id}`)
833
843
  }
834
844
  }
835
845
  if (typeof agent?.followup !== 'function') {
836
- ctx.logger?.warn?.(`[supervisor] auto-resume: no live agent available for ${id}`)
837
- doLog({ ts: Date.now(), sessionId, kind: 'no-agent', detail: 'agents.resume returned no followup-capable handle' })
846
+ const detail =
847
+ `agents.resume returned no followup-capable handle ` +
848
+ `(source=${source} agents=${agents == null ? 'absent' : 'present'} ` +
849
+ `controller=${controllerState} agentType=${agent === undefined ? 'undefined' : typeof agent})`
850
+ ctx.logger?.warn?.(`[supervisor] auto-resume: no live agent available for ${id} — ${detail}`)
851
+ doLog({ ts: Date.now(), sessionId, kind: 'no-agent', detail })
838
852
  continue
839
853
  }
840
854
  await verifyResumedComposition(sessionId, agent)
@@ -20,6 +20,7 @@ import { createRequire } from 'node:module'
20
20
  import { writeRestartRequest, readRestartRequest } from './restart-guards.js'
21
21
  import { intentPath, readIntent, readRestartOutcome } from './intents.js'
22
22
  import { supervisorDaemonState, describeDaemonState, type DaemonState } from './daemon-freshness.js'
23
+ import { resolveDshLaunch, isDshWebCommand } from './dsh-launch.js'
23
24
 
24
25
  /**
25
26
  * Copy a live profile tree for an isolated dry-boot. A naive recursive copy
@@ -109,7 +110,7 @@ export function listDryBootCandidates(readers: GcReaders = {}): DryBootCandidate
109
110
  const out: DryBootCandidate[] = []
110
111
  for (const p of readProc()) {
111
112
  if (p.pid === selfPid) continue
112
- if (!/bin\.ts web/.test(p.cmd)) continue
113
+ if (!isDshWebCommand(p.cmd)) continue
113
114
  const home = /^DSH_HOME=([^\0]*)/m.exec(p.env)?.[1] ?? ''
114
115
  if (!home.startsWith(join(tmpdir(), 'dsh-dryboot-'))) continue
115
116
  const ports = ssPortsOf(p.pid)
@@ -125,7 +126,9 @@ export function listDryBootCandidates(readers: GcReaders = {}): DryBootCandidate
125
126
  * Boot a copy of the live web profile on an isolated DSH_HOME and verify the
126
127
  * plugin tree loads and serves. Returns ok + a one-line detail for the tool
127
128
  * message. The spawned tree is killed (best-effort) and the temp home removed.
128
- * Unit tests mock this (never spawn a real node boot in tests).
129
+ * Unit tests mock this (never spawn a real node boot in tests). The boot uses
130
+ * `resolveDshLaunch`, so `harnessRoot` (the source checkout) only matters
131
+ * when `DSH_BIN` is unset.
129
132
  *
130
133
  * NOTE (bin.ts finding): the `web` alias already implies `--profile web`, and
131
134
  * the web app's own commander program (no allowUnknownOption) rejects a stray
@@ -144,8 +147,9 @@ export async function dryBootVerify(harnessRoot: string, opts: { timeoutMs?: num
144
147
  copyProfileForDryBoot(liveProfile, join(tmpHome, 'profiles', 'web'))
145
148
  const port = String(9000 + Math.floor(Math.random() * 1000))
146
149
  const url = `http://127.0.0.1:${port}/`
147
- child = spawn('node', ['--import', 'tsx/esm', 'apps/cli/src/bin.ts', 'web', '--no-open', '--port', port], {
148
- cwd: harnessRoot, env: { ...process.env, DSH_HOME: tmpHome }, stdio: ['ignore', 'pipe', 'pipe'],
150
+ const launch = resolveDshLaunch(['web', '--no-open', '--port', port], { sourceDir: harnessRoot })
151
+ child = spawn(launch.command, launch.args, {
152
+ cwd: launch.cwd, env: { ...process.env, DSH_HOME: tmpHome }, stdio: ['ignore', 'pipe', 'pipe'],
149
153
  })
150
154
  child.stdout?.on('data', (d: Buffer) => logs.push(d.toString()))
151
155
  child.stderr?.on('data', (d: Buffer) => logs.push(d.toString()))
@@ -3,7 +3,7 @@ import * as path from 'node:path'
3
3
  import { buildKillStalePortsCommand, writePlannedRestart } from './restart-guards.js'
4
4
  import { serializedSystemdRestart, shouldUseNohupFallback, systemdUnitExists } from './restart-exec.js'
5
5
  import { withBootLock, type BootLockDeps } from './boot-lock.js'
6
- import { resolveDeepseekHarnessDir } from './paths.js'
6
+ import { dshLaunchShell, type DshLaunchDeps } from './dsh-launch.js'
7
7
 
8
8
  /** Boot budget: how long a boot may take before its failures are judged. */
9
9
  export const DEFAULT_BOOT_GRACE_MS = 180_000
@@ -61,12 +61,14 @@ export async function performSingleBootRestart(deps: RestartWebDeps = {}): Promi
61
61
  return { restarted: true }
62
62
  }
63
63
 
64
+ /** The detached last-resort start, appending to the web log. Exported for tests. */
65
+ export function buildNohupCommand(logPath: string, deps: DshLaunchDeps = {}): string {
66
+ const launch = dshLaunchShell(['web', '--no-open'], deps)
67
+ return `setsid nohup bash -c 'export NVM_DIR="$HOME/.nvm"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"; ${launch} >> ${JSON.stringify(logPath)} 2>&1' &`
68
+ }
69
+
64
70
  async function defaultNohup(): Promise<void> {
65
71
  const { execSync } = await import('node:child_process')
66
- const harnessRoot = resolveDeepseekHarnessDir()
67
72
  const logPath = path.join(os.homedir(), '.dsh/dsh-web.log')
68
- execSync(
69
- `setsid nohup bash -c 'export NVM_DIR="$HOME/.nvm"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"; cd ${JSON.stringify(harnessRoot)} && exec node --import tsx/esm apps/cli/src/bin.ts web --no-open >> ${JSON.stringify(logPath)} 2>&1' &`,
70
- { timeout: 5000 },
71
- )
73
+ execSync(buildNohupCommand(logPath), { timeout: 5000 })
72
74
  }
@@ -81,7 +81,16 @@ export async function findInterrupted(dshHome?: string, opts?: FindInterruptedOp
81
81
  try {
82
82
  const obj = JSON.parse(line)
83
83
  foundTime = typeof obj.time === 'number' ? obj.time : undefined
84
- if (obj.type === 'turn/end' && obj.data?.reason?.kind === 'interrupted') { found = true; break }
84
+ // Two shapes mean "this turn never finished":
85
+ // interrupted the host died with the turn in flight
86
+ // aborted/disposed the host shut the turn down on purpose
87
+ // (supervisor restart, graceful stop)
88
+ // `aborted/user` is the person pressing stop and must stay out.
89
+ const reason = obj.data?.reason
90
+ const resumable =
91
+ reason?.kind === 'interrupted' ||
92
+ (reason?.kind === 'aborted' && reason?.reason?.kind === 'disposed')
93
+ if (obj.type === 'turn/end' && resumable) { found = true; break }
85
94
  } catch {}
86
95
  }
87
96
  if (!found) continue
@@ -10,7 +10,8 @@ import * as nodeFs from 'node:fs';
10
10
  import * as path from 'node:path';
11
11
  import { randomBytes, createHash } from 'node:crypto';
12
12
  import { normalizeEligiblePath } from './validation.js';
13
- import { hashFiles } from './hashing.js';
13
+ import { hashFiles, hashWirePaths } from './hashing.js';
14
+ import { localPathForWirePath, resolveStoreRoot } from './store-root.js';
14
15
  import { loadIndex, saveIndex, probeIndex, matchesStat, statFingerprint } from './fingerprint.js';
15
16
  import type { S3ObjectStore } from './s3-object-store.js';
16
17
  import type { BackupTarget } from './backup-config.js';
@@ -54,17 +55,61 @@ export interface SyncFailureLike {
54
55
  const TTL_MS = 60_000;
55
56
 
56
57
  export class BackupService {
57
- constructor(private readonly opts: { localDsh: string; store: S3ObjectStore; target: BackupTarget; previewDir: string; cacheDir: string; fs?: any }) {}
58
+ constructor(private readonly opts: { localDsh: string; storeRoot?: string; store: S3ObjectStore; target: BackupTarget; previewDir: string; cacheDir: string; fs?: any }) {}
59
+
60
+ /**
61
+ * The store may live outside the DSH home. Reads and writes of memory content map
62
+ * through the resolved root; sessions and sync state stay under the DSH home.
63
+ */
64
+ private resolveStoreRoot(): string {
65
+ return (
66
+ this.opts.storeRoot ??
67
+ resolveStoreRoot({ env: { ...process.env, DSH_HOME: this.opts.localDsh } }).root
68
+ );
69
+ }
70
+
71
+ private localPathForWirePath(wirePath: string): string {
72
+ return localPathForWirePath(wirePath, { storeRoot: this.resolveStoreRoot(), localDsh: this.opts.localDsh });
73
+ }
58
74
 
59
75
  blobKey(sha: string): string {
60
76
  return `blobs/sha256/${sha}`;
61
77
  }
62
78
 
79
+ /**
80
+ * A backup taken in the core-first release window would walk a root that does not
81
+ * exist yet, record zero memory files, and report `ok: true`. Refuse instead, with
82
+ * the same sentinel sync uses.
83
+ */
84
+ assertStoreMigrated(): void {
85
+ const fsMod = this.opts.fs ?? nodeFs;
86
+ if (typeof fsMod.existsSync !== 'function') return;
87
+ const storeRoot = this.resolveStoreRoot();
88
+ const exists = (p: string) => {
89
+ try {
90
+ return fsMod.existsSync(p);
91
+ } catch {
92
+ return false;
93
+ }
94
+ };
95
+ if (!exists(storeRoot) && exists(path.join(this.opts.localDsh, 'maestro-memory'))) {
96
+ const error: any = new Error(
97
+ `local store is still at ${path.join(this.opts.localDsh, 'maestro-memory')}; install the current build (its boot migration moves it to ${storeRoot}) before backing up`,
98
+ );
99
+ error.code = 'STORE_NOT_MIGRATED';
100
+ throw error;
101
+ }
102
+ }
103
+
63
104
  listEligibleFiles(): string[] {
105
+ this.assertStoreMigrated();
64
106
  const root = this.opts.localDsh;
107
+ const storeRoot = this.resolveStoreRoot();
65
108
  const fsMod = this.opts.fs ?? nodeFs;
66
109
  const out: string[] = [];
67
- const walk = (dir: string) => {
110
+ // `prefix` is the wire prefix of the directory being walked, so a store outside the
111
+ // DSH home still reports `maestro-memory/...` and passes normalization.
112
+ const walk = (dir: string, prefix = '') => {
68
113
  let ents: any[];
69
114
  try {
70
115
  ents = fsMod.readdirSync(dir, { withFileTypes: true });
@@ -74,9 +119,11 @@ export class BackupService {
74
119
  for (const ent of ents) {
75
120
  const full = path.join(dir, ent.name);
76
121
  if (typeof ent.isDirectory === 'function' && ent.isDirectory()) {
77
- if (!['node_modules', '.git', '.supervisor', 'profiles'].includes(ent.name)) walk(full);
122
+ if (!['node_modules', '.git', '.supervisor', 'profiles'].includes(ent.name)) {
123
+ walk(full, prefix ? `${prefix}/${ent.name}` : ent.name);
124
+ }
78
125
  } else {
79
- const rel = full.slice(root.length + 1).split(path.sep).join('/');
126
+ const rel = (prefix ? `${prefix}/${ent.name}` : ent.name).split(path.sep).join('/');
80
127
  try {
81
128
  normalizeEligiblePath(rel);
82
129
  out.push(rel);
@@ -85,8 +132,10 @@ export class BackupService {
85
132
  }
86
133
  };
87
134
  try {
88
- walk(path.join(root, 'dsh-maestro-memory'));
89
- walk(path.join(root, 'sessions'));
135
+ walk(storeRoot, 'maestro-memory');
136
+ // When the store sits inside the DSH home its files were already collected above,
137
+ // so sessions alone are walked from there.
138
+ walk(path.join(root, 'sessions'), 'sessions');
90
139
  } catch {}
91
140
  return out.sort();
92
141
  }
@@ -117,7 +166,7 @@ export class BackupService {
117
166
  const stale: string[] = [];
118
167
  const local: { path: string; sha256: string; size: number }[] = [];
119
168
  for (const rel of paths) {
120
- const full = path.join(this.opts.localDsh, rel);
169
+ const full = this.localPathForWirePath(rel);
121
170
  try {
122
171
  const st = fsMod.statSync(full, { bigint: true } as any);
123
172
  const e = probeIndex(rel, index);
@@ -127,11 +176,11 @@ export class BackupService {
127
176
  stale.push(rel);
128
177
  }
129
178
  }
130
- const hashed = await hashFiles(fsMod, this.opts.localDsh, stale);
179
+ const hashed = await hashWirePaths(fsMod, { storeRoot: this.resolveStoreRoot(), localDsh: this.opts.localDsh }, stale);
131
180
  for (const f of hashed) {
132
181
  local.push({ path: f.path, sha256: f.sha256, size: f.size });
133
182
  try {
134
- const st = fsMod.statSync(path.join(this.opts.localDsh, f.path), { bigint: true } as any);
183
+ const st = fsMod.statSync(this.localPathForWirePath(f.path), { bigint: true } as any);
135
184
  index.entries[f.path] = { ...statFingerprint(st), sha256: f.sha256 };
136
185
  } catch {}
137
186
  }
@@ -225,7 +274,7 @@ export class BackupService {
225
274
  }
226
275
  if (sha === null) {
227
276
  try {
228
- const buf = fsMod.readFileSync(path.join(this.opts.localDsh, rel));
277
+ const buf = fsMod.readFileSync(this.localPathForWirePath(rel));
229
278
  const b = Buffer.isBuffer(buf) ? buf : Buffer.from(String(buf), 'utf-8');
230
279
  sha = createHash('sha256').update(b).digest('hex');
231
280
  size = b.length;
@@ -286,7 +335,7 @@ export class BackupService {
286
335
  copied++;
287
336
  continue;
288
337
  }
289
- const full = path.join(this.opts.localDsh, f.path);
338
+ const full = this.localPathForWirePath(f.path);
290
339
  let cur: string | null = null;
291
340
  try {
292
341
  cur = createHash('sha256').update(fsMod.readFileSync(full)).digest('hex');
@@ -321,8 +370,12 @@ export class BackupService {
321
370
  try {
322
371
  for (const f of head.manifest.files) {
323
372
  try {
324
- const destBase = req.mode === 'new-dir' ? req.destDir ?? path.join(this.opts.localDsh, 'restored') : this.opts.localDsh;
325
- const outFull = path.join(destBase, f.path);
373
+ // In place means "into the live store", which is the resolved root, not the
374
+ // DSH home. Getting this wrong recreates the legacy directory on restore.
375
+ const outFull =
376
+ req.mode === 'new-dir'
377
+ ? path.join(req.destDir ?? path.join(this.opts.localDsh, 'restored'), f.path)
378
+ : this.localPathForWirePath(f.path);
326
379
  if (req.mode === 'in-place') {
327
380
  try {
328
381
  const cur = createHash('sha256').update(fsMod.readFileSync(outFull)).digest('hex');
@@ -55,4 +55,37 @@ export async function hashFiles(
55
55
  const workers = Array.from({ length: Math.min(concurrency, paths.length) }, () => worker());
56
56
  await Promise.all(workers);
57
57
  return results.sort((a, b) => a.path.localeCompare(b.path));
58
- }
58
+ }
59
+ /**
60
+ * Hash wire paths that live under two different roots.
61
+ *
62
+ * After the store move `maestro-memory/...` is under the store root and `sessions/...`
63
+ * under the DSH home, so one `hashFiles(root, paths)` call cannot cover a mixed list.
64
+ * The wire path is restored on the way out, because every caller reports wire paths.
65
+ */
66
+ export async function hashWirePaths(
67
+ fs: any,
68
+ roots: { storeRoot: string; localDsh: string },
69
+ wirePaths: string[],
70
+ opts: { onFile?: (h: HashOutcome) => void } = {},
71
+ ): Promise<HashOutcome[]> {
72
+ const out: HashOutcome[] = [];
73
+ const groups = new Map<string, string[]>();
74
+ for (const wire of wirePaths) {
75
+ const root = wire.startsWith('maestro-memory/') ? roots.storeRoot : roots.localDsh;
76
+ const bucket = groups.get(root);
77
+ if (bucket) bucket.push(wire);
78
+ else groups.set(root, [wire]);
79
+ }
80
+ for (const [root, wires] of groups) {
81
+ const rel = wires.map((w) => (w.startsWith('maestro-memory/') ? w.slice('maestro-memory/'.length) : w));
82
+ const hashed = await hashFiles(fs, root, rel);
83
+ for (const entry of hashed) {
84
+ const wire = root === roots.storeRoot ? `maestro-memory/${entry.path}` : entry.path;
85
+ const outcome = { ...entry, path: wire };
86
+ opts.onFile?.(outcome as HashOutcome);
87
+ out.push(outcome as HashOutcome);
88
+ }
89
+ }
90
+ return out;
91
+ }
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Core delimited merge for daily/projects/global memory.
3
- * Ported from packages/dsh-maestro-memory/src/host/storage/atomic-store.ts
3
+ * Ported from ~/Work/htdocs/maestro-memory/src/host/storage/atomic-store.ts
4
4
  * with header-aware parsing for DSH sync.
5
5
  */
6
6
 
@@ -147,7 +147,18 @@ while IFS= read -r line; do
147
147
  esac
148
148
  staged="$stage_dir/$rel"
149
149
  [ -f "$staged" ] || { echo "maestro-sync-commit: missing staged artifact: $rel" >&2; fail=1; continue; }
150
- target="$dsh_root/$rel"
150
+ # The peer's store may live outside its DSH home since 5.0. Memory wire paths land in
151
+ # whichever store root that peer actually reads; everything else stays under the DSH
152
+ # home. Resolved once per commit from the peer's own marker, never assumed.
153
+ case "$rel" in
154
+ maestro-memory/*)
155
+ if [ -f "$HOME/.maestro-memory/.maestro-memory/migrated-v5.json" ]; then
156
+ target="$HOME/.maestro-memory/\${rel#maestro-memory/}"
157
+ else
158
+ target="$dsh_root/$rel"
159
+ fi ;;
160
+ *) target="$dsh_root/$rel" ;;
161
+ esac
151
162
  if [ "$expected" = "absent" ]; then
152
163
  if [ -e "$target" ]; then
153
164
  echo "CONCURRENT_MODIFICATION: $rel (target exists, expected absent)" >&2
@@ -54,7 +54,7 @@ export function buildWarmCacheScript(dshRoot: string): string {
54
54
  const cache = remoteCachePath(dshRoot);
55
55
  return [
56
56
  `mkdir -p "${dshRoot}/.maestro-sync";`,
57
- `find ${dshRoot}/dsh-maestro-memory ${dshRoot}/sessions`,
57
+ `find ${dshRoot}/maestro-memory ${dshRoot}/sessions`,
58
58
  `\\( -name node_modules -o -name .git -o -name .supervisor -o -name profiles \\) -prune -o -type f -print0`,
59
59
  `| xargs -0 stat --printf='%i %s %.Y %.Z\\t%n\\0' 2>/dev/null`,
60
60
  `| while IFS= read -r -d '' rec; do`,