@ddtcorex/dsh-maestro-core 0.10.0 → 0.11.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 (43) hide show
  1. package/README.md +31 -12
  2. package/lib/cli.js +0 -2
  3. package/lib/client.js +58 -83
  4. package/lib/config/index.d.ts +11 -4
  5. package/lib/config/index.js +26 -9
  6. package/lib/config/service.d.ts +2 -2
  7. package/lib/config/service.js +2 -2
  8. package/lib/debug-agent.js +1 -1
  9. package/lib/paths.d.ts +8 -0
  10. package/lib/paths.js +22 -0
  11. package/lib/plugin.d.ts +21 -1
  12. package/lib/plugin.js +74 -6
  13. package/lib/restart-guards.js +1 -1
  14. package/lib/restart-tool.js +13 -4
  15. package/lib/resume-log.d.ts +4 -0
  16. package/lib/resume-log.js +13 -4
  17. package/lib/store/index.js +119 -45
  18. package/lib/supervisor.js +5 -7
  19. package/lib/types/client/config/MaestroSettings.d.ts.map +1 -1
  20. package/package.json +4 -2
  21. package/scripts/build-client.mjs +53 -0
  22. package/scripts/install-systemd.sh +55 -0
  23. package/scripts/sync/bench-preview.mjs +43 -0
  24. package/scripts/sync/cdp-sync-probe.mjs +200 -0
  25. package/scripts/sync/cdp-sync-verify.mjs +169 -0
  26. package/scripts/vendor-store.mjs +104 -0
  27. package/skills/dsh-safe-restart/SKILL.md +2 -2
  28. package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +2 -2
  29. package/src/client/config/MaestroSettings.tsx +4 -137
  30. package/src/host/cli.ts +0 -2
  31. package/src/host/config/index.ts +27 -10
  32. package/src/host/config/service.ts +2 -2
  33. package/src/host/debug-agent.ts +1 -1
  34. package/src/host/paths.ts +21 -0
  35. package/src/host/plugin.ts +79 -6
  36. package/src/host/restart-guards.ts +1 -1
  37. package/src/host/restart-tool.ts +12 -4
  38. package/src/host/resume-log.ts +20 -5
  39. package/src/host/store/index.ts +120 -33
  40. package/src/host/supervisor.ts +6 -8
  41. package/systemd/dsh-web-keepalive.service.template +12 -0
  42. package/systemd/dsh-web-supervisor.service.template +20 -0
  43. package/systemd/dsh-web.service.template +30 -0
@@ -1,12 +1,25 @@
1
1
  import { homedir } from 'node:os';
2
+ import { randomBytes } from 'node:crypto';
2
3
  import { dirname, join } from 'node:path';
3
- import { mkdir, open, readFile, rename, unlink, stat, rm, writeFile } from 'node:fs/promises';
4
+ import { mkdir, open, readFile, rename, unlink, stat, rm, writeFile, link } from 'node:fs/promises';
4
5
  import { mkdirSync, readFileSync } from 'node:fs';
5
6
  import { watch } from 'node:fs';
6
7
  const EMPTY_DOC = { version: 1, domains: {} };
7
8
  const domainValidators = new Map();
8
9
  const changeCbs = new Set();
9
10
  let cached = null;
