@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,59 @@
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 { getEngineRoot as getAgentDir } from "../host.js";
6
+ import { writeJson } from "../state/json-file.js";
7
+ import { stateDir } from "../state/state-directory.js";
8
+ import { ensureStateDir } from "../state/sync-state-store.js";
9
+ export const CONTINUOUS_RECORD_MAX_BYTES = 131072;
10
+ export function hashContinuous(value) {
11
+ return createHash("sha256")
12
+ .update(JSON.stringify(value) ?? "null")
13
+ .digest("hex");
14
+ }
15
+ export async function continuousBinding(config) {
16
+ return hashContinuous([await fs.realpath(getAgentDir()), config.setupName, backendIdentityCoordinates(config)]);
17
+ }
18
+ export function continuousRoot() {
19
+ return path.join(stateDir(), "continuous");
20
+ }
21
+ export async function prepareContinuousRoot() {
22
+ await ensureStateDir();
23
+ await fs.mkdir(continuousRoot(), { recursive: true, mode: 0o700 });
24
+ await checkContinuousRoot();
25
+ }
26
+ export async function checkContinuousRoot() {
27
+ const stat = await fs.lstat(continuousRoot());
28
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (process.platform !== "win32" && stat.mode & 0o077))
29
+ throw new Error("Unsafe continuous sync directory; evidence retained.");
30
+ }
31
+ export async function readContinuousPrivate(name) {
32
+ return (await readContinuousPrivateDocument(name))?.value;
33
+ }
34
+ /** Read-only metadata; uses the same private-file checks as runtime reads. */
35
+ export async function readContinuousPrivateDocument(name) {
36
+ try {
37
+ await checkContinuousRoot();
38
+ const file = path.join(continuousRoot(), name);
39
+ const stat = await fs.lstat(file);
40
+ if (!stat.isFile() ||
41
+ stat.isSymbolicLink() ||
42
+ stat.nlink !== 1 ||
43
+ stat.size > CONTINUOUS_RECORD_MAX_BYTES ||
44
+ (process.platform !== "win32" && stat.mode & 0o077))
45
+ throw new Error("Unsafe continuous sync record; evidence retained.");
46
+ const bytes = await fs.readFile(file);
47
+ return { value: JSON.parse(bytes.toString("utf8")), bytes: bytes.byteLength };
48
+ }
49
+ catch (error) {
50
+ if (error.code === "ENOENT")
51
+ return undefined;
52
+ throw error;
53
+ }
54
+ }
55
+ export async function writeContinuousPrivate(name, value) {
56
+ await checkContinuousRoot();
57
+ await readContinuousPrivate(name); // Never replace unsafe or malformed evidence.
58
+ await writeJson(path.join(continuousRoot(), name), value, { maxBytes: CONTINUOUS_RECORD_MAX_BYTES });
59
+ }
@@ -0,0 +1,15 @@
1
+ import type { EngineContext as ExtensionContext } from "../host.js";
2
+ import type { AnySyncConfig } from "../settings/settings-types.js";
3
+ import { type StartupTimingPublisher } from "./startup-timings.js";
4
+ import type { SyncLoaders } from "./sync-loaders.js";
5
+ export declare function continuousEnabled(config: Pick<AnySyncConfig, "continuous" | "agentMode">): boolean;
6
+ export interface ContinuousClock {
7
+ now(): number;
8
+ random(): number;
9
+ schedule(ms: number, run: () => void, kind?: "wait" | "authorization"): () => void;
10
+ }
11
+ /** Created on first enabled session. No module/factory-owned timers or watchers. */
12
+ export declare function createContinuousSync(loaders: SyncLoaders, clock?: ContinuousClock, publish?: StartupTimingPublisher): {
13
+ start(ctx: ExtensionContext, sessionSignal: AbortSignal, explicitRetry?: boolean | string, debug?: boolean): void;
14
+ stop(owner?: ExtensionContext["sessionManager"]): Promise<void>;
15
+ };
@@ -0,0 +1,496 @@
1
+ import { loadConfigForCheck, syncCheckConfigFingerprint } from "../settings/config.js";
2
+ import { snapshotOptionsForContext } from "../snapshot/session-paths.js";
3
+ import { withLock } from "../state/lock.js";
4
+ import { withStateDirectoryAccess } from "../state/state-directory.js";
5
+ import { readStateForConfig } from "../state/sync-state-store.js";
6
+ import { setSyncStatus, syncStatusFailureReason } from "../ui/sync-status.js";
7
+ import { withAgentSyncLock } from "./agent-sync.js";
8
+ import { ContinuousError, continuousFailure } from "./continuous-errors.js";
9
+ import { acquireContinuousLease } from "./continuous-lease.js";
10
+ import { normalizeContinuousClock, readContinuousRecord, reserveContinuousRequest, updateContinuousRecord, } from "./continuous-record.js";
11
+ import { continuousBinding, hashContinuous } from "./continuous-storage.js";
12
+ import { watchContinuous } from "./continuous-watch.js";
13
+ import { readMergeJournal } from "./merge-journal.js";
14
+ import { createStartupTimings } from "./startup-timings.js";
15
+ import { captureMutationOwner } from "./sync-local.js";
16
+ import { fileHashMap } from "./sync-state.js";
17
+ export function continuousEnabled(config) {
18
+ return Boolean(config.continuous && config.agentMode);
19
+ }
20
+ const systemClock = {
21
+ now: () => Date.now(),
22
+ random: () => Math.random(),
23
+ schedule: (ms, run) => {
24
+ const timer = setTimeout(run, ms);
25
+ timer.unref?.();
26
+ return () => clearTimeout(timer);
27
+ },
28
+ };
29
+ const LOCAL_CHECK_MS = 5_000;
30
+ const POLL_MS = 60_000;
31
+ const DEBOUNCE_MS = 1_000;
32
+ /** Created on first enabled session. No module/factory-owned timers or watchers. */
33
+ export function createContinuousSync(loaders, clock = systemClock, publish) {
34
+ const startups = new WeakMap();
35
+ const repairNotices = new WeakSet();
36
+ let task;
37
+ return {
38
+ // A setup name binds retry to the configuration loaded after asynchronous eligibility checks.
39
+ start(ctx, sessionSignal, explicitRetry = false, debug = false) {
40
+ if ((!ctx.backgroundAuthorized?.() && (!ctx.hasUI || (ctx.mode !== "tui" && ctx.mode !== "rpc"))) ||
41
+ sessionSignal.aborted ||
42
+ task)
43
+ return;
44
+ const controller = new AbortController();
45
+ const signal = AbortSignal.any([sessionSignal, controller.signal]);
46
+ const validateContext = captureMutationOwner(ctx);
47
+ // The caller supplies the session-start debug value, including first activation after settings edits.
48
+ const previousStartup = startups.get(ctx.sessionManager);
49
+ const startup = previousStartup?.signal === sessionSignal ? previousStartup : { signal: sessionSignal, debug, reported: false };
50
+ startups.set(ctx.sessionManager, startup);
51
+ const current = {
52
+ owner: ctx.sessionManager,
53
+ controller,
54
+ promise: Promise.resolve(),
55
+ clear: () => {
56
+ try {
57
+ validateContext();
58
+ setSyncStatus(ctx, undefined);
59
+ }
60
+ catch {
61
+ /* replaced session */
62
+ }
63
+ },
64
+ };
65
+ task = current;
66
+ current.promise = (async () => {
67
+ let explicit = explicitRetry;
68
+ while (!signal.aborted) {
69
+ try {
70
+ await run(ctx, signal, explicit, startup);
71
+ return;
72
+ }
73
+ catch {
74
+ if (signal.aborted)
75
+ return;
76
+ try {
77
+ validateContext();
78
+ setSyncStatus(ctx, "sync blocked: private state or settings need repair", {
79
+ activity: "blocked",
80
+ reason: "repair",
81
+ });
82
+ if (!repairNotices.has(ctx.sessionManager)) {
83
+ repairNotices.add(ctx.sessionManager);
84
+ ctx.ui.notify("Continuous sync blocked: private state or settings need repair. Use /sync. Evidence was retained.", "warning");
85
+ }
86
+ }
87
+ catch {
88
+ return;
89
+ }
90
+ }
91
+ explicit = false;
92
+ // Only local prerequisites are retried here. No remote/model request can
93
+ // pass a malformed settings/state read. A repair can resume monitoring.
94
+ await wait(clock, LOCAL_CHECK_MS, signal);
95
+ }
96
+ })()
97
+ .catch(() => {
98
+ /* Cancellation/UI disposal must not leak a detached rejection. */
99
+ })
100
+ .finally(() => {
101
+ if (task === current)
102
+ task = undefined;
103
+ });
104
+ },
105
+ async stop(owner) {
106
+ const current = task;
107
+ if (!current || (owner && current.owner !== owner))
108
+ return;
109
+ current.controller.abort(new DOMException("Continuous sync interrupted", "AbortError"));
110
+ current.clear();
111
+ await current.promise;
112
+ },
113
+ };
114
+ async function run(ctx, signal, explicitRetry, startup) {
115
+ const validateOwner = captureMutationOwner(ctx, signal);
116
+ try {
117
+ while (!signal.aborted) {
118
+ validateOwner();
119
+ const config = await loadConfigForCheck();
120
+ validateOwner();
121
+ if (!continuousEnabled(config) || (ctx.backgroundAuthorized && !ctx.backgroundAuthorized(config)))
122
+ return;
123
+ try {
124
+ if (ctx.isIdle()) {
125
+ let lease;
126
+ let binding = "";
127
+ try {
128
+ await withStateDirectoryAccess(async () => {
129
+ validateOwner();
130
+ binding = await continuousBinding(config);
131
+ validateOwner();
132
+ lease = await acquireContinuousLease(binding);
133
+ validateOwner();
134
+ });
135
+ if (lease) {
136
+ const retry = typeof explicitRetry === "string" ? explicitRetry === config.setupName : explicitRetry;
137
+ await monitor(ctx, config, binding, lease, signal, retry, startup);
138
+ explicitRetry = false;
139
+ }
140
+ else
141
+ setSyncStatus(ctx, "sync waiting: another local owner", { activity: "idle" });
142
+ }
143
+ finally {
144
+ await lease?.release();
145
+ }
146
+ }
147
+ }
148
+ catch (error) {
149
+ if (signal.aborted)
150
+ return;
151
+ const failure = continuousFailure(error);
152
+ if (!failure.retry && !(error instanceof Error && error.name === "AbortError"))
153
+ throw error;
154
+ setSyncStatus(ctx, `sync retry scheduled: ${failure.kind}`, {
155
+ activity: "retry",
156
+ reason: syncStatusFailureReason(failure.kind),
157
+ });
158
+ }
159
+ validateOwner();
160
+ const current = await loadConfigForCheck();
161
+ if (!continuousEnabled(current) || (ctx.backgroundAuthorized && !ctx.backgroundAuthorized(current)))
162
+ return;
163
+ validateOwner();
164
+ await wait(clock, LOCAL_CHECK_MS, signal);
165
+ }
166
+ }
167
+ finally {
168
+ // Shutdown/replacement owns clearing the old UI; do not call it from a stale continuation.
169
+ if (!signal.aborted) {
170
+ try {
171
+ validateOwner();
172
+ setSyncStatus(ctx, undefined);
173
+ }
174
+ catch {
175
+ /* stale context */
176
+ }
177
+ }
178
+ }
179
+ }
180
+ async function monitor(ctx, initial, binding, lease, parent, explicitRetry, startup) {
181
+ const signal = AbortSignal.any([parent, lease.signal]);
182
+ const validateOwner = captureMutationOwner(ctx, signal);
183
+ let config = initial;
184
+ let closeWatch = () => { };
185
+ let wake = () => { };
186
+ let dirtyAt;
187
+ let cycle;
188
+ const changed = (settings) => {
189
+ dirtyAt = clock.now();
190
+ if (settings)
191
+ cycle?.abort(new DOMException("Continuous settings changed", "AbortError"));
192
+ wake();
193
+ };
194
+ const validate = () => {
195
+ validateOwner();
196
+ lease.assert();
197
+ if (!ctx.isIdle())
198
+ throw new DOMException("Owning session became busy", "AbortError");
199
+ };
200
+ const stopWatch = () => {
201
+ closeWatch();
202
+ wake();
203
+ };
204
+ signal.addEventListener("abort", stopWatch, { once: true });
205
+ let pollDue = 0;
206
+ try {
207
+ closeWatch = await watchContinuous(config, changed);
208
+ validate();
209
+ while (!signal.aborted && ctx.isIdle()) {
210
+ validate();
211
+ const latest = await loadConfigForCheck();
212
+ validate();
213
+ if (!continuousEnabled(latest) ||
214
+ (ctx.backgroundAuthorized && !ctx.backgroundAuthorized(latest)) ||
215
+ (await continuousBinding(latest)) !== binding)
216
+ return;
217
+ validate();
218
+ if (syncCheckConfigFingerprint(latest) !== syncCheckConfigFingerprint(config)) {
219
+ closeWatch();
220
+ config = latest;
221
+ closeWatch = await watchContinuous(config, changed);
222
+ validate();
223
+ pollDue = 0;
224
+ }
225
+ const record = await readContinuousRecord(binding);
226
+ validate();
227
+ const now = clock.now();
228
+ const oldClock = JSON.stringify([record.next, record.calls]);
229
+ normalizeContinuousClock(record, now);
230
+ if (oldClock !== JSON.stringify([record.next, record.calls])) {
231
+ await updateContinuousRecord(binding, lease, (current) => normalizeContinuousClock(current, now));
232
+ validate();
233
+ }
234
+ const configuration = hashContinuous([{ ...config, showStatus: undefined, debug: undefined }, ctx.model]);
235
+ const controlChanged = record.configuration !== configuration;
236
+ if (controlChanged || explicitRetry) {
237
+ record.next = 0;
238
+ pollDue = 0;
239
+ }
240
+ const hintDue = dirtyAt === undefined ? Number.POSITIVE_INFINITY : dirtyAt + DEBOUNCE_MS;
241
+ const due = Math.max(record.error === "budget" ? 0 : record.next, Math.min(pollDue, hintDue));
242
+ if (now >= due) {
243
+ const timings = createStartupTimings(publish);
244
+ const report = !startup.reported && startup.debug;
245
+ startup.reported = true;
246
+ let outcome = "stopped";
247
+ const force = explicitRetry || controlChanged;
248
+ explicitRetry = false;
249
+ const expectedModel = hashContinuous(ctx.model);
250
+ const expectedConfig = syncCheckConfigFingerprint(config);
251
+ dirtyAt = undefined;
252
+ cycle = new AbortController();
253
+ const cancelDeadline = clock.schedule(30_000, () => cycle?.abort(new DOMException("Continuous cycle timed out", "TimeoutError")));
254
+ const guard = new AbortController();
255
+ const guardSignal = AbortSignal.any([signal, cycle.signal, guard.signal]);
256
+ const activeCycle = cycle;
257
+ // Transfer entrypoints supply each fresh settings read. Never let a new
258
+ // transfer adopt authorization that changed after this cycle's inspection.
259
+ const validateCycle = (latest) => {
260
+ validate();
261
+ if ((latest && syncCheckConfigFingerprint(latest) !== expectedConfig) ||
262
+ hashContinuous(ctx.model) !== expectedModel)
263
+ activeCycle.abort(new DOMException("Continuous authorization changed", "AbortError"));
264
+ activeCycle.signal.throwIfAborted();
265
+ };
266
+ const guardTask = (async () => {
267
+ while (!guardSignal.aborted) {
268
+ await wait(clock, LOCAL_CHECK_MS, guardSignal, undefined, "authorization");
269
+ if (guardSignal.aborted)
270
+ return;
271
+ try {
272
+ validate();
273
+ const latest = await loadConfigForCheck();
274
+ if (guardSignal.aborted)
275
+ return;
276
+ validateCycle(latest);
277
+ }
278
+ catch {
279
+ activeCycle.abort(new DOMException("Continuous authorization unavailable", "AbortError"));
280
+ }
281
+ }
282
+ })().catch(() => { });
283
+ try {
284
+ await performCycle(ctx, config, binding, lease, AbortSignal.any([signal, cycle.signal]), validateCycle, configuration, force, timings);
285
+ outcome = "completed";
286
+ }
287
+ catch (error) {
288
+ if (signal.aborted || !ctx.isIdle())
289
+ return;
290
+ // A settings hint interrupts the old authorization; load it afresh, not as a failed transfer.
291
+ if (cycle.signal.aborted && cycle.signal.reason?.name !== "TimeoutError") {
292
+ pollDue = 0;
293
+ continue;
294
+ }
295
+ const failure = continuousFailure(error);
296
+ let announce = false;
297
+ await updateContinuousRecord(binding, lease, (current) => {
298
+ const now = clock.now();
299
+ normalizeContinuousClock(current, now);
300
+ const notice = hashContinuous([failure.kind, current.evidence, configuration]);
301
+ announce = current.notice !== notice;
302
+ if (!failure.retry)
303
+ current.notice = notice;
304
+ current.configuration = configuration;
305
+ current.pending = true;
306
+ current.error = failure.kind;
307
+ current.phase = failure.retry ? "retry" : "blocked";
308
+ current.failures = Math.min(30, current.failures + 1);
309
+ const base = Math.min(300_000, 5_000 * 2 ** Math.min(6, current.failures - 1));
310
+ const delay = Math.min(300_000, base + Math.floor(clock.random() * base * 0.2));
311
+ current.next = now + Math.max(delay, failure.delay ?? 0);
312
+ });
313
+ validate();
314
+ if (announce && !failure.retry)
315
+ ctx.ui.notify(`Continuous sync blocked (${failure.kind}). Review /sync or repair the setup. Evidence was retained.`, "warning");
316
+ }
317
+ finally {
318
+ cancelDeadline();
319
+ guard.abort();
320
+ await guardTask;
321
+ cycle = undefined;
322
+ timings.publish(ctx, report, signal, "continuous startup", outcome);
323
+ }
324
+ pollDue = clock.now() + POLL_MS + Math.floor(clock.random() * 6_000);
325
+ closeWatch();
326
+ closeWatch = () => { };
327
+ closeWatch = await watchContinuous(config, changed);
328
+ validate();
329
+ }
330
+ validate();
331
+ const state = await readContinuousRecord(binding);
332
+ validate();
333
+ setSyncStatus(ctx, state.phase === "blocked"
334
+ ? `sync blocked: ${state.error}`
335
+ : state.phase === "retry"
336
+ ? `sync retry scheduled: ${state.error}`
337
+ : "sync waiting for changes", state.phase === "blocked" || state.phase === "retry"
338
+ ? { activity: state.phase, reason: syncStatusFailureReason(state.error) }
339
+ : { activity: "idle" });
340
+ if (state.phase === "retry")
341
+ pollDue = Math.min(pollDue, state.next);
342
+ const next = Math.max(state.error === "budget" ? 0 : state.next, Math.min(pollDue, dirtyAt === undefined ? Number.POSITIVE_INFINITY : dirtyAt + DEBOUNCE_MS));
343
+ await wait(clock, Math.max(1, Math.min(LOCAL_CHECK_MS, next - clock.now())), signal, (callback) => {
344
+ wake = callback;
345
+ });
346
+ }
347
+ }
348
+ finally {
349
+ signal.removeEventListener("abort", stopWatch);
350
+ closeWatch();
351
+ cycle?.abort();
352
+ }
353
+ }
354
+ async function performCycle(ctx, config, binding, lease, signal, validateOwner, configuration, force, timings) {
355
+ const validate = (latest) => {
356
+ signal.throwIfAborted();
357
+ validateOwner(latest);
358
+ };
359
+ validate();
360
+ const current = await readContinuousRecord(binding);
361
+ validate();
362
+ // A newly pending journal may prove an uncertain commit. It is never authority to republish.
363
+ const pending = await guardedLock("continuous-journal", () => readMergeJournal(config));
364
+ validate();
365
+ if (!force &&
366
+ !pending &&
367
+ current.phase === "blocked" &&
368
+ ["authentication", "storage", "unknown"].includes(current.error ?? ""))
369
+ return;
370
+ setSyncStatus(ctx, "sync checking", { activity: "checking" });
371
+ const inspectionModule = await timings.measure("inspection import", () => loaders.inspection());
372
+ validate();
373
+ const observed = await timings.measure("inspection and guards", () => guardedLock("continuous-check", async () => {
374
+ validate();
375
+ const inspection = await inspectionModule.inspectSync(config, snapshotOptionsForContext(ctx, config), signal, undefined, timings);
376
+ validate();
377
+ let localIdentity = inspection.localIdentity;
378
+ if (!localIdentity) {
379
+ const snapshotModule = await loaders.snapshot();
380
+ validate();
381
+ const local = await snapshotModule.createSnapshot(config.snapshotIdentity, {
382
+ ...snapshotOptionsForContext(ctx, config),
383
+ signal,
384
+ });
385
+ validate();
386
+ localIdentity = hashContinuous(fileHashMap(local));
387
+ }
388
+ const journal = await readMergeJournal(config);
389
+ validate();
390
+ return { inspection, journal, localIdentity };
391
+ }));
392
+ validate();
393
+ const evidence = hashContinuous([
394
+ configuration,
395
+ observed.localIdentity,
396
+ observed.inspection.head?.revision,
397
+ observed.inspection.stateIdentity,
398
+ ]);
399
+ const recovery = observed.journal ? hashContinuous([evidence, observed.journal]) : undefined;
400
+ const blocked = !force &&
401
+ current.evidence === evidence &&
402
+ ((current.phase === "blocked" && (!recovery || recovery === current.recovery)) ||
403
+ (current.error === "budget" && current.next > clock.now() && !observed.journal));
404
+ await updateContinuousRecord(binding, lease, (record) => {
405
+ if (record.configuration !== configuration) {
406
+ record.failures = 0;
407
+ record.next = 0;
408
+ }
409
+ record.configuration = configuration;
410
+ record.checked = clock.now();
411
+ record.evidence = evidence;
412
+ if (!blocked) {
413
+ if (record.phase !== "blocked")
414
+ record.phase = "syncing";
415
+ record.pending = true;
416
+ if (recovery)
417
+ record.recovery = recovery;
418
+ }
419
+ });
420
+ validate();
421
+ if (blocked)
422
+ return;
423
+ if (!observed.journal &&
424
+ (observed.inspection.firstSync ||
425
+ !observed.inspection.head ||
426
+ observed.inspection.selectionState?.kind !== "same"))
427
+ throw new ContinuousError("unsafe", "Continuous sync needs an accepted baseline and matching remote selection.");
428
+ let transferred = false;
429
+ if (observed.journal || observed.inspection.localChanged || observed.inspection.remoteChanged) {
430
+ const operations = await timings.measure("operations import", () => loaders.operations());
431
+ validate();
432
+ setSyncStatus(ctx, "sync syncing", { activity: "working" });
433
+ const result = await timings.measure("automatic transfer", () => withStateDirectoryAccess(() => withAgentSyncLock(ctx, {
434
+ args: [],
435
+ yes: true,
436
+ force: false,
437
+ stale: false,
438
+ silent: true,
439
+ reload: false,
440
+ auto: true,
441
+ signal,
442
+ startupTimings: timings,
443
+ background: {
444
+ validate,
445
+ reserve: (key, requestSignal) => reserveContinuousRequest(binding, lease, key, () => clock.now(), requestSignal),
446
+ },
447
+ }, (options) => operations.syncBoth(ctx, options))));
448
+ validate();
449
+ transferred = result === "applied";
450
+ }
451
+ const state = await guardedLock("continuous-result", () => readStateForConfig(config));
452
+ validate();
453
+ const unresolved = state.unresolved;
454
+ let announcePartial = false;
455
+ await updateContinuousRecord(binding, lease, (record) => {
456
+ record.phase = unresolved?.length ? "blocked" : "waiting";
457
+ record.pending = Boolean(unresolved?.length);
458
+ record.failures = 0;
459
+ record.next = 0;
460
+ if (unresolved?.length) {
461
+ record.error = "unsafe";
462
+ const notice = hashContinuous(["partial", unresolved, configuration]);
463
+ announcePartial = record.notice !== notice;
464
+ record.notice = notice;
465
+ }
466
+ else {
467
+ delete record.error;
468
+ delete record.notice;
469
+ }
470
+ if (transferred)
471
+ record.transferred = clock.now();
472
+ });
473
+ validate();
474
+ if (announcePartial)
475
+ ctx.ui.notify("Continuous sync retained unresolved groups. Review /sync conflicts; independent partial progress was preserved.", "warning");
476
+ }
477
+ }
478
+ function guardedLock(command, run) {
479
+ return withStateDirectoryAccess(() => withLock(command, run));
480
+ }
481
+ function wait(clock, ms, signal, expose, kind = "wait") {
482
+ signal.throwIfAborted();
483
+ return new Promise((resolve) => {
484
+ const done = () => {
485
+ cancel();
486
+ signal.removeEventListener("abort", done);
487
+ expose?.(() => { });
488
+ resolve();
489
+ };
490
+ const cancel = clock.schedule(ms, done, kind);
491
+ signal.addEventListener("abort", done, { once: true });
492
+ expose?.(done);
493
+ if (signal.aborted)
494
+ done();
495
+ });
496
+ }
@@ -0,0 +1,3 @@
1
+ import type { AnySyncConfig } from "../settings/settings-types.js";
2
+ /** Hints only. The scheduler's periodic snapshot scan remains required. */
3
+ export declare function watchContinuous(config: AnySyncConfig, changed: (settings: boolean) => void): Promise<() => void>;
@@ -0,0 +1,65 @@
1
+ import { watch } from "node:fs";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { getEngineRoot as getAgentDir } from "../host.js";
5
+ import { isDeniedPath, toPosix } from "../paths.js";
6
+ import { compileSyncExclude } from "./exclude-policy.js";
7
+ /** Hints only. The scheduler's periodic snapshot scan remains required. */
8
+ export async function watchContinuous(config, changed) {
9
+ const root = getAgentDir();
10
+ const watchers = [];
11
+ const excluded = compileSyncExclude(config.exclude);
12
+ const selected = config.include.map((item) => path.resolve(root, item));
13
+ const relevant = (target) => selected.some((item) => target === item || target.startsWith(`${item}${path.sep}`) || item.startsWith(`${target}${path.sep}`));
14
+ const add = (directory, recursive) => {
15
+ try {
16
+ const watcher = watch(directory, { recursive, persistent: false }, (_event, file) => {
17
+ // Unknown names can be our own private writes. Periodic scans cover them.
18
+ if (!file)
19
+ return;
20
+ const target = path.resolve(directory, String(file));
21
+ if (target === path.join(root, "pi-sync.json"))
22
+ changed(true);
23
+ else if (isDeniedPath(path.relative(root, target)))
24
+ return;
25
+ else if (!excluded(toPosix(path.relative(root, target))) && relevant(target))
26
+ changed(false);
27
+ });
28
+ watcher.on("error", () => watcher.close());
29
+ watchers.push(watcher);
30
+ }
31
+ catch {
32
+ /* Periodic scans cover unavailable or unsupported watchers. */
33
+ }
34
+ };
35
+ add(root, false);
36
+ const directories = new Set();
37
+ try {
38
+ for (const target of selected) {
39
+ try {
40
+ const stat = await fs.lstat(target);
41
+ if (stat.isSymbolicLink())
42
+ continue;
43
+ const directory = stat.isDirectory() ? target : path.dirname(target);
44
+ if (directory === root || directories.has(directory))
45
+ continue;
46
+ directories.add(directory);
47
+ add(directory, stat.isDirectory());
48
+ }
49
+ catch (error) {
50
+ if (error.code !== "ENOENT")
51
+ continue;
52
+ // Missing targets are found by the parent hint or the next periodic scan.
53
+ }
54
+ }
55
+ return () => {
56
+ for (const watcher of watchers)
57
+ watcher.close();
58
+ };
59
+ }
60
+ catch (error) {
61
+ for (const watcher of watchers)
62
+ watcher.close();
63
+ throw error;
64
+ }
65
+ }
@@ -0,0 +1,5 @@
1
+ /** Exclusions are a set; keep spelling for exact reviews, not filesystem lookup. */
2
+ export declare function normalizeSyncExclude(value: unknown): string[];
3
+ export declare function sameSyncExclude(left: unknown, right: unknown): boolean;
4
+ /** Compile at the operation boundary and reuse for every file/directory. */
5
+ export declare function compileSyncExclude(value: unknown): (relativePath: string) => boolean;