@narumitw/pi-sync-daemon 0.0.0-stage → 0.2.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 (265) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE +21 -0
  3. package/README.md +89 -2
  4. package/dist/cli.d.ts +2 -0
  5. package/dist/cli.js +128 -0
  6. package/dist/client.d.ts +55 -0
  7. package/dist/client.js +484 -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 +11 -0
  241. package/dist/engine-service.js +315 -0
  242. package/dist/identity.d.ts +20 -0
  243. package/dist/identity.js +133 -0
  244. package/dist/index.d.ts +8 -0
  245. package/dist/index.js +4 -0
  246. package/dist/lifecycle-log.d.ts +7 -0
  247. package/dist/lifecycle-log.js +53 -0
  248. package/dist/lifecycle.d.ts +2 -0
  249. package/dist/lifecycle.js +21 -0
  250. package/dist/model-signature.d.ts +2 -0
  251. package/dist/model-signature.js +7 -0
  252. package/dist/monitor.d.ts +11 -0
  253. package/dist/monitor.js +245 -0
  254. package/dist/participant-admission.d.ts +5 -0
  255. package/dist/participant-admission.js +30 -0
  256. package/dist/protocol.d.ts +97 -0
  257. package/dist/protocol.js +90 -0
  258. package/dist/resolver-host.d.ts +11 -0
  259. package/dist/resolver-host.js +78 -0
  260. package/dist/server.d.ts +18 -0
  261. package/dist/server.js +724 -0
  262. package/dist/service-host.d.ts +7 -0
  263. package/dist/service-host.js +174 -0
  264. package/docs/architecture.md +133 -0
  265. package/package.json +54 -4
