@nowcrew/daemon 0.6.51 → 0.6.52

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.
@@ -0,0 +1,129 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { z } from "zod";
4
+ import { atomicPrivateWrite } from "./atomic-private-write.js";
5
+ import { readStorageMigrationReceipt } from "./storage-migration-controller.js";
6
+ const FingerprintSchema = z.string().regex(/^sha256:[0-9a-f]{64}$/u);
7
+ const IdentitySchema = z.object({
8
+ type: z.literal("daemon:storage-migration-confirmed"),
9
+ migrationId: z.string().uuid(),
10
+ environment: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,31}$/u),
11
+ workspaceId: z.string().uuid(),
12
+ profile: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,47}$/u),
13
+ manifestDigest: z.string().regex(/^[0-9a-f]{64}$/u),
14
+ targetStorageFingerprint: FingerprintSchema,
15
+ }).strict();
16
+ const AcknowledgementSchema = IdentitySchema.omit({ type: true }).extend({
17
+ version: z.literal(1),
18
+ confirmedAt: z.string().datetime({ offset: true }),
19
+ }).strict();
20
+ const delay = (milliseconds) => new Promise((resolvePromise) => {
21
+ setTimeout(resolvePromise, milliseconds);
22
+ });
23
+ export function storageMigrationAcknowledgementPath(backupsRoot, migrationId) {
24
+ if (!isAbsolute(backupsRoot))
25
+ throw new Error("storage migration backups root must be absolute");
26
+ return join(backupsRoot, z.string().uuid().parse(migrationId), "hello-confirmed.json");
27
+ }
28
+ export async function waitForStorageMigrationAcknowledgement(input) {
29
+ const expected = IdentitySchema.omit({ type: true }).parse({
30
+ migrationId: input.migrationId,
31
+ environment: input.environment,
32
+ workspaceId: input.workspaceId,
33
+ profile: input.profile,
34
+ manifestDigest: input.manifestDigest,
35
+ targetStorageFingerprint: input.targetStorageFingerprint,
36
+ });
37
+ const timeoutMs = z.number().int().min(10).max(600_000).parse(input.timeoutMs ?? 120_000);
38
+ const pollIntervalMs = z.number().int().min(1).max(5_000).parse(input.pollIntervalMs ?? 250);
39
+ const path = storageMigrationAcknowledgementPath(input.backupsRoot, expected.migrationId);
40
+ const deadline = Date.now() + timeoutMs;
41
+ while (Date.now() <= deadline) {
42
+ try {
43
+ const acknowledgement = AcknowledgementSchema.parse(JSON.parse(await readFile(path, "utf8")));
44
+ const { version: _version, confirmedAt: _confirmedAt, ...identity } = acknowledgement;
45
+ if (JSON.stringify(identity) !== JSON.stringify(expected)) {
46
+ throw new Error("storage migration acknowledgement identity mismatch");
47
+ }
48
+ return;
49
+ }
50
+ catch (error) {
51
+ if (error.code !== "ENOENT")
52
+ throw error;
53
+ }
54
+ await delay(pollIntervalMs);
55
+ }
56
+ throw new Error("storage migration hello confirmation timeout");
57
+ }
58
+ export function createStorageTargetConfirmationHandler(input) {
59
+ const profile = z.string().regex(/^[a-z0-9][a-z0-9_-]{0,47}$/u).parse(input.profile);
60
+ const completionTimeoutMs = z.number().int().min(10).max(600_000).parse(input.completionTimeoutMs ?? 120_000);
61
+ const pollIntervalMs = z.number().int().min(1).max(5_000).parse(input.pollIntervalMs ?? 250);
62
+ if (input.identity.storageMigrationId === undefined) {
63
+ throw new Error("storage target confirmation requires a migration identity");
64
+ }
65
+ let active = null;
66
+ const handle = async (raw, send) => {
67
+ const rawType = typeof raw === "object" && raw !== null && "type" in raw ? raw.type : undefined;
68
+ if (rawType !== "daemon:storage-migration-confirmed")
69
+ return false;
70
+ const confirmation = IdentitySchema.parse(raw);
71
+ if (confirmation.migrationId !== input.identity.storageMigrationId
72
+ || confirmation.environment !== input.identity.storageEnvironment
73
+ || confirmation.workspaceId !== input.identity.storageWorkspaceId
74
+ || confirmation.profile !== profile
75
+ || confirmation.targetStorageFingerprint !== input.identity.storageIdFingerprint) {
76
+ throw new Error("storage migration confirmation identity mismatch");
77
+ }
78
+ const key = JSON.stringify(confirmation);
79
+ if (active !== null) {
80
+ if (active.key !== key)
81
+ throw new Error("storage migration confirmation changed while processing");
82
+ return active.promise;
83
+ }
84
+ const processConfirmation = async () => {
85
+ const receipt = await readStorageMigrationReceipt(input.backupsRoot, confirmation.migrationId);
86
+ if (receipt === null || receipt.status !== "service_switched"
87
+ || receipt.environment !== confirmation.environment
88
+ || receipt.workspaceId !== confirmation.workspaceId
89
+ || receipt.profile !== confirmation.profile
90
+ || receipt.manifestDigest !== confirmation.manifestDigest) {
91
+ throw new Error("storage migration confirmation receipt identity mismatch");
92
+ }
93
+ const { type: _type, ...confirmationIdentity } = confirmation;
94
+ await atomicPrivateWrite(storageMigrationAcknowledgementPath(input.backupsRoot, confirmation.migrationId), `${JSON.stringify(AcknowledgementSchema.parse({
95
+ version: 1,
96
+ ...confirmationIdentity,
97
+ confirmedAt: new Date().toISOString(),
98
+ }), null, 2)}\n`);
99
+ const deadline = Date.now() + completionTimeoutMs;
100
+ while (Date.now() <= deadline) {
101
+ const current = await readStorageMigrationReceipt(input.backupsRoot, confirmation.migrationId);
102
+ if (current?.status === "completed") {
103
+ send({
104
+ type: "daemon:storage-migration-status",
105
+ migrationId: confirmation.migrationId,
106
+ status: "completed",
107
+ environment: confirmation.environment,
108
+ workspaceId: confirmation.workspaceId,
109
+ profile: confirmation.profile,
110
+ });
111
+ return true;
112
+ }
113
+ if (current !== null && ["failed", "rolled_back", "rollback_failed"].includes(current.status)) {
114
+ throw new Error(`storage migration ended before completion: ${current.status}`);
115
+ }
116
+ await delay(pollIntervalMs);
117
+ }
118
+ throw new Error("storage migration worker completion timeout");
119
+ };
120
+ const promise = processConfirmation();
121
+ active = { key, promise };
122
+ void promise.catch(() => {
123
+ if (active?.key === key)
124
+ active = null;
125
+ });
126
+ return promise;
127
+ };
128
+ return Object.freeze({ handle });
129
+ }
@@ -0,0 +1,27 @@
1
+ import { posix, win32 } from "node:path";
2
+ import { executeStorageMigrationWorker, recoverStorageMigrationWorker, } from "./storage-worker-executor.js";
3
+ import { completeStorageMigrationWorkerServiceForHandoff } from "./storage-worker-handoff.js";
4
+ import { startStorageWorkerHeartbeat, writeStorageWorkerFailureStatus, } from "./storage-worker-status.js";
5
+ export async function runStorageWorkerCommand(args, execute = executeStorageMigrationWorker, writeFailure = writeStorageWorkerFailureStatus, startHeartbeat = startStorageWorkerHeartbeat, completeService = completeStorageMigrationWorkerServiceForHandoff, recover = recoverStorageMigrationWorker) {
6
+ const command = args[0];
7
+ if (command !== "storage-migration-worker" && command !== "storage-migration-recover")
8
+ return null;
9
+ const path = args[1] === "--job" ? args[2] : undefined;
10
+ if (args.length !== 3 || path === undefined || path.length === 0
11
+ || /[\0\r\n]/u.test(path) || (!posix.isAbsolute(path) && !win32.isAbsolute(path))) {
12
+ throw new Error("Invalid storage migration worker command");
13
+ }
14
+ const stopHeartbeat = await startHeartbeat(path);
15
+ try {
16
+ await (command === "storage-migration-recover" ? recover(path) : execute(path));
17
+ }
18
+ catch (error) {
19
+ await writeFailure(path, error).catch(() => undefined);
20
+ throw error;
21
+ }
22
+ finally {
23
+ await stopHeartbeat().catch(() => undefined);
24
+ await completeService(path);
25
+ }
26
+ return 0;
27
+ }
@@ -0,0 +1,380 @@
1
+ import { createHash } from "node:crypto";
2
+ import { realpathSync } from "node:fs";
3
+ import { buildServiceSpec, captureExactService, serviceAction, systemCommandRunner, } from "./computer-service.js";
4
+ import { listProfiles, loadProfile, removeProfile, saveProfile, } from "./computer-profile.js";
5
+ import { assertManagedServiceIdentity, installManagedService, uninstallManagedService, uninstallUnregisteredManagedService, } from "./managed-service-lifecycle.js";
6
+ import { readManagedServiceRegistry, normalizeManagedServiceRecord, serviceDescriptorSha256, } from "./managed-service-registry.js";
7
+ import { readInstallations, writeInstallations, } from "./storage-config.js";
8
+ import { runStorageDoctor } from "./storage-doctor.js";
9
+ import { readStorageMigrationReceipt, recoverStorageMigration, runStorageMigration, StorageMigrationFailure, } from "./storage-migration-controller.js";
10
+ import { readStorageWorkerHandoff } from "./storage-worker-handoff.js";
11
+ import { readStorageWorkerOperation } from "./storage-worker-operation.js";
12
+ import { storageIdFingerprint } from "./storage-identity.js";
13
+ import { waitForStorageMigrationAcknowledgement } from "./storage-target-confirmation.js";
14
+ const defaultServiceDependencies = () => ({
15
+ assertManagedServiceIdentity,
16
+ serviceAction,
17
+ uninstallManagedService,
18
+ uninstallUnregisteredManagedService,
19
+ installManagedService,
20
+ captureExactService,
21
+ readManagedServices: readManagedServiceRegistry,
22
+ listProfiles,
23
+ loadProfile,
24
+ saveProfile,
25
+ removeProfile,
26
+ readInstallations,
27
+ writeInstallations,
28
+ });
29
+ function serviceSpec(operation, record, profileHome) {
30
+ return buildServiceSpec({
31
+ platform: operation.service.platform,
32
+ profile: operation.profile,
33
+ userHome: realpathSync.native(operation.service.userHome),
34
+ uid: operation.service.uid,
35
+ nodePath: record.nodePath,
36
+ entryPath: record.entryPath,
37
+ profileHome,
38
+ });
39
+ }
40
+ function assertRecordMatchesSpec(record, spec) {
41
+ const normalizedDescriptorPath = spec.descriptorPath === null
42
+ ? null
43
+ : normalizeManagedServiceRecord({ ...record, descriptorPath: spec.descriptorPath }).descriptorPath;
44
+ const mismatches = [
45
+ spec.descriptor === null ? "descriptor" : null,
46
+ spec.descriptorPath === null ? "descriptorPath" : null,
47
+ record.platform !== spec.platform ? "platform" : null,
48
+ record.serviceId !== spec.id ? "serviceId" : null,
49
+ record.profile !== spec.profile ? "profile" : null,
50
+ record.descriptorPath !== normalizedDescriptorPath ? "descriptorPath" : null,
51
+ spec.descriptor !== null && record.descriptorSha256 !== serviceDescriptorSha256(spec.descriptor)
52
+ ? "descriptorSha256"
53
+ : null,
54
+ ].filter((value) => value !== null);
55
+ if (mismatches.length > 0) {
56
+ throw new Error(`Managed service record does not match operation service '${record.serviceId}': ${mismatches.join(", ")}`);
57
+ }
58
+ }
59
+ function sameRecord(left, right) {
60
+ return JSON.stringify(left) === JSON.stringify(right);
61
+ }
62
+ function sameInstallation(left, right) {
63
+ return JSON.stringify(left) === JSON.stringify(right);
64
+ }
65
+ function sameProfile(left, right) {
66
+ return JSON.stringify(left) === JSON.stringify(right);
67
+ }
68
+ function canonicalServerUrl(value) {
69
+ return value.replace(/\/+$/u, "");
70
+ }
71
+ export function createStorageWorkerServiceLifecycle(operation, injected = {}) {
72
+ const dependencies = { ...defaultServiceDependencies(), ...injected };
73
+ const registry = { userHome: operation.service.userHome };
74
+ const sourceRecord = operation.service.sourceRecord;
75
+ const targetRecord = operation.service.targetRecord;
76
+ const sourceSpec = serviceSpec(operation, sourceRecord, operation.migration.sourceRoots["daemon-home"]);
77
+ const targetSpec = serviceSpec(operation, targetRecord, operation.installation.configRoot);
78
+ assertRecordMatchesSpec(sourceRecord, sourceSpec);
79
+ assertRecordMatchesSpec(targetRecord, targetSpec);
80
+ let sourceProfile = null;
81
+ let savedTargetProfile = null;
82
+ let baselineInstallations = null;
83
+ let targetProfileCreated = false;
84
+ let targetInstallationWritten = false;
85
+ const assertSourceIdentity = () => dependencies.assertManagedServiceIdentity({
86
+ spec: sourceSpec,
87
+ record: sourceRecord,
88
+ registry,
89
+ });
90
+ const readTargetInstallations = () => dependencies.readInstallations({
91
+ configRoot: operation.installation.configRoot,
92
+ });
93
+ const assertTargetMetadataUnchanged = async () => {
94
+ const profiles = await dependencies.listProfiles(operation.installation.configRoot);
95
+ if (profiles.includes(operation.profile))
96
+ throw new Error(`Target profile '${operation.profile}' already exists`);
97
+ const current = await readTargetInstallations();
98
+ if (baselineInstallations !== null && JSON.stringify(current) !== JSON.stringify(baselineInstallations)) {
99
+ throw new Error("Target installation registry changed after worker preflight");
100
+ }
101
+ if (current.some((record) => record.profile === operation.profile
102
+ || record.installationId === operation.installation.target.installationId)) {
103
+ throw new Error("Target installation identity already exists");
104
+ }
105
+ return current;
106
+ };
107
+ const preflight = async () => {
108
+ await assertSourceIdentity();
109
+ const source = await dependencies.captureExactService(sourceSpec, systemCommandRunner);
110
+ if (!source.installed || !source.exact || source.running !== operation.service.sourceWasRunning) {
111
+ throw new Error("Source service state does not match worker operation");
112
+ }
113
+ const target = await dependencies.captureExactService(targetSpec, systemCommandRunner);
114
+ if (target.installed)
115
+ throw new Error(`Target service '${targetSpec.id}' already exists`);
116
+ sourceProfile = await dependencies.loadProfile(operation.profile, sourceRecord.daemonHome);
117
+ if (sourceProfile.name !== operation.profile
118
+ || canonicalServerUrl(sourceProfile.serverUrl) !== canonicalServerUrl(operation.installation.target.serverUrl)) {
119
+ throw new Error("Source profile does not match target installation identity");
120
+ }
121
+ baselineInstallations = await assertTargetMetadataUnchanged();
122
+ };
123
+ const stopSourceService = async () => {
124
+ await dependencies.serviceAction(sourceSpec, "stop", systemCommandRunner);
125
+ const stopped = await dependencies.captureExactService(sourceSpec, systemCommandRunner);
126
+ if (!stopped.installed || !stopped.exact || stopped.running) {
127
+ throw new Error(`Source service '${sourceSpec.id}' did not stop exactly`);
128
+ }
129
+ };
130
+ const installTargetService = async () => {
131
+ if (sourceProfile === null || baselineInstallations === null)
132
+ throw new Error("Worker service preflight is required");
133
+ const installations = await assertTargetMetadataUnchanged();
134
+ await assertSourceIdentity();
135
+ await dependencies.uninstallManagedService({
136
+ spec: sourceSpec,
137
+ record: sourceRecord,
138
+ runner: systemCommandRunner,
139
+ registry,
140
+ });
141
+ const { version: _version, ...profile } = sourceProfile;
142
+ savedTargetProfile = await dependencies.saveProfile({
143
+ ...profile,
144
+ agentsRoot: targetRecord.agentsRoot,
145
+ }, operation.installation.configRoot);
146
+ targetProfileCreated = true;
147
+ await dependencies.writeInstallations([...installations, operation.installation.target].sort((left, right) => left.profile.localeCompare(right.profile)), { configRoot: operation.installation.configRoot });
148
+ targetInstallationWritten = true;
149
+ await dependencies.installManagedService({
150
+ spec: targetSpec,
151
+ record: targetRecord,
152
+ runner: systemCommandRunner,
153
+ registry,
154
+ });
155
+ const target = await dependencies.captureExactService(targetSpec, systemCommandRunner);
156
+ if (!target.installed || !target.exact || target.running) {
157
+ throw new Error(`Target service '${targetSpec.id}' was not installed exactly in stopped state`);
158
+ }
159
+ };
160
+ const startTargetService = async () => {
161
+ await dependencies.serviceAction(targetSpec, "start", systemCommandRunner);
162
+ const target = await dependencies.captureExactService(targetSpec, systemCommandRunner);
163
+ if (!target.installed || !target.exact || !target.running) {
164
+ throw new Error(`Target service '${targetSpec.id}' did not start exactly`);
165
+ }
166
+ };
167
+ const removeTargetService = async () => {
168
+ const records = await dependencies.readManagedServices(registry);
169
+ const registered = records.find((record) => record.serviceId === targetRecord.serviceId
170
+ || (record.profile === targetRecord.profile && record.daemonHome === targetRecord.daemonHome));
171
+ if (registered !== undefined && !sameRecord(registered, targetRecord)) {
172
+ throw new Error(`Target service '${targetSpec.id}' identity changed before rollback`);
173
+ }
174
+ if (registered !== undefined) {
175
+ await dependencies.uninstallManagedService({
176
+ spec: targetSpec,
177
+ record: targetRecord,
178
+ runner: systemCommandRunner,
179
+ registry,
180
+ });
181
+ }
182
+ else {
183
+ const target = await dependencies.captureExactService(targetSpec, systemCommandRunner);
184
+ if (target.installed && !target.exact)
185
+ throw new Error(`Target service '${targetSpec.id}' changed before rollback`);
186
+ if (target.installed) {
187
+ await dependencies.uninstallUnregisteredManagedService({
188
+ spec: targetSpec,
189
+ daemonHome: targetRecord.daemonHome,
190
+ npmPrefix: targetRecord.npmPrefix,
191
+ runner: systemCommandRunner,
192
+ registry,
193
+ });
194
+ }
195
+ }
196
+ const installations = await readTargetInstallations();
197
+ const targetInstallation = installations.find((record) => record.profile === operation.profile
198
+ || record.installationId === operation.installation.target.installationId);
199
+ if (targetInstallation !== undefined) {
200
+ if (!sameInstallation(targetInstallation, operation.installation.target)) {
201
+ throw new Error("Target installation identity changed before rollback");
202
+ }
203
+ await dependencies.writeInstallations(installations.filter((record) => !sameInstallation(record, operation.installation.target)), { configRoot: operation.installation.configRoot });
204
+ targetInstallationWritten = false;
205
+ }
206
+ const profiles = await dependencies.listProfiles(operation.installation.configRoot);
207
+ if (profiles.includes(operation.profile)) {
208
+ const current = await dependencies.loadProfile(operation.profile, operation.installation.configRoot);
209
+ const original = sourceProfile
210
+ ?? await dependencies.loadProfile(operation.profile, sourceRecord.daemonHome);
211
+ const { version: _version, ...profile } = original;
212
+ const expected = savedTargetProfile ?? { version: 1, ...profile, agentsRoot: targetRecord.agentsRoot };
213
+ if (!sameProfile(current, expected)) {
214
+ throw new Error("Target profile identity changed before rollback");
215
+ }
216
+ await dependencies.removeProfile(operation.profile, operation.installation.configRoot);
217
+ targetProfileCreated = false;
218
+ }
219
+ };
220
+ const restoreSourceService = async () => {
221
+ const current = await dependencies.captureExactService(sourceSpec, systemCommandRunner);
222
+ if (current.installed && !current.exact) {
223
+ throw new Error(`Source service '${sourceSpec.id}' changed before rollback`);
224
+ }
225
+ if (!current.installed) {
226
+ await dependencies.installManagedService({
227
+ spec: sourceSpec,
228
+ record: sourceRecord,
229
+ runner: systemCommandRunner,
230
+ registry,
231
+ });
232
+ }
233
+ const afterInstall = current.installed
234
+ ? current
235
+ : await dependencies.captureExactService(sourceSpec, systemCommandRunner);
236
+ if (operation.service.sourceWasRunning && !afterInstall.running) {
237
+ await dependencies.serviceAction(sourceSpec, "start", systemCommandRunner);
238
+ }
239
+ else if (!operation.service.sourceWasRunning && afterInstall.running) {
240
+ await dependencies.serviceAction(sourceSpec, "stop", systemCommandRunner);
241
+ }
242
+ const restored = await dependencies.captureExactService(sourceSpec, systemCommandRunner);
243
+ if (!restored.installed || !restored.exact || restored.running !== operation.service.sourceWasRunning) {
244
+ throw new Error(`Source service '${sourceSpec.id}' was not restored exactly`);
245
+ }
246
+ };
247
+ return Object.freeze({
248
+ preflight,
249
+ assertServiceIdentity: assertSourceIdentity,
250
+ isBusy: () => false,
251
+ quiesceExecutions: async () => undefined,
252
+ waitForIdle: async () => undefined,
253
+ flushLocalState: async () => undefined,
254
+ stopSourceService,
255
+ installTargetService,
256
+ startTargetService,
257
+ removeTargetService,
258
+ restoreSourceService,
259
+ confirmHello: (receipt) => waitForStorageMigrationAcknowledgement({
260
+ backupsRoot: operation.migration.backupsRoot,
261
+ migrationId: operation.migrationId,
262
+ environment: operation.environment,
263
+ workspaceId: operation.workspaceId,
264
+ profile: operation.profile,
265
+ manifestDigest: receipt.manifestDigest,
266
+ targetStorageFingerprint: storageIdFingerprint(operation.installation.target.storageId),
267
+ }),
268
+ });
269
+ }
270
+ function validateFreshDoctor(operation, doctor) {
271
+ if (!doctor.applyAllowed
272
+ || doctor.manifestDigest !== operation.expectedManifestDigest
273
+ || doctor.manifest.migrationId !== operation.migrationId
274
+ || doctor.environment !== operation.environment
275
+ || doctor.workspaceId !== operation.workspaceId
276
+ || doctor.profile !== operation.profile
277
+ || doctor.manifest.targetWorkspaceRoot !== operation.migration.targetWorkspaceRoot) {
278
+ throw new StorageMigrationFailure("worker_doctor_mismatch", "fresh worker doctor digest or identity does not match the approved operation");
279
+ }
280
+ }
281
+ function workerDoctorInput(operation, generatedAt = operation.doctorInput.generatedAt) {
282
+ const { freeSpaceMultiplier, ...input } = operation.doctorInput;
283
+ return {
284
+ ...input,
285
+ generatedAt,
286
+ ...(freeSpaceMultiplier === undefined ? {} : { freeSpaceMultiplier }),
287
+ };
288
+ }
289
+ function workerSourceRoots(operation) {
290
+ return Object.fromEntries(Object.entries(operation.migration.sourceRoots)
291
+ .filter((entry) => entry[1] !== undefined));
292
+ }
293
+ export async function executeStorageMigrationWorker(handoffPath, injected = {}) {
294
+ const dependencies = {
295
+ runDoctor: (input) => runStorageDoctor(input),
296
+ runMigration: runStorageMigration,
297
+ recoverMigration: recoverStorageMigration,
298
+ readReceipt: readStorageMigrationReceipt,
299
+ createServiceLifecycle: (operation) => createStorageWorkerServiceLifecycle(operation),
300
+ now: () => new Date(),
301
+ ...injected,
302
+ };
303
+ const handoff = await readStorageWorkerHandoff(handoffPath);
304
+ const operation = await readStorageWorkerOperation(handoff.operationPath, handoff.operationSha256);
305
+ if (handoff.migrationId !== operation.migrationId || handoff.profile !== operation.profile) {
306
+ throw new StorageMigrationFailure("worker_handoff_mismatch", "worker handoff does not match operation identity");
307
+ }
308
+ const lifecycle = dependencies.createServiceLifecycle(operation);
309
+ const existing = await dependencies.readReceipt(operation.migration.backupsRoot, operation.migrationId);
310
+ if (existing !== null) {
311
+ if (existing.environment !== operation.environment || existing.workspaceId !== operation.workspaceId
312
+ || existing.profile !== operation.profile) {
313
+ throw new StorageMigrationFailure("worker_receipt_mismatch", "worker receipt does not match operation identity");
314
+ }
315
+ if (existing.status === "completed" || existing.status === "rolled_back")
316
+ return existing;
317
+ return dependencies.recoverMigration({
318
+ backupsRoot: operation.migration.backupsRoot,
319
+ migrationId: operation.migrationId,
320
+ }, { ...lifecycle, now: dependencies.now });
321
+ }
322
+ await lifecycle.preflight();
323
+ const doctor = await dependencies.runDoctor(workerDoctorInput(operation));
324
+ validateFreshDoctor(operation, doctor);
325
+ return dependencies.runMigration({
326
+ doctor,
327
+ sourceRoots: workerSourceRoots(operation),
328
+ stagingWorkspaceRoot: operation.migration.stagingWorkspaceRoot,
329
+ targetWorkspaceRoot: operation.migration.targetWorkspaceRoot,
330
+ backupsRoot: operation.migration.backupsRoot,
331
+ backupArtifacts: operation.migration.backupArtifacts,
332
+ acceptedWarnings: operation.migration.acceptedWarnings,
333
+ }, {
334
+ ...lifecycle,
335
+ now: dependencies.now,
336
+ refreshDoctor: async () => {
337
+ const refreshed = await dependencies.runDoctor(workerDoctorInput(operation, dependencies.now().toISOString()));
338
+ if (refreshed.manifest.migrationId !== operation.migrationId
339
+ || refreshed.environment !== operation.environment
340
+ || refreshed.workspaceId !== operation.workspaceId
341
+ || refreshed.profile !== operation.profile) {
342
+ throw new StorageMigrationFailure("final_doctor_failed", "final worker doctor identity changed");
343
+ }
344
+ return refreshed;
345
+ },
346
+ });
347
+ }
348
+ export async function recoverStorageMigrationWorker(handoffPath, injected = {}) {
349
+ const dependencies = {
350
+ runDoctor: (input) => runStorageDoctor(input),
351
+ runMigration: runStorageMigration,
352
+ recoverMigration: recoverStorageMigration,
353
+ readReceipt: readStorageMigrationReceipt,
354
+ createServiceLifecycle: (operation) => createStorageWorkerServiceLifecycle(operation),
355
+ now: () => new Date(),
356
+ ...injected,
357
+ };
358
+ const handoff = await readStorageWorkerHandoff(handoffPath);
359
+ const operation = await readStorageWorkerOperation(handoff.operationPath, handoff.operationSha256);
360
+ if (handoff.migrationId !== operation.migrationId || handoff.profile !== operation.profile) {
361
+ throw new StorageMigrationFailure("worker_handoff_mismatch", "worker handoff does not match operation identity");
362
+ }
363
+ const receipt = await dependencies.readReceipt(operation.migration.backupsRoot, operation.migrationId);
364
+ if (receipt === null) {
365
+ throw new StorageMigrationFailure("migration_receipt_missing", "explicit rollback requires an existing migration receipt");
366
+ }
367
+ if (receipt.environment !== operation.environment || receipt.workspaceId !== operation.workspaceId
368
+ || receipt.profile !== operation.profile) {
369
+ throw new StorageMigrationFailure("worker_receipt_mismatch", "worker receipt does not match operation identity");
370
+ }
371
+ if (receipt.status === "completed" || receipt.status === "rolled_back")
372
+ return receipt;
373
+ return dependencies.recoverMigration({
374
+ backupsRoot: operation.migration.backupsRoot,
375
+ migrationId: operation.migrationId,
376
+ }, { ...dependencies.createServiceLifecycle(operation), now: dependencies.now });
377
+ }
378
+ export function storageWorkerOperationDigest(operation) {
379
+ return createHash("sha256").update(`${JSON.stringify(operation, null, 2)}\n`).digest("hex");
380
+ }
@@ -0,0 +1,116 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readFile, rm } from "node:fs/promises";
3
+ import { join, posix, resolve, win32 } from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { z } from "zod";
6
+ import { atomicPrivateWrite } from "./atomic-private-write.js";
7
+ import { readStorageWorkerOperation } from "./storage-worker-operation.js";
8
+ const AbsolutePathSchema = z.string().min(1).max(32768)
9
+ .refine((value) => !/[\0\r\n]/u.test(value), "path must be a single line")
10
+ .refine((value) => posix.isAbsolute(value) || win32.isAbsolute(value), "path must be absolute");
11
+ const HandoffSchema = z.object({
12
+ version: z.literal(1),
13
+ migrationId: z.string().uuid(),
14
+ profile: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,47}$/u),
15
+ operationPath: AbsolutePathSchema,
16
+ operationSha256: z.string().regex(/^[0-9a-f]{64}$/u),
17
+ }).strict();
18
+ export async function writeStorageWorkerHandoff(raw, input) {
19
+ let handoff;
20
+ try {
21
+ handoff = HandoffSchema.parse(raw);
22
+ AbsolutePathSchema.parse(input.stateRoot);
23
+ }
24
+ catch (error) {
25
+ throw new Error("Invalid storage worker handoff", { cause: error });
26
+ }
27
+ const path = join(input.stateRoot, "migrations", handoff.migrationId, "handoff.json");
28
+ await atomicPrivateWrite(path, `${JSON.stringify(handoff, null, 2)}\n`);
29
+ return path;
30
+ }
31
+ export async function readStorageWorkerHandoff(path) {
32
+ try {
33
+ AbsolutePathSchema.parse(path);
34
+ return HandoffSchema.parse(JSON.parse(await readFile(path, "utf8")));
35
+ }
36
+ catch (error) {
37
+ throw new Error("Invalid storage worker handoff", { cause: error });
38
+ }
39
+ }
40
+ const execFileAsync = promisify(execFile);
41
+ const systemSupervisorRun = async (command, args) => {
42
+ try {
43
+ const result = await execFileAsync(command, [...args], {
44
+ encoding: "utf8",
45
+ timeout: 15_000,
46
+ maxBuffer: 64 * 1024,
47
+ });
48
+ return { exitCode: 0, stdout: result.stdout, stderr: result.stderr };
49
+ }
50
+ catch (error) {
51
+ const failure = error;
52
+ return {
53
+ exitCode: typeof failure.code === "number" ? failure.code : 127,
54
+ stdout: failure.stdout ?? "",
55
+ stderr: failure.stderr ?? failure.message,
56
+ };
57
+ }
58
+ };
59
+ function workerUnitName(migrationId) {
60
+ return `nowwork-storage-migration-${migrationId}.service`;
61
+ }
62
+ function workerUnitPath(userHome, migrationId) {
63
+ return resolve(userHome, ".config", "systemd", "user", workerUnitName(migrationId));
64
+ }
65
+ function systemdArg(value) {
66
+ if (/[\0\r\n]/u.test(value))
67
+ throw new Error("storage worker service argument must be a single line");
68
+ return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("%", "%%")}"`;
69
+ }
70
+ async function checkedSupervisor(run, command, args) {
71
+ const result = await run(command, args);
72
+ if (result.exitCode !== 0)
73
+ throw new Error(result.stderr.trim() || result.stdout.trim() || `exit ${result.exitCode}`);
74
+ }
75
+ export async function launchStorageMigrationWorker(input, runSupervisor = systemSupervisorRun) {
76
+ AbsolutePathSchema.parse(input.entryPath);
77
+ AbsolutePathSchema.parse(input.handoffPath);
78
+ AbsolutePathSchema.parse(input.userHome);
79
+ const migrationId = z.string().uuid().parse(input.migrationId).toLowerCase();
80
+ if (input.platform !== "linux")
81
+ throw new Error("Persistent storage migration workers require Linux systemd");
82
+ const worker = [process.execPath, input.entryPath, "storage-migration-worker", "--job", input.handoffPath];
83
+ const unit = workerUnitName(migrationId);
84
+ const path = workerUnitPath(input.userHome, migrationId);
85
+ const descriptor = `[Unit]\nDescription=NowWork storage migration ${migrationId}\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=exec\nExecStart=${worker.map(systemdArg).join(" ")}\nRestart=on-abnormal\nRestartSec=5\n\n[Install]\nWantedBy=default.target\n`;
86
+ await atomicPrivateWrite(path, descriptor);
87
+ try {
88
+ await checkedSupervisor(runSupervisor, "systemctl", ["--user", "daemon-reload"]);
89
+ await checkedSupervisor(runSupervisor, "systemctl", ["--user", "enable", "--now", unit]);
90
+ }
91
+ catch (error) {
92
+ await runSupervisor("systemctl", ["--user", "disable", "--now", unit]).catch(() => undefined);
93
+ await rm(path, { force: true });
94
+ await runSupervisor("systemctl", ["--user", "daemon-reload"]).catch(() => undefined);
95
+ throw new Error("Storage migration persistent service launch failed", { cause: error });
96
+ }
97
+ }
98
+ export async function completeStorageMigrationWorkerService(input, runSupervisor = systemSupervisorRun) {
99
+ const migrationId = z.string().uuid().parse(input.migrationId).toLowerCase();
100
+ if (input.platform !== "linux")
101
+ return;
102
+ AbsolutePathSchema.parse(input.userHome);
103
+ const unit = workerUnitName(migrationId);
104
+ await checkedSupervisor(runSupervisor, "systemctl", ["--user", "disable", unit]);
105
+ await rm(workerUnitPath(input.userHome, migrationId), { force: true });
106
+ await checkedSupervisor(runSupervisor, "systemctl", ["--user", "daemon-reload"]);
107
+ }
108
+ export async function completeStorageMigrationWorkerServiceForHandoff(path) {
109
+ const handoff = await readStorageWorkerHandoff(path);
110
+ const operation = await readStorageWorkerOperation(handoff.operationPath, handoff.operationSha256);
111
+ await completeStorageMigrationWorkerService({
112
+ migrationId: operation.migrationId,
113
+ platform: operation.service.platform,
114
+ userHome: operation.service.userHome,
115
+ });
116
+ }