@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
@@ -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. */
@@ -146,7 +146,18 @@ while IFS= read -r line; do
146
146
  esac
147
147
  staged="$stage_dir/$rel"
148
148
  [ -f "$staged" ] || { echo "maestro-sync-commit: missing staged artifact: $rel" >&2; fail=1; continue; }
149
- target="$dsh_root/$rel"
149
+ # The peer's store may live outside its DSH home since 5.0. Memory wire paths land in
150
+ # whichever store root that peer actually reads; everything else stays under the DSH
151
+ # home. Resolved once per commit from the peer's own marker, never assumed.
152
+ case "$rel" in
153
+ maestro-memory/*)
154
+ if [ -f "$HOME/.maestro-memory/.maestro-memory/migrated-v5.json" ]; then
155
+ target="$HOME/.maestro-memory/\${rel#maestro-memory/}"
156
+ else
157
+ target="$dsh_root/$rel"
158
+ fi ;;
159
+ *) target="$dsh_root/$rel" ;;
160
+ esac
150
161
  if [ "$expected" = "absent" ]; then
151
162
  if [ -e "$target" ]; then
152
163
  echo "CONCURRENT_MODIFICATION: $rel (target exists, expected absent)" >&2
@@ -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,30 @@ 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
+ /**
15
+ * Raised when the peer has moved its store out of the DSH home.
16
+ *
17
+ * Sync still addresses memory as `<dshRoot>/maestro-memory` on the sending side, so a
18
+ * push to a moved peer writes into the directory that peer no longer reads, and the
19
+ * transfer reports success. Until the remote scripts learn a second base path, the only
20
+ * honest thing is to refuse: a named refusal is worth more than memories that vanish.
21
+ */
22
+ export declare class PeerStoreMovedError extends Error {
23
+ readonly remotePath: string;
24
+ readonly code = "PEER_STORE_MOVED";
25
+ constructor(remotePath: string);
26
+ }
27
+ export declare class StoreNotMigratedError extends Error {
28
+ readonly remotePath: string;
29
+ readonly code = "STORE_NOT_MIGRATED";
30
+ constructor(remotePath: string);
31
+ }
7
32
  export declare function buildRemoteManifestScript(dshRoot: string): string;
8
33
  export declare function parseRemoteManifest(buf: Buffer): RemoteManifestEntry[];
