@narumitw/pi-sync 0.63.1 → 0.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +86 -10
  3. package/dist/chunks/{chunk-CKUGCBHP.ts → chunk-AYGMIMCV.ts} +2 -2
  4. package/dist/chunks/chunk-AYGMIMCV.ts.map +7 -0
  5. package/dist/chunks/{chunk-27F5W7DX.ts → chunk-DAZZ5BEJ.ts} +3 -1
  6. package/dist/chunks/chunk-DAZZ5BEJ.ts.map +7 -0
  7. package/dist/chunks/{chunk-VQ47JBLF.ts → chunk-FI2F5JBS.ts} +2 -2
  8. package/dist/chunks/{chunk-V76KCWHO.ts → chunk-IOM6E5FW.ts} +4 -4
  9. package/dist/chunks/{chunk-B5F3JLD3.ts → chunk-JQ5BAWW2.ts} +482 -78
  10. package/dist/chunks/chunk-JQ5BAWW2.ts.map +7 -0
  11. package/dist/chunks/{chunk-LBNC5AOM.ts → chunk-OBVJTKVY.ts} +12 -12
  12. package/dist/chunks/{chunk-EXDWEFIJ.ts → chunk-OWEOZZZE.ts} +6 -6
  13. package/dist/chunks/{chunk-SXCH4Q5O.ts → chunk-SZJOUVCL.ts} +3 -3
  14. package/dist/chunks/{chunk-HSCAFOT5.ts → chunk-TZMVSTAM.ts} +5 -5
  15. package/dist/chunks/{chunk-POWOMJ7S.ts → chunk-WJQ4TGN5.ts} +58 -31
  16. package/dist/chunks/chunk-WJQ4TGN5.ts.map +7 -0
  17. package/dist/chunks/{chunk-HLCML3OW.ts → chunk-XUZV4OGI.ts} +5 -3
  18. package/dist/chunks/chunk-XUZV4OGI.ts.map +7 -0
  19. package/dist/chunks/{command-handler-GMRRFWOL.ts → command-handler-YZ4DXQ7N.ts} +81 -30
  20. package/dist/chunks/command-handler-YZ4DXQ7N.ts.map +7 -0
  21. package/dist/chunks/{conflict-review-JWEA7DPQ.ts → conflict-review-J7L7S4AR.ts} +2 -2
  22. package/dist/chunks/{file-selection-KID23GAD.ts → file-selection-DDQN4LVD.ts} +9 -9
  23. package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts → manager-result-dispatcher-XB75YLEG.ts} +5 -5
  24. package/dist/chunks/{manager-ui-T5J5WG7T.ts → manager-ui-RGA26Z6G.ts} +103 -83
  25. package/dist/chunks/manager-ui-RGA26Z6G.ts.map +7 -0
  26. package/dist/chunks/{merge-review-OQDXNTJU.ts → merge-review-AAC674C6.ts} +3 -2
  27. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts +59 -0
  28. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts.map +7 -0
  29. package/dist/chunks/{remote-selection-ui-GPITNEBF.ts → remote-selection-ui-WVMET5RI.ts} +4 -4
  30. package/dist/chunks/{setup-switch-L54X5U5I.ts → setup-switch-644T6KHG.ts} +4 -4
  31. package/dist/chunks/{setup-wizard-LL6YMGUR.ts → setup-wizard-YP2KF2WQ.ts} +9 -9
  32. package/dist/chunks/{sync-inspection-SRU6HGGK.ts → sync-inspection-NBBTSMKR.ts} +5 -5
  33. package/dist/chunks/{sync-operations-UGSCONZ7.ts → sync-operations-AIEM2KL2.ts} +2 -2
  34. package/dist/daemon/dist/cli.js +2 -0
  35. package/dist/daemon/dist/client-transport.js +66 -0
  36. package/dist/daemon/dist/client.js +222 -354
  37. package/dist/daemon/dist/consent.js +33 -11
  38. package/dist/daemon/dist/daemon-debug.js +33 -0
  39. package/dist/daemon/dist/daemon-recovery.js +158 -0
  40. package/dist/daemon/dist/daemon-startup.js +257 -0
  41. package/dist/daemon/dist/engine/backends/git/git-backend.js +49 -13
  42. package/dist/daemon/dist/engine/backends/git/git-runner.js +6 -1
  43. package/dist/daemon/dist/engine/backends/git/git-storage.js +5 -9
  44. package/dist/daemon/dist/engine/backends/publication-encoding.js +19 -0
  45. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +30 -21
  46. package/dist/daemon/dist/engine/backends/sync-backend.js +16 -0
  47. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +34 -32
  48. package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +10 -0
  49. package/dist/daemon/dist/engine/debug-log.js +134 -0
  50. package/dist/daemon/dist/engine/paths.js +7 -1
  51. package/dist/daemon/dist/engine/settings/config-file.js +62 -17
  52. package/dist/daemon/dist/engine/settings/config.js +49 -14
  53. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +30 -8
  54. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +3 -1
  55. package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +32 -0
  56. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +34 -0
  57. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +50 -7
  58. package/dist/daemon/dist/engine/snapshot/snapshot.js +64 -25
  59. package/dist/daemon/dist/engine/state/lock.js +157 -17
  60. package/dist/daemon/dist/engine/sync/continuous-sync.js +35 -11
  61. package/dist/daemon/dist/engine/sync/directional-action.js +124 -0
  62. package/dist/daemon/dist/engine/sync/initialization.js +2 -2
  63. package/dist/daemon/dist/engine/sync/local-fields.js +42 -19
  64. package/dist/daemon/dist/engine/sync/merged-sync.js +13 -10
  65. package/dist/daemon/dist/engine/sync/remote-snapshot.js +21 -4
  66. package/dist/daemon/dist/engine/sync/session-push.js +13 -4
  67. package/dist/daemon/dist/engine/sync/startup-bootstrap.js +105 -0
  68. package/dist/daemon/dist/engine/sync/startup-recovery-evidence.js +37 -0
  69. package/dist/daemon/dist/engine/sync/startup-timings.js +80 -8
  70. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +6 -1
  71. package/dist/daemon/dist/engine/sync/sync-errors.js +20 -0
  72. package/dist/daemon/dist/engine/sync/sync-inspection.js +4 -7
  73. package/dist/daemon/dist/engine/sync/sync-local.js +59 -4
  74. package/dist/daemon/dist/engine/sync/sync-mutations.js +309 -337
  75. package/dist/daemon/dist/engine/sync/sync-policy.js +9 -1
  76. package/dist/daemon/dist/engine/sync/sync-queries.js +2 -1
  77. package/dist/daemon/dist/engine/sync/sync-rollback.js +198 -0
  78. package/dist/daemon/dist/engine/sync/sync-state.js +12 -4
  79. package/dist/daemon/dist/engine/sync/transfer-freshness.js +11 -5
  80. package/dist/daemon/dist/engine-service.js +122 -10
  81. package/dist/daemon/dist/foreground-queue-outcome.js +9 -0
  82. package/dist/daemon/dist/identity.js +36 -6
  83. package/dist/daemon/dist/index.js +2 -1
  84. package/dist/daemon/dist/monitor.js +21 -1
  85. package/dist/daemon/dist/paged-review.js +177 -0
  86. package/dist/daemon/dist/participant-ledger.js +149 -0
  87. package/dist/daemon/dist/protocol.js +4 -0
  88. package/dist/daemon/dist/server.js +340 -127
  89. package/dist/daemon/dist/service-host.js +83 -15
  90. package/dist/daemon/dist/state-wait-jobs.js +23 -0
  91. package/dist/daemon/dist/state-wait.js +34 -0
  92. package/dist/daemon/package.json +1 -1
  93. package/dist/index.ts +128 -48
  94. package/dist/index.ts.map +2 -2
  95. package/docs/continuous-sync-verification.md +2 -0
  96. package/docs/daemon-migration.md +31 -6
  97. package/docs/tui-contract.md +7 -1
  98. package/package.json +2 -2
  99. package/skills/configure-pi-sync/references/configuration.md +23 -13
  100. package/src/commands/command-execution.ts +67 -5
  101. package/src/commands/command-handler.ts +12 -3
  102. package/src/commands/command.ts +4 -2
  103. package/src/daemon/client-debug.ts +45 -0
  104. package/src/daemon/directional-recovery.ts +103 -0
  105. package/src/daemon/ownership-recovery.ts +50 -0
  106. package/src/daemon/pi-client.ts +399 -71
  107. package/src/daemon/startup-bootstrap-client.ts +26 -0
  108. package/src/settings/config.ts +1 -0
  109. package/src/sync/automatic-sync.ts +61 -18
  110. package/src/sync/startup-check.ts +13 -5
  111. package/src/sync-extension.ts +46 -8
  112. package/src/ui/cancellable-operation.ts +5 -2
  113. package/src/ui/manager-state.ts +31 -23
  114. package/src/ui/manager-ui.ts +45 -25
  115. package/src/ui/merge-review.ts +53 -18
  116. package/src/ui/settings-ui.ts +2 -2
  117. package/src/ui/sync-confirmation.ts +14 -17
  118. package/src/ui/sync-setups-ui.ts +15 -12
  119. package/dist/chunks/chunk-27F5W7DX.ts.map +0 -7
  120. package/dist/chunks/chunk-B5F3JLD3.ts.map +0 -7
  121. package/dist/chunks/chunk-CKUGCBHP.ts.map +0 -7
  122. package/dist/chunks/chunk-HLCML3OW.ts.map +0 -7
  123. package/dist/chunks/chunk-POWOMJ7S.ts.map +0 -7
  124. package/dist/chunks/command-handler-GMRRFWOL.ts.map +0 -7
  125. package/dist/chunks/manager-ui-T5J5WG7T.ts.map +0 -7
  126. /package/dist/chunks/{chunk-VQ47JBLF.ts.map → chunk-FI2F5JBS.ts.map} +0 -0
  127. /package/dist/chunks/{chunk-V76KCWHO.ts.map → chunk-IOM6E5FW.ts.map} +0 -0
  128. /package/dist/chunks/{chunk-LBNC5AOM.ts.map → chunk-OBVJTKVY.ts.map} +0 -0
  129. /package/dist/chunks/{chunk-EXDWEFIJ.ts.map → chunk-OWEOZZZE.ts.map} +0 -0
  130. /package/dist/chunks/{chunk-SXCH4Q5O.ts.map → chunk-SZJOUVCL.ts.map} +0 -0
  131. /package/dist/chunks/{chunk-HSCAFOT5.ts.map → chunk-TZMVSTAM.ts.map} +0 -0
  132. /package/dist/chunks/{conflict-review-JWEA7DPQ.ts.map → conflict-review-J7L7S4AR.ts.map} +0 -0
  133. /package/dist/chunks/{file-selection-KID23GAD.ts.map → file-selection-DDQN4LVD.ts.map} +0 -0
  134. /package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts.map → manager-result-dispatcher-XB75YLEG.ts.map} +0 -0
  135. /package/dist/chunks/{merge-review-OQDXNTJU.ts.map → merge-review-AAC674C6.ts.map} +0 -0
  136. /package/dist/chunks/{remote-selection-ui-GPITNEBF.ts.map → remote-selection-ui-WVMET5RI.ts.map} +0 -0
  137. /package/dist/chunks/{setup-switch-L54X5U5I.ts.map → setup-switch-644T6KHG.ts.map} +0 -0
  138. /package/dist/chunks/{setup-wizard-LL6YMGUR.ts.map → setup-wizard-YP2KF2WQ.ts.map} +0 -0
  139. /package/dist/chunks/{sync-inspection-SRU6HGGK.ts.map → sync-inspection-NBBTSMKR.ts.map} +0 -0
  140. /package/dist/chunks/{sync-operations-UGSCONZ7.ts.map → sync-operations-AIEM2KL2.ts.map} +0 -0
