@ran-sh/dsh-crew 1.1.1 → 1.2.0-rc.4

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 (83) hide show
  1. package/.claude-plugin/marketplace.json +16 -17
  2. package/.claude-plugin/plugin.json +7 -1
  3. package/README.md +44 -15
  4. package/README.zh.md +37 -12
  5. package/agents/ds-flash.md +16 -18
  6. package/agents/ds-pro.md +16 -24
  7. package/agents/ds-reviewer.md +15 -15
  8. package/agents/ds-worker.md +16 -16
  9. package/bin/dsh-crew.mjs +16 -12
  10. package/codex/AGENTS.md +37 -85
  11. package/codex/agents/ds-flash.toml +18 -14
  12. package/codex/agents/ds-pro.toml +18 -15
  13. package/codex/agents/ds-reviewer.toml +17 -13
  14. package/codex/agents/ds-worker.toml +17 -13
  15. package/codex/prompts/dsh-config.md +17 -1
  16. package/codex/prompts/dsh-status.md +5 -1
  17. package/commands/config.md +16 -4
  18. package/commands/status.md +6 -2
  19. package/docs/installation.md +54 -9
  20. package/docs/readiness-matrix.md +14 -6
  21. package/docs/ui-surfaces.md +32 -17
  22. package/lib/client.js +5434 -4844
  23. package/official-web-bridge/lib/client.js +567 -479
  24. package/official-web-bridge/overlay-entry.mjs +59 -0
  25. package/package.json +6 -3
  26. package/scripts/build-client.mjs +2 -0
  27. package/scripts/setup.mjs +8 -7
  28. package/scripts/verify-crew-ui-polish.mjs +145 -0
  29. package/scripts/verify-history-ui.mjs +97 -0
  30. package/scripts/verify-npm-install.mjs +1 -1
  31. package/src/client/history-panel.tsx +108 -0
  32. package/src/client/host-readiness.mjs +15 -6
  33. package/src/client/index.tsx +86 -64
  34. package/src/client/model-callability-view.mjs +17 -0
  35. package/src/client/panel-chrome.tsx +40 -0
  36. package/src/client/quick-panel.tsx +88 -73
  37. package/src/client/readiness-envelope.mjs +34 -0
  38. package/src/config-readiness.mjs +181 -115
  39. package/src/extension-contract.mjs +44 -26
  40. package/src/history/admission-gate.mjs +51 -0
  41. package/src/history/archive-store.mjs +261 -0
  42. package/src/history/cleanup-plan.mjs +64 -0
  43. package/src/history/http.mjs +32 -0
  44. package/src/history/operation.mjs +86 -0
  45. package/src/history/runner.mjs +51 -0
  46. package/src/history/runtime.mjs +28 -0
  47. package/src/history/service.mjs +137 -0
  48. package/src/history/state.mjs +27 -0
  49. package/src/hub/index.mjs +141 -24
  50. package/src/hub-client.mjs +17 -15
  51. package/src/image-output.mjs +71 -0
  52. package/src/install/install-legacy.mjs +126 -23
  53. package/src/install/npx-lifecycle.mjs +373 -64
  54. package/src/install/official-frontend-assets.mjs +78 -0
  55. package/src/install/payload-content.mjs +88 -0
  56. package/src/install/windows-startup.mjs +107 -19
  57. package/src/install/windows-supervisor-adapter.mjs +443 -0
  58. package/src/install/windows-supervisor-lifecycle.mjs +782 -0
  59. package/src/install/zcode.mjs +53 -14
  60. package/src/job-contracts.mjs +37 -31
  61. package/src/jobs.mjs +2 -2
  62. package/src/mcp-runtime.mjs +74 -9
  63. package/src/model-callability-contract.mjs +79 -0
  64. package/src/multimodal.mjs +0 -0
  65. package/src/official-web-bridge.mjs +0 -2
  66. package/src/provider-health.mjs +130 -124
  67. package/src/readiness-matrix.mjs +20 -15
  68. package/src/runtime-identity-contract.mjs +34 -0
  69. package/src/runtime-identity.mjs +14 -4
  70. package/src/runtime-readiness-snapshot.mjs +285 -87
  71. package/src/server.mjs +86 -76
  72. package/src/standalone-sdk.mjs +23 -0
  73. package/src/supervisor/restart-request.mjs +64 -10
  74. package/src/workflow-runtime.mjs +28 -13
  75. package/windows/start-dsh-crew.cmd +57 -57
  76. package/windows/start-dsh-crew.ps1 +314 -51
  77. package/windows/supervisor-control.ps1 +467 -0
  78. package/zcode/AGENTS.md +4 -1
  79. package/zcode/agents/ds-reviewer.md +31 -36
  80. package/zcode/agents/ds-worker.md +31 -39
  81. package/zcode/commands/dsh-config.md +17 -6
  82. package/zcode/commands/dsh-status.md +5 -4
  83. package/.mcp.json +0 -8
