@ddtcorex/dsh-maestro-core 0.11.2 → 0.12.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 (89) hide show
  1. package/README.md +18 -1
  2. package/cordis.patch.yml +4 -4
  3. package/lib/client.js +5 -29
  4. package/lib/guard/config.d.ts +3 -43
  5. package/lib/guard/config.js +3 -95
  6. package/lib/guard/index.d.ts +0 -17
  7. package/lib/guard/index.js +4 -54
  8. package/lib/guard/journal.js +11 -1
  9. package/lib/guard/paths.d.ts +0 -6
  10. package/lib/guard/paths.js +0 -12
  11. package/lib/guard/rules.js +1 -3
  12. package/lib/health-poller.d.ts +0 -2
  13. package/lib/health-poller.js +0 -4
  14. package/lib/notifier.d.ts +0 -8
  15. package/lib/notifier.js +0 -19
  16. package/lib/paths.d.ts +2 -3
  17. package/lib/paths.js +3 -8
  18. package/lib/plugin.d.ts +0 -1
  19. package/lib/plugin.js +37 -29
  20. package/lib/preset.js +1 -1
  21. package/lib/restart-exec.d.ts +0 -1
  22. package/lib/restart-exec.js +0 -1
  23. package/lib/restart-guards.d.ts +1 -1
  24. package/lib/restart-guards.js +3 -33
  25. package/lib/self-kill-guard.d.ts +0 -2
  26. package/lib/self-kill-guard.js +0 -4
  27. package/lib/supervisor.d.ts +0 -1
  28. package/lib/supervisor.js +0 -9
  29. package/lib/sync/cli.js +0 -8
  30. package/lib/sync/config.d.ts +1 -19
  31. package/lib/sync/config.js +0 -18
  32. package/lib/sync/index.js +2 -17
  33. package/lib/sync/merge.d.ts +0 -2
  34. package/lib/sync/merge.js +0 -2
  35. package/lib/sync/remote-agent.d.ts +0 -1
  36. package/lib/sync/remote-agent.js +0 -1
  37. package/lib/sync/snapshot.d.ts +0 -5
  38. package/lib/sync/snapshot.js +0 -33
  39. package/lib/sync/sync-service.d.ts +0 -20
  40. package/lib/sync/sync-service.js +0 -13
  41. package/lib/sync/transport.d.ts +1 -1
  42. package/lib/sync/transport.js +0 -4
  43. package/lib/types/client/config/MaestroSettings.d.ts.map +1 -1
  44. package/lib/types/client/config/components/BrandMark.d.ts +5 -2
  45. package/lib/types/client/config/components/BrandMark.d.ts.map +1 -1
  46. package/lib/types/client/config/guard-view.d.ts +7 -10
  47. package/lib/types/client/config/guard-view.d.ts.map +1 -1
  48. package/lib/types/client/sync/ui.d.ts +0 -4
  49. package/lib/types/client/sync/ui.d.ts.map +1 -1
  50. package/package.json +5 -2
  51. package/skills/dsh-safe-restart/SKILL.md +1 -1
  52. package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +6 -5
  53. package/src/client/config/MaestroSettings.tsx +4 -9
  54. package/src/client/config/components/BrandMark.tsx +5 -2
  55. package/src/client/config/guard-view.ts +10 -37
  56. package/src/client/sync/ui.tsx +1 -17
  57. package/src/host/guard/config.ts +4 -107
  58. package/src/host/guard/index.ts +4 -53
  59. package/src/host/guard/journal.ts +9 -1
  60. package/src/host/guard/paths.ts +0 -11
  61. package/src/host/guard/rules.ts +1 -3
  62. package/src/host/health-poller.ts +0 -5
  63. package/src/host/notifier.ts +0 -26
  64. package/src/host/paths.ts +3 -7
  65. package/src/host/plugin.ts +34 -28
  66. package/src/host/preset.ts +1 -1
  67. package/src/host/restart-exec.ts +0 -2
  68. package/src/host/restart-guards.ts +3 -27
  69. package/src/host/self-kill-guard.ts +0 -5
  70. package/src/host/supervisor.ts +0 -8
  71. package/src/host/sync/backup-config.ts +0 -1
  72. package/src/host/sync/cli.ts +0 -9
  73. package/src/host/sync/config.ts +1 -24
  74. package/src/host/sync/index.ts +1 -41
  75. package/src/host/sync/merge.ts +0 -3
  76. package/src/host/sync/remote-agent.ts +0 -1
  77. package/src/host/sync/snapshot.ts +0 -30
  78. package/src/host/sync/ssh-mux.ts +0 -1
  79. package/src/host/sync/sync-service.ts +2 -32
  80. package/src/host/sync/transport.ts +2 -7
  81. package/lib/guard/migrate.d.ts +0 -15
  82. package/lib/guard/migrate.js +0 -42
  83. package/lib/sync/session-merge.d.ts +0 -18
  84. package/lib/sync/session-merge.js +0 -191
  85. package/scripts/sync/bench-preview.mjs +0 -43
  86. package/scripts/sync/cdp-sync-probe.mjs +0 -200
  87. package/scripts/sync/cdp-sync-verify.mjs +0 -169
  88. package/src/host/guard/migrate.ts +0 -41
  89. package/src/host/sync/session-merge.ts +0 -220
