@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,48 @@
1
+ export interface SnapshotFile {
2
+ path: string;
3
+ contentBase64: string;
4
+ sha256: string;
5
+ }
6
+ export type SnapshotSelection = {
7
+ version: 1;
8
+ include: string[];
9
+ exclude?: never;
10
+ } | {
11
+ version: 2;
12
+ include: string[];
13
+ exclude: string[];
14
+ };
15
+ export interface Snapshot {
16
+ version: number;
17
+ id: string;
18
+ createdAt: string;
19
+ machine: string;
20
+ /** Backend-scoped remote identity retained in the snapshot wire format. */
21
+ profile: string;
22
+ syncSessions?: boolean;
23
+ /** Portable, credential-free included-content intent. Absent on legacy snapshots. */
24
+ selection?: SnapshotSelection;
25
+ localFields?: string[];
26
+ files: SnapshotFile[];
27
+ }
28
+ export interface SnapshotOptions {
29
+ signal?: AbortSignal;
30
+ /** Caller-owned session/generation guard, rechecked at file-mutation boundaries. */
31
+ validateMutation?: () => void;
32
+ /** Reviewed regular-file preimages; null means the path was absent. Checked under mutation queues. */
33
+ expectedFileHashes?: Readonly<Record<string, string | null>>;
34
+ include?: string[];
35
+ exclude?: string[];
36
+ sessionDir?: string;
37
+ /** Temporary internal projections while snapshot storage remains wire-compatible. */
38
+ syncFiles?: string[];
39
+ syncSessions?: boolean;
40
+ extraFiles?: string[];
41
+ }
42
+ export interface SnapshotApplyPlan {
43
+ writes: Array<{
44
+ target: string;
45
+ content: Buffer;
46
+ }>;
47
+ deletes: string[];
48
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,30 @@
1
+ export { isDeniedPath } from "../paths.js";
2
+ export { sessionStorageRoot } from "./snapshot-paths.js";
3
+ import { type SyncSelectionConfig } from "../sync/sync-policy.js";
4
+ import type { Snapshot, SnapshotFile, SnapshotOptions } from "./snapshot-types.js";
5
+ export { canonicalSnapshotPathForConfig, isConfiguredSnapshotPath } from "../sync/sync-policy.js";
6
+ export declare function regenerateSnapshotIdentity(snapshot: Snapshot): Snapshot;
7
+ export declare function createSnapshot(profile: string, options?: SnapshotOptions): Promise<Snapshot>;
8
+ export declare function collectFiles(root: string, options?: SnapshotOptions, excluded?: (relativePath: string) => boolean): Promise<SnapshotFile[]>;
9
+ export declare function isSessionPath(relativePath: string): boolean;
10
+ export declare function isSessionFilePath(relativePath: string): boolean;
11
+ export declare function sessionSnapshotPathFromAbsolute(sessionFile: string, configuredSessionDir?: string): string | undefined;
12
+ export declare function snapshotTarget(root: string, relativePath: string, configuredSessionDir?: string): string;
13
+ export declare function snapshotIncludesSessions(snapshot: Snapshot): boolean;
14
+ export declare function filterSnapshotForConfigPolicy(snapshot: Snapshot, config: SyncSelectionConfig, options?: {
15
+ regenerateId?: boolean;
16
+ }): {
17
+ id: string;
18
+ createdAt: string;
19
+ machine: string;
20
+ profile: string;
21
+ localFields?: string[];
22
+ version: number;
23
+ syncSessions: boolean | undefined;
24
+ selection: import("./snapshot-types.js").SnapshotSelection;
25
+ files: SnapshotFile[];
26
+ };
27
+ export declare function snapshotWithoutSessions(snapshot: Snapshot): Snapshot;
28
+ export declare function scanSnapshot(snapshot: Snapshot): string[];
29
+ export declare function mergeRemotePreservedFiles(local: Snapshot, remote: Snapshot, config: SyncSelectionConfig): Snapshot;
30
+ export declare function mergeRemoteSessionFiles(local: Snapshot, remote: Snapshot): Snapshot;
@@ -0,0 +1,364 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { isDeniedPath, posixJoin, safeJoin, toPosix } from "../paths.js";
6
+ import { agentDir, configuredSessionDir } from "./session-paths.js";
7
+ import { sessionStorageRoot } from "./snapshot-paths.js";
8
+ export { isDeniedPath } from "../paths.js";
9
+ export { sessionStorageRoot } from "./snapshot-paths.js";
10
+ import { compileSyncExclude } from "../sync/exclude-policy.js";
11
+ import { canonicalSnapshotPathForConfig, configuredSnapshotPathMatcher, customIncludePathsByLower, DEFAULT_SYNC_INCLUDE, includeFromSelectionConfig, isPreservableUnmanagedSnapshotPath, normalizeExtraFiles, normalizeSyncFiles, sameSnapshotSelection, selectionForSnapshot, snapshotSelectionExclude, snapshotSelectionInclude, syncIncludeSelection, } from "../sync/sync-policy.js";
12
+ export { canonicalSnapshotPathForConfig, isConfiguredSnapshotPath } from "../sync/sync-policy.js";
13
+ const VERSION = 1;
14
+ const TOP_LEVEL_FILES = DEFAULT_SYNC_INCLUDE.filter((name) => name.includes("."));
15
+ const TOP_LEVEL_DIRS = new Set(DEFAULT_SYNC_INCLUDE.filter((name) => !name.includes(".")));
16
+ const SECRET_PATTERNS = [
17
+ /AWS_SECRET_ACCESS_KEY\s*[=:]\s*['"]?[A-Za-z0-9/+]{35,}/i,
18
+ /(ANTHROPIC|OPENAI|GEMINI|GOOGLE|FIRECRAWL|GITHUB|CLOUDFLARE|R2|S3)_[A-Z0-9_]*(KEY|TOKEN|SECRET)\s*[=:]\s*['"]?[^\s'"]{12,}/i,
19
+ /sk-ant-[A-Za-z0-9_-]{20,}/,
20
+ /sk-[A-Za-z0-9]{20,}/,
21
+ /gh[pousr]_[A-Za-z0-9_]{20,}/,
22
+ ];
23
+ function selectTopLevelFileEntry(entries, fileName) {
24
+ const exact = entries.find((entry) => entry.isFile() && entry.name === fileName);
25
+ if (exact)
26
+ return exact;
27
+ const lower = fileName.toLowerCase();
28
+ return entries
29
+ .filter((entry) => entry.isFile() && entry.name.toLowerCase() === lower)
30
+ .sort((left, right) => left.name.localeCompare(right.name))[0];
31
+ }
32
+ function sha256(value) {
33
+ return createHash("sha256").update(value).digest("hex");
34
+ }
35
+ function isSafeSnapshotPath(relativePath) {
36
+ if (relativePath.includes("\\"))
37
+ return false;
38
+ const normalized = toPosix(relativePath);
39
+ return (Boolean(normalized) &&
40
+ normalized !== "." &&
41
+ normalized !== ".." &&
42
+ !normalized.startsWith("../") &&
43
+ !path.posix.isAbsolute(normalized) &&
44
+ path.posix.normalize(normalized) === normalized &&
45
+ !isDeniedPath(normalized));
46
+ }
47
+ function snapshotsMatch(left, right) {
48
+ const leftHashes = new Map(left.files.map((file) => [file.path, file.sha256]));
49
+ const rightHashes = new Map(right.files.map((file) => [file.path, file.sha256]));
50
+ return (left.syncSessions === right.syncSessions &&
51
+ sameSnapshotSelection(left.selection, right.selection) &&
52
+ leftHashes.size === rightHashes.size &&
53
+ [...leftHashes].every(([filePath, hash]) => rightHashes.get(filePath) === hash));
54
+ }
55
+ function snapshotId() {
56
+ return `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID().slice(0, 8)}`;
57
+ }
58
+ export function regenerateSnapshotIdentity(snapshot) {
59
+ return {
60
+ ...snapshot,
61
+ id: snapshotId(),
62
+ createdAt: new Date().toISOString(),
63
+ machine: os.hostname(),
64
+ };
65
+ }
66
+ export async function createSnapshot(profile, options = {}) {
67
+ options.signal?.throwIfAborted();
68
+ const include = effectiveInclude(options);
69
+ const excluded = compileSyncExclude(options.exclude);
70
+ const syncSessions = include.includes("sessions") && !excluded("sessions");
71
+ const needsSessionConfig = syncSessions || !excluded("settings.json");
72
+ const sessionDir = options.sessionDir ?? (needsSessionConfig ? await configuredSessionDir() : undefined);
73
+ options.signal?.throwIfAborted();
74
+ const files = await collectFiles(agentDir(), {
75
+ include,
76
+ exclude: options.exclude,
77
+ sessionDir,
78
+ signal: options.signal,
79
+ }, excluded);
80
+ options.signal?.throwIfAborted();
81
+ return {
82
+ version: options.exclude === undefined ? VERSION : 4,
83
+ id: snapshotId(),
84
+ createdAt: new Date().toISOString(),
85
+ machine: os.hostname(),
86
+ profile,
87
+ syncSessions,
88
+ selection: selectionForSnapshot(include, options.exclude),
89
+ files,
90
+ };
91
+ }
92
+ function effectiveInclude(options) {
93
+ if (options.include)
94
+ return options.include;
95
+ return [
96
+ ...normalizeSyncFiles(options.syncFiles),
97
+ ...normalizeExtraFiles(options.extraFiles),
98
+ ...(options.syncSessions ? ["sessions"] : []),
99
+ ];
100
+ }
101
+ export async function collectFiles(root, options = {}, excluded = compileSyncExclude(options.exclude)) {
102
+ const signal = options.signal;
103
+ signal?.throwIfAborted();
104
+ const results = [];
105
+ const entries = await fs.readdir(root, { withFileTypes: true });
106
+ signal?.throwIfAborted();
107
+ const selection = syncIncludeSelection(effectiveInclude(options));
108
+ const selectedFiles = new Set(selection.builtIns);
109
+ for (const entry of entries) {
110
+ if (entry.isDirectory() &&
111
+ TOP_LEVEL_DIRS.has(entry.name) &&
112
+ selectedFiles.has(entry.name) &&
113
+ !excluded(entry.name)) {
114
+ await collectDirectory(results, root, entry.name, { signal, excluded });
115
+ }
116
+ }
117
+ for (const fileName of TOP_LEVEL_FILES) {
118
+ if (!selectedFiles.has(fileName) || excluded(fileName))
119
+ continue;
120
+ const entry = selectTopLevelFileEntry(entries, fileName);
121
+ if (entry)
122
+ await addFile(results, root, entry.name, fileName, signal);
123
+ }
124
+ for (const relativePath of selection.custom) {
125
+ if (!excluded(relativePath))
126
+ await collectIncludedPath(results, root, relativePath, signal, excluded);
127
+ }
128
+ if (selection.sessions && !excluded("sessions")) {
129
+ try {
130
+ await collectDirectory(results, sessionStorageRoot(root, options.sessionDir), "", {
131
+ sessionsOnly: true,
132
+ excluded,
133
+ virtualPrefix: "sessions",
134
+ signal,
135
+ });
136
+ }
137
+ catch (error) {
138
+ if (error.code !== "ENOENT")
139
+ throw error;
140
+ }
141
+ }
142
+ signal?.throwIfAborted();
143
+ return results.sort((left, right) => left.path.localeCompare(right.path));
144
+ }
145
+ async function collectIncludedPath(results, root, relativePath, signal, excluded) {
146
+ signal?.throwIfAborted();
147
+ const absolutePath = safeJoin(root, relativePath);
148
+ try {
149
+ const stat = await fs.lstat(absolutePath);
150
+ signal?.throwIfAborted();
151
+ if (stat.isFile())
152
+ await addFile(results, root, relativePath, relativePath, signal);
153
+ else if (stat.isDirectory())
154
+ await collectDirectory(results, root, relativePath, { signal, excluded });
155
+ }
156
+ catch (error) {
157
+ if (error.code !== "ENOENT")
158
+ throw error;
159
+ if (!relativePath.includes("/")) {
160
+ const entries = await fs.readdir(root, { withFileTypes: true });
161
+ signal?.throwIfAborted();
162
+ const entry = selectTopLevelFileEntry(entries, relativePath);
163
+ if (entry)
164
+ await addFile(results, root, entry.name, relativePath, signal);
165
+ }
166
+ }
167
+ }
168
+ async function collectDirectory(results, root, relativeDirectory, options = {}) {
169
+ options.signal?.throwIfAborted();
170
+ const absoluteDirectory = path.join(root, relativeDirectory);
171
+ for (const entry of await fs.readdir(absoluteDirectory, { withFileTypes: true })) {
172
+ options.signal?.throwIfAborted();
173
+ const relativePath = relativeDirectory ? posixJoin(relativeDirectory, entry.name) : entry.name;
174
+ const snapshotPath = options.virtualPrefix ? posixJoin(options.virtualPrefix, relativePath) : relativePath;
175
+ if (isDeniedPath(snapshotPath) || options.excluded?.(snapshotPath))
176
+ continue;
177
+ if (entry.isDirectory()) {
178
+ await collectDirectory(results, root, relativePath, options);
179
+ }
180
+ else if (entry.isFile() && (!options.sessionsOnly || isSessionFilePath(snapshotPath))) {
181
+ await addFile(results, root, relativePath, snapshotPath, options.signal);
182
+ }
183
+ }
184
+ }
185
+ async function addFile(results, root, relativePath, snapshotPath = relativePath, signal) {
186
+ signal?.throwIfAborted();
187
+ if (!isSafeSnapshotPath(snapshotPath))
188
+ return;
189
+ const absolutePath = safeJoin(root, relativePath);
190
+ const content = await fs.readFile(absolutePath, { signal });
191
+ signal?.throwIfAborted();
192
+ results.push({
193
+ path: snapshotPath,
194
+ contentBase64: content.toString("base64"),
195
+ sha256: sha256(content),
196
+ });
197
+ }
198
+ export function isSessionPath(relativePath) {
199
+ return toPosix(relativePath).startsWith("sessions/");
200
+ }
201
+ export function isSessionFilePath(relativePath) {
202
+ const normalized = toPosix(relativePath);
203
+ return isSessionPath(normalized) && normalized.endsWith(".jsonl");
204
+ }
205
+ export function sessionSnapshotPathFromAbsolute(sessionFile, configuredSessionDir) {
206
+ const relativePath = toPosix(path.relative(sessionStorageRoot(agentDir(), configuredSessionDir), sessionFile));
207
+ if (!relativePath || relativePath.startsWith("../") || path.posix.isAbsolute(relativePath)) {
208
+ return undefined;
209
+ }
210
+ const snapshotPath = posixJoin("sessions", relativePath);
211
+ return isSessionFilePath(snapshotPath) ? snapshotPath : undefined;
212
+ }
213
+ export function snapshotTarget(root, relativePath, configuredSessionDir) {
214
+ if (isSessionPath(relativePath)) {
215
+ return safeJoin(sessionStorageRoot(root, configuredSessionDir), relativePath.slice("sessions/".length));
216
+ }
217
+ return safeJoin(root, relativePath);
218
+ }
219
+ export function snapshotIncludesSessions(snapshot) {
220
+ return (snapshot.syncSessions === true ||
221
+ (snapshotSelectionInclude(snapshot)?.includes("sessions") === true &&
222
+ !compileSyncExclude(snapshotSelectionExclude(snapshot))("sessions")) ||
223
+ snapshot.files.some((file) => isSessionPath(file.path)));
224
+ }
225
+ export function filterSnapshotForConfigPolicy(snapshot, config, options = {}) {
226
+ const include = includeFromSelectionConfig(config);
227
+ const includePaths = customIncludePathsByLower(include);
228
+ const exclude = config.exclude ?? (snapshot.version === 4 ? [] : undefined);
229
+ const filtered = {
230
+ ...snapshot,
231
+ version: exclude === undefined ? snapshot.version : 4,
232
+ syncSessions: include.includes("sessions") && !compileSyncExclude(exclude)("sessions") ? snapshot.syncSessions : false,
233
+ selection: selectionForSnapshot(include, exclude),
234
+ files: canonicalizeSnapshotFilesForConfig(snapshot.files, config, includePaths),
235
+ };
236
+ if (!options.regenerateId || snapshotsMatch(snapshot, filtered))
237
+ return filtered;
238
+ return {
239
+ ...filtered,
240
+ id: snapshotId(),
241
+ createdAt: new Date().toISOString(),
242
+ machine: os.hostname(),
243
+ };
244
+ }
245
+ function canonicalizeSnapshotFilesForConfig(files, config, includePaths) {
246
+ const configuredFiles = [];
247
+ const extraCandidates = new Map();
248
+ const configured = configuredSnapshotPathMatcher(config);
249
+ for (const file of files) {
250
+ const normalized = toPosix(file.path);
251
+ if (!isSafeSnapshotPath(file.path) || !configured(normalized)) {
252
+ continue;
253
+ }
254
+ if (normalized.includes("/")) {
255
+ configuredFiles.push(normalized === file.path ? file : { ...file, path: normalized });
256
+ continue;
257
+ }
258
+ const topLevelPath = canonicalSnapshotPathForConfig(normalized, includePaths);
259
+ const candidate = {
260
+ exact: normalized === topLevelPath,
261
+ file: { ...file, path: topLevelPath },
262
+ originalPath: normalized,
263
+ };
264
+ const current = extraCandidates.get(topLevelPath.toLowerCase());
265
+ if (!current || isPreferredExtraCandidate(candidate, current)) {
266
+ extraCandidates.set(topLevelPath.toLowerCase(), candidate);
267
+ }
268
+ }
269
+ return [...configuredFiles, ...[...extraCandidates.values()].map((candidate) => candidate.file)].sort((left, right) => left.path.localeCompare(right.path));
270
+ }
271
+ function isPreferredExtraCandidate(left, right) {
272
+ if (left.exact !== right.exact)
273
+ return left.exact;
274
+ return left.originalPath.localeCompare(right.originalPath) < 0;
275
+ }
276
+ export function snapshotWithoutSessions(snapshot) {
277
+ const files = snapshot.files.filter((file) => !isSessionPath(file.path));
278
+ const include = snapshotSelectionInclude(snapshot)?.filter((item) => item !== "sessions");
279
+ if (files.length === snapshot.files.length &&
280
+ snapshot.syncSessions !== true &&
281
+ include?.length === snapshot.selection?.include.length) {
282
+ return snapshot;
283
+ }
284
+ return {
285
+ ...snapshot,
286
+ id: snapshotId(),
287
+ createdAt: new Date().toISOString(),
288
+ machine: os.hostname(),
289
+ syncSessions: false,
290
+ ...(include ? { selection: selectionForSnapshot(include, snapshotSelectionExclude(snapshot)) } : {}),
291
+ files,
292
+ };
293
+ }
294
+ export function scanSnapshot(snapshot) {
295
+ const findings = [];
296
+ for (const file of snapshot.files) {
297
+ const content = Buffer.from(file.contentBase64, "base64");
298
+ if (content.includes(0))
299
+ continue;
300
+ const text = content.toString("utf8");
301
+ for (const pattern of SECRET_PATTERNS) {
302
+ if (pattern.test(text)) {
303
+ findings.push(file.path);
304
+ break;
305
+ }
306
+ }
307
+ }
308
+ return findings;
309
+ }
310
+ export function mergeRemotePreservedFiles(local, remote, config) {
311
+ const localPathNames = new Set(local.files.map((file) => file.path.toLowerCase()));
312
+ const preservedPathNames = new Set();
313
+ const configured = configuredSnapshotPathMatcher(config);
314
+ const excluded = compileSyncExclude(config.exclude);
315
+ const preserved = remote.files.filter((file) => {
316
+ const normalized = toPosix(file.path);
317
+ const lower = normalized.toLowerCase();
318
+ if (localPathNames.has(lower) ||
319
+ preservedPathNames.has(lower) ||
320
+ !isSafeSnapshotPath(file.path) ||
321
+ configured(normalized) ||
322
+ excluded(normalized) ||
323
+ !isPreservableUnmanagedSnapshotPath(normalized)) {
324
+ return false;
325
+ }
326
+ preservedPathNames.add(lower);
327
+ return true;
328
+ });
329
+ if (preserved.length === 0)
330
+ return local;
331
+ return {
332
+ ...local,
333
+ id: snapshotId(),
334
+ createdAt: new Date().toISOString(),
335
+ machine: os.hostname(),
336
+ syncSessions: !excluded("sessions") && (snapshotIncludesSessions(local) || snapshotIncludesSessions(remote)),
337
+ files: [...local.files, ...preserved].sort((left, right) => left.path.localeCompare(right.path)),
338
+ };
339
+ }
340
+ export function mergeRemoteSessionFiles(local, remote) {
341
+ const excluded = compileSyncExclude(snapshotSelectionExclude(local));
342
+ if (excluded("sessions"))
343
+ return local;
344
+ const remoteSessions = remote.files.filter((file) => {
345
+ const normalized = toPosix(file.path);
346
+ return isSessionFilePath(normalized) && isSafeSnapshotPath(file.path) && !excluded(normalized);
347
+ });
348
+ if (remoteSessions.length === 0 && !snapshotIncludesSessions(remote))
349
+ return local;
350
+ const localInclude = snapshotSelectionInclude(local);
351
+ return {
352
+ ...local,
353
+ id: snapshotId(),
354
+ createdAt: new Date().toISOString(),
355
+ machine: os.hostname(),
356
+ syncSessions: true,
357
+ ...(localInclude
358
+ ? {
359
+ selection: selectionForSnapshot(localInclude.includes("sessions") ? localInclude : [...localInclude, "sessions"], snapshotSelectionExclude(local)),
360
+ }
361
+ : {}),
362
+ files: [...local.files.filter((file) => !isSessionPath(file.path)), ...remoteSessions].sort((left, right) => left.path.localeCompare(right.path)),
363
+ };
364
+ }
@@ -0,0 +1,6 @@
1
+ export declare function readJsonIfExists<T>(filePath: string): Promise<T | undefined>;
2
+ export declare function writeJson(filePath: string, value: unknown, options?: {
3
+ maxBytes?: number;
4
+ }): Promise<void>;
5
+ /** POSIX rename/unlink durability; Windows does not expose directory fsync through Node. */
6
+ export declare function syncDirectory(directory: string): Promise<void>;
@@ -0,0 +1,49 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ export async function readJsonIfExists(filePath) {
5
+ try {
6
+ return JSON.parse(await fs.readFile(filePath, "utf8"));
7
+ }
8
+ catch (error) {
9
+ if (error.code === "ENOENT")
10
+ return undefined;
11
+ throw error;
12
+ }
13
+ }
14
+ export async function writeJson(filePath, value, options = {}) {
15
+ const content = `${JSON.stringify(value, null, "\t")}\n`;
16
+ if (options.maxBytes !== undefined && Buffer.byteLength(content) > options.maxBytes)
17
+ throw new Error("Private state document exceeds its storage bound; preserve existing evidence and use reviewed recovery.");
18
+ await fs.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
19
+ const temp = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
20
+ try {
21
+ const handle = await fs.open(temp, "wx", 0o600);
22
+ try {
23
+ await handle.writeFile(content);
24
+ await handle.sync();
25
+ }
26
+ finally {
27
+ await handle.close();
28
+ }
29
+ if (process.platform !== "win32")
30
+ await fs.chmod(temp, 0o600);
31
+ await fs.rename(temp, filePath);
32
+ await syncDirectory(path.dirname(filePath));
33
+ }
34
+ finally {
35
+ await fs.rm(temp, { force: true });
36
+ }
37
+ }
38
+ /** POSIX rename/unlink durability; Windows does not expose directory fsync through Node. */
39
+ export async function syncDirectory(directory) {
40
+ if (process.platform === "win32")
41
+ return;
42
+ const handle = await fs.open(directory, "r");
43
+ try {
44
+ await handle.sync();
45
+ }
46
+ finally {
47
+ await handle.close();
48
+ }
49
+ }
@@ -0,0 +1,2 @@
1
+ export declare const LOCK_GUARD_STALE_MS = 30000;
2
+ export declare const LOCK_GUARD_UPDATE_MS = 10000;
@@ -0,0 +1,2 @@
1
+ export const LOCK_GUARD_STALE_MS = 30_000;
2
+ export const LOCK_GUARD_UPDATE_MS = 10_000;
@@ -0,0 +1,20 @@
1
+ import type { CommandOptions } from "../commands/command-types.js";
2
+ import type { EngineContext as ExtensionCommandContext } from "../host.js";
3
+ import type { LockFile } from "./state-types.js";
4
+ export type LockInspection = {
5
+ status: "missing";
6
+ } | {
7
+ status: "unreadable";
8
+ } | {
9
+ status: "valid";
10
+ lock: LockFile;
11
+ };
12
+ export declare function withLock<T>(command: string, fn: () => Promise<T>, options?: {
13
+ reclaimStale?: boolean;
14
+ }): Promise<T>;
15
+ export declare function inspectLock(): Promise<LockInspection>;
16
+ export declare function readLock(): Promise<LockFile | undefined>;
17
+ export declare function lockFileExists(): Promise<boolean>;
18
+ export declare function isLockGuardHeld(): Promise<boolean>;
19
+ export declare function isStaleLock(lock: LockFile): boolean;
20
+ export declare function unlock(ctx: ExtensionCommandContext, options: CommandOptions): Promise<void>;