@ddtcorex/dsh-maestro-core 0.14.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 (51) hide show
  1. package/lib/client.js +4 -125
  2. package/lib/debug-agent.js +2 -1
  3. package/lib/plugin.d.ts +1 -0
  4. package/lib/plugin.js +17 -4
  5. package/lib/resume.js +9 -1
  6. package/lib/sync/backup-service.d.ts +13 -0
  7. package/lib/sync/backup-service.js +60 -14
  8. package/lib/sync/hashing.d.ts +13 -0
  9. package/lib/sync/hashing.js +30 -0
  10. package/lib/sync/merge.d.ts +1 -1
  11. package/lib/sync/merge.js +1 -1
  12. package/lib/sync/remote-agent.js +12 -1
  13. package/lib/sync/remote-cache.js +1 -1
  14. package/lib/sync/remote-manifest.d.ts +25 -0
  15. package/lib/sync/remote-manifest.js +49 -2
  16. package/lib/sync/store-root.d.ts +44 -0
  17. package/lib/sync/store-root.js +67 -0
  18. package/lib/sync/sync-service.d.ts +25 -1
  19. package/lib/sync/sync-service.js +117 -12
  20. package/lib/sync/sync-types.d.ts +1 -1
  21. package/lib/sync/validation.d.ts +2 -0
  22. package/lib/sync/validation.js +15 -2
  23. package/lib/types/client/config/components/BrandMark.d.ts +1 -1
  24. package/lib/types/client/config/components/BrandMark.d.ts.map +1 -1
  25. package/lib/types/client/config/index.d.ts +0 -1
  26. package/lib/types/client/config/index.d.ts.map +1 -1
  27. package/lib/types/client/config/maestro-mark.d.ts +6 -16
  28. package/lib/types/client/config/maestro-mark.d.ts.map +1 -1
  29. package/lib/types/client/sync/index.d.ts.map +1 -1
  30. package/package.json +1 -1
  31. package/src/client/config/components/BrandMark.tsx +0 -1
  32. package/src/client/config/index.tsx +5 -44
  33. package/src/client/config/maestro-mark.ts +6 -23
  34. package/src/client/sync/index.tsx +0 -50
  35. package/src/client/sync/ui.tsx +4 -4
  36. package/src/host/debug-agent.ts +2 -1
  37. package/src/host/plugin.ts +19 -5
  38. package/src/host/resume.ts +10 -1
  39. package/src/host/sync/backup-service.ts +67 -14
  40. package/src/host/sync/hashing.ts +34 -1
  41. package/src/host/sync/merge.ts +1 -1
  42. package/src/host/sync/remote-agent.ts +12 -1
  43. package/src/host/sync/remote-cache.ts +1 -1
  44. package/src/host/sync/remote-manifest.ts +49 -2
  45. package/src/host/sync/store-root.ts +83 -0
  46. package/src/host/sync/sync-service.ts +131 -12
  47. package/src/host/sync/sync-types.ts +1 -1
  48. package/src/host/sync/validation.ts +15 -2
  49. package/lib/types/client/config/settings-nav-icon.d.ts +0 -21
  50. package/lib/types/client/config/settings-nav-icon.d.ts.map +0 -1
  51. package/src/client/config/settings-nav-icon.ts +0 -68
@@ -13,37 +13,14 @@ export const MAESTRO_SETTINGS_ORDER = 26
13
13
 
14
14
  // DSH-native redesign — reuses DSH tokens & primitive geometry maximally (see MaestroSettings.tsx).
15
15
  import { MaestroSettingsTab } from './MaestroSettings.js'
16
- import { registerSettingsNavIcon, SETTINGS_NAV_MARKER } from './settings-nav-icon.js'
17
- import { maestroMarkMaskUri } from './components/BrandMark.js'
18
16
 