@@ -9,15 +9,15 @@ import { normalizeSyncExclude } from "../sync/exclude-policy.js";
9
9
  import { mergePathIdentity } from "../sync/file-merge-planner.js";
10
10
  import { includeFromSelectionConfig, selectionForSnapshot } from "../sync/sync-policy.js";
11
11
  import { agentDir, configuredSessionDir } from "./session-paths.js";
12
- import { agentDirectoryConfiguredSessionDir } from "./snapshot.js";
12
+ import { agentDirectoryConfiguredSessionDir, scanAgentDirectoryInventory } from "./snapshot.js";
13
13
  import { caseReplacementSpelling, coalesceCaseReplacements } from "./snapshot-case-replacement.js";
14
- import { recheckAgentDirectoryBudget } from "./snapshot-entry-projection.js";
14
+ import { assertProjectedAgentDirectoryBudget, recheckAgentDirectoryBudget } from "./snapshot-entry-projection.js";
15
15
  import { assertUnexcludedTargets } from "./snapshot-exclude-safety.js";
16
16
  import { withMissingTargetQueues, withTargetQueues } from "./snapshot-mutation-queues.js";
17
17
  import { sessionStorageRoot } from "./snapshot-paths.js";
18
18
  import { prepareSessionRootTransition, resolveTransitionSessionRoot, stableAgentDirectorySettingsImage, } from "./snapshot-root-transition.js";