@@ -1,191 +0,0 @@
1
- /**
2
- * Session Zstandard line union. DSH session artifacts require the first
3
- * checksummed Zstandard frame to contain exactly their JSONL header line.
4
- * Binary-safe: .jsonl.zstd is staged and merged only through validated Zstd artifact API.
5
- * Zstd bytes remain Buffer and are never converted to UTF-8 string; only decompressed
6
- * plaintext is stringified for line union. The standalone checksummed header frame is preserved.
7
- */
8
- import { copyFile, open, readFile, rename, unlink } from 'node:fs/promises';
9
- import { existsSync } from 'node:fs';
10
- import { randomBytes } from 'node:crypto';
11
- import { dirname } from 'node:path';
12
- import { constants, zstdCompress, zstdDecompress } from 'node:zlib';
13
- import { promisify } from 'node:util';
14
- const ZSTD_MAGIC = 0xFD2FB528;
15
- const compressZstd = promisify(zstdCompress);
16
- const decompressZstd = promisify(zstdDecompress);
17
- const ZSTD_CHECKSUM_OPTIONS = {
18
- params: { [constants.ZSTD_c_checksumFlag]: 1 },
19
- };
20
- /**
21
- * Union JSONL lines (or any line-delimited text) by exact line equality.
22
- * Preserves local order then appends remote-only lines.
23
- * Ensures trailing newline when result is non-empty.
24
- */
25
- export function mergeZstdLines(localText, remoteText) {
26
- const localLines = String(localText ?? '')
27
- .split('\n')
28
- .filter((line) => line.length > 0);
29
- const remoteLines = String(remoteText ?? '')
30
- .split('\n')
31
- .filter((line) => line.length > 0);
32
- const seen = new Set(localLines);
33
- const mergedArr = [...localLines];
34
- let added = 0;
35
- for (const line of remoteLines) {
36
- if (!seen.has(line)) {
37
- seen.add(line);
38
- mergedArr.push(line);
39
- added++;
40
- }
41
- }
42
- const merged = mergedArr.length > 0 ? mergedArr.join('\n') + '\n' : '';
43
- return { merged, added };
44
- }
45
- /** Locate complete normal Zstandard frames in a concatenated DSH artifact. */
46
- function scanZstdFrames(source) {
47
- const frames = [];
48
- let offset = 0;
49
- while (offset < source.length) {
50
- const start = offset;
51
- if (source.length - offset < 5 || source.readUInt32LE(offset) !== ZSTD_MAGIC) {
52
- throw new Error('corrupt Zstandard session artifact');
53
- }
54
- offset += 4;
55
- const descriptor = source.readUInt8(offset++);
56
- if ((descriptor & 0x18) !== 0)
57
- throw new Error('corrupt Zstandard frame descriptor');
58
- const contentSizeFlag = descriptor >>> 6;
59
- const singleSegment = (descriptor & 0x20) !== 0;
60
- const dictionaryFlag = descriptor & 0x03;
61
- const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag;
62
- const contentSizeBytes = contentSizeFlag === 0
63
- ? (singleSegment ? 1 : 0)
64
- : 1 << contentSizeFlag;
65
- const frameHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes;
66
- if (source.length - offset < frameHeaderBytes)
67
- throw new Error('incomplete Zstandard frame header');
68
- offset += frameHeaderBytes;
69
- for (;;) {
70
- if (source.length - offset < 3)
71
- throw new Error('incomplete Zstandard frame block');
72
- const blockHeader = source.readUIntLE(offset, 3);
73
- offset += 3;
74
- const lastBlock = (blockHeader & 1) !== 0;
75
- const blockType = (blockHeader >>> 1) & 0x03;
76
- const blockSize = blockHeader >>> 3;
77
- if (blockType === 3)
78
- throw new Error('corrupt Zstandard frame block');
79
- const payloadBytes = blockType === 1 ? 1 : blockSize;
80
- if (source.length - offset < payloadBytes)
81
- throw new Error('incomplete Zstandard frame payload');
82
- offset += payloadBytes;
83
- if (lastBlock)
84
- break;
85
- }
86
- if ((descriptor & 0x04) !== 0) {
87
- if (source.length - offset < 4)
88
- throw new Error('incomplete Zstandard frame checksum');
89
- offset += 4;
90
- }
91
- frames.push({ start, end: offset });
92
- }
93
- return frames;
94
- }
95
- function parseSessionHeader(header, label) {
96
- if (header.length === 0 || header.indexOf(0x0A) !== header.length - 1) {
97
- throw new Error(`${label} session artifact has no standalone header frame`);
98
- }
99
- const line = header.subarray(0, -1).toString('utf8');
100
- let value;
101
- try {
102
- value = JSON.parse(line);
103
- }
104
- catch {
105
- throw new Error(`${label} session artifact has an invalid session header`);
106
- }
107
- const record = value;
108
- const hasValidInteger = (field) => {
109
- const value = record?.[field];
110
- return typeof value === 'number'
111
- && Number.isSafeInteger(value)
112
- && value >= 0
113
- && !Object.is(value, -0);
114
- };
115
- if (record === null
116
- || typeof record !== 'object'
117
- || record.type !== 'session'
118
- || typeof record.version !== 'number'
119
- || typeof record.id !== 'string'
120
- || !hasValidInteger('createdAt')
121
- || !hasValidInteger('delegationDepth')
122
- || (record.origin !== undefined && record.origin !== 'subagent')
123
- || (record.agentPreset !== undefined && typeof record.agentPreset !== 'string')) {
124
- throw new Error(`${label} session artifact has an invalid session header`);
125
- }
126
- return line;
127
- }
128
- async function readSessionArtifact(filePath, label) {
129
- if (!existsSync(filePath))
130
- throw new Error(`${label} session artifact does not exist`);
131
- const source = await readFile(filePath);
132
- const frames = scanZstdFrames(source);
133
- if (frames.length === 0)
134
- throw new Error(`${label} session artifact has no Zstandard frames`);
135
- const headerBytes = await decompressZstd(source.subarray(frames[0].start, frames[0].end));
136
- const header = parseSessionHeader(headerBytes, label);
137
- const plaintext = await Promise.all(frames.map(async ({ start, end }) => decompressZstd(source.subarray(start, end))));
138
- return { header, text: Buffer.concat(plaintext).toString('utf8') };
139
- }
140
- async function writeAtomically(filePath, content) {
141
- const temporaryPath = `${filePath}.${randomBytes(12).toString('hex')}.tmp`;
142
- const handle = await open(temporaryPath, 'wx', 0o600);
143
- try {
144
- await handle.writeFile(content);
145
- await handle.sync();
146
- }
147
- finally {
148
- await handle.close();
149
- }
150
- try {
151
- await rename(temporaryPath, filePath);
152
- }
153
- catch (error) {
154
- await unlink(temporaryPath).catch(() => undefined);
155
- throw error;
156
- }
157
- const directory = await open(dirname(filePath), 'r');
158
- try {
159
- await directory.sync();
160
- }
161
- finally {
162
- await directory.close();
163
- }
164
- }
165
- /**
166
- * Merge two valid DSH Zstandard session artifacts into the local artifact.
167
- * The original local bytes are copied to a timestamped backup before the
168
- * atomic publish. Invalid, missing, plaintext, or mismatched input never
169
- * replaces the local file.
170
- */
171
- export async function mergeZstdFiles(localPath, remotePath) {
172
- const local = await readSessionArtifact(localPath, 'local');
173
- const remote = await readSessionArtifact(remotePath, 'remote');
174
- if (local.header !== remote.header) {
175
- throw new Error('cannot merge session artifacts with different headers');
176
- }
177
- const { merged, added } = mergeZstdLines(local.text, remote.text);
178
- if (added === 0)
179
- return { added: 0 };
180
- if (!merged.startsWith(local.header + '\n')) {
181
- throw new Error('merged session artifact lost its header');
182
- }
183
- const body = merged.slice(local.header.length + 1);
184
- const frames = [await compressZstd(local.header + '\n', ZSTD_CHECKSUM_OPTIONS)];
185
- if (body.length > 0)
186
- frames.push(await compressZstd(body, ZSTD_CHECKSUM_OPTIONS));
187
- const backupPath = `${localPath}.bak.${Date.now()}.${randomBytes(6).toString('hex')}`;
188
- await copyFile(localPath, backupPath);
189
- await writeAtomically(localPath, Buffer.concat(frames));
190
- return { added };
191
- }
@@ -1,43 +0,0 @@
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`);
@@ -1,200 +0,0 @@
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))
@@ -1,169 +0,0 @@
1
- // Live verify: settings card shows real status counts and Preview Pull lists real actions.
2
- // Usage: DSH_WEB_TOKEN=... node scripts/cdp-sync-verify.mjs [mobile|desktop]
3
- import http from 'node:http'
4
- import { spawn } from 'node:child_process'
5
- import { mkdtempSync } from 'node:fs'
6
- import { tmpdir } from 'node:os'
7
- import { join } from 'node:path'
8
-
9
- const TOKEN = process.env.DSH_WEB_TOKEN || ''
10
- const SESSION_ID = process.env.DSH_SESSION_ID || 'session-5674e8fd-f84a-4437-b648-b660fe59dbc9'
11
- const TOKEN_URL = `http://127.0.0.1:3080/?token=${TOKEN}`
12
- const MODE = process.argv[2] ?? 'mobile'
13
- const VIEW = MODE === 'mobile' ? { width: 390, height: 844, deviceScaleFactor: 2, mobile: true, hasTouch: true } : { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false, hasTouch: false }
14
-
15
- function allocPort() {
16
- return new Promise((res) => {
17
- const srv = http.createServer()
18
- srv.listen(0, '127.0.0.1', () => {
19
- const p = srv.address().port
20
- srv.close(() => res(p))
21
- })
22
- })
23
- }
24
- function rpc(ws, method, params = {}) {
25
- return new Promise((res, rej) => {
26
- const id = ++rpc._seq
27
- const onMsg = (ev) => {
28
- const m = JSON.parse(ev.data.toString())
29
- if (m.id !== id) return
30
- ws.removeEventListener('message', onMsg)
31
- if (m.error) rej(new Error(method + ': ' + JSON.stringify(m.error)))
32
- else res(m.result)
33
- }
34
- ws.addEventListener('message', onMsg)
35
- ws.send(JSON.stringify({ id, method, params }))
36
- })
37
- }
38
- rpc._seq = 0
39
-
40
- async function evalJs(ws, expr) {
41
- const r = await rpc(ws, 'Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true })
42
- if (r.exceptionDetails) throw new Error('eval failed: ' + JSON.stringify(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text))
43
- return r.result.value
44
- }
45
-
46
- async function main() {
47
- const port = await allocPort()
48
- const userData = mkdtempSync(join(tmpdir(), 'sync-verify-'))
49
- const chrome = spawn('/opt/google/chrome/chrome', [
50
- '--headless=new', '--no-sandbox', '--remote-debugging-port=' + port, '--user-data-dir=' + userData,
51
- ], { stdio: 'ignore' })
52
- let ws = null
53
- try {
54
- // wait for devtools endpoint
55
- let pages
56
- for (let i = 0; i < 50; i++) {
57
- try {
58
- pages = await fetch(`http://127.0.0.1:${port}/json`).then((r) => r.json())
59
- if (pages?.length) break
60
- } catch {}
61
- await new Promise((r) => setTimeout(r, 200))
62
- }
63
- const page = pages.find((p) => p.type === 'page')
64
- ws = await new Promise((res, rej) => {
65
- const w = new WebSocket(page.webSocketDebuggerUrl)
66
- w.addEventListener('open', () => res(w))
67
- w.addEventListener('error', (e) => rej(new Error('ws error')))
68
- })
69
-
70
- await rpc(ws, 'Emulation.setDeviceMetricsOverride', VIEW)
71
- await rpc(ws, 'Page.addScriptToEvaluateOnNewDocument', {
72
- source: `try { localStorage.setItem('dsh.sessions.current', ${JSON.stringify(JSON.stringify({ sessionId: SESSION_ID }))}); } catch (e) {}`,
73
- })
74
- await rpc(ws, 'Page.navigate', { url: TOKEN_URL })
75
- await new Promise((r) => setTimeout(r, 3000))
76
- // wait for app
77
- for (let i = 0; i < 50; i++) {
78
- const ready = await evalJs(ws, `typeof window.__DSH_BOOT__ === 'object' && !!(document.querySelector('[data-maestro-logo]') || document.body.innerText.includes('Settings'))`)
79
- if (ready) break
80
- await new Promise((r) => setTimeout(r, 300))
81
- }
82
- // open Settings -> Maestro Sync (mirrors cdp-sync-probe.mjs navigation)
83
- await evalJs(ws, `(() => { const b = document.querySelector('button[aria-label="Open sidebar"]'); if (b) { b.click(); return true; } return false; })()`)
84
- await new Promise((r) => setTimeout(r, 1200))
85
- const settingsBtn = await evalJs(ws, `(() => {
86
- const els = Array.from(document.querySelectorAll('button, [role="button"]'));
87
- const hit = els.find((el) => {
88
- const label = el.getAttribute('aria-label') || el.title || (el.textContent || '');
89
- return label.trim().toLowerCase() === 'settings';
90
- });
91
- if (!hit) return null;
92
- hit.click();
93
- return true;
94
- })()`)
95
- if (!settingsBtn) throw new Error('settings trigger not found')
96
- await new Promise((r) => setTimeout(r, 1400))
97
- const syncNav = await evalJs(ws, `(() => {
98
- const dialog = document.querySelector('[role="dialog"]');
99
- if (!dialog) return null;
100
- const btns = Array.from(dialog.querySelectorAll('button'));
101
- const hit = btns.find((el) => (el.textContent || '').trim().toLowerCase().includes('maestro sync'));
102
- if (!hit) return null;
103
- hit.click();
104
- return true;
105
- })()`)
106
- if (!syncNav) throw new Error('maestro sync trigger not found')
107
- // wait for status to resolve (no longer "Checking connection…")
108
- let cardText = ''
109
- for (let i = 0; i < 60; i++) {
110
- cardText = await evalJs(ws, `(() => { const c = document.querySelector('[data-sync-card], [data-maestro-logo]'); if (!c) return ''; let el = c; for (let k = 0; k < 6 && el; k++) { if ((el.innerText || '').includes('REMOTE HOST')) break; el = el.parentElement; } return (el || c).innerText })()`)
111
- if (!cardText.includes('Checking connection')) break
112
- await new Promise((r) => setTimeout(r, 500))
113
- }
114
- // stats + status line
115
- const body = await evalJs(ws, `document.body.innerText`)
116
- const statTiles = await evalJs(ws, `(() => { const tiles = [...document.querySelectorAll('[data-stat-tile], [data-stat]')].map((t) => t.innerText.replace(/\\n/g, ' ')); return tiles })()`)
117
- // wait for bucket page loads to settle (data-sync-file rows appear)
118
- for (let i = 0; i < 60; i++) {
119
- const n = await evalJs(ws, `document.querySelectorAll('[data-sync-file]').length`)
120
- if (n > 0) break
121
- await new Promise((r) => setTimeout(r, 500))
122
- }
123
- // dump the file-list sections verbatim (no preview click, avoids busy noise)
124
- const listSections = await evalJs(ws, `(() => {
125
- const el = document.querySelector('[data-sync-card], [data-maestro-logo]');
126
- if (!el) return [];
127
- let root = el; for (let k = 0; k < 6 && root; k++) { if ((root.innerText || '').includes('Coming from the other machine')) break; root = root.parentElement; }
128
- if (!root) return [];
129
- return { section: (root.innerText || '').slice(0, 2000) };
130
- })()`)
131
- await evalJs(ws, `(() => { const el = document.querySelector('[data-testid="sync-preview-pull"]'); if (el) el.click(); return !!el })()`)
132
- // capture the progress bar while the count-only preview runs (hashing ticks)
133
- let progressSeen = null
134
- for (let i = 0; i < 40; i++) {
135
- progressSeen = await evalJs(ws, `(() => { const p = document.querySelector('[data-sync-progress]'); if (!p) return null; return p.innerText.slice(0, 200) })()`)
136
- if (progressSeen) break
137
- await new Promise((r) => setTimeout(r, 300))
138
- }
139
- let dialog = null
140
- // remote preview runs a checksum-only session count now (~10s); md stage can still take a while
141
- for (let i = 0; i < 360; i++) {
142
- const alertHit = await evalJs(ws, `(() => { const a = document.querySelector('[role="alert"]'); return a ? a.innerText.slice(0, 300) : null })()`)
143
- if (alertHit) { dialog = { alert: alertHit, rows: 0 }; break }
144
- dialog = await evalJs(ws, `(() => { const d = [...document.querySelectorAll('[role="dialog"]')].find((x) => (x.innerText || '').includes('Cancel') && (x.innerText || '').includes('Apply')); if (!d) return null; const sc = d.querySelector('[data-sync-sessioncounts]'); return { text: d.innerText.slice(0, 800), rows: d.querySelectorAll('[data-action-row]').length, hasPreviewId: !!(d.innerText || '').match(/[a-f0-9]{32}/), sessionCounts: sc ? sc.innerText : null } })()`)
145
- if (dialog) break
146
- await new Promise((r) => setTimeout(r, 500))
147
- }
148
- const listSectionsOut = listSections
149
- const statLines = body.split('\n').filter((l) => /^\d+$/.test(l.trim())).slice(0, 6)
150
-
151
- const out = {
152
- mode: MODE,
153
- hasCard: await evalJs(ws, `!!document.querySelector('[data-maestro-logo]')`),
154
- statusResolved: !cardText.includes('Checking connection'),
155
- cardHead: cardText.slice(0, 160).replace(/\n/g, ' | '),
156
- statTiles,
157
- statsDigits: statLines,
158
- previewButtonClicked: !!(await evalJs(ws, `!!document.querySelector('[data-testid="sync-preview-pull"]')`)),
159
- progressSeen,
160
- lists: listSectionsOut,
161
- dialog,
162
- }
163
- console.log(JSON.stringify(out, null, 2))
164
- } finally {
165
- ws?.close()
166
- chrome.kill('SIGKILL')
167
- }
168
- }
169
- main().catch((e) => { console.error(e); process.exit(1) })
@@ -1,41 +0,0 @@
1
- import { chmod, mkdir, rename, stat } from 'node:fs/promises'
2
- import { join } from 'node:path'
3
- import { Journal, journalDir } from './journal.js'
4
-
5
- /**
6
- * Retire the legacy ticket store (Task A4). The guard no longer reads tickets —
7
- * the human answers through DSH's native approval service — so the old
8
- * `pending.json` is moved out of its active path into the journal directory,
9
- * where it is kept for reference but never consulted again.
10
- *
11
- * This runs once per boot inside `ctx.effect`; it is idempotent (a missing
12
- * source is a no-op) and never throws, because a failed retirement must not
13
- * stop the guard from booting.
14
- */
15
- export async function retireLegacyStore(journal: Journal, dshHome?: string): Promise<{ moved: boolean; to?: string }> {
16
- const dir = journalDir(dshHome)
17
- const from = join(dir, 'pending.json')
18
- const to = join(dir, 'legacy-pending.json')
19
- try {
20
- await stat(from)
21
- } catch {
22
- return { moved: false }
23
- }
24
- try {
25
- await mkdir(dir, { recursive: true, mode: 0o700 })
26
- await rename(from, to)
27
- await chmod(to, 0o600)
28
- await journal.append({
29
- tool: 'guard',
30
- rule: 'guard.migration',
31
- tier: 'journal',
32
- target: to,
33
- outcome: 'passed',
34
- note: 'legacy ticket store retired; retained for reference, no longer read by the guard',
35
- })
36
- return { moved: true, to }
37
- } catch (e) {
38
- console.error('[dsh-maestro-guard] legacy store retirement failed:', (e as Error)?.message)
39
- return { moved: false }
40
- }
41
- }