@narumitw/pi-sync 0.64.0 → 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 +10 -0
- package/README.md +76 -7
- package/dist/chunks/{chunk-CKUGCBHP.ts → chunk-AYGMIMCV.ts} +2 -2
- package/dist/chunks/chunk-AYGMIMCV.ts.map +7 -0
- package/dist/chunks/{chunk-F3VODLVQ.ts → chunk-IOM6E5FW.ts} +3 -3
- package/dist/chunks/{chunk-RW44KNFD.ts → chunk-JQ5BAWW2.ts} +182 -12
- package/dist/chunks/chunk-JQ5BAWW2.ts.map +7 -0
- package/dist/chunks/{chunk-NDEZ52SS.ts → chunk-OBVJTKVY.ts} +5 -5
- package/dist/chunks/{chunk-TJ7YNITN.ts → chunk-OWEOZZZE.ts} +2 -2
- package/dist/chunks/{chunk-VPSC7BXM.ts → chunk-SZJOUVCL.ts} +2 -2
- package/dist/chunks/{chunk-YT6PDRMM.ts → chunk-WJQ4TGN5.ts} +17 -17
- package/dist/chunks/chunk-WJQ4TGN5.ts.map +7 -0
- package/dist/chunks/{chunk-4VKWHVUO.ts → chunk-XUZV4OGI.ts} +3 -2
- package/dist/chunks/{chunk-4VKWHVUO.ts.map → chunk-XUZV4OGI.ts.map} +2 -2
- package/dist/chunks/{command-handler-N45GY7AV.ts → command-handler-YZ4DXQ7N.ts} +49 -10
- package/dist/chunks/command-handler-YZ4DXQ7N.ts.map +7 -0
- package/dist/chunks/{conflict-review-5E4M44BA.ts → conflict-review-J7L7S4AR.ts} +2 -2
- package/dist/chunks/{manager-result-dispatcher-FKW55L7I.ts → manager-result-dispatcher-XB75YLEG.ts} +4 -4
- package/dist/chunks/{manager-ui-EV23DPZQ.ts → manager-ui-RGA26Z6G.ts} +40 -38
- package/dist/chunks/manager-ui-RGA26Z6G.ts.map +7 -0
- package/dist/chunks/{merge-review-6YSLSMGS.ts → merge-review-AAC674C6.ts} +3 -3
- package/dist/chunks/{remote-selection-ui-N4NMWFT2.ts → remote-selection-ui-WVMET5RI.ts} +3 -3
- package/dist/chunks/{setup-switch-HY7K3442.ts → setup-switch-644T6KHG.ts} +3 -3
- package/dist/chunks/{setup-wizard-LEKDQ3HK.ts → setup-wizard-YP2KF2WQ.ts} +5 -5
- package/dist/chunks/{sync-inspection-OS2LVOLV.ts → sync-inspection-NBBTSMKR.ts} +2 -2
- package/dist/chunks/{sync-operations-D3MDJUQQ.ts → sync-operations-AIEM2KL2.ts} +2 -2
- package/dist/daemon/dist/client.js +125 -287
- package/dist/daemon/dist/daemon-recovery.js +85 -2
- package/dist/daemon/dist/daemon-startup.js +257 -0
- package/dist/daemon/dist/engine/backends/git/git-backend.js +10 -1
- package/dist/daemon/dist/engine/backends/s3/s3-backend.js +20 -9
- package/dist/daemon/dist/engine/backends/sync-backend.js +16 -0
- package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +19 -6
- package/dist/daemon/dist/engine/sync/directional-action.js +124 -0
- package/dist/daemon/dist/engine/sync/remote-snapshot.js +3 -1
- package/dist/daemon/dist/engine/sync/sync-errors.js +20 -0
- package/dist/daemon/dist/engine/sync/sync-local.js +56 -3
- package/dist/daemon/dist/engine/sync/sync-mutations.js +300 -334
- 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/transfer-freshness.js +11 -5
- package/dist/daemon/dist/engine-service.js +68 -0
- package/dist/daemon/dist/foreground-queue-outcome.js +9 -0
- package/dist/daemon/dist/monitor.js +1 -0
- package/dist/daemon/dist/server.js +76 -11
- package/dist/daemon/dist/service-host.js +56 -8
- package/dist/daemon/package.json +1 -1
- package/dist/index.ts +6 -6
- package/docs/daemon-migration.md +3 -6
- package/package.json +2 -2
- package/src/commands/command-execution.ts +56 -2
- package/src/commands/command-handler.ts +2 -0
- package/src/commands/command.ts +2 -1
- package/src/daemon/directional-recovery.ts +103 -0
- package/src/daemon/pi-client.ts +112 -9
- package/src/ui/cancellable-operation.ts +5 -2
- package/src/ui/manager-state.ts +2 -2
- package/src/ui/manager-ui.ts +29 -24
- package/src/ui/merge-review.ts +8 -9
- package/src/ui/sync-confirmation.ts +7 -7
- package/dist/chunks/chunk-CKUGCBHP.ts.map +0 -7
- package/dist/chunks/chunk-RW44KNFD.ts.map +0 -7
- package/dist/chunks/chunk-YT6PDRMM.ts.map +0 -7
- package/dist/chunks/command-handler-N45GY7AV.ts.map +0 -7
- package/dist/chunks/manager-ui-EV23DPZQ.ts.map +0 -7
- /package/dist/chunks/{chunk-F3VODLVQ.ts.map → chunk-IOM6E5FW.ts.map} +0 -0
- /package/dist/chunks/{chunk-NDEZ52SS.ts.map → chunk-OBVJTKVY.ts.map} +0 -0
- /package/dist/chunks/{chunk-TJ7YNITN.ts.map → chunk-OWEOZZZE.ts.map} +0 -0
- /package/dist/chunks/{chunk-VPSC7BXM.ts.map → chunk-SZJOUVCL.ts.map} +0 -0
- /package/dist/chunks/{conflict-review-5E4M44BA.ts.map → conflict-review-J7L7S4AR.ts.map} +0 -0
- /package/dist/chunks/{manager-result-dispatcher-FKW55L7I.ts.map → manager-result-dispatcher-XB75YLEG.ts.map} +0 -0
- /package/dist/chunks/{merge-review-6YSLSMGS.ts.map → merge-review-AAC674C6.ts.map} +0 -0
- /package/dist/chunks/{remote-selection-ui-N4NMWFT2.ts.map → remote-selection-ui-WVMET5RI.ts.map} +0 -0
- /package/dist/chunks/{setup-switch-HY7K3442.ts.map → setup-switch-644T6KHG.ts.map} +0 -0
- /package/dist/chunks/{setup-wizard-LEKDQ3HK.ts.map → setup-wizard-YP2KF2WQ.ts.map} +0 -0
- /package/dist/chunks/{sync-inspection-OS2LVOLV.ts.map → sync-inspection-NBBTSMKR.ts.map} +0 -0
- /package/dist/chunks/{sync-operations-D3MDJUQQ.ts.map → sync-operations-AIEM2KL2.ts.map} +0 -0
|
@@ -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,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();
|
|
@@ -225,6 +225,10 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
|
|
|
225
225
|
return inspectSync(config, snapshotOptionsForContext(ctx, config), execution.signal, undefined, timings);
|
|
226
226
|
})));
|
|
227
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
|
+
}
|
|
228
232
|
const supported = [
|
|
229
233
|
"status",
|
|
230
234
|
"diff",
|
|
@@ -419,9 +423,73 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
|
|
|
419
423
|
lifetime: () => (host.cleanupRequired() ? Promise.resolve("pause") : monitor.lifetime()),
|
|
420
424
|
quiesce: monitor.pause,
|
|
421
425
|
failure: monitor.blockAutomatic,
|
|
426
|
+
foregroundRecoveryAllowed: monitor.foregroundRecoveryAllowed,
|
|
422
427
|
},
|
|
423
428
|
};
|
|
424
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
|
+
}
|
|
425
493
|
async function withJobTimings(ctx, execution, label, action) {
|
|
426
494
|
const { createStartupTimings } = await import("./engine/sync/startup-timings.js");
|
|
427
495
|
const timings = createStartupTimings((_ctx, report) => execution.emit("timings", { report }));
|
|
@@ -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
|
+
}
|
|
@@ -5,16 +5,18 @@ import fs from "node:fs/promises";
|
|
|
5
5
|
import { createServer } from "node:http";
|
|
6
6
|
import lockfile from "proper-lockfile";
|
|
7
7
|
import { DAEMON_BUILD_VERSION } from "./build-version.js";
|
|
8
|
+
import { ConsentPublicationError, readConsent } from "./consent.js";
|
|
8
9
|
import { endpointOwner } from "./endpoint.js";
|
|
9
10
|
import { debugOperation } from "./engine/debug-log.js";
|
|
10
11
|
import { SyncDecisionRequiredError } from "./engine/sync/sync-errors.js";
|
|
12
|
+
import { isForegroundDirection, isForegroundQueueOutcome } from "./foreground-queue-outcome.js";
|
|
11
13
|
import { canonicalRootGuard, daemonPaths, matchesPublishedIdentity, privateDirectory, processExists, publishIdentity, readIdentity, readJsonBody, readUpgradeOwner, runtimePaths, } from "./identity.js";
|
|
12
14
|
import { createIdleExit } from "./idle-exit.js";
|
|
13
15
|
import { withCleanup } from "./lifecycle.js";
|
|
14
16
|
import { createPagedReviewOffer, reviewScope } from "./paged-review.js";
|
|
15
17
|
import { ParticipantAdmission } from "./participant-admission.js";
|
|
16
18
|
import { createParticipantLedger } from "./participant-ledger.js";
|
|
17
|
-
import { ClientContactExpiredError, DAEMON_JOB_CAPACITY, DaemonStoppingError, MAX_MESSAGE_BYTES, MAX_REVIEW_BYTES, operationPrefix, PROTOCOL_VERSION, REVIEW_PAGE_CHARS, record, remoteError, UNKNOWN_JOB_RESULT, validateFacts, validateHandoff, validId, } from "./protocol.js";
|
|
19
|
+
import { ClientContactExpiredError, DAEMON_JOB_CAPACITY, DaemonStoppingError, MAX_MESSAGE_BYTES, MAX_REVIEW_BYTES, OWNERSHIP_CLEANUP_REQUIRED, operationPrefix, PROTOCOL_VERSION, REVIEW_PAGE_CHARS, record, remoteError, UNKNOWN_JOB_RESULT, validateFacts, validateHandoff, validId, } from "./protocol.js";
|
|
18
20
|
import { ParticipantStateWait } from "./state-wait.js";
|
|
19
21
|
export async function startServer(root, execute, hooks = {}) {
|
|
20
22
|
const base = await runtimePaths(root);
|
|
@@ -81,6 +83,8 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
81
83
|
let participantGeneration = 0;
|
|
82
84
|
let closed = false;
|
|
83
85
|
let stopRequested = false;
|
|
86
|
+
let foregroundRecoveryJob;
|
|
87
|
+
let consentPublicationFailed = false;
|
|
84
88
|
let automaticClosing = false;
|
|
85
89
|
let idleExit;
|
|
86
90
|
let expiring;
|
|
@@ -327,6 +331,12 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
327
331
|
},
|
|
328
332
|
};
|
|
329
333
|
}
|
|
334
|
+
function assertForegroundQueueReady() {
|
|
335
|
+
if (foregroundRecoveryJob)
|
|
336
|
+
throw Object.assign(new Error("File-queue cleanup is pending; no new daemon work can start."), {
|
|
337
|
+
code: OWNERSHIP_CLEANUP_REQUIRED,
|
|
338
|
+
});
|
|
339
|
+
}
|
|
330
340
|
function enqueue(id, client, operation, payload) {
|
|
331
341
|
const peer = requireParticipant(client);
|
|
332
342
|
if (!id.startsWith(operationPrefix(identity)))
|
|
@@ -338,6 +348,7 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
338
348
|
throw new Error("Operation ID was reused with different input.");
|
|
339
349
|
return duplicate;
|
|
340
350
|
}
|
|
351
|
+
assertForegroundQueueReady();
|
|
341
352
|
if (retired.has(id))
|
|
342
353
|
throw new Error("Operation result expired; reconcile the existing journal before starting new work.");
|
|
343
354
|
if (retired.size + jobs.size >= 4096)
|
|
@@ -384,16 +395,26 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
384
395
|
job.promise = queue
|
|
385
396
|
.then(async () => {
|
|
386
397
|
execution.validate();
|
|
398
|
+
assertForegroundQueueReady();
|
|
387
399
|
job.view.phase = "running";
|
|
388
400
|
note("started");
|
|
389
401
|
const result = await execute(operation, payload, execution);
|
|
390
402
|
if (Buffer.byteLength(JSON.stringify(result ?? null)) > MAX_MESSAGE_BYTES / 2)
|
|
391
403
|
throw new Error("Operation result exceeds its byte limit; use bounded inspection.");
|
|
404
|
+
if (isForegroundDirection(operation) && isForegroundQueueOutcome(result)) {
|
|
405
|
+
if (result.foregroundQueueCleanup === "before-mutation" && job.committed)
|
|
406
|
+
throw Object.assign(new Error("File-queue release and transfer outcome could not be verified."), {
|
|
407
|
+
code: OWNERSHIP_CLEANUP_REQUIRED,
|
|
408
|
+
});
|
|
409
|
+
foregroundRecoveryJob ??= job;
|
|
410
|
+
}
|
|
392
411
|
job.view.result = result;
|
|
393
412
|
job.view.phase = "done";
|
|
394
413
|
note(result === "cancelled" ? "cancelled" : (job.debugOutcome ?? "completed"));
|
|
395
414
|
})
|
|
396
415
|
.catch((error) => {
|
|
416
|
+
if (error instanceof ConsentPublicationError)
|
|
417
|
+
consentPublicationFailed = true;
|
|
397
418
|
job.view.phase = "failed";
|
|
398
419
|
job.view.error = remoteError(error);
|
|
399
420
|
note(!job.committed && (job.controller.signal.aborted || (error instanceof Error && error.name === "AbortError"))
|
|
@@ -594,6 +615,52 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
594
615
|
hooks.idle?.();
|
|
595
616
|
return result;
|
|
596
617
|
}
|
|
618
|
+
function stop() {
|
|
619
|
+
stopRequested = true;
|
|
620
|
+
for (const peer of participants.values())
|
|
621
|
+
waiters.get(peer)?.changed();
|
|
622
|
+
setImmediate(() => {
|
|
623
|
+
void close().catch(() => { });
|
|
624
|
+
});
|
|
625
|
+
return { stopping: true };
|
|
626
|
+
}
|
|
627
|
+
async function stopForeground(params, signal) {
|
|
628
|
+
if (params.check !== undefined && params.check !== true)
|
|
629
|
+
throw new Error("Invalid foreground stop request.");
|
|
630
|
+
const barrier = await readUpgradeOwner(paths);
|
|
631
|
+
signal?.throwIfAborted();
|
|
632
|
+
assertOwner();
|
|
633
|
+
if (params.check === true
|
|
634
|
+
? barrier !== undefined
|
|
635
|
+
: barrier?.purpose !== "cleanup" || barrier.instance !== identity.instance || barrier.pid !== identity.pid)
|
|
636
|
+
return { blocked: "A daemon upgrade or recovery is already pending." };
|
|
637
|
+
if (!published || !matchesPublishedIdentity(paths, identity))
|
|
638
|
+
return { blocked: "Daemon owner changed during queue cleanup." };
|
|
639
|
+
const job = foregroundRecoveryJob;
|
|
640
|
+
const requester = validId(params.client) ? participants.get(params.client) : undefined;
|
|
641
|
+
if (job?.view.phase !== "done" ||
|
|
642
|
+
job.view.id !== params.job ||
|
|
643
|
+
!requester ||
|
|
644
|
+
requester.facts.id !== job.client ||
|
|
645
|
+
requester.facts.generation !== params.generation ||
|
|
646
|
+
requester.facts.generation !== job.generation ||
|
|
647
|
+
contactState(requester) !== "active")
|
|
648
|
+
return { blocked: "The completed transfer is not owned by the current Pi session." };
|
|
649
|
+
if (ledger.failed ||
|
|
650
|
+
consentPublicationFailed ||
|
|
651
|
+
hooks.foregroundRecoveryAllowed?.() !== true ||
|
|
652
|
+
Object.values(readConsent(paths.root)?.setups ?? {}).some((setup) => setup.afterExit))
|
|
653
|
+
return { blocked: "Daemon authorization or ownership evidence needs repair before a restart." };
|
|
654
|
+
if (peerOperations.size ||
|
|
655
|
+
expiring ||
|
|
656
|
+
backgroundJobs.size ||
|
|
657
|
+
pending.size ||
|
|
658
|
+
[...jobs.values()].some(({ view }) => view.phase === "queued" || view.phase === "running"))
|
|
659
|
+
return { blocked: "Another daemon operation may still be running; no restart was attempted." };
|
|
660
|
+
if ([...participants.values()].some((peer) => peer !== requester && participates(peer) && processExists(peer.facts.pid)))
|
|
661
|
+
return { blocked: "Another live Pi session still uses this daemon; no restart was attempted." };
|
|
662
|
+
return params.check === true ? { eligible: true } : stop();
|
|
663
|
+
}
|
|
597
664
|
async function handle(method, params, signal, reviewDetails = false) {
|
|
598
665
|
if (automaticClosing && method !== "stop")
|
|
599
666
|
throw new DaemonStoppingError();
|
|
@@ -690,6 +757,8 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
690
757
|
return resumeContact(params, signal);
|
|
691
758
|
}
|
|
692
759
|
if (method === "startup.bootstrap" && hooks.startup) {
|
|
760
|
+
if (foregroundRecoveryJob)
|
|
761
|
+
throw new Error("File-queue cleanup is pending; startup work did not begin.");
|
|
693
762
|
if (!record(params) ||
|
|
694
763
|
Object.keys(params).length !== 4 ||
|
|
695
764
|
!validId(params.client) ||
|
|
@@ -858,15 +927,10 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
858
927
|
await job.promise;
|
|
859
928
|
return job.view;
|
|
860
929
|
}
|
|
861
|
-
if (method === "stop")
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
setImmediate(() => {
|
|
866
|
-
void close().catch(() => { });
|
|
867
|
-
});
|
|
868
|
-
return { stopping: true };
|
|
869
|
-
}
|
|
930
|
+
if (method === "foreground-stop")
|
|
931
|
+
return stopForeground(params, signal);
|
|
932
|
+
if (method === "stop")
|
|
933
|
+
return stop();
|
|
870
934
|
throw new Error("Unknown daemon method.");
|
|
871
935
|
}
|
|
872
936
|
const respond = (response, status, value) => {
|
|
@@ -898,7 +962,7 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
898
962
|
respond(response, 403, { error: { name: "Error", message: "Invalid daemon identity or protocol." } });
|
|
899
963
|
return;
|
|
900
964
|
}
|
|
901
|
-
if (["attach", "resume-contact", "startup.bootstrap", "state-wait"].includes(body.method)) {
|
|
965
|
+
if (["attach", "resume-contact", "startup.bootstrap", "state-wait", "foreground-stop"].includes(body.method)) {
|
|
902
966
|
admissionController = new AbortController();
|
|
903
967
|
response.once("close", disconnect);
|
|
904
968
|
if (response.destroyed)
|
|
@@ -1134,6 +1198,7 @@ export async function startServer(root, execute, hooks = {}) {
|
|
|
1134
1198
|
checkLifetime: () => idleExit?.tick() ?? Promise.resolve(),
|
|
1135
1199
|
isIdle: () => !closed &&
|
|
1136
1200
|
!stopRequested &&
|
|
1201
|
+
!foregroundRecoveryJob &&
|
|
1137
1202
|
[...jobs.values()].every((job) => job.view.phase !== "queued" && job.view.phase !== "running"),
|
|
1138
1203
|
get closed() {
|
|
1139
1204
|
return closed;
|
|
@@ -14,7 +14,7 @@ class OwnershipCleanupError extends Error {
|
|
|
14
14
|
const scope = new AsyncLocalStorage();
|
|
15
15
|
/** One service process owns one root; tests must use a separate process per root. */
|
|
16
16
|
export function installServiceHost(root, ignoreFileOperationsAvailable) {
|
|
17
|
-
let poisoned
|
|
17
|
+
let poisoned;
|
|
18
18
|
const assertRoot = canonicalRootGuard(root);
|
|
19
19
|
function current() {
|
|
20
20
|
const value = scope.getStore();
|
|
@@ -42,17 +42,30 @@ export function installServiceHost(root, ignoreFileOperationsAvailable) {
|
|
|
42
42
|
protectedTarget(target, owner.execution);
|
|
43
43
|
const peers = owner.peers.toSorted((a, b) => a.id.localeCompare(b.id));
|
|
44
44
|
const requested = [];
|
|
45
|
+
const foreground = owner.foreground;
|
|
46
|
+
let acquireFailed = false;
|
|
47
|
+
let completed = false;
|
|
45
48
|
return withCleanup(async () => {
|
|
46
49
|
for (const peer of peers) {
|
|
47
50
|
owner.execution.validate();
|
|
48
51
|
const reservation = randomUUID();
|
|
49
52
|
requested.push({ client: peer.id, reservation });
|
|
50
|
-
|
|
53
|
+
try {
|
|
54
|
+
await owner.execution.request("queue-acquire", { reservation, targets: missing, generation: peer.generation, background: !owner.execution.clientId }, peer.id);
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
acquireFailed = true;
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
51
60
|
owner.execution.validate();
|
|
52
61
|
}
|
|
53
62
|
for (const target of missing)
|
|
54
63
|
protectedTarget(target, owner.execution);
|
|
55
|
-
|
|
64
|
+
if (foreground)
|
|
65
|
+
foreground.entered = true;
|
|
66
|
+
const result = await scope.run({ ...owner, held: new Set([...owner.held, ...missing]) }, action);
|
|
67
|
+
completed = true;
|
|
68
|
+
return result;
|
|
56
69
|
}, async () => {
|
|
57
70
|
// Release by request identity even when a grant response was lost. A cancelled
|
|
58
71
|
// prompt is not evidence that a granted remote writer stopped.
|
|
@@ -65,8 +78,17 @@ export function installServiceHost(root, ignoreFileOperationsAvailable) {
|
|
|
65
78
|
}));
|
|
66
79
|
const failure = results.find((result) => result.status === "rejected");
|
|
67
80
|
if (failure?.status === "rejected") {
|
|
68
|
-
poisoned
|
|
69
|
-
|
|
81
|
+
poisoned ??= "queue";
|
|
82
|
+
const error = new OwnershipCleanupError("File-queue release is uncertain; stop the daemon and keep grants quarantined until owner exit.", { cause: failure.reason });
|
|
83
|
+
if (foreground && poisoned === "queue") {
|
|
84
|
+
if (completed) {
|
|
85
|
+
foreground.deferred = true;
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (acquireFailed && !foreground.entered && !owner.execution.signal.aborted)
|
|
89
|
+
foreground.beforeMutation = error;
|
|
90
|
+
}
|
|
91
|
+
throw error;
|
|
70
92
|
}
|
|
71
93
|
});
|
|
72
94
|
}
|
|
@@ -75,7 +97,7 @@ export function installServiceHost(root, ignoreFileOperationsAvailable) {
|
|
|
75
97
|
allowConfigMigration: () => Boolean(readConsent(root)),
|
|
76
98
|
root: () => {
|
|
77
99
|
assertRoot();
|
|
78
|
-
if (poisoned)
|
|
100
|
+
if (poisoned && !(poisoned === "queue" && scope.getStore()?.foreground?.deferred))
|
|
79
101
|
throw new OwnershipCleanupError("Daemon ownership cleanup is uncertain; stop and reconcile before restarting.");
|
|
80
102
|
return root;
|
|
81
103
|
},
|
|
@@ -110,7 +132,7 @@ export function installServiceHost(root, ignoreFileOperationsAvailable) {
|
|
|
110
132
|
await release?.();
|
|
111
133
|
}
|
|
112
134
|
catch (error) {
|
|
113
|
-
poisoned =
|
|
135
|
+
poisoned = "other";
|
|
114
136
|
throw new OwnershipCleanupError("Pi settings lock release failed; stop and reconcile before restarting.", {
|
|
115
137
|
cause: error,
|
|
116
138
|
});
|
|
@@ -127,7 +149,33 @@ export function installServiceHost(root, ignoreFileOperationsAvailable) {
|
|
|
127
149
|
status: (_ctx, value, presentation) => current().execution.emit("status", { value, presentation }),
|
|
128
150
|
});
|
|
129
151
|
return {
|
|
130
|
-
cleanupRequired: () => poisoned,
|
|
152
|
+
cleanupRequired: () => poisoned !== undefined,
|
|
153
|
+
async runForeground(execution, action) {
|
|
154
|
+
const owner = current();
|
|
155
|
+
if (owner.execution !== execution || !execution.clientId || owner.held.size || owner.foreground)
|
|
156
|
+
throw new Error("Foreground queue recovery requires one attached directional job.");
|
|
157
|
+
const foreground = { entered: false, deferred: false };
|
|
158
|
+
return scope.run({ ...owner, foreground }, async () => {
|
|
159
|
+
try {
|
|
160
|
+
const result = await action();
|
|
161
|
+
if (foreground.deferred && poisoned === "queue")
|
|
162
|
+
return { foregroundQueueCleanup: "verified-result", result };
|
|
163
|
+
return result;
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
if (foreground.beforeMutation &&
|
|
167
|
+
!execution.signal.aborted &&
|
|
168
|
+
error instanceof AggregateError &&
|
|
169
|
+
error.errors.includes(foreground.beforeMutation))
|
|
170
|
+
return { foregroundQueueCleanup: "before-mutation" };
|
|
171
|
+
if (foreground.deferred && !(error instanceof OwnershipCleanupError)) {
|
|
172
|
+
const detail = error instanceof Error ? ` ${error.message}` : "";
|
|
173
|
+
throw new OwnershipCleanupError(`File-queue release was not confirmed.${detail}`, { cause: error });
|
|
174
|
+
}
|
|
175
|
+
throw error;
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
},
|
|
131
179
|
run(execution, action) {
|
|
132
180
|
return scope.run({ execution, held: new Set() }, async () => {
|
|
133
181
|
try {
|