@narumitw/pi-sync-daemon 0.0.0-stage → 0.3.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 (267) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/LICENSE +21 -0
  3. package/README.md +91 -2
  4. package/dist/cli.d.ts +2 -0
  5. package/dist/cli.js +127 -0
  6. package/dist/client.d.ts +57 -0
  7. package/dist/client.js +534 -0
  8. package/dist/consent.d.ts +24 -0
  9. package/dist/consent.js +205 -0
  10. package/dist/document.d.ts +10 -0
  11. package/dist/document.js +6 -0
  12. package/dist/endpoint.d.ts +8 -0
  13. package/dist/endpoint.js +91 -0
  14. package/dist/engine/backends/backend-factory.d.ts +6 -0
  15. package/dist/engine/backends/backend-factory.js +16 -0
  16. package/dist/engine/backends/backend-identity.d.ts +3 -0
  17. package/dist/engine/backends/backend-identity.js +38 -0
  18. package/dist/engine/backends/backend-types.d.ts +70 -0
  19. package/dist/engine/backends/backend-types.js +1 -0
  20. package/dist/engine/backends/git/git-backend.d.ts +55 -0
  21. package/dist/engine/backends/git/git-backend.js +700 -0
  22. package/dist/engine/backends/git/git-config.d.ts +5 -0
  23. package/dist/engine/backends/git/git-config.js +118 -0
  24. package/dist/engine/backends/git/git-runner.d.ts +25 -0
  25. package/dist/engine/backends/git/git-runner.js +232 -0
  26. package/dist/engine/backends/git/git-storage.d.ts +39 -0
  27. package/dist/engine/backends/git/git-storage.js +226 -0
  28. package/dist/engine/backends/s3/s3-backend.d.ts +32 -0
  29. package/dist/engine/backends/s3/s3-backend.js +436 -0
  30. package/dist/engine/backends/s3/s3-client.d.ts +36 -0
  31. package/dist/engine/backends/s3/s3-client.js +352 -0
  32. package/dist/engine/backends/s3/s3-conditions.d.ts +4 -0
  33. package/dist/engine/backends/s3/s3-conditions.js +66 -0
  34. package/dist/engine/backends/snapshot-pointer.d.ts +6 -0
  35. package/dist/engine/backends/snapshot-pointer.js +22 -0
  36. package/dist/engine/backends/sync-backend.d.ts +71 -0
  37. package/dist/engine/backends/sync-backend.js +23 -0
  38. package/dist/engine/backends/webdav/webdav-backend.d.ts +34 -0
  39. package/dist/engine/backends/webdav/webdav-backend.js +534 -0
  40. package/dist/engine/backends/webdav/webdav-client.d.ts +36 -0
  41. package/dist/engine/backends/webdav/webdav-client.js +326 -0
  42. package/dist/engine/backends/webdav/webdav-config.d.ts +5 -0
  43. package/dist/engine/backends/webdav/webdav-config.js +73 -0
  44. package/dist/engine/commands/command-types.d.ts +31 -0
  45. package/dist/engine/commands/command-types.js +1 -0
  46. package/dist/engine/host.d.ts +70 -0
  47. package/dist/engine/host.js +16 -0
  48. package/dist/engine/paths.d.ts +9 -0
  49. package/dist/engine/paths.js +71 -0
  50. package/dist/engine/settings/config-errors.d.ts +1 -0
  51. package/dist/engine/settings/config-errors.js +4 -0
  52. package/dist/engine/settings/config-file.d.ts +33 -0
  53. package/dist/engine/settings/config-file.js +630 -0
  54. package/dist/engine/settings/config.d.ts +24 -0
  55. package/dist/engine/settings/config.js +200 -0
  56. package/dist/engine/settings/settings-management.d.ts +24 -0
  57. package/dist/engine/settings/settings-management.js +191 -0
  58. package/dist/engine/settings/settings-store.d.ts +8 -0
  59. package/dist/engine/settings/settings-store.js +41 -0
  60. package/dist/engine/settings/settings-types.d.ts +134 -0
  61. package/dist/engine/settings/settings-types.js +1 -0
  62. package/dist/engine/settings/settings-validation.d.ts +15 -0
  63. package/dist/engine/settings/settings-validation.js +356 -0
  64. package/dist/engine/snapshot/session-paths.d.ts +12 -0
  65. package/dist/engine/snapshot/session-paths.js +91 -0
  66. package/dist/engine/snapshot/snapshot-apply.d.ts +22 -0
  67. package/dist/engine/snapshot/snapshot-apply.js +262 -0
  68. package/dist/engine/snapshot/snapshot-case-replacement.d.ts +15 -0
  69. package/dist/engine/snapshot/snapshot-case-replacement.js +82 -0
  70. package/dist/engine/snapshot/snapshot-codec.d.ts +6 -0
  71. package/dist/engine/snapshot/snapshot-codec.js +53 -0
  72. package/dist/engine/snapshot/snapshot-exclude-safety.d.ts +7 -0
  73. package/dist/engine/snapshot/snapshot-exclude-safety.js +47 -0
  74. package/dist/engine/snapshot/snapshot-mutation-queues.d.ts +9 -0
  75. package/dist/engine/snapshot/snapshot-mutation-queues.js +133 -0
  76. package/dist/engine/snapshot/snapshot-paths.d.ts +1 -0
  77. package/dist/engine/snapshot/snapshot-paths.js +11 -0
  78. package/dist/engine/snapshot/snapshot-root-transition.d.ts +25 -0
  79. package/dist/engine/snapshot/snapshot-root-transition.js +122 -0
  80. package/dist/engine/snapshot/snapshot-transaction-directory.d.ts +2 -0
  81. package/dist/engine/snapshot/snapshot-transaction-directory.js +16 -0
  82. package/dist/engine/snapshot/snapshot-transaction-plan.d.ts +12 -0
  83. package/dist/engine/snapshot/snapshot-transaction-plan.js +68 -0
  84. package/dist/engine/snapshot/snapshot-transaction.d.ts +15 -0
  85. package/dist/engine/snapshot/snapshot-transaction.js +787 -0
  86. package/dist/engine/snapshot/snapshot-types.d.ts +48 -0
  87. package/dist/engine/snapshot/snapshot-types.js +1 -0
  88. package/dist/engine/snapshot/snapshot.d.ts +30 -0
  89. package/dist/engine/snapshot/snapshot.js +364 -0
  90. package/dist/engine/state/json-file.d.ts +6 -0
  91. package/dist/engine/state/json-file.js +49 -0
  92. package/dist/engine/state/lock-policy.d.ts +2 -0
  93. package/dist/engine/state/lock-policy.js +2 -0
  94. package/dist/engine/state/lock.d.ts +20 -0
  95. package/dist/engine/state/lock.js +259 -0
  96. package/dist/engine/state/lockfile-fs.d.ts +13 -0
  97. package/dist/engine/state/lockfile-fs.js +13 -0
  98. package/dist/engine/state/merge-baseline-store.d.ts +11 -0
  99. package/dist/engine/state/merge-baseline-store.js +187 -0
  100. package/dist/engine/state/mutation-directory-sync.d.ts +5 -0
  101. package/dist/engine/state/mutation-directory-sync.js +34 -0
  102. package/dist/engine/state/operation-availability.d.ts +49 -0
  103. package/dist/engine/state/operation-availability.js +40 -0
  104. package/dist/engine/state/state-directory.d.ts +14 -0
  105. package/dist/engine/state/state-directory.js +225 -0
  106. package/dist/engine/state/state-types.d.ts +27 -0
  107. package/dist/engine/state/state-types.js +1 -0
  108. package/dist/engine/state/sync-state-store.d.ts +11 -0
  109. package/dist/engine/state/sync-state-store.js +54 -0
  110. package/dist/engine/sync/agent-candidate.d.ts +44 -0
  111. package/dist/engine/sync/agent-candidate.js +207 -0
  112. package/dist/engine/sync/agent-plan.d.ts +8 -0
  113. package/dist/engine/sync/agent-plan.js +84 -0
  114. package/dist/engine/sync/agent-policy.d.ts +9 -0
  115. package/dist/engine/sync/agent-policy.js +10 -0
  116. package/dist/engine/sync/agent-refusal-retry.d.ts +4 -0
  117. package/dist/engine/sync/agent-refusal-retry.js +39 -0
  118. package/dist/engine/sync/agent-request.d.ts +14 -0
  119. package/dist/engine/sync/agent-request.js +13 -0
  120. package/dist/engine/sync/agent-runner.d.ts +6 -0
  121. package/dist/engine/sync/agent-runner.js +183 -0
  122. package/dist/engine/sync/agent-store.d.ts +7 -0
  123. package/dist/engine/sync/agent-store.js +177 -0
  124. package/dist/engine/sync/agent-sync.d.ts +4 -0
  125. package/dist/engine/sync/agent-sync.js +132 -0
  126. package/dist/engine/sync/apply-review.d.ts +8 -0
  127. package/dist/engine/sync/apply-review.js +51 -0
  128. package/dist/engine/sync/conflict-artifact-ownership.d.ts +4 -0
  129. package/dist/engine/sync/conflict-artifact-ownership.js +53 -0
  130. package/dist/engine/sync/conflict-artifacts.d.ts +32 -0
  131. package/dist/engine/sync/conflict-artifacts.js +158 -0
  132. package/dist/engine/sync/conflict-groups.d.ts +9 -0
  133. package/dist/engine/sync/conflict-groups.js +76 -0
  134. package/dist/engine/sync/conflict-preview.d.ts +4 -0
  135. package/dist/engine/sync/conflict-preview.js +53 -0
  136. package/dist/engine/sync/conflict-resolution.d.ts +13 -0
  137. package/dist/engine/sync/conflict-resolution.js +53 -0
  138. package/dist/engine/sync/conflict-retention.d.ts +5 -0
  139. package/dist/engine/sync/conflict-retention.js +61 -0
  140. package/dist/engine/sync/conflict-review.d.ts +4 -0
  141. package/dist/engine/sync/conflict-review.js +73 -0
  142. package/dist/engine/sync/content-conflicts.d.ts +10 -0
  143. package/dist/engine/sync/content-conflicts.js +70 -0
  144. package/dist/engine/sync/continuous-errors.d.ts +14 -0
  145. package/dist/engine/sync/continuous-errors.js +66 -0
  146. package/dist/engine/sync/continuous-lease.d.ts +9 -0
  147. package/dist/engine/sync/continuous-lease.js +206 -0
  148. package/dist/engine/sync/continuous-record.d.ts +31 -0
  149. package/dist/engine/sync/continuous-record.js +199 -0
  150. package/dist/engine/sync/continuous-storage.d.ts +14 -0
  151. package/dist/engine/sync/continuous-storage.js +59 -0
  152. package/dist/engine/sync/continuous-sync.d.ts +15 -0
  153. package/dist/engine/sync/continuous-sync.js +496 -0
  154. package/dist/engine/sync/continuous-watch.d.ts +3 -0
  155. package/dist/engine/sync/continuous-watch.js +65 -0
  156. package/dist/engine/sync/exclude-policy.d.ts +5 -0
  157. package/dist/engine/sync/exclude-policy.js +79 -0
  158. package/dist/engine/sync/field-migration.d.ts +5 -0
  159. package/dist/engine/sync/field-migration.js +20 -0
  160. package/dist/engine/sync/file-merge-planner.d.ts +36 -0
  161. package/dist/engine/sync/file-merge-planner.js +123 -0
  162. package/dist/engine/sync/initialization.d.ts +12 -0
  163. package/dist/engine/sync/initialization.js +75 -0
  164. package/dist/engine/sync/json-document.d.ts +29 -0
  165. package/dist/engine/sync/json-document.js +172 -0
  166. package/dist/engine/sync/local-field-policy.d.ts +2 -0
  167. package/dist/engine/sync/local-field-policy.js +26 -0
  168. package/dist/engine/sync/local-fields.d.ts +9 -0
  169. package/dist/engine/sync/local-fields.js +116 -0
  170. package/dist/engine/sync/merge-apply.d.ts +5 -0
  171. package/dist/engine/sync/merge-apply.js +386 -0
  172. package/dist/engine/sync/merge-journal.d.ts +31 -0
  173. package/dist/engine/sync/merge-journal.js +179 -0
  174. package/dist/engine/sync/merge-transfer-error.d.ts +3 -0
  175. package/dist/engine/sync/merge-transfer-error.js +64 -0
  176. package/dist/engine/sync/merged-sync.d.ts +6 -0
  177. package/dist/engine/sync/merged-sync.js +618 -0
  178. package/dist/engine/sync/mutation-owner.d.ts +2 -0
  179. package/dist/engine/sync/mutation-owner.js +18 -0
  180. package/dist/engine/sync/package-merge.d.ts +3 -0
  181. package/dist/engine/sync/package-merge.js +82 -0
  182. package/dist/engine/sync/partial-progress.d.ts +15 -0
  183. package/dist/engine/sync/partial-progress.js +39 -0
  184. package/dist/engine/sync/remote-snapshot.d.ts +28 -0
  185. package/dist/engine/sync/remote-snapshot.js +62 -0
  186. package/dist/engine/sync/resolver-stream.d.ts +4 -0
  187. package/dist/engine/sync/resolver-stream.js +34 -0
  188. package/dist/engine/sync/session-merge.d.ts +3 -0
  189. package/dist/engine/sync/session-merge.js +178 -0
  190. package/dist/engine/sync/session-push.d.ts +5 -0
  191. package/dist/engine/sync/session-push.js +32 -0
  192. package/dist/engine/sync/settings-conflicts.d.ts +8 -0
  193. package/dist/engine/sync/settings-conflicts.js +56 -0
  194. package/dist/engine/sync/settings-merge.d.ts +13 -0
  195. package/dist/engine/sync/settings-merge.js +93 -0
  196. package/dist/engine/sync/signals.d.ts +2 -0
  197. package/dist/engine/sync/signals.js +8 -0
  198. package/dist/engine/sync/startup-timings.d.ts +11 -0
  199. package/dist/engine/sync/startup-timings.js +44 -0
  200. package/dist/engine/sync/sync-decision.d.ts +35 -0
  201. package/dist/engine/sync/sync-decision.js +66 -0
  202. package/dist/engine/sync/sync-error-guidance.d.ts +2 -0
  203. package/dist/engine/sync/sync-error-guidance.js +55 -0
  204. package/dist/engine/sync/sync-errors.d.ts +9 -0
  205. package/dist/engine/sync/sync-errors.js +18 -0
  206. package/dist/engine/sync/sync-inspection.d.ts +26 -0
  207. package/dist/engine/sync/sync-inspection.js +40 -0
  208. package/dist/engine/sync/sync-loaders.d.ts +7 -0
  209. package/dist/engine/sync/sync-loaders.js +8 -0
  210. package/dist/engine/sync/sync-local.d.ts +5 -0
  211. package/dist/engine/sync/sync-local.js +40 -0
  212. package/dist/engine/sync/sync-mutations.d.ts +30 -0
  213. package/dist/engine/sync/sync-mutations.js +589 -0
  214. package/dist/engine/sync/sync-operations.d.ts +2 -0
  215. package/dist/engine/sync/sync-operations.js +3 -0
  216. package/dist/engine/sync/sync-policy.d.ts +85 -0
  217. package/dist/engine/sync/sync-policy.js +356 -0
  218. package/dist/engine/sync/sync-queries.d.ts +7 -0
  219. package/dist/engine/sync/sync-queries.js +195 -0
  220. package/dist/engine/sync/sync-state.d.ts +31 -0
  221. package/dist/engine/sync/sync-state.js +92 -0
  222. package/dist/engine/sync/text-merge.d.ts +19 -0
  223. package/dist/engine/sync/text-merge.js +124 -0
  224. package/dist/engine/types.d.ts +5 -0
  225. package/dist/engine/types.js +2 -0
  226. package/dist/engine/ui/merge-review.d.ts +2 -0
  227. package/dist/engine/ui/merge-review.js +7 -0
  228. package/dist/engine/ui/merged-sync-summary.d.ts +25 -0
  229. package/dist/engine/ui/merged-sync-summary.js +86 -0
  230. package/dist/engine/ui/sync-format.d.ts +13 -0
  231. package/dist/engine/ui/sync-format.js +150 -0
  232. package/dist/engine/ui/sync-status.d.ts +9 -0
  233. package/dist/engine/ui/sync-status.js +30 -0
  234. package/dist/engine/ui/terminal-text.d.ts +3 -0
  235. package/dist/engine/ui/terminal-text.js +9 -0
  236. package/dist/engine/ui/transfer-changes.d.ts +12 -0
  237. package/dist/engine/ui/transfer-changes.js +24 -0
  238. package/dist/engine/ui/transfer-review.d.ts +3 -0
  239. package/dist/engine/ui/transfer-review.js +19 -0
  240. package/dist/engine-service.d.ts +14 -0
  241. package/dist/engine-service.js +322 -0
  242. package/dist/identity.d.ts +20 -0
  243. package/dist/identity.js +133 -0
  244. package/dist/idle-exit.d.ts +17 -0
  245. package/dist/idle-exit.js +77 -0
  246. package/dist/index.d.ts +8 -0
  247. package/dist/index.js +4 -0
  248. package/dist/lifecycle-log.d.ts +7 -0
  249. package/dist/lifecycle-log.js +53 -0
  250. package/dist/lifecycle.d.ts +2 -0
  251. package/dist/lifecycle.js +21 -0
  252. package/dist/model-signature.d.ts +2 -0
  253. package/dist/model-signature.js +7 -0
  254. package/dist/monitor.d.ts +14 -0
  255. package/dist/monitor.js +272 -0
  256. package/dist/participant-admission.d.ts +5 -0
  257. package/dist/participant-admission.js +30 -0
  258. package/dist/protocol.d.ts +102 -0
  259. package/dist/protocol.js +97 -0
  260. package/dist/resolver-host.d.ts +11 -0
  261. package/dist/resolver-host.js +78 -0
  262. package/dist/server.d.ts +24 -0
  263. package/dist/server.js +808 -0
  264. package/dist/service-host.d.ts +7 -0
  265. package/dist/service-host.js +174 -0
  266. package/docs/architecture.md +162 -0
  267. package/package.json +54 -4
