@narumitw/pi-sync 0.49.15 → 0.50.1

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 (213) hide show
  1. package/README.md +49 -16
  2. package/dist/chunks/attention-widget-Z7G3SYYJ.ts +9 -0
  3. package/dist/chunks/attention-widget-Z7G3SYYJ.ts.map +7 -0
  4. package/dist/chunks/chunk-2B2ELUF5.ts +29 -0
  5. package/dist/chunks/chunk-2B2ELUF5.ts.map +7 -0
  6. package/dist/chunks/{chunk-ARN2672F.ts → chunk-4CHTZMEO.ts} +23 -55
  7. package/dist/chunks/chunk-4CHTZMEO.ts.map +7 -0
  8. package/dist/chunks/chunk-6LP3MCR2.ts +115 -0
  9. package/dist/chunks/chunk-6LP3MCR2.ts.map +7 -0
  10. package/dist/chunks/{chunk-JF6MZCT4.ts → chunk-AUSDLD6F.ts} +4 -4
  11. package/dist/chunks/chunk-AUSDLD6F.ts.map +7 -0
  12. package/dist/chunks/{chunk-5T442OP3.ts → chunk-C7XY5NF5.ts} +210 -373
  13. package/dist/chunks/chunk-C7XY5NF5.ts.map +7 -0
  14. package/dist/chunks/chunk-CCSN3F47.ts +51 -0
  15. package/dist/chunks/chunk-CCSN3F47.ts.map +7 -0
  16. package/dist/chunks/{chunk-4U6AFLJB.ts → chunk-CHH26D4F.ts} +3 -2
  17. package/dist/chunks/chunk-CHH26D4F.ts.map +7 -0
  18. package/dist/chunks/chunk-CPEHGXJV.ts +50 -0
  19. package/dist/chunks/chunk-CPEHGXJV.ts.map +7 -0
  20. package/dist/chunks/{chunk-5MQ76BK5.ts → chunk-D5X27LCA.ts} +2 -2
  21. package/dist/chunks/chunk-D5X27LCA.ts.map +7 -0
  22. package/dist/chunks/{chunk-WSOBYHIZ.ts → chunk-ETTRJDNP.ts} +4 -4
  23. package/dist/chunks/chunk-ETTRJDNP.ts.map +7 -0
  24. package/dist/chunks/{chunk-44LPGQTI.ts → chunk-G4RNQQZS.ts} +9 -7
  25. package/dist/chunks/chunk-G4RNQQZS.ts.map +7 -0
  26. package/dist/chunks/{chunk-5LZALPCD.ts → chunk-HUDQATCL.ts} +25 -25
  27. package/dist/chunks/chunk-HUDQATCL.ts.map +7 -0
  28. package/dist/chunks/{chunk-X7SQ2EQM.ts → chunk-IJ6FJFA5.ts} +9 -9
  29. package/dist/chunks/chunk-IJ6FJFA5.ts.map +7 -0
  30. package/dist/chunks/{chunk-YQ6UW7IF.ts → chunk-JAAKLL6M.ts} +2 -2
  31. package/dist/chunks/chunk-JAAKLL6M.ts.map +7 -0
  32. package/dist/chunks/chunk-KW7YQEZN.ts +1255 -0
  33. package/dist/chunks/chunk-KW7YQEZN.ts.map +7 -0
  34. package/dist/chunks/{chunk-DFXBKHGN.ts → chunk-LCRI3ABW.ts} +21 -8
  35. package/dist/chunks/chunk-LCRI3ABW.ts.map +7 -0
  36. package/dist/chunks/chunk-LTBWGSBV.ts +12 -0
  37. package/dist/chunks/chunk-LTBWGSBV.ts.map +7 -0
  38. package/dist/chunks/chunk-NJFUIVYL.ts +17 -0
  39. package/dist/chunks/chunk-NJFUIVYL.ts.map +7 -0
  40. package/dist/chunks/{chunk-HVUSHMVL.ts → chunk-OEX4ABY6.ts} +39 -37
  41. package/dist/chunks/chunk-OEX4ABY6.ts.map +7 -0
  42. package/dist/chunks/{chunk-HGV24P4T.ts → chunk-Q2TUM5X6.ts} +3 -3
  43. package/dist/chunks/chunk-Q2TUM5X6.ts.map +7 -0
  44. package/dist/chunks/chunk-S7YBZR42.ts +146 -0
  45. package/dist/chunks/chunk-S7YBZR42.ts.map +7 -0
  46. package/dist/chunks/{chunk-GLQLN5GV.ts → chunk-SL64RLXR.ts} +8 -6
  47. package/dist/chunks/chunk-SL64RLXR.ts.map +7 -0
  48. package/dist/chunks/chunk-SZWBGPID.ts +57 -0
  49. package/dist/chunks/chunk-SZWBGPID.ts.map +7 -0
  50. package/dist/chunks/chunk-T2B5IU74.ts +25 -0
  51. package/dist/chunks/chunk-T2B5IU74.ts.map +7 -0
  52. package/dist/chunks/chunk-T3HH3UEJ.ts +96 -0
  53. package/dist/chunks/chunk-T3HH3UEJ.ts.map +7 -0
  54. package/dist/chunks/chunk-TEN2ZBJV.ts +101 -0
  55. package/dist/chunks/chunk-TEN2ZBJV.ts.map +7 -0
  56. package/dist/chunks/chunk-THMF4BVL.ts +18 -0
  57. package/dist/chunks/chunk-THMF4BVL.ts.map +7 -0
  58. package/dist/chunks/chunk-Z4DQF6L3.ts +12 -0
  59. package/dist/chunks/chunk-Z4DQF6L3.ts.map +7 -0
  60. package/dist/chunks/{chunk-F5QL2GPY.ts → chunk-ZI5MXMEX.ts} +5 -99
  61. package/dist/chunks/chunk-ZI5MXMEX.ts.map +7 -0
  62. package/dist/chunks/{file-selection-RKEHALNQ.ts → file-selection-FTTKAOYX.ts} +10 -7
  63. package/dist/chunks/file-selection-FTTKAOYX.ts.map +7 -0
  64. package/dist/chunks/{git-backend-E3UOUUOM.ts → git-backend-GMVS4PD4.ts} +39 -14
  65. package/dist/chunks/git-backend-GMVS4PD4.ts.map +7 -0
  66. package/dist/chunks/manager-result-dispatcher-FKIBM3GO.ts +22 -0
  67. package/dist/chunks/manager-ui-R3XPUFFS.ts +1680 -0
  68. package/dist/chunks/manager-ui-R3XPUFFS.ts.map +7 -0
  69. package/dist/chunks/remote-selection-ui-D7RBRJNL.ts +21 -0
  70. package/dist/chunks/{s3-backend-552LXHE4.ts → s3-backend-66O4FGBH.ts} +94 -16
  71. package/dist/chunks/s3-backend-66O4FGBH.ts.map +7 -0
  72. package/dist/chunks/{setup-switch-5YDG5YGJ.ts → setup-switch-IS2PEZ3J.ts} +9 -9
  73. package/dist/chunks/setup-wizard-IUB6ESEU.ts +89 -0
  74. package/dist/chunks/setup-wizard-IUB6ESEU.ts.map +7 -0
  75. package/dist/chunks/{snapshot-2RYBUDRA.ts → snapshot-HKEWCVK6.ts} +7 -6
  76. package/dist/chunks/sync-inspection-CST2KL65.ts +20 -0
  77. package/dist/chunks/{sync-operations-3LLIHWZO.ts → sync-operations-LBX3GKCM.ts} +369 -289
  78. package/dist/chunks/sync-operations-LBX3GKCM.ts.map +7 -0
  79. package/dist/chunks/{sync-state-SRN6YRBK.ts → sync-state-Q2FTXTW6.ts} +6 -6
  80. package/dist/chunks/sync-state-Q2FTXTW6.ts.map +7 -0
  81. package/dist/chunks/{webdav-backend-ZD5RHRIU.ts → webdav-backend-ECIKD7SO.ts} +26 -13
  82. package/dist/chunks/webdav-backend-ECIKD7SO.ts.map +7 -0
  83. package/dist/index.ts +476 -341
  84. package/dist/index.ts.map +4 -4
  85. package/docs/settings.md +30 -6
  86. package/package.json +1 -1
  87. package/src/{backend-factory.ts → backends/backend-factory.ts} +4 -4
  88. package/src/backends/backend-identity.ts +40 -0
  89. package/src/backends/backend-types.ts +81 -0
  90. package/src/{git-backend.ts → backends/git/git-backend.ts} +43 -19
  91. package/src/{git-config.ts → backends/git/git-config.ts} +1 -0
  92. package/src/{git-storage.ts → backends/git/git-storage.ts} +2 -2
  93. package/src/{s3-backend.ts → backends/s3/s3-backend.ts} +45 -9
  94. package/src/{s3-client.ts → backends/s3/s3-client.ts} +56 -8
  95. package/src/{sync-backend.ts → backends/sync-backend.ts} +1 -1
  96. package/src/{webdav-backend.ts → backends/webdav/webdav-backend.ts} +22 -10
  97. package/src/{webdav-client.ts → backends/webdav/webdav-client.ts} +1 -1
  98. package/src/{webdav-config.ts → backends/webdav/webdav-config.ts} +1 -0
  99. package/src/commands/command-execution.ts +330 -0
  100. package/src/commands/command-handler.ts +201 -0
  101. package/src/commands/command-types.ts +18 -0
  102. package/src/{command.ts → commands/command.ts} +2 -1
  103. package/src/commands/setup-completions.ts +6 -0
  104. package/src/settings/config.ts +238 -0
  105. package/src/{settings-management.ts → settings/settings-management.ts} +39 -14
  106. package/src/settings/settings-store.ts +109 -0
  107. package/src/settings/settings-types.ts +128 -0
  108. package/src/settings/settings-validation.ts +443 -0
  109. package/src/snapshot/session-paths.ts +84 -0
  110. package/src/{snapshot-apply.ts → snapshot/snapshot-apply.ts} +3 -3
  111. package/src/{snapshot-codec.ts → snapshot/snapshot-codec.ts} +2 -2
  112. package/src/{snapshot-transaction.ts → snapshot/snapshot-transaction.ts} +5 -4
  113. package/src/snapshot/snapshot-types.ts +38 -0
  114. package/src/{snapshot.ts → snapshot/snapshot.ts} +39 -20
  115. package/src/state/json-file.ts +20 -0
  116. package/src/{lock.ts → state/lock.ts} +3 -2
  117. package/src/{operation-availability.ts → state/operation-availability.ts} +2 -2
  118. package/src/state/state-types.ts +20 -0
  119. package/src/state/sync-state-store.ts +62 -0
  120. package/src/sync/automatic-sync.ts +103 -0
  121. package/src/{remote-snapshot.ts → sync/remote-snapshot.ts} +27 -4
  122. package/src/{setup-switch.ts → sync/setup-switch.ts} +6 -7
  123. package/src/sync/signals.ts +10 -0
  124. package/src/sync/startup-check.ts +128 -0
  125. package/src/{sync-decision.ts → sync/sync-decision.ts} +6 -3
  126. package/src/sync/sync-error-guidance.ts +53 -0
  127. package/src/sync/sync-inspection.ts +51 -0
  128. package/src/sync/sync-loaders.ts +54 -0
  129. package/src/{sync-operations.ts → sync/sync-mutations.ts} +34 -325
  130. package/src/sync/sync-operations.ts +12 -0
  131. package/src/{sync-policy.ts → sync/sync-policy.ts} +2 -2
  132. package/src/sync/sync-queries.ts +235 -0
  133. package/src/{sync-state.ts → sync/sync-state.ts} +5 -4
  134. package/src/sync-extension.ts +64 -708
  135. package/src/sync.ts +8 -8
  136. package/src/types.ts +47 -286
  137. package/src/ui/attention-widget.ts +1 -0
  138. package/src/ui/automatic-sync-summary.ts +6 -0
  139. package/src/{cancellable-operation.ts → ui/cancellable-operation.ts} +4 -4
  140. package/src/{file-selection.ts → ui/file-selection.ts} +5 -3
  141. package/src/{manager-attention.ts → ui/manager-attention.ts} +5 -1
  142. package/src/{manager-recovery.ts → ui/manager-recovery.ts} +6 -2
  143. package/src/{manager-state.ts → ui/manager-state.ts} +35 -14
  144. package/src/ui/manager-ui.ts +386 -0
  145. package/src/{remote-selection-ui.ts → ui/remote-selection-ui.ts} +21 -13
  146. package/src/{secret-input.ts → ui/secret-input.ts} +22 -4
  147. package/src/{settings-ui.ts → ui/settings-ui.ts} +17 -13
  148. package/src/ui/setup/git-ui.ts +293 -0
  149. package/src/{s3-credentials-ui.ts → ui/setup/s3-credentials-ui.ts} +13 -21
  150. package/src/ui/setup/s3-ui.ts +217 -0
  151. package/src/ui/setup/setup-actions.ts +127 -0
  152. package/src/ui/setup/setup-location-ui.ts +167 -0
  153. package/src/ui/setup/setup-name-ui.ts +34 -0
  154. package/src/ui/setup/setup-prompts.ts +92 -0
  155. package/src/ui/setup/setup-review.ts +70 -0
  156. package/src/ui/setup/setup-switcher.ts +181 -0
  157. package/src/ui/setup/setup-wizard.ts +39 -0
  158. package/src/ui/setup/text-input.ts +78 -0
  159. package/src/ui/setup/webdav-ui.ts +330 -0
  160. package/src/{storage-connections-ui.ts → ui/storage-connections-ui.ts} +99 -69
  161. package/src/ui/sync-attention.ts +187 -0
  162. package/src/{sync-format.ts → ui/sync-format.ts} +7 -13
  163. package/src/{sync-resolution-ui.ts → ui/sync-resolution-ui.ts} +4 -3
  164. package/src/{sync-setups-ui.ts → ui/sync-setups-ui.ts} +23 -10
  165. package/src/ui/terminal-text.ts +4 -0
  166. package/dist/chunks/chunk-44LPGQTI.ts.map +0 -7
  167. package/dist/chunks/chunk-4U6AFLJB.ts.map +0 -7
  168. package/dist/chunks/chunk-5LZALPCD.ts.map +0 -7
  169. package/dist/chunks/chunk-5MQ76BK5.ts.map +0 -7
  170. package/dist/chunks/chunk-5T442OP3.ts.map +0 -7
  171. package/dist/chunks/chunk-ARN2672F.ts.map +0 -7
  172. package/dist/chunks/chunk-C7LXZ3UH.ts +0 -167
  173. package/dist/chunks/chunk-C7LXZ3UH.ts.map +0 -7
  174. package/dist/chunks/chunk-DFXBKHGN.ts.map +0 -7
  175. package/dist/chunks/chunk-E4COSV32.ts +0 -82
  176. package/dist/chunks/chunk-E4COSV32.ts.map +0 -7
  177. package/dist/chunks/chunk-F5QL2GPY.ts.map +0 -7
  178. package/dist/chunks/chunk-GLQLN5GV.ts.map +0 -7
  179. package/dist/chunks/chunk-HGV24P4T.ts.map +0 -7
  180. package/dist/chunks/chunk-HVUSHMVL.ts.map +0 -7
  181. package/dist/chunks/chunk-JF6MZCT4.ts.map +0 -7
  182. package/dist/chunks/chunk-WSOBYHIZ.ts.map +0 -7
  183. package/dist/chunks/chunk-X7SQ2EQM.ts.map +0 -7
  184. package/dist/chunks/chunk-YQ6UW7IF.ts.map +0 -7
  185. package/dist/chunks/file-selection-RKEHALNQ.ts.map +0 -7
  186. package/dist/chunks/git-backend-E3UOUUOM.ts.map +0 -7
  187. package/dist/chunks/manager-result-dispatcher-LWPYJAD5.ts +0 -18
  188. package/dist/chunks/manager-ui-NF4RUHBY.ts +0 -2785
  189. package/dist/chunks/manager-ui-NF4RUHBY.ts.map +0 -7
  190. package/dist/chunks/remote-selection-ui-NUF5P4ZJ.ts +0 -17
  191. package/dist/chunks/s3-backend-552LXHE4.ts.map +0 -7
  192. package/dist/chunks/sync-operations-3LLIHWZO.ts.map +0 -7
  193. package/dist/chunks/webdav-backend-ZD5RHRIU.ts.map +0 -7
  194. package/src/config.ts +0 -923
  195. package/src/git-ui.ts +0 -307
  196. package/src/manager-helpers.ts +0 -64
  197. package/src/manager-ui.ts +0 -997
  198. package/src/sync-attention.ts +0 -100
  199. package/src/webdav-ui.ts +0 -421
  200. /package/dist/chunks/{manager-result-dispatcher-LWPYJAD5.ts.map → manager-result-dispatcher-FKIBM3GO.ts.map} +0 -0
  201. /package/dist/chunks/{remote-selection-ui-NUF5P4ZJ.ts.map → remote-selection-ui-D7RBRJNL.ts.map} +0 -0
  202. /package/dist/chunks/{setup-switch-5YDG5YGJ.ts.map → setup-switch-IS2PEZ3J.ts.map} +0 -0
  203. /package/dist/chunks/{snapshot-2RYBUDRA.ts.map → snapshot-HKEWCVK6.ts.map} +0 -0
  204. /package/dist/chunks/{sync-state-SRN6YRBK.ts.map → sync-inspection-CST2KL65.ts.map} +0 -0
  205. /package/src/{git-runner.ts → backends/git/git-runner.ts} +0 -0
  206. /package/src/{config-errors.ts → settings/config-errors.ts} +0 -0
  207. /package/src/{config-file.ts → settings/config-file.ts} +0 -0
  208. /package/src/{snapshot-paths.ts → snapshot/snapshot-paths.ts} +0 -0
  209. /package/src/{lock-policy.ts → state/lock-policy.ts} +0 -0
  210. /package/src/{lockfile-fs.ts → state/lockfile-fs.ts} +0 -0
  211. /package/src/{state-directory.ts → state/state-directory.ts} +0 -0
  212. /package/src/{sync-errors.ts → sync/sync-errors.ts} +0 -0
  213. /package/src/{manager-result-dispatcher.ts → ui/manager-result-dispatcher.ts} +0 -0