11
+ async function fileSig(path) {
12
+ try {
13
+ const st = await stat(path);
14
+ return { mtimeMs: st.mtimeMs, ino: st.ino, size: st.size };
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
20
+ function sameSig(a, b) {
21
+ return a !== null && b !== null && a.mtimeMs === b.mtimeMs && a.ino === b.ino && a.size === b.size;
22
+ }
10
23
  function resolveDshHome(explicit) {
11
24
  return explicit ?? process.env.DSH_HOME ?? join(homedir(), '.dsh');
12
25
  }
@@ -60,6 +73,21 @@ function readSnapshotSync(home) {
60
73
  return {}; // no store on disk yet: every domain is new
61
74
  }
62
75
  }
76
+ /**
77
+ * Run every listener for one domain. Each callback gets its own try/catch: a
78
+ * throwing listener must neither reject the write that already committed nor
79
+ * hide the change from the listeners registered after it.
80
+ */
81
+ function fire(domain) {
82
+ for (const cb of [...changeCbs]) {
83
+ try {
84
+ cb(domain);
85
+ }
86
+ catch (err) {
87
+ console.warn(`config-lib: onChange callback for '${domain}' threw: ${err instanceof Error ? err.message : String(err)}`);
88
+ }
89
+ }
90
+ }
63
91
  async function checkExternal() {
64
92
  if (changeCbs.size === 0 || watchedHome === null || checking)
65
93
  return;
@@ -76,8 +104,7 @@ async function checkExternal() {
76
104
  }
77
105
  snapshot = next;
78
106
  for (const domain of changed)
79
- for (const cb of [...changeCbs])
80
- cb(domain);
107
+ fire(domain);
81
108
  }
82
109
  catch {
83
110
  // A transient read failure must never break boot; the next tick retries.
@@ -117,11 +144,22 @@ function startWatching() {
117
144
  try {
118
145
  // fs.watch is not recursive, so it only sees the file when its own
119
146
  // directory exists; the store is the only writer of that path either way.
120
- mkdirSync(dirname(path), { recursive: true });
121
- watcher = watch(dirname(path), { persistent: false }, (_event, filename) => {
147
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
148
+ const w = watch(dirname(path), { persistent: false }, (_event, filename) => {
122
149
  if (filename === null || filename === FILE_BASENAME)
123
150
  scheduleCheck();
124
151
  });
152
+ // An unhandled 'error' event (EMFILE, directory removed, ...) would crash
153
+ // the host. Drop the watcher and let the poll below carry on alone.
154
+ w.on('error', () => {
155
+ try {
156
+ w.close();
157
+ }
158
+ catch { /* already closed */ }
159
+ if (watcher === w)
160
+ watcher = null;
161
+ });
162
+ watcher = w;
125
163
  }
126
164
  catch {
127
165
  watcher = null; // polling below still covers the change
@@ -152,14 +190,56 @@ export function resetForTests() {
152
190
  // ---------------------------------------------------------------------------
153
191
  // locking + io
154
192
  // ---------------------------------------------------------------------------
193
+ /**
194
+ * Lock timing. A lock is only stolen once it is older than STALE_MS, which is
195
+ * deliberately longer than the time a waiter is willing to wait: a live writer
196
+ * that is merely slow must time its waiters out, never get robbed.
197
+ */
198
+ const LOCK_TIMEOUT_MS = 5_000;
199
+ const LOCK_STALE_MS = 30_000;
200
+ /** Settings directory: created 0700, lock file 0600 (the settings file is 0600 too). Modes apply at creation only; existing paths are never chmod-ed. */
201
+ const DIR_MODE = 0o700;
202
+ const FILE_MODE = 0o600;
203
+ /**
204
+ * Move a stale lock aside and delete it. rename() is atomic, so of several
205
+ * waiters only one moves the file. If the moved file turns out not to be the
206
+ * one we judged stale (a new owner took the path between our stat and the
207
+ * rename), it is put back with link(), which refuses to overwrite.
208
+ */
209
+ async function stealStaleLock(lockPath, observedIno) {
210
+ const aside = `${lockPath}.stale-${randomBytes(4).toString('hex')}`;
211
+ try {
212
+ await rename(lockPath, aside);
213
+ }
214
+ catch {
215
+ return; // someone else removed or stole it first
216
+ }
217
+ try {
218
+ const moved = await stat(aside);
219
+ if (moved.ino !== observedIno)
220
+ await link(aside, lockPath).catch(() => { });
221
+ }
222
+ catch {
223
+ /* nothing to restore */
224
+ }
225
+ finally {
226
+ await rm(aside, { force: true }).catch(() => { });
227
+ }
228
+ }
155
229
  async function withLock(path, fn) {
156
- await mkdir(dirname(path), { recursive: true }); // the store dir may not exist on first write
230
+ await mkdir(dirname(path), { recursive: true, mode: DIR_MODE }); // the store dir may not exist on first write
157
231
  const lockPath = `${path}.lock`;
158
- const deadline = Date.now() + 5_000;
159
- let handle = null;
232
+ const token = `${process.pid}-${randomBytes(8).toString('hex')}`;
233
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
160
234
  for (;;) {
161
235
  try {
162
- handle = await open(lockPath, 'wx');
236
+ const handle = await open(lockPath, 'wx', FILE_MODE);
237
+ try {
238
+ await handle.writeFile(token);
239
+ }
240
+ finally {
241
+ await handle.close();
242
+ }
163
243
  break;
164
244
  }
165
245
  catch (err) {
@@ -168,8 +248,8 @@ async function withLock(path, fn) {
168
248
  // Break stale locks left behind by a crashed writer.
169
249
  try {
170
250
  const st = await stat(lockPath);
171
- if (Date.now() - st.mtimeMs > 5_000) {
172
- await rm(lockPath, { force: true });
251
+ if (Date.now() - st.mtimeMs > LOCK_STALE_MS) {
252
+ await stealStaleLock(lockPath, st.ino);
173
253
  continue;
174
254
  }
175
255
  }
@@ -185,8 +265,15 @@ async function withLock(path, fn) {
185
265
  return await fn();
186
266
  }
187
267
  finally {
188
- await unlink(lockPath).catch(() => { });
189
- void handle; // closed fd via unlink; keep handle referenced for GC clarity
268
+ // Only release a lock that is still ours: if it was stolen and re-acquired
269
+ // meanwhile, deleting it would break the new owner's mutual exclusion.
270
+ try {
271
+ if ((await readFile(lockPath, 'utf8')) === token)
272
+ await unlink(lockPath);
273
+ }
274
+ catch {
275
+ /* already gone */
276
+ }
190
277
  }
191
278
  }
192
279
  function parseDoc(raw) {
@@ -220,10 +307,17 @@ function deepMerge(base, patch) {
220
307
  return patch;
221
308
  }
222
309
  async function writeDocLocked(path, doc) {
223
- await mkdir(dirname(path), { recursive: true });
310
+ await mkdir(dirname(path), { recursive: true, mode: DIR_MODE });
224
311
  const tmp = `${path}.tmp-${Math.random().toString(16).slice(2, 10)}`;
225
- await writeFile(tmp, JSON.stringify(doc, null, 2) + '\n', { mode: 0o600 });
226
- await rename(tmp, path); // atomic on the same filesystem; rename carries the 600 mode
312
+ try {
313
+ await writeFile(tmp, JSON.stringify(doc, null, 2) + '\n', { mode: FILE_MODE });
314
+ await rename(tmp, path); // atomic on the same filesystem; rename carries the 600 mode
315
+ }
316
+ finally {
317
+ // After a successful rename the temp name is gone and this is a no-op; after
318
+ // a failed write or rename it removes the orphan instead of leaking one per try.
319
+ await rm(tmp, { force: true }).catch(() => { });
320
+ }
227
321
  }
228
322
  // ---------------------------------------------------------------------------
229
323
  // public API
@@ -234,22 +328,14 @@ export async function load(opts) {
234
328
  if (cached && cached.key === homeKey) {
235
329
  // One stat per load: out-of-band edits (other processes) must surface
236
330
  // without a restart.
237
- try {
238
- const st = await stat(path);
239
- if (st.mtimeMs === cached.mtimeMs)
240
- return cached.doc;
241
- }
242
- catch {
331
+ const now = await fileSig(path);
332
+ if (now === null)
243
333
  return cached.doc; // stat failed (vanished/locked) — serve stale, never break boot
244
- }
334
+ if (sameSig(now, cached.sig))
335
+ return cached.doc;
245
336
  }
246
337
  const doc = await readDoc(path);
247
- let mtimeMs = 0;
248
- try {
249
- mtimeMs = (await stat(path)).mtimeMs;
250
- }
251
- catch { }
252
- cached = { key: homeKey, doc, mtimeMs };
338
+ cached = { key: homeKey, doc, sig: await fileSig(path) };
253
339
  return doc;
254
340
  }
255
341
  export async function get(domain, opts) {
@@ -272,18 +358,12 @@ export async function set(domain, patch, opts) {
272
358
  doc.domains[domain] = merged;
273
359
  written = merged;
274
360
  await writeDocLocked(path, doc);
275
- let mtimeMs = 0;
276
- try {
277
- mtimeMs = (await stat(path)).mtimeMs;
278
- }
279
- catch { }
280
- cached = { key, doc, mtimeMs };
361
+ cached = { key, doc, sig: await fileSig(path) };
281
362
  });
282
363
  // Refresh the watched copy first so the watcher sees no diff for this write.
283
364
  if (watchedHome === key)
284
365
  snapshot[domain] = JSON.stringify(written) ?? 'undefined';
285
- for (const cb of [...changeCbs])
286
- cb(domain);
366
+ fire(domain);
287
367
  }
288
368
  /**
289
369
  * Delete one TOP-LEVEL key of a domain — the delete operation `set()` cannot
@@ -318,19 +398,13 @@ export async function unset(domain, key, opts) {
318
398
  doc.domains[domain] = next;
319
399
  written = next;
320
400
  await writeDocLocked(path, doc);
321
- let mtimeMs = 0;
322
- try {
323
- mtimeMs = (await stat(path)).mtimeMs;
324
- }
325
- catch { }
326
- cached = { key: homeKey, doc, mtimeMs };
401
+ cached = { key: homeKey, doc, sig: await fileSig(path) };
327
402
  return true;
328
403
  });
329
404
  if (deleted) {
330
405
  if (watchedHome === homeKey)
331
406
  snapshot[domain] = JSON.stringify(written) ?? 'undefined';
332
- for (const cb of [...changeCbs])
333
- cb(domain);
407
+ fire(domain);
334
408
  }
335
409
  return deleted;
336
410
  }
package/lib/supervisor.js CHANGED
@@ -4,7 +4,7 @@ import { findInterrupted as defaultFindInterrupted, parseDuration } from './resu
4
4
  import * as fs from 'node:fs';
5
5
  import * as path from 'node:path';
6
6
  import * as os from 'node:os';
7
- import { resolveHarnessRoot } from './paths.js';
7
+ import { resolveHarnessRoot, readSettingsDocSync } from './paths.js';
8
8
  import { readSupervisorConfig } from './config.js';
9
9
  import { writePlannedRestart as defaultWritePlannedRestart, checkPlannedRestart as defaultCheckPlannedRestart, clearPlannedRestart } from './restart-guards.js';
10
10
  import { writeRestartOutcome as defaultWriteOutcome } from './intents.js';
@@ -139,9 +139,8 @@ export class Supervisor {
139
139
  return false;
140
140
  }
141
141
  }
142
- const maestroPath = path.join(os.homedir(), '.dsh/maestro/settings.json');
143
- if (fs.existsSync(maestroPath)) {
144
- const j = JSON.parse(fs.readFileSync(maestroPath, 'utf-8'));
142
+ const j = readSettingsDocSync();
143
+ if (j) {
145
144
  const raw = j?.domains?.supervisor?.autoResumeEnabled ?? j?.supervisor?.autoResumeEnabled ?? j?.domains?.supervisor?.autoResume ?? j?.supervisor?.autoResume;
146
145
  if (typeof raw === 'boolean')
147
146
  return raw;
@@ -190,9 +189,8 @@ export class Supervisor {
190
189
  else if (typeof raw === 'number')
191
190
  return raw * 60 * 1000; // number is MINUTES
192
191
  }
193
- const maestroPath = path.join(os.homedir(), '.dsh/maestro/settings.json');
194
- if (fs.existsSync(maestroPath)) {
195
- const j = JSON.parse(fs.readFileSync(maestroPath, 'utf-8'));
192
+ const j = readSettingsDocSync();
193
+ if (j) {
196
194
  const raw = j?.domains?.supervisor?.autoResumeWithin ?? j?.supervisor?.autoResumeWithin;
197
195
  if (typeof raw === 'string') {
198
196
  if (/^\d+$/.test(raw.trim()))
@@ -1 +1 @@
1
- {"version":3,"file":"MaestroSettings.d.ts","sourceRoot":"","sources":["../../../../src/client/config/MaestroSettings.tsx"],"names":[],"mappings":"AACA;;;;;;;;GAQG;AAqeH,wBAAgB,kBAAkB,CAAC,EAAE,aAAa,EAAE,iBAAiB,EAAE,EAAE;IAAE,aAAa,CAAC,EAAE,GAAG,CAAC;IAAC,iBAAiB,CAAC,EAAE,GAAG,CAAA;CAAE;;;;;;;;;mBA2X8C,GAAG;;gBAkBzK"}
1
+ {"version":3,"file":"MaestroSettings.d.ts","sourceRoot":"","sources":["../../../../src/client/config/MaestroSettings.tsx"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AA6VH,wBAAgB,kBAAkB,CAAC,EAAE,aAAa,EAAE,iBAAiB,EAAE,EAAE;IAAE,aAAa,CAAC,EAAE,GAAG,CAAC;IAAC,iBAAiB,CAAC,EAAE,GAAG,CAAA;CAAE;;;;;;;;;mBA+X8C,GAAG;;gBAkBzK"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ddtcorex/dsh-maestro-core",
3
- "version": "0.10.0",
4
- "description": "Supervisor daemon for DSH Web resilience — auto-detect crashes, rollback to LKG, report",
3
+ "version": "0.11.0",
4
+ "description": "DSH Web supervisor, settings store, tool guard and sync engine",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -49,6 +49,8 @@
49
49
  "lib",
50
50
  "src",
51
51
  "skills",
52
+ "scripts",
53
+ "systemd",
52
54
  "README.md",
53
55
  "cordis.patch.yml"
54
56
  ],
@@ -0,0 +1,53 @@
1
+ // Bundle every client surface this package owns into the DSH browser loader
2
+ // shape: window.__ModuleLoader__.load({ id, factory: (require) => ... }).
3
+ //
4
+ // One bundle, one id, one entry point (src/client/index.tsx): the entry
5
+ // decides which surfaces register and in what order, so the per-module build
6
+ // scripts this replaces are gone rather than kept as three ways to produce one
7
+ // artifact. react and the DSH platform modules stay external and resolve from
8
+ // the host's module table at runtime.
9
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
10
+ import { dirname, resolve } from 'node:path'
11
+ import { fileURLToPath } from 'node:url'
12
+ import { build } from 'esbuild'
13
+
14
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
15
+ const outputPath = resolve(root, 'lib/client.js')
16
+ // The loader id is the manifest name, read rather than written out. This script
17
+ // is the one the sibling packages copied, and a copy that kept a written-out id
18
+ // shipped that sibling's name instead of its own: the bundle registered under an
19
+ // id the host never asked for, which drops the entry at boot with no error
20
+ // naming the cause.
21
+ const id = JSON.parse(await readFile(resolve(root, 'package.json'), 'utf8')).name
22
+
23
+ const result = await build({
24
+ entryPoints: [resolve(root, 'src/client/index.tsx')],
25
+ bundle: true,
26
+ format: 'cjs',
27
+ platform: 'browser',
28
+ target: ['chrome100'],
29
+ external: ['react', 'react/jsx-runtime', '@deepseek-ai/dsh-client-ui-primitives'],
30
+ jsx: 'automatic',
31
+ write: false,
32
+ minify: process.env.NODE_ENV === 'production',
33
+ legalComments: 'none',
34
+ })
35
+
36
+ const bundled = result.outputFiles?.[0]?.text
37
+ if (!bundled) throw new Error('esbuild did not produce a client bundle')
38
+
39
+ const wrapped = `window.__ModuleLoader__.load({
40
+ id: '${id}',
41
+ factory: (require) => {
42
+ var module = { exports: {} };
43
+ var exports = module.exports;
44
+ var React = require("react");
45
+ ${bundled}
46
+ return module.exports;
47
+ }
48
+ });
49
+ `
50
+
51
+ await mkdir(dirname(outputPath), { recursive: true })
52
+ await writeFile(outputPath, wrapped, 'utf8')
53
+ console.log(`client bundle written: ${outputPath} (${bundled.length} bytes)`)
@@ -0,0 +1,55 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
4
+ SYSTEMD_DIR="$SCRIPT_DIR/../systemd"
5
+ # Detect harness root (three levels up from scripts/) — portable across machines
6
+ MAESTRO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
7
+
8
+ install_one() {
9
+ local template="$1"
10
+ local dest="$2"
11
+ mkdir -p "$(dirname "$dest")"
12
+ sed -e "s|%h|$HOME|g" -e "s|%MAESTRO_ROOT%|$MAESTRO_ROOT|g" "$template" > "$dest"
13
+ echo "installed $dest (MAESTRO_ROOT=$MAESTRO_ROOT)"
14
+ }
15
+
16
+ # Migrate old keepalive.service if present (pre-prefix)
17
+ if [ -f "$HOME/.config/systemd/user/keepalive.service" ] && [ ! -f "$HOME/.config/systemd/user/dsh-web-keepalive.service" ]; then
18
+ mv "$HOME/.config/systemd/user/keepalive.service" "$HOME/.config/systemd/user/dsh-web-keepalive.service" 2>/dev/null || cp "$HOME/.config/systemd/user/keepalive.service" "$HOME/.config/systemd/user/dsh-web-keepalive.service" 2>/dev/null || true
19
+ echo "migrated keepalive.service → dsh-web-keepalive.service"
20
+ fi
21
+ install_one "$SYSTEMD_DIR/dsh-web.service.template" "$HOME/.config/systemd/user/dsh-web.service"
22
+ install_one "$SYSTEMD_DIR/dsh-web-supervisor.service.template" "$HOME/.config/systemd/user/dsh-web-supervisor.service"
23
+ install_one "$SYSTEMD_DIR/dsh-web-keepalive.service.template" "$HOME/.config/systemd/user/dsh-web-keepalive.service"
24
+
25
+ # Auto-enable without requiring the user to run systemctl manually (plugin spirit):
26
+ # keepalive prevents user manager exit when manager session is Removed (11:42:58 crash),
27
+ # dsh-web + supervisor are the actual workloads. Linger keeps manager alive after reboot.
28
+ # All commands are best-effort — failures are logged but never block install (e.g. bus dead).
29
+ try_enable() {
30
+ if command -v loginctl >/dev/null 2>&1; then
31
+ if [ ! -f /var/lib/systemd/linger/"$USER" ]; then
32
+ loginctl enable-linger "$USER" 2>/dev/null || true
33
+ fi
34
+ fi
35
+ if command -v systemctl >/dev/null 2>&1; then
36
+ systemctl --user daemon-reload 2>/dev/null || true
37
+ # Disable old keepalive.service if it was previously enabled
38
+ systemctl --user disable keepalive.service 2>/dev/null || true
39
+ systemctl --user enable dsh-web-keepalive.service 2>/dev/null || true
40
+ systemctl --user enable dsh-web.service 2>/dev/null || true
41
+ systemctl --user enable dsh-web-supervisor.service 2>/dev/null || true
42
+ # Try to start if bus is alive; if user manager is dead (Connection refused) this is a no-op
43
+ # and the next reboot / manual `systemctl --user start` will pick it up.
44
+ systemctl --user start dsh-web-keepalive.service 2>/dev/null || true
45
+ systemctl --user stop keepalive.service 2>/dev/null || true
46
+ systemctl --user start dsh-web.service 2>/dev/null || true
47
+ systemctl --user start dsh-web-supervisor.service 2>/dev/null || true
48
+ fi
49
+ }
50
+ try_enable
51
+
52
+ echo "done. Units installed and auto-enabled (best-effort):"
53
+ echo " dsh-web-keepalive.service + dsh-web.service + dsh-web-supervisor.service"
54
+ echo " linger: $(test -f /var/lib/systemd/linger/$USER && echo enabled || echo not-enabled)"
55
+ echo " check: systemctl --user status dsh-web-keepalive dsh-web dsh-web-supervisor --no-pager"
@@ -0,0 +1,43 @@
1
+ // bench-preview.mjs — dry-run preview benchmark for dsh-maestro-sync (no writes)
2
+ // Usage: node scripts/bench-preview.mjs --direction pull --rounds 3
3
+ import { execFileSync } from 'node:child_process';
4
+ import * as fs from 'node:fs';
5
+ import * as path from 'node:path';
6
+
7
+ const dsh = process.env.DSH_HOME || path.join(process.env.HOME, '.dsh');
8
+
9
+ function eligibleCounts() {
10
+ let md = 0;
11
+ let zstd = 0;
12
+ const walk = (d) => {
13
+ for (const ent of fs.readdirSync(d, { withFileTypes: true })) {
14
+ const full = path.join(d, ent.name);
15
+ if (ent.isDirectory()) {
16
+ if (!['node_modules', '.git', '.supervisor', 'profiles'].includes(ent.name)) walk(full);
17
+ } else if (ent.name.endsWith('.jsonl.zstd')) {
18
+ zstd++;
19
+ } else if (ent.name.endsWith('.md') && !ent.name.includes('.bak.')) {
20
+ md++;
21
+ }
22
+ }
23
+ };
24
+ walk(path.join(dsh, 'memories'));
25
+ walk(path.join(dsh, 'sessions'));
26
+ return { md, zstd };
27
+ }
28
+
29
+ const args = process.argv.slice(2);
30
+ const direction = args.includes('--push') ? 'push' : 'pull';
31
+ const rounds = Number(args[args.indexOf('--rounds') + 1] || 3);
32
+ const cli = path.resolve('lib/sync/cli.js');
33
+ const { md, zstd } = eligibleCounts();
34
+ const times = [];
35
+ for (let i = 0; i < rounds; i++) {
36
+ const t0 = process.hrtime.bigint();
37
+ const out = execFileSync('node', [cli, `--${direction}`, '--dry-run'], { stdio: ['ignore', 'pipe', 'inherit'] }).toString('utf-8');
38
+ const ms = Number(process.hrtime.bigint() - t0) / 1e6;
39
+ times.push(ms);
40
+ const json = JSON.parse(out.trim().split('\n').pop());
41
+ process.stdout.write(`round ${i + 1}: ${Math.round(ms)}ms copy=${json.summary?.copied ?? 0} merge=${json.summary?.merged ?? 0}\n`);
42
+ }
43
+ process.stdout.write(`BASELINE md=${md} zstd=${zstd} medianMs=${Math.round(times.sort((a, b) => a - b)[Math.floor(times.length / 2)])}\n`);
@@ -0,0 +1,200 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CDP probe for the redesigned Maestro Sync settings card (mobile + desktop).
4
+ * - Fresh user-data-dir per probe; authenticates via the live process token,
5
+ * sets the session id + viewport, opens the sidebar (mobile) then Settings.
6
+ * - Navigates to the Maestro Sync section, screenshots the card, reports
7
+ * overflow + key geometry at 390 and 1440 widths.
8
+ */
9
+ import { spawn } from 'node:child_process'
10
+ import { mkdtempSync } from 'node:fs'
11
+ import { tmpdir } from 'node:os'
12
+ import { join, dirname } from 'node:path'
13
+ import { fileURLToPath } from 'node:url'
14
+ import net from 'node:net'
15
+
16
+ const TOKEN = process.env.DSH_WEB_TOKEN || 'L3L3mRdW6jqHK_RUCa20XSGLK6Z_YeHCgHUPNMDvhvU'
17
+ const TOKEN_URL = `http://127.0.0.1:3080/?token=${TOKEN}`
18
+ const SESSION_ID = process.env.DSH_SESSION_ID || 'session-5674e8fd-f84a-4437-b648-b660fe59dbc9'
19
+ const CHROME = '/opt/google/chrome/chrome'
20
+ const SCREENSHOT_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..', 'screenshots')
21
+
22
+ function allocPort() {
23
+ return new Promise((resolve) => {
24
+ const srv = net.createServer()
25
+ srv.listen(0, '127.0.0.1', () => {
26
+ const port = srv.address().port
27
+ srv.close(() => resolve(port))
28
+ })
29
+ })
30
+ }
31
+
32
+ let msgId = 0
33
+ function rpc(ws, method, params = {}) {
34
+ const id = ++msgId
35
+ return new Promise((resolve, reject) => {
36
+ const onMsg = (ev) => {
37
+ const data = JSON.parse(ev.data)
38
+ if (data.id === id) {
39
+ ws.removeEventListener('message', onMsg)
40
+ data.error ? reject(new Error(data.error.message)) : resolve(data.result)
41
+ }
42
+ }
43
+ ws.addEventListener('message', onMsg)
44
+ ws.send(JSON.stringify({ id, method, params }))
45
+ })
46
+ }
47
+
48
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
49
+
50
+ async function evalJs(ws, expression) {
51
+ const r = await rpc(ws, 'Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true })
52
+ if (r.exceptionDetails) throw new Error('eval failed: ' + JSON.stringify(r.exceptionDetails).slice(0, 300))
53
+ return r.result?.value
54
+ }
55
+
56
+ async function shot(ws, path) {
57
+ const { writeFileSync, mkdirSync } = await import('node:fs')
58
+ mkdirSync(SCREENSHOT_DIR, { recursive: true })
59
+ const r = await rpc(ws, 'Page.captureScreenshot', { format: 'png', fromSurface: true })
60
+ writeFileSync(join(SCREENSHOT_DIR, path), Buffer.from(r.data, 'base64'))
61
+ console.log(' screenshot ->', join(SCREENSHOT_DIR, path))
62
+ }
63
+
64
+ async function click(ws, x, y) {
65
+ await rpc(ws, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x, y })
66
+ await rpc(ws, 'Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 })
67
+ await rpc(ws, 'Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 })
68
+ await sleep(300)
69
+ }
70
+
71
+ async function queryStats(ws) {
72
+ return evalJs(
73
+ ws,
74
+ `(() => {
75
+ const doc = document.documentElement;
76
+ const syncCard = document.querySelector('[data-sync-root]');
77
+ const syncList = document.querySelector('[data-sync-filetables]');
78
+ const cols = document.querySelectorAll('[data-sync-dcol]');
79
+ return {
80
+ vw: doc.clientWidth,
81
+ vh: doc.clientHeight,
82
+ overflowX: doc.scrollWidth - doc.clientWidth,
83
+ overflowY: doc.scrollHeight - doc.clientHeight,
84
+ scrollW: doc.scrollWidth,
85
+ scrollH: doc.scrollHeight,
86
+ hasCard: !!syncCard,
87
+ cardW: syncCard ? Math.round(syncCard.getBoundingClientRect().width) : null,
88
+ cardTop: syncCard ? Math.round(syncCard.getBoundingClientRect().top) : null,
89
+ cardBottom: syncCard ? Math.round(syncCard.getBoundingClientRect().bottom) : null,
90
+ hasFileTables: !!syncList,
91
+ fileTablesW: syncList ? Math.round(syncList.getBoundingClientRect().width) : null,
92
+ colCount: cols.length,
93
+ visibleCols: Array.from(cols).filter((c) => getComputedStyle(c).display !== 'none').length,
94
+ logo: !!document.querySelector('[data-maestro-logo]'),
95
+ title: syncCard ? (syncCard.querySelector('div')?.textContent || '').slice(0, 40) : '',
96
+ statsTiles: document.querySelectorAll('[data-sync-stat]').length,
97
+ };
98
+ })()`,
99
+ )
100
+ }
101
+
102
+ async function probe(width, height, mobile, label) {
103
+ console.log(`\n=== probe ${label} ${width}x${height} mobile=${mobile} ===`)
104
+ const port = await allocPort()
105
+ const userData = mkdtempSync(join(tmpdir(), 'dsh-sync-probe-'))
106
+ const chrome = spawn(
107
+ CHROME,
108
+ ['--headless=new', '--no-sandbox', '--disable-dev-shm-usage', `--remote-debugging-port=${port}`, `--user-data-dir=${userData}`, '--window-size=1440,900', 'about:blank'],
109
+ { stdio: 'ignore' },
110
+ )
111
+ try {
112
+ let target = null
113
+ for (let i = 0; i < 40; i++) {
114
+ await sleep(250)
115
+ try {
116
+ const list = await fetch(`http://127.0.0.1:${port}/json`).then((r) => r.json())
117
+ target = list.find((t) => t.type === 'page')
118
+ if (target) break
119
+ } catch {}
120
+ }
121
+ if (!target) throw new Error('no chrome page target')
122
+ const ws = await new Promise((res, rej) => {
123
+ const w = new WebSocket(target.webSocketDebuggerUrl)
124
+ w.onopen = () => res(w)
125
+ w.onerror = rej
126
+ })
127
+
128
+ await rpc(ws, 'Page.enable')
129
+ await rpc(ws, 'Runtime.enable')
130
+ await rpc(ws, 'Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 2, mobile, hasTouch: mobile })
131
+ await rpc(ws, 'Page.addScriptToEvaluateOnNewDocument', {
132
+ source: `localStorage['dsh.sessions.current'] = JSON.stringify({ sessionId: ${JSON.stringify(SESSION_ID)} });`,
133
+ })
134
+ await rpc(ws, 'Page.navigate', { url: TOKEN_URL })
135
+ await sleep(4500)
136
+
137
+ // Mobile: the left sidebar is an off-canvas rail — open it via JS click
138
+ if (mobile) {
139
+ const opened = await evalJs(ws, `(() => { const b = document.querySelector('button[aria-label="Open sidebar"]'); if (b) { b.click(); return true; } return false; })()`)
140
+ console.log(' open sidebar (JS):', opened)
141
+ await sleep(1200)
142
+ }
143
+
144
+ // Open settings — sidebar footer "Settings" row (JS click bypasses offscreen geometry)
145
+ const settingsBtn = await evalJs(
146
+ ws,
147
+ `(() => {
148
+ const els = Array.from(document.querySelectorAll('button, [role="button"]'));
149
+ const hit = els.find((el) => {
150
+ const label = el.getAttribute('aria-label') || el.title || (el.textContent || '');
151
+ return label.trim().toLowerCase() === 'settings';
152
+ });
153
+ if (!hit) return null;
154
+ hit.click();
155
+ return { text: (hit.textContent || '').trim().slice(0, 20) };
156
+ })()`,
157
+ )
158
+ if (!settingsBtn) throw new Error('settings trigger not found')
159
+ console.log(' settings clicked:', JSON.stringify(settingsBtn))
160
+ await sleep(1400)
161
+
162
+ // Navigate to the Maestro Sync settings section
163
+ const syncNav = await evalJs(
164
+ ws,
165
+ `(() => {
166
+ const dialog = document.querySelector('[role="dialog"]');
167
+ if (!dialog) return null;
168
+ const btns = Array.from(dialog.querySelectorAll('button'));
169
+ const hit = btns.find((b) => (b.textContent || '').trim() === 'Maestro Sync' || (b.getAttribute('aria-label') || '') === 'Maestro Sync');
170
+ if (!hit) return null;
171
+ hit.click();
172
+ return { text: 'Maestro Sync' };
173
+ })()`,
174
+ )
175
+ if (syncNav) {
176
+ console.log(' nav clicked:', JSON.stringify(syncNav))
177
+ } else {
178
+ console.log(' [warn] Maestro Sync nav row not found')
179
+ }
180
+ await sleep(2200)
181
+
182
+ const stats = await queryStats(ws)
183
+ console.log(' settings:', JSON.stringify(stats))
184
+ await shot(ws, `sync-settings-${label}.png`)
185
+
186
+ ws.close()
187
+ return { label, settings: stats }
188
+ } catch (e) {
189
+ console.log(' [error]', e.message)
190
+ return { label, error: e.message }
191
+ } finally {
192
+ chrome.kill('SIGKILL')
193
+ }
194
+ }
195
+
196
+ const results = []
197
+ results.push(await probe(390, 844, true, 'mobile'))
198
+ results.push(await probe(1440, 900, false, 'desktop'))
199
+ console.log('\n=== SUMMARY ===')
200
+ for (const r of results) console.log(JSON.stringify(r))