@ddtcorex/dsh-maestro-core 0.14.0 → 0.15.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 (49) 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-cache.js +1 -1
  13. package/lib/sync/remote-manifest.d.ts +12 -0
  14. package/lib/sync/remote-manifest.js +23 -1
  15. package/lib/sync/store-root.d.ts +44 -0
  16. package/lib/sync/store-root.js +67 -0
  17. package/lib/sync/sync-service.d.ts +27 -1
  18. package/lib/sync/sync-service.js +133 -13
  19. package/lib/sync/sync-types.d.ts +1 -1
  20. package/lib/sync/validation.d.ts +2 -0
  21. package/lib/sync/validation.js +15 -2
  22. package/lib/types/client/config/components/BrandMark.d.ts +1 -1
  23. package/lib/types/client/config/components/BrandMark.d.ts.map +1 -1
  24. package/lib/types/client/config/index.d.ts +0 -1
  25. package/lib/types/client/config/index.d.ts.map +1 -1
  26. package/lib/types/client/config/maestro-mark.d.ts +6 -16
  27. package/lib/types/client/config/maestro-mark.d.ts.map +1 -1
  28. package/lib/types/client/sync/index.d.ts.map +1 -1
  29. package/package.json +1 -1
  30. package/src/client/config/components/BrandMark.tsx +0 -1
  31. package/src/client/config/index.tsx +5 -44
  32. package/src/client/config/maestro-mark.ts +6 -23
  33. package/src/client/sync/index.tsx +0 -50
  34. package/src/client/sync/ui.tsx +4 -4
  35. package/src/host/debug-agent.ts +2 -1
  36. package/src/host/plugin.ts +19 -5
  37. package/src/host/resume.ts +10 -1
  38. package/src/host/sync/backup-service.ts +67 -14
  39. package/src/host/sync/hashing.ts +34 -1
  40. package/src/host/sync/merge.ts +1 -1
  41. package/src/host/sync/remote-cache.ts +1 -1
  42. package/src/host/sync/remote-manifest.ts +22 -1
  43. package/src/host/sync/store-root.ts +83 -0
  44. package/src/host/sync/sync-service.ts +148 -13
  45. package/src/host/sync/sync-types.ts +1 -1
  46. package/src/host/sync/validation.ts +15 -2
  47. package/lib/types/client/config/settings-nav-icon.d.ts +0 -21
  48. package/lib/types/client/config/settings-nav-icon.d.ts.map +0 -1
  49. package/src/client/config/settings-nav-icon.ts +0 -68
package/lib/client.js CHANGED
@@ -209,10 +209,6 @@ var MAESTRO_MARK_PATH = "M2 11 L5 4 L8 9 L11 4 L14 11";
209
209
  var MAESTRO_MARK_VIEWBOX = "0 0 16 16";
210
210
  var MAESTRO_MARK_STROKE_WIDTH = 1.6;
211
211
  var MAESTRO_BRAND_TILE = "#0A84FF";