19
19
  import { pendingTransactionEntries, transactionRoot } from "./snapshot-transaction-directory.js";
20
- import { legacyImage, MAX_TRANSACTION_JOURNAL_BYTES, ownedScopedPostTree, readTransactionJournal, recheckScopedImage, removeScopedImage, scopedDescendant, scopedIdentity, scopedPathIdentity, scopedTransactionImage, stableScopedIdentity, } from "./snapshot-transaction-images.js";
20
+ import { legacyImage, MAX_TRANSACTION_JOURNAL_BYTES, ownedScopedPostTree, readTransactionJournal, recheckScopedImage, recheckUnchangedFile, removeScopedImage, scopedDescendant, scopedIdentity, scopedPathIdentity, scopedTransactionImage, stableScopedIdentity, verifyUnchangedFile, } from "./snapshot-transaction-images.js";
21
21
  import { indexTransactionPlan } from "./snapshot-transaction-plan.js";
22
22
  import { AGENT_DIRECTORY_JOURNAL_VERSION, assertAllowedTarget, assertRecoveryPolicy, assertSafeParents, BOUND_DIRECTORY_JOURNAL_VERSION, BOUND_INCLUDED_PATHS_JOURNAL_VERSION, IGNORE_POLICY_JOURNAL_VERSION, ignorePolicyValidator, ignoreSourceBinding, isScopedJournal, isStrictlyInside, recoveryPolicyKey, StaleIgnorePolicyError, touchesProtectedTarget, transactionHasSessionTargets, validateJournal, validateJournalPolicy, } from "./snapshot-transaction-policy.js";
23
23
  import { assertNoUnclaimedLegacyStage, buildScopedRecoveryStage, cleanScopedLegacyStage, cleanScopedWorkspace, inspectScopedRecoveryStage, prepareLegacyRecoveryStage, recoveryStagePath, } from "./snapshot-transaction-stage.js";
@@ -25,7 +25,7 @@ import { verifyTarget } from "./snapshot-transaction-verification.js";
25
25
  const JOURNAL_VERSION = 4;
26
26
  class ScopedRemovalError extends Error {
27
27
  }
