@narumitw/pi-sync 0.70.2 → 0.70.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +2 -0
- package/dist/daemon/dist/build-id.json +1 -1
- package/dist/daemon/dist/engine/host.js +4 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +2 -9
- package/dist/daemon/dist/engine/snapshot/snapshot-mutation-queues.js +20 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +104 -92
- package/dist/daemon/dist/engine/sync/merge-apply.js +25 -21
- package/dist/daemon/dist/engine-service.js +3 -3
- package/dist/daemon/dist/identity.js +12 -8
- package/dist/daemon/dist/index.js +1 -0
- package/dist/daemon/dist/service-host.js +20 -2
- package/dist/daemon/dist/session-presence.js +207 -0
- package/dist/daemon/package.json +1 -1
- package/dist/index.ts +72 -4
- package/dist/index.ts.map +4 -4
- package/docs/daemon-migration.md +5 -1
- package/package.json +6 -6
- package/src/daemon/session-presence.ts +56 -0
- package/src/sync-extension.ts +26 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @narumitw/pi-sync
|
|
2
2
|
|
|
3
|
+
## 0.70.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 2c80989: Update the pinned Pi SDK to 1.7.0 in the embedded and standalone Sync daemon.
|
|
8
|
+
|
|
9
|
+
## 0.70.3
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 75838c3: Protect the open session of a Pi that starts before sync is configured or before the daemon runs. The daemon checks these private registrations before local writes, including forced pulls and recovery. Both the Pi Sync client and the running daemon must include this change.
|
|
14
|
+
|
|
3
15
|
## 0.70.2
|
|
4
16
|
|
|
5
17
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -48,6 +48,8 @@ Pi loads `dist/index.ts` from the package directory, so build Kit and complete t
|
|
|
48
48
|
|
|
49
49
|
Extensions run with Pi's permissions, so install only packages from sources you trust.
|
|
50
50
|
|
|
51
|
+
Once Pi Sync finishes starting, it protects the open session file even if sync is not configured or the daemon is not yet running. Pull and rollback do not overwrite that file, even with `--force`. Close or upgrade older Pi sessions on the same agent directory before a transfer; older versions do not publish this protection. See [write coordination](./docs/daemon-migration.md#write-coordination-and-disconnection).
|
|
52
|
+
|
|
51
53
|
Update Pi Sync to get a newer bundled daemon; updating the standalone package does not change this copy. Revoke retained unattended permission before updating, then start Pi or use `/reload`. An older daemon that supports guarded upgrades is replaced only when no sync work is active. If the update is deferred, wait for the work to finish and use `/reload` again. Older builds without this check require a one-time [manual restart](./docs/daemon-migration.md#ownership-and-upgrade). `/sync daemon status` compares the running and expected builds without starting or replacing a daemon.
|
|
52
54
|
|
|
53
55
|
Use a Pi runtime that satisfies this package’s declared peer floor. Installing an extension dependency does not upgrade a separately installed Pi runtime. The declared Kit floor supplies exact scrolling/paginated review and configured-keybinding support.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"
|
|
1
|
+
"b913d113d2f4ab4c8a4a4e9e11f72046d9315917a211a38006e8b4b01d7f4c34"
|
|
@@ -14,3 +14,7 @@ export function getEngineRoot() {
|
|
|
14
14
|
export function withEngineMutationQueue(target, action) {
|
|
15
15
|
return engineHost().mutate(target, action);
|
|
16
16
|
}
|
|
17
|
+
export function withSessionWriteProtection(targets, action) {
|
|
18
|
+
const protect = engineHost().protectSessionWrite;
|
|
19
|
+
return protect && targets.length ? protect(targets, action) : action();
|
|
20
|
+
}
|
|
@@ -2,7 +2,6 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { assertWithinRoot, isDeniedPath, isPathInside, parentPaths, safeJoin, toPosix } from "../paths.js";
|
|
5
|
-
import { syncDirectory } from "../state/json-file.js";
|
|
6
5
|
import { stateDir } from "../state/state-directory.js";
|
|
7
6
|
import { collidingPaths } from "../sync/file-merge-planner.js";
|
|
8
7
|
import { assertSnapshotExcludesDebugLog, compileSyncPolicyExclude, requireLegacyTransferPolicy, } from "../sync/sync-policy.js";
|
|
@@ -322,14 +321,8 @@ async function ensureSafeDirectory(root, directory, deletePaths, options) {
|
|
|
322
321
|
throw new Error(`Snapshot path parent is not a directory: ${current}`);
|
|
323
322
|
}
|
|
324
323
|
}
|
|
325
|
-
else
|
|
326
|
-
|
|
327
|
-
return true;
|
|
328
|
-
await fs.mkdir(current);
|
|
329
|
-
assertMutationCurrent(options);
|
|
330
|
-
await syncDirectory(path.dirname(current));
|
|
331
|
-
assertMutationCurrent(options);
|
|
332
|
-
}
|
|
324
|
+
else
|
|
325
|
+
return true;
|
|
333
326
|
}
|
|
334
327
|
return false;
|
|
335
328
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import fs from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { engineHost, withEngineMutationQueue as withFileMutationQueue } from "../host.js";
|
|
4
|
+
import { syncDirectory } from "../state/json-file.js";
|
|
4
5
|
function assertCurrent(options) {
|
|
5
6
|
options.validateMutation?.();
|
|
6
7
|
options.signal?.throwIfAborted();
|
|
@@ -68,6 +69,25 @@ export async function assertCanonicalMutationTargets(targets, options) {
|
|
|
68
69
|
for (const target of targets)
|
|
69
70
|
await assertCanonicalParent(target, options);
|
|
70
71
|
}
|
|
72
|
+
export async function createMutationParents(target, options) {
|
|
73
|
+
const parent = path.dirname(target);
|
|
74
|
+
if (!(await targetMissing(parent, options)))
|
|
75
|
+
return;
|
|
76
|
+
await assertCanonicalParent(target, options);
|
|
77
|
+
const missing = [];
|
|
78
|
+
for (let directory = parent; await targetMissing(directory, options); directory = path.dirname(directory)) {
|
|
79
|
+
if (directory === path.dirname(directory))
|
|
80
|
+
throw new Error("Snapshot target has no existing ancestor.");
|
|
81
|
+
missing.unshift(directory);
|
|
82
|
+
}
|
|
83
|
+
for (const directory of missing) {
|
|
84
|
+
assertCurrent(options);
|
|
85
|
+
await fs.mkdir(directory);
|
|
86
|
+
assertCurrent(options);
|
|
87
|
+
await syncDirectory(path.dirname(directory));
|
|
88
|
+
assertCurrent(options);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
71
91
|
export async function withTargetQueues(targets, options, action, coordinator = engineHost()) {
|
|
72
92
|
// Check the whole group before reserving any key or changing live files.
|
|
73
93
|
await assertCanonicalMutationTargets(targets, options);
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
|
+
import { withSessionWriteProtection } from "../host.js";
|
|
4
5
|
import { syncDirectory, writeJson } from "../state/json-file.js";
|
|
5
6
|
import { withLock } from "../state/lock.js";
|
|
6
7
|
import { syncMutationParents } from "../state/mutation-directory-sync.js";
|
|
@@ -13,7 +14,7 @@ import { agentDirectoryConfiguredSessionDir, scanAgentDirectoryInventory } from
|
|
|
13
14
|
import { caseReplacementSpelling, coalesceCaseReplacements } from "./snapshot-case-replacement.js";
|
|
14
15
|
import { assertProjectedAgentDirectoryBudget, recheckAgentDirectoryBudget } from "./snapshot-entry-projection.js";
|
|
15
16
|
import { assertUnexcludedTargets } from "./snapshot-exclude-safety.js";
|
|
16
|
-
import { withMissingTargetQueues, withTargetQueues } from "./snapshot-mutation-queues.js";
|
|
17
|
+
import { createMutationParents, withMissingTargetQueues, withTargetQueues } from "./snapshot-mutation-queues.js";
|
|
17
18
|
import { sessionStorageRoot } from "./snapshot-paths.js";
|
|
18
19
|
import { prepareSessionRootTransition, resolveTransitionSessionRoot, stableAgentDirectorySettingsImage, } from "./snapshot-root-transition.js";
|
|
19
20
|
import { pendingTransactionEntries, transactionRoot } from "./snapshot-transaction-directory.js";
|
|
@@ -146,55 +147,55 @@ export async function applySnapshotTransaction(plan, options = {}, skipped = [])
|
|
|
146
147
|
await options.validateApplyReview();
|
|
147
148
|
if (scoped && plan.writes.length)
|
|
148
149
|
await recheckAgentDirectoryBudget(root, { deletes: [], writes: plan.writes }, options);
|
|
149
|
-
await
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
const entry = entriesByTarget.get(item.target);
|
|
155
|
-
if (!entry)
|
|
156
|
-
throw new Error("Unowned transaction target.");
|
|
157
|
-
const deletedByThisCall = uninstalledWrites.delete(entry.target);
|
|
158
|
-
if (options.scope === "agent-directory")
|
|
159
|
-
await assertUnexcludedTargets(transaction.journal.root, [item.target], options);
|
|
160
|
-
await verifyTarget(transaction.directory, entry, transaction.journal, options, deletedByThisCall);
|
|
161
|
-
options.validateMutation?.();
|
|
162
|
-
options.signal?.throwIfAborted();
|
|
163
|
-
await fs.mkdir(path.dirname(item.target), { recursive: true });
|
|
164
|
-
options.validateMutation?.();
|
|
165
|
-
options.signal?.throwIfAborted();
|
|
166
|
-
const temp = path.join(path.dirname(item.target), `.pi-sync.json.${randomUUID()}.apply`);
|
|
167
|
-
try {
|
|
168
|
-
let mode = 0o600;
|
|
169
|
-
try {
|
|
170
|
-
const stat = await fs.lstat(item.target);
|
|
171
|
-
if (stat.isFile())
|
|
172
|
-
mode = stat.mode & 0o777;
|
|
173
|
-
}
|
|
174
|
-
catch (error) {
|
|
175
|
-
if (error.code !== "ENOENT")
|
|
176
|
-
throw error;
|
|
177
|
-
}
|
|
178
|
-
const handle = await fs.open(temp, "wx", mode);
|
|
179
|
-
try {
|
|
180
|
-
await handle.writeFile(item.content);
|
|
181
|
-
await handle.sync();
|
|
182
|
-
}
|
|
183
|
-
finally {
|
|
184
|
-
await handle.close();
|
|
185
|
-
}
|
|
186
|
-
await verifyTarget(transaction.directory, entry, transaction.journal, options, deletedByThisCall);
|
|
150
|
+
await withSessionWriteProtection(writes.map(({ target }) => target), async () => {
|
|
151
|
+
await retireRemovalIntent(transaction.directory, transaction.journal, transaction.journal.entries.filter((entry) => entry.removalPending && (entry.afterImage !== "missing" || (entry.postFiles?.length ?? 0) > 0)), options);
|
|
152
|
+
// Only this uninterrupted call knows which deleted writes have not attempted installation yet.
|
|
153
|
+
const uninstalledWrites = new Set(transaction.deletedWrites);
|
|
154
|
+
for (const item of writes) {
|
|
187
155
|
options.signal?.throwIfAborted();
|
|
156
|
+
const entry = entriesByTarget.get(item.target);
|
|
157
|
+
if (!entry)
|
|
158
|
+
throw new Error("Unowned transaction target.");
|
|
159
|
+
const deletedByThisCall = uninstalledWrites.delete(entry.target);
|
|
160
|
+
if (options.scope === "agent-directory")
|
|
161
|
+
await assertUnexcludedTargets(transaction.journal.root, [item.target], options);
|
|
162
|
+
await verifyTarget(transaction.directory, entry, transaction.journal, options, deletedByThisCall);
|
|
188
163
|
options.validateMutation?.();
|
|
164
|
+
options.signal?.throwIfAborted();
|
|
165
|
+
await createMutationParents(item.target, options);
|
|
189
166
|
options.validateMutation?.();
|
|
190
167
|
options.signal?.throwIfAborted();
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
168
|
+
const temp = path.join(path.dirname(item.target), `.pi-sync.json.${randomUUID()}.apply`);
|
|
169
|
+
try {
|
|
170
|
+
let mode = 0o600;
|
|
171
|
+
try {
|
|
172
|
+
const stat = await fs.lstat(item.target);
|
|
173
|
+
if (stat.isFile())
|
|
174
|
+
mode = stat.mode & 0o777;
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
if (error.code !== "ENOENT")
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
const handle = await fs.open(temp, "wx", mode);
|
|
181
|
+
try {
|
|
182
|
+
await handle.writeFile(item.content);
|
|
183
|
+
await handle.sync();
|
|
184
|
+
}
|
|
185
|
+
finally {
|
|
186
|
+
await handle.close();
|
|
187
|
+
}
|
|
188
|
+
await verifyTarget(transaction.directory, entry, transaction.journal, options, deletedByThisCall);
|
|
189
|
+
options.validateMutation?.();
|
|
190
|
+
options.signal?.throwIfAborted();
|
|
191
|
+
await fs.rename(temp, item.target);
|
|
192
|
+
await syncDirectory(path.dirname(item.target));
|
|
193
|
+
}
|
|
194
|
+
finally {
|
|
195
|
+
await fs.rm(temp, { force: true });
|
|
196
|
+
}
|
|
196
197
|
}
|
|
197
|
-
}
|
|
198
|
+
});
|
|
198
199
|
options.validateMutation?.();
|
|
199
200
|
options.signal?.throwIfAborted();
|
|
200
201
|
await syncMutationParents(mutationTargets, [transaction.journal.root, ...(transaction.journal.sessionRoot ? [transaction.journal.sessionRoot] : [])], options);
|
|
@@ -510,7 +511,7 @@ async function restoreQueuedTransaction(directory, journal, options, heldKeys) {
|
|
|
510
511
|
try {
|
|
511
512
|
options.validateMutation?.();
|
|
512
513
|
options.signal?.throwIfAborted();
|
|
513
|
-
await
|
|
514
|
+
await withSessionWriteProtection([entry.target], () => createMutationParents(entry.target, options));
|
|
514
515
|
await fs.copyFile(path.join(directory, "before", entry.backupName), temporary);
|
|
515
516
|
// Windows requires write access to flush an existing regular file.
|
|
516
517
|
const handle = await fs.open(temporary, process.platform === "win32" ? "r+" : "r");
|
|
@@ -544,15 +545,18 @@ async function restoreQueuedTransaction(directory, journal, options, heldKeys) {
|
|
|
544
545
|
options.signal?.throwIfAborted();
|
|
545
546
|
if (atRename === before && (await spellingMatches()))
|
|
546
547
|
return;
|
|
547
|
-
await
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
548
|
+
await withSessionWriteProtection([entry.target], async () => {
|
|
549
|
+
const { value: atInstall } = await verifyTarget(directory, entry, journal, options, atRename === "missing");
|
|
550
|
+
if (atInstall === before && (await spellingMatches()))
|
|
551
|
+
return;
|
|
552
|
+
await retireRestorationIntent(directory, journal, entry, options);
|
|
553
|
+
const { value: armed } = await verifyTarget(directory, entry, journal, options, atRename === "missing");
|
|
554
|
+
if (armed === before && (await spellingMatches()))
|
|
555
|
+
return;
|
|
556
|
+
options.validateMutation?.();
|
|
557
|
+
options.signal?.throwIfAborted();
|
|
558
|
+
await fs.rename(temporary, entry.target);
|
|
559
|
+
});
|
|
556
560
|
await syncDirectory(path.dirname(entry.target));
|
|
557
561
|
});
|
|
558
562
|
}
|
|
@@ -564,7 +568,7 @@ async function restoreQueuedTransaction(directory, journal, options, heldKeys) {
|
|
|
564
568
|
try {
|
|
565
569
|
options.validateMutation?.();
|
|
566
570
|
options.signal?.throwIfAborted();
|
|
567
|
-
await
|
|
571
|
+
await withSessionWriteProtection([entry.target], () => createMutationParents(entry.target, options));
|
|
568
572
|
await assertSafeParents(journal.root, journal.sessionRoot, entry.target);
|
|
569
573
|
if (entry.kind === "directory") {
|
|
570
574
|
await fs.cp(path.join(directory, "before", entry.backupName), temporary, {
|
|
@@ -593,15 +597,18 @@ async function restoreQueuedTransaction(directory, journal, options, heldKeys) {
|
|
|
593
597
|
options.signal?.throwIfAborted();
|
|
594
598
|
if (atRename === before)
|
|
595
599
|
return;
|
|
596
|
-
await
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
600
|
+
await withSessionWriteProtection([entry.target], async () => {
|
|
601
|
+
const { value: atInstall } = await verifyTarget(directory, entry, journal, options, atRename === "missing");
|
|
602
|
+
if (atInstall === before)
|
|
603
|
+
return;
|
|
604
|
+
await retireRestorationIntent(directory, journal, entry, options);
|
|
605
|
+
const { value: armed } = await verifyTarget(directory, entry, journal, options, atRename === "missing");
|
|
606
|
+
if (armed === before)
|
|
607
|
+
return;
|
|
608
|
+
options.validateMutation?.();
|
|
609
|
+
options.signal?.throwIfAborted();
|
|
610
|
+
await fs.rename(temporary, entry.target);
|
|
611
|
+
});
|
|
605
612
|
await syncDirectory(path.dirname(entry.target));
|
|
606
613
|
});
|
|
607
614
|
}
|
|
@@ -617,7 +624,7 @@ async function restoreQueuedTransaction(directory, journal, options, heldKeys) {
|
|
|
617
624
|
async function restoreScopedEntry(directory, journal, entry, options, heldKeys, before, spellingMatches) {
|
|
618
625
|
options.validateMutation?.();
|
|
619
626
|
options.signal?.throwIfAborted();
|
|
620
|
-
await
|
|
627
|
+
await withSessionWriteProtection([entry.target], () => createMutationParents(entry.target, options));
|
|
621
628
|
await assertSafeParents(journal.root, journal.sessionRoot, entry.target);
|
|
622
629
|
if (!entry.vacantInstall) {
|
|
623
630
|
await buildScopedRecoveryStage(directory, entry, options, () => persistJournal(directory, journal));
|
|
@@ -667,16 +674,18 @@ async function restoreScopedEntry(directory, journal, entry, options, heldKeys,
|
|
|
667
674
|
await persistJournal(directory, journal);
|
|
668
675
|
await verifyStage();
|
|
669
676
|
}
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
677
|
+
await withSessionWriteProtection([entry.target], async () => {
|
|
678
|
+
if ((await scopedPathIdentity(stage.payload, options)) !== stage.identity)
|
|
679
|
+
throw new Error("Staged recovery image changed before restoration; preserve evidence for review.");
|
|
680
|
+
const atInstall = await verifyTarget(directory, entry, journal, options);
|
|
681
|
+
if (atInstall.value === before && (await spellingMatches()))
|
|
682
|
+
return;
|
|
683
|
+
if (atInstall.value !== atRename)
|
|
684
|
+
throw new Error("Transaction target changed before restoration; preserve evidence for review.");
|
|
685
|
+
options.validateMutation?.();
|
|
686
|
+
options.signal?.throwIfAborted();
|
|
687
|
+
await fs.rename(stage.payload, entry.target);
|
|
688
|
+
});
|
|
680
689
|
await syncDirectory(path.dirname(entry.target));
|
|
681
690
|
await syncDirectory(path.dirname(stage.payload));
|
|
682
691
|
if ((await verifyTarget(directory, entry, journal, options)).value !== before)
|
|
@@ -734,24 +743,27 @@ async function removeOwnedTarget(directory, entry, journal, options, { apply, re
|
|
|
734
743
|
options.validateMutation?.();
|
|
735
744
|
options.signal?.throwIfAborted();
|
|
736
745
|
await persistJournal(directory, journal);
|
|
737
|
-
const
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
if (restoringBefore !== undefined && verified.value === restoringBefore)
|
|
741
|
-
return false;
|
|
742
|
-
if (current.scoped) {
|
|
743
|
-
if (current.value !== verified.value)
|
|
744
|
-
throw new Error("Transaction removal image changed.");
|
|
745
|
-
await assertUnexcludedTargets(journal.root, [entry.target], options);
|
|
746
|
-
await removeScopedImage(entry.target, current.scoped, options);
|
|
747
|
-
}
|
|
748
|
-
else {
|
|
746
|
+
const targets = [entry.target, ...(entry.afterTarget ? [entry.afterTarget] : [])];
|
|
747
|
+
return await withSessionWriteProtection(targets, async () => {
|
|
748
|
+
const verified = await verifyTarget(directory, entry, journal, options);
|
|
749
749
|
options.validateMutation?.();
|
|
750
750
|
options.signal?.throwIfAborted();
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
751
|
+
if (restoringBefore !== undefined && verified.value === restoringBefore)
|
|
752
|
+
return false;
|
|
753
|
+
if (current.scoped) {
|
|
754
|
+
if (current.value !== verified.value)
|
|
755
|
+
throw new Error("Transaction removal image changed.");
|
|
756
|
+
await assertUnexcludedTargets(journal.root, [entry.target], options);
|
|
757
|
+
await removeScopedImage(entry.target, current.scoped, options);
|
|
758
|
+
}
|
|
759
|
+
else {
|
|
760
|
+
options.validateMutation?.();
|
|
761
|
+
options.signal?.throwIfAborted();
|
|
762
|
+
await fs.rm(entry.target, { recursive: true, force: true });
|
|
763
|
+
}
|
|
764
|
+
await syncDirectory(path.dirname(entry.target));
|
|
765
|
+
return true;
|
|
766
|
+
});
|
|
755
767
|
}
|
|
756
768
|
catch (error) {
|
|
757
769
|
if (!scoped)
|
|
@@ -2,14 +2,14 @@ import { createHash, randomUUID } from "node:crypto";
|
|
|
2
2
|
import { constants } from "node:fs";
|
|
3
3
|
import fs from "node:fs/promises";
|
|
4
4
|
import path from "node:path";
|
|
5
|
-
import { withEngineMutationQueue as withFileMutationQueue } from "../host.js";
|
|
5
|
+
import { withEngineMutationQueue as withFileMutationQueue, withSessionWriteProtection } from "../host.js";
|
|
6
6
|
import { agentDir } from "../snapshot/session-paths.js";
|
|
7
7
|
import { agentDirectoryConfiguredSessionDir, agentDirectoryInventory, createSnapshot, observeSnapshot, snapshotTarget, } from "../snapshot/snapshot.js";
|
|
8
8
|
import { preflightSnapshotApply, preflightSnapshotMutations } from "../snapshot/snapshot-apply.js";
|
|
9
9
|
import { assertAgentDirectorySnapshotBound, MAX_AGENT_DIRECTORY_BYTES } from "../snapshot/snapshot-bounds.js";
|
|
10
10
|
import { assertProjectedAgentDirectoryBudget, recheckAgentDirectoryBudget, } from "../snapshot/snapshot-entry-projection.js";
|
|
11
11
|
import { assertUnexcludedTargets } from "../snapshot/snapshot-exclude-safety.js";
|
|
12
|
-
import { assertCanonicalMutationTargets } from "../snapshot/snapshot-mutation-queues.js";
|
|
12
|
+
import { assertCanonicalMutationTargets, createMutationParents } from "../snapshot/snapshot-mutation-queues.js";
|
|
13
13
|
import { sessionStorageRoot } from "../snapshot/snapshot-paths.js";
|
|
14
14
|
import { snapshotBase64Size } from "../snapshot/snapshot-payload.js";
|
|
15
15
|
import { syncDirectory } from "../state/json-file.js";
|
|
@@ -434,22 +434,21 @@ export async function applyMergedSnapshot(before, after, protectedPaths, options
|
|
|
434
434
|
if (options.scope === "agent-directory" && plan.deletes.length)
|
|
435
435
|
await recheckAgentDirectoryBudget(root, plan, options);
|
|
436
436
|
for (const target of plan.deletes) {
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
await
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
}
|
|
437
|
+
if (checkApplyImage)
|
|
438
|
+
await requireReviewedApplyImage();
|
|
439
|
+
await withSessionWriteProtection([target], async () => {
|
|
440
|
+
const kind = await revalidateTarget(target);
|
|
441
|
+
try {
|
|
442
|
+
if (kind === "directory")
|
|
443
|
+
await fs.rmdir(target); // Only an empty, reviewed directory may be replaced.
|
|
444
|
+
else if (kind === "file")
|
|
445
|
+
await fs.rm(target, { force: true });
|
|
446
|
+
}
|
|
447
|
+
catch (error) {
|
|
448
|
+
if (error.code !== "ENOENT")
|
|
449
|
+
throw error;
|
|
450
|
+
}
|
|
451
|
+
});
|
|
453
452
|
await syncDirectory(path.dirname(target));
|
|
454
453
|
}
|
|
455
454
|
const requireAbsentDestinations = async () => {
|
|
@@ -491,7 +490,10 @@ export async function applyMergedSnapshot(before, after, protectedPaths, options
|
|
|
491
490
|
await assertFilesystemTarget(root, relative, options, new Set());
|
|
492
491
|
if (checkApplyImage)
|
|
493
492
|
await requireReviewedApplyImage();
|
|
494
|
-
await
|
|
493
|
+
await withSessionWriteProtection([item.target], async () => {
|
|
494
|
+
await validate();
|
|
495
|
+
await createMutationParents(item.target, options);
|
|
496
|
+
});
|
|
495
497
|
const temporary = path.join(path.dirname(item.target), `.pi-sync.json.${randomUUID()}.apply`);
|
|
496
498
|
let mode = 0o600;
|
|
497
499
|
try {
|
|
@@ -510,8 +512,10 @@ export async function applyMergedSnapshot(before, after, protectedPaths, options
|
|
|
510
512
|
finally {
|
|
511
513
|
await handle.close();
|
|
512
514
|
}
|
|
513
|
-
await
|
|
514
|
-
|
|
515
|
+
await withSessionWriteProtection([item.target], async () => {
|
|
516
|
+
await revalidateTarget(item.target);
|
|
517
|
+
await fs.rename(temporary, item.target);
|
|
518
|
+
});
|
|
515
519
|
await syncDirectory(path.dirname(item.target));
|
|
516
520
|
}
|
|
517
521
|
finally {
|
|
@@ -8,7 +8,7 @@ import { captureStartupReviewLock } from "./engine/state/lock.js";
|
|
|
8
8
|
import { isForegroundTransferIntent } from "./foreground-transfer.js";
|
|
9
9
|
import { createLegacyConsentGuard } from "./legacy-consent-guard.js";
|
|
10
10
|
import { MAX_SETTINGS_BYTES, record } from "./protocol.js";
|
|
11
|
-
import {
|
|
11
|
+
import { installServiceHost } from "./service-host.js";
|
|
12
12
|
function optionsFrom(value, execution, automatic) {
|
|
13
13
|
if (!record(value))
|
|
14
14
|
throw new Error("Invalid operation options.");
|
|
@@ -60,7 +60,7 @@ export function createEngineService(root) {
|
|
|
60
60
|
if (operation === "diff.review") {
|
|
61
61
|
const { captureDiffReview } = await import("./engine/sync/diff-review-capture.js");
|
|
62
62
|
execution.validate();
|
|
63
|
-
return captureDiffReview(
|
|
63
|
+
return captureDiffReview(await host.context(execution), payload, execution);
|
|
64
64
|
}
|
|
65
65
|
if (operation === "daemon.authorize") {
|
|
66
66
|
return Boolean(await authorizeAfterExit(execution, payload));
|
|
@@ -125,7 +125,7 @@ export function createEngineService(root) {
|
|
|
125
125
|
execution.committed();
|
|
126
126
|
return saved;
|
|
127
127
|
}
|
|
128
|
-
const ctx =
|
|
128
|
+
const ctx = await host.context(execution);
|
|
129
129
|
if (operation === "initialize")
|
|
130
130
|
return initialize(ctx, execution);
|
|
131
131
|
if (operation === "inspect")
|
|
@@ -133,7 +133,7 @@ export function matchesPublishedIdentity(paths, identity) {
|
|
|
133
133
|
closeSync(fd);
|
|
134
134
|
}
|
|
135
135
|
}
|
|
136
|
-
function validBirth(value) {
|
|
136
|
+
export function validBirth(value) {
|
|
137
137
|
const fields = typeof value === "string" && birthPattern.exec(value);
|
|
138
138
|
return (!!fields &&
|
|
139
139
|
Number(fields[1]) <= 0xffff_ffff &&
|
|
@@ -150,7 +150,7 @@ function validOwner(value, root) {
|
|
|
150
150
|
Number(value.pid) >= 1 &&
|
|
151
151
|
Number(value.pid) <= 2_147_483_647);
|
|
152
152
|
}
|
|
153
|
-
async function readPrivateRecord(file) {
|
|
153
|
+
export async function readPrivateRecord(file, description = "daemon identity") {
|
|
154
154
|
let handle;
|
|
155
155
|
try {
|
|
156
156
|
const before = await fs.lstat(file);
|
|
@@ -159,12 +159,16 @@ async function readPrivateRecord(file) {
|
|
|
159
159
|
before.size > 8192 ||
|
|
160
160
|
(process.getuid && before.uid !== process.getuid()) ||
|
|
161
161
|
(process.platform !== "win32" && (before.mode & 0o077) !== 0))
|
|
162
|
-
throw new Error(
|
|
163
|
-
handle = await fs.open(file,
|
|
162
|
+
throw new Error(`Unsafe ${description} file.`);
|
|
163
|
+
handle = await fs.open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
164
164
|
const opened = await handle.stat();
|
|
165
|
-
if (before.dev !== opened.dev || before.ino !== opened.ino)
|
|
166
|
-
throw new Error(
|
|
167
|
-
|
|
165
|
+
if (before.dev !== opened.dev || before.ino !== opened.ino || before.size !== opened.size)
|
|
166
|
+
throw new Error(`The ${description} changed while opening.`);
|
|
167
|
+
const bytes = Buffer.alloc(8193);
|
|
168
|
+
const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
|
|
169
|
+
if (bytesRead !== before.size)
|
|
170
|
+
throw new Error(`The ${description} changed while reading.`);
|
|
171
|
+
return JSON.parse(bytes.toString("utf8", 0, bytesRead));
|
|
168
172
|
}
|
|
169
173
|
catch (error) {
|
|
170
174
|
if (error.code === "ENOENT")
|
|
@@ -244,7 +248,7 @@ export async function processExited({ pid, birth }) {
|
|
|
244
248
|
export function publishIdentity(paths, identity) {
|
|
245
249
|
return publishPrivateRecord(paths, paths.identity, identity);
|
|
246
250
|
}
|
|
247
|
-
async function publishPrivateRecord(paths, file, value) {
|
|
251
|
+
export async function publishPrivateRecord(paths, file, value) {
|
|
248
252
|
const temporary = path.join(paths.directory, `.${randomUUID()}.json`);
|
|
249
253
|
const handle = await fs.open(temporary, "wx", 0o600);
|
|
250
254
|
try {
|
|
@@ -7,3 +7,4 @@ export { documentFingerprint } from "./document.js";
|
|
|
7
7
|
export { isDestinationConflict } from "./foreground-transfer.js";
|
|
8
8
|
export { modelSignature } from "./model-signature.js";
|
|
9
9
|
export { MAX_SETTINGS_BYTES, OWNERSHIP_CLEANUP_REQUIRED, PROTOCOL_VERSION } from "./protocol.js";
|
|
10
|
+
export { createSessionPresence } from "./session-presence.js";
|
|
@@ -8,6 +8,7 @@ import { configureEngineHost } from "./engine/host.js";
|
|
|
8
8
|
import { canonicalRootGuard, processExists } from "./identity.js";
|
|
9
9
|
import { withCleanup } from "./lifecycle.js";
|
|
10
10
|
import { OWNERSHIP_CLEANUP_REQUIRED } from "./protocol.js";
|
|
11
|
+
import { sessionPathsOverlap, sessionPresenceReader } from "./session-presence.js";
|
|
11
12
|
class OwnershipCleanupError extends Error {
|
|
12
13
|
code = OWNERSHIP_CLEANUP_REQUIRED;
|
|
13
14
|
}
|
|
@@ -16,6 +17,7 @@ const scope = new AsyncLocalStorage();
|
|
|
16
17
|
export function installServiceHost(root) {
|
|
17
18
|
let poisoned;
|
|
18
19
|
const assertRoot = canonicalRootGuard(root);
|
|
20
|
+
const presence = sessionPresenceReader(root);
|
|
19
21
|
function current() {
|
|
20
22
|
const value = scope.getStore();
|
|
21
23
|
if (!value)
|
|
@@ -101,6 +103,14 @@ export function installServiceHost(root) {
|
|
|
101
103
|
return root;
|
|
102
104
|
},
|
|
103
105
|
reserveTargets: reserve,
|
|
106
|
+
protectSessionWrite: (targets, action) => {
|
|
107
|
+
const { execution } = current();
|
|
108
|
+
return presence.protect(targets, action, () => {
|
|
109
|
+
execution.validate();
|
|
110
|
+
if (targets.some((target) => execution.liveClients().some((peer) => peer.sessionFile && sessionPathsOverlap(target, peer.sessionFile))))
|
|
111
|
+
throw new Error("A live client's session is protected, including after orderly exit.");
|
|
112
|
+
});
|
|
113
|
+
},
|
|
104
114
|
mutate: async (target, action) => reserve([target], async () => {
|
|
105
115
|
const owner = current();
|
|
106
116
|
protectedTarget(target, owner.execution);
|
|
@@ -149,6 +159,11 @@ export function installServiceHost(root) {
|
|
|
149
159
|
});
|
|
150
160
|
return {
|
|
151
161
|
cleanupRequired: () => poisoned !== undefined,
|
|
162
|
+
async context(execution) {
|
|
163
|
+
const files = await presence.files();
|
|
164
|
+
execution.validate();
|
|
165
|
+
return createServiceContext(execution, files);
|
|
166
|
+
},
|
|
152
167
|
async runForeground(execution, action) {
|
|
153
168
|
const owner = current();
|
|
154
169
|
if (owner.execution !== execution || !execution.clientId || owner.held.size || owner.foreground)
|
|
@@ -192,7 +207,7 @@ export function installServiceHost(root) {
|
|
|
192
207
|
},
|
|
193
208
|
};
|
|
194
209
|
}
|
|
195
|
-
export function createServiceContext(execution) {
|
|
210
|
+
export function createServiceContext(execution, presenceFiles = []) {
|
|
196
211
|
const initial = execution.facts();
|
|
197
212
|
if (!initial)
|
|
198
213
|
throw new Error("This operation needs an attached client.");
|
|
@@ -221,7 +236,10 @@ export function createServiceContext(execution) {
|
|
|
221
236
|
usesDefaultSessionDir: () => facts().sessionDir === undefined,
|
|
222
237
|
},
|
|
223
238
|
get protectedSessionFiles() {
|
|
224
|
-
return
|
|
239
|
+
return [
|
|
240
|
+
...presenceFiles,
|
|
241
|
+
...execution.liveClients().flatMap((peer) => (peer.sessionFile ? [peer.sessionFile] : [])),
|
|
242
|
+
];
|
|
225
243
|
},
|
|
226
244
|
isIdle: () => execution.participants().every((peer) => peer.idle),
|
|
227
245
|
reload: async () => {
|