@@ -1,82 +0,0 @@
1
- // @generated by scripts/build-runtime.mjs; do not edit.
2
- // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
- import {
4
- safeTerminalText
5
- } from "./chunk-C7LXZ3UH.ts";
6
- import {
7
- syncConfigReviewFingerprint
8
- } from "./chunk-5T442OP3.ts";
9
- import {
10
- compareSyncInclude,
11
- sameSyncInclude
12
- } from "./chunk-YQ6UW7IF.ts";
13
-
14
- // src/sync-attention.ts
15
- import { truncateToWidth } from "@earendil-works/pi-tui";
16
- var STATUS_KEY = "sync";
17
- var WIDGET_KEY = "sync:attention";
18
- function syncAttentionMatchesConfig(attention, config) {
19
- return attention.decision.setupName === config.setupName && attention.decision.configIdentity === syncConfigReviewFingerprint(config) && sameSyncInclude(attention.decision.localInclude, config.include);
20
- }
21
- function createSyncAttentionController() {
22
- let state;
23
- return {
24
- set(decision, origin) {
25
- state = { decision, origin, offered: false };
26
- },
27
- current() {
28
- return state;
29
- },
30
- markOffered() {
31
- if (!state || state.offered) return false;
32
- state = { ...state, offered: true };
33
- return true;
34
- },
35
- clear(ctx) {
36
- state = void 0;
37
- clearAttentionPresentation(ctx);
38
- },
39
- reset(ctx) {
40
- state = void 0;
41
- clearAttentionPresentation(ctx);
42
- },
43
- publish(ctx) {
44
- if (!state) {
45
- clearAttentionPresentation(ctx);
46
- return;
47
- }
48
- const presentation = attentionPresentation(state.decision);
49
- ctx.ui.setStatus(STATUS_KEY, presentation.status);
50
- if (ctx.mode !== "tui") return;
51
- ctx.ui.setWidget(WIDGET_KEY, (_tui, theme) => ({
52
- render(width) {
53
- const safeWidth = Math.max(1, width);
54
- return presentation.lines.map(
55
- (line, index) => truncateToWidth(theme.fg(index === 0 ? "warning" : "muted", line), safeWidth, "\u2026")
56
- );
57
- },
58
- invalidate() {
59
- }
60
- }));
61
- }
62
- };
63
- }
64
- function attentionPresentation(decision) {
65
- const setupName = safeTerminalText(decision.setupName);
66
- const comparison = compareSyncInclude(decision.localInclude, decision.remoteInclude);
67
- const difference = comparison.remoteOnly.length === 0 && comparison.localOnly.length === 0 ? "Only list order differs" : `Remote ${comparison.remoteOnly.length} \xB7 Device ${comparison.localOnly.length}`;
68
- return {
69
- status: "review needed",
70
- lines: [`Pi Sync needs review \xB7 ${setupName}`, difference, "No changes \xB7 Run /sync to review"]
71
- };
72
- }
73
- function clearAttentionPresentation(ctx) {
74
- ctx.ui.setStatus(STATUS_KEY, void 0);
75
- ctx.ui.setWidget(WIDGET_KEY, void 0);
76
- }
77
-
78
- export {
79
- syncAttentionMatchesConfig,
80
- createSyncAttentionController
81
- };
82
- //# sourceMappingURL=chunk-E4COSV32.ts.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/sync-attention.ts"],
4
- "sourcesContent": ["import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { truncateToWidth } from \"@earendil-works/pi-tui\";\nimport { syncConfigReviewFingerprint } from \"./config.js\";\nimport { safeTerminalText } from \"./sync-format.js\";\nimport {\n\tcompareSyncInclude,\n\ttype RemoteSelectionDecision,\n\tsameSyncInclude,\n} from \"./sync-policy.js\";\nimport type { AnySyncConfig } from \"./types.js\";\n\nconst STATUS_KEY = \"sync\";\nconst WIDGET_KEY = \"sync:attention\";\n\nexport type SyncAttentionOrigin = \"sync\" | \"pull\" | \"push\";\n\nexport interface SyncAttentionState {\n\tdecision: RemoteSelectionDecision;\n\torigin: SyncAttentionOrigin;\n\toffered: boolean;\n}\n\nexport function syncAttentionMatchesConfig(attention: SyncAttentionState, config: AnySyncConfig) {\n\treturn (\n\t\tattention.decision.setupName === config.setupName &&\n\t\tattention.decision.configIdentity === syncConfigReviewFingerprint(config) &&\n\t\tsameSyncInclude(attention.decision.localInclude, config.include)\n\t);\n}\n\nexport interface SyncAttentionController {\n\tset(decision: RemoteSelectionDecision, origin: SyncAttentionOrigin): void;\n\tcurrent(): SyncAttentionState | undefined;\n\tmarkOffered(): boolean;\n\tclear(ctx: ExtensionContext): void;\n\treset(ctx: ExtensionContext): void;\n\tpublish(ctx: ExtensionContext): void;\n}\n\nexport function createSyncAttentionController(): SyncAttentionController {\n\tlet state: SyncAttentionState | undefined;\n\n\treturn {\n\t\tset(decision, origin) {\n\t\t\tstate = { decision, origin, offered: false };\n\t\t},\n\t\tcurrent() {\n\t\t\treturn state;\n\t\t},\n\t\tmarkOffered() {\n\t\t\tif (!state || state.offered) return false;\n\t\t\tstate = { ...state, offered: true };\n\t\t\treturn true;\n\t\t},\n\t\tclear(ctx) {\n\t\t\tstate = undefined;\n\t\t\tclearAttentionPresentation(ctx);\n\t\t},\n\t\treset(ctx) {\n\t\t\tstate = undefined;\n\t\t\tclearAttentionPresentation(ctx);\n\t\t},\n\t\tpublish(ctx) {\n\t\t\tif (!state) {\n\t\t\t\tclearAttentionPresentation(ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst presentation = attentionPresentation(state.decision);\n\t\t\tctx.ui.setStatus(STATUS_KEY, presentation.status);\n\t\t\tif (ctx.mode !== \"tui\") return;\n\t\t\tctx.ui.setWidget(WIDGET_KEY, (_tui, theme) => ({\n\t\t\t\trender(width: number) {\n\t\t\t\t\tconst safeWidth = Math.max(1, width);\n\t\t\t\t\treturn presentation.lines.map((line, index) =>\n\t\t\t\t\t\ttruncateToWidth(theme.fg(index === 0 ? \"warning\" : \"muted\", line), safeWidth, \"\u2026\"),\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\tinvalidate() {},\n\t\t\t}));\n\t\t},\n\t};\n}\n\nfunction attentionPresentation(decision: RemoteSelectionDecision) {\n\tconst setupName = safeTerminalText(decision.setupName);\n\tconst comparison = compareSyncInclude(decision.localInclude, decision.remoteInclude);\n\tconst difference =\n\t\tcomparison.remoteOnly.length === 0 && comparison.localOnly.length === 0\n\t\t\t? \"Only list order differs\"\n\t\t\t: `Remote ${comparison.remoteOnly.length} \u00B7 Device ${comparison.localOnly.length}`;\n\treturn {\n\t\tstatus: \"review needed\",\n\t\tlines: [`Pi Sync needs review \u00B7 ${setupName}`, difference, \"No changes \u00B7 Run /sync to review\"],\n\t};\n}\n\nfunction clearAttentionPresentation(ctx: ExtensionContext) {\n\tctx.ui.setStatus(STATUS_KEY, undefined);\n\tctx.ui.setWidget(WIDGET_KEY, undefined);\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;AACA,SAAS,uBAAuB;AAUhC,IAAM,aAAa;AACnB,IAAM,aAAa;AAUZ,SAAS,2BAA2B,WAA+B,QAAuB;AAChG,SACC,UAAU,SAAS,cAAc,OAAO,aACxC,UAAU,SAAS,mBAAmB,4BAA4B,MAAM,KACxE,gBAAgB,UAAU,SAAS,cAAc,OAAO,OAAO;AAEjE;AAWO,SAAS,gCAAyD;AACxE,MAAI;AAEJ,SAAO;AAAA,IACN,IAAI,UAAU,QAAQ;AACrB,cAAQ,EAAE,UAAU,QAAQ,SAAS,MAAM;AAAA,IAC5C;AAAA,IACA,UAAU;AACT,aAAO;AAAA,IACR;AAAA,IACA,cAAc;AACb,UAAI,CAAC,SAAS,MAAM,QAAS,QAAO;AACpC,cAAQ,EAAE,GAAG,OAAO,SAAS,KAAK;AAClC,aAAO;AAAA,IACR;AAAA,IACA,MAAM,KAAK;AACV,cAAQ;AACR,iCAA2B,GAAG;AAAA,IAC/B;AAAA,IACA,MAAM,KAAK;AACV,cAAQ;AACR,iCAA2B,GAAG;AAAA,IAC/B;AAAA,IACA,QAAQ,KAAK;AACZ,UAAI,CAAC,OAAO;AACX,mCAA2B,GAAG;AAC9B;AAAA,MACD;AACA,YAAM,eAAe,sBAAsB,MAAM,QAAQ;AACzD,UAAI,GAAG,UAAU,YAAY,aAAa,MAAM;AAChD,UAAI,IAAI,SAAS,MAAO;AACxB,UAAI,GAAG,UAAU,YAAY,CAAC,MAAM,WAAW;AAAA,QAC9C,OAAO,OAAe;AACrB,gBAAM,YAAY,KAAK,IAAI,GAAG,KAAK;AACnC,iBAAO,aAAa,MAAM;AAAA,YAAI,CAAC,MAAM,UACpC,gBAAgB,MAAM,GAAG,UAAU,IAAI,YAAY,SAAS,IAAI,GAAG,WAAW,QAAG;AAAA,UAClF;AAAA,QACD;AAAA,QACA,aAAa;AAAA,QAAC;AAAA,MACf,EAAE;AAAA,IACH;AAAA,EACD;AACD;AAEA,SAAS,sBAAsB,UAAmC;AACjE,QAAM,YAAY,iBAAiB,SAAS,SAAS;AACrD,QAAM,aAAa,mBAAmB,SAAS,cAAc,SAAS,aAAa;AACnF,QAAM,aACL,WAAW,WAAW,WAAW,KAAK,WAAW,UAAU,WAAW,IACnE,4BACA,UAAU,WAAW,WAAW,MAAM,gBAAa,WAAW,UAAU,MAAM;AAClF,SAAO;AAAA,IACN,QAAQ;AAAA,IACR,OAAO,CAAC,6BAA0B,SAAS,IAAI,YAAY,qCAAkC;AAAA,EAC9F;AACD;AAEA,SAAS,2BAA2B,KAAuB;AAC1D,MAAI,GAAG,UAAU,YAAY,MAAS;AACtC,MAAI,GAAG,UAAU,YAAY,MAAS;AACvC;",
6
- "names": []
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/git-config.ts", "../../src/state-directory.ts", "../../src/lock-policy.ts", "../../src/lockfile-fs.ts"],
4
- "sourcesContent": ["const DEFAULT_GIT_BRANCH = \"pi-sync\";\nconst DEFAULT_GIT_DIRECTORY = \"pi-sync\";\n\nexport function normalizeGitRemote(value: string | undefined) {\n\tconst normalized = normalizeOptionalString(value);\n\tif (!normalized) return undefined;\n\tif (\n\t\thasControlCharacter(normalized) ||\n\t\t/\\s/u.test(normalized) ||\n\t\tnormalized.startsWith(\"-\") ||\n\t\tnormalized.includes(\"\\\\\")\n\t) {\n\t\tthrow new Error(\"Invalid pi-sync Git remote.\");\n\t}\n\tif (\n\t\t!normalized.includes(\"://\") &&\n\t\t/^(?:[A-Za-z0-9._-]+@)?(?:\\[[0-9A-Fa-f:]+\\]|[A-Za-z0-9.-]+):(?!-)[^:].+$/u.test(normalized)\n\t) {\n\t\treturn normalized;\n\t}\n\tif (/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(normalized) && !normalized.includes(\"://\")) {\n\t\tthrow new Error(\"Invalid pi-sync Git remote: unsupported transport or remote-helper syntax.\");\n\t}\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(normalized);\n\t} catch {\n\t\tthrow new Error(\"Invalid pi-sync Git remote: use an SSH or HTTPS remote.\");\n\t}\n\tif (url.protocol !== \"https:\" && url.protocol !== \"ssh:\") {\n\t\tthrow new Error(\"Invalid pi-sync Git remote: only SSH and HTTPS are supported.\");\n\t}\n\tif (url.password || (url.protocol === \"https:\" && url.username)) {\n\t\tthrow new Error(\"Invalid pi-sync Git remote: URL credentials or userinfo are not allowed.\");\n\t}\n\tif (url.search || url.hash || !url.hostname || !url.pathname || url.pathname === \"/\") {\n\t\tthrow new Error(\"Invalid pi-sync Git remote.\");\n\t}\n\treturn url.toString();\n}\n\nexport function normalizeGitRemoteIdentity(value: string) {\n\tconst normalized = normalizeGitRemote(value);\n\tif (!normalized) return \"\";\n\tif (!normalized.includes(\"://\")) {\n\t\tconst match =\n\t\t\t/^(?<user>[A-Za-z0-9._-]+@)?(?<host>\\[[0-9A-Fa-f:]+\\]|[A-Za-z0-9.-]+):(?<path>.+)$/u.exec(\n\t\t\t\tnormalized,\n\t\t\t);\n\t\tif (!match?.groups) return normalized;\n\t\tconst userAndHost = `${match.groups.user ?? \"\"}${match.groups.host.toLowerCase()}`;\n\t\tconst remotePath = match.groups.path.replace(/\\/+$/gu, \"\");\n\t\treturn remotePath.startsWith(\"/\")\n\t\t\t? `scp-absolute://${userAndHost}${remotePath}`\n\t\t\t: `ssh://${userAndHost}/${remotePath}`;\n\t}\n\tconst url = new URL(normalized);\n\turl.hostname = url.hostname.toLowerCase();\n\tif (url.protocol === \"ssh:\" && url.port === \"22\") url.port = \"\";\n\turl.pathname = url.pathname.replace(/\\/+$/gu, \"\");\n\tif (url.protocol === \"ssh:\") {\n\t\treturn `ssh://${url.username ? `${url.username}@` : \"\"}${url.host}${url.pathname}`;\n\t}\n\treturn url.toString();\n}\n\nexport function normalizeGitBranch(value: string | undefined) {\n\tconst branch = normalizeOptionalString(value) ?? DEFAULT_GIT_BRANCH;\n\tif (\n\t\tbranch === \"@\" ||\n\t\tbranch.startsWith(\"-\") ||\n\t\tbranch.startsWith(\"refs/\") ||\n\t\tbranch.startsWith(\"/\") ||\n\t\tbranch.endsWith(\"/\") ||\n\t\tbranch.endsWith(\".\") ||\n\t\tbranch.includes(\"..\") ||\n\t\tbranch.includes(\"@{\") ||\n\t\tbranch.includes(\"\\\\\") ||\n\t\thasControlCharacter(branch) ||\n\t\t/[ ~^:?*[\\]]/u.test(branch) ||\n\t\tbranch\n\t\t\t.split(\"/\")\n\t\t\t.some((segment) => !segment || segment.startsWith(\".\") || segment.endsWith(\".lock\"))\n\t) {\n\t\tthrow new Error(\"Invalid pi-sync Git branch.\");\n\t}\n\treturn branch;\n}\n\nexport function normalizeGitDirectory(value: string | undefined) {\n\tconst directory = trimSlashes(normalizeOptionalString(value) ?? DEFAULT_GIT_DIRECTORY);\n\tif (\n\t\t!directory ||\n\t\tdirectory.startsWith(\"-\") ||\n\t\tdirectory.includes(\"\\\\\") ||\n\t\thasControlCharacter(directory) ||\n\t\tdirectory\n\t\t\t.split(\"/\")\n\t\t\t.some((segment) => !segment || segment === \".\" || segment === \"..\" || segment === \".git\")\n\t) {\n\t\tthrow new Error(\"Invalid pi-sync Git directory.\");\n\t}\n\treturn directory;\n}\n\nexport function validateGitNamespace(value: string) {\n\tif (\n\t\tvalue.length > 256 ||\n\t\tvalue === \".\" ||\n\t\tvalue === \"..\" ||\n\t\tvalue.includes(\"/\") ||\n\t\tvalue.includes(\"\\\\\") ||\n\t\thasControlCharacter(value)\n\t) {\n\t\tthrow new Error(\"Invalid pi-sync Git namespace.\");\n\t}\n}\n\nfunction normalizeOptionalString(value: unknown) {\n\tif (value !== undefined && typeof value !== \"string\") {\n\t\tthrow new Error(\"Invalid pi-sync settings: expected a string.\");\n\t}\n\tconst normalized = value?.trim();\n\treturn normalized || undefined;\n}\n\nfunction trimSlashes(value: string) {\n\treturn value.replace(/^\\/+|\\/+$/gu, \"\");\n}\n\nfunction hasControlCharacter(value: string) {\n\treturn [...value].some((character) => {\n\t\tconst code = character.codePointAt(0) ?? 0;\n\t\treturn code < 0x20 || (code >= 0x7f && code <= 0x9f);\n\t});\n}\n", "import { lstatSync } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { getAgentDir } from \"@earendil-works/pi-coding-agent\";\nimport lockfile from \"proper-lockfile\";\nimport { LOCK_GUARD_STALE_MS } from \"./lock-policy.js\";\nimport { LOCKFILE_FS_ADAPTER } from \"./lockfile-fs.js\";\n\nconst CANONICAL_DIRECTORY_NAME = \"pi-sync\";\nconst LEGACY_DIRECTORY_NAME = \".pisync\";\nconst MIGRATION_LOCK_NAME = \".pi-sync-state-migration.lock\";\nconst MIGRATION_LOCK_STALE_MS = 30_000;\nconst MIGRATION_LOCK_UPDATE_MS = 10_000;\n\nexport type StateDirectoryPreparation =\n\t| { status: \"ready\" }\n\t| { status: \"migrated\"; message: string }\n\t| { status: \"deferred\"; message: string };\n\ninterface StateDirectoryGuard {\n\trelease: () => Promise<void>;\n\tthrowIfCompromised: () => void;\n}\n\ninterface SharedStateDirectoryGuard {\n\tguard: Promise<StateDirectoryGuard>;\n\tusers: number;\n\tclosing?: Promise<void>;\n}\n\nconst sharedStateDirectoryGuards = new Map<string, SharedStateDirectoryGuard>();\n\nexport function stateDir() {\n\tconst roots = inspectStateRoots();\n\tif (roots.canonical) return canonicalStateDir();\n\tif (roots.legacy) return legacyStateDir();\n\treturn canonicalStateDir();\n}\n\nexport function legacyStateDir() {\n\treturn path.join(getAgentDir(), LEGACY_DIRECTORY_NAME);\n}\n\nexport function stateDirectoryMigrationNotice() {\n\tconst roots = inspectStateRoots();\n\tif (!roots.legacy) return undefined;\n\treturn \"Legacy pi-sync state is still stored in .pisync. Close other Pi sessions, then run /sync migrate-state to move it to pi-sync/.\";\n}\n\nexport async function withStateDirectoryAccess<T>(fn: () => Promise<T>): Promise<T> {\n\tconst roots = inspectStateRoots();\n\tif (!roots.legacy) return fn();\n\treturn runWithStateDirectoryGuard(await acquireSharedStateDirectoryGuard(), fn);\n}\n\nexport async function migrateLegacyStateDirectory(): Promise<StateDirectoryPreparation> {\n\tconst initial = inspectStateRoots();\n\tif (initial.canonical || !initial.legacy) return { status: \"ready\" };\n\n\tlet guard: StateDirectoryGuard;\n\ttry {\n\t\tguard = await acquireStateDirectoryGuard();\n\t} catch (error) {\n\t\tif (!isLockHeldError(error)) throw error;\n\t\treturn {\n\t\t\tstatus: \"deferred\",\n\t\t\tmessage:\n\t\t\t\t\"pi-sync state migration was deferred because another state user is active. Close other Pi sessions and retry.\",\n\t\t};\n\t}\n\treturn runWithStateDirectoryGuard(guard, async () => {\n\t\tconst roots = inspectStateRoots();\n\t\tif (roots.canonical || !roots.legacy) return { status: \"ready\" };\n\n\t\tconst legacyLock = path.join(legacyStateDir(), \"lock\");\n\t\tconst legacyGuardHeld = await lockfile.check(legacyLock, {\n\t\t\tfs: LOCKFILE_FS_ADAPTER,\n\t\t\tlockfilePath: `${legacyLock}.guard`,\n\t\t\trealpath: false,\n\t\t\tstale: LOCK_GUARD_STALE_MS,\n\t\t});\n\t\tif (legacyGuardHeld || (await pathExists(legacyLock))) {\n\t\t\treturn {\n\t\t\t\tstatus: \"deferred\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"pi-sync state migration was deferred because the legacy directory is busy. Close other Pi sessions, clear any confirmed stale sync lock, and retry.\",\n\t\t\t};\n\t\t}\n\t\tguard.throwIfCompromised();\n\t\tawait fs.rename(legacyStateDir(), canonicalStateDir());\n\t\tguard.throwIfCompromised();\n\t\tinspectStateRoots();\n\t\treturn {\n\t\t\tstatus: \"migrated\",\n\t\t\tmessage: `Migrated pi-sync state from ${legacyStateDir()} to ${canonicalStateDir()}.`,\n\t\t};\n\t});\n}\n\nasync function acquireSharedStateDirectoryGuard(): Promise<StateDirectoryGuard> {\n\tconst key = migrationLockPath();\n\tfor (;;) {\n\t\tlet shared = sharedStateDirectoryGuards.get(key);\n\t\tif (shared?.closing) {\n\t\t\tawait shared.closing;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!shared) {\n\t\t\tshared = { guard: acquireStateDirectoryGuard(), users: 0 };\n\t\t\tsharedStateDirectoryGuards.set(key, shared);\n\t\t}\n\t\tshared.users += 1;\n\t\tlet guard: StateDirectoryGuard;\n\t\ttry {\n\t\t\tguard = await shared.guard;\n\t\t} catch (error) {\n\t\t\tif (sharedStateDirectoryGuards.get(key) === shared) {\n\t\t\t\tsharedStateDirectoryGuards.delete(key);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tlet released = false;\n\t\treturn {\n\t\t\tthrowIfCompromised: guard.throwIfCompromised,\n\t\t\trelease: async () => {\n\t\t\t\tif (released) return;\n\t\t\t\treleased = true;\n\t\t\t\tshared.users -= 1;\n\t\t\t\tif (shared.users > 0) return;\n\t\t\t\tconst closing = guard.release();\n\t\t\t\tshared.closing = closing;\n\t\t\t\ttry {\n\t\t\t\t\tawait closing;\n\t\t\t\t} finally {\n\t\t\t\t\tif (sharedStateDirectoryGuards.get(key) === shared) {\n\t\t\t\t\t\tsharedStateDirectoryGuards.delete(key);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t}\n}\n\nasync function acquireStateDirectoryGuard(): Promise<StateDirectoryGuard> {\n\tlet compromisedError: Error | undefined;\n\tconst release = await lockfile.lock(getAgentDir(), {\n\t\tfs: LOCKFILE_FS_ADAPTER,\n\t\tlockfilePath: migrationLockPath(),\n\t\trealpath: false,\n\t\tstale: MIGRATION_LOCK_STALE_MS,\n\t\tupdate: MIGRATION_LOCK_UPDATE_MS,\n\t\tretries: { retries: 20, minTimeout: 10, maxTimeout: 50 },\n\t\tonCompromised: (error) => {\n\t\t\tcompromisedError = error;\n\t\t},\n\t});\n\treturn {\n\t\trelease,\n\t\tthrowIfCompromised: () => {\n\t\t\tif (compromisedError) throw compromisedError;\n\t\t},\n\t};\n}\n\nasync function runWithStateDirectoryGuard<T>(guard: StateDirectoryGuard, fn: () => Promise<T>) {\n\tlet result: T | undefined;\n\tlet failed = false;\n\tlet failure: unknown;\n\ttry {\n\t\tguard.throwIfCompromised();\n\t\tresult = await fn();\n\t\tguard.throwIfCompromised();\n\t} catch (error) {\n\t\tfailed = true;\n\t\tfailure = error;\n\t}\n\ttry {\n\t\tawait guard.release();\n\t} catch (error) {\n\t\tif (!failed) {\n\t\t\tfailed = true;\n\t\t\tfailure = error;\n\t\t}\n\t}\n\tif (failed) throw failure;\n\treturn result as T;\n}\n\nfunction isLockHeldError(error: unknown) {\n\treturn (error as NodeJS.ErrnoException).code === \"ELOCKED\";\n}\n\nfunction canonicalStateDir() {\n\treturn path.join(getAgentDir(), CANONICAL_DIRECTORY_NAME);\n}\n\nfunction migrationLockPath() {\n\treturn path.join(getAgentDir(), MIGRATION_LOCK_NAME);\n}\n\nfunction inspectStateRoots() {\n\tconst canonical = isDirectoryRoot(canonicalStateDir(), \"canonical\");\n\tconst legacy = isDirectoryRoot(legacyStateDir(), \"legacy\");\n\tif (canonical && legacy) {\n\t\tthrow new Error(\n\t\t\t`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.`,\n\t\t);\n\t}\n\treturn { canonical, legacy };\n}\n\nfunction isDirectoryRoot(directory: string, label: string) {\n\ttry {\n\t\tconst entry = lstatSync(directory);\n\t\tif (entry.isSymbolicLink()) {\n\t\t\tthrow new Error(\n\t\t\t\t`Refusing to use ${label} pi-sync state directory symbolic link: ${directory}`,\n\t\t\t);\n\t\t}\n\t\tif (!entry.isDirectory()) {\n\t\t\tthrow new Error(`${label} pi-sync state path is not a directory: ${directory}`);\n\t\t}\n\t\treturn true;\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n\t\tthrow error;\n\t}\n}\n\nasync function pathExists(filePath: string) {\n\ttry {\n\t\tawait fs.lstat(filePath);\n\t\treturn true;\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n\t\tthrow error;\n\t}\n}\n", "export const LOCK_GUARD_STALE_MS = 30_000;\nexport const LOCK_GUARD_UPDATE_MS = 10_000;\n", "import {\n\tmkdir,\n\tmkdirSync,\n\trealpath,\n\trealpathSync,\n\trmdir,\n\trmdirSync,\n\tstat,\n\tstatSync,\n\tutimes,\n\tutimesSync,\n} from \"node:fs\";\n\nexport const LOCKFILE_FS_ADAPTER = {\n\tmkdir,\n\tmkdirSync,\n\trealpath,\n\trealpathSync,\n\trmdir,\n\trmdirSync,\n\tstat,\n\tstatSync,\n\tutimes,\n\tutimesSync,\n};\n"],
5
- "mappings": ";;;;AAAA,IAAM,qBAAqB;AAC3B,IAAM,wBAAwB;AAEvB,SAAS,mBAAmB,OAA2B;AAC7D,QAAM,aAAa,wBAAwB,KAAK;AAChD,MAAI,CAAC,WAAY,QAAO;AACxB,MACC,oBAAoB,UAAU,KAC9B,MAAM,KAAK,UAAU,KACrB,WAAW,WAAW,GAAG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G,KAAK,2CAA2C,SAAS,EAAE;AAAA,IAC/E;AACA,WAAO;AAAA,EACR,SAAS,OAAO;AACf,QAAK,MAAgC,SAAS,SAAU,QAAO;AAC/D,UAAM;AAAA,EACP;AACD;AAEA,eAAe,WAAW,UAAkB;AAC3C,MAAI;AACH,UAAM,GAAG,MAAM,QAAQ;AACvB,WAAO;AAAA,EACR,SAAS,OAAO;AACf,QAAK,MAAgC,SAAS,SAAU,QAAO;AAC/D,UAAM;AAAA,EACP;AACD;",
6
- "names": []
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/setup-switch.ts"],
4
- "sourcesContent": ["import type { ExtensionCommandContext } from \"@earendil-works/pi-coding-agent\";\nimport { setSyncSetupCompletions } from \"./command.js\";\nimport {\n\tconfiguredSyncSetupNames,\n\tloadConfig,\n\tnormalizeOnSwitch,\n\tsyncConfigReviewIdentity,\n\tsyncSetupReviewIdentity,\n\tupdateLocalConfig,\n} from \"./config.js\";\nimport { SetupPullRequiresUiError } from \"./sync-errors.js\";\nimport { safeTerminalText } from \"./sync-format.js\";\nimport type { OnSwitchAction } from \"./types.js\";\n\nexport { SetupPullRequiresUiError } from \"./sync-errors.js\";\n\nexport const SETUP_SWITCH_ACTION_OPTIONS: ReadonlyArray<{\n\tlabel: string;\n\tvalue: OnSwitchAction;\n}> = [\n\t{ label: \"Ask before pull\", value: \"ask-before-pull\" },\n\t{ label: \"Start pull\", value: \"pull-after-switch\" },\n\t{ label: \"Switch only\", value: \"switch-only\" },\n];\n\nexport function setupSwitchActionLabel(action: OnSwitchAction) {\n\treturn SETUP_SWITCH_ACTION_OPTIONS.find((option) => option.value === action)?.label ?? action;\n}\n\nexport function setupSwitchActionFromLabel(label: string): OnSwitchAction | undefined {\n\treturn SETUP_SWITCH_ACTION_OPTIONS.find((option) => option.label === label)?.value;\n}\n\nexport async function saveOnSwitch(action: OnSwitchAction, signal?: AbortSignal) {\n\tawait updateLocalConfig((settings) => ({ ...settings, onSwitch: action }), signal);\n}\n\nexport type SetupPullOutcome = \"applied\" | \"cancelled\";\n\nexport interface SetupSwitchResult {\n\tpullApplied: boolean;\n}\n\nexport async function useSyncSetup(\n\tctx: ExtensionCommandContext,\n\tname: string,\n\tpullCurrentSetup?: (setup: string) => Promise<SetupPullOutcome | undefined>,\n\texpectedAction?: OnSwitchAction,\n\tsignal?: AbortSignal,\n\texpectedSetupIdentity?: string,\n): Promise<SetupSwitchResult> {\n\tconst normalized = name.trim();\n\tif (!normalized) throw new Error(\"Usage: /sync use <setup>\");\n\tconst loadedConfig = await loadConfig(normalized);\n\tconst reviewedSetupIdentity = expectedSetupIdentity ?? syncConfigReviewIdentity(loadedConfig);\n\tthrowIfAborted(signal);\n\tconst switchResult: { action: OnSwitchAction; switched: boolean } = {\n\t\taction: \"ask-before-pull\",\n\t\tswitched: false,\n\t};\n\tawait updateLocalConfig((current) => {\n\t\tthrowIfAborted(signal);\n\t\tconst setup = current.syncSetups[normalized];\n\t\tif (!setup) {\n\t\t\tthrow new Error(`Sync setup \u201C${safeTerminalText(normalized)}\u201D no longer exists.`);\n\t\t}\n\t\tconst connectionName = setup.storage.connection;\n\t\tconst connection = current.storageConnections[connectionName];\n\t\tif (\n\t\t\t!connection ||\n\t\t\tsyncSetupReviewIdentity(normalized, setup, connectionName, connection) !==\n\t\t\t\treviewedSetupIdentity\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Sync setup \u201C${safeTerminalText(normalized)}\u201D changed while the switch preview was open; reopen it and review the current destination.`,\n\t\t\t);\n\t\t}\n\t\tswitchResult.action = normalizeOnSwitch(current.onSwitch);\n\t\tif (expectedAction !== undefined && switchResult.action !== expectedAction) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Setup-switch behavior changed while the preview was open; reopen it and retry.\",\n\t\t\t);\n\t\t}\n\t\tif (switchResult.action === \"pull-after-switch\" && !ctx.hasUI) {\n\t\t\tthrow new SetupPullRequiresUiError(\n\t\t\t\t`Automatic setup pulls require interactive confirmation; sync setup \u201C${safeTerminalText(normalized)}\u201D was not switched. Use TUI or RPC mode.`,\n\t\t\t);\n\t\t}\n\t\tif (current.activeSyncSetup === normalized) return current;\n\t\tswitchResult.switched = true;\n\t\treturn { ...current, activeSyncSetup: normalized };\n\t}, signal);\n\tthrowIfAborted(signal);\n\tif (!switchResult.switched) {\n\t\tctx.ui.notify(`Sync setup \u201C${safeTerminalText(normalized)}\u201D is already current.`, \"info\");\n\t\treturn { pullApplied: false };\n\t}\n\tsetSyncSetupCompletions(await configuredSyncSetupNames());\n\tthrowIfAborted(signal);\n\n\tif (switchResult.action === \"switch-only\") {\n\t\tctx.ui.notify(`Switched to \u201C${safeTerminalText(normalized)}\u201D. No files were pulled.`, \"info\");\n\t\treturn { pullApplied: false };\n\t}\n\tif (switchResult.action === \"ask-before-pull\") {\n\t\tif (ctx.mode !== \"tui\") {\n\t\t\tctx.ui.notify(\n\t\t\t\t`Switched to \u201C${safeTerminalText(normalized)}\u201D. No files were pulled because confirmation requires TUI mode; run /sync pull to apply this setup.`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t\treturn { pullApplied: false };\n\t\t}\n\t\tconst confirmed = await ctx.ui.confirm(\n\t\t\t`Review a pull for sync setup \u201C${safeTerminalText(normalized)}\u201D now?`,\n\t\t\t\"pi-sync will check the remote snapshot and show the exact local writes and deletions before applying anything.\",\n\t\t\t{ signal },\n\t\t);\n\t\tthrowIfAborted(signal);\n\t\tif (!confirmed) {\n\t\t\tctx.ui.notify(\n\t\t\t\t`Switched to \u201C${safeTerminalText(normalized)}\u201D; files were not pulled.`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t\treturn { pullApplied: false };\n\t\t}\n\t}\n\n\tctx.ui.notify(\n\t\t`Switched to \u201C${safeTerminalText(normalized)}\u201D. Checking remote files for a reviewed pull\u2026`,\n\t\t\"info\",\n\t);\n\tif (!pullCurrentSetup) {\n\t\tthrow new Error(`Switched to \u201C${safeTerminalText(normalized)}\u201D, but pull is unavailable.`);\n\t}\n\tconst pullOutcome = await pullCurrentSetup(normalized);\n\tthrowIfAborted(signal);\n\tif (pullOutcome === \"cancelled\") {\n\t\tctx.ui.notify(\n\t\t\t`Pull cancelled; sync setup \u201C${safeTerminalText(normalized)}\u201D remains current and synced files were not changed.`,\n\t\t\t\"info\",\n\t\t);\n\t}\n\treturn { pullApplied: pullOutcome === \"applied\" };\n}\n\nfunction throwIfAborted(signal?: AbortSignal) {\n\tif (!signal?.aborted) return;\n\tthrow signal.reason instanceof Error\n\t\t? signal.reason\n\t\t: new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;AAgBO,IAAM,8BAGR;AAAA,EACJ,EAAE,OAAO,mBAAmB,OAAO,kBAAkB;AAAA,EACrD,EAAE,OAAO,cAAc,OAAO,oBAAoB;AAAA,EAClD,EAAE,OAAO,eAAe,OAAO,cAAc;AAC9C;AAEO,SAAS,uBAAuB,QAAwB;AAC9D,SAAO,4BAA4B,KAAK,CAAC,WAAW,OAAO,UAAU,MAAM,GAAG,SAAS;AACxF;AAEO,SAAS,2BAA2B,OAA2C;AACrF,SAAO,4BAA4B,KAAK,CAAC,WAAW,OAAO,UAAU,KAAK,GAAG;AAC9E;AAEA,eAAsB,aAAa,QAAwB,QAAsB;AAChF,QAAM,kBAAkB,CAAC,cAAc,EAAE,GAAG,UAAU,UAAU,OAAO,IAAI,MAAM;AAClF;AAQA,eAAsB,aACrB,KACA,MACA,kBACA,gBACA,QACA,uBAC6B;AAC7B,QAAM,aAAa,KAAK,KAAK;AAC7B,MAAI,CAAC,WAAY,OAAM,IAAI,MAAM,0BAA0B;AAC3D,QAAM,eAAe,MAAM,WAAW,UAAU;AAChD,QAAM,wBAAwB,yBAAyB,yBAAyB,YAAY;AAC5F,iBAAe,MAAM;AACrB,QAAM,eAA8D;AAAA,IACnE,QAAQ;AAAA,IACR,UAAU;AAAA,EACX;AACA,QAAM,kBAAkB,CAAC,YAAY;AAC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,UAAU,CAAC;AAAA,QAC5C;AAAA,MACD;AACA,aAAO,EAAE,aAAa,MAAM;AAAA,IAC7B;AACA,UAAM,YAAY,MAAM,IAAI,GAAG;AAAA,MAC9B,sCAAiC,iBAAiB,UAAU,CAAC;AAAA,MAC7D;AAAA,MACA,EAAE,OAAO;AAAA,IACV;AACA,mBAAe,MAAM;AACrB,QAAI,CAAC,WAAW;AACf,UAAI,GAAG;AAAA,QACN,qBAAgB,iBAAiB,UAAU,CAAC;AAAA,QAC5C;AAAA,MACD;AACA,aAAO,EAAE,aAAa,MAAM;AAAA,IAC7B;AAAA,EACD;AAEA,MAAI,GAAG;AAAA,IACN,qBAAgB,iBAAiB,UAAU,CAAC;AAAA,IAC5C;AAAA,EACD;AACA,MAAI,CAAC,kBAAkB;AACtB,UAAM,IAAI,MAAM,qBAAgB,iBAAiB,UAAU,CAAC,kCAA6B;AAAA,EAC1F;AACA,QAAM,cAAc,MAAM,iBAAiB,UAAU;AACrD,iBAAe,MAAM;AACrB,MAAI,gBAAgB,aAAa;AAChC,QAAI,GAAG;AAAA,MACN,oCAA+B,iBAAiB,UAAU,CAAC;AAAA,MAC3D;AAAA,IACD;AAAA,EACD;AACA,SAAO,EAAE,aAAa,gBAAgB,UAAU;AACjD;AAEA,SAAS,eAAe,QAAsB;AAC7C,MAAI,CAAC,QAAQ,QAAS;AACtB,QAAM,OAAO,kBAAkB,QAC5B,OAAO,SACP,IAAI,aAAa,6BAA6B,YAAY;AAC9D;",
6
- "names": []
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/snapshot-codec.ts"],
4
- "sourcesContent": ["import { Readable, Writable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport { promisify } from \"node:util\";\nimport { createGunzip, gzip } from \"node:zlib\";\nimport { snapshotSelectionInclude } from \"./sync-policy.js\";\nimport type { Snapshot } from \"./types.js\";\n\nconst VERSION = 1;\nconst MAX_DECOMPRESSED_SNAPSHOT_BYTES = 512 * 1024 * 1024;\nconst gzipAsync = promisify(gzip);\n\nexport async function encodeSnapshot(snapshot: Snapshot) {\n\tsnapshotSelectionInclude(snapshot);\n\treturn gzipAsync(Buffer.from(JSON.stringify(snapshot), \"utf8\"));\n}\n\nexport async function decodeSnapshot(\n\tbuffer: Buffer,\n\toptions: { signal?: AbortSignal; maxOutputLength?: number } = {},\n): Promise<Snapshot> {\n\tthrowIfAborted(options.signal);\n\tconst limit = options.maxOutputLength ?? MAX_DECOMPRESSED_SNAPSHOT_BYTES;\n\tconst chunks: Buffer[] = [];\n\tlet total = 0;\n\tconst sink = new Writable({\n\t\twrite(chunk: Buffer, _encoding, callback) {\n\t\t\ttotal += chunk.byteLength;\n\t\t\tif (total > limit) {\n\t\t\t\tcallback(new Error(`Decompressed snapshot exceeds the ${limit}-byte limit.`));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tchunks.push(Buffer.from(chunk));\n\t\t\tcallback();\n\t\t},\n\t});\n\tawait pipeline(Readable.from([buffer]), createGunzip(), sink, { signal: options.signal });\n\tthrowIfAborted(options.signal);\n\tconst parsed = JSON.parse(Buffer.concat(chunks, total).toString(\"utf8\")) as Snapshot;\n\tif (parsed.version !== VERSION || !Array.isArray(parsed.files)) {\n\t\tthrow new Error(\"Unsupported snapshot format.\");\n\t}\n\tsnapshotSelectionInclude(parsed);\n\treturn parsed;\n}\n\nfunction throwIfAborted(signal?: AbortSignal) {\n\tif (!signal?.aborted) return;\n\tthrow signal.reason instanceof Error\n\t\t? signal.reason\n\t\t: new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n"],
5
- "mappings": ";;;;;;;AAAA,SAAS,UAAU,gBAAgB;AACnC,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAC1B,SAAS,cAAc,YAAY;AAInC,IAAM,UAAU;AAChB,IAAM,kCAAkC,MAAM,OAAO;AACrD,IAAM,YAAY,UAAU,IAAI;AAEhC,eAAsB,eAAe,UAAoB;AACxD,2BAAyB,QAAQ;AACjC,SAAO,UAAU,OAAO,KAAK,KAAK,UAAU,QAAQ,GAAG,MAAM,CAAC;AAC/D;AAEA,eAAsB,eACrB,QACA,UAA8D,CAAC,GAC3C;AACpB,iBAAe,QAAQ,MAAM;AAC7B,QAAM,QAAQ,QAAQ,mBAAmB;AACzC,QAAM,SAAmB,CAAC;AAC1B,MAAI,QAAQ;AACZ,QAAM,OAAO,IAAI,SAAS;AAAA,IACzB,MAAM,OAAe,WAAW,UAAU;AACzC,eAAS,MAAM;AACf,UAAI,QAAQ,OAAO;AAClB,iBAAS,IAAI,MAAM,qCAAqC,KAAK,cAAc,CAAC;AAC5E;AAAA,MACD;AACA,aAAO,KAAK,OAAO,KAAK,KAAK,CAAC;AAC9B,eAAS;AAAA,IACV;AAAA,EACD,CAAC;AACD,QAAM,SAAS,SAAS,KAAK,CAAC,MAAM,CAAC,GAAG,aAAa,GAAG,MAAM,EAAE,QAAQ,QAAQ,OAAO,CAAC;AACxF,iBAAe,QAAQ,MAAM;AAC7B,QAAM,SAAS,KAAK,MAAM,OAAO,OAAO,QAAQ,KAAK,EAAE,SAAS,MAAM,CAAC;AACvE,MAAI,OAAO,YAAY,WAAW,CAAC,MAAM,QAAQ,OAAO,KAAK,GAAG;AAC/D,UAAM,IAAI,MAAM,8BAA8B;AAAA,EAC/C;AACA,2BAAyB,MAAM;AAC/B,SAAO;AACR;AAEA,SAAS,eAAe,QAAsB;AAC7C,MAAI,CAAC,QAAQ,QAAS;AACtB,QAAM,OAAO,kBAAkB,QAC5B,OAAO,SACP,IAAI,aAAa,6BAA6B,YAAY;AAC9D;",
6
- "names": []
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/snapshot.ts", "../../src/snapshot-paths.ts"],
4
- "sourcesContent": ["import { createHash, randomUUID } from \"node:crypto\";\nimport type { Dirent } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { agentDir, configuredSessionDir } from \"./config.js\";\nimport { isDeniedPath, posixJoin, safeJoin, toPosix } from \"./paths.js\";\nimport { sessionStorageRoot } from \"./snapshot-paths.js\";\n\nexport { isDeniedPath } from \"./paths.js\";\nexport { sessionStorageRoot } from \"./snapshot-paths.js\";\n\nimport {\n\tcanonicalSnapshotPathForConfig,\n\tcustomIncludePathsByLower,\n\tDEFAULT_SYNC_INCLUDE,\n\tincludeFromSelectionConfig,\n\tisConfiguredSnapshotPath,\n\tisPreservableUnmanagedSnapshotPath,\n\tnormalizeExtraFiles,\n\tnormalizeSyncFiles,\n\ttype SyncSelectionConfig,\n\tselectionForSnapshot,\n\tsnapshotSelectionInclude,\n\tsyncIncludeSelection,\n} from \"./sync-policy.js\";\nimport type { Snapshot, SnapshotFile, SnapshotOptions } from \"./types.js\";\n\nexport { canonicalSnapshotPathForConfig, isConfiguredSnapshotPath } from \"./sync-policy.js\";\n\nconst VERSION = 1;\nconst TOP_LEVEL_FILES: readonly string[] = DEFAULT_SYNC_INCLUDE.filter((name) =>\n\tname.includes(\".\"),\n);\nconst TOP_LEVEL_DIRS = new Set<string>(DEFAULT_SYNC_INCLUDE.filter((name) => !name.includes(\".\")));\nconst SECRET_PATTERNS = [\n\t/AWS_SECRET_ACCESS_KEY\\s*[=:]\\s*['\"]?[A-Za-z0-9/+]{35,}/i,\n\t/(ANTHROPIC|OPENAI|GEMINI|GOOGLE|FIRECRAWL|GITHUB|CLOUDFLARE|R2|S3)_[A-Z0-9_]*(KEY|TOKEN|SECRET)\\s*[=:]\\s*['\"]?[^\\s'\"]{12,}/i,\n\t/sk-ant-[A-Za-z0-9_-]{20,}/,\n\t/sk-[A-Za-z0-9]{20,}/,\n\t/gh[pousr]_[A-Za-z0-9_]{20,}/,\n];\n\nfunction selectTopLevelFileEntry(entries: Dirent[], fileName: string) {\n\tconst exact = entries.find((entry) => entry.isFile() && entry.name === fileName);\n\tif (exact) return exact;\n\tconst lower = fileName.toLowerCase();\n\treturn entries\n\t\t.filter((entry) => entry.isFile() && entry.name.toLowerCase() === lower)\n\t\t.sort((left, right) => left.name.localeCompare(right.name))[0];\n}\n\nfunction sha256(value: Buffer) {\n\treturn createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nfunction isSafeSnapshotPath(relativePath: string) {\n\tif (relativePath.includes(\"\\\\\")) return false;\n\tconst normalized = toPosix(relativePath);\n\treturn (\n\t\tBoolean(normalized) &&\n\t\tnormalized !== \".\" &&\n\t\tnormalized !== \"..\" &&\n\t\t!normalized.startsWith(\"../\") &&\n\t\t!path.posix.isAbsolute(normalized) &&\n\t\tpath.posix.normalize(normalized) === normalized &&\n\t\t!isDeniedPath(normalized)\n\t);\n}\n\nfunction snapshotsMatch(left: Snapshot, right: Snapshot) {\n\tconst leftHashes = new Map(left.files.map((file) => [file.path, file.sha256]));\n\tconst rightHashes = new Map(right.files.map((file) => [file.path, file.sha256]));\n\treturn (\n\t\tleft.syncSessions === right.syncSessions &&\n\t\tsameOptionalInclude(snapshotSelectionInclude(left), snapshotSelectionInclude(right)) &&\n\t\tleftHashes.size === rightHashes.size &&\n\t\t[...leftHashes].every(([filePath, hash]) => rightHashes.get(filePath) === hash)\n\t);\n}\n\nfunction snapshotId() {\n\treturn `${new Date().toISOString().replace(/[:.]/g, \"-\")}-${randomUUID().slice(0, 8)}`;\n}\n\nexport function regenerateSnapshotIdentity(snapshot: Snapshot): Snapshot {\n\treturn {\n\t\t...snapshot,\n\t\tid: snapshotId(),\n\t\tcreatedAt: new Date().toISOString(),\n\t\tmachine: os.hostname(),\n\t};\n}\n\nexport async function createSnapshot(\n\tprofile: string,\n\toptions: SnapshotOptions = {},\n): Promise<Snapshot> {\n\tconst include = effectiveInclude(options);\n\tconst syncSessions = include.includes(\"sessions\");\n\tconst files = await collectFiles(agentDir(), {\n\t\tinclude,\n\t\tsessionDir: options.sessionDir ?? (await configuredSessionDir()),\n\t});\n\treturn {\n\t\tversion: VERSION,\n\t\tid: snapshotId(),\n\t\tcreatedAt: new Date().toISOString(),\n\t\tmachine: os.hostname(),\n\t\tprofile,\n\t\tsyncSessions,\n\t\tselection: selectionForSnapshot(include),\n\t\tfiles,\n\t};\n}\n\nfunction effectiveInclude(options: SnapshotOptions) {\n\tif (options.include) return options.include;\n\treturn [\n\t\t...normalizeSyncFiles(options.syncFiles),\n\t\t...normalizeExtraFiles(options.extraFiles),\n\t\t...(options.syncSessions ? [\"sessions\"] : []),\n\t];\n}\n\nexport async function collectFiles(\n\troot: string,\n\toptions: SnapshotOptions = {},\n): Promise<SnapshotFile[]> {\n\tconst results: SnapshotFile[] = [];\n\tconst entries = await fs.readdir(root, { withFileTypes: true });\n\tconst selection = syncIncludeSelection(effectiveInclude(options));\n\tconst selectedFiles = new Set<string>(selection.builtIns);\n\tfor (const entry of entries) {\n\t\tif (entry.isDirectory() && TOP_LEVEL_DIRS.has(entry.name) && selectedFiles.has(entry.name)) {\n\t\t\tawait collectDirectory(results, root, entry.name);\n\t\t}\n\t}\n\tfor (const fileName of TOP_LEVEL_FILES) {\n\t\tif (!selectedFiles.has(fileName)) continue;\n\t\tconst entry = selectTopLevelFileEntry(entries, fileName);\n\t\tif (entry) await addFile(results, root, entry.name, fileName);\n\t}\n\tfor (const relativePath of selection.custom) {\n\t\tawait collectIncludedPath(results, root, relativePath);\n\t}\n\tif (selection.sessions) {\n\t\ttry {\n\t\t\tawait collectDirectory(results, sessionStorageRoot(root, options.sessionDir), \"\", {\n\t\t\t\tsessionsOnly: true,\n\t\t\t\tvirtualPrefix: \"sessions\",\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t\t}\n\t}\n\treturn results.sort((left, right) => left.path.localeCompare(right.path));\n}\n\nasync function collectIncludedPath(results: SnapshotFile[], root: string, relativePath: string) {\n\tconst absolutePath = safeJoin(root, relativePath);\n\ttry {\n\t\tconst stat = await fs.lstat(absolutePath);\n\t\tif (stat.isFile()) await addFile(results, root, relativePath);\n\t\telse if (stat.isDirectory()) await collectDirectory(results, root, relativePath);\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t\tif (!relativePath.includes(\"/\")) {\n\t\t\tconst entries = await fs.readdir(root, { withFileTypes: true });\n\t\t\tconst entry = selectTopLevelFileEntry(entries, relativePath);\n\t\t\tif (entry) await addFile(results, root, entry.name, relativePath);\n\t\t}\n\t}\n}\n\nasync function collectDirectory(\n\tresults: SnapshotFile[],\n\troot: string,\n\trelativeDirectory: string,\n\toptions: { sessionsOnly?: boolean; virtualPrefix?: string } = {},\n) {\n\tconst absoluteDirectory = path.join(root, relativeDirectory);\n\tfor (const entry of await fs.readdir(absoluteDirectory, { withFileTypes: true })) {\n\t\tconst relativePath = relativeDirectory ? posixJoin(relativeDirectory, entry.name) : entry.name;\n\t\tconst snapshotPath = options.virtualPrefix\n\t\t\t? posixJoin(options.virtualPrefix, relativePath)\n\t\t\t: relativePath;\n\t\tif (isDeniedPath(snapshotPath)) continue;\n\t\tif (entry.isDirectory()) {\n\t\t\tawait collectDirectory(results, root, relativePath, options);\n\t\t} else if (entry.isFile() && (!options.sessionsOnly || isSessionFilePath(snapshotPath))) {\n\t\t\tawait addFile(results, root, relativePath, snapshotPath);\n\t\t}\n\t}\n}\n\nasync function addFile(\n\tresults: SnapshotFile[],\n\troot: string,\n\trelativePath: string,\n\tsnapshotPath = relativePath,\n) {\n\tif (!isSafeSnapshotPath(snapshotPath)) return;\n\tconst absolutePath = safeJoin(root, relativePath);\n\tconst content = await fs.readFile(absolutePath);\n\tresults.push({\n\t\tpath: snapshotPath,\n\t\tcontentBase64: content.toString(\"base64\"),\n\t\tsha256: sha256(content),\n\t});\n}\n\nexport function isSessionPath(relativePath: string) {\n\treturn toPosix(relativePath).startsWith(\"sessions/\");\n}\n\nexport function isSessionFilePath(relativePath: string) {\n\tconst normalized = toPosix(relativePath);\n\treturn isSessionPath(normalized) && normalized.endsWith(\".jsonl\");\n}\n\nexport function sessionSnapshotPathFromAbsolute(\n\tsessionFile: string,\n\tconfiguredSessionDir?: string,\n) {\n\tconst relativePath = toPosix(\n\t\tpath.relative(sessionStorageRoot(agentDir(), configuredSessionDir), sessionFile),\n\t);\n\tif (!relativePath || relativePath.startsWith(\"../\") || path.posix.isAbsolute(relativePath)) {\n\t\treturn undefined;\n\t}\n\tconst snapshotPath = posixJoin(\"sessions\", relativePath);\n\treturn isSessionFilePath(snapshotPath) ? snapshotPath : undefined;\n}\n\nexport function snapshotTarget(root: string, relativePath: string, configuredSessionDir?: string) {\n\tif (isSessionPath(relativePath)) {\n\t\treturn safeJoin(\n\t\t\tsessionStorageRoot(root, configuredSessionDir),\n\t\t\trelativePath.slice(\"sessions/\".length),\n\t\t);\n\t}\n\treturn safeJoin(root, relativePath);\n}\n\nexport function snapshotIncludesSessions(snapshot: Snapshot) {\n\treturn (\n\t\tsnapshot.syncSessions === true ||\n\t\tsnapshotSelectionInclude(snapshot)?.includes(\"sessions\") === true ||\n\t\tsnapshot.files.some((file) => isSessionPath(file.path))\n\t);\n}\n\nexport function filterSnapshotForConfigPolicy(\n\tsnapshot: Snapshot,\n\tconfig: SyncSelectionConfig,\n\toptions: { regenerateId?: boolean } = {},\n) {\n\tconst include = includeFromSelectionConfig(config);\n\tconst includePaths = customIncludePathsByLower(include);\n\tconst filtered = {\n\t\t...snapshot,\n\t\tsyncSessions: include.includes(\"sessions\") ? snapshot.syncSessions : false,\n\t\tselection: selectionForSnapshot(include),\n\t\tfiles: canonicalizeSnapshotFilesForConfig(snapshot.files, config, includePaths),\n\t};\n\tif (!options.regenerateId || snapshotsMatch(snapshot, filtered)) return filtered;\n\treturn {\n\t\t...filtered,\n\t\tid: snapshotId(),\n\t\tcreatedAt: new Date().toISOString(),\n\t\tmachine: os.hostname(),\n\t};\n}\n\nfunction canonicalizeSnapshotFilesForConfig(\n\tfiles: SnapshotFile[],\n\tconfig: SyncSelectionConfig,\n\tincludePaths: Map<string, string>,\n) {\n\tconst configuredFiles: SnapshotFile[] = [];\n\tconst extraCandidates = new Map<\n\t\tstring,\n\t\t{ exact: boolean; file: SnapshotFile; originalPath: string }\n\t>();\n\tfor (const file of files) {\n\t\tconst normalized = toPosix(file.path);\n\t\tif (!isSafeSnapshotPath(file.path) || !isConfiguredSnapshotPath(normalized, config)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (normalized.includes(\"/\")) {\n\t\t\tconfiguredFiles.push(normalized === file.path ? file : { ...file, path: normalized });\n\t\t\tcontinue;\n\t\t}\n\t\tconst topLevelPath = canonicalSnapshotPathForConfig(normalized, includePaths);\n\t\tconst candidate = {\n\t\t\texact: normalized === topLevelPath,\n\t\t\tfile: { ...file, path: topLevelPath },\n\t\t\toriginalPath: normalized,\n\t\t};\n\t\tconst current = extraCandidates.get(topLevelPath.toLowerCase());\n\t\tif (!current || isPreferredExtraCandidate(candidate, current)) {\n\t\t\textraCandidates.set(topLevelPath.toLowerCase(), candidate);\n\t\t}\n\t}\n\treturn [\n\t\t...configuredFiles,\n\t\t...[...extraCandidates.values()].map((candidate) => candidate.file),\n\t].sort((left, right) => left.path.localeCompare(right.path));\n}\n\nfunction isPreferredExtraCandidate(\n\tleft: { exact: boolean; originalPath: string },\n\tright: { exact: boolean; originalPath: string },\n) {\n\tif (left.exact !== right.exact) return left.exact;\n\treturn left.originalPath.localeCompare(right.originalPath) < 0;\n}\n\nexport function snapshotWithoutSessions(snapshot: Snapshot) {\n\tconst files = snapshot.files.filter((file) => !isSessionPath(file.path));\n\tconst include = snapshotSelectionInclude(snapshot)?.filter((item) => item !== \"sessions\");\n\tif (\n\t\tfiles.length === snapshot.files.length &&\n\t\tsnapshot.syncSessions !== true &&\n\t\tinclude?.length === snapshot.selection?.include.length\n\t) {\n\t\treturn snapshot;\n\t}\n\treturn {\n\t\t...snapshot,\n\t\tid: snapshotId(),\n\t\tcreatedAt: new Date().toISOString(),\n\t\tmachine: os.hostname(),\n\t\tsyncSessions: false,\n\t\t...(include ? { selection: selectionForSnapshot(include) } : {}),\n\t\tfiles,\n\t};\n}\n\nexport function scanSnapshot(snapshot: Snapshot) {\n\tconst findings: string[] = [];\n\tfor (const file of snapshot.files) {\n\t\tconst content = Buffer.from(file.contentBase64, \"base64\");\n\t\tif (content.includes(0)) continue;\n\t\tconst text = content.toString(\"utf8\");\n\t\tfor (const pattern of SECRET_PATTERNS) {\n\t\t\tif (pattern.test(text)) {\n\t\t\t\tfindings.push(file.path);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn findings;\n}\n\nexport function mergeRemotePreservedFiles(\n\tlocal: Snapshot,\n\tremote: Snapshot,\n\tconfig: SyncSelectionConfig,\n) {\n\tconst localPathNames = new Set(local.files.map((file) => file.path.toLowerCase()));\n\tconst preservedPathNames = new Set<string>();\n\tconst preserved = remote.files.filter((file) => {\n\t\tconst normalized = toPosix(file.path);\n\t\tconst lower = normalized.toLowerCase();\n\t\tif (\n\t\t\tlocalPathNames.has(lower) ||\n\t\t\tpreservedPathNames.has(lower) ||\n\t\t\t!isSafeSnapshotPath(file.path) ||\n\t\t\tisConfiguredSnapshotPath(normalized, config) ||\n\t\t\t!isPreservableUnmanagedSnapshotPath(normalized)\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tpreservedPathNames.add(lower);\n\t\treturn true;\n\t});\n\tif (preserved.length === 0) return local;\n\treturn {\n\t\t...local,\n\t\tid: snapshotId(),\n\t\tcreatedAt: new Date().toISOString(),\n\t\tmachine: os.hostname(),\n\t\tsyncSessions: snapshotIncludesSessions(local) || snapshotIncludesSessions(remote),\n\t\tfiles: [...local.files, ...preserved].sort((left, right) =>\n\t\t\tleft.path.localeCompare(right.path),\n\t\t),\n\t};\n}\n\nexport function mergeRemoteSessionFiles(local: Snapshot, remote: Snapshot) {\n\tconst remoteSessions = remote.files.filter((file) => {\n\t\tconst normalized = toPosix(file.path);\n\t\treturn isSessionFilePath(normalized) && isSafeSnapshotPath(file.path);\n\t});\n\tif (remoteSessions.length === 0 && !snapshotIncludesSessions(remote)) return local;\n\tconst localInclude = snapshotSelectionInclude(local);\n\treturn {\n\t\t...local,\n\t\tid: snapshotId(),\n\t\tcreatedAt: new Date().toISOString(),\n\t\tmachine: os.hostname(),\n\t\tsyncSessions: true,\n\t\t...(localInclude\n\t\t\t? {\n\t\t\t\t\tselection: selectionForSnapshot(\n\t\t\t\t\t\tlocalInclude.includes(\"sessions\") ? localInclude : [...localInclude, \"sessions\"],\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t\tfiles: [...local.files.filter((file) => !isSessionPath(file.path)), ...remoteSessions].sort(\n\t\t\t(left, right) => left.path.localeCompare(right.path),\n\t\t),\n\t};\n}\n\nfunction sameOptionalInclude(left: string[] | undefined, right: string[] | undefined) {\n\tif (!left || !right) return left === right;\n\treturn left.length === right.length && left.every((item, index) => item === right[index]);\n}\n", "import path from \"node:path\";\n\nfunction expandHome(value: string) {\n\tif (value === \"~\") return process.env.HOME ?? value;\n\tif (value.startsWith(\"~/\")) return path.join(process.env.HOME ?? \"~\", value.slice(2));\n\treturn value;\n}\n\nexport function sessionStorageRoot(root: string, configuredSessionDir?: string) {\n\treturn configuredSessionDir\n\t\t? path.resolve(expandHome(configuredSessionDir))\n\t\t: path.resolve(root, \"sessions\");\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,kBAAkB;AAEvC,OAAO,QAAQ;AACf,OAAO,QAAQ;AACf,OAAOA,WAAU;;;ACJjB,OAAO,UAAU;AAEjB,SAAS,WAAW,OAAe;AAClC,MAAI,UAAU,IAAK,QAAO,QAAQ,IAAI,QAAQ;AAC9C,MAAI,MAAM,WAAW,IAAI,EAAG,QAAO,KAAK,KAAK,QAAQ,IAAI,QAAQ,KAAK,MAAM,MAAM,CAAC,CAAC;AACpF,SAAO;AACR;AAEO,SAAS,mBAAmB,MAAcC,uBAA+B;AAC/E,SAAOA,wBACJ,KAAK,QAAQ,WAAWA,qBAAoB,CAAC,IAC7C,KAAK,QAAQ,M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C,QAAQ,CAAC,MAAO,QAAO,SAAS;AACrC,SAAO,KAAK,WAAW,MAAM,UAAU,KAAK,MAAM,CAAC,MAAM,UAAU,SAAS,MAAM,KAAK,CAAC;AACzF;",
6
- "names": ["path", "configuredSessionDir", "path", "configuredSessionDir"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/sync-state.ts"],
4
- "sourcesContent": ["import { toPosix } from \"./paths.js\";\nimport {\n\tcanonicalSnapshotPathForConfig,\n\tfilterSnapshotForConfigPolicy,\n\tisConfiguredSnapshotPath,\n\tisSessionPath,\n} from \"./snapshot.js\";\nimport type { RemoteHead } from \"./sync-backend.js\";\nimport {\n\tcustomIncludePathsByLower,\n\tincludeFromSelectionConfig,\n\tnormalizeSyncInclude,\n\ttype SyncSelectionConfig,\n} from \"./sync-policy.js\";\nimport type { Snapshot, SyncState } from \"./types.js\";\n\ntype SyncPolicyConfig = SyncSelectionConfig;\n\nexport function hasLocalChanges(local: Snapshot, state: SyncState, config: SyncPolicyConfig) {\n\treturn !sameHashes(fileHashMap(local), stateHashMapForConfig(state, config));\n}\n\nexport function remoteChangedSinceState(\n\thead: RemoteHead | undefined,\n\tstate: SyncState,\n\tconfig: SyncPolicyConfig,\n\tsameRevision: (left: string, right: string) => boolean,\n) {\n\tif (!head) return Boolean(state.lastAppliedSnapshot);\n\tif (head.snapshotId !== state.lastAppliedSnapshot) return true;\n\tif (state.lastRemoteRevision && !sameRevision(head.revision, state.lastRemoteRevision))\n\t\treturn true;\n\tif (syncIncludeChanged(state, config)) return true;\n\treturn (\n\t\tincludeFromSelectionConfig(config).includes(\"sessions\") &&\n\t\t!state.include?.includes(\"sessions\") &&\n\t\thead.syncSessions\n\t);\n}\n\nexport function hasRemoteChanges(\n\tremote: Snapshot,\n\tstate: SyncState,\n\tconfig: SyncPolicyConfig,\n\tignoredPaths = new Set<string>(),\n) {\n\tif (remote.id === state.lastAppliedSnapshot && !syncPolicyChanged(state, config)) return false;\n\treturn !snapshotHashesMatchState(\n\t\tfilterSnapshotForConfigPolicy(remote, config),\n\t\tstate,\n\t\tconfig,\n\t\tignoredPaths,\n\t);\n}\n\nexport function sameHashes(left: Record<string, string>, right: Record<string, string>) {\n\tconst keys = new Set([...Object.keys(left), ...Object.keys(right)]);\n\tfor (const key of keys) if (left[key] !== right[key]) return false;\n\treturn true;\n}\n\nexport function fileHashMap(snapshot: Snapshot) {\n\treturn Object.fromEntries(snapshot.files.map((file) => [file.path, file.sha256]));\n}\n\nfunction stateHashMapForConfig(state: SyncState, config: SyncPolicyConfig) {\n\tconst includePaths = customIncludePathsByLower(includeFromSelectionConfig(config));\n\treturn Object.fromEntries(\n\t\tObject.entries(state.lastFileHashes)\n\t\t\t.filter(([filePath]) => isConfiguredSnapshotPath(filePath, config))\n\t\t\t.map(([filePath, hash]) => [canonicalSnapshotPathForConfig(filePath, includePaths), hash]),\n\t);\n}\n\nexport function snapshotHashesMatchState(\n\tsnapshot: Snapshot,\n\tstate: SyncState,\n\tconfig: SyncPolicyConfig,\n\tignoredPaths = new Set<string>(),\n) {\n\treturn sameHashes(\n\t\twithoutHashPaths(fileHashMap(snapshot), ignoredPaths),\n\t\twithoutHashPaths(stateHashMapForConfig(state, config), ignoredPaths),\n\t);\n}\n\nexport function snapshotsMatch(left: Snapshot, right: Snapshot) {\n\treturn (\n\t\tleft.syncSessions === right.syncSessions && sameHashes(fileHashMap(left), fileHashMap(right))\n\t);\n}\n\nfunction withoutHashPaths(hashes: Record<string, string>, ignoredPaths: Set<string>) {\n\tif (ignoredPaths.size === 0) return hashes;\n\treturn Object.fromEntries(\n\t\tObject.entries(hashes).filter(([filePath]) => !ignoredPaths.has(toPosix(filePath))),\n\t);\n}\n\nexport function syncPolicyChanged(state: SyncState, config: SyncPolicyConfig) {\n\treturn syncIncludeChanged(state, config);\n}\n\nexport function shouldRefreshSyncedState(\n\tremote: Snapshot,\n\thead: RemoteHead | undefined,\n\tstate: SyncState,\n\tconfig: SyncPolicyConfig,\n\tsameRevision: (left: string, right: string) => boolean,\n) {\n\treturn (\n\t\tremote.id !== state.lastAppliedSnapshot ||\n\t\tBoolean(\n\t\t\thead && (!state.lastRemoteRevision || !sameRevision(head.revision, state.lastRemoteRevision)),\n\t\t) ||\n\t\tsyncPolicyChanged(state, config)\n\t);\n}\n\nfunction syncIncludeChanged(state: SyncState, config: SyncPolicyConfig) {\n\tconst stored = state.include\n\t\t? normalizeSyncInclude(state.include)\n\t\t: includeFromSelectionConfig(state);\n\tconst current = includeFromSelectionConfig(config);\n\treturn stored.length !== current.length || stored.some((item, index) => item !== current[index]);\n}\n\nexport function settingsHashMap(snapshot: Snapshot) {\n\treturn Object.fromEntries(\n\t\tsnapshot.files\n\t\t\t.filter((file) => !isSessionPath(file.path))\n\t\t\t.map((file) => [file.path, file.sha256]),\n\t);\n}\n\nexport function sessionHashMap(snapshot: Snapshot) {\n\treturn Object.fromEntries(\n\t\tsnapshot.files\n\t\t\t.filter((file) => isSessionPath(file.path))\n\t\t\t.map((file) => [file.path, file.sha256]),\n\t);\n}\n\nexport function settingsHashMapFromState(state: SyncState) {\n\treturn Object.fromEntries(\n\t\tObject.entries(state.lastFileHashes).filter(([filePath]) => !isSessionPath(filePath)),\n\t);\n}\n\nexport function settingsHashesMatchState(remote: Snapshot, state: SyncState) {\n\treturn sameHashes(settingsHashMap(remote), settingsHashMapFromState(state));\n}\n\nexport function canPullRemoteSettingsOnFirstSync(local: Snapshot, remote: Snapshot) {\n\tconst remoteSettings = settingsHashMap(remote);\n\treturn Object.entries(settingsHashMap(local)).every(\n\t\t([filePath, hash]) => remoteSettings[filePath] === hash,\n\t);\n}\n\nexport function canPullRemoteSessionsOnFirstSync(local: Snapshot, remote: Snapshot) {\n\tconst localSessions = sessionHashMap(local);\n\tconst remoteSessions = sessionHashMap(remote);\n\treturn Object.entries(localSessions).every(\n\t\t([filePath, hash]) => remoteSessions[filePath] === hash,\n\t);\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;A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,MACP,OAAO,CAAC,SAAS,CAAC,cAAc,KAAK,IAAI,CAAC,EAC1C,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM,KAAK,MAAM,CAAC;AAAA,EACzC;AACD;AAEO,SAAS,eAAe,UAAoB;AAClD,SAAO,OAAO;AAAA,IACb,SAAS,MACP,OAAO,CAAC,SAAS,cAAc,KAAK,IAAI,CAAC,EACzC,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM,KAAK,MAAM,CAAC;AAAA,EACzC;AACD;AAEO,SAAS,yBAAyB,OAAkB;AAC1D,SAAO,OAAO;AAAA,IACb,OAAO,QAAQ,MAAM,cAAc,EAAE,OAAO,CAAC,CAAC,QAAQ,MAAM,CAAC,cAAc,QAAQ,CAAC;AAAA,EACrF;AACD;AAEO,SAAS,yBAAyB,QAAkB,OAAkB;AAC5E,SAAO,WAAW,gBAAgB,MAAM,GAAG,yBAAyB,KAAK,CAAC;AAC3E;AAEO,SAAS,iCAAiC,OAAiB,QAAkB;AACnF,QAAM,iBAAiB,gBAAgB,MAAM;AAC7C,SAAO,OAAO,QAAQ,gBAAgB,KAAK,CAAC,EAAE;AAAA,IAC7C,CAAC,CAAC,UAAU,IAAI,MAAM,eAAe,QAAQ,MAAM;AAAA,EACpD;AACD;AAEO,SAAS,iCAAiC,OAAiB,QAAkB;AACnF,QAAM,gBAAgB,eAAe,KAAK;AAC1C,QAAM,iBAAiB,eAAe,MAAM;AAC5C,SAAO,OAAO,QAAQ,aAAa,EAAE;AAAA,IACpC,CAAC,CAAC,UAAU,IAAI,MAAM,eAAe,QAAQ,MAAM;AAAA,EACpD;AACD;",
6
- "names": []
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/lock.ts"],
4
- "sourcesContent": ["import { randomUUID } from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport type { ExtensionCommandContext } from \"@earendil-works/pi-coding-agent\";\nimport lockfile from \"proper-lockfile\";\nimport { ensureStateDir, lockPath } from \"./config.js\";\nimport { LOCK_GUARD_STALE_MS, LOCK_GUARD_UPDATE_MS } from \"./lock-policy.js\";\nimport { LOCKFILE_FS_ADAPTER } from \"./lockfile-fs.js\";\nimport type { CommandOptions, LockFile } from \"./types.js\";\n\nconst LOCK_STALE_MS = 30 * 60 * 1000;\nconst MAX_PROCESS_ID = 2_147_483_647;\n\ninterface Guard {\n\trelease: () => Promise<void>;\n\tthrowIfCompromised: () => void;\n\tisCompromised: () => boolean;\n}\n\nexport type LockInspection =\n\t| { status: \"missing\" }\n\t| { status: \"unreadable\" }\n\t| { status: \"valid\"; lock: LockFile };\n\nexport async function withLock<T>(\n\tcommand: string,\n\tfn: () => Promise<T>,\n\toptions: { reclaimStale?: boolean } = {},\n): Promise<T> {\n\tawait ensureStateDir();\n\tconst lock: LockFile = {\n\t\tid: randomUUID(),\n\t\tpid: process.pid,\n\t\tcommand,\n\t\tstartedAt: new Date().toISOString(),\n\t};\n\tlet guard: Guard | undefined;\n\tlet result: T | undefined;\n\tlet failed = false;\n\tlet failure: unknown;\n\ttry {\n\t\ttry {\n\t\t\tguard = await acquireGuard();\n\t\t} catch (error) {\n\t\t\tif (!isLockHeldError(error)) throw error;\n\t\t\tthrow await describeHeldLock();\n\t\t}\n\n\t\tlet inspection = await inspectLock();\n\t\tif (inspection.status === \"valid\" && isStaleLock(inspection.lock)) {\n\t\t\tif (!options.reclaimStale) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`pi-sync lock is stale (pid ${inspection.lock.pid}). Run /sync unlock --stale, then retry.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tguard.throwIfCompromised();\n\t\t\tconst rechecked = await inspectLock();\n\t\t\tif (\n\t\t\t\trechecked.status !== \"valid\" ||\n\t\t\t\trechecked.lock.id !== inspection.lock.id ||\n\t\t\t\t!isStaleLock(rechecked.lock)\n\t\t\t) {\n\t\t\t\tthrow new Error(\"pi-sync lock changed while preparing transaction recovery; retry.\");\n\t\t\t}\n\t\t\tawait fs.rm(lockPath(), { force: true });\n\t\t\tinspection = { status: \"missing\" };\n\t\t}\n\t\tif (inspection.status === \"valid\") {\n\t\t\tthrow new Error(\n\t\t\t\t`pi-sync is already running (${inspection.lock.command}, pid ${inspection.lock.pid}, started ${inspection.lock.startedAt}).`,\n\t\t\t);\n\t\t}\n\t\tif (inspection.status === \"unreadable\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"pi-sync lock metadata is unreadable. Run /sync unlock --stale after verifying no sync is running.\",\n\t\t\t);\n\t\t}\n\n\t\tawait fs.writeFile(lockPath(), JSON.stringify(lock, null, \"\\t\"), { flag: \"wx\" });\n\t\tguard.throwIfCompromised();\n\t\tresult = await fn();\n\t\tguard.throwIfCompromised();\n\t} catch (error) {\n\t\tfailed = true;\n\t\tfailure = error;\n\t}\n\n\ttry {\n\t\tconst current = await readLock();\n\t\tif (current?.id === lock.id) await fs.rm(lockPath(), { force: true });\n\t} catch (error) {\n\t\tif (!failed) {\n\t\t\tfailed = true;\n\t\t\tfailure = error;\n\t\t}\n\t}\n\tif (guard) {\n\t\tconst releaseError = await releaseGuard(guard);\n\t\tif (releaseError && !failed) {\n\t\t\tfailed = true;\n\t\t\tfailure = releaseError;\n\t\t}\n\t}\n\tif (failed) throw failure;\n\treturn result as T;\n}\n\nexport async function inspectLock(): Promise<LockInspection> {\n\ttry {\n\t\tconst text = await fs.readFile(lockPath(), \"utf8\");\n\t\tif (text.trim().length === 0) return { status: \"unreadable\" };\n\t\tconst parsed = JSON.parse(text) as unknown;\n\t\treturn isLockFile(parsed) ? { status: \"valid\", lock: parsed } : { status: \"unreadable\" };\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { status: \"missing\" };\n\t\tif (error instanceof SyntaxError) return { status: \"unreadable\" };\n\t\tthrow error;\n\t}\n}\n\nexport async function readLock(): Promise<LockFile | undefined> {\n\tconst inspection = await inspectLock();\n\treturn inspection.status === \"valid\" ? inspection.lock : undefined;\n}\n\nexport async function lockFileExists(): Promise<boolean> {\n\ttry {\n\t\tawait fs.stat(lockPath());\n\t\treturn true;\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n\t\tthrow error;\n\t}\n}\n\nexport function isLockGuardHeld() {\n\treturn lockfile.check(lockPath(), {\n\t\tfs: LOCKFILE_FS_ADAPTER,\n\t\tlockfilePath: `${lockPath()}.guard`,\n\t\trealpath: false,\n\t\tstale: LOCK_GUARD_STALE_MS,\n\t});\n}\n\nexport function isStaleLock(lock: LockFile) {\n\ttry {\n\t\tprocess.kill(lock.pid, 0);\n\t\treturn false;\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ESRCH\") return true;\n\t\treturn Date.now() - Date.parse(lock.startedAt) > LOCK_STALE_MS;\n\t}\n}\n\nexport async function unlock(ctx: ExtensionCommandContext, options: CommandOptions) {\n\tthrowIfAborted(options.signal);\n\tawait ensureStateDir();\n\tthrowIfAborted(options.signal);\n\tlet guard: Guard;\n\ttry {\n\t\tguard = await acquireGuard();\n\t} catch (error) {\n\t\tif (!isLockHeldError(error)) throw error;\n\t\tctx.ui.notify((await describeHeldLock()).message, \"warning\");\n\t\treturn;\n\t}\n\n\tlet failed = false;\n\tlet failure: unknown;\n\ttry {\n\t\tawait unlockGuarded(ctx, options);\n\t} catch (error) {\n\t\tfailed = true;\n\t\tfailure = error;\n\t}\n\tconst releaseError = await releaseGuard(guard);\n\tif (releaseError && !failed) {\n\t\tfailed = true;\n\t\tfailure = releaseError;\n\t}\n\tif (failed) throw failure;\n}\n\nasync function unlockGuarded(ctx: ExtensionCommandContext, options: CommandOptions) {\n\tthrowIfAborted(options.signal);\n\tlet inspection = await inspectLock();\n\tthrowIfAborted(options.signal);\n\tif (inspection.status === \"missing\") {\n\t\tctx.ui.notify(\"No pi-sync lock is present.\", \"info\");\n\t\treturn;\n\t}\n\tif (inspection.status === \"unreadable\") {\n\t\tif (!options.stale) {\n\t\t\tctx.ui.notify(\n\t\t\t\t\"Pi-sync lock metadata is unreadable. Use /sync unlock --stale only after verifying no sync is running.\",\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tinspection = await inspectLock();\n\t\tthrowIfAborted(options.signal);\n\t\tif (inspection.status === \"unreadable\") {\n\t\t\t// Legacy writers expose an empty file before writing owner metadata, so no\n\t\t\t// automatic test can prove this file is abandoned. The explicit --stale\n\t\t\t// flag is the user's confirmation that no legacy sync is still running.\n\t\t\tthrowIfAborted(options.signal);\n\t\t\tawait fs.rm(lockPath(), { force: true });\n\t\t\tif (!options.signal?.aborted) {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\"Removed unreadable pi-sync lock. No settings, files, sync state, or remote data were changed.\",\n\t\t\t\t\t\"info\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (inspection.status === \"missing\") {\n\t\t\tctx.ui.notify(\"No pi-sync lock is present.\", \"info\");\n\t\t\treturn;\n\t\t}\n\t}\n\tif (!isStaleLock(inspection.lock)) {\n\t\tctx.ui.notify(\"Lock owner is still live; refusing to remove it.\", \"warning\");\n\t\treturn;\n\t}\n\tthrowIfAborted(options.signal);\n\tawait fs.rm(lockPath(), { force: true });\n\tif (!options.signal?.aborted) {\n\t\tctx.ui.notify(\n\t\t\t\"Removed stale pi-sync lock. No settings, files, sync state, or remote data were changed.\",\n\t\t\t\"info\",\n\t\t);\n\t}\n}\n\nfunction throwIfAborted(signal?: AbortSignal) {\n\tif (!signal?.aborted) return;\n\tthrow signal.reason instanceof Error\n\t\t? signal.reason\n\t\t: new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n\nasync function releaseGuard(guard: Guard) {\n\ttry {\n\t\tawait guard.release();\n\t\treturn undefined;\n\t} catch (error) {\n\t\treturn guard.isCompromised() ? undefined : error;\n\t}\n}\n\nasync function acquireGuard(): Promise<Guard> {\n\tlet compromisedError: Error | undefined;\n\tconst release = await lockfile.lock(lockPath(), {\n\t\tfs: LOCKFILE_FS_ADAPTER,\n\t\tlockfilePath: `${lockPath()}.guard`,\n\t\trealpath: false,\n\t\tstale: LOCK_GUARD_STALE_MS,\n\t\tupdate: LOCK_GUARD_UPDATE_MS,\n\t\tonCompromised: (error) => {\n\t\t\tcompromisedError = error;\n\t\t},\n\t});\n\treturn {\n\t\trelease,\n\t\tthrowIfCompromised: () => {\n\t\t\tif (compromisedError) throw compromisedError;\n\t\t},\n\t\tisCompromised: () => compromisedError !== undefined,\n\t};\n}\n\nasync function describeHeldLock() {\n\tconst current = await readLock();\n\tif (current && isStaleLock(current)) {\n\t\treturn new Error(\"pi-sync lock owner exited; retry shortly while the lock guard expires.\");\n\t}\n\tif (current) {\n\t\treturn new Error(\n\t\t\t`Pi-sync is currently running (${current.command}, pid ${current.pid}, started ${current.startedAt}).`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t\"Pi-sync is currently running (lock metadata is unreadable or still being written).\",\n\t);\n}\n\nfunction isLockHeldError(error: unknown) {\n\treturn (error as NodeJS.ErrnoException).code === \"ELOCKED\";\n}\n\nfunction isLockFile(value: unknown): value is LockFile {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst lock = value as Partial<LockFile>;\n\treturn (\n\t\ttypeof lock.id === \"string\" &&\n\t\tlock.id.length > 0 &&\n\t\tNumber.isInteger(lock.pid) &&\n\t\t(lock.pid ?? 0) > 0 &&\n\t\t(lock.pid ?? 0) <= MAX_PROCESS_ID &&\n\t\ttypeof lock.command === \"string\" &&\n\t\tlock.command.length > 0 &&\n\t\ttypeof lock.startedAt === \"string\" &&\n\t\tNumber.isFinite(Date.parse(lock.startedAt))\n\t);\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,OAAO,QAAQ;AAEf,OAAO,cAAc;AAMrB,IAAM,gBAAgB,KAAK,KAAK;AAChC,IAAM,iBAAiB;AAavB,eAAsB,SACrB,SACA,IACA,UAAsC,CAAC,GAC1B;AACb,QAAM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I,WAAW,YAAY,OAAO,GAAG;AACpC,WAAO,IAAI,MAAM,wEAAwE;AAAA,EAC1F;AACA,MAAI,SAAS;AACZ,WAAO,IAAI;AAAA,MACV,iCAAiC,QAAQ,OAAO,SAAS,QAAQ,GAAG,aAAa,QAAQ,SAAS;AAAA,IACnG;AAAA,EACD;AACA,SAAO,IAAI;AAAA,IACV;AAAA,EACD;AACD;AAEA,SAAS,gBAAgB,OAAgB;AACxC,SAAQ,MAAgC,SAAS;AAClD;AAEA,SAAS,WAAW,OAAmC;AACtD,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,EAAG,QAAO;AACxE,QAAM,OAAO;AACb,SACC,OAAO,KAAK,OAAO,YACnB,KAAK,GAAG,SAAS,KACjB,OAAO,UAAU,KAAK,GAAG,MACxB,KAAK,OAAO,KAAK,MACjB,KAAK,OAAO,MAAM,kBACnB,OAAO,KAAK,YAAY,YACxB,KAAK,QAAQ,SAAS,KACtB,OAAO,KAAK,cAAc,YAC1B,OAAO,SAAS,KAAK,MAAM,KAAK,SAAS,CAAC;AAE5C;",
6
- "names": []
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/snapshot-transaction.ts"],
4
- "sourcesContent": ["import { randomUUID } from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { agentDir, stateDir } from \"./config.js\";\nimport { withLock } from \"./lock.js\";\nimport { assertWithinRoot, isPathInside } from \"./paths.js\";\nimport { sessionStorageRoot } from \"./snapshot-paths.js\";\nimport type { SnapshotApplyPlan } from \"./types.js\";\n\nconst JOURNAL_VERSION = 1;\n\ninterface TransactionEntry {\n\ttarget: string;\n\tbackupName: string;\n\tkind: \"missing\" | \"file\" | \"directory\" | \"symlink\";\n\tlinkTarget?: string;\n}\n\ninterface TransactionJournal {\n\tversion: number;\n\troot: string;\n\tsessionRoot?: string;\n\tentries: TransactionEntry[];\n}\n\nexport async function applySnapshotTransaction(\n\tplan: SnapshotApplyPlan,\n\toptions: { sessionDir?: string } = {},\n) {\n\tawait recoverPendingSnapshotTransactions();\n\tconst transaction = await prepareTransaction(plan, options.sessionDir);\n\ttry {\n\t\tfor (const target of plan.deletes) {\n\t\t\tawait fs.rm(target, { force: true, recursive: true });\n\t\t}\n\t\tfor (const item of plan.writes) {\n\t\t\tawait fs.mkdir(path.dirname(item.target), { recursive: true });\n\t\t\tawait fs.writeFile(item.target, item.content);\n\t\t}\n\t\tawait fs.rm(transaction.directory, { recursive: true, force: true });\n\t} catch (error) {\n\t\ttry {\n\t\t\tawait restoreTransaction(transaction.directory, transaction.journal);\n\t\t} catch (recoveryError) {\n\t\t\tthrow new AggregateError(\n\t\t\t\t[error, recoveryError],\n\t\t\t\t`Snapshot apply failed and automatic recovery also failed. Transaction retained at ${transaction.directory}.`,\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nexport async function recoverSnapshotTransactionsOnStartup() {\n\tif (!(await pendingTransactionEntries()).some((entry) => entry.isDirectory())) return;\n\tawait withLock(\"recovery\", recoverPendingSnapshotTransactions, { reclaimStale: true });\n}\n\nexport async function recoverPendingSnapshotTransactions() {\n\tconst directory = transactionRoot();\n\tconst entries = await pendingTransactionEntries();\n\tfor (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {\n\t\tif (!entry.isDirectory()) continue;\n\t\tconst transactionDirectory = path.join(directory, entry.name);\n\t\tconst journalPath = path.join(transactionDirectory, \"journal.json\");\n\t\tlet journal: TransactionJournal;\n\t\ttry {\n\t\t\tjournal = JSON.parse(await fs.readFile(journalPath, \"utf8\")) as TransactionJournal;\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n\t\t\t\tawait fs.rm(transactionDirectory, { recursive: true, force: true });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow new Error(`Cannot recover malformed pi-sync transaction: ${journalPath}`, {\n\t\t\t\tcause: error,\n\t\t\t});\n\t\t}\n\t\tawait restoreTransaction(transactionDirectory, journal);\n\t}\n}\n\nasync function pendingTransactionEntries() {\n\ttry {\n\t\treturn await fs.readdir(transactionRoot(), { withFileTypes: true });\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\tthrow error;\n\t}\n}\n\nasync function prepareTransaction(plan: SnapshotApplyPlan, sessionDir?: string) {\n\tconst root = path.resolve(agentDir());\n\tconst sessionRoot = sessionDir ? path.resolve(sessionStorageRoot(root, sessionDir)) : undefined;\n\tconst directory = path.join(transactionRoot(), randomUUID());\n\tconst backupDirectory = path.join(directory, \"before\");\n\tawait fs.mkdir(backupDirectory, { recursive: true, mode: 0o700 });\n\tconst targets = [...new Set([...plan.deletes, ...plan.writes.map((item) => item.target)])].sort();\n\tconst entries: TransactionEntry[] = [];\n\tfor (let index = 0; index < targets.length; index += 1) {\n\t\tconst target = targets[index];\n\t\tif (!target) continue;\n\t\tassertAllowedTarget(root, sessionRoot, target);\n\t\tconst backupName = `${index}`;\n\t\tconst backupPath = path.join(backupDirectory, backupName);\n\t\ttry {\n\t\t\tconst stat = await fs.lstat(target);\n\t\t\tif (stat.isSymbolicLink()) {\n\t\t\t\tentries.push({\n\t\t\t\t\ttarget,\n\t\t\t\t\tbackupName,\n\t\t\t\t\tkind: \"symlink\",\n\t\t\t\t\tlinkTarget: await fs.readlink(target),\n\t\t\t\t});\n\t\t\t} else if (stat.isDirectory()) {\n\t\t\t\tawait fs.cp(target, backupPath, {\n\t\t\t\t\trecursive: true,\n\t\t\t\t\tdereference: false,\n\t\t\t\t\tpreserveTimestamps: true,\n\t\t\t\t});\n\t\t\t\tentries.push({ target, backupName, kind: \"directory\" });\n\t\t\t} else if (stat.isFile()) {\n\t\t\t\tawait fs.copyFile(target, backupPath);\n\t\t\t\tawait fs.chmod(backupPath, stat.mode);\n\t\t\t\tentries.push({ target, backupName, kind: \"file\" });\n\t\t\t} else {\n\t\t\t\tthrow new Error(`Unsupported existing snapshot target: ${target}`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst code = (error as NodeJS.ErrnoException).code;\n\t\t\tif (code !== \"ENOENT\" && code !== \"ENOTDIR\") throw error;\n\t\t\tentries.push({ target, backupName, kind: \"missing\" });\n\t\t}\n\t}\n\tconst journal: TransactionJournal = {\n\t\tversion: JOURNAL_VERSION,\n\t\troot,\n\t\tsessionRoot,\n\t\tentries,\n\t};\n\tawait fs.writeFile(\n\t\tpath.join(directory, \"journal.json\"),\n\t\t`${JSON.stringify(journal, null, \"\\t\")}\\n`,\n\t\t{\n\t\t\tmode: 0o600,\n\t\t},\n\t);\n\treturn { directory, journal };\n}\n\nasync function restoreTransaction(directory: string, journal: TransactionJournal) {\n\tvalidateJournal(directory, journal);\n\tfor (const entry of [...journal.entries].sort(\n\t\t(left, right) => right.target.length - left.target.length,\n\t)) {\n\t\tawait fs.rm(entry.target, { recursive: true, force: true });\n\t}\n\tfor (const entry of journal.entries) {\n\t\tif (entry.kind === \"missing\") continue;\n\t\tawait fs.mkdir(path.dirname(entry.target), { recursive: true });\n\t\tconst backupPath = path.join(directory, \"before\", entry.backupName);\n\t\tassertWithinRoot(directory, backupPath);\n\t\tif (entry.kind === \"file\") await fs.copyFile(backupPath, entry.target);\n\t\telse if (entry.kind === \"directory\") {\n\t\t\tawait fs.cp(backupPath, entry.target, {\n\t\t\t\trecursive: true,\n\t\t\t\tdereference: false,\n\t\t\t\tpreserveTimestamps: true,\n\t\t\t});\n\t\t} else if (entry.kind === \"symlink\" && entry.linkTarget !== undefined) {\n\t\t\tawait fs.symlink(entry.linkTarget, entry.target);\n\t\t}\n\t}\n\tawait fs.rm(directory, { recursive: true, force: true });\n}\n\nfunction validateJournal(directory: string, journal: TransactionJournal) {\n\tif (journal.version !== JOURNAL_VERSION || !Array.isArray(journal.entries)) {\n\t\tthrow new Error(`Unsupported pi-sync transaction journal: ${directory}`);\n\t}\n\tconst expectedRoot = path.resolve(agentDir());\n\tif (path.resolve(journal.root) !== expectedRoot) {\n\t\tthrow new Error(`Transaction root no longer matches the Pi agent directory: ${directory}`);\n\t}\n\tfor (const entry of journal.entries) {\n\t\tif (\n\t\t\t!entry ||\n\t\t\ttypeof entry.target !== \"string\" ||\n\t\t\ttypeof entry.backupName !== \"string\" ||\n\t\t\t!/^\\d+$/u.test(entry.backupName)\n\t\t) {\n\t\t\tthrow new Error(`Invalid pi-sync transaction entry: ${directory}`);\n\t\t}\n\t\tassertAllowedTarget(journal.root, journal.sessionRoot, entry.target);\n\t}\n}\n\nfunction assertAllowedTarget(root: string, sessionRoot: string | undefined, target: string) {\n\tconst resolved = path.resolve(target);\n\tif (isPathInside(root, resolved)) {\n\t\tassertWithinRoot(root, resolved);\n\t\treturn;\n\t}\n\tif (sessionRoot && isPathInside(sessionRoot, resolved)) {\n\t\tassertWithinRoot(sessionRoot, resolved);\n\t\treturn;\n\t}\n\tthrow new Error(`Transaction target is outside configured roots: ${target}`);\n}\n\nfunction transactionRoot() {\n\treturn path.join(stateDir(), \"transactions\");\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,OAAO,QAAQ;AACf,OAAO,UAAU;AAOjB,IAAM,kBAAkB;AAgBxB,eAAsB,yBACrB,MACA,UAAmC,CAAC,GACnC;AACD,QAAM,mCAAmC;AACzC,QAAM,cAAc,MAAM,mBAAmB,MAAM,QAAQ,UAAU;AACrE,MAAI;AACH,eAAW,UAAU,KAAK,SAAS;AAClC,YAAM,GAAG,GAAG,QAAQ,EAAE,OAAO,MAAM,WAAW,KAAK,CAAC;AAAA,IACrD;AACA,eAAW,QAAQ,KAAK,QAAQ;AAC/B,YAAM,GAAG,MAAM,KAAK,QAAQ,KAAK,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;AAC7D,YAAM,GAAG,UAAU,KAAK,QAAQ,KAAK,OAAO;AAAA,IAC7C;AACA,UAAM,GAAG,GAAG,YAAY,WAAW,EAAE,WAAW,MAAM,OAAO,KA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,SAAS,GAAG,cAAc;AAC5C;",
6
- "names": []
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/paths.ts", "../../src/sync-policy.ts"],
4
- "sourcesContent": ["import path from \"node:path\";\n\nexport function isDeniedPath(relativePath: string) {\n\tconst normalized = toPosix(relativePath);\n\tconst lower = normalized.toLowerCase();\n\tconst segments = lower.split(\"/\");\n\tconst base = path.posix.basename(lower);\n\treturn (\n\t\tsegments.includes(\"node_modules\") ||\n\t\tsegments.includes(\".git\") ||\n\t\tsegments.includes(\".pisync\") ||\n\t\tsegments.includes(\"pi-sync\") ||\n\t\tsegments.includes(\".pi-sync-state-migration.lock\") ||\n\t\tbase === \".env\" ||\n\t\tbase.startsWith(\".env.\") ||\n\t\tbase.endsWith(\".env\") ||\n\t\tbase.includes(\"secret\") ||\n\t\tbase.includes(\"token\") ||\n\t\tbase === \"pi-sync.json\" ||\n\t\tbase.startsWith(\"pi-sync.json.\") ||\n\t\tbase.startsWith(\".pi-sync.json.\") ||\n\t\tbase === \"pi-sync.local.json\" ||\n\t\tbase.startsWith(\"pi-sync.local.json.\") ||\n\t\tbase.startsWith(\".pi-sync.local.json.\")\n\t);\n}\n\nexport function isPathInside(parent: string, child: string) {\n\tconst relative = path.relative(path.resolve(parent), path.resolve(child));\n\treturn relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n}\n\nexport function safeJoin(root: string, relativePath: string) {\n\tconst target = path.resolve(root, relativePath);\n\tassertWithinRoot(root, target, relativePath);\n\treturn target;\n}\n\nexport function assertWithinRoot(root: string, target: string, label = target) {\n\tconst resolvedRoot = path.resolve(root);\n\tconst resolvedTarget = path.resolve(target);\n\tif (resolvedTarget !== resolvedRoot && !resolvedTarget.startsWith(`${resolvedRoot}${path.sep}`)) {\n\t\tthrow new Error(`Unsafe path in snapshot: ${label}`);\n\t}\n}\n\nexport function encodeKey(key: string) {\n\treturn key.split(\"/\").map(encodeURIComponent).join(\"/\");\n}\n\nexport function posixJoin(...parts: string[]) {\n\treturn parts\n\t\t.map((part) => trimSlashes(part))\n\t\t.filter(Boolean)\n\t\t.join(\"/\");\n}\n\nexport function parentPaths(relativePath: string) {\n\tconst results: string[] = [];\n\tlet index = relativePath.lastIndexOf(\"/\");\n\twhile (index > 0) {\n\t\tresults.push(relativePath.slice(0, index));\n\t\tindex = relativePath.lastIndexOf(\"/\", index - 1);\n\t}\n\treturn results;\n}\n\nexport function toPosix(value: string) {\n\treturn value.split(path.sep).join(\"/\");\n}\n\nfunction trimSlashes(value: string) {\n\treturn value.replace(/^\\/+|\\/+$/g, \"\");\n}\n\nexport function safeName(value: string) {\n\treturn value.replace(/[^A-Za-z0-9._-]/g, \"_\");\n}\n", "import path from \"node:path\";\nimport { isDeniedPath, toPosix } from \"./paths.js\";\nimport type { Snapshot, SnapshotSelection } from \"./types.js\";\n\nexport const BUILT_IN_SYNC_ROOTS = [\n\t\"settings.json\",\n\t\"keybindings.json\",\n\t\"models.json\",\n\t\"AGENTS.md\",\n\t\"APPEND_SYSTEM.md\",\n\t\"skills\",\n\t\"prompts\",\n\t\"themes\",\n\t\"extensions\",\n] as const;\n\nexport const DEFAULT_SYNC_INCLUDE = [...BUILT_IN_SYNC_ROOTS] as const;\nexport type BuiltInSyncFile = (typeof BUILT_IN_SYNC_ROOTS)[number];\nconst SNAPSHOT_SELECTION_VERSION = 1;\nconst MAX_SYNC_INCLUDE_ITEMS = 1_024;\nconst MAX_SYNC_INCLUDE_PATH_BYTES = 4_096;\nconst MAX_SYNC_INCLUDE_TOTAL_BYTES = 256 * 1_024;\n\ninterface IncludePathNode {\n\tselected?: string;\n\tchildren: Map<string, IncludePathNode>;\n}\n\nconst BUILT_IN_BY_LOWER = new Map<string, BuiltInSyncFile>(\n\tBUILT_IN_SYNC_ROOTS.map((fileName) => [fileName.toLowerCase(), fileName]),\n);\nconst TOP_LEVEL_FILE_PATHS = new Map<string, string>(\n\tBUILT_IN_SYNC_ROOTS.filter((fileName) => fileName.includes(\".\")).map((fileName) => [\n\t\tfileName.toLowerCase(),\n\t\tfileName,\n\t]),\n);\nconst TOP_LEVEL_DIRS = new Set<string>(\n\tBUILT_IN_SYNC_ROOTS.filter((fileName) => !fileName.includes(\".\")),\n);\nconst RESERVED_TOP_LEVEL_NAMES = new Set<string>([...BUILT_IN_BY_LOWER.keys(), \"sessions\"]);\n\nexport function normalizeSyncInclude(value: unknown): string[] {\n\tif (!Array.isArray(value)) {\n\t\tthrow new Error(\"Invalid pi-sync settings: sync.include must be an array.\");\n\t}\n\tif (value.length > MAX_SYNC_INCLUDE_ITEMS) {\n\t\tthrow new Error(\n\t\t\t`Invalid pi-sync settings: sync.include has too many items; limit: ${MAX_SYNC_INCLUDE_ITEMS}.`,\n\t\t);\n\t}\n\tconst result: string[] = [];\n\tconst seen = new Set<string>();\n\tconst pathRoot: IncludePathNode = { children: new Map() };\n\tlet totalBytes = 0;\n\tfor (const item of value) {\n\t\tif (typeof item !== \"string\") {\n\t\t\tthrow new Error(\"Invalid pi-sync settings: sync.include items must be strings.\");\n\t\t}\n\t\tconst itemBytes = Buffer.byteLength(item, \"utf8\");\n\t\tif (itemBytes > MAX_SYNC_INCLUDE_PATH_BYTES) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid pi-sync settings: sync.include item is too long; limit: ${MAX_SYNC_INCLUDE_PATH_BYTES} bytes.`,\n\t\t\t);\n\t\t}\n\t\ttotalBytes += itemBytes;\n\t\tif (totalBytes > MAX_SYNC_INCLUDE_TOTAL_BYTES) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid pi-sync settings: sync.include is too large; limit: ${MAX_SYNC_INCLUDE_TOTAL_BYTES} bytes.`,\n\t\t\t);\n\t\t}\n\t\tconst trimmed = item.trim();\n\t\tconst builtIn = BUILT_IN_BY_LOWER.get(trimmed.toLowerCase());\n\t\tconst normalized = builtIn ?? (trimmed.toLowerCase() === \"sessions\" ? \"sessions\" : trimmed);\n\t\tif (!builtIn && normalized !== \"sessions\") validateAgentRelativeInclude(normalized);\n\t\tconst identity = normalized.toLowerCase();\n\t\tif (seen.has(identity)) {\n\t\t\tthrow new Error(`Invalid pi-sync settings: duplicate sync.include item: ${item}`);\n\t\t}\n\t\taddIncludePath(pathRoot, identity, item);\n\t\tseen.add(identity);\n\t\tresult.push(normalized);\n\t}\n\treturn result;\n}\n\nfunction addIncludePath(root: IncludePathNode, identity: string, source: string) {\n\tlet node = root;\n\tfor (const segment of identity.split(\"/\")) {\n\t\tif (node.selected !== undefined) throwOverlappingInclude(source);\n\t\tlet child = node.children.get(segment);\n\t\tif (!child) {\n\t\t\tchild = { children: new Map() };\n\t\t\tnode.children.set(segment, child);\n\t\t}\n\t\tnode = child;\n\t}\n\tif (node.children.size > 0) throwOverlappingInclude(source);\n\tnode.selected = identity;\n}\n\nfunction throwOverlappingInclude(item: string): never {\n\tthrow new Error(\n\t\t`Invalid pi-sync settings: overlapping sync.include items are ambiguous: ${item}`,\n\t);\n}\n\nfunction validateAgentRelativeInclude(value: string) {\n\tconst normalized = toPosix(value);\n\tconst topLevel = normalized.split(\"/\")[0]?.toLowerCase();\n\tif (\n\t\t!normalized ||\n\t\tnormalized === \".\" ||\n\t\tnormalized === \"..\" ||\n\t\tnormalized.startsWith(\"../\") ||\n\t\tpath.posix.isAbsolute(normalized) ||\n\t\tnormalized.includes(\"\\\\\") ||\n\t\tpath.posix.normalize(normalized) !== normalized ||\n\t\t// biome-ignore lint/suspicious/noControlCharactersInRegex: Include paths cannot contain controls.\n\t\t/[\\u0000-\\u001f\\u007f-\\u009f]/u.test(normalized)\n\t) {\n\t\tthrow new Error(\n\t\t\t`Invalid pi-sync settings: sync.include item must be a safe agent-relative path: ${value}`,\n\t\t);\n\t}\n\tif (isDeniedPath(normalized)) {\n\t\tthrow new Error(`Invalid pi-sync settings: ${value} cannot be synced.`);\n\t}\n\tif (topLevel && RESERVED_TOP_LEVEL_NAMES.has(topLevel)) {\n\t\tthrow new Error(\n\t\t\t`Invalid pi-sync settings: use the canonical ${topLevel} root instead of a nested sync.include path.`,\n\t\t);\n\t}\n}\n\nexport function portableSnapshotSelection(value: unknown): SnapshotSelection {\n\tconst selection = value as Partial<SnapshotSelection> | null;\n\tif (\n\t\t!selection ||\n\t\ttypeof selection !== \"object\" ||\n\t\tArray.isArray(selection) ||\n\t\tselection.version !== SNAPSHOT_SELECTION_VERSION ||\n\t\t!Object.hasOwn(selection, \"include\") ||\n\t\tObject.keys(selection).some((key) => key !== \"version\" && key !== \"include\")\n\t) {\n\t\tthrow new Error(\"Invalid snapshot selection policy.\");\n\t}\n\treturn {\n\t\tversion: SNAPSHOT_SELECTION_VERSION,\n\t\tinclude: normalizeSyncInclude(selection.include),\n\t};\n}\n\nexport function snapshotSelectionInclude(snapshot: Pick<Snapshot, \"selection\">) {\n\treturn snapshot.selection === undefined\n\t\t? undefined\n\t\t: portableSnapshotSelection(snapshot.selection).include;\n}\n\nexport function selectionForSnapshot(include: unknown): SnapshotSelection {\n\treturn { version: SNAPSHOT_SELECTION_VERSION, include: normalizeSyncInclude(include) };\n}\n\nexport function sameSyncInclude(left: unknown, right: unknown) {\n\tconst normalizedLeft = normalizeSyncInclude(left);\n\tconst normalizedRight = normalizeSyncInclude(right);\n\treturn (\n\t\tnormalizedLeft.length === normalizedRight.length &&\n\t\tnormalizedLeft.every((item, index) => item === normalizedRight[index])\n\t);\n}\n\nexport function compareSyncInclude(local: unknown, remote: unknown) {\n\tconst localInclude = normalizeSyncInclude(local);\n\tconst remoteInclude = normalizeSyncInclude(remote);\n\tconst localSet = new Set(localInclude);\n\tconst remoteSet = new Set(remoteInclude);\n\treturn {\n\t\tsame: sameSyncInclude(localInclude, remoteInclude),\n\t\tremoteOnly: remoteInclude.filter((item) => !localSet.has(item)),\n\t\tlocalOnly: localInclude.filter((item) => !remoteSet.has(item)),\n\t};\n}\n\nexport type RemoteSelectionState =\n\t| { kind: \"legacy\"; discovered: string[] }\n\t| { kind: \"same\"; include: string[] }\n\t| {\n\t\t\tkind: \"different\";\n\t\t\tinclude: string[];\n\t\t\tremoteOnly: string[];\n\t\t\tlocalOnly: string[];\n\t };\n\nexport function inspectRemoteSelection(\n\tlocalInclude: unknown,\n\tsnapshot: Pick<Snapshot, \"selection\" | \"files\">,\n): RemoteSelectionState {\n\tconst remoteInclude = snapshotSelectionInclude(snapshot);\n\tif (!remoteInclude) {\n\t\treturn { kind: \"legacy\", discovered: discoverLegacySnapshotInclude(snapshot) };\n\t}\n\tconst comparison = compareSyncInclude(localInclude, remoteInclude);\n\treturn comparison.same\n\t\t? { kind: \"same\", include: remoteInclude }\n\t\t: { kind: \"different\", include: remoteInclude, ...comparison };\n}\n\nexport interface RemoteSelectionDecision {\n\tsetupName: string;\n\tconfigIdentity: string;\n\tlocalInclude: readonly string[];\n\tremoteInclude: readonly string[];\n}\n\nexport class RemoteSelectionMismatchError extends Error {\n\treadonly decision: RemoteSelectionDecision;\n\treadonly setupName: string;\n\treadonly localInclude: string[];\n\treadonly remoteInclude: string[];\n\n\tconstructor(\n\t\tsetupName: string,\n\t\tlocalInclude: unknown,\n\t\tremoteInclude: unknown,\n\t\tconfigIdentity = JSON.stringify([setupName, normalizeSyncInclude(localInclude)]),\n\t) {\n\t\tconst local = normalizeSyncInclude(localInclude);\n\t\tconst remote = normalizeSyncInclude(remoteInclude);\n\t\tsuper(formatRemoteSelectionMismatch(setupName, local, remote));\n\t\tthis.name = \"RemoteSelectionMismatchError\";\n\t\tthis.setupName = setupName;\n\t\tthis.localInclude = local;\n\t\tthis.remoteInclude = remote;\n\t\tthis.decision = {\n\t\t\tsetupName,\n\t\t\tconfigIdentity,\n\t\t\tlocalInclude: [...local],\n\t\t\tremoteInclude: [...remote],\n\t\t};\n\t}\n}\n\nexport function remoteSelectionMismatch(\n\tconfig: { setupName: string; include: unknown },\n\tremoteInclude: unknown,\n\tconfigIdentity?: string,\n) {\n\treturn new RemoteSelectionMismatchError(\n\t\tconfig.setupName,\n\t\tconfig.include,\n\t\tremoteInclude,\n\t\tconfigIdentity,\n\t);\n}\n\nexport function formatRemoteSelectionMismatch(\n\tsetupName: string,\n\tlocalInclude: readonly string[],\n\tremoteInclude: readonly string[],\n) {\n\tconst comparison = compareSyncInclude(localInclude, remoteInclude);\n\tconst lines = [\n\t\t`Synced content differs for sync setup \u201C${stripTerminalControls(setupName)}\u201D.`,\n\t\t`Remote-only: ${comparison.remoteOnly.join(\", \") || \"none\"}`,\n\t\t`This-device-only: ${comparison.localOnly.join(\", \") || \"none\"}`,\n\t];\n\tif (comparison.remoteOnly.length === 0 && comparison.localOnly.length === 0) {\n\t\tlines.push(\n\t\t\t\"Only ordering differs.\",\n\t\t\t`Remote order: ${remoteInclude.join(\", \") || \"none\"}`,\n\t\t\t`This device order: ${localInclude.join(\", \") || \"none\"}`,\n\t\t);\n\t}\n\tlines.push(\"Run /sync in TUI to review both content lists and choose what happens next.\");\n\treturn lines.join(\"\\n\");\n}\n\nfunction stripTerminalControls(value: string) {\n\t// biome-ignore lint/suspicious/noControlCharactersInRegex: Escape untrusted terminal controls.\n\treturn value.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/gu, \"?\");\n}\n\nexport function discoverLegacySnapshotInclude(snapshot: Pick<Snapshot, \"files\">) {\n\tconst builtIns = new Set<BuiltInSyncFile>();\n\tconst custom = new Set<string>();\n\tlet sessions = false;\n\tfor (const file of snapshot.files) {\n\t\tconst normalized = toPosix(file.path);\n\t\tif (\n\t\t\t!normalized ||\n\t\t\tfile.path.includes(\"\\\\\") ||\n\t\t\tnormalized.length > 4096 ||\n\t\t\tnormalized.startsWith(\"../\") ||\n\t\t\tpath.posix.isAbsolute(normalized) ||\n\t\t\tpath.posix.normalize(normalized) !== normalized ||\n\t\t\t// biome-ignore lint/suspicious/noControlCharactersInRegex: Ignore unsafe legacy paths.\n\t\t\t/[\\u0000-\\u001f\\u007f-\\u009f]/u.test(normalized) ||\n\t\t\tisDeniedPath(normalized)\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst [topLevel, ...rest] = normalized.split(\"/\");\n\t\tif (!topLevel) continue;\n\t\tif (topLevel === \"sessions\" && rest.length > 0) {\n\t\t\tsessions = true;\n\t\t\tcontinue;\n\t\t}\n\t\tconst builtIn = BUILT_IN_BY_LOWER.get(topLevel.toLowerCase());\n\t\tif (\n\t\t\tbuiltIn &&\n\t\t\t((TOP_LEVEL_DIRS.has(builtIn) && rest.length > 0) ||\n\t\t\t\t(!TOP_LEVEL_DIRS.has(builtIn) && rest.length === 0))\n\t\t) {\n\t\t\tbuiltIns.add(builtIn);\n\t\t\tcontinue;\n\t\t}\n\t\tif (isSafeCustomIncludePath(topLevel)) custom.add(topLevel);\n\t}\n\treturn [\n\t\t...BUILT_IN_SYNC_ROOTS.filter((item) => builtIns.has(item)),\n\t\t...[...custom].sort((left, right) => left.localeCompare(right)),\n\t\t...(sessions ? [\"sessions\"] : []),\n\t];\n}\n\nexport function syncIncludeSelection(value: unknown) {\n\tconst include = normalizeSyncInclude(value);\n\tconst builtIns = include.filter((item): item is BuiltInSyncFile =>\n\t\tBUILT_IN_BY_LOWER.has(item.toLowerCase()),\n\t);\n\tconst custom = include.filter(\n\t\t(item) => item !== \"sessions\" && !BUILT_IN_BY_LOWER.has(item.toLowerCase()),\n\t);\n\treturn { include, builtIns, custom, sessions: include.includes(\"sessions\") };\n}\n\nexport function customIncludePathsByLower(value: unknown) {\n\treturn new Map(\n\t\tsyncIncludeSelection(value).custom.map((relativePath) => [\n\t\t\trelativePath.toLowerCase(),\n\t\t\trelativePath,\n\t\t]),\n\t);\n}\n\nexport interface SyncSelectionConfig {\n\tinclude?: unknown;\n\tsyncFiles?: unknown;\n\tsyncSessions?: boolean;\n\textraFiles?: unknown;\n}\n\nexport function includeFromSelectionConfig(config: SyncSelectionConfig) {\n\tif (config.include !== undefined) return normalizeSyncInclude(config.include);\n\treturn [\n\t\t...normalizeSyncFiles(config.syncFiles),\n\t\t...normalizeExtraFiles(config.extraFiles),\n\t\t...(config.syncSessions ? [\"sessions\"] : []),\n\t];\n}\n\nexport function isConfiguredSnapshotPath(\n\trelativePath: string,\n\tconfig: SyncSelectionConfig,\n\t_legacyExtraFiles?: Set<string>,\n) {\n\tconst normalized = toPosix(relativePath);\n\tconst selection = syncIncludeSelection(includeFromSelectionConfig(config));\n\tif (normalized.startsWith(\"sessions/\")) return selection.sessions;\n\tconst lower = normalized.toLowerCase();\n\tif (!normalized.includes(\"/\")) {\n\t\tconst builtIn = BUILT_IN_BY_LOWER.get(lower);\n\t\tif (builtIn) return selection.builtIns.includes(builtIn) && !TOP_LEVEL_DIRS.has(builtIn);\n\t}\n\tconst topLevel = normalized.slice(0, normalized.indexOf(\"/\"));\n\tif (selection.builtIns.includes(topLevel as BuiltInSyncFile) && TOP_LEVEL_DIRS.has(topLevel)) {\n\t\treturn true;\n\t}\n\treturn selection.custom.some((candidate) => {\n\t\tconst candidateLower = candidate.toLowerCase();\n\t\treturn lower === candidateLower || lower.startsWith(`${candidateLower}/`);\n\t});\n}\n\nexport function canonicalSnapshotPathForConfig(\n\trelativePath: string,\n\tincludePaths: Map<string, string>,\n) {\n\tconst normalized = toPosix(relativePath);\n\tconst lower = normalized.toLowerCase();\n\treturn TOP_LEVEL_FILE_PATHS.get(lower) ?? includePaths.get(lower) ?? normalized;\n}\n\nexport function isPreservableUnmanagedSnapshotPath(relativePath: string) {\n\tconst normalized = toPosix(relativePath);\n\tif (!normalized || isDeniedPath(normalized)) return false;\n\tif (normalized.startsWith(\"sessions/\")) return normalized.endsWith(\".jsonl\");\n\tif (!normalized.includes(\"/\")) {\n\t\tconst lower = normalized.toLowerCase();\n\t\treturn TOP_LEVEL_FILE_PATHS.has(lower) || !RESERVED_TOP_LEVEL_NAMES.has(lower);\n\t}\n\treturn true;\n}\n\nexport function isSafeCustomIncludePath(relativePath: string) {\n\ttry {\n\t\tvalidateAgentRelativeInclude(relativePath);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function isBuiltInTopLevelFile(fileName: string) {\n\treturn TOP_LEVEL_FILE_PATHS.has(path.posix.basename(fileName).toLowerCase());\n}\n\n/** Compatibility projection for backend-neutral output while callers move to sync.include. */\nexport function normalizeSyncFiles(value: unknown): BuiltInSyncFile[] {\n\tif (value === undefined) return [...DEFAULT_SYNC_INCLUDE];\n\tif (Array.isArray(value)) {\n\t\treturn normalizeSyncInclude(value).filter((item): item is BuiltInSyncFile =>\n\t\t\tBUILT_IN_BY_LOWER.has(item.toLowerCase()),\n\t\t);\n\t}\n\tthrow new Error(\"Invalid pi-sync settings: expected an include array.\");\n}\n\n/** Compatibility projection for old rendering helpers; v3 persistence never writes this split field. */\nexport function normalizeExtraFiles(value: unknown) {\n\tif (!Array.isArray(value)) return [];\n\treturn value.filter(\n\t\t(item): item is string => typeof item === \"string\" && isSafeCustomIncludePath(item),\n\t);\n}\n\nexport const extraFilePathsByLower = customIncludePathsByLower;\nexport const isSafeExtraFileName = isSafeCustomIncludePath;\nexport const selectedSyncFileSet = (value: unknown) => new Set(normalizeSyncFiles(value));\n"],
5
- "mappings": ";;;;AAAA,OAAO,UAAU;AAEV,SAAS,aAAa,cAAsB;AAClD,QAAM,aAAa,QAAQ,YAAY;AACvC,QAAM,QAAQ,WAAW,YAAY;AACrC,QAAM,WAAW,MAAM,MAAM,GAAG;AAChC,QAAM,OAAO,KAAK,MAAM,SAAS,KAAK;AACtC,SACC,SAAS,SAAS,cAAc,KAChC,SAAS,SAAS,MAAM,KACxB,SAAS,SAAS,SAAS,KAC3B,SAAS,SAAS,SAAS,KAC3B,SAAS,SAAS,+BAA+B,KACjD,SAAS,UACT,KAAK,WAAW,OAAO,KACvB,KAAK,SAAS,MAAM,KACpB,KAAK,SAAS,QAAQ,KACtB,KAAK,SAAS,OAAO,KACrB,SAAS,kBACT,KAAK,WAAW,eAAe,KAC/B,KAAK,WAAW,gBAAgB,KAChC,SAAS,wBACT,KAAK,WAAW,qBAAqB,KACrC,KAAK,WAAW,sBAAsB;AAExC;AAEO,SAAS,aAAa,QAAgB,OA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AA,EACR,QAAQ;AACP,WAAO;AAAA,EACR;AACD;AAOO,SAAS,mBAAmB,OAAmC;AACrE,MAAI,UAAU,OAAW,QAAO,CAAC,GAAG,oBAAoB;AACxD,MAAI,MAAM,QAAQ,KAAK,GAAG;AACzB,WAAO,qBAAqB,KAAK,EAAE;AAAA,MAAO,CAAC,SAC1C,kBAAkB,IAAI,KAAK,YAAY,CAAC;AAAA,IACzC;AAAA,EACD;AACA,QAAM,IAAI,MAAM,sDAAsD;AACvE;AAGO,SAAS,oBAAoB,OAAgB;AACnD,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO,CAAC;AACnC,SAAO,MAAM;AAAA,IACZ,CAAC,SAAyB,OAAO,SAAS,YAAY,wBAAwB,IAAI;AAAA,EACnF;AACD;",
6
- "names": ["path", "path"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/file-selection.ts"],
4
- "sourcesContent": ["import fs from \"node:fs/promises\";\nimport type { ExtensionCommandContext } from \"@earendil-works/pi-coding-agent\";\nimport { defineMenu, runMenu } from \"@narumitw/pi-tui-kit\";\nimport { agentDir, loadConfig, localConfigPath } from \"./config.js\";\nimport { updateSyncSetup } from \"./settings-management.js\";\nimport {\n\tBUILT_IN_SYNC_ROOTS,\n\tisSafeCustomIncludePath,\n\tnormalizeSyncInclude,\n\tsyncIncludeSelection,\n} from \"./sync-policy.js\";\n\nconst BUILT_IN_PREFIX = \"builtin:\";\nconst CUSTOM_PREFIX = \"custom:\";\nconst SESSIONS_ID = \"sessions\";\nconst ADD_CUSTOM_ID = \"add-custom\";\n\ninterface SelectionDraft {\n\tbuiltIns: Set<string>;\n\tcustom: Set<string>;\n\tsessions: boolean;\n}\n\nexport async function showFileSelection(\n\tctx: ExtensionCommandContext,\n\tsetupName?: string,\n\tsignal?: AbortSignal,\n) {\n\tconst config = await loadConfig(setupName);\n\tif (signal?.aborted) return;\n\tconst selection = syncIncludeSelection(config.include);\n\tconst original: SelectionDraft = {\n\t\tbuiltIns: new Set(selection.builtIns),\n\t\tcustom: new Set(selection.custom),\n\t\tsessions: selection.sessions,\n\t};\n\tconst draft = cloneDraft(original);\n\tconst customCandidates = await listCustomCandidates(draft.custom);\n\n\tif (ctx.mode !== \"tui\") {\n\t\tctx.ui.notify(\n\t\t\t[\n\t\t\t\t`pi-sync included content for sync setup ${safeTerminalText(config.setupName)}:`,\n\t\t\t\t`include: ${config.include.map(safeTerminalText).join(\", \") || \"none\"}`,\n\t\t\t\t`Edit sync.include in ${safeTerminalText(localConfigPath())}.`,\n\t\t\t].join(\"\\n\"),\n\t\t\t\"info\",\n\t\t);\n\t\treturn;\n\t}\n\n\twhile (!signal?.aborted) {\n\t\tawait showDraftEditor(ctx, config.setupName, draft, customCandidates, signal);\n\t\tif (signal?.aborted || sameDraft(original, draft)) return;\n\t\tconst choice = await showDraftReview(ctx, original, draft, signal);\n\t\tif (signal?.aborted) return;\n\t\tif (choice === \"Continue editing\") continue;\n\t\tif (choice !== \"Save changes\") {\n\t\t\tctx.ui.notify(\"Included-content changes discarded.\", \"info\");\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tif (!original.sessions && draft.sessions) {\n\t\t\t\tconst acknowledged = await ctx.ui.confirm(\n\t\t\t\t\t\"Include session conversations?\",\n\t\t\t\t\t\"Session JSONL may contain prompts, tool output, file paths, images, and secrets. Continue only with storage you trust.\",\n\t\t\t\t\t{ signal },\n\t\t\t\t);\n\t\t\t\tif (signal?.aborted) return;\n\t\t\t\tif (!acknowledged) {\n\t\t\t\t\tctx.ui.notify(\"Session inclusion was not saved.\", \"info\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst include = [\n\t\t\t\t...BUILT_IN_SYNC_ROOTS.filter((candidate) => draft.builtIns.has(candidate)),\n\t\t\t\t...draft.custom,\n\t\t\t\t...(draft.sessions ? [\"sessions\"] : []),\n\t\t\t];\n\t\t\tif (signal?.aborted) return;\n\t\t\tawait updateSyncSetup(\n\t\t\t\tconfig.setupName,\n\t\t\t\t(setup) => ({\n\t\t\t\t\t...setup,\n\t\t\t\t\tsync: { ...setup.sync, include },\n\t\t\t\t}),\n\t\t\t\t{ expectedInclude: config.include, signal },\n\t\t\t);\n\t\t\tif (signal?.aborted) return;\n\t\t\tctx.ui.notify(\n\t\t\t\t`Saved included content for sync setup \u201C${safeTerminalText(config.setupName)}\u201D. It applies to the next manual or automatic sync.`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) return;\n\t\t\tctx.ui.notify(\n\t\t\t\t`Could not save pi-sync file selection: ${safeTerminalText(error instanceof Error ? error.message : String(error))}`,\n\t\t\t\t\"error\",\n\t\t\t);\n\t\t}\n\t\treturn;\n\t}\n}\n\nasync function showDraftEditor(\n\tctx: ExtensionCommandContext,\n\tsetupName: string,\n\tdraft: SelectionDraft,\n\tcustomCandidates: string[],\n\tsignal?: AbortSignal,\n) {\n\tconst menu = defineMenu<undefined, \"editor\", \"toggle\" | \"addCustom\", ExtensionCommandContext>({\n\t\tstart: \"editor\",\n\t\tscreens: {\n\t\t\teditor: () => ({\n\t\t\t\tkind: \"multiSelect\",\n\t\t\t\ttitle: `Included Content \u00B7 ${safeTerminalText(setupName)}`,\n\t\t\t\tlines: [\"Draft only \u00B7 leaving this screen opens Save, Discard, or Continue editing.\"],\n\t\t\t\tviewportSize: 12,\n\t\t\t\titems: [\n\t\t\t\t\t...BUILT_IN_SYNC_ROOTS.map((relativePath) => ({\n\t\t\t\t\t\tid: `${BUILT_IN_PREFIX}${relativePath}`,\n\t\t\t\t\t\tlabel: relativePath,\n\t\t\t\t\t\tdescription: relativePath.includes(\".\")\n\t\t\t\t\t\t\t? `Sync the top-level ${relativePath} file when present.`\n\t\t\t\t\t\t\t: `Recursively sync every safe file under ${relativePath}/.`,\n\t\t\t\t\t\tselected: draft.builtIns.has(relativePath),\n\t\t\t\t\t})),\n\t\t\t\t\t...customCandidates.map((relativePath) => ({\n\t\t\t\t\t\tid: `${CUSTOM_PREFIX}${relativePath}`,\n\t\t\t\t\t\tlabel: safeTerminalText(relativePath),\n\t\t\t\t\t\tdescription: \"Additional safe agent-relative file or directory.\",\n\t\t\t\t\t\tselected: draft.custom.has(relativePath),\n\t\t\t\t\t})),\n\t\t\t\t\t{\n\t\t\t\t\t\tid: SESSIONS_ID,\n\t\t\t\t\t\tlabel: \"sessions\",\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\"Session JSONL may contain prompts, tool output, paths, images, and secrets. Sync only to storage you trust.\",\n\t\t\t\t\t\tselected: draft.sessions,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\taction: \"toggle\",\n\t\t\t\tactions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: ADD_CUSTOM_ID,\n\t\t\t\t\t\tlabel: \"Add custom path\u2026\",\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\"Include an agent-relative file or directory even when it exists only remotely.\",\n\t\t\t\t\t\taction: \"addCustom\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\thint: \"close\",\n\t\t\t\tdoneLabel: \"Review changes\",\n\t\t\t}),\n\t\t},\n\t\tactions: {\n\t\t\ttoggle: async ({ itemId, selected }) => {\n\t\t\t\tupdateDraft(draft, itemId, selected === true);\n\t\t\t\treturn { kind: \"stay\" };\n\t\t\t},\n\t\t\taddCustom: async ({ ctx: actionCtx, signal: actionSignal }) => {\n\t\t\t\tconst entered = await actionCtx.ui.input(\n\t\t\t\t\t\"Add included content\",\n\t\t\t\t\t\"Agent-relative path, for example custom.toml or snippets\",\n\t\t\t\t\t{ signal: actionSignal },\n\t\t\t\t);\n\t\t\t\tif (actionSignal.aborted) return { kind: \"stay\" };\n\t\t\t\tconst requested = entered?.trim();\n\t\t\t\tif (!requested) return { kind: \"stay\" };\n\t\t\t\tconst existing = customCandidates.find(\n\t\t\t\t\t(candidate) => candidate.toLowerCase() === requested.toLowerCase(),\n\t\t\t\t);\n\t\t\t\tconst relativePath = existing ?? requested;\n\t\t\t\tif (draft.custom.has(relativePath)) return { kind: \"stay\" };\n\t\t\t\ttry {\n\t\t\t\t\tif (!isSafeCustomIncludePath(relativePath)) {\n\t\t\t\t\t\tthrow new Error(\"Enter a safe agent-relative file or directory path.\");\n\t\t\t\t\t}\n\t\t\t\t\tnormalizeSyncInclude([\n\t\t\t\t\t\t...draft.builtIns,\n\t\t\t\t\t\t...draft.custom,\n\t\t\t\t\t\t...(draft.sessions ? [\"sessions\"] : []),\n\t\t\t\t\t\trelativePath,\n\t\t\t\t\t]);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (actionSignal.aborted) return { kind: \"stay\" };\n\t\t\t\t\tactionCtx.ui.notify(\n\t\t\t\t\t\t`Could not add included content: ${safeTerminalText(error instanceof Error ? error.message : String(error))}`,\n\t\t\t\t\t\t\"error\",\n\t\t\t\t\t);\n\t\t\t\t\treturn { kind: \"stay\" };\n\t\t\t\t}\n\t\t\t\tif (!existing) {\n\t\t\t\t\tcustomCandidates.push(relativePath);\n\t\t\t\t\tcustomCandidates.sort((left, right) => left.localeCompare(right));\n\t\t\t\t}\n\t\t\t\tdraft.custom.add(relativePath);\n\t\t\t\treturn { kind: \"stay\" };\n\t\t\t},\n\t\t},\n\t});\n\tawait runMenu(ctx, menu, {\n\t\tgetState: () => undefined,\n\t\tsignal,\n\t\tisCurrent: () => !signal?.aborted,\n\t});\n}\n\nasync function showDraftReview(\n\tctx: ExtensionCommandContext,\n\toriginal: SelectionDraft,\n\tdraft: SelectionDraft,\n\tsignal?: AbortSignal,\n) {\n\tlet choice: \"Save changes\" | \"Discard changes\" | \"Continue editing\" | undefined;\n\tconst menu = defineMenu<undefined, \"review\", \"choose\", ExtensionCommandContext>({\n\t\tstart: \"review\",\n\t\tscreens: {\n\t\t\treview: () => ({\n\t\t\t\tkind: \"actions\",\n\t\t\t\ttitle: \"Review included-content changes\",\n\t\t\t\tlines: formatDraftPreview(original, draft).split(\"\\n\").slice(2),\n\t\t\t\titems: [\n\t\t\t\t\t{ id: \"save\", label: \"Save changes\", action: \"choose\" },\n\t\t\t\t\t{ id: \"discard\", label: \"Discard changes\", action: \"choose\" },\n\t\t\t\t\t{ id: \"continue\", label: \"Continue editing\", action: \"choose\" },\n\t\t\t\t],\n\t\t\t\thint: \"close\",\n\t\t\t}),\n\t\t},\n\t\tactions: {\n\t\t\tchoose: async ({ itemId }) => {\n\t\t\t\tchoice =\n\t\t\t\t\titemId === \"save\"\n\t\t\t\t\t\t? \"Save changes\"\n\t\t\t\t\t\t: itemId === \"continue\"\n\t\t\t\t\t\t\t? \"Continue editing\"\n\t\t\t\t\t\t\t: \"Discard changes\";\n\t\t\t\treturn { kind: \"close\" };\n\t\t\t},\n\t\t},\n\t});\n\tawait runMenu(ctx, menu, {\n\t\tgetState: () => undefined,\n\t\tsignal,\n\t\tisCurrent: () => !signal?.aborted,\n\t});\n\treturn choice;\n}\n\nfunction updateDraft(draft: SelectionDraft, id: string, included: boolean) {\n\tif (id.startsWith(BUILT_IN_PREFIX))\n\t\treturn updateSet(draft.builtIns, id.slice(BUILT_IN_PREFIX.length), included);\n\tif (id.startsWith(CUSTOM_PREFIX))\n\t\treturn updateSet(draft.custom, id.slice(CUSTOM_PREFIX.length), included);\n\tif (id === SESSIONS_ID) {\n\t\tdraft.sessions = included;\n\t\treturn;\n\t}\n\tthrow new Error(`Unknown file selection: ${id}`);\n}\n\nfunction updateSet(set: Set<string>, value: string, included: boolean) {\n\tif (included) set.add(value);\n\telse set.delete(value);\n}\n\nfunction formatDraftPreview(original: SelectionDraft, draft: SelectionDraft) {\n\tconst lines = [\"Review included-content changes\", \"\"];\n\tfor (const item of new Set([\n\t\t...original.builtIns,\n\t\t...draft.builtIns,\n\t\t...original.custom,\n\t\t...draft.custom,\n\t])) {\n\t\tconst before = original.builtIns.has(item) || original.custom.has(item);\n\t\tconst after = draft.builtIns.has(item) || draft.custom.has(item);\n\t\tif (before !== after) lines.push(`${after ? \"Include\" : \"Exclude\"}: ${safeTerminalText(item)}`);\n\t}\n\tif (original.sessions !== draft.sessions)\n\t\tlines.push(`${draft.sessions ? \"Include\" : \"Exclude\"}: sessions`);\n\tlines.push(\"\", \"Saving does not start a network sync.\");\n\treturn lines.join(\"\\n\");\n}\n\nasync function listCustomCandidates(configured: Set<string>) {\n\tconst candidates = new Map([...configured].map((item) => [item.toLowerCase(), item]));\n\ttry {\n\t\tfor (const entry of await fs.readdir(agentDir(), { withFileTypes: true })) {\n\t\t\tif ((!entry.isFile() && !entry.isDirectory()) || !isSafeCustomIncludePath(entry.name))\n\t\t\t\tcontinue;\n\t\t\tif (!candidates.has(entry.name.toLowerCase()))\n\t\t\t\tcandidates.set(entry.name.toLowerCase(), entry.name);\n\t\t}\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t}\n\treturn [...candidates.values()].sort((left, right) => left.localeCompare(right));\n}\n\nfunction cloneDraft(value: SelectionDraft): SelectionDraft {\n\treturn {\n\t\tbuiltIns: new Set(value.builtIns),\n\t\tcustom: new Set(value.custom),\n\t\tsessions: value.sessions,\n\t};\n}\n\nfunction sameDraft(left: SelectionDraft, right: SelectionDraft) {\n\treturn (\n\t\tleft.sessions === right.sessions &&\n\t\tsameSet(left.builtIns, right.builtIns) &&\n\t\tsameSet(left.custom, right.custom)\n\t);\n}\n\nfunction sameSet(left: Set<string>, right: Set<string>) {\n\treturn left.size === right.size && [...left].every((item) => right.has(item));\n}\n\nfunction safeTerminalText(value: string) {\n\t// biome-ignore lint/suspicious/noControlCharactersInRegex: Escape untrusted terminal controls.\n\treturn value.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/gu, \"?\");\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;AAAA,OAAO,QAAQ;AAEf,SAAS,YAAY,eAAe;AAUpC,IAAM,kBAAkB;AACxB,IAAM,gBAAgB;AACtB,IAAM,cAAc;AACpB,IAAM,gBAAgB;AAQt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