28
- export async function applySnapshotTransaction(plan, options = {}) {
28
+ export async function applySnapshotTransaction(plan, options = {}, skipped = []) {
29
29
  options.validateMutation?.();
30
30
  const root = path.resolve(agentDir());
31
31
  if (options.scope === "agent-directory") {
@@ -90,7 +90,10 @@ export async function applySnapshotTransaction(plan, options = {}) {
90
90
  expectedPreimages.set(target, evidence.image);
91
91
  }
92
92
  }
93
+ const skippedPreimages = new Map(skipped.map(({ target, preimage }) => [target, preimage]));
93
94
  for (const [target, expected] of expectedPreimages) {
95
+ if (skippedPreimages.get(target) === expected)
96
+ continue;
94
97
  if (scoped || options.reservedIgnoreNames?.length)
95
98
  await assertUnexcludedTargets(root, [target], options);
96
99
  const current = scoped ? (await scopedTransactionImage(target, options)).value : await legacyImage(target);
@@ -101,7 +104,29 @@ export async function applySnapshotTransaction(plan, options = {}) {
101
104
  }
102
105
  if (validateIgnorePolicy)
103
106
  await validateIgnorePolicy();
104
- const transaction = await prepareTransaction(coalesced.plan, targets, { ...options, expectedPreimages }, coalesced.replacements);
107
+ const mutationTargets = skipped.length ? targets.filter((target) => !skippedPreimages.has(target)) : targets;
108
+ const writes = skipped.length ? plan.writes.filter(({ target }) => !skippedPreimages.has(target)) : plan.writes;
109
+ if (mutationTargets.length === 0) {
110
+ if (options.validateApplyReview)
111
+ await options.validateApplyReview();
112
+ if (scoped) {
113
+ const pendingStateEntry = stateDir(root);
114
+ const inventory = await scanAgentDirectoryInventory(root, options, pendingStateEntry);
115
+ options.validateMutation?.();
116
+ options.signal?.throwIfAborted();
117
+ assertProjectedAgentDirectoryBudget(inventory, { deletes: [], writes: [{ target: pendingStateEntry }] }, options);
118
+ }
119
+ if (validateIgnorePolicy)
120
+ await validateIgnorePolicy();
121
+ await verifySkippedWrites(root, skipped, heldKeys, options);
122
+ options.validateMutation?.();
123
+ options.signal?.throwIfAborted();
124
+ return;
125
+ }
126
+ const mutationPlan = skipped.length
127
+ ? { ...coalesced.plan, writes: coalesced.plan.writes.filter(({ target }) => !skippedPreimages.has(target)) }
128
+ : coalesced.plan;
129
+ const transaction = await prepareTransaction(mutationPlan, mutationTargets, { ...options, expectedPreimages }, coalesced.replacements);
105
130
  const entriesByTarget = new Map(transaction.journal.entries.flatMap((entry) => [
106
131
  [entry.target, entry],
107
132
  ...(entry.afterTarget ? [[entry.afterTarget, entry]] : []),
@@ -135,7 +160,7 @@ export async function applySnapshotTransaction(plan, options = {}) {
135
160
  await retireRemovalIntent(transaction.directory, transaction.journal, transaction.journal.entries.filter((entry) => entry.removalPending && (entry.afterImage !== "missing" || (entry.postFiles?.length ?? 0) > 0)), options);
136
161
  // Only this uninterrupted call knows which deleted writes have not attempted installation yet.
137
162
  const uninstalledWrites = new Set(transaction.deletedWrites);
138
- for (const item of plan.writes) {
163
+ for (const item of writes) {
139
164
  options.signal?.throwIfAborted();
140
165
  const entry = entriesByTarget.get(item.target);
141
166
  if (!entry)
@@ -194,7 +219,7 @@ export async function applySnapshotTransaction(plan, options = {}) {
194
219
  }
195
220
  options.validateMutation?.();
196
221
  options.signal?.throwIfAborted();
197
- await syncMutationParents(targets, [transaction.journal.root, ...(transaction.journal.sessionRoot ? [transaction.journal.sessionRoot] : [])], options);
222
+ await syncMutationParents(mutationTargets, [transaction.journal.root, ...(transaction.journal.sessionRoot ? [transaction.journal.sessionRoot] : [])], options);
198
223
  options.validateMutation?.();
199
224
  options.signal?.throwIfAborted();
200
225
  if (validateIgnorePolicy)
@@ -202,6 +227,9 @@ export async function applySnapshotTransaction(plan, options = {}) {
202
227
  });
203
228
  if (validateIgnorePolicy)
204
229
  await validateIgnorePolicy();
230
+ await verifySkippedWrites(root, skipped, heldKeys, options);
231
+ options.validateMutation?.();
232
+ options.signal?.throwIfAborted();
205
233
  }
206
234
  catch (error) {
207
235
  // Aborted owners cannot roll back files after another session has replaced them.
@@ -226,6 +254,21 @@ export async function applySnapshotTransaction(plan, options = {}) {
226
254
  await completeTransaction(transaction.directory, transaction.journal);
227
255
  });
228
256
  }
257
+ async function verifySkippedWrites(root, skipped, heldKeys, options) {
258
+ if (!skipped.length)
259
+ return;
260
+ await assertUnexcludedTargets(root, skipped.map(({ target }) => target), options, { recursive: false });
261
+ const sessionRoot = options.sessionDir ? sessionStorageRoot(root, options.sessionDir) : undefined;
262
+ const verified = [];
263
+ for (const { target, content } of skipped) {
264
+ if (!heldKeys.has(target) || touchesProtectedTarget(target, options.protectedTargets))
265
+ throw new Error("Skipped file lost its transaction queue or session protection changed; review is required.");
266
+ await assertSafeParents(root, sessionRoot, target);
267
+ verified.push({ target, stat: await verifyUnchangedFile(target, content, options) });
268
+ }
269
+ for (const { target, stat } of verified)
270
+ await recheckUnchangedFile(target, stat, options);
271
+ }
229
272
  export async function recoverSnapshotTransactionsOnStartup(options = {}) {
230
273
  if (!(await pendingTransactionEntries()).some((entry) => entry.isDirectory()))
231
274
  return;
@@ -71,7 +71,11 @@ export function regenerateSnapshotIdentity(snapshot) {
71
71
  machine: os.hostname(),
72
72
  };
73
73
  }
74
- export async function createSnapshot(profile, options = {}) {
74
+ const SCAN_FILE_BATCH_SIZE = 8;
75
+ function materializeSnapshotFile(filePath, content) {
76
+ return { path: filePath, contentBase64: content.toString("base64"), sha256: sha256(content) };
77
+ }
78
+ async function collectSnapshotFiles(options, materialize) {
75
79
  options.signal?.throwIfAborted();
76
80
  const include = effectiveInclude(options);
77
81
  const policy = { ...options, include };
@@ -83,8 +87,39 @@ export async function createSnapshot(profile, options = {}) {
83
87
  : (options.sessionDir ?? (needsSessionConfig ? await configuredSessionDir(options) : undefined));
84
88
  options.signal?.throwIfAborted();
85
89
  const collectionOptions = { ...policy, sessionDir };
86
- const collected = options.scope === "agent-directory" ? await collectAgentDirectory(agentDir(), collectionOptions) : undefined;
87
- const files = collected?.files ?? (await collectFiles(agentDir(), collectionOptions, excluded));
90
+ const collected = options.scope === "agent-directory"
91
+ ? await collectAgentDirectory(agentDir(), collectionOptions, materialize)
92
+ : undefined;
93
+ const files = collected?.files ?? (await collectSelectedFiles(agentDir(), collectionOptions, excluded, materialize));
94
+ options.signal?.throwIfAborted();
95
+ return { files, inventory: collected?.inventory, include, syncSessions };
96
+ }
97
+ export async function observeSnapshot(options = {}, retainSettings = false) {
98
+ const { files, inventory } = await collectSnapshotFiles(options, (filePath, content) => ({
99
+ path: filePath,
100
+ sha256: sha256(content),
101
+ ...(retainSettings && filePath === "settings.json" ? { settingsContent: content } : {}),
102
+ }));
103
+ options.signal?.throwIfAborted();
104
+ const observation = { files, scope: options.scope };
105
+ if (inventory)
106
+ scanInventories.set(observation, inventory);
107
+ return observation;
108
+ }
109
+ export function snapshotWithObservedInventory(snapshot, observation) {
110
+ if (snapshot.selection?.scope !== observation.scope ||
111
+ snapshot.files.length !== observation.files.length ||
112
+ observation.files.some((file, index) => file.path !== snapshot.files[index]?.path || file.sha256 !== snapshot.files[index]?.sha256))
113
+ return undefined;
114
+ const inventory = scanInventories.get(observation);
115
+ if (!inventory)
116
+ return observation.scope === undefined ? snapshot : undefined;
117
+ const refreshed = { ...snapshot };
118
+ scanInventories.set(refreshed, inventory);
119
+ return refreshed;
120
+ }
121
+ export async function createSnapshot(profile, options = {}) {
122
+ const { files, inventory, include, syncSessions } = await collectSnapshotFiles(options, materializeSnapshotFile);
88
123
  options.signal?.throwIfAborted();
89
124
  const selection = selectionForSnapshot(include, options.exclude, options);
90
125
  const snapshot = {
@@ -103,8 +138,8 @@ export async function createSnapshot(profile, options = {}) {
103
138
  selection,
104
139
  files,
105
140
  };
106
- if (collected)
107
- scanInventories.set(snapshot, collected.inventory);
141
+ if (inventory)
142
+ scanInventories.set(snapshot, inventory);
108
143
  return snapshot;
109
144
  }
110
145
  function effectiveInclude(options) {
@@ -120,10 +155,13 @@ function effectiveInclude(options) {
120
155
  }
121
156
  export async function collectFiles(root, options = {}, excluded = compileSyncPolicyExclude(options)) {
122
157
  if (options.scope === "agent-directory")
123
- return (await collectAgentDirectory(root, options)).files;
158
+ return (await collectAgentDirectory(root, options, materializeSnapshotFile)).files;
159
+ return collectSelectedFiles(root, options, excluded, materializeSnapshotFile);
160
+ }
161
+ async function collectSelectedFiles(root, options, excluded, materialize) {
124
162
  const signal = options.signal;
125
163
  const guardReserved = reservedIgnoreTargetGuard(root, options);
126
- const collection = { signal, excluded, guardReserved };
164
+ const collection = { signal, excluded, guardReserved, materialize };
127
165
  signal?.throwIfAborted();
128
166
  const results = [];
129
167
  const entries = await fs.readdir(root, { withFileTypes: true });
@@ -189,6 +227,16 @@ async function recheck({ absolute, canonical, stat }, signal) {
189
227
  if (!sameScannedPath((await identify(absolute, canonical, signal)).stat, stat))
190
228
  changedScan();
191
229
  }
230
+ async function forEachScannedFile(files, signal, run) {
231
+ for (let offset = 0; offset < files.length; offset += SCAN_FILE_BATCH_SIZE) {
232
+ signal?.throwIfAborted();
233
+ const settled = await Promise.allSettled(files.slice(offset, offset + SCAN_FILE_BATCH_SIZE).map((file, index) => run(file, index + offset)));
234
+ signal?.throwIfAborted();
235
+ for (const result of settled)
236
+ if (result.status === "rejected")
237
+ throw result.reason;
238
+ }
239
+ }
192
240
  async function readScannedFile(candidate, signal) {
193
241
  await recheck(candidate, signal);
194
242
  const handle = await fs.open(candidate.absolute, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
@@ -254,9 +302,9 @@ export function agentDirectorySessionDirFromSettings(content) {
254
302
  return value ? expandSessionDir(value) : undefined;
255
303
  }
256
304
  export async function scanAgentDirectoryInventory(root, options, pendingStateEntry) {
257
- return (await collectAgentDirectory(root, options, false, pendingStateEntry)).inventory;
305
+ return (await collectAgentDirectory(root, options, undefined, pendingStateEntry)).inventory;
258
306
  }
259
- async function collectAgentDirectory(root, options, readContents = true, pendingStateEntry) {
307
+ async function collectAgentDirectory(root, options, materialize, pendingStateEntry) {
260
308
  const signal = options.signal;
261
309
  const excluded = compileSyncPolicyExclude(options);
262
310
  const canTraverse = compileSyncPolicyTraversal(options);
@@ -347,15 +395,11 @@ async function collectAgentDirectory(root, options, readContents = true, pending
347
395
  await walk(sessionDirectory, "sessions", true);
348
396
  assertAgentDirectoryPathLayout(candidates.map((candidate) => candidate.snapshotPath));
349
397
  const results = [];
350
- if (readContents) {
351
- for (const candidate of candidates) {
398
+ if (materialize) {
399
+ await forEachScannedFile(candidates, signal, async (candidate, index) => {
352
400
  const content = await readScannedFile(candidate, signal);
353
- results.push({
354
- path: candidate.snapshotPath,
355
- contentBase64: content.toString("base64"),
356
- sha256: sha256(content),
357
- });
358
- }
401
+ results[index] = materialize(candidate.snapshotPath, content);
402
+ });
359
403
  }
360
404
  for (const directory of directories)
361
405
  await recheck(directory, signal);
@@ -369,8 +413,7 @@ async function collectAgentDirectory(root, options, readContents = true, pending
369
413
  (sessionDirectory.stat.dev !== currentSessionDirectory.stat.dev ||
370
414
  sessionDirectory.stat.ino !== currentSessionDirectory.stat.ino)))
371
415
  changedScan();
372
- for (const candidate of candidates)
373
- await recheck(candidate, signal);
416
+ await forEachScannedFile(candidates, signal, (candidate) => recheck(candidate, signal));
374
417
  signal?.throwIfAborted();
375
418
  return {
376
419
  files: results.sort((left, right) => left.path.localeCompare(right.path)),
@@ -439,18 +482,14 @@ export async function readLegacySnapshotSource(absolutePath, guardReserved, sign
439
482
  changedScan();
440
483
  return readScannedFile(candidate, signal);
441
484
  }
442
- async function addFile(results, root, relativePath, snapshotPath, { signal, guardReserved }) {
485
+ async function addFile(results, root, relativePath, snapshotPath, { signal, guardReserved, materialize }) {
443
486
  signal?.throwIfAborted();
444
487
  if (!isSafeSnapshotPath(snapshotPath))
445
488
  return;
446
489
  const absolutePath = safeJoin(root, relativePath);
447
490
  const content = await readLegacySnapshotSource(absolutePath, guardReserved, signal);
448
491
  signal?.throwIfAborted();
449
- results.push({
450
- path: snapshotPath,
451
- contentBase64: content.toString("base64"),
452
- sha256: sha256(content),
453
- });
492
+ results.push(materialize(snapshotPath, content));
454
493
  }
455
494
  export function isSessionPath(relativePath) {
456
495
  return toPosix(relativePath).startsWith("sessions/");
@@ -1,14 +1,80 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
1
2
  import { randomUUID } from "node:crypto";
3
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs";
2
4
  import fs from "node:fs/promises";
5
+ import path from "node:path";
3
6
  import lockfile from "proper-lockfile";
7
+ import { canonicalRootGuard } from "../../identity.js";
8
+ import { getEngineRoot } from "../host.js";
4
9
  import { throwIfAborted } from "../sync/signals.js";
5
10
  import { LOCK_GUARD_STALE_MS, LOCK_GUARD_UPDATE_MS } from "./lock-policy.js";
6
11
  import { LOCKFILE_FS_ADAPTER } from "./lockfile-fs.js";
12
+ import { stateDir } from "./state-directory.js";
7
13
  import { ensureStateDir, lockPath } from "./sync-state-store.js";
8
14
  const LOCK_STALE_MS = 30 * 60 * 1000;
9
15
  const MAX_PROCESS_ID = 2_147_483_647;
16
+ const activeLock = new AsyncLocalStorage();
17
+ export function captureStartupReviewLock() {
18
+ const owner = activeLock.getStore();
19
+ if (!owner?.active())
20
+ return;
21
+ const guardPath = `${owner.path}.guard`;
22
+ const originalGuard = lstatSync(guardPath, { bigint: true, throwIfNoEntry: false });
23
+ const originalLock = lstatSync(owner.path, { bigint: true, throwIfNoEntry: false });
24
+ if (!originalGuard?.isDirectory() || !originalLock?.isFile())
25
+ return;
26
+ const validate = () => {
27
+ if (!owner.active() || owner.path !== lockPath())
28
+ return false;
29
+ const guard = lstatSync(guardPath, { bigint: true, throwIfNoEntry: false });
30
+ const candidate = lstatSync(owner.path, { bigint: true, throwIfNoEntry: false });
31
+ if (!guard?.isDirectory() ||
32
+ guard.dev !== originalGuard.dev ||
33
+ guard.ino !== originalGuard.ino ||
34
+ Number(guard.mtimeMs) < Date.now() - LOCK_GUARD_STALE_MS ||
35
+ !candidate?.isFile() ||
36
+ candidate.dev !== originalLock.dev ||
37
+ candidate.ino !== originalLock.ino ||
38
+ candidate.size !== BigInt(owner.contents.length))
39
+ return false;
40
+ const fd = openSync(owner.path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
41
+ try {
42
+ const opened = fstatSync(fd, { bigint: true });
43
+ if (!opened.isFile() || opened.dev !== candidate.dev || opened.ino !== candidate.ino)
44
+ return false;
45
+ const current = Buffer.alloc(owner.contents.length + 1);
46
+ let offset = 0;
47
+ while (offset < current.length) {
48
+ const count = readSync(fd, current, offset, current.length - offset, offset);
49
+ if (!count)
50
+ break;
51
+ offset += count;
52
+ }
53
+ return current.subarray(0, offset).equals(owner.contents);
54
+ }
55
+ finally {
56
+ closeSync(fd);
57
+ }
58
+ };
59
+ return validate() ? validate : undefined;
60
+ }
10
61
  export async function withLock(command, fn, options = {}) {
11
62
  await ensureStateDir();
63
+ const configuredRoot = getEngineRoot();
64
+ const root = realpathSync(configuredRoot);
65
+ const assertRoot = canonicalRootGuard(root);
66
+ const directory = stateDir(root);
67
+ const file = path.join(directory, "lock");
68
+ const original = lstatSync(directory);
69
+ const assertLocation = () => {
70
+ assertRoot();
71
+ if (realpathSync(configuredRoot) !== root || stateDir(root) !== directory)
72
+ throw new Error("Pi Sync operation lock directory changed.");
73
+ const current = lstatSync(directory);
74
+ if (!current.isDirectory() || current.dev !== original.dev || current.ino !== original.ino)
75
+ throw new Error("Pi Sync operation lock directory changed.");
76
+ };
77
+ assertLocation();
12
78
  const lock = {
13
79
  id: randomUUID(),
14
80
  pid: process.pid,
@@ -16,29 +82,34 @@ export async function withLock(command, fn, options = {}) {
16
82
  startedAt: new Date().toISOString(),
17
83
  };
18
84
  let guard;
85
+ let written = false;
19
86
  let result;
20
87
  let failed = false;
21
88
  let failure;
22
89
  try {
23
90
  try {
24
- guard = await acquireGuard();
91
+ guard = await acquireGuard(file, assertLocation);
25
92
  }
26
93
  catch (error) {
27
94
  if (!isLockHeldError(error))
28
95
  throw error;
29
- throw await describeHeldLock();
96
+ assertLocation();
97
+ throw await describeHeldLock(file);
30
98
  }
31
- let inspection = await inspectLock();
99
+ assertLocation();
100
+ let inspection = await inspectLockAt(file);
32
101
  if (inspection.status === "valid" && isStaleLock(inspection.lock)) {
33
102
  if (!options.reclaimStale) {
34
103
  throw new Error(`pi-sync lock is stale (pid ${inspection.lock.pid}). Run /sync unlock --stale, then retry.`);
35
104
  }
36
105
  guard.throwIfCompromised();
37
- const rechecked = await inspectLock();
106
+ const rechecked = await inspectLockAt(file);
38
107
  if (rechecked.status !== "valid" || rechecked.lock.id !== inspection.lock.id || !isStaleLock(rechecked.lock)) {
39
108
  throw new Error("pi-sync lock changed while preparing transaction recovery; retry.");
40
109
  }
41
- await fs.rm(lockPath(), { force: true });
110
+ assertLocation();
111
+ guard.throwIfCompromised();
112
+ await fs.rm(file, { force: true });
42
113
  inspection = { status: "missing" };
43
114
  }
44
115
  if (inspection.status === "valid") {
@@ -47,19 +118,48 @@ export async function withLock(command, fn, options = {}) {
47
118
  if (inspection.status === "unreadable") {
48
119
  throw new Error("pi-sync lock metadata is unreadable. Run /sync unlock --stale after verifying no sync is running.");
49
120
  }
50
- await fs.writeFile(lockPath(), JSON.stringify(lock, null, "\t"), { flag: "wx" });
121
+ assertLocation();
51
122
  guard.throwIfCompromised();
52
- result = await fn();
123
+ const contents = Buffer.from(JSON.stringify(lock, null, "\t"));
124
+ await fs.writeFile(file, contents, { flag: "wx" });
125
+ written = true;
53
126
  guard.throwIfCompromised();
127
+ const held = guard;
128
+ let active = true;
129
+ const ownsLock = () => {
130
+ if (!active || held.isCompromised())
131
+ return false;
132
+ try {
133
+ assertLocation();
134
+ return true;
135
+ }
136
+ catch {
137
+ return false;
138
+ }
139
+ };
140
+ try {
141
+ result = await activeLock.run({ path: file, contents, active: ownsLock }, fn);
142
+ guard.throwIfCompromised();
143
+ }
144
+ finally {
145
+ active = false;
146
+ }
54
147
  }
55
148
  catch (error) {
56
149
  failed = true;
57
150
  failure = error;
58
151
  }
59
152
  try {
60
- const current = await readLock();
61
- if (current?.id === lock.id)
62
- await fs.rm(lockPath(), { force: true });
153
+ if (written && guard) {
154
+ assertLocation();
155
+ guard.throwIfCompromised();
156
+ const current = await inspectLockAt(file);
157
+ if (current.status === "valid" && current.lock.id === lock.id) {
158
+ assertLocation();
159
+ guard.throwIfCompromised();
160
+ await fs.rm(file, { force: true });
161
+ }
162
+ }
63
163
  }
64
164
  catch (error) {
65
165
  if (!failed) {
@@ -79,8 +179,11 @@ export async function withLock(command, fn, options = {}) {
79
179
  return result;
80
180
  }
81
181
  export async function inspectLock() {
182
+ return inspectLockAt(lockPath());
183
+ }
184
+ async function inspectLockAt(file) {
82
185
  try {
83
- const text = await fs.readFile(lockPath(), "utf8");
186
+ const text = await fs.readFile(file, "utf8");
84
187
  if (text.trim().length === 0)
85
188
  return { status: "unreadable" };
86
189
  const parsed = JSON.parse(text);
@@ -209,11 +312,47 @@ async function releaseGuard(guard) {
209
312
  return guard.isCompromised() ? undefined : error;
210
313
  }
211
314
  }
212
- async function acquireGuard() {
315
+ function guardFilesystem(assertLocation) {
316
+ const { mkdir, rmdir, rmdirSync, stat, utimes } = LOCKFILE_FS_ADAPTER;
317
+ function check(callback) {
318
+ try {
319
+ assertLocation();
320
+ return true;
321
+ }
322
+ catch (error) {
323
+ callback(error);
324
+ return false;
325
+ }
326
+ }
327
+ return {
328
+ ...LOCKFILE_FS_ADAPTER,
329
+ mkdir: (file, callback) => {
330
+ if (check(callback))
331
+ mkdir(file, callback);
332
+ },
333
+ rmdir: (...args) => {
334
+ if (check(args[1]))
335
+ rmdir(...args);
336
+ },
337
+ rmdirSync: (...args) => {
338
+ assertLocation();
339
+ return rmdirSync(...args);
340
+ },
341
+ stat: (file, callback) => {
342
+ if (check(callback))
343
+ stat(file, callback);
344
+ },
345
+ utimes: (...args) => {
346
+ if (check(args[3]))
347
+ utimes(...args);
348
+ },
349
+ };
350
+ }
351
+ async function acquireGuard(file = lockPath(), assertLocation) {
213
352
  let compromisedError;
214
- const release = await lockfile.lock(lockPath(), {
215
- fs: LOCKFILE_FS_ADAPTER,
216
- lockfilePath: `${lockPath()}.guard`,
353
+ const release = await lockfile.lock(file, {
354
+ fs: assertLocation ? guardFilesystem(assertLocation) : LOCKFILE_FS_ADAPTER,
355
+ lockfilePath: `${file}.guard`,
217
356
  realpath: false,
218
357
  stale: LOCK_GUARD_STALE_MS,
219
358
  update: LOCK_GUARD_UPDATE_MS,
@@ -230,8 +369,9 @@ async function acquireGuard() {
230
369
  isCompromised: () => compromisedError !== undefined,
231
370
  };
232
371
  }
233
- async function describeHeldLock() {
234
- const current = await readLock();
372
+ async function describeHeldLock(file = lockPath()) {
373
+ const inspection = await inspectLockAt(file);
374
+ const current = inspection.status === "valid" ? inspection.lock : undefined;
235
375
  if (current && isStaleLock(current)) {
236
376
  return new Error("pi-sync lock owner exited; retry shortly while the lock guard expires.");
237
377
  }