@narumitw/pi-sync 0.70.1 → 0.70.3

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 CHANGED
@@ -1,5 +1,17 @@
1
1
  # @narumitw/pi-sync
2
2
 
3
+ ## 0.70.3
4
+
5
+ ### Patch Changes
6
+
7
+ - 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.
8
+
9
+ ## 0.70.2
10
+
11
+ ### Patch Changes
12
+
13
+ - d114af2: Bundle the daemon that writes the operational `pi-sync-lifecycle.log`. The separate Debug mode log, `pi-sync.log`, is unchanged.
14
+
3
15
  ## 0.70.1
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.
@@ -191,7 +193,7 @@ Turn on **/sync → Settings → Debug mode**, or set the top-level `"debug": tr
191
193
 
192
194
  Both processes append startup timings and selected check and transfer outcomes to the private, local-only `<getAgentDir()>/pi-sync.log` (normally `~/.pi/agent/pi-sync.log`). It uses one JSON record per line; filter by `source` (`pi-sync` or `pi-sync-daemon`). Records omit raw errors, credentials, file contents, and model data. Turning Debug mode Off does not remove the file, and nothing rotates it automatically.
193
195
 
194
- Timing reports still appear in the TUI transcript or as RPC notifications without entering model context. The Pi client does not write debug records in print or JSON mode. The daemon's separate operational `lifecycle.log` is unchanged. See the [Debug mode reference](./skills/configure-pi-sync/references/configuration.md#debug-mode) for safe cleanup, older snapshots, and timing details.
196
+ Timing reports still appear in the TUI transcript or as RPC notifications without entering model context. The Pi client does not write debug records in print or JSON mode. The daemon's separate operational `pi-sync-lifecycle.log` is independent of Debug mode. See the [Debug mode reference](./skills/configure-pi-sync/references/configuration.md#debug-mode) for safe cleanup, older snapshots, and timing details.
195
197
 
196
198
  ### Background startup checks
197
199
 
@@ -1 +1 @@
1
- "f8b913923befa9472a13eb6663c5a8ac9d4aadb5a69499d0b2258135abc1cd38"
1
+ "b913d113d2f4ab4c8a4a4e9e11f72046d9315917a211a38006e8b4b01d7f4c34"
@@ -69,6 +69,7 @@ export async function hello(paths, identity, signal) {
69
69
  buildVersion,
70
70
  buildId,
71
71
  upgradeStop: value.upgradeStop === 1,
72
+ prefixedLifecycleLog: value.prefixedLifecycleLog === true,
72
73
  ignoreFilesRetired: value.ignoreFilesRetired === true,
73
74
  autonomousSyncRetired: value.autonomousSyncRetired === true,
74
75
  needsUpgrade: buildVersion === undefined || lt(buildVersion, DAEMON_BUILD_VERSION),
@@ -3,6 +3,7 @@ import { gt } from "semver";
3
3
  import { DAEMON_BUILD_ID, DAEMON_BUILD_VERSION } from "./build-version.js";
4
4
  import { hello } from "./client-transport.js";
5
5
  import { processExited, readIdentity, readUpgradeOwner, runtimePaths } from "./identity.js";
6
+ import { LIFECYCLE_LOG_FILENAME } from "./lifecycle-log.js";
6
7
  import { PROTOCOL_VERSION } from "./protocol.js";
7
8
  export async function inspectDaemonStatus(root, signal) {
8
9
  signal?.throwIfAborted();
@@ -35,7 +36,7 @@ export async function inspectDaemonStatus(root, signal) {
35
36
  ...(build.buildId && { buildId: build.buildId }),
36
37
  buildComparison: compareBuild(build),
37
38
  ...(build.upgradeStop && { guardedUpgrade: true }),
38
- lifecycleLog: path.join(paths.directory, "lifecycle.log"),
39
+ lifecycleLog: path.join(paths.directory, build.prefixedLifecycleLog ? LIFECYCLE_LOG_FILENAME : "lifecycle.log"),
39
40
  };
40
41
  }
41
42
  catch {
@@ -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
- if (options.scope === "agent-directory")
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 retireRemovalIntent(transaction.directory, transaction.journal, transaction.journal.entries.filter((entry) => entry.removalPending && (entry.afterImage !== "missing" || (entry.postFiles?.length ?? 0) > 0)), options);
150
- // Only this uninterrupted call knows which deleted writes have not attempted installation yet.
151
- const uninstalledWrites = new Set(transaction.deletedWrites);
152
- for (const item of writes) {
153
- options.signal?.throwIfAborted();
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
- await fs.rename(temp, item.target);
192
- await syncDirectory(path.dirname(item.target));
193
- }
194
- finally {
195
- await fs.rm(temp, { force: true });
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 fs.mkdir(path.dirname(entry.target), { recursive: true });
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 retireRestorationIntent(directory, journal, entry, options);
548
- const { value: atInstall } = await verifyTarget(directory, entry, journal, options, atRename === "missing");
549
- options.validateMutation?.();
550
- options.signal?.throwIfAborted();
551
- if (atInstall === before && (await spellingMatches()))
552
- return;
553
- options.validateMutation?.();
554
- options.signal?.throwIfAborted();
555
- await fs.rename(temporary, entry.target);
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 fs.mkdir(path.dirname(entry.target), { recursive: true });
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 retireRestorationIntent(directory, journal, entry, options);
597
- const { value: atInstall } = await verifyTarget(directory, entry, journal, options, atRename === "missing");
598
- options.validateMutation?.();
599
- options.signal?.throwIfAborted();
600
- if (atInstall === before)
601
- return;
602
- options.validateMutation?.();
603
- options.signal?.throwIfAborted();
604
- await fs.rename(temporary, entry.target);
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 fs.mkdir(path.dirname(entry.target), { recursive: true });
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
- if ((await scopedPathIdentity(stage.payload, options)) !== stage.identity)
671
- throw new Error("Staged recovery image changed before restoration; preserve evidence for review.");
672
- const atInstall = await verifyTarget(directory, entry, journal, options);
673
- if (atInstall.value === before && (await spellingMatches()))
674
- return;
675
- if (atInstall.value !== atRename)
676
- throw new Error("Transaction target changed before restoration; preserve evidence for review.");
677
- options.validateMutation?.();
678
- options.signal?.throwIfAborted();
679
- await fs.rename(stage.payload, entry.target);
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 verified = await verifyTarget(directory, entry, journal, options);
738
- options.validateMutation?.();
739
- options.signal?.throwIfAborted();
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
- await fs.rm(entry.target, { recursive: true, force: true });
752
- }
753
- await syncDirectory(path.dirname(entry.target));
754
- return true;
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
- let kind = await revalidateTarget(target);
438
- try {
439
- const stat = await fs.lstat(target);
440
- await validate();
441
- kind = stat.isDirectory() ? "directory" : "file";
442
- if (checkApplyImage)
443
- await requireReviewedApplyImage();
444
- if (kind === "directory")
445
- await fs.rmdir(target); // Only an empty, reviewed directory may be replaced.
446
- else if (kind === "file")
447
- await fs.rm(target, { force: true });
448
- }
449
- catch (error) {
450
- if (error.code !== "ENOENT")
451
- throw error;
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 fs.mkdir(path.dirname(item.target), { recursive: true });
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 revalidateTarget(item.target);
514
- await fs.rename(temporary, item.target);
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 { createServiceContext, installServiceHost } from "./service-host.js";
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(createServiceContext(execution), payload, execution);
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 = createServiceContext(execution);
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("Unsafe daemon identity file.");
163
- handle = await fs.open(file, "r");
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("Daemon identity changed while opening.");
167
- return JSON.parse(await handle.readFile("utf8"));
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";
@@ -1,5 +1,6 @@
1
1
  import { closeSync, constants, fstatSync, ftruncateSync, lstatSync, openSync, writeSync } from "node:fs";
2
2
  import path from "node:path";
3
+ export const LIFECYCLE_LOG_FILENAME = "pi-sync-lifecycle.log";
3
4
  const MAX_BYTES = 8192;
4
5
  /** Bounded lifecycle facts only: never log payloads, credentials, provider output, or exception text. */
5
6
  export function openLifecycleLog(directory) {
@@ -7,7 +8,7 @@ export function openLifecycleLog(directory) {
7
8
  const privateOwner = (value) => (!process.getuid || value.uid === process.getuid()) && (process.platform === "win32" || (value.mode & 0o077) === 0);
8
9
  if (!parent.isDirectory() || parent.isSymbolicLink() || !privateOwner(parent))
9
10
  throw new Error("Unsafe lifecycle log directory.");
10
- const target = path.join(directory, "lifecycle.log");
11
+ const target = path.join(directory, LIFECYCLE_LOG_FILENAME);
11
12
  const handle = openSync(target, constants.O_CREAT | constants.O_APPEND | constants.O_RDWR | (constants.O_NOFOLLOW ?? 0), 0o600);
12
13
  let closed = false;
13
14
  const validate = () => {
@@ -747,6 +747,7 @@ export async function startServer(root, execute, hooks = {}) {
747
747
  buildVersion: DAEMON_BUILD_VERSION,
748
748
  ...(DAEMON_BUILD_ID && { buildId: DAEMON_BUILD_ID }),
749
749
  upgradeStop: 1,
750
+ prefixedLifecycleLog: true,
750
751
  root: identity.root,
751
752
  instance: identity.instance,
752
753
  pid: identity.pid,