@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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { isDeniedPath, toPosix } from "../paths.js";
|
|
3
|
+
import { DEBUG_LOG_FILENAME, isDebugLogPath, isDeniedPath, toPosix } from "../paths.js";
|
|
4
4
|
import { IGNORE_SNAPSHOT_VERSION, } from "../snapshot/snapshot-types.js";
|
|
5
5
|
import { compilePathRules, compileSyncExclude, normalizeSyncExclude, sameSyncExclude } from "./exclude-policy.js";
|
|
6
6
|
export const BUILT_IN_SYNC_ROOTS = [
|
|
@@ -202,6 +202,14 @@ export function validateSnapshotSelection(snapshot) {
|
|
|
202
202
|
if ((snapshot.version === IGNORE_SNAPSHOT_VERSION) !== (selection?.version === 4))
|
|
203
203
|
throw new Error("Ignore-file policy requires snapshot version 6 and selection version 4.");
|
|
204
204
|
}
|
|
205
|
+
export function assertSnapshotPathExcludesDebugLog(filePath) {
|
|
206
|
+
if (typeof filePath === "string" && isDebugLogPath(filePath))
|
|
207
|
+
throw new Error(`Snapshot contains the local-only ${DEBUG_LOG_FILENAME}. Review the old snapshot before retrying sync.`);
|
|
208
|
+
}
|
|
209
|
+
export function assertSnapshotExcludesDebugLog(snapshot) {
|
|
210
|
+
for (const file of snapshot.files)
|
|
211
|
+
assertSnapshotPathExcludesDebugLog(file?.path);
|
|
212
|
+
}
|
|
205
213
|
export function requireLegacyTransferPolicy(snapshot) {
|
|
206
214
|
if (snapshot.version === IGNORE_SNAPSHOT_VERSION || snapshot.selection?.version === 4)
|
|
207
215
|
throw new Error("This setup cannot transfer an ignore-file snapshot without a reviewed local ignore policy.");
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createSyncBackend } from "../backends/backend-factory.js";
|
|
2
|
+
import { HISTORY_PREVIEW_LIMIT } from "../backends/sync-backend.js";
|
|
2
3
|
import { loadConfig, syncSessionsWarnings } from "../settings/config.js";
|
|
3
4
|
import { resolvedSnapshotOptionsForContext } from "../snapshot/session-paths.js";
|
|
4
5
|
import { createSnapshot, scanSnapshot } from "../snapshot/snapshot.js";
|
|
@@ -174,7 +175,7 @@ export async function history(ctx, options, factory = createSyncBackend) {
|
|
|
174
175
|
const config = await loadConfig(options.setup);
|
|
175
176
|
throwIfAborted(options.signal);
|
|
176
177
|
const backend = await factory(config);
|
|
177
|
-
const snapshots = (await backend.listHistory(options.signal)).slice(-
|
|
178
|
+
const snapshots = (await backend.listHistory(options.signal)).slice(-HISTORY_PREVIEW_LIMIT).reverse();
|
|
178
179
|
throwIfAborted(options.signal);
|
|
179
180
|
const lastApplied = await readStateForConfig(config)
|
|
180
181
|
.then((state) => state.lastAppliedSnapshot)
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { createSyncBackend } from "../backends/backend-factory.js";
|
|
2
|
+
import { expectedRemoteHead } from "../backends/sync-backend.js";
|
|
3
|
+
import { loadConfig, syncCheckConfigFingerprint } from "../settings/config.js";
|
|
4
|
+
import { effectiveSessionRoot, requireStableMergeSessionRoot, resolvedSnapshotOptionsForContext, sessionDirForApply, } from "../snapshot/session-paths.js";
|
|
5
|
+
import { createSnapshot, filterSnapshotForConfigPolicy, regenerateSnapshotIdentity, snapshotIncludesSessions, snapshotWithoutSessions, } from "../snapshot/snapshot.js";
|
|
6
|
+
import { applySnapshot } from "../snapshot/snapshot-apply.js";
|
|
7
|
+
import { ignorePolicyValidator } from "../snapshot/snapshot-transaction-policy.js";
|
|
8
|
+
import { pruneMergeBaselines } from "../state/merge-baseline-store.js";
|
|
9
|
+
import { readStateForConfig, syncStateFingerprint, writeStateForConfig } from "../state/sync-state-store.js";
|
|
10
|
+
import { formatPublicationPreview, formatRollbackSummary, formatTransferReview } from "../ui/sync-format.js";
|
|
11
|
+
import { confirmTransferReview } from "../ui/transfer-review.js";
|
|
12
|
+
import { inspectCaseCleanup, revalidateCaseCleanup } from "./apply-review.js";
|
|
13
|
+
import { confirmFieldMigration } from "./field-migration.js";
|
|
14
|
+
import { overlayLocalFields, portableSnapshot, sameLocalFields, validatePortableSnapshot } from "./local-fields.js";
|
|
15
|
+
import { requireNoMergeJournal, retireMergeJournal } from "./merge-journal.js";
|
|
16
|
+
import { readSnapshotForHead, requireCompatibleRemoteSelection, sameRemoteHead, snapshotForUpload, } from "./remote-snapshot.js";
|
|
17
|
+
import { throwIfAborted } from "./signals.js";
|
|
18
|
+
import { PublicationStatePersistenceError, RollbackPublicationError } from "./sync-errors.js";
|
|
19
|
+
import { backupLocal, captureMutationOwner, maybeReload, protectedSessionPaths } from "./sync-local.js";
|
|
20
|
+
import { requireLegacyTransferPolicy, syncSessionsSelected } from "./sync-policy.js";
|
|
21
|
+
import { acceptedSelection, fileHashMap, sameHashes } from "./sync-state.js";
|
|
22
|
+
import { directionalApplyGuards, requireIgnoreBaselineReview, requireResolvedDirectionalProgress, validateDirectionalPublication, } from "./transfer-freshness.js";
|
|
23
|
+
const VERSION = 1;
|
|
24
|
+
const POST_LOCAL_COMMIT_TIMEOUT_MS = 30_000;
|
|
25
|
+
export async function rollback(ctx, options, factory = createSyncBackend, expectedSelection) {
|
|
26
|
+
if (options.directionalAction)
|
|
27
|
+
throw new Error("Single-action transfer cannot authorize rollback.");
|
|
28
|
+
const validateMutation = captureMutationOwner(ctx, options.signal);
|
|
29
|
+
const validateCommittedOwner = captureMutationOwner(ctx);
|
|
30
|
+
const target = options.args[0];
|
|
31
|
+
if (!target)
|
|
32
|
+
throw new Error("Usage: /sync rollback <snapshot-id> [--yes]");
|
|
33
|
+
const config = await loadConfig(options.setup);
|
|
34
|
+
validateMutation();
|
|
35
|
+
if (config.ignorePolicy && (options.yes || options.auto || !ctx.hasUI))
|
|
36
|
+
throw new Error("Ignore-file rollback requires a separate foreground review; --yes cannot confirm it.");
|
|
37
|
+
const backend = await factory(config);
|
|
38
|
+
if (expectedSelection &&
|
|
39
|
+
(backend.identity !== expectedSelection.backendIdentity || config.setupName !== expectedSelection.setup)) {
|
|
40
|
+
throw new Error("Sync setup or storage location changed while history was open; reopen history and retry.");
|
|
41
|
+
}
|
|
42
|
+
await requireNoMergeJournal(config);
|
|
43
|
+
const state = await readStateForConfig(config);
|
|
44
|
+
validateMutation();
|
|
45
|
+
requireIgnoreBaselineReview(ctx, config, state, options);
|
|
46
|
+
requireResolvedDirectionalProgress(state, options, false);
|
|
47
|
+
const decoded = await backend.readSnapshot(target, options.signal);
|
|
48
|
+
validateMutation();
|
|
49
|
+
validatePortableSnapshot(decoded);
|
|
50
|
+
if (!config.ignorePolicy)
|
|
51
|
+
requireLegacyTransferPolicy(decoded);
|
|
52
|
+
if (config.ignorePolicy && expectedSelection?.snapshotId && decoded.id !== expectedSelection.snapshotId)
|
|
53
|
+
throw new Error("Historical snapshot changed while history was open; reopen history and retry.");
|
|
54
|
+
if (!sameLocalFields(decoded.localFields, config.localFields))
|
|
55
|
+
throw new Error("Rollback requires the historical snapshot local-field policy to match the configured rules. Review push --force from current local bytes to migrate policy first; choose matching history afterward.");
|
|
56
|
+
const snapshotOptions = await resolvedSnapshotOptionsForContext(ctx, config, options.signal);
|
|
57
|
+
validateMutation();
|
|
58
|
+
const validateIgnorePolicy = ignorePolicyValidator({ ...snapshotOptions, validateMutation });
|
|
59
|
+
const selected = filterSnapshotForConfigPolicy(config.ignorePolicy || syncSessionsSelected(config) ? decoded : snapshotWithoutSessions(decoded), config, snapshotOptions);
|
|
60
|
+
const remote = portableSnapshot(regenerateSnapshotIdentity(selected), config.localFields);
|
|
61
|
+
const local = await createSnapshot(config.snapshotIdentity, snapshotOptions);
|
|
62
|
+
const expectedHead = await backend.readHead(options.signal);
|
|
63
|
+
const currentRemote = expectedHead
|
|
64
|
+
? await readSnapshotForHead(backend, expectedHead, options.signal, config)
|
|
65
|
+
: undefined;
|
|
66
|
+
validateMutation();
|
|
67
|
+
if (config.ignorePolicy && currentRemote)
|
|
68
|
+
requireCompatibleRemoteSelection(config, currentRemote);
|
|
69
|
+
if (!(await confirmFieldMigration(ctx, config, state, currentRemote, true, options.signal)))
|
|
70
|
+
return;
|
|
71
|
+
validateMutation();
|
|
72
|
+
const physical = overlayLocalFields(remote, local, config.localFields);
|
|
73
|
+
if (config.scope === "agent-directory")
|
|
74
|
+
requireStableMergeSessionRoot(local, physical, config.scope);
|
|
75
|
+
const upload = config.ignorePolicy
|
|
76
|
+
? remote
|
|
77
|
+
: await snapshotForUpload(backend, config, remote, expectedHead, currentRemote, snapshotOptions);
|
|
78
|
+
if (config.scope === "agent-directory")
|
|
79
|
+
validatePortableSnapshot(upload);
|
|
80
|
+
const caseCleanup = options.yes ? [] : await inspectCaseCleanup(physical, snapshotOptions);
|
|
81
|
+
validateMutation();
|
|
82
|
+
const reviewedProtectedPaths = protectedSessionPaths(ctx, snapshotOptions.sessionDir);
|
|
83
|
+
if (!options.yes) {
|
|
84
|
+
const title = snapshotIncludesSessions(remote) ? "Rollback pi settings and sessions?" : "Rollback pi settings?";
|
|
85
|
+
const summary = formatRollbackSummary(config, backend.destination, local, physical, target, reviewedProtectedPaths, caseCleanup.map((item) => item.path));
|
|
86
|
+
const confirmed = config.ignorePolicy
|
|
87
|
+
? await confirmTransferReview(ctx, title, formatTransferReview("Historical files are projected through this device's current ignore rules. Historical rules are not adopted. Retained history is not erased.", "", summary, "", "Remote publication:", formatPublicationPreview(currentRemote, upload)), options.signal, validateMutation)
|
|
88
|
+
: await ctx.ui.confirm(title, summary.content, { signal: options.signal });
|
|
89
|
+
validateMutation();
|
|
90
|
+
if (!confirmed) {
|
|
91
|
+
ctx.ui.notify("Rollback cancelled.", "info");
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
validateMutation();
|
|
96
|
+
const currentLocal = await createSnapshot(config.snapshotIdentity, snapshotOptions);
|
|
97
|
+
if (!sameHashes(fileHashMap(currentLocal), fileHashMap(local)))
|
|
98
|
+
throw new Error("Local bytes changed during rollback review.");
|
|
99
|
+
if (syncCheckConfigFingerprint(config) !== syncCheckConfigFingerprint(await loadConfig(options.setup)))
|
|
100
|
+
throw new Error("Settings changed during rollback review.");
|
|
101
|
+
if (!sameRemoteHead(backend, expectedHead, await backend.readHead(options.signal)))
|
|
102
|
+
throw new Error("Remote changed during rollback review.");
|
|
103
|
+
validateMutation();
|
|
104
|
+
throwIfAborted(options.signal);
|
|
105
|
+
const backup = await backupLocal(config.snapshotIdentity, snapshotOptions, options.signal);
|
|
106
|
+
const applySessionDir = await sessionDirForApply(ctx, config.scope ? physical : remote, snapshotOptions);
|
|
107
|
+
const currentState = await readStateForConfig(config);
|
|
108
|
+
if ((validateIgnorePolicy || !options.yes) && syncStateFingerprint(currentState) !== syncStateFingerprint(state))
|
|
109
|
+
throw new Error("Baseline changed during rollback review.");
|
|
110
|
+
requireResolvedDirectionalProgress(currentState, options, false);
|
|
111
|
+
if (!options.yes)
|
|
112
|
+
await revalidateCaseCleanup(caseCleanup, physical, snapshotOptions);
|
|
113
|
+
if (config.scope && applySessionDir !== (await effectiveSessionRoot(ctx, config, options.signal)))
|
|
114
|
+
throw new Error("Pi session storage changed during rollback review.");
|
|
115
|
+
validateMutation();
|
|
116
|
+
if (syncCheckConfigFingerprint(config) !== syncCheckConfigFingerprint(await loadConfig(options.setup)))
|
|
117
|
+
throw new Error("Settings changed during rollback review.");
|
|
118
|
+
validateMutation();
|
|
119
|
+
if (validateIgnorePolicy) {
|
|
120
|
+
if (!sameRemoteHead(backend, expectedHead, await backend.readHead(options.signal)))
|
|
121
|
+
throw new Error("Remote changed during rollback review.");
|
|
122
|
+
await validateIgnorePolicy();
|
|
123
|
+
}
|
|
124
|
+
const protectedPaths = protectedSessionPaths(ctx, snapshotOptions.sessionDir);
|
|
125
|
+
const applyGuards = directionalApplyGuards({
|
|
126
|
+
ctx,
|
|
127
|
+
config,
|
|
128
|
+
backend,
|
|
129
|
+
state,
|
|
130
|
+
sessionDir: snapshotOptions.sessionDir,
|
|
131
|
+
head: expectedHead,
|
|
132
|
+
protectedPaths: reviewedProtectedPaths,
|
|
133
|
+
signal: options.signal,
|
|
134
|
+
onCommit: options.onCommit,
|
|
135
|
+
validateMutation,
|
|
136
|
+
validateIgnorePolicy,
|
|
137
|
+
});
|
|
138
|
+
applyGuards.validateMutation();
|
|
139
|
+
if (!validateIgnorePolicy)
|
|
140
|
+
options.onCommit?.();
|
|
141
|
+
const lastFileHashes = await applySnapshot(physical, protectedPaths, {
|
|
142
|
+
...snapshotOptions,
|
|
143
|
+
sessionDir: applySessionDir,
|
|
144
|
+
...applyGuards,
|
|
145
|
+
...(config.scope === "agent-directory" || validateIgnorePolicy ? { reviewedLocal: local } : {}),
|
|
146
|
+
expectedFileHashes: config.localFields?.length
|
|
147
|
+
? { "settings.json": fileHashMap(local)["settings.json"] ?? null }
|
|
148
|
+
: undefined,
|
|
149
|
+
});
|
|
150
|
+
validateCommittedOwner();
|
|
151
|
+
let result;
|
|
152
|
+
try {
|
|
153
|
+
const signal = AbortSignal.timeout(POST_LOCAL_COMMIT_TIMEOUT_MS);
|
|
154
|
+
const validatePolicy = ignorePolicyValidator({
|
|
155
|
+
...snapshotOptions,
|
|
156
|
+
signal,
|
|
157
|
+
validateMutation: validateCommittedOwner,
|
|
158
|
+
});
|
|
159
|
+
const validatePublication = validatePolicy
|
|
160
|
+
? () => validateDirectionalPublication(ctx, config, { ...snapshotOptions, sessionDir: applySessionDir, signal }, state, lastFileHashes, validatePolicy, "rollback")
|
|
161
|
+
: undefined;
|
|
162
|
+
result = await backend.publishSnapshot(upload, expectedRemoteHead(expectedHead), {
|
|
163
|
+
signal,
|
|
164
|
+
...(validatePublication ? { validateIgnorePolicy: validatePublication } : {}),
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
throw new RollbackPublicationError(backup, error);
|
|
169
|
+
}
|
|
170
|
+
try {
|
|
171
|
+
await writeStateForConfig(config, {
|
|
172
|
+
version: VERSION,
|
|
173
|
+
profile: config.snapshotIdentity,
|
|
174
|
+
lastAppliedSnapshot: result.head.snapshotId,
|
|
175
|
+
lastRemoteRevision: result.head.revision,
|
|
176
|
+
lastFileHashes: config.localFields?.length
|
|
177
|
+
? { ...lastFileHashes, "settings.json": fileHashMap(remote)["settings.json"] }
|
|
178
|
+
: lastFileHashes,
|
|
179
|
+
...acceptedSelection(config),
|
|
180
|
+
...(config.localFields !== undefined ? { localFields: config.localFields } : {}),
|
|
181
|
+
}, remote, validateCommittedOwner);
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
throw new PublicationStatePersistenceError(result.head, error, backup);
|
|
185
|
+
}
|
|
186
|
+
await retireMergeJournal(config);
|
|
187
|
+
await pruneMergeBaselines(config, await readStateForConfig(config), validateCommittedOwner);
|
|
188
|
+
validateCommittedOwner();
|
|
189
|
+
if (options.signal?.aborted)
|
|
190
|
+
return;
|
|
191
|
+
ctx.ui.notify([
|
|
192
|
+
`Rolled back sync setup “${config.setupName}” to ${target}; latest: ${result.head.snapshotId}. Backup: ${backup}`,
|
|
193
|
+
...result.warnings,
|
|
194
|
+
]
|
|
195
|
+
.filter(Boolean)
|
|
196
|
+
.join("\n"), result.warnings.length > 0 ? "warning" : "info");
|
|
197
|
+
await maybeReload(ctx, options.signal, validateMutation);
|
|
198
|
+
}
|
|
@@ -1,14 +1,17 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
1
2
|
import { toPosix } from "../paths.js";
|
|
2
3
|
import { canonicalSnapshotPathForConfig, filterSnapshotForConfigPolicy, isSessionPath } from "../snapshot/snapshot.js";
|
|
3
4
|
import { sameSyncExclude } from "./exclude-policy.js";
|
|
4
|
-
import { portableSnapshot, sameLocalFields } from "./local-fields.js";
|
|
5
|
+
import { portableObservation, portableSnapshot, sameLocalFields } from "./local-fields.js";
|
|
5
6
|
import { compareIgnorePolicy, configuredSnapshotPathMatcher, customIncludePathsByLower, includeFromSelectionConfig, localIgnorePolicyKey, normalizeSyncInclude, syncDirectoryPolicyKey, syncSessionsSelected, } from "./sync-policy.js";
|
|
6
7
|
export function hasLocalChanges(local, state, config) {
|
|
7
|
-
|
|
8
|
+
if (state.lastAppliedSnapshot &&
|
|
8
9
|
(state.scope !== config.scope ||
|
|
9
10
|
!sameLocalFields(state.localFields, config.localFields) ||
|
|
10
|
-
!sameSelectionRules(state, config)))
|
|
11
|
-
|
|
11
|
+
!sameSelectionRules(state, config)))
|
|
12
|
+
return true;
|
|
13
|
+
const portable = "version" in local ? portableSnapshot(local, config.localFields) : portableObservation(local, config.localFields);
|
|
14
|
+
return !sameHashes(fileHashMap(portable), stateHashMapForConfig(state, config));
|
|
12
15
|
}
|
|
13
16
|
export function remoteChangedSinceState(head, state, config, sameRevision) {
|
|
14
17
|
if (!head)
|
|
@@ -46,6 +49,11 @@ export function sameHashes(left, right) {
|
|
|
46
49
|
export function fileHashMap(snapshot) {
|
|
47
50
|
return Object.fromEntries(snapshot.files.map((file) => [file.path, file.sha256]));
|
|
48
51
|
}
|
|
52
|
+
export function rawSnapshotHashIdentity(snapshot) {
|
|
53
|
+
return createHash("sha256")
|
|
54
|
+
.update(JSON.stringify(fileHashMap(snapshot)))
|
|
55
|
+
.digest("hex");
|
|
56
|
+
}
|
|
49
57
|
function stateHashMapForConfig(state, config) {
|
|
50
58
|
const includePaths = customIncludePathsByLower(includeFromSelectionConfig(config));
|
|
51
59
|
const configured = configuredSnapshotPathMatcher(config);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { resolvedSnapshotOptionsForContext } from "../snapshot/session-paths.js";
|
|
1
|
+
import { effectiveSessionRoot, resolvedSnapshotOptionsForContext } from "../snapshot/session-paths.js";
|
|
2
2
|
import { createSnapshot } from "../snapshot/snapshot.js";
|
|
3
3
|
import { StaleIgnorePolicyError } from "../snapshot/snapshot-transaction-policy.js";
|
|
4
4
|
import { readStateForConfig, syncStateFingerprint } from "../state/sync-state-store.js";
|
|
@@ -19,14 +19,17 @@ export function requireIgnoreBaselineReview(ctx, config, state, options) {
|
|
|
19
19
|
throw new Error("Local ignore-file policy or source changed since the last accepted baseline. Review a foreground directional transfer.");
|
|
20
20
|
}
|
|
21
21
|
}
|
|
22
|
-
export async function validateDirectionalPublication(ctx, config, options, state, expectedHashes, validatePolicy, direction) {
|
|
22
|
+
export async function validateDirectionalPublication(ctx, config, options, state, expectedHashes, validatePolicy, direction, effectiveRoot = false) {
|
|
23
23
|
const current = await createSnapshot(config.snapshotIdentity, options);
|
|
24
24
|
if (!sameHashes(fileHashMap(current), expectedHashes))
|
|
25
25
|
throw new Error(`Local bytes changed at the ${direction} publication boundary.`);
|
|
26
26
|
if (syncStateFingerprint(await readStateForConfig(config)) !== syncStateFingerprint(state))
|
|
27
27
|
throw new Error(`Baseline changed at the ${direction} publication boundary.`);
|
|
28
28
|
if ((config.scope === "agent-directory" || direction === "push") &&
|
|
29
|
-
options.sessionDir !==
|
|
29
|
+
options.sessionDir !==
|
|
30
|
+
(effectiveRoot
|
|
31
|
+
? await effectiveSessionRoot(ctx, config, options.signal)
|
|
32
|
+
: (await resolvedSnapshotOptionsForContext(ctx, config, options.signal)).sessionDir))
|
|
30
33
|
throw new Error(`Pi session storage changed at the ${direction} publication boundary.`);
|
|
31
34
|
await validatePolicy();
|
|
32
35
|
}
|
|
@@ -35,7 +38,7 @@ export function checkLiveProtection(ctx, sessionDir, reviewed) {
|
|
|
35
38
|
if (current.size !== reviewed.size || [...current].some((item) => !reviewed.has(item)))
|
|
36
39
|
throw new StaleIgnorePolicyError("Live session protection changed during review; reopen the review.");
|
|
37
40
|
}
|
|
38
|
-
export function directionalApplyGuards({ ctx, config, backend, state, sessionDir, head, protectedPaths, signal, validateMutation, validateIgnorePolicy, onCommit, }) {
|
|
41
|
+
export function directionalApplyGuards({ ctx, config, backend, state, sessionDir, head, protectedPaths, signal, validateMutation, validateIgnorePolicy, onCommit, effectiveRoot = false, }) {
|
|
39
42
|
if (!validateIgnorePolicy)
|
|
40
43
|
return { validateMutation };
|
|
41
44
|
const validateOwner = () => {
|
|
@@ -50,7 +53,10 @@ export function directionalApplyGuards({ ctx, config, backend, state, sessionDir
|
|
|
50
53
|
throw new StaleIgnorePolicyError("Remote changed before local apply; reopen the review.");
|
|
51
54
|
if (syncStateFingerprint(await readStateForConfig(config)) !== syncStateFingerprint(state))
|
|
52
55
|
throw new StaleIgnorePolicyError("Baseline changed before local apply; reopen the review.");
|
|
53
|
-
if (sessionDir !==
|
|
56
|
+
if (sessionDir !==
|
|
57
|
+
(effectiveRoot
|
|
58
|
+
? await effectiveSessionRoot(ctx, config, signal)
|
|
59
|
+
: (await resolvedSnapshotOptionsForContext(ctx, config, signal)).sessionDir))
|
|
54
60
|
throw new StaleIgnorePolicyError("Pi session storage changed before local apply; reopen the review.");
|
|
55
61
|
await validateIgnorePolicy();
|
|
56
62
|
validateOwner();
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { authorizeAfterExit, automaticPolicyAuthorized, captureAutomaticAuthorization, consentFingerprint, readConsent, requireHandover, reviewAutomaticPolicy, revokeAfterExitGrants, } from "./consent.js";
|
|
2
|
+
import { createDaemonDebug } from "./daemon-debug.js";
|
|
2
3
|
import { documentFingerprint } from "./document.js";
|
|
4
|
+
import { captureStartupReviewLock } from "./engine/state/lock.js";
|
|
3
5
|
import { createMonitor } from "./monitor.js";
|
|
4
6
|
import { MAX_SETTINGS_BYTES, record } from "./protocol.js";
|
|
5
7
|
import { createServiceContext, installServiceHost } from "./service-host.js";
|
|
@@ -37,6 +39,7 @@ function optionsFrom(value, execution, automatic) {
|
|
|
37
39
|
...(typeof value.automaticFingerprint === "string" ? { automaticFingerprint: value.automaticFingerprint } : {}),
|
|
38
40
|
signal: execution.signal,
|
|
39
41
|
onCommit: execution.committed,
|
|
42
|
+
noteDebugOutcome: execution.noteDebugOutcome,
|
|
40
43
|
};
|
|
41
44
|
}
|
|
42
45
|
/** Engine dispatch is loaded only by the service, never by the public IPC client. */
|
|
@@ -222,6 +225,10 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
|
|
|
222
225
|
return inspectSync(config, snapshotOptionsForContext(ctx, config), execution.signal, undefined, timings);
|
|
223
226
|
})));
|
|
224
227
|
}
|
|
228
|
+
if (operation === "push.foreground" || operation === "pull.foreground") {
|
|
229
|
+
const direction = operation === "push.foreground" ? "push" : "pull";
|
|
230
|
+
return runForegroundDirectional(host, execution, ctx, direction, payload);
|
|
231
|
+
}
|
|
225
232
|
const supported = [
|
|
226
233
|
"status",
|
|
227
234
|
"diff",
|
|
@@ -248,18 +255,24 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
|
|
|
248
255
|
const { syncSessionsSelected } = await import("./engine/sync/sync-policy.js");
|
|
249
256
|
const config = await loadConfigForCheck(undefined, execution.signal);
|
|
250
257
|
execution.validate();
|
|
251
|
-
if (!config.automatic || !syncSessionsSelected(config))
|
|
258
|
+
if (!config.automatic || !syncSessionsSelected(config)) {
|
|
259
|
+
execution.noteDebugOutcome?.("skipped");
|
|
252
260
|
return;
|
|
261
|
+
}
|
|
253
262
|
}
|
|
254
|
-
if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode))
|
|
263
|
+
if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) {
|
|
264
|
+
execution.noteDebugOutcome?.("blocked");
|
|
255
265
|
throw new Error("Synchronization requires an observable TUI or RPC client.");
|
|
266
|
+
}
|
|
256
267
|
const { withStateDirectoryAccess, migrateLegacyStateDirectory } = await import("./engine/state/state-directory.js");
|
|
257
268
|
if (operation === "migrate-state") {
|
|
258
269
|
if (!options.yes) {
|
|
259
270
|
const accepted = await ctx.ui.confirm("Migrate pi-sync state directory", "Confirm that every older Pi process is closed. Preserve both roots and pending journals on failure.", { signal: execution.signal });
|
|
260
271
|
execution.validate();
|
|
261
|
-
if (!accepted)
|
|
272
|
+
if (!accepted) {
|
|
273
|
+
execution.noteDebugOutcome?.("cancelled");
|
|
262
274
|
return { status: "cancelled", message: "pi-sync state migration cancelled." };
|
|
275
|
+
}
|
|
263
276
|
}
|
|
264
277
|
execution.validate();
|
|
265
278
|
const result = await migrateLegacyStateDirectory();
|
|
@@ -294,8 +307,10 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
|
|
|
294
307
|
}
|
|
295
308
|
if (operation === "startup-transfer") {
|
|
296
309
|
const { startupTransferEnabled } = await import("./engine/sync/agent-policy.js");
|
|
297
|
-
if (!automatic || !startupTransferEnabled(automatic.config) || !ctx.isIdle())
|
|
310
|
+
if (!automatic || !startupTransferEnabled(automatic.config) || !ctx.isIdle()) {
|
|
311
|
+
execution.noteDebugOutcome?.("blocked");
|
|
298
312
|
throw new Error("Startup transfer is no longer authorized or idle.");
|
|
313
|
+
}
|
|
299
314
|
options.auto = true;
|
|
300
315
|
options.yes = true;
|
|
301
316
|
options.silent = true;
|
|
@@ -310,6 +325,7 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
|
|
|
310
325
|
automatic?.validate(config);
|
|
311
326
|
execution.validate();
|
|
312
327
|
if (config.agentMode && !automaticPolicyAuthorized(root, config)) {
|
|
328
|
+
execution.noteDebugOutcome?.("blocked");
|
|
313
329
|
throw new Error("Autonomous sync requires a separate policy review. Use Settings → Review automatic transfers, or choose a reviewed push or pull.");
|
|
314
330
|
}
|
|
315
331
|
if (operation === "sync" && !options.agentRetryRefusal)
|
|
@@ -360,8 +376,10 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
|
|
|
360
376
|
execution.participants().some((peer) => peer.ready !== true) ||
|
|
361
377
|
inspection.firstSync ||
|
|
362
378
|
!inspection.head ||
|
|
363
|
-
inspection.selectionState?.kind !== "same")
|
|
379
|
+
inspection.selectionState?.kind !== "same") {
|
|
380
|
+
execution.noteDebugOutcome?.("blocked");
|
|
364
381
|
throw new Error("Startup transfer requires a fresh initialized baseline, matching selection, and idle ready clients; use the reviewed foreground command.");
|
|
382
|
+
}
|
|
365
383
|
}
|
|
366
384
|
return operations.syncBoth(ctx, current);
|
|
367
385
|
});
|
|
@@ -371,9 +389,12 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
|
|
|
371
389
|
}
|
|
372
390
|
};
|
|
373
391
|
return operation === "startup-transfer"
|
|
374
|
-
? withJobTimings(ctx, execution, "daemon transfer", (timings) => {
|
|
392
|
+
? withJobTimings(ctx, execution, "daemon transfer", async (timings) => {
|
|
375
393
|
options.startupTimings = timings;
|
|
376
|
-
|
|
394
|
+
const result = await run();
|
|
395
|
+
if (timings.wasUnchanged())
|
|
396
|
+
execution.noteDebugOutcome?.("skipped");
|
|
397
|
+
return result;
|
|
377
398
|
})
|
|
378
399
|
: run();
|
|
379
400
|
}
|
|
@@ -388,15 +409,87 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
|
|
|
388
409
|
execute,
|
|
389
410
|
bind: monitor.bind,
|
|
390
411
|
hooks: {
|
|
412
|
+
diagnostic: createDaemonDebug(root),
|
|
413
|
+
startup: {
|
|
414
|
+
captureReviewLock: captureStartupReviewLock,
|
|
415
|
+
async probe(fingerprint, signal, reviewLock) {
|
|
416
|
+
const { captureStartupBootstrap } = await import("./engine/sync/startup-bootstrap.js");
|
|
417
|
+
return captureStartupBootstrap(root, fingerprint, signal, reviewLock);
|
|
418
|
+
},
|
|
419
|
+
},
|
|
391
420
|
factsChanged: monitor.factsChanged,
|
|
392
421
|
idle: monitor.schedule,
|
|
393
422
|
close: monitor.close,
|
|
394
|
-
lifetime: monitor.lifetime,
|
|
423
|
+
lifetime: () => (host.cleanupRequired() ? Promise.resolve("pause") : monitor.lifetime()),
|
|
395
424
|
quiesce: monitor.pause,
|
|
396
425
|
failure: monitor.blockAutomatic,
|
|
426
|
+
foregroundRecoveryAllowed: monitor.foregroundRecoveryAllowed,
|
|
397
427
|
},
|
|
398
428
|
};
|
|
399
429
|
}
|
|
430
|
+
async function runForegroundDirectional(host, execution, ctx, direction, payload) {
|
|
431
|
+
const fingerprintPattern = /^[a-f0-9]{64}$/u;
|
|
432
|
+
if (!execution.clientId ||
|
|
433
|
+
!ctx.hasUI ||
|
|
434
|
+
!["tui", "rpc"].includes(ctx.mode) ||
|
|
435
|
+
!record(payload) ||
|
|
436
|
+
Object.keys(payload).some((key) => !["setup", "fingerprint", "retryCheckpoint"].includes(key)) ||
|
|
437
|
+
typeof payload.setup !== "string" ||
|
|
438
|
+
!payload.setup ||
|
|
439
|
+
payload.setup.length > 512 ||
|
|
440
|
+
typeof payload.fingerprint !== "string" ||
|
|
441
|
+
!fingerprintPattern.test(payload.fingerprint) ||
|
|
442
|
+
(payload.retryCheckpoint !== undefined &&
|
|
443
|
+
(typeof payload.retryCheckpoint !== "string" || !fingerprintPattern.test(payload.retryCheckpoint)))) {
|
|
444
|
+
throw new Error("Invalid foreground directional request.");
|
|
445
|
+
}
|
|
446
|
+
const { setup, fingerprint, retryCheckpoint } = payload;
|
|
447
|
+
const { withStateDirectoryAccess } = await import("./engine/state/state-directory.js");
|
|
448
|
+
const { withLock } = await import("./engine/state/lock.js");
|
|
449
|
+
const { loadConfigForCheck, syncCheckConfigFingerprint } = await import("./engine/settings/config.js");
|
|
450
|
+
const operations = await import("./engine/sync/sync-operations.js");
|
|
451
|
+
const validate = (config) => {
|
|
452
|
+
execution.validate();
|
|
453
|
+
if (config.setupName !== setup || syncCheckConfigFingerprint(config) !== fingerprint)
|
|
454
|
+
throw new Error("The sync setup changed after the action was selected. No transfer was started for the changed setup.");
|
|
455
|
+
};
|
|
456
|
+
execution.validate();
|
|
457
|
+
return withStateDirectoryAccess(async () => {
|
|
458
|
+
validate(await loadConfigForCheck(undefined, execution.signal));
|
|
459
|
+
if (retryCheckpoint === undefined) {
|
|
460
|
+
await requireHandover(execution);
|
|
461
|
+
validate(await loadConfigForCheck(undefined, execution.signal));
|
|
462
|
+
await initialize(ctx, execution, false);
|
|
463
|
+
}
|
|
464
|
+
else {
|
|
465
|
+
if (!readConsent(execution.root))
|
|
466
|
+
throw new Error("Daemon handover is no longer valid; the transfer was not replayed.");
|
|
467
|
+
await requireStartupRecoveryCleared(execution);
|
|
468
|
+
}
|
|
469
|
+
return host.runForeground(execution, () => withLock(direction, async () => {
|
|
470
|
+
validate(await loadConfigForCheck(undefined, execution.signal));
|
|
471
|
+
let message;
|
|
472
|
+
const outcome = await operations[direction](ctx, {
|
|
473
|
+
...optionsFrom({ setup, args: [] }, execution, false),
|
|
474
|
+
directionalAction: {
|
|
475
|
+
validate,
|
|
476
|
+
async checkpoint(current) {
|
|
477
|
+
execution.validate();
|
|
478
|
+
if (retryCheckpoint !== undefined && retryCheckpoint !== current)
|
|
479
|
+
throw new Error("The transfer source or destination changed during recovery. The transfer was not replayed.");
|
|
480
|
+
if ((await execution.request("directional-checkpoint", { fingerprint: current })) !== true)
|
|
481
|
+
throw new Error("The original transfer could not be retained for recovery. No transfer was started.");
|
|
482
|
+
execution.validate();
|
|
483
|
+
},
|
|
484
|
+
notifySuccess(value) {
|
|
485
|
+
message = value;
|
|
486
|
+
},
|
|
487
|
+
},
|
|
488
|
+
});
|
|
489
|
+
return { outcome, ...(message === undefined ? {} : { message }) };
|
|
490
|
+
}));
|
|
491
|
+
});
|
|
492
|
+
}
|
|
400
493
|
async function withJobTimings(ctx, execution, label, action) {
|
|
401
494
|
const { createStartupTimings } = await import("./engine/sync/startup-timings.js");
|
|
402
495
|
const timings = createStartupTimings((_ctx, report) => execution.emit("timings", { report }));
|
|
@@ -407,9 +500,17 @@ async function withJobTimings(ctx, execution, label, action) {
|
|
|
407
500
|
return result;
|
|
408
501
|
}
|
|
409
502
|
finally {
|
|
410
|
-
timings.publish(ctx, execution.facts()?.startupDebug ?? false, execution.signal, label, completed ? "completed" : "stopped");
|
|
503
|
+
timings.publish(ctx, execution.facts()?.startupDebug ?? false, execution.signal, label, completed ? "completed" : "stopped", timingObserver(execution));
|
|
411
504
|
}
|
|
412
505
|
}
|
|
506
|
+
async function requireStartupRecoveryCleared(execution) {
|
|
507
|
+
const { pendingTransactionEntries } = await import("./engine/snapshot/snapshot-transaction-directory.js");
|
|
508
|
+
execution.validate();
|
|
509
|
+
const pending = await pendingTransactionEntries();
|
|
510
|
+
execution.validate();
|
|
511
|
+
if (pending.length)
|
|
512
|
+
throw new Error("Pi Sync startup cannot confirm recovery is clear. Preserve recovery files and check /sync doctor before retrying.");
|
|
513
|
+
}
|
|
413
514
|
async function initialize(ctx, execution, diagnostics = true) {
|
|
414
515
|
const { pendingTransactionEntries } = await import("./engine/snapshot/snapshot-transaction-directory.js");
|
|
415
516
|
const pending = await pendingTransactionEntries();
|
|
@@ -430,12 +531,23 @@ async function initialize(ctx, execution, diagnostics = true) {
|
|
|
430
531
|
execution.validate();
|
|
431
532
|
const settings = document ? validateSettingsDocument(document.parsed) : undefined;
|
|
432
533
|
const config = settings?.activeSyncSetup ? configFromSettings(settings) : undefined;
|
|
534
|
+
if (diagnostics)
|
|
535
|
+
await requireStartupRecoveryCleared(execution);
|
|
536
|
+
execution.noteDebugOutcome?.("blocked");
|
|
433
537
|
return { debug: settings?.debug ?? false, settings, config, handoverRequired: true };
|
|
434
538
|
}
|
|
435
539
|
const { initializeSync } = await import("./engine/sync/initialization.js");
|
|
436
540
|
const initialized = await initializeSync(ctx, execution.signal, (_ctx, report) => {
|
|
437
541
|
if (diagnostics)
|
|
438
542
|
execution.emit("timings", { report });
|
|
439
|
-
});
|
|
543
|
+
}, diagnostics ? timingObserver(execution) : undefined);
|
|
544
|
+
execution.validate();
|
|
545
|
+
if (diagnostics)
|
|
546
|
+
await requireStartupRecoveryCleared(execution);
|
|
547
|
+
execution.validate();
|
|
440
548
|
return { ...initialized, handoverRequired: !readConsent(execution.root) };
|
|
441
549
|
}
|
|
550
|
+
function timingObserver(execution) {
|
|
551
|
+
const debug = execution.debug;
|
|
552
|
+
return debug ? (report) => debug({ event: "startup-timings", report }) : undefined;
|
|
553
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export function isForegroundDirection(operation) {
|
|
2
|
+
return operation === "push.foreground" || operation === "pull.foreground";
|
|
3
|
+
}
|
|
4
|
+
export function isForegroundQueueOutcome(value) {
|
|
5
|
+
if (!value || typeof value !== "object" || !("foregroundQueueCleanup" in value))
|
|
6
|
+
return false;
|
|
7
|
+
return (value.foregroundQueueCleanup === "before-mutation" ||
|
|
8
|
+
(value.foregroundQueueCleanup === "verified-result" && Object.hasOwn(value, "result")));
|
|
9
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { lstatSync, realpathSync } from "node:fs";
|
|
2
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs";
|
|
3
3
|
import fs from "node:fs/promises";
|
|
4
4
|
import os from "node:os";
|
|
5
5
|
import path from "node:path";
|
|
@@ -84,13 +84,15 @@ export async function readUpgradeOwner(paths) {
|
|
|
84
84
|
const value = await readPrivateRecord(upgradeFile(paths));
|
|
85
85
|
if (value === undefined)
|
|
86
86
|
return;
|
|
87
|
-
if (!validOwner(value, paths.root) ||
|
|
87
|
+
if (!validOwner(value, paths.root) ||
|
|
88
|
+
(value.birth !== undefined && !validBirth(value.birth)) ||
|
|
89
|
+
(value.purpose !== undefined && value.purpose !== "cleanup"))
|
|
88
90
|
throw new Error("Invalid daemon upgrade record; state retained.");
|
|
89
|
-
const { version, root, instance, pid, birth } = value;
|
|
90
|
-
return
|
|
91
|
+
const { version, root, instance, pid, birth, purpose } = value;
|
|
92
|
+
return { version, root, instance, pid, ...(birth && { birth }), ...(purpose && { purpose }) };
|
|
91
93
|
}
|
|
92
|
-
export function recordUpgradeOwner(paths, { version, root, instance, pid, birth }) {
|
|
93
|
-
return publishPrivateRecord(paths, upgradeFile(paths), { version, root, instance, pid, birth });
|
|
94
|
+
export function recordUpgradeOwner(paths, { version, root, instance, pid, birth, purpose }) {
|
|
95
|
+
return publishPrivateRecord(paths, upgradeFile(paths), { version, root, instance, pid, birth, purpose });
|
|
94
96
|
}
|
|
95
97
|
export function clearUpgradeOwner(paths) {
|
|
96
98
|
return fs.rm(upgradeFile(paths), { force: true });
|
|
@@ -103,6 +105,34 @@ export async function readIdentity(paths) {
|
|
|
103
105
|
throw new Error("Invalid or incompatible daemon identity; state retained.");
|
|
104
106
|
return { ...value, token: value.token };
|
|
105
107
|
}
|
|
108
|
+
export function matchesPublishedIdentity(paths, identity) {
|
|
109
|
+
const expected = Buffer.from(JSON.stringify(identity));
|
|
110
|
+
if (expected.length > 8192)
|
|
111
|
+
return false;
|
|
112
|
+
const before = lstatSync(paths.identity, { bigint: true, throwIfNoEntry: false });
|
|
113
|
+
if (!before?.isFile() ||
|
|
114
|
+
before.size !== BigInt(expected.length) ||
|
|
115
|
+
(process.getuid && before.uid !== BigInt(process.getuid())) ||
|
|
116
|
+
(process.platform !== "win32" && (before.mode & 63n) !== 0n))
|
|
117
|
+
return false;
|
|
118
|
+
const sameFile = (info) => info?.dev === before.dev &&
|
|
119
|
+
info.ino === before.ino &&
|
|
120
|
+
info.size === before.size &&
|
|
121
|
+
info.ctimeNs === before.ctimeNs &&
|
|
122
|
+
info.mtimeNs === before.mtimeNs;
|
|
123
|
+
const fd = openSync(paths.identity, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
124
|
+
try {
|
|
125
|
+
if (!sameFile(fstatSync(fd, { bigint: true })))
|
|
126
|
+
return false;
|
|
127
|
+
const observed = Buffer.alloc(expected.length + 1);
|
|
128
|
+
return (readSync(fd, observed) === expected.length &&
|
|
129
|
+
observed.subarray(0, expected.length).equals(expected) &&
|
|
130
|
+
sameFile(lstatSync(paths.identity, { bigint: true, throwIfNoEntry: false })));
|
|
131
|
+
}
|
|
132
|
+
finally {
|
|
133
|
+
closeSync(fd);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
106
136
|
function validBirth(value) {
|
|
107
137
|
const fields = typeof value === "string" && birthPattern.exec(value);
|
|
108
138
|
return (!!fields &&
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { DaemonConnection, DaemonError, ensureDaemon, findDaemon, requestDaemon, stopDaemon, waitForDaemonExit, } from "./client.js";
|
|
2
|
+
export { inspectDaemonRecovery, stopDaemonForRecovery, } from "./daemon-recovery.js";
|
|
2
3
|
export { documentFingerprint } from "./document.js";
|
|
3
4
|
export { modelSignature } from "./model-signature.js";
|
|
4
|
-
export { MAX_SETTINGS_BYTES, PROTOCOL_VERSION } from "./protocol.js";
|
|
5
|
+
export { MAX_SETTINGS_BYTES, OWNERSHIP_CLEANUP_REQUIRED, PROTOCOL_VERSION } from "./protocol.js";
|