19
17
  /**
20
- * DSH 0.1.x gives external settings sections a generic gear and exposes no
21
- * icon field in the settings.section contract (mirrors dsh-better-sidebar):
22
- * the marker only claims this plugin's localized row and this CSS paints the
23
- * Maestro M-logo glyph as a currentColor mask so it follows native nav
24
- * hover/active colors at the shell's 16px icon rhythm. The glyph itself is
25
- * declared once in components/BrandMark.tsx — the workspace reference
26
- * implementation.
18
+ * The nav row keeps the shell's default gear. DSH 0.2.x paints a section row
19
+ * through the settings.section.icon slot: the glyph sits inside a wrapping
20
+ * span, so the 0.1.x marker + `::before` mask this plugin used to carry hid
21
+ * nothing and painted a second glyph beside the gear. A custom row icon is a
22
+ * slot registration, not a DOM rewrite, and no Maestro section asks for one.
27
23
  */
28
- const SETTINGS_NAV_CSS = `
29
-
30
- /* maestro: replace the settings-nav fallback gear with the Maestro M-logo glyph — same mark as components/BrandMark.tsx */
31
- [${SETTINGS_NAV_MARKER}] > svg:first-child,
32
- [${SETTINGS_NAV_MARKER}] > svg.zWKi1a_navIcon {
33
- display: none !important;
34
- }
35
-
36
- [${SETTINGS_NAV_MARKER}]::before {
37
- content: '';
38
- flex: none;
39
- width: 16px;
40
- height: 16px;
41
- display: inline-block;
42
- background: currentColor;
43
- -webkit-mask: url("${maestroMarkMaskUri()}") center / contain no-repeat;
44
- mask: url("${maestroMarkMaskUri()}") center / contain no-repeat;
45
- }
46
- `
47
24
 