212
- function maestroMarkMaskUri() {
213
- const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='${MAESTRO_MARK_VIEWBOX}' fill='none' stroke='black' stroke-width='${MAESTRO_MARK_STROKE_WIDTH}' stroke-linecap='round' stroke-linejoin='round'><path d='${MAESTRO_MARK_PATH}'/></svg>`;
214
- return `data:image/svg+xml,${svg.replace(/</g, "%3C").replace(/>/g, "%3E")}`;
215
- }
216
212
 
217
213
  // src/client/config/components/BrandMark.tsx
218
214
  var BRAND_BADGE_LAYOUT_KEYS = [
@@ -960,73 +956,8 @@ function MaestroSettingsTab({ configRpcCall, supervisorRpcCall }) {
960
956
  );
961
957
  }
962
958
 
963
- // src/client/config/settings-nav-icon.ts
964
- var SETTINGS_NAV_MARKER = "data-maestro-settings-nav";
965
- function registerSettingsNavIcon(label, root) {
966
- if (typeof document === "undefined" && root === void 0) {
967
- return () => {
968
- };
969
- }
970
- const scope = root ?? document;
971
- let disposed = false;
972
- const sync = () => {
973
- if (disposed) return;
974
- const currentLabel = label().trim();
975
- const buttons = scope.querySelectorAll('[role="dialog"] nav button');
976
- for (const button of Array.from(buttons)) {
977
- const el = button;
978
- const matches = currentLabel.length > 0 && button.textContent != null && button.textContent.trim() === currentLabel;
979
- if (matches) el.setAttribute(SETTINGS_NAV_MARKER, "");
980
- else el.removeAttribute(SETTINGS_NAV_MARKER);
981
- }
982
- };
983
- sync();
984
- let observer = null;
985
- if (typeof MutationObserver !== "undefined") {
986
- observer = new MutationObserver(sync);
987
- observer.observe(document.body, { childList: true, subtree: true, characterData: true });
988
- }
989
- return () => {
990
- disposed = true;
991
- if (observer !== null) observer.disconnect();
992
- for (const element of Array.from(scope.querySelectorAll(`[${SETTINGS_NAV_MARKER}]`))) {
993
- ;
994
- element.removeAttribute(SETTINGS_NAV_MARKER);
995
- }
996
- };
997
- }
998
-
999
959
  // src/client/config/index.tsx
1000
960
  var MAESTRO_SETTINGS_ORDER = 26;
1001
- var SETTINGS_NAV_CSS = `
1002
-
1003
- /* maestro: replace the settings-nav fallback gear with the Maestro M-logo glyph \u2014 same mark as components/BrandMark.tsx */
1004
- [${SETTINGS_NAV_MARKER}] > svg:first-child,
1005
- [${SETTINGS_NAV_MARKER}] > svg.zWKi1a_navIcon {
1006
- display: none !important;
1007
- }
1008
-
1009
- [${SETTINGS_NAV_MARKER}]::before {
1010
- content: '';
1011
- flex: none;
1012
- width: 16px;
1013
- height: 16px;
1014
- display: inline-block;
1015
- background: currentColor;
1016
- -webkit-mask: url("${maestroMarkMaskUri()}") center / contain no-repeat;
1017
- mask: url("${maestroMarkMaskUri()}") center / contain no-repeat;
1018
- }
1019
- `;
1020
- function installNavIconStyle() {
1021
- const tag = document.createElement("style");
1022
- tag.dataset.plugin = "@ddtcorex/dsh-maestro-config";
1023
- tag.dataset.pluginCss = "maestro/settings-nav.css";
1024
- tag.textContent = SETTINGS_NAV_CSS;
1025
- document.head.appendChild(tag);
1026
- return () => {
1027
- document.querySelector('style[data-plugin-css="maestro/settings-nav.css"]')?.remove();
1028
- };
1029
- }
1030
961
  function apply2(ctx) {
1031
962
  const slots = ctx.get?.("slots");
1032
963
  if (slots === void 0) return;
@@ -1040,8 +971,6 @@ function apply2(ctx) {
1040
971
  if (!connection?.rpc?.call) return Promise.reject(new Error("RPC not available"));
1041
972
  return connection.rpc.call("/dsh-maestro-supervisor-resume", endpoint, payload, signal);
1042
973
  };
1043
- ctx.effect(() => registerSettingsNavIcon(() => "Maestro"), "maestro: settings nav icon");
1044
- ctx.effect(installNavIconStyle, "maestro: settings nav css");
1045
974
  slots.inject(
1046
975
  "settings.section",
1047
976
  () => slots.register(
@@ -1232,8 +1161,8 @@ function formatLastSync(v) {
1232
1161
  }
1233
1162
  }
1234
1163
  function formatFile(path) {
1235
- if (path.startsWith("dsh-maestro-memory/daily/")) {
1236
- const date = path.replace("dsh-maestro-memory/daily/", "").replace(".md", "");
1164
+ if (path.startsWith("maestro-memory/daily/")) {
1165
+ const date = path.replace("maestro-memory/daily/", "").replace(".md", "");
1237
1166
  try {
1238
1167
  const d = new Date(date);
1239
1168
  if (!isNaN(d.getTime())) return { icon: "calendar", title: `Daily notes \u2014 ${d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}`, path, meta: "Daily" };
@@ -1241,11 +1170,11 @@ function formatFile(path) {
1241
1170
  }
1242
1171
  return { icon: "calendar", title: `Daily notes \u2014 ${date}`, path, meta: "Daily" };
1243
1172
  }
1244
- if (path.startsWith("dsh-maestro-memory/projects/")) {
1173
+ if (path.startsWith("maestro-memory/projects/")) {
1245
1174
  const hash = path.split("/")[2] ?? "";
1246
1175
  return { icon: "folder", title: "Project memory", path, meta: hash.slice(0, 7) };
1247
1176
  }
1248
- if (path === "dsh-maestro-memory/MEMORY.md") return { icon: "star", title: "Global memory", path, meta: "Global" };
1177
+ if (path === "maestro-memory/MEMORY.md") return { icon: "star", title: "Global memory", path, meta: "Global" };
1249
1178
  if (path.startsWith("sessions/")) {
1250
1179
  const hash = path.split("/")[1] ?? "";
1251
1180
  return { icon: "message", title: "Session", path, meta: hash.slice(0, 7) };
@@ -2516,54 +2445,6 @@ function SyncPanel(props) {
2516
2445
  }
2517
2446
 
2518
2447
  // src/client/sync/index.tsx
2519
- var SETTINGS_NAV_MARKER2 = "data-maestro-sync-settings-nav";
2520
- var SETTINGS_NAV_CSS2 = `
2521
- [${SETTINGS_NAV_MARKER2}] > svg:first-child,
2522
- [${SETTINGS_NAV_MARKER2}] > svg.zWKi1a_navIcon {
2523
- display: none !important;
2524
- }
2525
- [${SETTINGS_NAV_MARKER2}]::before {
2526
- content: '';
2527
- flex: none;
2528
- width: 16px;
2529
- height: 16px;
2530
- display: inline-block;
2531
- background: currentColor;
2532
- -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;
2533
- 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;
2534
- }
2535
- `;
2536
- function registerSyncNavIcon(label, root) {
2537
- if (typeof document === "undefined" && root === void 0) return () => {
2538
- };
2539
- const scope = root ?? document;
2540
- let disposed = false;
2541
- const sync = () => {
2542
- if (disposed) return;
2543
- const currentLabel = label().trim();
2544
- const buttons = scope.querySelectorAll('[role="dialog"] nav button');
2545
- for (const button of Array.from(buttons)) {
2546
- const el = button;
2547
- const matches = currentLabel.length > 0 && button.textContent != null && button.textContent.trim() === currentLabel;
2548
- if (matches) el.setAttribute(SETTINGS_NAV_MARKER2, "");
2549
- else el.removeAttribute(SETTINGS_NAV_MARKER2);
2550
- }
2551
- };
2552
- sync();
2553
- let observer = null;
2554
- if (typeof MutationObserver !== "undefined") {
2555
- observer = new MutationObserver(sync);
2556
- observer.observe(document.body, { childList: true, subtree: true, characterData: true });
2557
- }
2558
- return () => {
2559
- disposed = true;
2560
- if (observer !== null) observer.disconnect();
2561
- for (const element of Array.from(scope.querySelectorAll(`[${SETTINGS_NAV_MARKER2}]`))) {
2562
- ;
2563
- element.removeAttribute(SETTINGS_NAV_MARKER2);
2564
- }
2565
- };
2566
- }
2567
2448
  function installStyleTag(css, pluginCss) {
2568
2449
  if (typeof document === "undefined") return () => {
2569
2450
  };
@@ -2811,8 +2692,6 @@ button[data-sync-stat]:focus-visible { outline: 2px solid var(--dsw-alias-border
2811
2692
  function apply3(ctx) {
2812
2693
  const slots = ctx.slots ?? ctx.get?.("slots");
2813
2694
  if (!slots?.inject || !slots?.register) return;
2814
- ctx.effect(() => registerSyncNavIcon(() => "Maestro Sync"), "maestro-sync: settings nav icon");
2815
- ctx.effect(() => installStyleTag(SETTINGS_NAV_CSS2, "maestro-sync/settings-nav.css"), "maestro-sync: settings nav css");
2816
2695
  ctx.effect(() => installStyleTag(SYNC_CSS, "maestro-sync/settings.css"), "maestro-sync: settings css");
2817
2696
  ctx.effect(() => {
2818
2697
  const dispose = slots.inject(
@@ -58,7 +58,8 @@ async function autoFixKnownPatterns(err, exec, readFile, writeFile) {
58
58
  return;
59
59
  }
60
60
  if (err.includes('ERR_MODULE_NOT_FOUND') || err.includes('Cannot find module')) {
61
- const candidates = ['dsh-maestro-core', 'dsh-maestro-observe', 'dsh-maestro-memory'];
61
+ // memory left the workspace on 2026-11-09 for ~/Work/htdocs/maestro-memory
62
+ const candidates = ['dsh-maestro-core', 'dsh-maestro-observe'];
62
63
  for (const pkg of candidates) {
63
64
  try {
64
65
  const p = `${harnessRoot}/packages/${pkg}/lib/index.js`;
package/lib/plugin.d.ts CHANGED
@@ -177,6 +177,7 @@ export declare function activateSessionAgent(ctx: any, sessionId: string, deps?:
177
177
  }): Promise<{
178
178
  agent?: any;
179
179
  via: 'controller' | 'resume';
180
+ controller: 'resolved' | 'declined' | 'absent' | 'threw';
180
181
  }>;
181
182
  export declare function resumeInterrupted(ctx: any, ids: string[], deps?: {
182
183
  readIntent?: (id: string) => RestartIntent | undefined;
package/lib/plugin.js CHANGED
@@ -577,12 +577,14 @@ export async function activateSessionAgent(ctx, sessionId, deps = {}) {
577
577
  try {
578
578
  const resolved = await resolveViaController(ctx, sessionId);
579
579
  if (resolved?.agent !== undefined)
580
- return { agent: resolved.agent, via: 'controller' };
580
+ return { agent: resolved.agent, via: 'controller', controller: 'resolved' };
581
+ const controller = ctx?.get?.('sessionController') ?? ctx?.sessionController;
582
+ return { via: 'resume', controller: typeof controller?.resolveAgent === 'function' || deps.resolveSessionAgent !== undefined ? 'declined' : 'absent' };
581
583
  }
582
584
  catch {
583
585
  /* fall through: the resume path owns the ownership retry and prompt delivery */
584
586
  }
585
- return { via: 'resume' };
587
+ return { via: 'resume', controller: 'threw' };
586
588
  }
587
589
  export async function resumeInterrupted(ctx, ids, deps = {}) {
588
590
  const doReadIntent = deps.readIntent ?? readIntent;
@@ -695,14 +697,21 @@ export async function resumeInterrupted(ctx, ids, deps = {}) {
695
697
  const sessionId = id.split('/').pop();
696
698
  const agents = ctx.get?.('agents') ?? ctx.agents;
697
699
  let agent = agents?.get?.(sessionId);
700
+ // Which branch last produced the agent candidate. The no-agent journal
701
+ // entry reports it, so a silent miss (absent service, empty handle)
702
+ // cannot masquerade as a resume that returned a bad agent.
703
+ let source = agent === undefined ? 'none' : 'live';
704
+ let controllerState = 'unprobed';
698
705
  if (agent === undefined) {
699
706
  // The activation owner runs FIRST and needs no recovered route: it
700
707
  // resolves provider/model itself while composing the session's preset.
701
708
  const activation = await activateSessionAgent(ctx, sessionId, {
702
709
  ...(deps.resolveSessionAgent !== undefined ? { resolveSessionAgent: deps.resolveSessionAgent } : {}),
703
710
  });
711
+ controllerState = activation.controller;
704
712
  if (activation.agent !== undefined) {
705
713
  agent = activation.agent;
714
+ source = 'controller';
706
715
  ctx.logger?.info?.(`[supervisor] auto-resume: resolved the agent for ${id} through sessionController`);
707
716
  }
708
717
  else {
@@ -796,13 +805,17 @@ export async function resumeInterrupted(ctx, ids, deps = {}) {
796
805
  throw error;
797
806
  }
798
807
  agent = handle?.agent;
808
+ source = 'manual';
799
809
  if (agent !== undefined)
800
810
  ctx.logger?.info?.(`[supervisor] auto-resume: re-attached agent for ${id}`);
801
811
  }
802
812
  }
803
813
  if (typeof agent?.followup !== 'function') {
804
- ctx.logger?.warn?.(`[supervisor] auto-resume: no live agent available for ${id}`);
805
- doLog({ ts: Date.now(), sessionId, kind: 'no-agent', detail: 'agents.resume returned no followup-capable handle' });
814
+ const detail = `agents.resume returned no followup-capable handle ` +
815
+ `(source=${source} agents=${agents == null ? 'absent' : 'present'} ` +
816
+ `controller=${controllerState} agentType=${agent === undefined ? 'undefined' : typeof agent})`;
817
+ ctx.logger?.warn?.(`[supervisor] auto-resume: no live agent available for ${id} — ${detail}`);
818
+ doLog({ ts: Date.now(), sessionId, kind: 'no-agent', detail });
806
819
  continue;
807
820
  }
808
821
  await verifyResumedComposition(sessionId, agent);
package/lib/resume.js CHANGED
@@ -75,7 +75,15 @@ export async function findInterrupted(dshHome, opts) {
75
75
  try {
76
76
  const obj = JSON.parse(line);
77
77
  foundTime = typeof obj.time === 'number' ? obj.time : undefined;
78
- if (obj.type === 'turn/end' && obj.data?.reason?.kind === 'interrupted') {
78
+ // Two shapes mean "this turn never finished":
79
+ // interrupted the host died with the turn in flight
80
+ // aborted/disposed the host shut the turn down on purpose
81
+ // (supervisor restart, graceful stop)
82
+ // `aborted/user` is the person pressing stop and must stay out.
83
+ const reason = obj.data?.reason;
84
+ const resumable = reason?.kind === 'interrupted' ||
85
+ (reason?.kind === 'aborted' && reason?.reason?.kind === 'disposed');
86
+ if (obj.type === 'turn/end' && resumable) {
79
87
  found = true;
80
88
  break;
81
89
  }
@@ -38,13 +38,26 @@ export declare class BackupService {
38
38
  private readonly opts;
39
39
  constructor(opts: {
40
40
  localDsh: string;
41
+ storeRoot?: string;
41
42
  store: S3ObjectStore;
42
43
  target: BackupTarget;
43
44
  previewDir: string;
44
45
  cacheDir: string;
45
46
  fs?: any;
46
47
  });
48
+ /**
49
+ * The store may live outside the DSH home. Reads and writes of memory content map
50
+ * through the resolved root; sessions and sync state stay under the DSH home.
51
+ */
52
+ private resolveStoreRoot;
53
+ private localPathForWirePath;
47
54
  blobKey(sha: string): string;
55
+ /**
56
+ * A backup taken in the core-first release window would walk a root that does not
57
+ * exist yet, record zero memory files, and report `ok: true`. Refuse instead, with
58
+ * the same sentinel sync uses.
59
+ */
60
+ assertStoreMigrated(): void;
48
61
  listEligibleFiles(): string[];
49
62
  readHeadManifest(): Promise<{
50
63
  key: string;
@@ -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 { 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
  const TTL_MS = 60_000;
16
17
  export class BackupService {
@@ -18,14 +19,53 @@ export class BackupService {
18
19
  constructor(opts) {
19
20
  this.opts = opts;
20
21
  }
22
+ /**
23
+ * The store may live outside the DSH home. Reads and writes of memory content map
24
+ * through the resolved root; sessions and sync state stay under the DSH home.
25
+ */
26
+ resolveStoreRoot() {
27
+ return (this.opts.storeRoot ??
28
+ resolveStoreRoot({ env: { ...process.env, DSH_HOME: this.opts.localDsh } }).root);
29
+ }
30
+ localPathForWirePath(wirePath) {
31
+ return localPathForWirePath(wirePath, { storeRoot: this.resolveStoreRoot(), localDsh: this.opts.localDsh });
32
+ }
21
33
  blobKey(sha) {
22
34
  return `blobs/sha256/${sha}`;
23
35
  }
36
+ /**
37
+ * A backup taken in the core-first release window would walk a root that does not
38
+ * exist yet, record zero memory files, and report `ok: true`. Refuse instead, with
39
+ * the same sentinel sync uses.
40
+ */
41
+ assertStoreMigrated() {
42
+ const fsMod = this.opts.fs ?? nodeFs;
43
+ if (typeof fsMod.existsSync !== 'function')
44
+ return;
45
+ const storeRoot = this.resolveStoreRoot();
46
+ const exists = (p) => {
47
+ try {
48
+ return fsMod.existsSync(p);
49
+ }
50
+ catch {
51
+ return false;
52
+ }
53
+ };
54
+ if (!exists(storeRoot) && exists(path.join(this.opts.localDsh, 'maestro-memory'))) {
55
+ const error = new Error(`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`);
56
+ error.code = 'STORE_NOT_MIGRATED';
57
+ throw error;
58
+ }
59
+ }
24
60
  listEligibleFiles() {
61
+ this.assertStoreMigrated();
25
62
  const root = this.opts.localDsh;
63
+ const storeRoot = this.resolveStoreRoot();
26
64
  const fsMod = this.opts.fs ?? nodeFs;
27
65
  const out = [];
28
- const walk = (dir) => {
66
+ // `prefix` is the wire prefix of the directory being walked, so a store outside the
67
+ // DSH home still reports `maestro-memory/...` and passes normalization.
68
+ const walk = (dir, prefix = '') => {
29
69
  let ents;
30
70
  try {
31
71
  ents = fsMod.readdirSync(dir, { withFileTypes: true });
@@ -36,11 +76,12 @@ export class BackupService {
36
76
  for (const ent of ents) {
37
77
  const full = path.join(dir, ent.name);
38
78
  if (typeof ent.isDirectory === 'function' && ent.isDirectory()) {
39
- if (!['node_modules', '.git', '.supervisor', 'profiles'].includes(ent.name))
40
- walk(full);
79
+ if (!['node_modules', '.git', '.supervisor', 'profiles'].includes(ent.name)) {
80
+ walk(full, prefix ? `${prefix}/${ent.name}` : ent.name);
81
+ }
41
82
  }
42
83
  else {
43
- const rel = full.slice(root.length + 1).split(path.sep).join('/');
84
+ const rel = (prefix ? `${prefix}/${ent.name}` : ent.name).split(path.sep).join('/');
44
85
  try {
45
86
  normalizeEligiblePath(rel);
46
87
  out.push(rel);
@@ -50,8 +91,10 @@ export class BackupService {
50
91
  }
51
92
  };
52
93
  try {
53
- walk(path.join(root, 'dsh-maestro-memory'));
54
- walk(path.join(root, 'sessions'));
94
+ walk(storeRoot, 'maestro-memory');
95
+ // When the store sits inside the DSH home its files were already collected above,
96
+ // so sessions alone are walked from there.
97
+ walk(path.join(root, 'sessions'), 'sessions');
55
98
  }
56
99
  catch { }
57
100
  return out.sort();
@@ -84,7 +127,7 @@ export class BackupService {
84
127
  const stale = [];
85
128
  const local = [];
86
129
  for (const rel of paths) {
87
- const full = path.join(this.opts.localDsh, rel);
130
+ const full = this.localPathForWirePath(rel);
88
131
  try {
89
132
  const st = fsMod.statSync(full, { bigint: true });
90
133
  const e = probeIndex(rel, index);
@@ -97,11 +140,11 @@ export class BackupService {
97
140
  stale.push(rel);
98
141
  }
99
142
  }
100
- const hashed = await hashFiles(fsMod, this.opts.localDsh, stale);
143
+ const hashed = await hashWirePaths(fsMod, { storeRoot: this.resolveStoreRoot(), localDsh: this.opts.localDsh }, stale);
101
144
  for (const f of hashed) {
102
145
  local.push({ path: f.path, sha256: f.sha256, size: f.size });
103
146
  try {
104
- const st = fsMod.statSync(path.join(this.opts.localDsh, f.path), { bigint: true });
147
+ const st = fsMod.statSync(this.localPathForWirePath(f.path), { bigint: true });
105
148
  index.entries[f.path] = { ...statFingerprint(st), sha256: f.sha256 };
106
149
  }
107
150
  catch { }
@@ -199,7 +242,7 @@ export class BackupService {
199
242
  }
200
243
  if (sha === null) {
201
244
  try {
202
- const buf = fsMod.readFileSync(path.join(this.opts.localDsh, rel));
245
+ const buf = fsMod.readFileSync(this.localPathForWirePath(rel));
203
246
  const b = Buffer.isBuffer(buf) ? buf : Buffer.from(String(buf), 'utf-8');
204
247
  sha = createHash('sha256').update(b).digest('hex');
205
248
  size = b.length;
@@ -263,7 +306,7 @@ export class BackupService {
263
306
  copied++;
264
307
  continue;
265
308
  }
266
- const full = path.join(this.opts.localDsh, f.path);
309
+ const full = this.localPathForWirePath(f.path);
267
310
  let cur = null;
268
311
  try {
269
312
  cur = createHash('sha256').update(fsMod.readFileSync(full)).digest('hex');
@@ -305,8 +348,11 @@ export class BackupService {
305
348
  try {
306
349
  for (const f of head.manifest.files) {
307
350
  try {
308
- const destBase = req.mode === 'new-dir' ? req.destDir ?? path.join(this.opts.localDsh, 'restored') : this.opts.localDsh;
309
- const outFull = path.join(destBase, f.path);
351
+ // In place means "into the live store", which is the resolved root, not the
352
+ // DSH home. Getting this wrong recreates the legacy directory on restore.
353
+ const outFull = req.mode === 'new-dir'
354
+ ? path.join(req.destDir ?? path.join(this.opts.localDsh, 'restored'), f.path)
355
+ : this.localPathForWirePath(f.path);
310
356
  if (req.mode === 'in-place') {
311
357
  try {
312
358
  const cur = createHash('sha256').update(fsMod.readFileSync(outFull)).digest('hex');
@@ -7,3 +7,16 @@ export declare function hashFiles(fs: any, root: string, paths: readonly string[
7
7
  concurrency?: number;
8
8
  onFile?: (h: HashOutcome) => void;
9
9
  }): Promise<HashOutcome[]>;
10
+ /**
11
+ * Hash wire paths that live under two different roots.
12
+ *
13
+ * After the store move `maestro-memory/...` is under the store root and `sessions/...`
14
+ * under the DSH home, so one `hashFiles(root, paths)` call cannot cover a mixed list.
15
+ * The wire path is restored on the way out, because every caller reports wire paths.
16
+ */
17
+ export declare function hashWirePaths(fs: any, roots: {
18
+ storeRoot: string;
19
+ localDsh: string;
20
+ }, wirePaths: string[], opts?: {
21
+ onFile?: (h: HashOutcome) => void;
22
+ }): Promise<HashOutcome[]>;
@@ -45,3 +45,33 @@ export async function hashFiles(fs, root, paths, opts = {}) {
45
45
  await Promise.all(workers);
46
46
  return results.sort((a, b) => a.path.localeCompare(b.path));
47
47
  }
48
+ /**
49
+ * Hash wire paths that live under two different roots.
50
+ *
51
+ * After the store move `maestro-memory/...` is under the store root and `sessions/...`
52
+ * under the DSH home, so one `hashFiles(root, paths)` call cannot cover a mixed list.
53
+ * The wire path is restored on the way out, because every caller reports wire paths.
54
+ */
55
+ export async function hashWirePaths(fs, roots, wirePaths, opts = {}) {
56
+ const out = [];
57
+ const groups = new Map();
58
+ for (const wire of wirePaths) {
59
+ const root = wire.startsWith('maestro-memory/') ? roots.storeRoot : roots.localDsh;
60
+ const bucket = groups.get(root);
61
+ if (bucket)
62
+ bucket.push(wire);
63
+ else
64
+ groups.set(root, [wire]);
65
+ }
66
+ for (const [root, wires] of groups) {
67
+ const rel = wires.map((w) => (w.startsWith('maestro-memory/') ? w.slice('maestro-memory/'.length) : w));
68
+ const hashed = await hashFiles(fs, root, rel);
69
+ for (const entry of hashed) {
70
+ const wire = root === roots.storeRoot ? `maestro-memory/${entry.path}` : entry.path;
71
+ const outcome = { ...entry, path: wire };
72
+ opts.onFile?.(outcome);
73
+ out.push(outcome);
74
+ }
75
+ }
76
+ return out;
77
+ }
@@ -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
  /** Entry delimiter, byte-compatible with Hermes MEMORY.md / USER.md. */
package/lib/sync/merge.js CHANGED
@@ -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
  /** Entry delimiter, byte-compatible with Hermes MEMORY.md / USER.md. */
@@ -46,7 +46,7 @@ export function buildWarmCacheScript(dshRoot) {
46
46
  const cache = remoteCachePath(dshRoot);
47
47
  return [
48
48
  `mkdir -p "${dshRoot}/.maestro-sync";`,
49
- `find ${dshRoot}/dsh-maestro-memory ${dshRoot}/sessions`,
49
+ `find ${dshRoot}/maestro-memory ${dshRoot}/sessions`,
50
50
  `\\( -name node_modules -o -name .git -o -name .supervisor -o -name profiles \\) -prune -o -type f -print0`,
51
51
  `| xargs -0 stat --printf='%i %s %.Y %.Z\\t%n\\0' 2>/dev/null`,
52
52
  `| while IFS= read -r -d '' rec; do`,
@@ -4,5 +4,17 @@ export interface RemoteManifestEntry {
4
4
  size: number;
5
5
  mtimeSec: number;
6
6
  }
7
+ /**
8
+ * Raised when the peer has not moved its store to the 4.0 root yet.
9
+ *
10
+ * Before this guard the peer's `find` simply matched nothing, the plan read as
11
+ * "the peer has no memory", and the next push would have looked like the first
12
+ * one. A named refusal is worth more than a silent empty inventory.
13
+ */
14
+ export declare class StoreNotMigratedError extends Error {
15
+ readonly remotePath: string;
16
+ readonly code = "STORE_NOT_MIGRATED";
17
+ constructor(remotePath: string);
18
+ }
7
19
  export declare function buildRemoteManifestScript(dshRoot: string): string;
8
20
  export declare function parseRemoteManifest(buf: Buffer): RemoteManifestEntry[];
@@ -8,6 +8,22 @@
8
8
  // never an equality proof (equality uses sha256+size).
9
9
  import { normalizeEligiblePath } from './validation.js';
10
10
  import { remoteCachePath } from './remote-cache.js';
11
+ /**
12
+ * Raised when the peer has not moved its store to the 4.0 root yet.
13
+ *
14
+ * Before this guard the peer's `find` simply matched nothing, the plan read as
15
+ * "the peer has no memory", and the next push would have looked like the first
16
+ * one. A named refusal is worth more than a silent empty inventory.
17
+ */
18
+ export class StoreNotMigratedError extends Error {
19
+ remotePath;
20
+ code = 'STORE_NOT_MIGRATED';
21
+ constructor(remotePath) {
22
+ super(`remote store not migrated: ${remotePath} has no migrated-v4 marker; run the new build on that machine first`);
23
+ this.remotePath = remotePath;
24
+ this.name = 'StoreNotMigratedError';
25
+ }
26
+ }
11
27
  export function buildRemoteManifestScript(dshRoot) {
12
28
  // Fixed script; dshRoot is the validated absolute root (same trust rule as transport.list).
13
29
  // Cache-aware, READ-ONLY (spec §4.7 clarification, decision C): it consults
@@ -22,7 +38,10 @@ export function buildRemoteManifestScript(dshRoot) {
22
38
  // inside a `do...done` one-liner break bash's parser (verified 2026-09-02).
23
39
  const cache = remoteCachePath(dshRoot);
24
40
  return [
25
- `find ${dshRoot}/dsh-maestro-memory ${dshRoot}/sessions`,
41
+ // Preflight sentinel: no 4.0 marker means the peer still holds the old
42
+ // root, so an empty inventory must not be mistaken for an empty store.
43
+ `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;`,
44
+ `find ${dshRoot}/maestro-memory ${dshRoot}/sessions`,
26
45
  `\\( -name node_modules -o -name .git -o -name .supervisor -o -name profiles \\) -prune -o -type f -print0`,
27
46
  `| xargs -0 stat --printf='%i %s %.Y %.Z\\t%n\\n' 2>/dev/null`,
28
47
  `| 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;}'`,