@@ -8,6 +8,39 @@
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
+ /**
19
+ * Raised when the peer has moved its store out of the DSH home.
20
+ *
21
+ * Sync still addresses memory as `<dshRoot>/maestro-memory` on the sending side, so a
22
+ * push to a moved peer writes into the directory that peer no longer reads, and the
23
+ * transfer reports success. Until the remote scripts learn a second base path, the only
24
+ * honest thing is to refuse: a named refusal is worth more than memories that vanish.
25
+ */
26
+ export class PeerStoreMovedError extends Error {
27
+ remotePath;
28
+ code = 'PEER_STORE_MOVED';
29
+ constructor(remotePath) {
30
+ super(`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`);
31
+ this.remotePath = remotePath;
32
+ this.name = 'PeerStoreMovedError';
33
+ }
34
+ }
35
+ export class StoreNotMigratedError extends Error {
36
+ remotePath;
37
+ code = 'STORE_NOT_MIGRATED';
38
+ constructor(remotePath) {
39
+ super(`remote store not migrated: ${remotePath} has no migrated-v4 marker; run the new build on that machine first`);
40
+ this.remotePath = remotePath;
41
+ this.name = 'StoreNotMigratedError';
42
+ }
43
+ }
11
44
  export function buildRemoteManifestScript(dshRoot) {
12
45
  // Fixed script; dshRoot is the validated absolute root (same trust rule as transport.list).
13
46
  // Cache-aware, READ-ONLY (spec §4.7 clarification, decision C): it consults
@@ -22,7 +55,14 @@ export function buildRemoteManifestScript(dshRoot) {
22
55
  // inside a `do...done` one-liner break bash's parser (verified 2026-09-02).
23
56
  const cache = remoteCachePath(dshRoot);
24
57
  return [
25
- `find ${dshRoot}/dsh-maestro-memory ${dshRoot}/sessions`,
58
+ // Preflight sentinel: no 4.0 marker means the peer still holds the old
59
+ // root, so an empty inventory must not be mistaken for an empty store.
60
+ `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;`,
61
+ // 5.0 moved the store out of the DSH home on the peer. Its `find` below would match
62
+ // nothing and read as "the peer has no memory", exactly the failure the v4 sentinel
63
+ // above exists to prevent.
64
+ `mem_root=${dshRoot}/maestro-memory; if [ -f "$HOME/.maestro-memory/.maestro-memory/migrated-v5.json" ]; then mem_root="$HOME/.maestro-memory"; fi;`,
65
+ `find "$mem_root" ${dshRoot}/sessions`,
26
66
  `\\( -name node_modules -o -name .git -o -name .supervisor -o -name profiles \\) -prune -o -type f -print0`,
27
67
  `| xargs -0 stat --printf='%i %s %.Y %.Z\\t%n\\n' 2>/dev/null`,
28
68
  `| 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;}'`,
@@ -33,7 +73,8 @@ export function buildRemoteManifestScript(dshRoot) {
33
73
  `printf '%s\\t%s\\t%s\\t%s\\0' "$sha" "$size" "$mtime" "$rel";`,
34
74
  `else`,
35
75
  `rel=\${rest%%$'\\t'*}; st=\${rest#*$'\\t'};`,
36
- `sha=$(sha256sum -- "${dshRoot}/$rel" 2>/dev/null | awk '{print $1}');`,
76
+ `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;`,
77
+ `sha=$(sha256sum -- "$full" 2>/dev/null | awk '{print $1}');`,
37
78
  `set -- $st;`,
38
79
  `printf '%s\\t%s\\t%s\\t%s\\0' "$sha" "$2" "$3" "$rel";`,
39
80
  `fi;`,
@@ -46,6 +87,12 @@ export function parseRemoteManifest(buf) {
46
87
  for (const part of parts) {
47
88
  if (!part)
48
89
  continue;
90
+ if (part.startsWith('STORE_NOT_MIGRATED\t')) {
91
+ throw new StoreNotMigratedError(part.split('\t').slice(3).join('\t'));
92
+ }
93
+ if (part.startsWith('PEER_STORE_MOVED\t')) {
94
+ throw new PeerStoreMovedError(part.split('\t').slice(3).join('\t'));
95
+ }
49
96
  const [sha, sizeRaw, mtimeRaw, ...rest] = part.split('\t');
50
97
  const p = rest.join('\t');
51
98
  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
+ }>;
@@ -0,0 +1,67 @@
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
+ import { realpathSync } from 'node:fs';
18
+ import { homedir } from 'node:os';
19
+ import { join } from 'node:path';
20
+ function realpathOr(value) {
21
+ try {
22
+ return realpathSync.native(value);
23
+ }
24
+ catch {
25
+ return value;
26
+ }
27
+ }
28
+ export function resolveStoreRoot(opts = {}) {
29
+ if (opts.memoryDir)
30
+ return { root: opts.memoryDir, mode: 'configured' };
31
+ const env = opts.env ?? process.env;
32
+ const envDir = typeof env.MAESTRO_MEMORY_DIR === 'string' ? env.MAESTRO_MEMORY_DIR.trim() : '';
33
+ if (envDir)
34
+ return { root: envDir, mode: 'env' };
35
+ const home = realpathOr(opts.home ?? homedir());
36
+ const dshDefault = join(home, '.dsh');
37
+ const rawDsh = typeof env.DSH_HOME === 'string' && env.DSH_HOME.trim() ? env.DSH_HOME.trim() : '';
38
+ if (rawDsh && realpathOr(rawDsh) !== dshDefault) {
39
+ return { root: join(rawDsh, 'maestro-memory'), mode: 'isolated' };
40
+ }
41
+ return { root: join(home, '.maestro-memory'), mode: 'default' };
42
+ }
43
+ /** Map a wire path onto the local filesystem. Wire paths never change; roots do. */
44
+ export function localPathForWirePath(wirePath, roots) {
45
+ if (wirePath.startsWith('maestro-memory/')) {
46
+ return join(roots.storeRoot, wirePath.slice('maestro-memory/'.length));
47
+ }
48
+ return join(roots.localDsh, wirePath);
49
+ }
50
+ /**
51
+ * Group wire paths by the local root they resolve to, so a caller that hashes or stats
52
+ * many paths at once hashes each group against its own root instead of assuming the
53
+ * DSH home. After the store move, `maestro-memory/...` and `sessions/...` live in two
54
+ * different trees.
55
+ */
56
+ export function partitionByWireRoot(wirePaths, roots) {
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
+ return [...groups.entries()].map(([root, paths]) => ({ root, paths }));
67
+ }
@@ -51,6 +51,8 @@ export interface PreviewResult extends SyncPreview {
51
51
  }
52
52
  export interface SyncServiceOpts {
53
53
  localDsh?: string;
54
+ /** Resolved memory store root; defaults to the same rules the plugin uses. */
55
+ storeRoot?: string;
54
56
  remote?: string;
55
57
  remoteDsh?: string;
56
58
  previewDir?: string;
@@ -61,6 +63,7 @@ export interface SyncServiceOpts {
61
63
  }
62
64
  export declare class SyncService {
63
65
  localDsh: string;
66
+ storeRoot: string;
64
67
  remote: string;
65
68
  remoteDsh: string;
66
69
  previewDir: string;
@@ -78,10 +81,17 @@ export declare class SyncService {
78
81
  checkConnection(): Promise<ConnectionStatus>;
79
82
  private requireConnection;
80
83
  /**
81
- * Local eligible files (dsh-maestro-memory/*.md, dsh-maestro-memory/SUGGESTIONS.jsonl,
84
+ * Local eligible files (maestro-memory/*.md, maestro-memory/SUGGESTIONS.jsonl,
82
85
  * sessions/<cwd-hash>/<id>/session.jsonl.zstd) as relative paths, sorted.
83
86
  * Only content that matches the eligible contract is ever read or hashed.
84
87
  */
88
+ /** The two roots a wire path can resolve to. */
89
+ hashRoots(): {
90
+ storeRoot: string;
91
+ localDsh: string;
92
+ };
93
+ /** Map a wire path to its local file, through the resolved store root. */
94
+ localPathForWirePath(wirePath: string): string;
85
95
  listLocalFiles(): string[];
86
96
  /**
87
97
  * Snapshot both sides with the manifest-first pipeline:
@@ -96,6 +106,20 @@ export declare class SyncService {
96
106
  * re-hashed at write time (see apply), so a stale cache can never publish a
97
107
  * wrong mutation target.
98
108
  */
109
+ /**
110
+ * The 4.0 rename moved the store root. A machine still on the old root would
111
+ * inventory zero memory files, which reads exactly like "nothing to sync".
112
+ * Refuse instead: the marker is written by the plugin's boot migration.
113
+ */
114
+ private assertLocalStoreMigrated;
115
+ /**
116
+ * Refuse a peer that still keeps its store inside the DSH home.
117
+ *
118
+ * The wire paths are the same on both sides, so a mixed pair writes into a directory
119
+ * the upgraded machine no longer reads: the transfer succeeds and the memories are
120
+ * invisible. The marker is the only signal available before the transfer starts.
121
+ */
122
+ assertPeerMoved(remotePaths: string[]): void;
99
123
  private snapshotBoth;
100
124
  /**
101
125
  * Read-only preview: exact plan with copy/merge/skip/conflict and real added