48
25
  type SlotsApi = {
49
26
  inject(name: string, factory: () => unknown): void
@@ -56,22 +33,10 @@ type RpcCall = (endpoint: string, payload?: unknown, signal?: AbortSignal) => Pr
56
33
 
57
34
  interface ClientCtx {
58
35
  get?(name: string): unknown
59
- effect(fn: () => () => void, label?: string): unknown
60
36
  }
61
37
 
62
38
  export const inject = ['slots', 'connection'] as const
63
39
 
64
- function installNavIconStyle(): () => void {
65
- const tag = document.createElement('style')
66
- tag.dataset.plugin = '@ddtcorex/dsh-maestro-config'
67
- tag.dataset.pluginCss = 'maestro/settings-nav.css'
68
- tag.textContent = SETTINGS_NAV_CSS
69
- document.head.appendChild(tag)
70
- return () => {
71
- document.querySelector('style[data-plugin-css="maestro/settings-nav.css"]')?.remove()
72
- }
73
- }
74
-
75
40
  export function apply(ctx: ClientCtx): void {
76
41
  const slots = ctx.get?.('slots') as SlotsApi | undefined
77
42
  if (slots === undefined) return
@@ -96,10 +61,6 @@ export function apply(ctx: ClientCtx): void {
96
61
  return connection.rpc.call('/dsh-maestro-supervisor-resume', endpoint, payload, signal)
97
62
  }
98
63
 
99
- // Reversible effects: nav-row marker observer + owned style tag.
100
- ctx.effect(() => registerSettingsNavIcon(() => 'Maestro'), 'maestro: settings nav icon')
101
- ctx.effect(installNavIconStyle, 'maestro: settings nav css')
102
-
103
64
  slots.inject('settings.section', () =>
104
65
  slots.register(
105
66
  { name: 'settings.section', id: 'maestro', order: MAESTRO_SETTINGS_ORDER, label: () => 'Maestro', inject: () => ({ configRpcCall, supervisorRpcCall }) },
@@ -1,13 +1,12 @@
1
1
  /**
2
2
  * Maestro M logo — the react-free half of the reference implementation.
3
3
  *
4
- * Split out from `components/BrandMark.tsx` so the glyph declaration and the
5
- * CSS-mask encoding are importable from a test. `BrandMark.tsx` imports react,
6
- * which the client bundler treats as an EXTERNAL with no entry in this
7
- * package's `package.json` — so it cannot be imported from vitest at all, and a
8
- * test that only greps its text would accept a naive `encodeURIComponent` that
9
- * silently changes every rendered mask. This module has no react import, so
10
- * `tests/brand-mark.spec.ts` can assert the exact URI bytes.
4
+ * Split out from `components/BrandMark.tsx` so the glyph declaration is
5
+ * importable from a test: `BrandMark.tsx` imports react, which the client
6
+ * bundler treats as an EXTERNAL with no entry in this package's `package.json`,
7
+ * so it cannot be imported from vitest at all. This module has no react import,
8
+ * so `tests/brand-mark.spec.ts` can still read the declarations a caller builds
9
+ * its glyph from.
11
10
  *
12
11
  * The path itself is duplicated in other Maestro packages and that duplication
13
12
  * is structural — see the header in `components/BrandMark.tsx`.
@@ -19,19 +18,3 @@ export const MAESTRO_MARK_STROKE_WIDTH = 1.6
19
18
 
20
19
  /** Badge tile colour — part of the house pattern documented in AGENTS.md. */
21
20
  export const MAESTRO_BRAND_TILE = '#0A84FF'
22
-
23
- /**
24
- * The exact data-URI the settings-nav row paints as a `currentColor` mask.
25
- *
26
- * Only `<` and `>` are encoded. `encodeURIComponent` would additionally escape
27
- * quotes, slashes and spaces, producing a different URI than the literal this
28
- * replaces — and the row renders through `mask`, so a subtly different URI can
29
- * leave the glyph blank. `tests/brand-mark.spec.ts` pins the bytes.
30
- */
31
- export function maestroMarkMaskUri(): string {
32
- const svg =
33
- `<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='${MAESTRO_MARK_VIEWBOX}' ` +
34
- `fill='none' stroke='black' stroke-width='${MAESTRO_MARK_STROKE_WIDTH}' ` +
35
- `stroke-linecap='round' stroke-linejoin='round'><path d='${MAESTRO_MARK_PATH}'/></svg>`
36
- return `data:image/svg+xml,${svg.replace(/</g, '%3C').replace(/>/g, '%3E')}`
37
- }
@@ -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) }
@@ -71,7 +71,8 @@ async function autoFixKnownPatterns(err: string, exec: (c: string, o?: any) => s
71
71
  return
72
72
  }
73
73
  if (err.includes('ERR_MODULE_NOT_FOUND') || err.includes('Cannot find module')) {
74
- 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']
75
76
  for (const pkg of candidates) {
76
77
  try {
77
78
  const p = `${harnessRoot}/packages/${pkg}/lib/index.js`
@@ -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)
@@ -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`,
@@ -16,6 +16,39 @@ export interface RemoteManifestEntry {
16
16
  mtimeSec: number;
17
17
  }
18
18
 
19
+ /**
20
+ * Raised when the peer has not moved its store to the 4.0 root yet.
21
+ *
22
+ * Before this guard the peer's `find` simply matched nothing, the plan read as
23
+ * "the peer has no memory", and the next push would have looked like the first
24
+ * one. A named refusal is worth more than a silent empty inventory.
25
+ */
26
+ /**
27
+ * Raised when the peer has moved its store out of the DSH home.
28
+ *
29
+ * Sync still addresses memory as `<dshRoot>/maestro-memory` on the sending side, so a
30
+ * push to a moved peer writes into the directory that peer no longer reads, and the
31
+ * transfer reports success. Until the remote scripts learn a second base path, the only
32
+ * honest thing is to refuse: a named refusal is worth more than memories that vanish.
33
+ */
34
+ export class PeerStoreMovedError extends Error {
35
+ readonly code = 'PEER_STORE_MOVED'
36
+ constructor(readonly remotePath: string) {
37
+ super(
38
+ `peer store moved to ${remotePath}: this sync can only write <dshRoot>/maestro-memory, so publishing would be lost. Upgrade this machine's sync before transferring`,
39
+ )
40
+ this.name = 'PeerStoreMovedError'
41
+ }
42
+ }
43
+
44
+ export class StoreNotMigratedError extends Error {
45
+ readonly code = 'STORE_NOT_MIGRATED'
46
+ constructor(readonly remotePath: string) {
47
+ super(`remote store not migrated: ${remotePath} has no migrated-v4 marker; run the new build on that machine first`)
48
+ this.name = 'StoreNotMigratedError'
49
+ }
50
+ }
51
+
19
52
  export function buildRemoteManifestScript(dshRoot: string): string {
20
53
  // Fixed script; dshRoot is the validated absolute root (same trust rule as transport.list).
21
54
  // Cache-aware, READ-ONLY (spec §4.7 clarification, decision C): it consults
@@ -30,7 +63,14 @@ export function buildRemoteManifestScript(dshRoot: string): string {
30
63
  // inside a `do...done` one-liner break bash's parser (verified 2026-09-02).
31
64
  const cache = remoteCachePath(dshRoot);
32
65
  return [
33
- `find ${dshRoot}/dsh-maestro-memory ${dshRoot}/sessions`,
66
+ // Preflight sentinel: no 4.0 marker means the peer still holds the old
67
+ // root, so an empty inventory must not be mistaken for an empty store.
68
+ `if [ ! -f ${dshRoot}/maestro-memory/.maestro-memory/migrated-v4 ] && [ -d ${dshRoot}/dsh-maestro-memory ]; then printf 'STORE_NOT_MIGRATED\\t0\\t0\\t%s\\0' ${dshRoot}/dsh-maestro-memory; exit 0; fi;`,
69
+ // 5.0 moved the store out of the DSH home on the peer. Its `find` below would match
70
+ // nothing and read as "the peer has no memory", exactly the failure the v4 sentinel
71
+ // above exists to prevent.
72
+ `mem_root=${dshRoot}/maestro-memory; if [ -f "$HOME/.maestro-memory/.maestro-memory/migrated-v5.json" ]; then mem_root="$HOME/.maestro-memory"; fi;`,
73
+ `find "$mem_root" ${dshRoot}/sessions`,
34
74
  `\\( -name node_modules -o -name .git -o -name .supervisor -o -name profiles \\) -prune -o -type f -print0`,
35
75
  `| xargs -0 stat --printf='%i %s %.Y %.Z\\t%n\\n' 2>/dev/null`,
36
76
  `| awk -F '\\t' -v root='${dshRoot}/' -v cachefile='${cache}' 'BEGIN{while((getline line < cachefile) > 0){if(line=="")continue; m=split(line,a,"\\t"); if(m>=6){c[a[1]]=(a[2]" "a[3]" "a[4]" "a[5])"\\t"a[6]"\\t"a[3]"\\t"a[4];}} close(cachefile);} {st=$1; rel=$2; sub(root,"",rel); if(rel in c){split(c[rel],e,"\\t"); if(e[1]==st){print "H\\t"rel"\\t"e[2]"\\t"e[3]"\\t"e[4]; next;}} print "M\\t"rel"\\t"st;}'`,
@@ -41,7 +81,8 @@ export function buildRemoteManifestScript(dshRoot: string): string {
41
81
  `printf '%s\\t%s\\t%s\\t%s\\0' "$sha" "$size" "$mtime" "$rel";`,
42
82
  `else`,
43
83
  `rel=\${rest%%$'\\t'*}; st=\${rest#*$'\\t'};`,
44
- `sha=$(sha256sum -- "${dshRoot}/$rel" 2>/dev/null | awk '{print $1}');`,
84
+ `case "$rel" in maestro-memory/*) if [ "$mem_root" != "${dshRoot}/maestro-memory" ]; then full="$mem_root/\${rel#maestro-memory/}"; else full="${dshRoot}/$rel"; fi;; *) full="${dshRoot}/$rel";; esac;`,
85
+ `sha=$(sha256sum -- "$full" 2>/dev/null | awk '{print $1}');`,
45
86
  `set -- $st;`,
46
87
  `printf '%s\\t%s\\t%s\\t%s\\0' "$sha" "$2" "$3" "$rel";`,
47
88
  `fi;`,
@@ -54,6 +95,12 @@ export function parseRemoteManifest(buf: Buffer): RemoteManifestEntry[] {
54
95
  const parts = buf.toString('utf-8').split('\0');
55
96
  for (const part of parts) {
56
97
  if (!part) continue;
98
+ if (part.startsWith('STORE_NOT_MIGRATED\t')) {
99
+ throw new StoreNotMigratedError(part.split('\t').slice(3).join('\t'));
100
+ }
101
+ if (part.startsWith('PEER_STORE_MOVED\t')) {
102
+ throw new PeerStoreMovedError(part.split('\t').slice(3).join('\t'));
103
+ }
57
104
  const [sha, sizeRaw, mtimeRaw, ...rest] = part.split('\t');
58
105
  const p = rest.join('\t');
59
106
  const size = Number(sizeRaw);