@@ -0,0 +1,259 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import lockfile from "proper-lockfile";
4
+ import { throwIfAborted } from "../sync/signals.js";
5
+ import { LOCK_GUARD_STALE_MS, LOCK_GUARD_UPDATE_MS } from "./lock-policy.js";
6
+ import { LOCKFILE_FS_ADAPTER } from "./lockfile-fs.js";
7
+ import { ensureStateDir, lockPath } from "./sync-state-store.js";
8
+ const LOCK_STALE_MS = 30 * 60 * 1000;
9
+ const MAX_PROCESS_ID = 2_147_483_647;
10
+ export async function withLock(command, fn, options = {}) {
11
+ await ensureStateDir();
12
+ const lock = {
13
+ id: randomUUID(),
14
+ pid: process.pid,
15
+ command,
16
+ startedAt: new Date().toISOString(),
17
+ };
18
+ let guard;
19
+ let result;
20
+ let failed = false;
21
+ let failure;
22
+ try {
23
+ try {
24
+ guard = await acquireGuard();
25
+ }
26
+ catch (error) {
27
+ if (!isLockHeldError(error))
28
+ throw error;
29
+ throw await describeHeldLock();
30
+ }
31
+ let inspection = await inspectLock();
32
+ if (inspection.status === "valid" && isStaleLock(inspection.lock)) {
33
+ if (!options.reclaimStale) {
34
+ throw new Error(`pi-sync lock is stale (pid ${inspection.lock.pid}). Run /sync unlock --stale, then retry.`);
35
+ }
36
+ guard.throwIfCompromised();
37
+ const rechecked = await inspectLock();
38
+ if (rechecked.status !== "valid" || rechecked.lock.id !== inspection.lock.id || !isStaleLock(rechecked.lock)) {
39
+ throw new Error("pi-sync lock changed while preparing transaction recovery; retry.");
40
+ }
41
+ await fs.rm(lockPath(), { force: true });
42
+ inspection = { status: "missing" };
43
+ }
44
+ if (inspection.status === "valid") {
45
+ throw Object.assign(new Error(`pi-sync is already running (${inspection.lock.command}, pid ${inspection.lock.pid}, started ${inspection.lock.startedAt}).`), { code: "ELOCKED" });
46
+ }
47
+ if (inspection.status === "unreadable") {
48
+ throw new Error("pi-sync lock metadata is unreadable. Run /sync unlock --stale after verifying no sync is running.");
49
+ }
50
+ await fs.writeFile(lockPath(), JSON.stringify(lock, null, "\t"), { flag: "wx" });
51
+ guard.throwIfCompromised();
52
+ result = await fn();
53
+ guard.throwIfCompromised();
54
+ }
55
+ catch (error) {
56
+ failed = true;
57
+ failure = error;
58
+ }
59
+ try {
60
+ const current = await readLock();
61
+ if (current?.id === lock.id)
62
+ await fs.rm(lockPath(), { force: true });
63
+ }
64
+ catch (error) {
65
+ if (!failed) {
66
+ failed = true;
67
+ failure = error;
68
+ }
69
+ }
70
+ if (guard) {
71
+ const releaseError = await releaseGuard(guard);
72
+ if (releaseError && !failed) {
73
+ failed = true;
74
+ failure = releaseError;
75
+ }
76
+ }
77
+ if (failed)
78
+ throw failure;
79
+ return result;
80
+ }
81
+ export async function inspectLock() {
82
+ try {
83
+ const text = await fs.readFile(lockPath(), "utf8");
84
+ if (text.trim().length === 0)
85
+ return { status: "unreadable" };
86
+ const parsed = JSON.parse(text);
87
+ return isLockFile(parsed) ? { status: "valid", lock: parsed } : { status: "unreadable" };
88
+ }
89
+ catch (error) {
90
+ if (error.code === "ENOENT")
91
+ return { status: "missing" };
92
+ if (error instanceof SyntaxError)
93
+ return { status: "unreadable" };
94
+ throw error;
95
+ }
96
+ }
97
+ export async function readLock() {
98
+ const inspection = await inspectLock();
99
+ return inspection.status === "valid" ? inspection.lock : undefined;
100
+ }
101
+ export async function lockFileExists() {
102
+ try {
103
+ await fs.stat(lockPath());
104
+ return true;
105
+ }
106
+ catch (error) {
107
+ if (error.code === "ENOENT")
108
+ return false;
109
+ throw error;
110
+ }
111
+ }
112
+ export function isLockGuardHeld() {
113
+ return lockfile.check(lockPath(), {
114
+ fs: LOCKFILE_FS_ADAPTER,
115
+ lockfilePath: `${lockPath()}.guard`,
116
+ realpath: false,
117
+ stale: LOCK_GUARD_STALE_MS,
118
+ });
119
+ }
120
+ export function isStaleLock(lock) {
121
+ try {
122
+ process.kill(lock.pid, 0);
123
+ return false;
124
+ }
125
+ catch (error) {
126
+ if (error.code === "ESRCH")
127
+ return true;
128
+ return Date.now() - Date.parse(lock.startedAt) > LOCK_STALE_MS;
129
+ }
130
+ }
131
+ export async function unlock(ctx, options) {
132
+ throwIfAborted(options.signal);
133
+ await ensureStateDir();
134
+ throwIfAborted(options.signal);
135
+ let guard;
136
+ try {
137
+ guard = await acquireGuard();
138
+ }
139
+ catch (error) {
140
+ if (!isLockHeldError(error))
141
+ throw error;
142
+ ctx.ui.notify((await describeHeldLock()).message, "warning");
143
+ return;
144
+ }
145
+ let failed = false;
146
+ let failure;
147
+ try {
148
+ await unlockGuarded(ctx, options);
149
+ }
150
+ catch (error) {
151
+ failed = true;
152
+ failure = error;
153
+ }
154
+ const releaseError = await releaseGuard(guard);
155
+ if (releaseError && !failed) {
156
+ failed = true;
157
+ failure = releaseError;
158
+ }
159
+ if (failed)
160
+ throw failure;
161
+ }
162
+ async function unlockGuarded(ctx, options) {
163
+ throwIfAborted(options.signal);
164
+ let inspection = await inspectLock();
165
+ throwIfAborted(options.signal);
166
+ if (inspection.status === "missing") {
167
+ ctx.ui.notify("No pi-sync lock is present.", "info");
168
+ return;
169
+ }
170
+ if (inspection.status === "unreadable") {
171
+ if (!options.stale) {
172
+ ctx.ui.notify("Pi-sync lock metadata is unreadable. Use /sync unlock --stale only after verifying no sync is running.", "warning");
173
+ return;
174
+ }
175
+ inspection = await inspectLock();
176
+ throwIfAborted(options.signal);
177
+ if (inspection.status === "unreadable") {
178
+ // Legacy writers expose an empty file before writing owner metadata, so no
179
+ // automatic test can prove this file is abandoned. The explicit --stale
180
+ // flag is the user's confirmation that no legacy sync is still running.
181
+ throwIfAborted(options.signal);
182
+ await fs.rm(lockPath(), { force: true });
183
+ if (!options.signal?.aborted) {
184
+ ctx.ui.notify("Removed unreadable pi-sync lock. No settings, files, sync state, or remote data were changed.", "info");
185
+ }
186
+ return;
187
+ }
188
+ if (inspection.status === "missing") {
189
+ ctx.ui.notify("No pi-sync lock is present.", "info");
190
+ return;
191
+ }
192
+ }
193
+ if (!isStaleLock(inspection.lock)) {
194
+ ctx.ui.notify("Lock owner is still live; refusing to remove it.", "warning");
195
+ return;
196
+ }
197
+ throwIfAborted(options.signal);
198
+ await fs.rm(lockPath(), { force: true });
199
+ if (!options.signal?.aborted) {
200
+ ctx.ui.notify("Removed stale pi-sync lock. No settings, files, sync state, or remote data were changed.", "info");
201
+ }
202
+ }
203
+ async function releaseGuard(guard) {
204
+ try {
205
+ await guard.release();
206
+ return undefined;
207
+ }
208
+ catch (error) {
209
+ return guard.isCompromised() ? undefined : error;
210
+ }
211
+ }
212
+ async function acquireGuard() {
213
+ let compromisedError;
214
+ const release = await lockfile.lock(lockPath(), {
215
+ fs: LOCKFILE_FS_ADAPTER,
216
+ lockfilePath: `${lockPath()}.guard`,
217
+ realpath: false,
218
+ stale: LOCK_GUARD_STALE_MS,
219
+ update: LOCK_GUARD_UPDATE_MS,
220
+ onCompromised: (error) => {
221
+ compromisedError = error;
222
+ },
223
+ });
224
+ return {
225
+ release,
226
+ throwIfCompromised: () => {
227
+ if (compromisedError)
228
+ throw compromisedError;
229
+ },
230
+ isCompromised: () => compromisedError !== undefined,
231
+ };
232
+ }
233
+ async function describeHeldLock() {
234
+ const current = await readLock();
235
+ if (current && isStaleLock(current)) {
236
+ return new Error("pi-sync lock owner exited; retry shortly while the lock guard expires.");
237
+ }
238
+ if (current) {
239
+ return Object.assign(new Error(`Pi-sync is currently running (${current.command}, pid ${current.pid}, started ${current.startedAt}).`), { code: "ELOCKED" });
240
+ }
241
+ return Object.assign(new Error("Pi-sync is currently running (lock metadata is unreadable or still being written)."), { code: "ELOCKED" });
242
+ }
243
+ function isLockHeldError(error) {
244
+ return error.code === "ELOCKED";
245
+ }
246
+ function isLockFile(value) {
247
+ if (!value || typeof value !== "object" || Array.isArray(value))
248
+ return false;
249
+ const lock = value;
250
+ return (typeof lock.id === "string" &&
251
+ lock.id.length > 0 &&
252
+ Number.isInteger(lock.pid) &&
253
+ (lock.pid ?? 0) > 0 &&
254
+ (lock.pid ?? 0) <= MAX_PROCESS_ID &&
255
+ typeof lock.command === "string" &&
256
+ lock.command.length > 0 &&
257
+ typeof lock.startedAt === "string" &&
258
+ Number.isFinite(Date.parse(lock.startedAt)));
259
+ }
@@ -0,0 +1,13 @@
1
+ import { mkdir, mkdirSync, realpath, realpathSync, rmdir, rmdirSync, stat, statSync, utimes, utimesSync } from "node:fs";
2
+ export declare const LOCKFILE_FS_ADAPTER: {
3
+ mkdir: typeof mkdir;
4
+ mkdirSync: typeof mkdirSync;
5
+ realpath: typeof realpath;
6
+ realpathSync: typeof realpathSync;
7
+ rmdir: typeof rmdir;
8
+ rmdirSync: typeof rmdirSync;
9
+ stat: typeof stat;
10
+ statSync: typeof statSync;
11
+ utimes: typeof utimes;
12
+ utimesSync: typeof utimesSync;
13
+ };
@@ -0,0 +1,13 @@
1
+ import { mkdir, mkdirSync, realpath, realpathSync, rmdir, rmdirSync, stat, statSync, utimes, utimesSync, } from "node:fs";
2
+ export const LOCKFILE_FS_ADAPTER = {
3
+ mkdir,
4
+ mkdirSync,
5
+ realpath,
6
+ realpathSync,
7
+ rmdir,
8
+ rmdirSync,
9
+ stat,
10
+ statSync,
11
+ utimes,
12
+ utimesSync,
13
+ };
@@ -0,0 +1,11 @@
1
+ import type { AnySyncConfig } from "../settings/settings-types.js";
2
+ import type { Snapshot, SnapshotFile } from "../snapshot/snapshot-types.js";
3
+ import type { SyncState } from "./state-types.js";
4
+ /** Stage before accepted state, retain its previous ancestor until journal retirement. Never bootstrap from current edits. */
5
+ export declare function stageMergeBaseline(config: AnySyncConfig, snapshot: Snapshot, accepted: SyncState, previous?: SyncState): Promise<void>;
6
+ export declare function readMergeAncestors(config: AnySyncConfig, state: SyncState): Promise<SnapshotFile[] | undefined>;
7
+ /** A no-op must not skip seeding or repairing ancestors required by later merges. */
8
+ export declare function hasCurrentMergeBaseline(config: AnySyncConfig, snapshot: Snapshot, state: SyncState): Promise<boolean>;
9
+ export declare function readMergeAncestor(config: AnySyncConfig, state: SyncState, filePath: string): Promise<Buffer<ArrayBuffer> | undefined>;
10
+ /** Caller must hold the sync operation lock and retire the commit journal before pruning. */
11
+ export declare function pruneMergeBaselines(config: AnySyncConfig, state: SyncState, validate: () => void): Promise<void>;
@@ -0,0 +1,187 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { backendIdentityCoordinates } from "../backends/backend-identity.js";
5
+ import { compileSyncExclude, normalizeSyncExclude } from "../sync/exclude-policy.js";
6
+ import { collidingPaths, planFileMerge } from "../sync/file-merge-planner.js";
7
+ import { parseSettingsDocument } from "../sync/json-document.js";
8
+ import { validateSession } from "../sync/session-merge.js";
9
+ import { isMergeTextPath, text } from "../sync/text-merge.js";
10
+ import { syncDirectory, writeJson } from "./json-file.js";
11
+ import { statePathForConfig, syncStateFingerprint } from "./sync-state-store.js";
12
+ const MAX_BYTES = 192 * 1024 * 1024;
13
+ function eligible(file) {
14
+ try {
15
+ const bytes = Buffer.from(file.contentBase64, "base64");
16
+ if (file.path === "settings.json")
17
+ parseSettingsDocument(bytes);
18
+ else if (isMergeTextPath(file.path))
19
+ text(bytes);
20
+ else if (file.path.startsWith("sessions/") && file.path.endsWith(".jsonl"))
21
+ validateSession(bytes);
22
+ else
23
+ return false;
24
+ return true;
25
+ }
26
+ catch {
27
+ return false;
28
+ }
29
+ }
30
+ function identity(config) {
31
+ return JSON.stringify([
32
+ config.setupName,
33
+ backendIdentityCoordinates(config),
34
+ config.include,
35
+ config.localFields ?? [],
36
+ ...(config.exclude === undefined
37
+ ? []
38
+ : ["exclude", normalizeSyncExclude(config.exclude).map((rule) => rule.toLowerCase())]),
39
+ ]);
40
+ }
41
+ function directory(config) {
42
+ return `${statePathForConfig(config)}.ancestors`;
43
+ }
44
+ async function checkDirectory(config, create = false) {
45
+ const target = directory(config);
46
+ if (create)
47
+ await fs.mkdir(target, { recursive: true, mode: 0o700 });
48
+ const stat = await fs.lstat(target);
49
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (process.platform !== "win32" && (stat.mode & 0o077) !== 0))
50
+ throw new Error("Unsafe private ancestor directory; preserve evidence.");
51
+ }
52
+ function baselinePath(config, state) {
53
+ return path.join(directory(config), `${syncStateFingerprint(state)}.json`);
54
+ }
55
+ /** Stage before accepted state, retain its previous ancestor until journal retirement. Never bootstrap from current edits. */
56
+ export async function stageMergeBaseline(config, snapshot, accepted, previous) {
57
+ const collisions = collidingPaths(snapshot.files.map((file) => file.path));
58
+ const excluded = compileSyncExclude(config.exclude);
59
+ const files = snapshot.files.filter((file) => {
60
+ return (!excluded(file.path) &&
61
+ !collisions.has(file.path) &&
62
+ accepted.lastFileHashes[file.path] === file.sha256 &&
63
+ (file.path === "settings.json" || config.mergeContent || (config.agentMode && isMergeTextPath(file.path))) &&
64
+ eligible(file));
65
+ });
66
+ if (previous) {
67
+ const stagedPaths = new Set(files.map((file) => file.path));
68
+ let ancestors = [];
69
+ try {
70
+ ancestors = (await readMergeAncestors(config, previous)) ?? [];
71
+ }
72
+ catch {
73
+ /* Keep unknown evidence; missing bytes are never invented. */
74
+ }
75
+ for (const ancestor of ancestors)
76
+ if (!excluded(ancestor.path) &&
77
+ !collisions.has(ancestor.path) &&
78
+ accepted.lastFileHashes[ancestor.path] === ancestor.sha256 &&
79
+ !stagedPaths.has(ancestor.path)) {
80
+ files.push(ancestor);
81
+ stagedPaths.add(ancestor.path);
82
+ }
83
+ }
84
+ const plan = planFileMerge({ baseline: {}, local: files, remote: [], selectionCompatible: true });
85
+ if (plan.kind !== "planned" || plan.conflicts.length)
86
+ throw new Error("Cannot stage unverified merge ancestor bytes.");
87
+ const record = {
88
+ version: 1,
89
+ identity: identity(config),
90
+ acceptedState: syncStateFingerprint(accepted),
91
+ files,
92
+ };
93
+ await checkDirectory(config, true);
94
+ await writeJson(baselinePath(config, accepted), record, { maxBytes: MAX_BYTES });
95
+ }
96
+ async function readBaselineRecord(config, target, acceptedState, validate = () => { }) {
97
+ const stat = await fs.lstat(target);
98
+ validate();
99
+ if (!stat.isFile() || stat.size > MAX_BYTES || (process.platform !== "win32" && (stat.mode & 0o077) !== 0))
100
+ throw new Error("Unsafe cache.");
101
+ const record = JSON.parse(await fs.readFile(target, "utf8"));
102
+ validate();
103
+ if (record.version !== 1 ||
104
+ record.identity !== identity(config) ||
105
+ record.acceptedState !== acceptedState ||
106
+ !Array.isArray(record.files) ||
107
+ record.files.length > 16_384 ||
108
+ record.files.some((file) => !eligible(file)))
109
+ throw new Error("Invalid cache identity.");
110
+ const plan = planFileMerge({ baseline: {}, local: record.files, remote: [], selectionCompatible: true });
111
+ if (plan.kind !== "planned" || plan.conflicts.length)
112
+ throw new Error("Invalid cache bytes.");
113
+ return record;
114
+ }
115
+ export async function readMergeAncestors(config, state) {
116
+ let record;
117
+ try {
118
+ await checkDirectory(config);
119
+ record = await readBaselineRecord(config, baselinePath(config, state), syncStateFingerprint(state));
120
+ for (const file of record.files) {
121
+ if (state.lastFileHashes[file.path] !== file.sha256 ||
122
+ createHash("sha256").update(Buffer.from(file.contentBase64, "base64")).digest("hex") !== file.sha256)
123
+ throw new Error("Cache hash mismatch.");
124
+ }
125
+ }
126
+ catch (error) {
127
+ if (error.code === "ENOENT")
128
+ return;
129
+ throw new Error("Merge ancestor is invalid; preserve its private cache and review the conflict.");
130
+ }
131
+ const excluded = compileSyncExclude(config.exclude);
132
+ return record.files.filter((file) => !excluded(file.path));
133
+ }
134
+ /** A no-op must not skip seeding or repairing ancestors required by later merges. */
135
+ export async function hasCurrentMergeBaseline(config, snapshot, state) {
136
+ try {
137
+ const ancestors = await readMergeAncestors(config, state);
138
+ if (!ancestors)
139
+ return false;
140
+ const hashes = new Map(ancestors.map((file) => [file.path, file.sha256]));
141
+ return snapshot.files.every((file) => !(file.path === "settings.json" || config.mergeContent || (config.agentMode && isMergeTextPath(file.path))) ||
142
+ !eligible(file) ||
143
+ hashes.get(file.path) === file.sha256);
144
+ }
145
+ catch {
146
+ // Preserve the existing full path's validation and repair behavior for unknown evidence.
147
+ return false;
148
+ }
149
+ }
150
+ export async function readMergeAncestor(config, state, filePath) {
151
+ const file = (await readMergeAncestors(config, state))?.find((file) => file.path === filePath);
152
+ return file ? Buffer.from(file.contentBase64, "base64") : undefined;
153
+ }
154
+ /** Caller must hold the sync operation lock and retire the commit journal before pruning. */
155
+ export async function pruneMergeBaselines(config, state, validate) {
156
+ validate();
157
+ const keep = path.basename(baselinePath(config, state));
158
+ let names;
159
+ try {
160
+ await checkDirectory(config);
161
+ validate();
162
+ names = await fs.readdir(directory(config));
163
+ }
164
+ catch (error) {
165
+ if (error.code === "ENOENT")
166
+ return;
167
+ throw error;
168
+ }
169
+ for (const name of names) {
170
+ validate();
171
+ if (name === keep || !/^[a-f0-9]{64}\.json$/u.test(name))
172
+ continue;
173
+ const target = path.join(directory(config), name);
174
+ try {
175
+ await readBaselineRecord(config, target, name.slice(0, -5), validate);
176
+ }
177
+ catch {
178
+ validate();
179
+ continue; // Unknown/corrupted evidence is not an owned pruning candidate.
180
+ }
181
+ validate();
182
+ await fs.rm(target);
183
+ validate();
184
+ }
185
+ await syncDirectory(directory(config));
186
+ validate();
187
+ }
@@ -0,0 +1,5 @@
1
+ /** Persist created ancestor names as well as the immediate rename/delete directory. */
2
+ export declare function syncMutationParents(targets: readonly string[], roots: readonly string[], options?: {
3
+ signal?: AbortSignal;
4
+ validateMutation?: () => void;
5
+ }): Promise<void>;
@@ -0,0 +1,34 @@
1
+ import path from "node:path";
2
+ import { isPathInside } from "../paths.js";
3
+ import { mergePathIdentity } from "../sync/file-merge-planner.js";
4
+ import { syncDirectory } from "./json-file.js";
5
+ /** Persist created ancestor names as well as the immediate rename/delete directory. */
6
+ export async function syncMutationParents(targets, roots, options = {}) {
7
+ const directories = new Set();
8
+ for (const target of targets) {
9
+ const root = roots.map((root) => path.resolve(root)).find((root) => isPathInside(root, target));
10
+ if (!root)
11
+ throw new Error("Unowned mutation directory.");
12
+ for (let parent = path.dirname(target);; parent = path.dirname(parent)) {
13
+ directories.add(parent);
14
+ if (mergePathIdentity(parent) === mergePathIdentity(root))
15
+ break;
16
+ if (path.dirname(parent) === parent)
17
+ throw new Error("Mutation directory escaped its owned root.");
18
+ }
19
+ }
20
+ for (const directory of [...directories].sort((a, b) => b.length - a.length)) {
21
+ options.signal?.throwIfAborted();
22
+ options.validateMutation?.();
23
+ try {
24
+ await syncDirectory(directory);
25
+ }
26
+ catch (error) {
27
+ const code = error.code;
28
+ if (code !== "ENOENT" && code !== "ENOTDIR")
29
+ throw error;
30
+ }
31
+ options.signal?.throwIfAborted();
32
+ options.validateMutation?.();
33
+ }
34
+ }
@@ -0,0 +1,49 @@
1
+ import { type LockInspection } from "./lock.js";
2
+ import type { LockFile } from "./state-types.js";
3
+ export type OperationAvailability = {
4
+ kind: "free";
5
+ } | {
6
+ kind: "live";
7
+ lock: LockFile;
8
+ } | {
9
+ kind: "busy";
10
+ lock?: LockFile;
11
+ metadata: LockInspection["status"];
12
+ } | {
13
+ kind: "recoverable-stale";
14
+ lock: LockFile;
15
+ } | {
16
+ kind: "recoverable-unreadable";
17
+ } | {
18
+ kind: "inspection-error";
19
+ message: string;
20
+ };
21
+ interface OperationInspectionDependencies {
22
+ inspectMetadata(): Promise<LockInspection>;
23
+ inspectGuard(): Promise<boolean>;
24
+ }
25
+ export declare function inspectOperationAvailability(dependencies?: OperationInspectionDependencies): Promise<OperationAvailability>;
26
+ export declare function classifyOperationAvailability(metadata: LockInspection, guardHeld: boolean): OperationAvailability;
27
+ export declare function operationBlocksChanges(availability: OperationAvailability): availability is {
28
+ kind: "live";
29
+ lock: LockFile;
30
+ } | {
31
+ kind: "busy";
32
+ lock?: LockFile;
33
+ metadata: LockInspection["status"];
34
+ } | {
35
+ kind: "recoverable-stale";
36
+ lock: LockFile;
37
+ } | {
38
+ kind: "recoverable-unreadable";
39
+ } | {
40
+ kind: "inspection-error";
41
+ message: string;
42
+ };
43
+ export declare function operationCanRecover(availability: OperationAvailability): availability is {
44
+ kind: "recoverable-stale";
45
+ lock: LockFile;
46
+ } | {
47
+ kind: "recoverable-unreadable";
48
+ };
49
+ export {};
@@ -0,0 +1,40 @@
1
+ import { errorMessage } from "../sync/sync-errors.js";
2
+ import { inspectLock, isLockGuardHeld, isStaleLock } from "./lock.js";
3
+ const DEFAULT_INSPECTION_DEPENDENCIES = {
4
+ inspectMetadata: inspectLock,
5
+ inspectGuard: isLockGuardHeld,
6
+ };
7
+ export async function inspectOperationAvailability(dependencies = DEFAULT_INSPECTION_DEPENDENCIES) {
8
+ try {
9
+ const metadata = await dependencies.inspectMetadata();
10
+ const guardHeld = await dependencies.inspectGuard();
11
+ return classifyOperationAvailability(metadata, guardHeld);
12
+ }
13
+ catch (error) {
14
+ return { kind: "inspection-error", message: errorMessage(error) };
15
+ }
16
+ }
17
+ export function classifyOperationAvailability(metadata, guardHeld) {
18
+ if (metadata.status === "valid" && !isStaleLock(metadata.lock)) {
19
+ return { kind: "live", lock: metadata.lock };
20
+ }
21
+ if (guardHeld) {
22
+ return {
23
+ kind: "busy",
24
+ metadata: metadata.status,
25
+ ...(metadata.status === "valid" ? { lock: metadata.lock } : {}),
26
+ };
27
+ }
28
+ if (metadata.status === "valid") {
29
+ return { kind: "recoverable-stale", lock: metadata.lock };
30
+ }
31
+ if (metadata.status === "unreadable")
32
+ return { kind: "recoverable-unreadable" };
33
+ return { kind: "free" };
34
+ }
35
+ export function operationBlocksChanges(availability) {
36
+ return availability.kind !== "free";
37
+ }
38
+ export function operationCanRecover(availability) {
39
+ return availability.kind === "recoverable-stale" || availability.kind === "recoverable-unreadable";
40
+ }
@@ -0,0 +1,14 @@
1
+ export type StateDirectoryPreparation = {
2
+ status: "ready";
3
+ } | {
4
+ status: "migrated";
5
+ message: string;
6
+ } | {
7
+ status: "deferred";
8
+ message: string;
9
+ };
10
+ export declare function stateDir(): string;
11
+ export declare function legacyStateDir(): string;
12
+ export declare function stateDirectoryMigrationNotice(): "Legacy pi-sync state is still stored in .pisync. Close other Pi sessions, then run /sync migrate-state to move it to pi-sync/." | undefined;
13
+ export declare function withStateDirectoryAccess<T>(fn: () => Promise<T>): Promise<T>;
14
+ export declare function migrateLegacyStateDirectory(): Promise<StateDirectoryPreparation>;