@@ -0,0 +1,443 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { createServer } from 'node:net';
4
+ import { existsSync, readFileSync } from 'node:fs';
5
+ import { join, win32 } from 'node:path';
6
+ import { homedir } from 'node:os';
7
+
8
+ import {
9
+ readMaintenanceSession,
10
+ readSupervisorHeartbeat,
11
+ readSupervisorHeartbeatRecord,
12
+ } from '../supervisor/restart-request.mjs';
13
+ import {
14
+ acquireWindowsSupervisorHandoffLock,
15
+ releaseWindowsSupervisorHandoffLock,
16
+ runWindowsSupervisorHandoff,
17
+ windowsSupervisorHandoffJournalPath,
18
+ windowsSupervisorHandoffLockPath,
19
+ } from './windows-supervisor-lifecycle.mjs';
20
+ import { readWindowsSupervisorAssets } from './windows-startup.mjs';
21
+
22
+ const HASH_RE = /^[a-f0-9]{64}$/u;
23
+ export const PENDING_RUNTIME_ACTIVATION = 'runtime-activation-pending';
24
+ const EXACT_VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
25
+
26
+ function text(value) {
27
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
28
+ }
29
+
30
+ function sameHash(left, right) {
31
+ return typeof left === 'string' && typeof right === 'string' && left.toLowerCase() === right.toLowerCase();
32
+ }
33
+
34
+ export function validateSupervisorRuntime(runtime, { expectedCrewVersion = null, expectedDshVersion = null } = {}) {
35
+ return !!runtime
36
+ && text(runtime.runtime_id) !== null
37
+ && runtime.service === 'dsh-crew-hub'
38
+ && runtime.execution_plane === 'hub-3210'
39
+ && runtime.profile === 'dsh-crew'
40
+ && Number(runtime.listen_port) === 3210
41
+ && Number(runtime.protocol_version) === 1
42
+ && (!expectedCrewVersion || runtime.runtime_version === expectedCrewVersion)
43
+ && (!expectedDshVersion || runtime.dsh_version === expectedDshVersion);
44
+ }
45
+
46
+ export function hashSupervisorHelper(file) {
47
+ try { return createHash('sha256').update(readFileSync(file)).digest('hex'); } catch { return null; }
48
+ }
49
+
50
+ export function canonicalWindowsPowerShellPath({
51
+ environment = process.env,
52
+ exists = existsSync,
53
+ } = {}) {
54
+ const systemRoot = text(environment.SystemRoot ?? environment.SYSTEMROOT ?? environment.WINDIR ?? environment.windir);
55
+ if (!systemRoot || !win32.isAbsolute(systemRoot)) return null;
56
+ const candidate = win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
57
+ return exists(candidate) ? candidate : null;
58
+ }
59
+
60
+ function samePath(left, right) {
61
+ return typeof left === 'string'
62
+ && typeof right === 'string'
63
+ && left.replaceAll('/', '\\').toLowerCase() === right.replaceAll('/', '\\').toLowerCase();
64
+ }
65
+
66
+ export function runWindowsSupervisorControl(request, {
67
+ controlScript,
68
+ timeoutMs = 60_000,
69
+ maxOutputBytes = 64 * 1024,
70
+ spawnImpl = spawn,
71
+ environment = process.env,
72
+ exists = existsSync,
73
+ } = {}) {
74
+ return new Promise((resolve) => {
75
+ if (!text(controlScript)) {
76
+ resolve({ ok: false, code: 'SUPERVISOR_CONTROL_SCRIPT_MISSING' });
77
+ return;
78
+ }
79
+ const powerShell = canonicalWindowsPowerShellPath({ environment, exists });
80
+ if (!powerShell) {
81
+ resolve({ ok: false, code: 'SUPERVISOR_CONTROL_POWERSHELL_UNAVAILABLE' });
82
+ return;
83
+ }
84
+ let child;
85
+ try {
86
+ child = spawnImpl(powerShell, [
87
+ '-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
88
+ '-File', controlScript,
89
+ ], { windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
90
+ } catch {
91
+ resolve({ ok: false, code: 'SUPERVISOR_CONTROL_START_FAILED' });
92
+ return;
93
+ }
94
+ let stdout = '';
95
+ let stderr = '';
96
+ let settled = false;
97
+ let timer = null;
98
+ const finish = (result) => {
99
+ if (settled) return;
100
+ settled = true;
101
+ clearTimeout(timer);
102
+ resolve(result);
103
+ };
104
+ const append = (current, chunk) => {
105
+ const next = current + String(chunk);
106
+ if (Buffer.byteLength(next, 'utf8') > maxOutputBytes) {
107
+ try { child.kill(); } catch {}
108
+ finish({ ok: false, code: 'SUPERVISOR_CONTROL_OUTPUT_LIMIT' });
109
+ return current;
110
+ }
111
+ return next;
112
+ };
113
+ child.stdout?.setEncoding('utf8');
114
+ child.stderr?.setEncoding('utf8');
115
+ child.stdout?.on('data', (chunk) => { stdout = append(stdout, chunk); });
116
+ child.stderr?.on('data', (chunk) => { stderr = append(stderr, chunk); });
117
+ child.on('error', () => finish({ ok: false, code: 'SUPERVISOR_CONTROL_START_FAILED' }));
118
+ child.on('close', (code) => {
119
+ if (settled) return;
120
+ let parsed = null;
121
+ try { parsed = JSON.parse(stdout.trim()); } catch {}
122
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
123
+ finish({ ok: false, code: 'SUPERVISOR_CONTROL_RESPONSE_INVALID', detail: stderr.trim().slice(-300) || null });
124
+ return;
125
+ }
126
+ finish(code === 0 && parsed.ok === true
127
+ ? parsed
128
+ : { ok: false, code: text(parsed.code) ?? 'SUPERVISOR_CONTROL_FAILED', error: text(parsed.error) ?? null });
129
+ });
130
+ timer = setTimeout(() => {
131
+ try { child.kill(); } catch {}
132
+ finish({ ok: false, code: 'SUPERVISOR_CONTROL_TIMEOUT' });
133
+ }, timeoutMs);
134
+ timer.unref?.();
135
+ try { child.stdin.end(JSON.stringify(request)); } catch { finish({ ok: false, code: 'SUPERVISOR_CONTROL_STDIN_FAILED' }); }
136
+ });
137
+ }
138
+
139
+ function portFree(port = 3210) {
140
+ return new Promise((resolve) => {
141
+ const server = createServer();
142
+ server.unref();
143
+ server.once('error', () => resolve({ ok: true, free: false }));
144
+ server.listen({ host: '127.0.0.1', port, exclusive: true }, () => {
145
+ server.close(() => resolve({ ok: true, free: true }));
146
+ });
147
+ });
148
+ }
149
+
150
+ async function runtimeFromHub(fetchImpl = globalThis.fetch, timeoutMs = 3_000) {
151
+ try {
152
+ const response = await fetchImpl('http://127.0.0.1:3210/_dsh/dsh-crew/extension', {
153
+ headers: { accept: 'application/json' },
154
+ signal: AbortSignal.timeout(Math.max(1, Math.min(3_000, timeoutMs))),
155
+ });
156
+ if (!response.ok) return null;
157
+ const body = await response.json();
158
+ return body?.ok === true ? body.extension?.runtime ?? null : null;
159
+ } catch { return null; }
160
+ }
161
+
162
+ function watcherRequest(operation, target, expected = null, { allowHelperDrift = false } = {}) {
163
+ return {
164
+ operation,
165
+ helper_path: target.helper_path,
166
+ ...(expected ? { expected } : {}),
167
+ ...(allowHelperDrift ? { allow_helper_drift: true } : {}),
168
+ ...(operation === 'start' ? { helper_hash: target.helper_hash } : {}),
169
+ };
170
+ }
171
+
172
+ export function createWindowsSupervisorHandoffHooks({
173
+ appRoot = null,
174
+ target,
175
+ maintenanceClient,
176
+ expectedCrewVersion = null,
177
+ expectedDshVersion = null,
178
+ readHeartbeatRecord = () => readSupervisorHeartbeatRecord(appRoot, { staleAfterMs: 30_000 }),
179
+ readAuthoritativeHeartbeat = () => readSupervisorHeartbeat(appRoot, { staleAfterMs: 30_000 }),
180
+ runControl,
181
+ controlScript,
182
+ fetchRuntime = ({ timeoutMs = 3_000 } = {}) => runtimeFromHub(globalThis.fetch, timeoutMs),
183
+ verifyPortFree = ({ port }) => portFree(port),
184
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
185
+ readyTimeoutMs = 90_000,
186
+ heartbeatRecoveryAttempts = 180,
187
+ heartbeatRecoveryPollMs = 500,
188
+ now = Date.now,
189
+ } = {}) {
190
+ const control = runControl ?? ((request) => runWindowsSupervisorControl(request, { controlScript }));
191
+
192
+ const inspect = async (expected, { allowHelperDrift = false } = {}) => control(watcherRequest(
193
+ 'inspect', target, expected, { allowHelperDrift },
194
+ ));
195
+ const classifyHeartbeat = async ({
196
+ expect_target: expectTarget = false,
197
+ attempt = 0,
198
+ deadline = null,
199
+ live_runtime_seen: liveRuntimeSeen = false,
200
+ } = {}) => {
201
+ const cutoff = Number.isFinite(deadline) ? deadline : now() + readyTimeoutMs;
202
+ const remaining = () => Math.max(0, cutoff - now());
203
+ const fetchWithinBudget = async () => {
204
+ const budget = remaining();
205
+ return budget > 0 ? fetchRuntime({ timeoutMs: Math.min(3_000, budget) }) : null;
206
+ };
207
+ const retry = async (sawLive) => {
208
+ const budget = remaining();
209
+ if (attempt >= heartbeatRecoveryAttempts || budget <= 0) return null;
210
+ await sleep(Math.min(heartbeatRecoveryPollMs, budget));
211
+ return classifyHeartbeat({
212
+ expect_target: expectTarget,
213
+ attempt: attempt + 1,
214
+ deadline: cutoff,
215
+ live_runtime_seen: sawLive,
216
+ });
217
+ };
218
+ const observed = readHeartbeatRecord();
219
+ let runtime = null;
220
+ if (!observed) {
221
+ runtime = await fetchWithinBudget();
222
+ const sawLive = liveRuntimeSeen || !!runtime?.runtime_id;
223
+ if (sawLive || expectTarget) {
224
+ const retried = await retry(sawLive);
225
+ if (retried) return retried;
226
+ }
227
+ if (sawLive) return { ok: false, code: 'SUPERVISOR_HEARTBEAT_MISSING_WITH_LIVE_RUNTIME' };
228
+ if (expectTarget) return { ok: false, code: 'SUPERVISOR_TARGET_HEARTBEAT_TIMEOUT' };
229
+ return { ok: true, classification: 'absent', watcher: null, runtime_id: null };
230
+ }
231
+ const record = observed.record ?? {};
232
+ const expected = {
233
+ pid: record.pid,
234
+ ...(record.process_started_at_utc_ticks ? { process_started_at_utc_ticks: String(record.process_started_at_utc_ticks) } : {}),
235
+ ...(record.helper_hash ? { helper_hash: record.helper_hash } : {}),
236
+ };
237
+ const fullyAttestedStale = observed.state !== 'legacy-v1'
238
+ && expected.process_started_at_utc_ticks
239
+ && expected.helper_hash
240
+ && !sameHash(expected.helper_hash, target.helper_hash);
241
+ const inspected = await inspect(expected, { allowHelperDrift: fullyAttestedStale });
242
+ if (inspected?.ok === false && inspected.code === 'PROCESS_NOT_FOUND') {
243
+ if (expectTarget) {
244
+ const retried = await retry(liveRuntimeSeen);
245
+ if (retried) return retried;
246
+ }
247
+ runtime ??= await fetchWithinBudget();
248
+ if (runtime?.runtime_id) {
249
+ return { ok: false, code: 'SUPERVISOR_HEARTBEAT_PROCESS_MISSING_WITH_LIVE_RUNTIME' };
250
+ }
251
+ if (expectTarget) {
252
+ return {
253
+ ok: false,
254
+ code: liveRuntimeSeen
255
+ ? 'SUPERVISOR_HEARTBEAT_PROCESS_MISSING_WITH_LIVE_RUNTIME'
256
+ : 'SUPERVISOR_TARGET_HEARTBEAT_TIMEOUT',
257
+ };
258
+ }
259
+ return { ok: true, classification: 'absent', watcher: null, runtime_id: null };
260
+ }
261
+ if (inspected?.ok !== true || !inspected.watcher) return inspected ?? { ok: false, code: 'SUPERVISOR_WATCHER_UNVERIFIED' };
262
+ runtime ??= await fetchWithinBudget();
263
+ if (observed.state === 'legacy-v1') {
264
+ return runtime?.runtime_id
265
+ ? { ok: true, classification: 'legacy', watcher: inspected.watcher, runtime_id: runtime.runtime_id }
266
+ : { ok: false, code: 'SUPERVISOR_RUNTIME_IDENTITY_UNAVAILABLE' };
267
+ }
268
+ const targetHash = sameHash(record.helper_hash, target.helper_hash);
269
+ if (targetHash && observed.state === 'ready') {
270
+ return runtime?.runtime_id
271
+ ? { ok: true, classification: 'target-ready', watcher: inspected.watcher, runtime_id: runtime.runtime_id }
272
+ : { ok: false, code: 'SUPERVISOR_RUNTIME_IDENTITY_UNAVAILABLE' };
273
+ }
274
+ if (targetHash) return { ok: true, classification: 'target-starting', watcher: inspected.watcher, runtime_id: runtime?.runtime_id ?? null };
275
+ return runtime?.runtime_id
276
+ ? { ok: true, classification: 'stale', watcher: inspected.watcher, runtime_id: runtime.runtime_id }
277
+ : { ok: false, code: 'SUPERVISOR_RUNTIME_IDENTITY_UNAVAILABLE' };
278
+ };
279
+ return {
280
+ classifyHeartbeat,
281
+ verifyExactWatcher: async ({ expected, role }) => inspect(expected, {
282
+ allowHelperDrift: role === 'old' && !sameHash(expected?.helper_hash, target.helper_hash),
283
+ }),
284
+ maintenanceStop: async ({ lease, runtime_id: runtimeId }) => maintenanceClient?.stopOwnedBackend?.({ lease, runtimeId })
285
+ ?? { ok: false, code: 'SUPERVISOR_MAINTENANCE_UNAVAILABLE' },
286
+ maintenanceStatus: async ({ lease, runtime_id: runtimeId }) => {
287
+ const durable = readMaintenanceSession(appRoot);
288
+ if (!durable.ok) return durable;
289
+ if (durable.state === 'absent') return { ok: true, state: 'absent' };
290
+ const session = durable.session;
291
+ return session.lease === lease && session.runtime_id === runtimeId
292
+ ? { ok: true, state: 'matching', lease, runtime_id: runtimeId, request_id: session.request_id }
293
+ : { ok: true, state: 'conflict', lease: session.lease, runtime_id: session.runtime_id };
294
+ },
295
+ verifyPortFree,
296
+ stopExactWatcher: async ({ expected }) => control(watcherRequest('stop', target, expected, {
297
+ allowHelperDrift: !sameHash(expected?.helper_hash, target.helper_hash),
298
+ })),
299
+ launchTargetWatcher: async () => control(watcherRequest('start', target)),
300
+ maintenanceStart: async ({ lease, runtime_id: runtimeId }) => maintenanceClient?.startOwnedBackend?.({
301
+ lease,
302
+ runtimeId,
303
+ expectedCrewVersion,
304
+ expectedDshVersion,
305
+ }) ?? { ok: false, code: 'SUPERVISOR_MAINTENANCE_UNAVAILABLE' },
306
+ verifyReady: async ({ previous_runtime_id: previousRuntimeId }) => {
307
+ const deadline = now() + readyTimeoutMs;
308
+ while (now() <= deadline) {
309
+ const heartbeat = readAuthoritativeHeartbeat();
310
+ if (heartbeat && sameHash(heartbeat.helper_hash, target.helper_hash)) {
311
+ const exact = await inspect({
312
+ pid: heartbeat.pid,
313
+ process_started_at_utc_ticks: String(heartbeat.process_started_at_utc_ticks),
314
+ helper_hash: heartbeat.helper_hash,
315
+ });
316
+ const runtime = await fetchRuntime({ timeoutMs: Math.max(1, Math.min(3_000, deadline - now())) });
317
+ if (exact?.ok === true
318
+ && exact.watcher
319
+ && validateSupervisorRuntime(runtime, { expectedCrewVersion, expectedDshVersion })
320
+ && (!previousRuntimeId || runtime.runtime_id !== previousRuntimeId)) {
321
+ return { ok: true, watcher: exact.watcher, runtime };
322
+ }
323
+ }
324
+ await sleep(500);
325
+ }
326
+ return { ok: false, code: 'SUPERVISOR_READY_TIMEOUT' };
327
+ },
328
+ };
329
+ }
330
+
331
+ function prepareWindowsSupervisorConvergence({ home, root, platform }) {
332
+ if (platform !== 'win32') return { ok: true, skipped: true, reason: 'unsupported-platform' };
333
+ const appRoot = join(home, '.config', 'dsh-crew');
334
+ const assets = readWindowsSupervisorAssets({ home });
335
+ if (!assets.ok || !HASH_RE.test(assets.helper_hash) || !HASH_RE.test(assets.control_hash)) {
336
+ return { ok: false, code: 'SUPERVISOR_TARGET_UNAVAILABLE' };
337
+ }
338
+ let manifest = null;
339
+ try { manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')); } catch {}
340
+ const expectedCrewVersion = text(manifest?.version);
341
+ let expectedDshVersion = text(manifest?.dependencies?.['@deepseek-ai/dsh'] ?? manifest?.peerDependencies?.['@deepseek-ai/dsh']);
342
+ if (!EXACT_VERSION_RE.test(expectedDshVersion ?? '')) {
343
+ try {
344
+ const cohort = JSON.parse(readFileSync(join(root, 'release-cohort.json'), 'utf8'));
345
+ expectedDshVersion = text(cohort?.dsh_version);
346
+ } catch { expectedDshVersion = null; }
347
+ }
348
+ if (manifest?.name !== '@ran-sh/dsh-crew'
349
+ || !EXACT_VERSION_RE.test(expectedCrewVersion ?? '')
350
+ || !EXACT_VERSION_RE.test(expectedDshVersion ?? '')) {
351
+ return { ok: false, code: 'SUPERVISOR_TARGET_UNAVAILABLE' };
352
+ }
353
+ return {
354
+ ok: true,
355
+ home,
356
+ root,
357
+ appRoot,
358
+ target: {
359
+ helper_path: assets.helper_path,
360
+ helper_hash: assets.helper_hash,
361
+ control_path: assets.control_path,
362
+ control_hash: assets.control_hash,
363
+ },
364
+ controlScript: assets.control_path,
365
+ controlHash: assets.control_hash,
366
+ expectedCrewVersion,
367
+ expectedDshVersion,
368
+ };
369
+ }
370
+
371
+ export function windowsSupervisorConvergencePending({ home = homedir() } = {}) {
372
+ const appRoot = join(home, '.config', 'dsh-crew');
373
+ return existsSync(windowsSupervisorHandoffJournalPath(appRoot))
374
+ || existsSync(windowsSupervisorHandoffLockPath(appRoot));
375
+ }
376
+
377
+ export function reserveWindowsSupervisorConvergence({
378
+ home = homedir(),
379
+ root,
380
+ platform = process.platform,
381
+ } = {}) {
382
+ const prepared = prepareWindowsSupervisorConvergence({ home, root, platform });
383
+ if (!prepared.ok || prepared.skipped) return prepared;
384
+ const lock = acquireWindowsSupervisorHandoffLock({ appRoot: prepared.appRoot });
385
+ return lock.ok ? { ...prepared, lock } : { ok: false, code: lock.code, error: lock.error ?? null };
386
+ }
387
+
388
+ export function releaseWindowsSupervisorConvergenceReservation(reservation) {
389
+ if (!reservation?.lock) return { ok: false, code: 'SUPERVISOR_RESERVATION_INVALID' };
390
+ return releaseWindowsSupervisorHandoffLock(reservation.lock);
391
+ }
392
+
393
+ export async function convergeWindowsSupervisor({
394
+ home = homedir(),
395
+ root,
396
+ maintenanceClient,
397
+ platform = process.platform,
398
+ runControl,
399
+ fetchRuntime,
400
+ readHeartbeatRecord,
401
+ readAuthoritativeHeartbeat,
402
+ verifyPortFree,
403
+ sleep,
404
+ reservation = null,
405
+ } = {}) {
406
+ const prepared = prepareWindowsSupervisorConvergence({ home, root, platform });
407
+ if (!prepared.ok || prepared.skipped) {
408
+ if (reservation?.lock) releaseWindowsSupervisorHandoffLock(reservation.lock);
409
+ return prepared;
410
+ }
411
+ if (reservation && (!reservation.ok
412
+ || !samePath(reservation.root, prepared.root)
413
+ || !samePath(reservation.target?.helper_path, prepared.target.helper_path)
414
+ || !sameHash(reservation.target?.helper_hash, prepared.target.helper_hash)
415
+ || !samePath(reservation.target?.control_path, prepared.target.control_path)
416
+ || !sameHash(reservation.target?.control_hash, prepared.target.control_hash)
417
+ || reservation.expectedCrewVersion !== prepared.expectedCrewVersion
418
+ || reservation.expectedDshVersion !== prepared.expectedDshVersion)) {
419
+ if (reservation?.lock) releaseWindowsSupervisorHandoffLock(reservation.lock);
420
+ return { ok: false, code: 'SUPERVISOR_RESERVATION_MISMATCH' };
421
+ }
422
+ const hooks = createWindowsSupervisorHandoffHooks({
423
+ appRoot: prepared.appRoot,
424
+ target: prepared.target,
425
+ maintenanceClient,
426
+ expectedCrewVersion: prepared.expectedCrewVersion,
427
+ expectedDshVersion: prepared.expectedDshVersion,
428
+ controlScript: prepared.controlScript,
429
+ runControl,
430
+ fetchRuntime,
431
+ readHeartbeatRecord,
432
+ readAuthoritativeHeartbeat,
433
+ verifyPortFree,
434
+ sleep,
435
+ });
436
+ return runWindowsSupervisorHandoff({
437
+ appRoot: prepared.appRoot,
438
+ target: prepared.target,
439
+ hooks,
440
+ preAcquiredLock: reservation?.lock ?? null,
441
+ forceRestart: existsSync(join(root, PENDING_RUNTIME_ACTIVATION)),
442
+ });
443
+ }