@@ -0,0 +1,225 @@
1
+ import { lstatSync } from "node:fs";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import lockfile from "proper-lockfile";
5
+ import { getEngineRoot as getAgentDir } from "../host.js";
6
+ import { LOCK_GUARD_STALE_MS } from "./lock-policy.js";
7
+ import { LOCKFILE_FS_ADAPTER } from "./lockfile-fs.js";
8
+ const CANONICAL_DIRECTORY_NAME = "pi-sync";
9
+ const LEGACY_DIRECTORY_NAME = ".pisync";
10
+ const MIGRATION_LOCK_NAME = ".pi-sync-state-migration.lock";
11
+ const MIGRATION_LOCK_STALE_MS = 30_000;
12
+ const MIGRATION_LOCK_UPDATE_MS = 10_000;
13
+ const sharedStateDirectoryGuards = new Map();
14
+ export function stateDir() {
15
+ const roots = inspectStateRoots();
16
+ if (roots.canonical)
17
+ return canonicalStateDir();
18
+ if (roots.legacy)
19
+ return legacyStateDir();
20
+ return canonicalStateDir();
21
+ }
22
+ export function legacyStateDir() {
23
+ return path.join(getAgentDir(), LEGACY_DIRECTORY_NAME);
24
+ }
25
+ export function stateDirectoryMigrationNotice() {
26
+ const roots = inspectStateRoots();
27
+ if (!roots.legacy)
28
+ return undefined;
29
+ return "Legacy pi-sync state is still stored in .pisync. Close other Pi sessions, then run /sync migrate-state to move it to pi-sync/.";
30
+ }
31
+ export async function withStateDirectoryAccess(fn) {
32
+ const roots = inspectStateRoots();
33
+ if (!roots.legacy)
34
+ return fn();
35
+ return runWithStateDirectoryGuard(await acquireSharedStateDirectoryGuard(), fn);
36
+ }
37
+ export async function migrateLegacyStateDirectory() {
38
+ const initial = inspectStateRoots();
39
+ if (initial.canonical || !initial.legacy)
40
+ return { status: "ready" };
41
+ let guard;
42
+ try {
43
+ guard = await acquireStateDirectoryGuard();
44
+ }
45
+ catch (error) {
46
+ if (!isLockHeldError(error))
47
+ throw error;
48
+ return {
49
+ status: "deferred",
50
+ message: "pi-sync state migration was deferred because another state user is active. Close other Pi sessions and retry.",
51
+ };
52
+ }
53
+ return runWithStateDirectoryGuard(guard, async () => {
54
+ const roots = inspectStateRoots();
55
+ if (roots.canonical || !roots.legacy)
56
+ return { status: "ready" };
57
+ const legacyLock = path.join(legacyStateDir(), "lock");
58
+ const legacyGuardHeld = await lockfile.check(legacyLock, {
59
+ fs: LOCKFILE_FS_ADAPTER,
60
+ lockfilePath: `${legacyLock}.guard`,
61
+ realpath: false,
62
+ stale: LOCK_GUARD_STALE_MS,
63
+ });
64
+ // Idle continuous owners do not retain the exclusive migration guard.
65
+ // A live renewable lease still prevents moving their private state root.
66
+ const schedulerHeld = await lockfile.check(path.join(legacyStateDir(), "continuous", "scheduler"), {
67
+ fs: LOCKFILE_FS_ADAPTER,
68
+ realpath: false,
69
+ stale: LOCK_GUARD_STALE_MS,
70
+ });
71
+ if (legacyGuardHeld || schedulerHeld || (await pathExists(legacyLock))) {
72
+ return {
73
+ status: "deferred",
74
+ message: "pi-sync state migration was deferred because the legacy directory is busy. Close other Pi sessions, clear any confirmed stale sync lock, and retry.",
75
+ };
76
+ }
77
+ guard.throwIfCompromised();
78
+ await fs.rename(legacyStateDir(), canonicalStateDir());
79
+ guard.throwIfCompromised();
80
+ inspectStateRoots();
81
+ return {
82
+ status: "migrated",
83
+ message: `Migrated pi-sync state from ${legacyStateDir()} to ${canonicalStateDir()}.`,
84
+ };
85
+ });
86
+ }
87
+ async function acquireSharedStateDirectoryGuard() {
88
+ const key = migrationLockPath();
89
+ for (;;) {
90
+ let shared = sharedStateDirectoryGuards.get(key);
91
+ if (shared?.closing) {
92
+ await shared.closing;
93
+ continue;
94
+ }
95
+ if (!shared) {
96
+ shared = { guard: acquireStateDirectoryGuard(), users: 0 };
97
+ sharedStateDirectoryGuards.set(key, shared);
98
+ }
99
+ shared.users += 1;
100
+ let guard;
101
+ try {
102
+ guard = await shared.guard;
103
+ }
104
+ catch (error) {
105
+ if (sharedStateDirectoryGuards.get(key) === shared) {
106
+ sharedStateDirectoryGuards.delete(key);
107
+ }
108
+ throw error;
109
+ }
110
+ let released = false;
111
+ return {
112
+ throwIfCompromised: guard.throwIfCompromised,
113
+ release: async () => {
114
+ if (released)
115
+ return;
116
+ released = true;
117
+ shared.users -= 1;
118
+ if (shared.users > 0)
119
+ return;
120
+ const closing = guard.release();
121
+ shared.closing = closing;
122
+ try {
123
+ await closing;
124
+ }
125
+ finally {
126
+ if (sharedStateDirectoryGuards.get(key) === shared) {
127
+ sharedStateDirectoryGuards.delete(key);
128
+ }
129
+ }
130
+ },
131
+ };
132
+ }
133
+ }
134
+ async function acquireStateDirectoryGuard() {
135
+ let compromisedError;
136
+ const release = await lockfile.lock(getAgentDir(), {
137
+ fs: LOCKFILE_FS_ADAPTER,
138
+ lockfilePath: migrationLockPath(),
139
+ realpath: false,
140
+ stale: MIGRATION_LOCK_STALE_MS,
141
+ update: MIGRATION_LOCK_UPDATE_MS,
142
+ retries: { retries: 20, minTimeout: 10, maxTimeout: 50 },
143
+ onCompromised: (error) => {
144
+ compromisedError = error;
145
+ },
146
+ });
147
+ return {
148
+ release,
149
+ throwIfCompromised: () => {
150
+ if (compromisedError)
151
+ throw compromisedError;
152
+ },
153
+ };
154
+ }
155
+ async function runWithStateDirectoryGuard(guard, fn) {
156
+ let result;
157
+ let failed = false;
158
+ let failure;
159
+ try {
160
+ guard.throwIfCompromised();
161
+ result = await fn();
162
+ guard.throwIfCompromised();
163
+ }
164
+ catch (error) {
165
+ failed = true;
166
+ failure = error;
167
+ }
168
+ try {
169
+ await guard.release();
170
+ }
171
+ catch (error) {
172
+ if (!failed) {
173
+ failed = true;
174
+ failure = error;
175
+ }
176
+ }
177
+ if (failed)
178
+ throw failure;
179
+ return result;
180
+ }
181
+ function isLockHeldError(error) {
182
+ return error.code === "ELOCKED";
183
+ }
184
+ function canonicalStateDir() {
185
+ return path.join(getAgentDir(), CANONICAL_DIRECTORY_NAME);
186
+ }
187
+ function migrationLockPath() {
188
+ return path.join(getAgentDir(), MIGRATION_LOCK_NAME);
189
+ }
190
+ function inspectStateRoots() {
191
+ const canonical = isDirectoryRoot(canonicalStateDir(), "canonical");
192
+ const legacy = isDirectoryRoot(legacyStateDir(), "legacy");
193
+ if (canonical && legacy) {
194
+ throw new Error(`Both legacy ${legacyStateDir()} and canonical ${canonicalStateDir()} pi-sync state directories exist. Close all Pi sessions and reconcile the directories manually; pi-sync will not merge or delete either directory.`);
195
+ }
196
+ return { canonical, legacy };
197
+ }
198
+ function isDirectoryRoot(directory, label) {
199
+ try {
200
+ const entry = lstatSync(directory);
201
+ if (entry.isSymbolicLink()) {
202
+ throw new Error(`Refusing to use ${label} pi-sync state directory symbolic link: ${directory}`);
203
+ }
204
+ if (!entry.isDirectory()) {
205
+ throw new Error(`${label} pi-sync state path is not a directory: ${directory}`);
206
+ }
207
+ return true;
208
+ }
209
+ catch (error) {
210
+ if (error.code === "ENOENT")
211
+ return false;
212
+ throw error;
213
+ }
214
+ }
215
+ async function pathExists(filePath) {
216
+ try {
217
+ await fs.lstat(filePath);
218
+ return true;
219
+ }
220
+ catch (error) {
221
+ if (error.code === "ENOENT")
222
+ return false;
223
+ throw error;
224
+ }
225
+ }
@@ -0,0 +1,27 @@
1
+ export interface SyncState {
2
+ version: number;
3
+ profile: string;
4
+ lastAppliedSnapshot?: string;
5
+ lastRemoteRevision?: string;
6
+ lastRemoteEtag?: string;
7
+ lastFileHashes: Record<string, string>;
8
+ include?: string[];
9
+ exclude?: string[];
10
+ localFields?: string[];
11
+ lastObservedSnapshot?: string;
12
+ lastObservedRevision?: string;
13
+ unresolved?: {
14
+ paths: string[];
15
+ artifact: string;
16
+ }[];
17
+ /** Legacy state fields are read only so v3 can detect and replace stale policy state. */
18
+ syncFiles?: string[];
19
+ syncSessions?: boolean;
20
+ extraFiles?: string[];
21
+ }
22
+ export interface LockFile {
23
+ id: string;
24
+ pid: number;
25
+ command: string;
26
+ startedAt: string;
27
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ import type { AnySyncConfig } from "../settings/settings-types.js";
2
+ import type { SyncState } from "./state-types.js";
3
+ /** Bounded observation token; do not retain the full baseline in passive UI state. */
4
+ export declare function syncStateFingerprint(state: SyncState): string;
5
+ export declare function readState(profile: string): Promise<SyncState>;
6
+ export declare function writeState(profile: string, state: SyncState): Promise<void>;
7
+ export declare function readStateForConfig(config: AnySyncConfig): Promise<SyncState>;
8
+ export declare function writeStateForConfig(config: AnySyncConfig, state: SyncState, snapshot?: import("../snapshot/snapshot-types.js").Snapshot, validate?: () => void): Promise<void>;
9
+ export declare function statePathForConfig(config: AnySyncConfig): string;
10
+ export declare function lockPath(): string;
11
+ export declare function ensureStateDir(): Promise<void>;
@@ -0,0 +1,54 @@
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 { safeName } from "../paths.js";
6
+ import { readJsonIfExists, writeJson } from "./json-file.js";
7
+ import { stateDir } from "./state-directory.js";
8
+ const STATE_VERSION = 2;
9
+ /** Bounded observation token; do not retain the full baseline in passive UI state. */
10
+ export function syncStateFingerprint(state) {
11
+ return createHash("sha256").update(JSON.stringify(state)).digest("hex");
12
+ }
13
+ export async function readState(profile) {
14
+ return ((await readJsonIfExists(statePath(profile))) ?? {
15
+ version: STATE_VERSION,
16
+ profile,
17
+ lastFileHashes: {},
18
+ });
19
+ }
20
+ export async function writeState(profile, state) {
21
+ await writeJson(statePath(profile), state);
22
+ }
23
+ export async function readStateForConfig(config) {
24
+ return ((await readJsonIfExists(statePathForConfig(config))) ?? {
25
+ version: STATE_VERSION,
26
+ profile: config.snapshotIdentity,
27
+ lastFileHashes: {},
28
+ });
29
+ }
30
+ export async function writeStateForConfig(config, state, snapshot, validate = () => { }) {
31
+ validate();
32
+ if (snapshot) {
33
+ const { stageMergeBaseline } = await import("./merge-baseline-store.js");
34
+ validate();
35
+ await stageMergeBaseline(config, snapshot, state);
36
+ validate();
37
+ }
38
+ await writeJson(statePathForConfig(config), state);
39
+ validate();
40
+ }
41
+ export function statePathForConfig(config) {
42
+ const identity = backendIdentityCoordinates(config);
43
+ const hash = createHash("sha256").update(identity).digest("hex").slice(0, 16);
44
+ return path.join(stateDir(), "setups", `${config.backend.type}-${hash}.state.json`);
45
+ }
46
+ function statePath(profile) {
47
+ return path.join(stateDir(), `${safeName(profile)}.state.json`);
48
+ }
49
+ export function lockPath() {
50
+ return path.join(stateDir(), "lock");
51
+ }
52
+ export async function ensureStateDir() {
53
+ await fs.mkdir(stateDir(), { recursive: true });
54
+ }
@@ -0,0 +1,44 @@
1
+ import type { Snapshot, SnapshotFile } from "../snapshot/snapshot-types.js";
2
+ import type { FileMergePlan } from "./file-merge-planner.js";
3
+ export interface AgentUnit {
4
+ id: string;
5
+ path: string;
6
+ kind: "text" | "settings";
7
+ base: string;
8
+ local: string;
9
+ remote: string;
10
+ }
11
+ interface CandidateFile {
12
+ path: string;
13
+ base: string;
14
+ local: string;
15
+ remote: string;
16
+ parts?: (string | AgentUnit)[];
17
+ fields?: {
18
+ id: string;
19
+ key: string;
20
+ }[];
21
+ }
22
+ export interface AgentEvidence {
23
+ units: AgentUnit[];
24
+ files: CandidateFile[];
25
+ unsupported: string[];
26
+ }
27
+ export interface AgentCandidate {
28
+ version: 1;
29
+ results: ({
30
+ id: string;
31
+ content: string;
32
+ } | {
33
+ id: string;
34
+ source: "local" | "remote";
35
+ } | {
36
+ id: string;
37
+ refuse: true;
38
+ })[];
39
+ }
40
+ export declare const digest: (value: unknown) => string;
41
+ export declare function buildAgentEvidence(plan: FileMergePlan, local: Snapshot, remote: Snapshot, ancestors: SnapshotFile[]): AgentEvidence;
42
+ export declare function parseAgentCandidate(raw: string, evidence: AgentEvidence): AgentCandidate;
43
+ export declare function applyAgentCandidate(plan: FileMergePlan, evidence: AgentEvidence, candidate: AgentCandidate): FileMergePlan;
44
+ export {};
@@ -0,0 +1,207 @@
1
+ import { createHash } from "node:crypto";
2
+ import { scanSnapshot } from "../snapshot/snapshot.js";
3
+ import { AGENT_INPUT_BYTES, AGENT_MAX_UNITS, AGENT_OUTPUT_BYTES } from "./agent-policy.js";
4
+ import { snapshotFile } from "./content-conflicts.js";
5
+ import { parseJsonObjectDocument, parseSettingsDocument } from "./json-document.js";
6
+ import { COUPLED_FIELDS, mergeSettingsJson } from "./settings-merge.js";
7
+ import { edits, isMergeTextPath, lines, text } from "./text-merge.js";
8
+ export const digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
9
+ function overlaps(a, b) {
10
+ return a.start === a.end || b.start === b.end
11
+ ? a.start <= b.end && b.start <= a.end
12
+ : a.start < b.end && b.start < a.end;
13
+ }
14
+ /** Only overlapping edit regions are model-writable; all other bytes are assembled by code. */
15
+ function textParts(filePath, baseText, localText, remoteText) {
16
+ const base = lines(baseText);
17
+ const changes = [
18
+ ...edits(base, lines(localText)).map((hunk) => ({ ...hunk, side: "local" })),
19
+ ...edits(base, lines(remoteText)).map((hunk) => ({ ...hunk, side: "remote" })),
20
+ ].sort((a, b) => a.start - b.start || a.end - b.end);
21
+ const clusters = [];
22
+ for (const change of changes) {
23
+ const last = clusters.at(-1);
24
+ if (last?.some((item) => overlaps(item, change)))
25
+ last.push(change);
26
+ else
27
+ clusters.push([change]);
28
+ }
29
+ const result = [];
30
+ let cursor = 0;
31
+ for (const cluster of clusters) {
32
+ const start = Math.min(...cluster.map((item) => item.start));
33
+ const end = Math.max(...cluster.map((item) => item.end));
34
+ result.push(base.slice(cursor, start).join(""));
35
+ const image = (side) => {
36
+ let position = start;
37
+ const output = [];
38
+ for (const hunk of cluster.filter((item) => item.side === side)) {
39
+ output.push(...base.slice(position, hunk.start), ...hunk.lines);
40
+ position = hunk.end;
41
+ }
42
+ return [...output, ...base.slice(position, end)].join("");
43
+ };
44
+ const local = image("local");
45
+ const remote = image("remote");
46
+ const original = base.slice(start, end).join("");
47
+ if (local === remote || local === original || remote === original)
48
+ result.push(local === original ? remote : local);
49
+ else
50
+ result.push({ id: "", path: filePath, kind: "text", base: original, local, remote });
51
+ cursor = end;
52
+ }
53
+ result.push(base.slice(cursor).join(""));
54
+ return result;
55
+ }
56
+ export function buildAgentEvidence(plan, local, remote, ancestors) {
57
+ const evidence = { units: [], files: [], unsupported: [] };
58
+ if (plan.kind !== "planned")
59
+ return evidence;
60
+ if (plan.conflicts.length > AGENT_MAX_UNITS)
61
+ throw new Error("Autonomous sync paused: too many conflict paths for bounded analysis.");
62
+ for (const conflict of plan.conflicts) {
63
+ try {
64
+ if (conflict.reason !== "both-changed")
65
+ throw new Error("unsupported conflict");
66
+ const versions = [ancestors, local.files, remote.files].map((files) => {
67
+ const file = files.find((item) => item.path === conflict.path);
68
+ if (!file)
69
+ throw new Error("missing ancestor/version");
70
+ const bytes = Buffer.from(file.contentBase64, "base64");
71
+ if (bytes.length > 8192)
72
+ throw new Error("file bound");
73
+ return text(bytes);
74
+ });
75
+ const [base, left, right] = versions;
76
+ const file = { path: conflict.path, base, local: left, remote: right };
77
+ let units;
78
+ if (conflict.path === "settings.json") {
79
+ const documents = versions.map((value) => parseSettingsDocument(Buffer.from(value)));
80
+ const merge = mergeSettingsJson(...versions.map((value) => Buffer.from(value)), undefined, true);
81
+ if (merge.kind === "review" && merge.reason !== "field-conflict")
82
+ throw new Error("unsupported settings");
83
+ const fields = new Set(merge.kind === "review" ? merge.fields : []);
84
+ const groups = COUPLED_FIELDS.map((group) => [...group]);
85
+ const coupled = new Set(groups.flat());
86
+ groups.push(...[...fields].filter((key) => !coupled.has(key)).map((key) => [key]));
87
+ file.fields = [];
88
+ units = groups
89
+ .filter((group) => group.some((key) => fields.has(key)))
90
+ .map((group) => {
91
+ const values = documents.map((document) => JSON.stringify(Object.fromEntries(group.flatMap((key) => {
92
+ const node = document.root.members.get(key)?.node;
93
+ return node ? [[key, node.value]] : [];
94
+ }))));
95
+ const unit = {
96
+ id: "",
97
+ path: file.path,
98
+ kind: "settings",
99
+ base: values[0] ?? "{}",
100
+ local: values[1] ?? "{}",
101
+ remote: values[2] ?? "{}",
102
+ };
103
+ file.fields?.push({ id: String(evidence.units.length + file.fields.length), key: group[0] ?? "" });
104
+ return unit;
105
+ });
106
+ }
107
+ else {
108
+ if (!isMergeTextPath(conflict.path))
109
+ throw new Error("unsupported path");
110
+ file.parts = textParts(file.path, base, left, right);
111
+ units = file.parts.filter((part) => typeof part !== "string");
112
+ }
113
+ for (const unit of units) {
114
+ unit.id = String(evidence.units.length);
115
+ evidence.units.push(unit);
116
+ }
117
+ evidence.files.push(file);
118
+ }
119
+ catch {
120
+ evidence.unsupported.push(conflict.path);
121
+ }
122
+ }
123
+ if (evidence.units.length > AGENT_MAX_UNITS || Buffer.byteLength(JSON.stringify(evidence.units)) > AGENT_INPUT_BYTES)
124
+ throw new Error("Autonomous sync paused: conflict evidence exceeds its input bound.");
125
+ // Scan only the actual disclosure image; skipSecretScan never authorizes model disclosure.
126
+ if (scanSnapshot({
127
+ ...local,
128
+ files: evidence.units.flatMap((unit) => [unit.path, unit.base, unit.local, unit.remote].map((value) => snapshotFile(unit.path, Buffer.from(value)))),
129
+ }).length)
130
+ throw new Error("Autonomous sync paused: possible secrets in model evidence; nothing was disclosed.");
131
+ return evidence;
132
+ }
133
+ export function parseAgentCandidate(raw, evidence) {
134
+ if (Buffer.byteLength(raw) > AGENT_OUTPUT_BYTES)
135
+ throw new Error("Agent output exceeds its bound.");
136
+ const parsed = parseJsonObjectDocument(Buffer.from(raw)).root.value;
137
+ if (Object.keys(parsed).sort().join(",") !== "results,version" ||
138
+ parsed.version !== 1 ||
139
+ !Array.isArray(parsed.results) ||
140
+ parsed.results.length !== evidence.units.length)
141
+ throw new Error("Invalid agent candidate contract.");
142
+ const seen = new Set();
143
+ for (const result of parsed.results) {
144
+ if (!result || typeof result !== "object" || Array.isArray(result))
145
+ throw new Error("Invalid agent result.");
146
+ const row = result;
147
+ const unit = evidence.units.find((unit) => unit.id === row.id);
148
+ if (!unit || seen.has(unit.id))
149
+ throw new Error("Unowned or duplicate agent unit.");
150
+ seen.add(unit.id);
151
+ const keys = Object.keys(row).sort().join(",");
152
+ if (keys === "id,refuse" && row.refuse === true)
153
+ continue;
154
+ if (unit.kind === "settings" && keys === "id,source" && (row.source === "local" || row.source === "remote"))
155
+ continue;
156
+ if (unit.kind === "text" && keys === "content,id" && typeof row.content === "string" && row.content.length > 0) {
157
+ text(Buffer.from(row.content));
158
+ if (/^(?:<{7}|={7}|>{7}|\|{7})/mu.test(row.content))
159
+ throw new Error("Unresolved conflict markers.");
160
+ continue;
161
+ }
162
+ throw new Error("Unsupported agent action.");
163
+ }
164
+ return parsed;
165
+ }
166
+ export function applyAgentCandidate(plan, evidence, candidate) {
167
+ // Persisted candidates cross a trust boundary too.
168
+ parseAgentCandidate(JSON.stringify(candidate), evidence);
169
+ if (plan.kind !== "planned")
170
+ throw new Error("Unverified merge plan.");
171
+ const results = new Map(candidate.results.map((row) => [row.id, row]));
172
+ const replacements = new Map();
173
+ for (const file of evidence.files) {
174
+ const units = evidence.units.filter((unit) => unit.path === file.path);
175
+ if (units.some((unit) => results.get(unit.id) && "refuse" in (results.get(unit.id) ?? {})))
176
+ continue;
177
+ let bytes;
178
+ if (file.parts) {
179
+ bytes = Buffer.from(file.parts
180
+ .map((part) => (typeof part === "string" ? part : results.get(part.id).content))
181
+ .join(""));
182
+ }
183
+ else {
184
+ const selections = new Map((file.fields ?? []).map(({ id, key }) => [key, results.get(id).source]));
185
+ const merged = mergeSettingsJson(Buffer.from(file.base), Buffer.from(file.local), Buffer.from(file.remote), selections, true);
186
+ if (merged.kind !== "merged")
187
+ throw new Error("Agent settings units remain unresolved.");
188
+ // The existing renderer/parser retains atomic values, unknown members and exact numeric policy.
189
+ parseSettingsDocument(merged.content);
190
+ for (const { key } of file.fields ?? []) {
191
+ if (!selections.has(key))
192
+ throw new Error("Missing atomic settings selection.");
193
+ }
194
+ bytes = merged.content;
195
+ }
196
+ if (bytes.length > AGENT_OUTPUT_BYTES)
197
+ throw new Error("Agent file exceeds output bound.");
198
+ replacements.set(file.path, snapshotFile(file.path, bytes));
199
+ }
200
+ const decisions = plan.decisions.map((decision) => {
201
+ const file = replacements.get(decision.path);
202
+ return file && decision.kind === "conflict"
203
+ ? { kind: "accepted", path: file.path, source: "merged", file }
204
+ : decision;
205
+ });
206
+ return { kind: "planned", decisions, conflicts: decisions.filter((item) => item.kind === "conflict") };
207
+ }
@@ -0,0 +1,8 @@
1
+ import type { RemoteHead, SyncBackend } from "../backends/sync-backend.js";
2
+ import type { CommandOptions } from "../commands/command-types.js";
3
+ import type { EngineContext as ExtensionContext } from "../host.js";
4
+ import type { AnySyncConfig } from "../settings/settings-types.js";
5
+ import type { Snapshot, SnapshotOptions } from "../snapshot/snapshot-types.js";
6
+ import type { SyncState } from "../state/state-types.js";
7
+ import type { FileMergePlan } from "./file-merge-planner.js";
8
+ export declare function resolveAgentPlan(ctx: ExtensionContext, options: CommandOptions, config: AnySyncConfig, backend: SyncBackend, state: SyncState, local: Snapshot, localRaw: Snapshot, remote: Snapshot, head: RemoteHead, plan: FileMergePlan, snapshotOptions: SnapshotOptions, validate: () => Promise<void>): Promise<FileMergePlan>;
@@ -0,0 +1,84 @@
1
+ import { syncConfigReviewIdentity } from "../settings/config.js";
2
+ import { createSnapshot } from "../snapshot/snapshot.js";
3
+ import { readMergeAncestors } from "../state/merge-baseline-store.js";
4
+ import { readStateForConfig, syncStateFingerprint } from "../state/sync-state-store.js";
5
+ import { applyAgentCandidate, buildAgentEvidence, digest } from "./agent-candidate.js";
6
+ import { AgentResolutionRequired } from "./agent-request.js";
7
+ import { ContinuousError } from "./continuous-errors.js";
8
+ import { fileHashMap, sameHashes } from "./sync-state.js";
9
+ export async function resolveAgentPlan(ctx, options, config, backend, state, local, localRaw, remote, head, plan, snapshotOptions, validate) {
10
+ if (plan.kind !== "planned" || !plan.conflicts.length) {
11
+ if (options.agentRetryRefusal)
12
+ throw new ContinuousError("unsafe", "No eligible cached refusal for the current evidence. Use Sync now.");
13
+ return plan;
14
+ }
15
+ if (!(options.background && ctx.backgroundAuthorized?.(config)) &&
16
+ (!ctx.hasUI || (ctx.mode !== "tui" && ctx.mode !== "rpc")))
17
+ throw new Error("Autonomous sync paused: TUI/RPC is required.");
18
+ const ancestors = (await readMergeAncestors(config, state)) ?? [];
19
+ await validate();
20
+ let evidence;
21
+ try {
22
+ evidence = buildAgentEvidence(plan, local, remote, ancestors);
23
+ }
24
+ catch {
25
+ throw new ContinuousError("unsafe", "Autonomous sync paused: unsafe or unsupported conflict evidence.");
26
+ }
27
+ if (!config.partialSync && evidence.unsupported.length)
28
+ throw new ContinuousError("unsafe", "Autonomous sync paused: unsupported conflicts prevent an all-or-nothing transfer.");
29
+ if (!evidence.files.length) {
30
+ if (options.agentRetryRefusal)
31
+ throw new ContinuousError("unsafe", "No eligible cached refusal for the current evidence. Use Sync now.");
32
+ if (config.partialSync)
33
+ return plan;
34
+ throw new ContinuousError("unsafe", "Autonomous sync paused: unsupported conflict or missing verified ancestor; evidence is unchanged.");
35
+ }
36
+ if (!evidence.units.length) {
37
+ if (options.agentRetryRefusal)
38
+ throw new ContinuousError("unsafe", "No eligible cached refusal for the current evidence. Use Sync now.");
39
+ return applyAgentCandidate(plan, evidence, { version: 1, results: [] });
40
+ }
41
+ if (!ctx.model)
42
+ throw new ContinuousError("model", ctx.modelUnavailableReason ?? "Autonomous sync paused: select an available model first.");
43
+ const model = digest(ctx.model);
44
+ const key = digest([
45
+ 1,
46
+ backend.identity,
47
+ syncConfigReviewIdentity(config),
48
+ syncStateFingerprint(state),
49
+ head.revision,
50
+ fileHashMap(localRaw),
51
+ evidence,
52
+ model,
53
+ ]);
54
+ if (options.agentAcceptance?.key === key) {
55
+ try {
56
+ return applyAgentCandidate(plan, evidence, options.agentAcceptance.candidate);
57
+ }
58
+ catch {
59
+ throw new ContinuousError("unsafe", "Autonomous sync paused: candidate refused or unsupported conflict remains.");
60
+ }
61
+ }
62
+ const validateEvidence = async (signal = options.signal) => {
63
+ const check = async () => {
64
+ signal?.throwIfAborted();
65
+ await validate();
66
+ signal?.throwIfAborted();
67
+ };
68
+ await check();
69
+ if (digest(ctx.model) !== model)
70
+ throw new Error("Autonomous sync paused: selected model changed.");
71
+ const current = await createSnapshot(config.snapshotIdentity, { ...snapshotOptions, signal });
72
+ await check();
73
+ const currentState = await readStateForConfig(config);
74
+ await check();
75
+ const currentHead = await backend.readHead(signal);
76
+ await check();
77
+ if (!sameHashes(fileHashMap(current), fileHashMap(localRaw)) ||
78
+ syncStateFingerprint(currentState) !== syncStateFingerprint(state) ||
79
+ !currentHead ||
80
+ !backend.sameRevision(head.revision, currentHead.revision))
81
+ throw new ContinuousError("stale", "Autonomous sync paused: conflict evidence changed; retry a fresh sync.");
82
+ };
83
+ throw new AgentResolutionRequired(key, evidence, validateEvidence);
84
+ }
@@ -0,0 +1,9 @@
1
+ import type { AnySyncConfig } from "../settings/settings-types.js";
2
+ /** One policy for startup scheduling and commit-time authorization. */
3
+ export declare function startupTransferEnabled(config: Pick<AnySyncConfig, "automaticTransfer" | "agentMode">): boolean;
4
+ export declare const AGENT_TIMEOUT_MS = 20000;
5
+ export declare const AGENT_INPUT_BYTES: number;
6
+ export declare const AGENT_OUTPUT_BYTES: number;
7
+ export declare const AGENT_MAX_TOKENS = 8192;
8
+ export declare const AGENT_MAX_UNITS = 16;
9
+ export declare const AGENT_MAX_ATTEMPTS = 2;