@@ -46,6 +65,9 @@ export function parseRemoteManifest(buf) {
46
65
  for (const part of parts) {
47
66
  if (!part)
48
67
  continue;
68
+ if (part.startsWith('STORE_NOT_MIGRATED\t')) {
69
+ throw new StoreNotMigratedError(part.split('\t').slice(3).join('\t'));
70
+ }
49
71
  const [sha, sizeRaw, mtimeRaw, ...rest] = part.split('\t');
50
72
  const p = rest.join('\t');
51
73
  const size = Number(sizeRaw);
@@ -0,0 +1,44 @@
1
+ /**
2
+ * sync/store-root.ts — where the memory store lives, resolved the same way the plugin
3
+ * resolves it.
4
+ *
5
+ * Core cannot import the plugin (separate package, separate release), so this is a
6
+ * deliberate second implementation. `tests/sync/store-root-parity.spec.ts` runs the
7
+ * shared fixture against it, and the plugin runs the same fixture against its own
8
+ * copy, so a rule change on one side fails on that side instead of drifting silently.
9
+ *
10
+ * The rules, in order:
11
+ * 1. `memoryDir` (explicit config) wins.
12
+ * 2. `MAESTRO_MEMORY_DIR` wins next.
13
+ * 3. A `DSH_HOME` that realpaths somewhere other than `<home>/.dsh` is an isolated run
14
+ * (dry-boot, test, second profile): the store stays inside it.
15
+ * 4. Otherwise the neutral root, `<home>/.maestro-memory`.
16
+ */
17
+ export type StoreRootMode = 'configured' | 'env' | 'isolated' | 'default';
18
+ export interface StoreRoot {
19
+ root: string;
20
+ mode: StoreRootMode;
21
+ }
22
+ export declare function resolveStoreRoot(opts?: {
23
+ memoryDir?: string | null;
24
+ env?: NodeJS.ProcessEnv;
25
+ home?: string;
26
+ }): StoreRoot;
27
+ /** Map a wire path onto the local filesystem. Wire paths never change; roots do. */
28
+ export declare function localPathForWirePath(wirePath: string, roots: {
29
+ storeRoot: string;
30
+ localDsh: string;
31
+ }): string;
32
+ /**
33
+ * Group wire paths by the local root they resolve to, so a caller that hashes or stats
34
+ * many paths at once hashes each group against its own root instead of assuming the
35
+ * DSH home. After the store move, `maestro-memory/...` and `sessions/...` live in two
36
+ * different trees.
37
+ */
38
+ export declare function partitionByWireRoot(wirePaths: string[], roots: {
39
+ storeRoot: string;
40
+ localDsh: string;
41
+ }): Array<{
42
+ root: string;
43
+ paths: string[];
44
+ }>;