@narumitw/pi-sync 0.63.1 → 0.65.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.
- package/CHANGELOG.md +21 -0
- package/README.md +86 -10
- package/dist/chunks/{chunk-CKUGCBHP.ts → chunk-AYGMIMCV.ts} +2 -2
- package/dist/chunks/chunk-AYGMIMCV.ts.map +7 -0
- package/dist/chunks/{chunk-27F5W7DX.ts → chunk-DAZZ5BEJ.ts} +3 -1
- package/dist/chunks/chunk-DAZZ5BEJ.ts.map +7 -0
- package/dist/chunks/{chunk-VQ47JBLF.ts → chunk-FI2F5JBS.ts} +2 -2
- package/dist/chunks/{chunk-V76KCWHO.ts → chunk-IOM6E5FW.ts} +4 -4
- package/dist/chunks/{chunk-B5F3JLD3.ts → chunk-JQ5BAWW2.ts} +482 -78
- package/dist/chunks/chunk-JQ5BAWW2.ts.map +7 -0
- package/dist/chunks/{chunk-LBNC5AOM.ts → chunk-OBVJTKVY.ts} +12 -12
- package/dist/chunks/{chunk-EXDWEFIJ.ts → chunk-OWEOZZZE.ts} +6 -6
- package/dist/chunks/{chunk-SXCH4Q5O.ts → chunk-SZJOUVCL.ts} +3 -3
- package/dist/chunks/{chunk-HSCAFOT5.ts → chunk-TZMVSTAM.ts} +5 -5
- package/dist/chunks/{chunk-POWOMJ7S.ts → chunk-WJQ4TGN5.ts} +58 -31
- package/dist/chunks/chunk-WJQ4TGN5.ts.map +7 -0
- package/dist/chunks/{chunk-HLCML3OW.ts → chunk-XUZV4OGI.ts} +5 -3
- package/dist/chunks/chunk-XUZV4OGI.ts.map +7 -0
- package/dist/chunks/{command-handler-GMRRFWOL.ts → command-handler-YZ4DXQ7N.ts} +81 -30
- package/dist/chunks/command-handler-YZ4DXQ7N.ts.map +7 -0
- package/dist/chunks/{conflict-review-JWEA7DPQ.ts → conflict-review-J7L7S4AR.ts} +2 -2
- package/dist/chunks/{file-selection-KID23GAD.ts → file-selection-DDQN4LVD.ts} +9 -9
- package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts → manager-result-dispatcher-XB75YLEG.ts} +5 -5
- package/dist/chunks/{manager-ui-T5J5WG7T.ts → manager-ui-RGA26Z6G.ts} +103 -83
- package/dist/chunks/manager-ui-RGA26Z6G.ts.map +7 -0
- package/dist/chunks/{merge-review-OQDXNTJU.ts → merge-review-AAC674C6.ts} +3 -2
- package/dist/chunks/ownership-recovery-UDDHSDSZ.ts +59 -0
- package/dist/chunks/ownership-recovery-UDDHSDSZ.ts.map +7 -0
- package/dist/chunks/{remote-selection-ui-GPITNEBF.ts → remote-selection-ui-WVMET5RI.ts} +4 -4
- package/dist/chunks/{setup-switch-L54X5U5I.ts → setup-switch-644T6KHG.ts} +4 -4
- package/dist/chunks/{setup-wizard-LL6YMGUR.ts → setup-wizard-YP2KF2WQ.ts} +9 -9
- package/dist/chunks/{sync-inspection-SRU6HGGK.ts → sync-inspection-NBBTSMKR.ts} +5 -5
- package/dist/chunks/{sync-operations-UGSCONZ7.ts → sync-operations-AIEM2KL2.ts} +2 -2
- package/dist/daemon/dist/cli.js +2 -0
- package/dist/daemon/dist/client-transport.js +66 -0
- package/dist/daemon/dist/client.js +222 -354
- package/dist/daemon/dist/consent.js +33 -11
- package/dist/daemon/dist/daemon-debug.js +33 -0
- package/dist/daemon/dist/daemon-recovery.js +158 -0
- package/dist/daemon/dist/daemon-startup.js +257 -0
- package/dist/daemon/dist/engine/backends/git/git-backend.js +49 -13
- package/dist/daemon/dist/engine/backends/git/git-runner.js +6 -1
- package/dist/daemon/dist/engine/backends/git/git-storage.js +5 -9
- package/dist/daemon/dist/engine/backends/publication-encoding.js +19 -0
- package/dist/daemon/dist/engine/backends/s3/s3-backend.js +30 -21
- package/dist/daemon/dist/engine/backends/sync-backend.js +16 -0
- package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +34 -32
- package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +10 -0
- package/dist/daemon/dist/engine/debug-log.js +134 -0
- package/dist/daemon/dist/engine/paths.js +7 -1
- package/dist/daemon/dist/engine/settings/config-file.js +62 -17
- package/dist/daemon/dist/engine/settings/config.js +49 -14
- package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +30 -8
- package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +3 -1
- package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +32 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +34 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +50 -7
- package/dist/daemon/dist/engine/snapshot/snapshot.js +64 -25
- package/dist/daemon/dist/engine/state/lock.js +157 -17
- package/dist/daemon/dist/engine/sync/continuous-sync.js +35 -11
- package/dist/daemon/dist/engine/sync/directional-action.js +124 -0
- package/dist/daemon/dist/engine/sync/initialization.js +2 -2
- package/dist/daemon/dist/engine/sync/local-fields.js +42 -19
- package/dist/daemon/dist/engine/sync/merged-sync.js +13 -10
- package/dist/daemon/dist/engine/sync/remote-snapshot.js +21 -4
- package/dist/daemon/dist/engine/sync/session-push.js +13 -4
- package/dist/daemon/dist/engine/sync/startup-bootstrap.js +105 -0
- package/dist/daemon/dist/engine/sync/startup-recovery-evidence.js +37 -0
- package/dist/daemon/dist/engine/sync/startup-timings.js +80 -8
- package/dist/daemon/dist/engine/sync/sync-error-guidance.js +6 -1
- package/dist/daemon/dist/engine/sync/sync-errors.js +20 -0
- package/dist/daemon/dist/engine/sync/sync-inspection.js +4 -7
- package/dist/daemon/dist/engine/sync/sync-local.js +59 -4
- package/dist/daemon/dist/engine/sync/sync-mutations.js +309 -337
- package/dist/daemon/dist/engine/sync/sync-policy.js +9 -1
- package/dist/daemon/dist/engine/sync/sync-queries.js +2 -1
- package/dist/daemon/dist/engine/sync/sync-rollback.js +198 -0
- package/dist/daemon/dist/engine/sync/sync-state.js +12 -4
- package/dist/daemon/dist/engine/sync/transfer-freshness.js +11 -5
- package/dist/daemon/dist/engine-service.js +122 -10
- package/dist/daemon/dist/foreground-queue-outcome.js +9 -0
- package/dist/daemon/dist/identity.js +36 -6
- package/dist/daemon/dist/index.js +2 -1
- package/dist/daemon/dist/monitor.js +21 -1
- package/dist/daemon/dist/paged-review.js +177 -0
- package/dist/daemon/dist/participant-ledger.js +149 -0
- package/dist/daemon/dist/protocol.js +4 -0
- package/dist/daemon/dist/server.js +340 -127
- package/dist/daemon/dist/service-host.js +83 -15
- package/dist/daemon/dist/state-wait-jobs.js +23 -0
- package/dist/daemon/dist/state-wait.js +34 -0
- package/dist/daemon/package.json +1 -1
- package/dist/index.ts +128 -48
- package/dist/index.ts.map +2 -2
- package/docs/continuous-sync-verification.md +2 -0
- package/docs/daemon-migration.md +31 -6
- package/docs/tui-contract.md +7 -1
- package/package.json +2 -2
- package/skills/configure-pi-sync/references/configuration.md +23 -13
- package/src/commands/command-execution.ts +67 -5
- package/src/commands/command-handler.ts +12 -3
- package/src/commands/command.ts +4 -2
- package/src/daemon/client-debug.ts +45 -0
- package/src/daemon/directional-recovery.ts +103 -0
- package/src/daemon/ownership-recovery.ts +50 -0
- package/src/daemon/pi-client.ts +399 -71
- package/src/daemon/startup-bootstrap-client.ts +26 -0
- package/src/settings/config.ts +1 -0
- package/src/sync/automatic-sync.ts +61 -18
- package/src/sync/startup-check.ts +13 -5
- package/src/sync-extension.ts +46 -8
- package/src/ui/cancellable-operation.ts +5 -2
- package/src/ui/manager-state.ts +31 -23
- package/src/ui/manager-ui.ts +45 -25
- package/src/ui/merge-review.ts +53 -18
- package/src/ui/settings-ui.ts +2 -2
- package/src/ui/sync-confirmation.ts +14 -17
- package/src/ui/sync-setups-ui.ts +15 -12
- package/dist/chunks/chunk-27F5W7DX.ts.map +0 -7
- package/dist/chunks/chunk-B5F3JLD3.ts.map +0 -7
- package/dist/chunks/chunk-CKUGCBHP.ts.map +0 -7
- package/dist/chunks/chunk-HLCML3OW.ts.map +0 -7
- package/dist/chunks/chunk-POWOMJ7S.ts.map +0 -7
- package/dist/chunks/command-handler-GMRRFWOL.ts.map +0 -7
- package/dist/chunks/manager-ui-T5J5WG7T.ts.map +0 -7
- /package/dist/chunks/{chunk-VQ47JBLF.ts.map → chunk-FI2F5JBS.ts.map} +0 -0
- /package/dist/chunks/{chunk-V76KCWHO.ts.map → chunk-IOM6E5FW.ts.map} +0 -0
- /package/dist/chunks/{chunk-LBNC5AOM.ts.map → chunk-OBVJTKVY.ts.map} +0 -0
- /package/dist/chunks/{chunk-EXDWEFIJ.ts.map → chunk-OWEOZZZE.ts.map} +0 -0
- /package/dist/chunks/{chunk-SXCH4Q5O.ts.map → chunk-SZJOUVCL.ts.map} +0 -0
- /package/dist/chunks/{chunk-HSCAFOT5.ts.map → chunk-TZMVSTAM.ts.map} +0 -0
- /package/dist/chunks/{conflict-review-JWEA7DPQ.ts.map → conflict-review-J7L7S4AR.ts.map} +0 -0
- /package/dist/chunks/{file-selection-KID23GAD.ts.map → file-selection-DDQN4LVD.ts.map} +0 -0
- /package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts.map → manager-result-dispatcher-XB75YLEG.ts.map} +0 -0
- /package/dist/chunks/{merge-review-OQDXNTJU.ts.map → merge-review-AAC674C6.ts.map} +0 -0
- /package/dist/chunks/{remote-selection-ui-GPITNEBF.ts.map → remote-selection-ui-WVMET5RI.ts.map} +0 -0
- /package/dist/chunks/{setup-switch-L54X5U5I.ts.map → setup-switch-644T6KHG.ts.map} +0 -0
- /package/dist/chunks/{setup-wizard-LL6YMGUR.ts.map → setup-wizard-YP2KF2WQ.ts.map} +0 -0
- /package/dist/chunks/{sync-inspection-SRU6HGGK.ts.map → sync-inspection-NBBTSMKR.ts.map} +0 -0
- /package/dist/chunks/{sync-operations-UGSCONZ7.ts.map → sync-operations-AIEM2KL2.ts.map} +0 -0
|
@@ -182,11 +182,15 @@ export function automaticPolicyAuthorized(root, config) {
|
|
|
182
182
|
export async function reviewAutomaticPolicy(execution, config, expectedFingerprint) {
|
|
183
183
|
if (consentFingerprint(execution.root, config) !== expectedFingerprint)
|
|
184
184
|
throw new Error("Setup changed; reopen the automatic transfer review.");
|
|
185
|
-
if (config.reservedIgnoreNames === undefined || automaticPolicyAuthorized(execution.root, config))
|
|
185
|
+
if (config.reservedIgnoreNames === undefined || automaticPolicyAuthorized(execution.root, config)) {
|
|
186
|
+
execution.noteDebugOutcome?.("skipped");
|
|
186
187
|
return false;
|
|
188
|
+
}
|
|
187
189
|
const consent = readConsent(execution.root);
|
|
188
|
-
if (!consent)
|
|
190
|
+
if (!consent) {
|
|
191
|
+
execution.noteDebugOutcome?.("blocked");
|
|
189
192
|
return false;
|
|
193
|
+
}
|
|
190
194
|
const consentToken = JSON.stringify(consent);
|
|
191
195
|
const peers = participantBinding(execution);
|
|
192
196
|
const binding = JSON.stringify(execution.facts());
|
|
@@ -202,8 +206,10 @@ export async function reviewAutomaticPolicy(execution, config, expectedFingerpri
|
|
|
202
206
|
};
|
|
203
207
|
const current = await loadConfigForCheck(undefined, execution.signal);
|
|
204
208
|
validate();
|
|
205
|
-
if (syncCheckConfigFingerprint(current) !== fingerprint)
|
|
209
|
+
if (syncCheckConfigFingerprint(current) !== fingerprint) {
|
|
210
|
+
execution.noteDebugOutcome?.("blocked");
|
|
206
211
|
return false;
|
|
212
|
+
}
|
|
207
213
|
const modes = [
|
|
208
214
|
startupTransferEnabled(config) && "Automatic transfer at startup",
|
|
209
215
|
config.automatic &&
|
|
@@ -229,8 +235,10 @@ export async function reviewAutomaticPolicy(execution, config, expectedFingerpri
|
|
|
229
235
|
].join("\n"),
|
|
230
236
|
});
|
|
231
237
|
validate();
|
|
232
|
-
if (accepted !== true)
|
|
238
|
+
if (accepted !== true) {
|
|
239
|
+
execution.noteDebugOutcome?.("cancelled");
|
|
233
240
|
return false;
|
|
241
|
+
}
|
|
234
242
|
const latest = await loadConfigForCheck(undefined, execution.signal);
|
|
235
243
|
await config.validateIgnorePolicy?.();
|
|
236
244
|
validate();
|
|
@@ -254,28 +262,38 @@ export async function reviewAutomaticPolicy(execution, config, expectedFingerpri
|
|
|
254
262
|
}
|
|
255
263
|
export async function captureAutomaticAuthorization(execution, expectedFingerprint) {
|
|
256
264
|
const consent = readConsent(execution.root);
|
|
257
|
-
if (!consent)
|
|
265
|
+
if (!consent) {
|
|
266
|
+
execution.noteDebugOutcome?.("blocked");
|
|
258
267
|
throw new Error("Automatic work requires reviewed daemon handover first.");
|
|
268
|
+
}
|
|
259
269
|
const consentToken = JSON.stringify(consent);
|
|
260
270
|
const peers = participantBinding(execution);
|
|
261
271
|
const { loadConfigForCheck } = await import("./engine/settings/config.js");
|
|
262
272
|
const validateParticipants = () => {
|
|
263
273
|
execution.validate();
|
|
264
|
-
if (participantBinding(execution) !== peers || JSON.stringify(readConsent(execution.root)) !== consentToken)
|
|
274
|
+
if (participantBinding(execution) !== peers || JSON.stringify(readConsent(execution.root)) !== consentToken) {
|
|
275
|
+
execution.noteDebugOutcome?.("blocked");
|
|
265
276
|
throw new Error("Daemon participants or consent changed before automatic work completed.");
|
|
277
|
+
}
|
|
266
278
|
};
|
|
267
279
|
validateParticipants();
|
|
268
280
|
const config = await loadConfigForCheck(undefined, execution.signal);
|
|
269
281
|
validateParticipants();
|
|
270
282
|
const fingerprint = syncCheckConfigFingerprint(config);
|
|
271
|
-
if (expectedFingerprint !== undefined ? fingerprint !== expectedFingerprint : config.reservedIgnoreNames !== undefined)
|
|
283
|
+
if (expectedFingerprint !== undefined ? fingerprint !== expectedFingerprint : config.reservedIgnoreNames !== undefined) {
|
|
284
|
+
execution.noteDebugOutcome?.("blocked");
|
|
272
285
|
throw new Error("Settings changed before automatic work; use the reviewed foreground command.");
|
|
273
|
-
|
|
286
|
+
}
|
|
287
|
+
if (!automaticPolicyAuthorized(execution.root, config)) {
|
|
288
|
+
execution.noteDebugOutcome?.("blocked");
|
|
274
289
|
throw new Error("Automatic transfer requires separate approval for the current setup and policy. Run reviewed /sync first.");
|
|
290
|
+
}
|
|
275
291
|
const validate = (current) => {
|
|
276
292
|
validateParticipants();
|
|
277
|
-
if (current && syncCheckConfigFingerprint(current) !== fingerprint)
|
|
293
|
+
if (current && syncCheckConfigFingerprint(current) !== fingerprint) {
|
|
294
|
+
execution.noteDebugOutcome?.("blocked");
|
|
278
295
|
throw new Error("Settings changed before automatic work completed.");
|
|
296
|
+
}
|
|
279
297
|
};
|
|
280
298
|
const refresh = async () => {
|
|
281
299
|
validate();
|
|
@@ -294,8 +312,10 @@ export async function requireHandover(execution) {
|
|
|
294
312
|
message: "Close or upgrade every older Pi process before continuing. An idle older Pi cannot be detected from an absent sync lock. The daemon will own transfers; Pi keeps presentation and live file queues. Autonomous resolution uses independently available auth.json/models.json configuration and the environment captured when the service starts, not Pi runtime accounts or providers. Credential commands run non-interactively from the canonical agent root. Review this independent provider/account configuration; restart the service after changing its environment. This does not authorize transfers or model requests after the last Pi exits.",
|
|
295
313
|
});
|
|
296
314
|
execution.validate();
|
|
297
|
-
if (accepted !== true)
|
|
315
|
+
if (accepted !== true) {
|
|
316
|
+
execution.noteDebugOutcome?.("cancelled");
|
|
298
317
|
throw new Error("Daemon handover was not approved; no transfer was started.");
|
|
318
|
+
}
|
|
299
319
|
const { withLock } = await import("./engine/state/lock.js");
|
|
300
320
|
await withLock("daemon-handover", async () => {
|
|
301
321
|
execution.validate();
|
|
@@ -347,8 +367,10 @@ export async function authorizeAfterExit(execution, payload) {
|
|
|
347
367
|
message: `Setup: ${safeTerminalText(config.setupName)}\n${selection}\nModel: ${safeTerminalText(facts?.model?.provider ?? "unavailable")}/${safeTerminalText(facts?.model?.id ?? "unavailable")}\n\n${payload.afterExit ? `The daemon may transfer selected private content and send conflict evidence to this independently available provider after Pi exits. Existing budgets, exclusions, journals, and stale-evidence checks still apply. No parent conversation or tools are sent. Changing this setup or model invalidates this permission.${config.reservedIgnoreNames !== undefined ? " This also approves the enabled automatic modes for this setup while Pi clients are attached." : ""}` : "The daemon may remain alive, but no new transfer or model request may start with zero clients."}`,
|
|
348
368
|
});
|
|
349
369
|
execution.validate();
|
|
350
|
-
if (accepted !== true)
|
|
370
|
+
if (accepted !== true) {
|
|
371
|
+
execution.noteDebugOutcome?.("cancelled");
|
|
351
372
|
return undefined;
|
|
373
|
+
}
|
|
352
374
|
const latest = await loadConfigForCheck(undefined, execution.signal);
|
|
353
375
|
execution.validate();
|
|
354
376
|
await config.validateIgnorePolicy?.();
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { appendDebugEvent } from "./engine/debug-log.js";
|
|
2
|
+
import { readLocalConfigForDiagnostics } from "./engine/settings/config-file.js";
|
|
3
|
+
import { validateSettingsDocument } from "./engine/settings/settings-validation.js";
|
|
4
|
+
export function createDaemonDebug(root) {
|
|
5
|
+
let waiting = [];
|
|
6
|
+
let flushing = false;
|
|
7
|
+
async function flush() {
|
|
8
|
+
while (waiting.length) {
|
|
9
|
+
const batch = waiting;
|
|
10
|
+
waiting = [];
|
|
11
|
+
try {
|
|
12
|
+
const snapshot = await readLocalConfigForDiagnostics(root);
|
|
13
|
+
if (!snapshot || validateSettingsDocument(snapshot.document.parsed).debug !== true)
|
|
14
|
+
continue;
|
|
15
|
+
for (const { event, current } of batch) {
|
|
16
|
+
if ((current?.() ?? true) && snapshot.stillCurrent())
|
|
17
|
+
appendDebugEvent(root, "pi-sync-daemon", event);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
catch { }
|
|
21
|
+
}
|
|
22
|
+
flushing = false;
|
|
23
|
+
}
|
|
24
|
+
return (event, current) => {
|
|
25
|
+
if (waiting.length >= 32)
|
|
26
|
+
return;
|
|
27
|
+
waiting.push({ event, current });
|
|
28
|
+
if (flushing)
|
|
29
|
+
return;
|
|
30
|
+
flushing = true;
|
|
31
|
+
queueMicrotask(() => void flush());
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { DaemonError, hello, requestDaemon } from "./client-transport.js";
|
|
2
|
+
import { acquireStartupLock, checkUpgradeConsent, finishUpgrade } from "./daemon-startup.js";
|
|
3
|
+
import { canonicalRootGuard, clearUpgradeOwner, processExists, processExited, readIdentity, readProcessBirth, readUpgradeOwner, recordUpgradeOwner, runtimePaths, upgradeRepairStarted, } from "./identity.js";
|
|
4
|
+
import { withCleanup } from "./lifecycle.js";
|
|
5
|
+
import { record } from "./protocol.js";
|
|
6
|
+
export async function stopDaemonAfterForegroundQueueFailure(paths, identity, { job, client, generation, birth }, signal) {
|
|
7
|
+
const assertRoot = canonicalRootGuard(paths.root);
|
|
8
|
+
if (process.platform === "linux" && birth === undefined)
|
|
9
|
+
throw new Error("Daemon process identity could not be verified during queue cleanup.");
|
|
10
|
+
const barrier = { ...identity, birth, purpose: "cleanup" };
|
|
11
|
+
const samePublished = (current) => current !== undefined && sameOwner(current, identity) && current.token === identity.token;
|
|
12
|
+
const release = await acquireStartupLock(paths, signal);
|
|
13
|
+
await withCleanup(async () => {
|
|
14
|
+
signal.throwIfAborted();
|
|
15
|
+
assertRoot();
|
|
16
|
+
if (await readUpgradeOwner(paths))
|
|
17
|
+
throw new Error("A daemon upgrade or recovery is already pending.");
|
|
18
|
+
await checkUpgradeConsent(paths, assertRoot, signal);
|
|
19
|
+
const requireCurrent = async () => {
|
|
20
|
+
const sampled = birth === undefined ? undefined : await readProcessBirth(identity.pid);
|
|
21
|
+
const current = await readIdentity(paths);
|
|
22
|
+
signal.throwIfAborted();
|
|
23
|
+
assertRoot();
|
|
24
|
+
if (!current && (await processExited(barrier))) {
|
|
25
|
+
if (await readIdentity(paths))
|
|
26
|
+
throw new Error("Daemon owner changed during queue cleanup.");
|
|
27
|
+
signal.throwIfAborted();
|
|
28
|
+
assertRoot();
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
if (!samePublished(current) || !processExists(identity.pid) || birth !== sampled)
|
|
32
|
+
throw new Error("Daemon owner changed or could not be verified during queue cleanup.");
|
|
33
|
+
return true;
|
|
34
|
+
};
|
|
35
|
+
if (!(await requireCurrent()))
|
|
36
|
+
return;
|
|
37
|
+
const params = { job, client, generation };
|
|
38
|
+
let checked;
|
|
39
|
+
try {
|
|
40
|
+
checked = await requestDaemon(paths, identity, "foreground-stop", { ...params, check: true }, signal);
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (!(await requireCurrent()))
|
|
44
|
+
return;
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
if (!record(checked) || checked.eligible !== true)
|
|
48
|
+
throw new Error(record(checked) && typeof checked.blocked === "string"
|
|
49
|
+
? checked.blocked
|
|
50
|
+
: "Daemon queue cleanup could not be verified.");
|
|
51
|
+
if (!(await requireCurrent()))
|
|
52
|
+
return;
|
|
53
|
+
signal.throwIfAborted();
|
|
54
|
+
await recordUpgradeOwner(paths, barrier);
|
|
55
|
+
if (!(await requireCurrent()))
|
|
56
|
+
return finishUpgrade(paths, barrier, assertRoot, signal);
|
|
57
|
+
let reply;
|
|
58
|
+
try {
|
|
59
|
+
assertRoot();
|
|
60
|
+
reply = await requestDaemon(paths, identity, "foreground-stop", params, signal);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
signal.throwIfAborted();
|
|
64
|
+
const current = await readIdentity(paths);
|
|
65
|
+
signal.throwIfAborted();
|
|
66
|
+
assertRoot();
|
|
67
|
+
if (current && !samePublished(current))
|
|
68
|
+
throw new Error("Daemon owner changed during recovery. Keep the recorded evidence.", { cause: error });
|
|
69
|
+
if (current && error instanceof DaemonError)
|
|
70
|
+
throw new Error("Daemon stop could not be confirmed. Queue grants and recovery evidence were retained.", {
|
|
71
|
+
cause: error,
|
|
72
|
+
});
|
|
73
|
+
return finishUpgrade(paths, barrier, assertRoot, signal);
|
|
74
|
+
}
|
|
75
|
+
if (record(reply) && typeof reply.blocked === "string") {
|
|
76
|
+
const current = await readIdentity(paths);
|
|
77
|
+
signal.throwIfAborted();
|
|
78
|
+
assertRoot();
|
|
79
|
+
if (samePublished(current))
|
|
80
|
+
await clearUpgradeOwner(paths);
|
|
81
|
+
throw new Error(reply.blocked);
|
|
82
|
+
}
|
|
83
|
+
if (!record(reply) || reply.stopping !== true)
|
|
84
|
+
throw new Error("Daemon stop could not be confirmed. Queue grants and recovery evidence were retained.");
|
|
85
|
+
await finishUpgrade(paths, barrier, assertRoot, signal);
|
|
86
|
+
}, release);
|
|
87
|
+
}
|
|
88
|
+
async function recoveryOwner(paths) {
|
|
89
|
+
const pending = await readUpgradeOwner(paths);
|
|
90
|
+
if (pending && (pending.purpose !== "cleanup" || (await upgradeRepairStarted(paths, pending))))
|
|
91
|
+
throw new Error("A daemon upgrade or repair is pending. Follow the daemon recovery guide.");
|
|
92
|
+
const identity = await readIdentity(paths);
|
|
93
|
+
if (pending && identity && !sameOwner(pending, identity))
|
|
94
|
+
throw new Error("Daemon owner changed during recovery. Keep the recorded evidence.");
|
|
95
|
+
return { identity, pending };
|
|
96
|
+
}
|
|
97
|
+
function sameOwner(left, right) {
|
|
98
|
+
return left.root === right.root && left.pid === right.pid && left.instance === right.instance;
|
|
99
|
+
}
|
|
100
|
+
export async function inspectDaemonRecovery(root, signal) {
|
|
101
|
+
const paths = await runtimePaths(root);
|
|
102
|
+
const assertRoot = canonicalRootGuard(paths.root);
|
|
103
|
+
signal?.throwIfAborted();
|
|
104
|
+
const { identity, pending } = await recoveryOwner(paths);
|
|
105
|
+
if (!pending && identity)
|
|
106
|
+
await hello(paths, identity, signal);
|
|
107
|
+
signal?.throwIfAborted();
|
|
108
|
+
assertRoot();
|
|
109
|
+
const owner = pending ?? identity;
|
|
110
|
+
if (owner)
|
|
111
|
+
return { root: owner.root, pid: owner.pid, instance: owner.instance };
|
|
112
|
+
}
|
|
113
|
+
export async function stopDaemonForRecovery(target, signal) {
|
|
114
|
+
const paths = await runtimePaths(target.root);
|
|
115
|
+
const assertRoot = canonicalRootGuard(paths.root);
|
|
116
|
+
signal?.throwIfAborted();
|
|
117
|
+
const release = await acquireStartupLock(paths, signal);
|
|
118
|
+
await withCleanup(async () => {
|
|
119
|
+
signal?.throwIfAborted();
|
|
120
|
+
assertRoot();
|
|
121
|
+
const { identity, pending } = await recoveryOwner(paths);
|
|
122
|
+
const owner = pending ?? identity;
|
|
123
|
+
if (!owner || !sameOwner(owner, target))
|
|
124
|
+
throw new Error("Daemon owner changed. Review the current owner before stopping it.");
|
|
125
|
+
let barrier = pending;
|
|
126
|
+
if (!barrier && identity) {
|
|
127
|
+
const before = await readProcessBirth(identity.pid);
|
|
128
|
+
await hello(paths, identity, signal);
|
|
129
|
+
const birth = before === undefined ? undefined : await readProcessBirth(identity.pid);
|
|
130
|
+
if (!processExists(identity.pid) || (before !== undefined && before !== birth))
|
|
131
|
+
throw new Error("Daemon process changed during authentication. Review the current owner.");
|
|
132
|
+
await checkUpgradeConsent(paths, assertRoot, signal);
|
|
133
|
+
const current = await readIdentity(paths);
|
|
134
|
+
if (!current || !sameOwner(identity, current))
|
|
135
|
+
throw new Error("Daemon owner changed. Review the current owner before stopping it.");
|
|
136
|
+
signal?.throwIfAborted();
|
|
137
|
+
assertRoot();
|
|
138
|
+
barrier = { ...target, version: identity.version, birth, purpose: "cleanup" };
|
|
139
|
+
await recordUpgradeOwner(paths, barrier);
|
|
140
|
+
}
|
|
141
|
+
if (!barrier)
|
|
142
|
+
throw new Error("Daemon recovery has no recorded owner.");
|
|
143
|
+
if (identity && !(await processExited(barrier))) {
|
|
144
|
+
await checkUpgradeConsent(paths, assertRoot, signal);
|
|
145
|
+
try {
|
|
146
|
+
const reply = await requestDaemon(paths, identity, "stop", {}, signal);
|
|
147
|
+
if (!record(reply) || reply.stopping !== true)
|
|
148
|
+
throw new Error("Daemon did not acknowledge stop.");
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
signal?.throwIfAborted();
|
|
152
|
+
if (await readIdentity(paths))
|
|
153
|
+
throw new Error("Daemon stop could not be confirmed. Keep recovery evidence and retry.", { cause: error });
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
await finishUpgrade(paths, barrier, assertRoot, signal);
|
|
157
|
+
}, release);
|
|
158
|
+
}
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import lockfile from "proper-lockfile";
|
|
5
|
+
import { DaemonError, hello, requestDaemon } from "./client-transport.js";
|
|
6
|
+
import { canonicalRootGuard, clearUpgradeOwner, daemonPaths, privateDirectory, processExists, processExited, readIdentity, readProcessBirth, readUpgradeOwner, recordUpgradeOwner, runtimePaths, upgradeRepairStarted, } from "./identity.js";
|
|
7
|
+
import { OWNERSHIP_CLEANUP_REQUIRED, record } from "./protocol.js";
|
|
8
|
+
export async function checkUpgradeConsent(paths, assertRoot, signal) {
|
|
9
|
+
const { readConsent } = await import("./consent.js");
|
|
10
|
+
const { withStateDirectoryGuardForRoot } = await import("./engine/state/state-directory.js");
|
|
11
|
+
signal?.throwIfAborted();
|
|
12
|
+
await withStateDirectoryGuardForRoot(paths.root, () => {
|
|
13
|
+
signal?.throwIfAborted();
|
|
14
|
+
assertRoot();
|
|
15
|
+
const consent = readConsent(paths.root);
|
|
16
|
+
if (consent && Object.values(consent.setups).some((setup) => setup.afterExit))
|
|
17
|
+
throw new Error("Review or revoke unattended Pi Sync permission before stopping or replacing the daemon.");
|
|
18
|
+
});
|
|
19
|
+
signal?.throwIfAborted();
|
|
20
|
+
assertRoot();
|
|
21
|
+
}
|
|
22
|
+
export async function finishUpgrade(paths, owner, assertRoot, signal) {
|
|
23
|
+
await waitForProcessExit(owner, signal);
|
|
24
|
+
const current = await readIdentity(paths);
|
|
25
|
+
if (current?.instance === owner.instance)
|
|
26
|
+
throw new Error("The daemon exited without releasing its identity.");
|
|
27
|
+
if (current && owner.purpose === "cleanup")
|
|
28
|
+
throw new Error("Daemon owner changed during recovery. Review the current owner before retrying.");
|
|
29
|
+
await checkUpgradeConsent(paths, assertRoot, signal);
|
|
30
|
+
await clearUpgradeOwner(paths);
|
|
31
|
+
signal?.throwIfAborted();
|
|
32
|
+
assertRoot();
|
|
33
|
+
}
|
|
34
|
+
async function drainForUpgrade(paths, owner, { recorded, birth }, assertRoot, signal) {
|
|
35
|
+
await checkUpgradeConsent(paths, assertRoot, signal);
|
|
36
|
+
const barrier = recorded ?? { ...owner, birth };
|
|
37
|
+
try {
|
|
38
|
+
if (!recorded)
|
|
39
|
+
await recordUpgradeOwner(paths, barrier);
|
|
40
|
+
assertRoot();
|
|
41
|
+
const reply = await requestDaemon(paths, owner, "stop", {}, signal);
|
|
42
|
+
if (!record(reply) || reply.stopping !== true)
|
|
43
|
+
throw new Error("Daemon did not acknowledge stop.");
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
signal?.throwIfAborted();
|
|
47
|
+
throw new Error("Pi Sync could not upgrade the older daemon safely. Check `pi-sync-daemon status --root <agent-directory>`. Do not force a second owner or remove recovery files.", { cause: error });
|
|
48
|
+
}
|
|
49
|
+
await finishUpgrade(paths, barrier, assertRoot, signal);
|
|
50
|
+
}
|
|
51
|
+
export async function acquireStartupLock(paths, signal) {
|
|
52
|
+
const deadline = performance.now() + 150_000;
|
|
53
|
+
for (;;) {
|
|
54
|
+
signal?.throwIfAborted();
|
|
55
|
+
try {
|
|
56
|
+
return await lockfile.lock(paths.directory, {
|
|
57
|
+
realpath: false,
|
|
58
|
+
lockfilePath: paths.startup,
|
|
59
|
+
stale: 30_000,
|
|
60
|
+
update: 5_000,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
signal?.throwIfAborted();
|
|
65
|
+
if (error.code !== "ELOCKED")
|
|
66
|
+
throw error;
|
|
67
|
+
if (performance.now() >= deadline)
|
|
68
|
+
throw new Error("Timed out waiting to start the Pi Sync daemon.", { cause: error });
|
|
69
|
+
await delay(50, undefined, { signal });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export async function ensureDaemon(root, signal, options) {
|
|
74
|
+
const paths = await runtimePaths(root);
|
|
75
|
+
const assertRoot = canonicalRootGuard(paths.root);
|
|
76
|
+
signal?.throwIfAborted();
|
|
77
|
+
await privateDirectory(paths.directory);
|
|
78
|
+
signal?.throwIfAborted();
|
|
79
|
+
const release = await acquireStartupLock(paths, signal);
|
|
80
|
+
try {
|
|
81
|
+
signal?.throwIfAborted();
|
|
82
|
+
let waited = false;
|
|
83
|
+
let upgraded = false;
|
|
84
|
+
for (;;) {
|
|
85
|
+
signal?.throwIfAborted();
|
|
86
|
+
const upgrade = await readUpgradeOwner(paths);
|
|
87
|
+
if (upgrade && options?.compatibleOnly)
|
|
88
|
+
throw new Error("A daemon upgrade or recovery is pending; no replacement was attempted.");
|
|
89
|
+
if (upgrade && (await upgradeRepairStarted(paths, upgrade)))
|
|
90
|
+
throw new Error("A daemon upgrade repair is incomplete. Run `pi-sync-daemon repair-upgrade` for this root.");
|
|
91
|
+
const existing = await readIdentity(paths);
|
|
92
|
+
if (upgrade && existing?.instance === upgrade.instance && existing.pid !== upgrade.pid)
|
|
93
|
+
throw new Error("The recorded upgrade owner changed; private state was retained.");
|
|
94
|
+
if (upgrade && (existing?.instance !== upgrade.instance || (await processExited(upgrade)))) {
|
|
95
|
+
await finishUpgrade(paths, upgrade, assertRoot, signal);
|
|
96
|
+
upgraded = true;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (upgrade?.purpose === "cleanup")
|
|
100
|
+
throw Object.assign(new Error("Daemon recovery is incomplete. Use /sync daemon recover to finish the reviewed stop."), { code: OWNERSHIP_CLEANUP_REQUIRED });
|
|
101
|
+
if (!existing)
|
|
102
|
+
break;
|
|
103
|
+
const beforeHello = upgrade ? undefined : await readProcessBirth(existing.pid);
|
|
104
|
+
let status;
|
|
105
|
+
try {
|
|
106
|
+
status = await hello(paths, existing, signal);
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
if (signal?.aborted)
|
|
110
|
+
throw signal.reason;
|
|
111
|
+
if (upgrade) {
|
|
112
|
+
await finishUpgrade(paths, upgrade, assertRoot, signal);
|
|
113
|
+
upgraded = true;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError" && !waited) {
|
|
117
|
+
waited = true;
|
|
118
|
+
await waitForDaemonExit(existing, signal);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (processExists(existing.pid))
|
|
122
|
+
throw new Error("A daemon owner is alive but unavailable; use diagnostics instead of starting a second owner.", { cause: error });
|
|
123
|
+
break;
|
|
124
|
+
}
|
|
125
|
+
signal?.throwIfAborted();
|
|
126
|
+
assertRoot();
|
|
127
|
+
if (!status.needsUpgrade) {
|
|
128
|
+
if (upgrade)
|
|
129
|
+
throw new Error("The recorded upgrade owner changed; private state was retained.");
|
|
130
|
+
return { paths: daemonPaths(paths, existing.instance), identity: existing, ...status };
|
|
131
|
+
}
|
|
132
|
+
if (options?.compatibleOnly)
|
|
133
|
+
throw new Error("A compatible daemon could not be attached; an older owner was left unchanged.");
|
|
134
|
+
if (upgraded)
|
|
135
|
+
throw new Error("An older Pi Sync daemon started again. Close or upgrade other Pi sessions, then use /reload.");
|
|
136
|
+
const birth = beforeHello === undefined ? undefined : await readProcessBirth(existing.pid);
|
|
137
|
+
if (birth !== undefined && birth !== beforeHello)
|
|
138
|
+
throw new Error("The daemon process changed during authentication; private state was retained.");
|
|
139
|
+
await drainForUpgrade(paths, existing, { recorded: upgrade, birth }, assertRoot, signal);
|
|
140
|
+
upgraded = true;
|
|
141
|
+
}
|
|
142
|
+
signal?.throwIfAborted();
|
|
143
|
+
assertRoot();
|
|
144
|
+
const executable = process.versions.bun ? "node" : process.execPath;
|
|
145
|
+
const child = spawn(executable, [fileURLToPath(new URL("./cli.js", import.meta.url)), "serve", "--root", paths.root], {
|
|
146
|
+
detached: true,
|
|
147
|
+
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
148
|
+
windowsHide: true,
|
|
149
|
+
});
|
|
150
|
+
const ready = await new Promise((resolve, reject) => {
|
|
151
|
+
let timer;
|
|
152
|
+
const abort = () => {
|
|
153
|
+
cleanup();
|
|
154
|
+
reject(signal?.reason);
|
|
155
|
+
};
|
|
156
|
+
const cleanup = () => {
|
|
157
|
+
if (timer)
|
|
158
|
+
clearTimeout(timer);
|
|
159
|
+
signal?.removeEventListener("abort", abort);
|
|
160
|
+
child.off("message", message);
|
|
161
|
+
child.off("error", failed);
|
|
162
|
+
child.off("exit", exited);
|
|
163
|
+
};
|
|
164
|
+
const failed = (error) => {
|
|
165
|
+
cleanup();
|
|
166
|
+
reject(error);
|
|
167
|
+
};
|
|
168
|
+
const exited = (code) => failed(new Error(`Daemon startup exited (${code}); private state was retained.`));
|
|
169
|
+
const message = (value) => {
|
|
170
|
+
if (!record(value))
|
|
171
|
+
return;
|
|
172
|
+
if (value.type === "booting") {
|
|
173
|
+
timer = setTimeout(() => failed(new Error("Daemon readiness timed out.")), 15_000);
|
|
174
|
+
timer.unref?.();
|
|
175
|
+
}
|
|
176
|
+
if (value.type === "error")
|
|
177
|
+
failed(new Error(typeof value.message === "string" ? value.message : "Daemon startup failed."));
|
|
178
|
+
if (value.type === "ready" && record(value.identity)) {
|
|
179
|
+
cleanup();
|
|
180
|
+
resolve(value.identity);
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
184
|
+
child.on("message", message);
|
|
185
|
+
child.once("error", failed);
|
|
186
|
+
child.once("exit", exited);
|
|
187
|
+
if (signal?.aborted)
|
|
188
|
+
abort();
|
|
189
|
+
}).finally(() => {
|
|
190
|
+
if (child.connected)
|
|
191
|
+
child.disconnect();
|
|
192
|
+
child.unref();
|
|
193
|
+
});
|
|
194
|
+
const status = await hello(paths, ready, signal);
|
|
195
|
+
signal?.throwIfAborted();
|
|
196
|
+
assertRoot();
|
|
197
|
+
if (status.needsUpgrade)
|
|
198
|
+
throw new Error("The daemon installation changed during startup. Use /reload to retry.");
|
|
199
|
+
return { paths: daemonPaths(paths, ready.instance), identity: ready, ...status };
|
|
200
|
+
}
|
|
201
|
+
finally {
|
|
202
|
+
await release();
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
export async function waitForDaemonExit({ pid }, signal) {
|
|
206
|
+
await waitForProcessExit({ pid }, signal);
|
|
207
|
+
}
|
|
208
|
+
async function waitForProcessExit(owner, signal) {
|
|
209
|
+
const deadline = Date.now() + 30_000;
|
|
210
|
+
signal?.throwIfAborted();
|
|
211
|
+
while (!(await processExited(owner))) {
|
|
212
|
+
signal?.throwIfAborted();
|
|
213
|
+
if (Date.now() >= deadline)
|
|
214
|
+
throw new Error("Closing daemon is still alive; replacement was not attempted.");
|
|
215
|
+
await delay(25, undefined, { signal });
|
|
216
|
+
}
|
|
217
|
+
signal?.throwIfAborted();
|
|
218
|
+
}
|
|
219
|
+
export async function findDaemon(root) {
|
|
220
|
+
let paths;
|
|
221
|
+
try {
|
|
222
|
+
paths = await runtimePaths(root);
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
if (error.code === "ENOENT")
|
|
226
|
+
return undefined;
|
|
227
|
+
throw error;
|
|
228
|
+
}
|
|
229
|
+
const identity = await readIdentity(paths);
|
|
230
|
+
if (!identity || !processExists(identity.pid))
|
|
231
|
+
return undefined;
|
|
232
|
+
try {
|
|
233
|
+
const status = await hello(paths, identity);
|
|
234
|
+
return { paths: daemonPaths(paths, identity.instance), identity, ...status };
|
|
235
|
+
}
|
|
236
|
+
catch (error) {
|
|
237
|
+
if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError")
|
|
238
|
+
return undefined;
|
|
239
|
+
throw error;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
export async function stopDaemon(root) {
|
|
243
|
+
const paths = await runtimePaths(root);
|
|
244
|
+
const identity = await readIdentity(paths);
|
|
245
|
+
if (!identity)
|
|
246
|
+
return false;
|
|
247
|
+
await requestDaemon(paths, identity, "stop", {});
|
|
248
|
+
const deadline = Date.now() + 30_000;
|
|
249
|
+
for (;;) {
|
|
250
|
+
const current = await readIdentity(paths);
|
|
251
|
+
if (!current || current.instance !== identity.instance)
|
|
252
|
+
return true;
|
|
253
|
+
if (Date.now() >= deadline)
|
|
254
|
+
throw new Error("Daemon did not drain; no replacement was attempted.");
|
|
255
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
256
|
+
}
|
|
257
|
+
}
|