@narumitw/pi-sync 0.58.1 → 0.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +9 -5
  3. package/dist/chunks/{agent-candidate-U2NU3GUX.ts → agent-candidate-ZHN7FTZT.ts} +9 -8
  4. package/dist/chunks/{agent-plan-3YXDIJXO.ts → agent-plan-ILFEUJ2E.ts} +12 -11
  5. package/dist/chunks/{agent-plan-3YXDIJXO.ts.map → agent-plan-ILFEUJ2E.ts.map} +1 -1
  6. package/dist/chunks/{agent-refusal-retry-476YGNU5.ts → agent-refusal-retry-HRMHCX2A.ts} +9 -8
  7. package/dist/chunks/{agent-refusal-retry-476YGNU5.ts.map → agent-refusal-retry-HRMHCX2A.ts.map} +1 -1
  8. package/dist/chunks/{agent-store-7GINKTS7.ts → agent-store-CCKN4DPR.ts} +3 -3
  9. package/dist/chunks/{agent-sync-2R4GG2MF.ts → agent-sync-EGA2I5W7.ts} +4 -4
  10. package/dist/chunks/{chunk-CQD2TJHE.ts → chunk-25QCU3LY.ts} +4 -4
  11. package/dist/chunks/{chunk-OJARL2TG.ts → chunk-2UKUKIBI.ts} +4 -4
  12. package/dist/chunks/{chunk-REMGB255.ts → chunk-2ZZJXITS.ts} +16 -5
  13. package/dist/chunks/chunk-2ZZJXITS.ts.map +7 -0
  14. package/dist/chunks/chunk-3JTZF7Z5.ts +77 -0
  15. package/dist/chunks/chunk-3JTZF7Z5.ts.map +7 -0
  16. package/dist/chunks/{chunk-DN4IA7MR.ts → chunk-4NVHHDN2.ts} +2 -2
  17. package/dist/chunks/{chunk-AKMV47YC.ts → chunk-6OFMB6KK.ts} +2 -2
  18. package/dist/chunks/{chunk-45COPAK7.ts → chunk-6XU5HZAN.ts} +6 -6
  19. package/dist/chunks/{chunk-45COPAK7.ts.map → chunk-6XU5HZAN.ts.map} +2 -2
  20. package/dist/chunks/{chunk-Y4UVXOLQ.ts → chunk-6YGRZSCN.ts} +15 -10
  21. package/dist/chunks/chunk-6YGRZSCN.ts.map +7 -0
  22. package/dist/chunks/{chunk-XEODG2PE.ts → chunk-76HID27T.ts} +2 -2
  23. package/dist/chunks/{chunk-7A35ZAVO.ts → chunk-7WYF2KUO.ts} +174 -122
  24. package/dist/chunks/chunk-7WYF2KUO.ts.map +7 -0
  25. package/dist/chunks/{chunk-MMQIEDZ6.ts → chunk-APDNHB2T.ts} +78 -35
  26. package/dist/chunks/chunk-APDNHB2T.ts.map +7 -0
  27. package/dist/chunks/{chunk-U6GXGY5G.ts → chunk-DTPELCPW.ts} +4 -4
  28. package/dist/chunks/{chunk-TZC7GDJE.ts → chunk-ILXMZ2HU.ts} +4 -4
  29. package/dist/chunks/{chunk-CBLTWXAU.ts → chunk-LA3HQMFG.ts} +2 -1
  30. package/dist/chunks/{chunk-CBLTWXAU.ts.map → chunk-LA3HQMFG.ts.map} +2 -2
  31. package/dist/chunks/{chunk-ESKOPQVB.ts → chunk-MKC3PXCN.ts} +53 -32
  32. package/dist/chunks/chunk-MKC3PXCN.ts.map +7 -0
  33. package/dist/chunks/{chunk-MG66XM5U.ts → chunk-NGW4JMBF.ts} +63 -19
  34. package/dist/chunks/chunk-NGW4JMBF.ts.map +7 -0
  35. package/dist/chunks/{chunk-TIMWN2RH.ts → chunk-OQBE2OMB.ts} +13 -14
  36. package/dist/chunks/chunk-OQBE2OMB.ts.map +7 -0
  37. package/dist/chunks/{chunk-MKSMJPVA.ts → chunk-P3YD4ONV.ts} +22 -6
  38. package/dist/chunks/chunk-P3YD4ONV.ts.map +7 -0
  39. package/dist/chunks/{chunk-JYILGR3K.ts → chunk-PQ75RPUP.ts} +3 -3
  40. package/dist/chunks/{chunk-FLHCOJCD.ts → chunk-QQVK2XFC.ts} +13 -6
  41. package/dist/chunks/chunk-QQVK2XFC.ts.map +7 -0
  42. package/dist/chunks/{chunk-WQMYV4DW.ts → chunk-RDOX3VH5.ts} +5 -5
  43. package/dist/chunks/{chunk-6O3EDBRL.ts → chunk-S7D6XWHI.ts} +2 -2
  44. package/dist/chunks/{chunk-7ZIYU5QS.ts → chunk-SHPNS7FM.ts} +7 -7
  45. package/dist/chunks/{chunk-7ZIYU5QS.ts.map → chunk-SHPNS7FM.ts.map} +2 -2
  46. package/dist/chunks/{chunk-GNYGNHFF.ts → chunk-T2TYBLXK.ts} +2 -2
  47. package/dist/chunks/{chunk-6LD5KX55.ts → chunk-UZSDS4HF.ts} +13 -6
  48. package/dist/chunks/chunk-UZSDS4HF.ts.map +7 -0
  49. package/dist/chunks/{chunk-5TSCBBPP.ts → chunk-VPODHKOX.ts} +3 -3
  50. package/dist/chunks/{chunk-BEST45H2.ts → chunk-WEKGW7HV.ts} +17 -8
  51. package/dist/chunks/chunk-WEKGW7HV.ts.map +7 -0
  52. package/dist/chunks/{chunk-KYTT7KV4.ts → chunk-WUHRVSWI.ts} +87 -37
  53. package/dist/chunks/chunk-WUHRVSWI.ts.map +7 -0
  54. package/dist/chunks/{chunk-OVBAW7KV.ts → chunk-XZ3ZTHKR.ts} +19 -9
  55. package/dist/chunks/chunk-XZ3ZTHKR.ts.map +7 -0
  56. package/dist/chunks/{chunk-S5OCYVPS.ts → chunk-YEULK7MK.ts} +3 -3
  57. package/dist/chunks/{command-handler-MRXE5AKK.ts → command-handler-SDGKIQH2.ts} +16 -14
  58. package/dist/chunks/command-handler-SDGKIQH2.ts.map +7 -0
  59. package/dist/chunks/{config-HYG7G5EM.ts → config-J5VZUY4J.ts} +4 -3
  60. package/dist/chunks/{conflict-artifacts-J6WSDCWP.ts → conflict-artifacts-MYSH3L2J.ts} +10 -9
  61. package/dist/chunks/{conflict-review-GXA6Y7KY.ts → conflict-review-J6ZSPNWL.ts} +21 -20
  62. package/dist/chunks/{conflict-review-GXA6Y7KY.ts.map → conflict-review-J6ZSPNWL.ts.map} +1 -1
  63. package/dist/chunks/{continuous-record-EPHGR2DU.ts → continuous-record-OM64J27R.ts} +4 -4
  64. package/dist/chunks/{continuous-sync-FAFNLEUW.ts → continuous-sync-BH5SWIRV.ts} +22 -17
  65. package/dist/chunks/continuous-sync-BH5SWIRV.ts.map +7 -0
  66. package/dist/chunks/{file-selection-IELTXSGZ.ts → file-selection-7HEVPO4T.ts} +11 -8
  67. package/dist/chunks/file-selection-7HEVPO4T.ts.map +7 -0
  68. package/dist/chunks/{git-backend-KHD36W27.ts → git-backend-6CKI6CUG.ts} +12 -15
  69. package/dist/chunks/{git-backend-KHD36W27.ts.map → git-backend-6CKI6CUG.ts.map} +2 -2
  70. package/dist/chunks/{local-fields-JEKAPZKD.ts → local-fields-SR7PH66U.ts} +6 -5
  71. package/dist/chunks/{manager-result-dispatcher-XCYPW7RC.ts → manager-result-dispatcher-CXUP5WDP.ts} +15 -14
  72. package/dist/chunks/{manager-ui-AY34N4UY.ts → manager-ui-65ZETN6F.ts} +168 -51
  73. package/dist/chunks/manager-ui-65ZETN6F.ts.map +7 -0
  74. package/dist/chunks/{merge-baseline-store-65GKUMXI.ts → merge-baseline-store-4Y2X7P2D.ts} +4 -3
  75. package/dist/chunks/{remote-selection-ui-MYM2YCPF.ts → remote-selection-ui-W55BQDJQ.ts} +14 -13
  76. package/dist/chunks/{s3-backend-L24UZ6IK.ts → s3-backend-FDK7JSDQ.ts} +8 -7
  77. package/dist/chunks/{s3-backend-L24UZ6IK.ts.map → s3-backend-FDK7JSDQ.ts.map} +1 -1
  78. package/dist/chunks/{setup-switch-KLGESLQX.ts → setup-switch-AB27ADDI.ts} +5 -4
  79. package/dist/chunks/{setup-wizard-ZQAK35BP.ts → setup-wizard-5FILKFLQ.ts} +6 -5
  80. package/dist/chunks/{setup-wizard-ZQAK35BP.ts.map → setup-wizard-5FILKFLQ.ts.map} +1 -1
  81. package/dist/chunks/{snapshot-RGNDYT6A.ts → snapshot-G3W2GOGB.ts} +5 -4
  82. package/dist/chunks/{snapshot-transaction-26BQO36S.ts → snapshot-transaction-SGRUWT73.ts} +6 -5
  83. package/dist/chunks/{sync-inspection-MOMLGUTD.ts → sync-inspection-MDYHZHT7.ts} +10 -9
  84. package/dist/chunks/{sync-operations-45APGOL3.ts → sync-operations-ZAUP65FH.ts} +40 -29
  85. package/dist/chunks/sync-operations-ZAUP65FH.ts.map +7 -0
  86. package/dist/chunks/{sync-state-7L4NT7W2.ts → sync-state-H4TFZZ7S.ts} +7 -6
  87. package/dist/chunks/{webdav-backend-3ZCACILP.ts → webdav-backend-UNMIAXM5.ts} +7 -6
  88. package/dist/chunks/{webdav-backend-3ZCACILP.ts.map → webdav-backend-UNMIAXM5.ts.map} +1 -1
  89. package/dist/index.ts +26 -19
  90. package/dist/index.ts.map +2 -2
  91. package/docs/exclude-policy-audit.md +54 -0
  92. package/docs/exclude-review-ledger.md +36 -0
  93. package/docs/tui-contract.md +1 -1
  94. package/package.json +2 -1
  95. package/skills/configure-pi-sync/SKILL.md +4 -3
  96. package/skills/configure-pi-sync/references/configuration.md +72 -13
  97. package/src/backends/git/git-storage.ts +12 -11
  98. package/src/commands/command-execution.ts +2 -2
  99. package/src/settings/config.ts +9 -3
  100. package/src/settings/settings-management.ts +4 -3
  101. package/src/settings/settings-types.ts +4 -1
  102. package/src/settings/settings-validation.ts +8 -4
  103. package/src/snapshot/session-paths.ts +1 -0
  104. package/src/snapshot/snapshot-apply.ts +23 -7
  105. package/src/snapshot/snapshot-codec.ts +12 -3
  106. package/src/snapshot/snapshot-exclude-safety.ts +44 -0
  107. package/src/snapshot/snapshot-transaction.ts +12 -0
  108. package/src/snapshot/snapshot-types.ts +4 -4
  109. package/src/snapshot/snapshot.ts +71 -30
  110. package/src/state/merge-baseline-store.ts +9 -1
  111. package/src/state/state-types.ts +1 -0
  112. package/src/sync/automatic-sync.ts +7 -2
  113. package/src/sync/continuous-watch.ts +4 -2
  114. package/src/sync/exclude-policy.ts +84 -0
  115. package/src/sync/local-fields.ts +15 -4
  116. package/src/sync/merge-apply.ts +6 -1
  117. package/src/sync/merge-journal.ts +12 -3
  118. package/src/sync/merged-sync.ts +17 -12
  119. package/src/sync/partial-progress.ts +1 -0
  120. package/src/sync/remote-snapshot.ts +7 -8
  121. package/src/sync/sync-decision.ts +11 -1
  122. package/src/sync/sync-inspection.ts +3 -1
  123. package/src/sync/sync-mutations.ts +11 -4
  124. package/src/sync/sync-policy.ts +101 -37
  125. package/src/sync/sync-queries.ts +13 -3
  126. package/src/sync/sync-state.ts +16 -10
  127. package/src/ui/excluded-paths-ui.ts +106 -0
  128. package/src/ui/file-selection.ts +6 -3
  129. package/src/ui/manager-state.ts +11 -5
  130. package/src/ui/remote-selection-ui.ts +73 -10
  131. package/src/ui/settings-ui.ts +20 -5
  132. package/src/ui/setup/setup-actions.ts +1 -1
  133. package/src/ui/setup/setup-switcher.ts +3 -2
  134. package/src/ui/storage-connections-ui.ts +2 -2
  135. package/src/ui/sync-attention.ts +17 -3
  136. package/src/ui/sync-format.ts +13 -1
  137. package/dist/chunks/chunk-6LD5KX55.ts.map +0 -7
  138. package/dist/chunks/chunk-7A35ZAVO.ts.map +0 -7
  139. package/dist/chunks/chunk-BEST45H2.ts.map +0 -7
  140. package/dist/chunks/chunk-ESKOPQVB.ts.map +0 -7
  141. package/dist/chunks/chunk-FLHCOJCD.ts.map +0 -7
  142. package/dist/chunks/chunk-KYTT7KV4.ts.map +0 -7
  143. package/dist/chunks/chunk-MG66XM5U.ts.map +0 -7
  144. package/dist/chunks/chunk-MKSMJPVA.ts.map +0 -7
  145. package/dist/chunks/chunk-MMQIEDZ6.ts.map +0 -7
  146. package/dist/chunks/chunk-OVBAW7KV.ts.map +0 -7
  147. package/dist/chunks/chunk-REMGB255.ts.map +0 -7
  148. package/dist/chunks/chunk-TIMWN2RH.ts.map +0 -7
  149. package/dist/chunks/chunk-Y4UVXOLQ.ts.map +0 -7
  150. package/dist/chunks/command-handler-MRXE5AKK.ts.map +0 -7
  151. package/dist/chunks/continuous-sync-FAFNLEUW.ts.map +0 -7
  152. package/dist/chunks/file-selection-IELTXSGZ.ts.map +0 -7
  153. package/dist/chunks/manager-ui-AY34N4UY.ts.map +0 -7
  154. package/dist/chunks/sync-operations-45APGOL3.ts.map +0 -7
  155. /package/dist/chunks/{agent-candidate-U2NU3GUX.ts.map → agent-candidate-ZHN7FTZT.ts.map} +0 -0
  156. /package/dist/chunks/{agent-store-7GINKTS7.ts.map → agent-store-CCKN4DPR.ts.map} +0 -0
  157. /package/dist/chunks/{agent-sync-2R4GG2MF.ts.map → agent-sync-EGA2I5W7.ts.map} +0 -0
  158. /package/dist/chunks/{chunk-CQD2TJHE.ts.map → chunk-25QCU3LY.ts.map} +0 -0
  159. /package/dist/chunks/{chunk-OJARL2TG.ts.map → chunk-2UKUKIBI.ts.map} +0 -0
  160. /package/dist/chunks/{chunk-DN4IA7MR.ts.map → chunk-4NVHHDN2.ts.map} +0 -0
  161. /package/dist/chunks/{chunk-AKMV47YC.ts.map → chunk-6OFMB6KK.ts.map} +0 -0
  162. /package/dist/chunks/{chunk-XEODG2PE.ts.map → chunk-76HID27T.ts.map} +0 -0
  163. /package/dist/chunks/{chunk-U6GXGY5G.ts.map → chunk-DTPELCPW.ts.map} +0 -0
  164. /package/dist/chunks/{chunk-TZC7GDJE.ts.map → chunk-ILXMZ2HU.ts.map} +0 -0
  165. /package/dist/chunks/{chunk-JYILGR3K.ts.map → chunk-PQ75RPUP.ts.map} +0 -0
  166. /package/dist/chunks/{chunk-WQMYV4DW.ts.map → chunk-RDOX3VH5.ts.map} +0 -0
  167. /package/dist/chunks/{chunk-6O3EDBRL.ts.map → chunk-S7D6XWHI.ts.map} +0 -0
  168. /package/dist/chunks/{chunk-GNYGNHFF.ts.map → chunk-T2TYBLXK.ts.map} +0 -0
  169. /package/dist/chunks/{chunk-5TSCBBPP.ts.map → chunk-VPODHKOX.ts.map} +0 -0
  170. /package/dist/chunks/{chunk-S5OCYVPS.ts.map → chunk-YEULK7MK.ts.map} +0 -0
  171. /package/dist/chunks/{config-HYG7G5EM.ts.map → config-J5VZUY4J.ts.map} +0 -0
  172. /package/dist/chunks/{conflict-artifacts-J6WSDCWP.ts.map → conflict-artifacts-MYSH3L2J.ts.map} +0 -0
  173. /package/dist/chunks/{continuous-record-EPHGR2DU.ts.map → continuous-record-OM64J27R.ts.map} +0 -0
  174. /package/dist/chunks/{local-fields-JEKAPZKD.ts.map → local-fields-SR7PH66U.ts.map} +0 -0
  175. /package/dist/chunks/{manager-result-dispatcher-XCYPW7RC.ts.map → manager-result-dispatcher-CXUP5WDP.ts.map} +0 -0
  176. /package/dist/chunks/{merge-baseline-store-65GKUMXI.ts.map → merge-baseline-store-4Y2X7P2D.ts.map} +0 -0
  177. /package/dist/chunks/{remote-selection-ui-MYM2YCPF.ts.map → remote-selection-ui-W55BQDJQ.ts.map} +0 -0
  178. /package/dist/chunks/{setup-switch-KLGESLQX.ts.map → setup-switch-AB27ADDI.ts.map} +0 -0
  179. /package/dist/chunks/{snapshot-RGNDYT6A.ts.map → snapshot-G3W2GOGB.ts.map} +0 -0
  180. /package/dist/chunks/{snapshot-transaction-26BQO36S.ts.map → snapshot-transaction-SGRUWT73.ts.map} +0 -0
  181. /package/dist/chunks/{sync-inspection-MOMLGUTD.ts.map → sync-inspection-MDYHZHT7.ts.map} +0 -0
  182. /package/dist/chunks/{sync-state-7L4NT7W2.ts.map → sync-state-H4TFZZ7S.ts.map} +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/state/merge-baseline-store.ts", "../../src/sync/session-merge.ts", "../../src/sync/text-merge.ts"],
4
+ "sourcesContent": ["import { createHash } from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { backendIdentityCoordinates } from \"../backends/backend-identity.js\";\nimport type { AnySyncConfig } from \"../settings/settings-types.js\";\nimport type { Snapshot, SnapshotFile } from \"../snapshot/snapshot-types.js\";\nimport { compileSyncExclude, normalizeSyncExclude } from \"../sync/exclude-policy.js\";\nimport { collidingPaths, planFileMerge } from \"../sync/file-merge-planner.js\";\nimport { parseSettingsDocument } from \"../sync/json-document.js\";\nimport { validateSession } from \"../sync/session-merge.js\";\nimport { isMergeTextPath, text } from \"../sync/text-merge.js\";\nimport { syncDirectory, writeJson } from \"./json-file.js\";\nimport type { SyncState } from \"./state-types.js\";\nimport { statePathForConfig, syncStateFingerprint } from \"./sync-state-store.js\";\n\ninterface MergeBaseline {\n version: 1;\n identity: string;\n acceptedState: string;\n files: SnapshotFile[];\n}\nconst MAX_BYTES = 192 * 1024 * 1024;\nfunction eligible(file: SnapshotFile) {\n try {\n const bytes = Buffer.from(file.contentBase64, \"base64\");\n if (file.path === \"settings.json\") parseSettingsDocument(bytes);\n else if (isMergeTextPath(file.path)) text(bytes);\n else if (file.path.startsWith(\"sessions/\") && file.path.endsWith(\".jsonl\")) validateSession(bytes);\n else return false;\n return true;\n } catch {\n return false;\n }\n}\n\nfunction identity(config: AnySyncConfig) {\n return JSON.stringify([\n config.setupName,\n backendIdentityCoordinates(config),\n config.include,\n config.localFields ?? [],\n ...(config.exclude === undefined\n ? []\n : [\"exclude\", normalizeSyncExclude(config.exclude).map((rule) => rule.toLowerCase())]),\n ]);\n}\nfunction directory(config: AnySyncConfig) {\n return `${statePathForConfig(config)}.ancestors`;\n}\nasync function checkDirectory(config: AnySyncConfig, create = false) {\n const target = directory(config);\n if (create) await fs.mkdir(target, { recursive: true, mode: 0o700 });\n const stat = await fs.lstat(target);\n if (!stat.isDirectory() || stat.isSymbolicLink() || (process.platform !== \"win32\" && (stat.mode & 0o077) !== 0))\n throw new Error(\"Unsafe private ancestor directory; preserve evidence.\");\n}\nfunction baselinePath(config: AnySyncConfig, state: SyncState) {\n return path.join(directory(config), `${syncStateFingerprint(state)}.json`);\n}\n\n/** Stage before accepted state, retain its previous ancestor until journal retirement. Never bootstrap from current edits. */\nexport async function stageMergeBaseline(\n config: AnySyncConfig,\n snapshot: Snapshot,\n accepted: SyncState,\n previous?: SyncState,\n) {\n const collisions = collidingPaths(snapshot.files.map((file) => file.path));\n const excluded = compileSyncExclude(config.exclude);\n const files = snapshot.files.filter((file) => {\n return (\n !excluded(file.path) &&\n !collisions.has(file.path) &&\n accepted.lastFileHashes[file.path] === file.sha256 &&\n (file.path === \"settings.json\" || config.mergeContent || (config.agentMode && isMergeTextPath(file.path))) &&\n eligible(file)\n );\n });\n if (previous) {\n const stagedPaths = new Set(files.map((file) => file.path));\n let ancestors: SnapshotFile[] = [];\n try {\n ancestors = (await readMergeAncestors(config, previous)) ?? [];\n } catch {\n /* Keep unknown evidence; missing bytes are never invented. */\n }\n for (const ancestor of ancestors)\n if (\n !excluded(ancestor.path) &&\n !collisions.has(ancestor.path) &&\n accepted.lastFileHashes[ancestor.path] === ancestor.sha256 &&\n !stagedPaths.has(ancestor.path)\n ) {\n files.push(ancestor);\n stagedPaths.add(ancestor.path);\n }\n }\n const plan = planFileMerge({ baseline: {}, local: files, remote: [], selectionCompatible: true });\n if (plan.kind !== \"planned\" || plan.conflicts.length)\n throw new Error(\"Cannot stage unverified merge ancestor bytes.\");\n const record: MergeBaseline = {\n version: 1,\n identity: identity(config),\n acceptedState: syncStateFingerprint(accepted),\n files,\n };\n await checkDirectory(config, true);\n await writeJson(baselinePath(config, accepted), record, { maxBytes: MAX_BYTES });\n}\n\nasync function readBaselineRecord(\n config: AnySyncConfig,\n target: string,\n acceptedState: string,\n validate: () => void = () => {},\n): Promise<MergeBaseline> {\n const stat = await fs.lstat(target);\n validate();\n if (!stat.isFile() || stat.size > MAX_BYTES || (process.platform !== \"win32\" && (stat.mode & 0o077) !== 0))\n throw new Error(\"Unsafe cache.\");\n const record = JSON.parse(await fs.readFile(target, \"utf8\")) as MergeBaseline;\n validate();\n if (\n record.version !== 1 ||\n record.identity !== identity(config) ||\n record.acceptedState !== acceptedState ||\n !Array.isArray(record.files) ||\n record.files.length > 16_384 ||\n record.files.some((file) => !eligible(file))\n )\n throw new Error(\"Invalid cache identity.\");\n const plan = planFileMerge({ baseline: {}, local: record.files, remote: [], selectionCompatible: true });\n if (plan.kind !== \"planned\" || plan.conflicts.length) throw new Error(\"Invalid cache bytes.\");\n return record;\n}\n\nexport async function readMergeAncestors(config: AnySyncConfig, state: SyncState): Promise<SnapshotFile[] | undefined> {\n let record: MergeBaseline;\n try {\n await checkDirectory(config);\n record = await readBaselineRecord(config, baselinePath(config, state), syncStateFingerprint(state));\n for (const file of record.files) {\n if (\n state.lastFileHashes[file.path] !== file.sha256 ||\n createHash(\"sha256\").update(Buffer.from(file.contentBase64, \"base64\")).digest(\"hex\") !== file.sha256\n )\n throw new Error(\"Cache hash mismatch.\");\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw new Error(\"Merge ancestor is invalid; preserve its private cache and review the conflict.\");\n }\n const excluded = compileSyncExclude(config.exclude);\n return record.files.filter((file) => !excluded(file.path));\n}\n/** A no-op must not skip seeding or repairing ancestors required by later merges. */\nexport async function hasCurrentMergeBaseline(config: AnySyncConfig, snapshot: Snapshot, state: SyncState) {\n try {\n const ancestors = await readMergeAncestors(config, state);\n if (!ancestors) return false;\n const hashes = new Map(ancestors.map((file) => [file.path, file.sha256]));\n return snapshot.files.every(\n (file) =>\n !(file.path === \"settings.json\" || config.mergeContent || (config.agentMode && isMergeTextPath(file.path))) ||\n !eligible(file) ||\n hashes.get(file.path) === file.sha256,\n );\n } catch {\n // Preserve the existing full path's validation and repair behavior for unknown evidence.\n return false;\n }\n}\n\nexport async function readMergeAncestor(config: AnySyncConfig, state: SyncState, filePath: string) {\n const file = (await readMergeAncestors(config, state))?.find((file) => file.path === filePath);\n return file ? Buffer.from(file.contentBase64, \"base64\") : undefined;\n}\n\n/** Caller must hold the sync operation lock and retire the commit journal before pruning. */\nexport async function pruneMergeBaselines(config: AnySyncConfig, state: SyncState, validate: () => void) {\n validate();\n const keep = path.basename(baselinePath(config, state));\n let names: string[];\n try {\n await checkDirectory(config);\n validate();\n names = await fs.readdir(directory(config));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw error;\n }\n for (const name of names) {\n validate();\n if (name === keep || !/^[a-f0-9]{64}\\.json$/u.test(name)) continue;\n const target = path.join(directory(config), name);\n try {\n await readBaselineRecord(config, target, name.slice(0, -5), validate);\n } catch {\n validate();\n continue; // Unknown/corrupted evidence is not an owned pruning candidate.\n }\n validate();\n await fs.rm(target);\n validate();\n }\n await syncDirectory(directory(config));\n validate();\n}\n", "import { CURRENT_SESSION_VERSION } from \"@earendil-works/pi-coding-agent\";\nimport { parseJsonObjectDocument } from \"./json-document.js\";\nimport { text } from \"./text-merge.js\";\n\n// Public header IDs use Pi assertValidSessionId; generated entry IDs have a separate grammar.\nconst sessionId = (value: unknown): value is string =>\n typeof value === \"string\" && /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/u.test(value);\nconst id = (value: unknown): value is string => typeof value === \"string\" && /^[a-zA-Z0-9_-]{1,128}$/u.test(value);\nconst content = (value: unknown, types = [\"text\", \"image\", \"thinking\", \"toolCall\"]): boolean =>\n typeof value === \"string\" ||\n (Array.isArray(value) &&\n value.every(\n (block) =>\n object(block) &&\n types.includes(String(block.type)) &&\n ((block.type === \"text\" && typeof block.text === \"string\") ||\n (block.type === \"image\" && typeof block.data === \"string\" && typeof block.mimeType === \"string\") ||\n (block.type === \"thinking\" && typeof block.thinking === \"string\") ||\n (block.type === \"toolCall\" &&\n typeof block.id === \"string\" &&\n typeof block.name === \"string\" &&\n object(block.arguments))),\n ));\nconst message = (value: unknown) => {\n if (!object(value) || typeof value.timestamp !== \"number\" || !Number.isFinite(value.timestamp)) return false;\n switch (value.role) {\n case \"system\":\n return (\n content(value.content, [\"text\"]) &&\n (value.sections === undefined ||\n (object(value.sections) &&\n Object.values(value.sections).every((section) => section === null || typeof section === \"string\"))) &&\n (value.toolsAdded === undefined ||\n (Array.isArray(value.toolsAdded) &&\n value.toolsAdded.every(\n (tool) =>\n object(tool) &&\n typeof tool.name === \"string\" &&\n typeof tool.description === \"string\" &&\n object(tool.parameters),\n ))) &&\n (value.toolsRemoved === undefined ||\n (Array.isArray(value.toolsRemoved) &&\n value.toolsRemoved.every((tool) => object(tool) && typeof tool.name === \"string\")))\n );\n case \"user\":\n return content(value.content, [\"text\", \"image\"]);\n case \"assistant\":\n return (\n Array.isArray(value.content) &&\n content(value.content, [\"text\", \"thinking\", \"toolCall\"]) &&\n typeof value.api === \"string\" &&\n typeof value.provider === \"string\" &&\n typeof value.model === \"string\" &&\n object(value.usage) &&\n [\"pending\", \"stop\", \"length\", \"toolUse\", \"error\", \"aborted\", \"deferred\"].includes(String(value.stopReason))\n );\n case \"toolResult\":\n return (\n typeof value.toolCallId === \"string\" &&\n typeof value.toolName === \"string\" &&\n Array.isArray(value.content) &&\n content(value.content, [\"text\", \"image\"]) &&\n typeof value.isError === \"boolean\"\n );\n case \"custom\":\n return (\n typeof value.customType === \"string\" &&\n content(value.content, [\"text\", \"image\"]) &&\n typeof value.display === \"boolean\"\n );\n case \"bashExecution\":\n return (\n typeof value.command === \"string\" &&\n typeof value.output === \"string\" &&\n typeof value.cancelled === \"boolean\" &&\n typeof value.truncated === \"boolean\"\n );\n case \"branchSummary\":\n return typeof value.summary === \"string\" && (value.fromId === null || typeof value.fromId === \"string\");\n case \"compactionSummary\":\n return (\n typeof value.summary === \"string\" &&\n typeof value.tokensBefore === \"number\" &&\n Number.isFinite(value.tokensBefore) &&\n value.tokensBefore >= 0\n );\n default:\n return false;\n }\n};\nconst object = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n/** Stricter than Pi's repair-tolerant reader: never skip malformed lines or migrate a log. */\nexport function validateSession(bytes: Buffer) {\n if (CURRENT_SESSION_VERSION !== 3) throw new Error(\"Unaudited Pi session format; require review.\");\n const raw = text(bytes);\n if (!raw.endsWith(\"\\n\")) throw new Error(\"Incomplete session tail.\");\n const rows: unknown[] = raw\n .slice(0, -1)\n .split(\"\\n\")\n .map((line) => {\n if (line.startsWith(\"\\uFEFF\")) throw new Error(\"Unexpected session-record BOM; require review.\");\n return parseJsonObjectDocument(Buffer.from(line)).root.value;\n });\n if (rows.length > 16_384) throw new Error(\"Session entry bound exceeded.\");\n const header = rows[0];\n if (\n !object(header) ||\n header.type !== \"session\" ||\n header.version !== CURRENT_SESSION_VERSION ||\n !sessionId(header.id) ||\n typeof header.cwd !== \"string\" ||\n typeof header.timestamp !== \"string\" ||\n !Number.isFinite(Date.parse(header.timestamp)) ||\n (header.parentSession !== undefined && typeof header.parentSession !== \"string\")\n )\n throw new Error(\"Unsupported session header.\");\n const ids = new Set<string>();\n const known = (value: unknown) => id(value) && ids.has(value);\n for (const row of rows.slice(1)) {\n if (\n !object(row) ||\n !id(row.id) ||\n ids.has(row.id) ||\n typeof row.timestamp !== \"string\" ||\n !Number.isFinite(Date.parse(row.timestamp)) ||\n (row.parentId !== null && !known(row.parentId))\n )\n throw new Error(\"Invalid session graph.\");\n const strings = (...keys: string[]) => keys.every((key) => typeof row[key] === \"string\");\n let valid = false;\n switch (row.type) {\n case \"message\":\n valid = message(row.message);\n break;\n case \"thinking_level_change\":\n valid = strings(\"thinkingLevel\");\n break;\n case \"model_change\":\n valid = strings(\"provider\", \"modelId\");\n break;\n case \"usage\":\n valid = strings(\"kind\", \"provider\", \"model\") && object(row.usage);\n break;\n case \"compaction\":\n valid =\n strings(\"summary\") &&\n (known(row.firstKeptEntryId) || row.firstKeptEntryId === row.id) &&\n (row.systemMessage === undefined ||\n (object(row.systemMessage) && row.systemMessage.role === \"system\" && message(row.systemMessage))) &&\n typeof row.tokensBefore === \"number\" &&\n Number.isFinite(row.tokensBefore) &&\n row.tokensBefore >= 0;\n break;\n case \"branch_summary\":\n valid = strings(\"summary\") && (known(row.fromId) || row.fromId === \"root\");\n break;\n case \"custom\":\n valid = strings(\"customType\");\n break;\n case \"custom_message\":\n valid = strings(\"customType\") && typeof row.display === \"boolean\" && content(row.content, [\"text\", \"image\"]);\n break;\n case \"context_edit\":\n valid =\n known(row.targetId) &&\n (row.replacement === null || (object(row.replacement) && content(row.replacement.content)));\n break;\n case \"label\":\n valid = known(row.targetId) && (row.label === undefined || typeof row.label === \"string\");\n break;\n case \"session_info\":\n valid = row.name === undefined || typeof row.name === \"string\";\n break;\n }\n if (!valid) throw new Error(\"Unsupported session entry.\");\n ids.add(row.id);\n }\n return header.id;\n}\nexport function mergeSession(base: Buffer, local: Buffer, remote: Buffer): Buffer | undefined {\n try {\n const identity = validateSession(base);\n if (validateSession(local) !== identity || validateSession(remote) !== identity) return;\n const prefix = (left: Buffer, right: Buffer) =>\n right.length >= left.length && right.subarray(0, left.length).equals(left);\n if (!prefix(base, local) || !prefix(base, remote)) return;\n if (prefix(local, remote)) return remote;\n if (prefix(remote, local)) return local;\n } catch {\n return;\n }\n}\n", "import path from \"node:path\";\nexport const TEXT_LIMIT = 1024 * 1024;\nexport const TEXT_MERGE_WORK_LIMIT = 8_000_000;\nexport interface TextMergeBudget {\n remaining: number;\n}\nexport interface TextMergeOptions {\n budget?: TextMergeBudget;\n signal?: AbortSignal;\n}\nfunction charge(budget: TextMergeBudget, work: number) {\n if (work > budget.remaining) throw new Error(\"Text merge operation complexity bound exceeded.\");\n budget.remaining -= work;\n}\nexport function isMergeTextPath(filePath: string) {\n return (\n filePath === \"AGENTS.md\" ||\n (/\\.(?:md|txt)$/u.test(filePath) &&\n [\"prompts\", \"skills\"].includes(filePath.split(\"/\")[0] ?? \"\") &&\n path.posix.basename(filePath) !== \"keybindings.json\")\n );\n}\nexport function text(bytes: Buffer) {\n if (bytes.length > TEXT_LIMIT) throw new Error(\"Text merge bound exceeded.\");\n const decoded = bytes.toString(\"utf8\");\n if (\n !Buffer.from(decoded).equals(bytes) ||\n bytes.some((byte) => (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) || byte === 127)\n )\n throw new Error(\"Unsupported text encoding.\");\n return decoded;\n}\nexport type Hunk = { start: number; end: number; lines: string[] };\nexport function lines(value: string) {\n return value.match(/[^\\n]*\\n|[^\\n]+$/gu) ?? [];\n}\nexport function edits(base: string[], next: string[], signal?: AbortSignal): Hunk[] {\n const width = next.length + 1;\n if ((base.length + 1) * width > 4_000_000) throw new Error(\"Text merge complexity bound exceeded.\");\n // Intern once so each charged DP cell compares fixed-size IDs, not long line strings.\n const ids = new Map<string, number>();\n const intern = (line: string) => {\n let id = ids.get(line);\n if (id === undefined) {\n id = ids.size;\n ids.set(line, id);\n }\n return id;\n };\n const baseIds = base.map(intern);\n const nextIds = next.map(intern);\n const grid = new Uint32Array((base.length + 1) * width);\n for (let i = base.length - 1; i >= 0; i--) {\n signal?.throwIfAborted();\n for (let j = next.length - 1; j >= 0; j--)\n grid[i * width + j] =\n baseIds[i] === nextIds[j]\n ? 1 + (grid[(i + 1) * width + j + 1] ?? 0)\n : Math.max(grid[(i + 1) * width + j] ?? 0, grid[i * width + j + 1] ?? 0);\n }\n const result: Hunk[] = [];\n let i = 0;\n let j = 0;\n let active: Hunk | undefined;\n while (i < base.length || j < next.length) {\n if (i < base.length && j < next.length && baseIds[i] === nextIds[j]) {\n if (active) {\n result.push(active);\n active = undefined;\n }\n i++;\n j++;\n continue;\n }\n active ??= { start: i, end: i, lines: [] };\n if (j < next.length && (i === base.length || (grid[i * width + j + 1] ?? 0) >= (grid[(i + 1) * width + j] ?? 0)))\n active.lines.push(next[j++] ?? \"\");\n else active.end = ++i;\n }\n if (active) result.push(active);\n return result;\n}\nexport function mergeText(\n baseBytes: Buffer,\n localBytes: Buffer,\n remoteBytes: Buffer,\n options: TextMergeOptions = {},\n): Buffer | undefined {\n const budget = options.budget ?? { remaining: TEXT_MERGE_WORK_LIMIT };\n try {\n options.signal?.throwIfAborted();\n const base = lines(text(baseBytes));\n const ours = lines(text(localBytes));\n const theirs = lines(text(remoteBytes));\n const cells = [ours, theirs].map((next) => (base.length + 1) * (next.length + 1));\n if (cells.some((count) => count > 4_000_000)) return;\n charge(budget, (cells[0] ?? 0) + (cells[1] ?? 0));\n const local = edits(base, ours, options.signal);\n const remote = edits(base, theirs, options.signal);\n const combined = [...local];\n for (const right of remote) {\n let same = false;\n for (const left of local) {\n options.signal?.throwIfAborted();\n charge(budget, 1);\n if (left.start === right.start && left.end === right.end && left.lines.join(\"\") === right.lines.join(\"\")) {\n same = true;\n continue;\n }\n const overlap =\n left.start === left.end || right.start === right.end\n ? left.start <= right.end && right.start <= left.end\n : left.start < right.end && right.start < left.end;\n if (overlap) return;\n }\n if (!same) combined.push(right);\n }\n combined.sort((left, right) => left.start - right.start || left.end - right.end);\n let cursor = 0;\n const output: string[] = [];\n for (const edit of combined) {\n output.push(...base.slice(cursor, edit.start), ...edit.lines);\n cursor = edit.end;\n }\n output.push(...base.slice(cursor));\n const result = Buffer.from(output.join(\"\"));\n text(result);\n return result;\n } catch {\n options.signal?.throwIfAborted();\n return;\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,OAAO,QAAQ;AACf,OAAOA,WAAU;;;ACFjB,SAAS,+BAA+B;;;ACAxC,OAAO,UAAU;AACV,IAAM,aAAa,OAAO;AAC1B,IAAM,wBAAwB;AAQrC,SAAS,OAAO,QAAyB,MAAc;AACrD,MAAI,OAAO,OAAO,UAAW,OAAM,IAAI,MAAM,iDAAiD;AAC9F,SAAO,aAAa;AACtB;AACO,SAAS,gBAAgB,UAAkB;AAChD,SACE,aAAa,eACZ,iBAAiB,KAAK,QAAQ,KAC7B,CAAC,WAAW,QAAQ,EAAE,SAAS,SAAS,MAAM,GAAG,EAAE,CAAC,KAAK,EAAE,KAC3D,KAAK,MAAM,SAAS,QAAQ,MAAM;AAExC;AACO,SAAS,KAAK,OAAe;AAClC,MAAI,MAAM,SAAS,WAAY,OAAM,IAAI,MAAM,4BAA4B;AAC3E,QAAM,UAAU,MAAM,SAAS,MAAM;AACrC,MACE,CAAC,OAAO,KAAK,OAAO,EAAE,OAAO,KAAK,KAClC,MAAM,KAAK,CAAC,SAAU,OAAO,MAAM,SAAS,KAAK,SAAS,MAAM,SAAS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AAM,GAAG,IAAI;AAChD,QAAI;AACF,YAAM,mBAAmB,QAAQ,QAAQ,KAAK,MAAM,GAAG,EAAE,GAAG,QAAQ;AAAA,IACtE,QAAQ;AACN,eAAS;AACT;AAAA,IACF;AACA,aAAS;AACT,UAAM,GAAG,GAAG,MAAM;AAClB,aAAS;AAAA,EACX;AACA,QAAM,cAAc,UAAU,MAAM,CAAC;AACrC,WAAS;AACX;",
6
+ "names": ["path", "id", "i", "j", "identity", "path", "file"]
7
+ }
@@ -2,7 +2,7 @@
2
2
  // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
3
  import {
4
4
  mergeJournalIdentity
5
- } from "./chunk-BEST45H2.ts";
5
+ } from "./chunk-WEKGW7HV.ts";
6
6
  import {
7
7
  mergePathIdentity,
8
8
  planFileMerge
@@ -10,7 +10,7 @@ import {
10
10
  import {
11
11
  statePathForConfig,
12
12
  syncStateFingerprint
13
- } from "./chunk-DN4IA7MR.ts";
13
+ } from "./chunk-4NVHHDN2.ts";
14
14
  import {
15
15
  syncDirectory,
16
16
  writeJson
@@ -226,4 +226,4 @@ export {
226
226
  saveConflictArtifact,
227
227
  readConflictArtifact
228
228
  };
229
- //# sourceMappingURL=chunk-5TSCBBPP.ts.map
229
+ //# sourceMappingURL=chunk-VPODHKOX.ts.map
@@ -3,32 +3,41 @@
3
3
  import {
4
4
  fileHashMap,
5
5
  sameHashes
6
- } from "./chunk-Y4UVXOLQ.ts";
6
+ } from "./chunk-6YGRZSCN.ts";
7
7
  import {
8
8
  portableSnapshot,
9
9
  sameLocalFields,
10
10
  validatePortableSnapshot,
11
11
  validateSnapshotFieldPolicy
12
- } from "./chunk-MKSMJPVA.ts";
12
+ } from "./chunk-P3YD4ONV.ts";
13
13
  import {
14
14
  planFileMerge
15
15
  } from "./chunk-XJHQPB3E.ts";
16
16
  import {
17
17
  statePathForConfig,
18
18
  syncStateFingerprint
19
- } from "./chunk-DN4IA7MR.ts";
19
+ } from "./chunk-4NVHHDN2.ts";
20
20
  import {
21
21
  readJsonIfExists,
22
22
  syncDirectory,
23
23
  writeJson
24
24
  } from "./chunk-AR2DGDUI.ts";
25
+ import {
26
+ normalizeSyncExclude
27
+ } from "./chunk-3JTZF7Z5.ts";
25
28
 
26
29
  // src/sync/merge-journal.ts
27
30
  import { randomUUID } from "node:crypto";
28
31
  import fs from "node:fs/promises";
29
32
  import path from "node:path";
30
33
  function mergeJournalIdentity(config, backendIdentity) {
31
- return JSON.stringify([config.setupName, backendIdentity, [...config.include].sort(), config.localFields ?? null]);
34
+ return JSON.stringify([
35
+ config.setupName,
36
+ backendIdentity,
37
+ [...config.include].sort(),
38
+ config.localFields ?? null,
39
+ ...config.exclude === void 0 ? [] : ["exclude", normalizeSyncExclude(config.exclude).map((rule) => rule.toLowerCase())]
40
+ ]);
32
41
  }
33
42
  function mergeJournalPath(config) {
34
43
  return `${statePathForConfig(config)}.merge-journal.json`;
@@ -55,7 +64,7 @@ async function readMergeJournal(config) {
55
64
  ...journal.accepted ? [journal.accepted] : []
56
65
  ]) {
57
66
  validateSnapshotFieldPolicy(snapshot);
58
- if (snapshot.version !== 1 && snapshot.version !== 2 && snapshot.version !== 3 || typeof snapshot.id !== "string" || typeof snapshot.profile !== "string" || snapshot.files.length > 16384 || snapshot.files.reduce(
67
+ if (snapshot.version !== 1 && snapshot.version !== 2 && snapshot.version !== 3 && snapshot.version !== 4 || typeof snapshot.id !== "string" || typeof snapshot.profile !== "string" || snapshot.files.length > 16384 || snapshot.files.reduce(
59
68
  (bytes, file) => bytes + (typeof file?.contentBase64 === "string" ? file.contentBase64.length * 0.75 : Infinity),
60
69
  0
61
70
  ) > 64 * 1024 * 1024)
@@ -65,7 +74,7 @@ async function readMergeJournal(config) {
65
74
  throw new Error("Invalid journal collision group.");
66
75
  }
67
76
  validatePortableSnapshot(journal.upload);
68
- if ((journal.upload.version === 2 || journal.upload.version === 3) && !journal.accepted)
77
+ if (journal.upload.version >= 2 && !journal.accepted)
69
78
  throw new Error("Portable merge journal requires an explicit accepted projection.");
70
79
  if (journal.accepted) validatePortableSnapshot(journal.accepted);
71
80
  } catch {
@@ -94,7 +103,7 @@ async function readMergeJournal(config) {
94
103
  if (journal.progress) {
95
104
  const before = fileHashMap(journal.before);
96
105
  const after = fileHashMap(journal.after);
97
- const { readConflictArtifact } = await import("./conflict-artifacts-J6WSDCWP.ts");
106
+ const { readConflictArtifact } = await import("./conflict-artifacts-MYSH3L2J.ts");
98
107
  const backendIdentity = JSON.parse(journal.identity)[1];
99
108
  if (typeof backendIdentity !== "string") throw new Error("Invalid partial backend identity.");
100
109
  const byArtifact = /* @__PURE__ */ new Map();
@@ -150,4 +159,4 @@ export {
150
159
  retireMergeJournal,
151
160
  requireNoMergeJournal
152
161
  };
153
- //# sourceMappingURL=chunk-BEST45H2.ts.map
162
+ //# sourceMappingURL=chunk-WEKGW7HV.ts.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/sync/merge-journal.ts"],
4
+ "sourcesContent": ["import { randomUUID } from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { RemoteHead } from \"../backends/sync-backend.js\";\nimport type { AnySyncConfig } from \"../settings/settings-types.js\";\nimport type { Snapshot } from \"../snapshot/snapshot-types.js\";\nimport { readJsonIfExists, syncDirectory, writeJson } from \"../state/json-file.js\";\nimport { statePathForConfig, syncStateFingerprint } from \"../state/sync-state-store.js\";\nimport { normalizeSyncExclude } from \"./exclude-policy.js\";\nimport { planFileMerge } from \"./file-merge-planner.js\";\nimport {\n portableSnapshot,\n sameLocalFields,\n validatePortableSnapshot,\n validateSnapshotFieldPolicy,\n} from \"./local-fields.js\";\nimport type { PartialProgress } from \"./partial-progress.js\";\nimport { fileHashMap, sameHashes } from \"./sync-state.js\";\n\nexport interface MergeJournal {\n version: 1;\n identity: string;\n before: Snapshot;\n after: Snapshot;\n accepted?: Snapshot;\n progress?: PartialProgress;\n upload: Snapshot;\n expectedHead: RemoteHead;\n committedHead?: RemoteHead;\n /** No remote publication was attempted; a stale candidate can retire if local preimages remain intact. */\n applyOnly?: boolean;\n backup: string;\n stateIdentity: string;\n /** Effective collection/apply root; absent legacy evidence cannot authorize session recovery. */\n sessionRoot?: string;\n warnings?: string[];\n}\n\nexport function mergeJournalIdentity(config: AnySyncConfig, backendIdentity: string) {\n return JSON.stringify([\n config.setupName,\n backendIdentity,\n [...config.include].sort(),\n config.localFields ?? null,\n ...(config.exclude === undefined\n ? []\n : [\"exclude\", normalizeSyncExclude(config.exclude).map((rule) => rule.toLowerCase())]),\n ]);\n}\n\nexport function mergeJournalPath(config: AnySyncConfig) {\n return `${statePathForConfig(config)}.merge-journal.json`;\n}\n\nexport async function readMergeJournal(config: AnySyncConfig): Promise<MergeJournal | undefined> {\n let journal: MergeJournal | undefined;\n try {\n const stat = await fs.lstat(mergeJournalPath(config));\n if (!stat.isFile() || stat.size > 384 * 1024 * 1024) throw new Error(\"Unsafe or oversized journal.\");\n journal = await readJsonIfExists<MergeJournal>(mergeJournalPath(config));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n // A JSON parser error may quote sensitive journal contents; do not retain it in a public error.\n throw new Error(\"Cannot read the private merge journal; preserve it and review recovery.\");\n }\n if (!journal) return;\n if (\n journal.version !== 1 ||\n typeof journal.identity !== \"string\" ||\n typeof journal.backup !== \"string\" ||\n typeof journal.stateIdentity !== \"string\" ||\n (journal.applyOnly !== undefined &&\n (journal.applyOnly !== true ||\n !journal.committedHead ||\n journal.committedHead.revision !== journal.expectedHead?.revision ||\n journal.committedHead.snapshotId !== journal.expectedHead?.snapshotId ||\n journal.upload?.id !== journal.expectedHead?.snapshotId)) ||\n (journal.sessionRoot !== undefined &&\n (typeof journal.sessionRoot !== \"string\" ||\n !path.isAbsolute(journal.sessionRoot) ||\n path.resolve(journal.sessionRoot) !== journal.sessionRoot)) ||\n (journal.warnings !== undefined &&\n (!Array.isArray(journal.warnings) ||\n journal.warnings.length > 64 ||\n journal.warnings.some((item) => typeof item !== \"string\"))) ||\n !journal.expectedHead ||\n typeof journal.expectedHead.revision !== \"string\" ||\n !journal.before ||\n !journal.after ||\n !journal.upload ||\n !Array.isArray(journal.before.files) ||\n !Array.isArray(journal.after.files) ||\n !Array.isArray(journal.upload.files)\n )\n throw new Error(\"Unsupported or damaged merge journal; preserve it and review recovery before syncing.\");\n // Verify every path and byte, including the unmanaged remote files retained for publication.\n try {\n const pinnedPaths = new Set(journal.progress?.groups.flatMap((group) => group.paths) ?? []);\n for (const snapshot of [\n journal.before,\n journal.after,\n journal.upload,\n ...(journal.accepted ? [journal.accepted] : []),\n ]) {\n validateSnapshotFieldPolicy(snapshot);\n if (\n (snapshot.version !== 1 && snapshot.version !== 2 && snapshot.version !== 3 && snapshot.version !== 4) ||\n typeof snapshot.id !== \"string\" ||\n typeof snapshot.profile !== \"string\" ||\n snapshot.files.length > 16_384 ||\n snapshot.files.reduce(\n (bytes, file) =>\n bytes + (typeof file?.contentBase64 === \"string\" ? file.contentBase64.length * 0.75 : Infinity),\n 0,\n ) >\n 64 * 1024 * 1024\n )\n throw new Error(\"Invalid journal input.\");\n const plan = planFileMerge({ baseline: {}, local: snapshot.files, remote: [], selectionCompatible: true });\n if (\n plan.kind !== \"planned\" ||\n plan.conflicts.some((conflict) => conflict.reason !== \"path-collision\" || !pinnedPaths.has(conflict.path))\n )\n throw new Error(\"Invalid journal collision group.\");\n }\n validatePortableSnapshot(journal.upload);\n if (journal.upload.version >= 2 && !journal.accepted)\n throw new Error(\"Portable merge journal requires an explicit accepted projection.\");\n if (journal.accepted) validatePortableSnapshot(journal.accepted);\n } catch {\n throw new Error(\"Invalid merge journal paths, metadata, or bytes; preserve evidence for review.\");\n }\n // Integrity is intrinsic to the recorded transaction, not the user's current recovery policy.\n // completeJournal separately checks that the recorded policy matches the current setup.\n try {\n if (\n journal.accepted &&\n (!sameLocalFields(journal.accepted.localFields, journal.upload.localFields) ||\n !sameHashes(\n fileHashMap(portableSnapshot(journal.after, journal.upload.localFields)),\n fileHashMap(portableSnapshot(journal.accepted, journal.upload.localFields)),\n ))\n )\n throw new Error(\"Projection mismatch.\");\n } catch {\n throw new Error(\"Invalid accepted merge projection; preserve journal evidence.\");\n }\n if (journal.progress) {\n const known = new Set([\n ...Object.keys(journal.progress.previous?.lastFileHashes ?? {}),\n ...[...journal.before.files, ...journal.after.files, ...journal.upload.files].map((file) => file.path),\n ]);\n const progress = journal.progress;\n if (\n !config.partialSync ||\n !progress.previous ||\n syncStateFingerprint(progress.previous) !== journal.stateIdentity ||\n !Array.isArray(progress.groups) ||\n progress.groups.length > 16_384 ||\n progress.groups.some(\n (group) =>\n !Array.isArray(group.paths) ||\n !group.paths.length ||\n group.paths.length > 16_384 ||\n group.paths.some((filePath) => !known.has(filePath)) ||\n !/^[a-f0-9-]{36}$/u.test(group.artifact),\n )\n )\n throw new Error(\"Invalid partial acceptance metadata; preserve journal evidence.\");\n }\n if (journal.progress) {\n const before = fileHashMap(journal.before);\n const after = fileHashMap(journal.after);\n const { readConflictArtifact } = await import(\"./conflict-artifacts.js\");\n const backendIdentity = (JSON.parse(journal.identity) as unknown[])[1];\n if (typeof backendIdentity !== \"string\") throw new Error(\"Invalid partial backend identity.\");\n const byArtifact = new Map<string, typeof journal.progress.groups>();\n for (const group of journal.progress.groups) {\n const groups = byArtifact.get(group.artifact) ?? [];\n groups.push(group);\n byArtifact.set(group.artifact, groups);\n }\n for (const [token, groups] of byArtifact) {\n const artifact = await readConflictArtifact(config, backendIdentity, token);\n const retainedGroups = new Set(artifact.groups.map((group) => JSON.stringify(group.paths)));\n const remote = fileHashMap(artifact.remote);\n const upload = fileHashMap(journal.upload);\n for (const group of groups) {\n if (!retainedGroups.has(JSON.stringify(group.paths)))\n throw new Error(\"Partial group does not match retained artifact evidence.\");\n for (const filePath of group.paths)\n if (\n before[filePath] !== after[filePath] ||\n remote[filePath] !== upload[filePath] ||\n journal.progress.previous.lastFileHashes[filePath] !== artifact.state.lastFileHashes[filePath]\n )\n throw new Error(\"Withheld version changed in journal; preserve evidence.\");\n }\n }\n }\n return journal;\n}\n\nexport async function writeMergeJournal(config: AnySyncConfig, journal: MergeJournal) {\n await writeJson(mergeJournalPath(config), journal, { maxBytes: 384 * 1024 * 1024 });\n}\n\nexport async function clearMergeJournal(config: AnySyncConfig) {\n await fs.rm(mergeJournalPath(config), { force: true });\n await syncDirectory(path.dirname(mergeJournalPath(config)));\n}\n\nexport async function retireMergeJournal(config: AnySyncConfig) {\n if (!(await readMergeJournal(config))) return;\n const file = mergeJournalPath(config);\n await fs.rename(file, `${file}.${randomUUID()}.resolved`);\n await syncDirectory(path.dirname(file));\n}\n\nexport async function requireNoMergeJournal(config: AnySyncConfig, options: { force?: boolean } = {}) {\n const journal = await readMergeJournal(config);\n if (options.force || !journal) return;\n if (journal) {\n throw new Error(\n \"A merged transfer needs recovery. Run /sync sync to reconcile it. If newer local edits or remote revisions prevent recovery, review /sync diff and explicitly choose push --force or pull --force; the selected directional result will archive the old journal, not restore old bytes. Keep its backup; do not downgrade while recovery is pending.\",\n );\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,OAAO,QAAQ;AACf,OAAO,UAAU;AAoCV,SAAS,qBAAqB,QAAuB,iBAAyB;AACnF,SAAO,KAAK,UAAU;AAAA,IACpB,OAAO;AAAA,IACP;AAAA,IACA,CAAC,GAAG,OAAO,OAAO,EAAE,KAAK;AAAA,IACzB,OAAO,eAAe;AAAA,IACtB,GAAI,OAAO,YAAY,SACnB,CAAC,IACD,CAAC,WAAW,qBAAqB,OAAO,OAAO,EAAE,IAAI,CAAC,SAAS,KAAK,YAAY,CAAC,CAAC;AAAA,EACxF,CAAC;AACH;AAEO,SAAS,iBAAiB,QAAuB;AACtD,SAAO,GAAG,mBAAmB,MAAM,CAAC;AACtC;AAEA,eAAsB,iBAAiB,QAA0D;AAC/F,MAAI;AACJ,MAAI;AACF,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QAAQ,IAAI,CAAC;AACxC;AAEA,eAAsB,sBAAsB,QAAuB,UAA+B,CAAC,GAAG;AACpG,QAAM,UAAU,MAAM,iBAAiB,MAAM;AAC7C,MAAI,QAAQ,SAAS,CAAC,QAAS;AAC/B,MAAI,SAAS;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -1,5 +1,10 @@
1
1
  // @generated by scripts/build-runtime.mjs; do not edit.
2
2
  // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
+ import {
4
+ compileSyncExclude,
5
+ normalizeSyncExclude,
6
+ sameSyncExclude
7
+ } from "./chunk-3JTZF7Z5.ts";
3
8
  import {
4
9
  isDeniedPath,
5
10
  toPosix
@@ -19,7 +24,6 @@ var BUILT_IN_SYNC_ROOTS = [
19
24
  "extensions"
20
25
  ];
21
26
  var DEFAULT_SYNC_INCLUDE = [...BUILT_IN_SYNC_ROOTS];
22
- var SNAPSHOT_SELECTION_VERSION = 1;
23
27
  var MAX_SYNC_INCLUDE_ITEMS = 1024;
24
28
  var MAX_SYNC_INCLUDE_PATH_BYTES = 4096;
25
29
  var MAX_SYNC_INCLUDE_TOTAL_BYTES = 256 * 1024;
@@ -110,19 +114,32 @@ function validateAgentRelativeInclude(value) {
110
114
  }
111
115
  function portableSnapshotSelection(value) {
112
116
  const selection = value;
113
- if (!selection || typeof selection !== "object" || Array.isArray(selection) || selection.version !== SNAPSHOT_SELECTION_VERSION || !Object.hasOwn(selection, "include") || Object.keys(selection).some((key) => key !== "version" && key !== "include")) {
117
+ if (!selection || typeof selection !== "object" || Array.isArray(selection) || selection.version !== 1 && selection.version !== 2 || !Object.hasOwn(selection, "include") || selection.version === 2 && !Object.hasOwn(selection, "exclude") || Object.keys(selection).some(
118
+ (key) => key !== "version" && key !== "include" && !(selection.version === 2 && key === "exclude")
119
+ ))
114
120
  throw new Error("Invalid snapshot selection policy.");
115
- }
116
- return {
117
- version: SNAPSHOT_SELECTION_VERSION,
118
- include: normalizeSyncInclude(selection.include)
119
- };
121
+ const include = normalizeSyncInclude(selection.include);
122
+ if (selection.version === 1) return { version: 1, include };
123
+ if (!Array.isArray(selection.exclude)) throw new Error("Invalid snapshot exclude policy.");
124
+ return { version: 2, include, exclude: normalizeSyncExclude(selection.exclude) };
120
125
  }
121
126
  function snapshotSelectionInclude(snapshot) {
122
127
  return snapshot.selection === void 0 ? void 0 : portableSnapshotSelection(snapshot.selection).include;
123
128
  }
124
- function selectionForSnapshot(include) {
125
- return { version: SNAPSHOT_SELECTION_VERSION, include: normalizeSyncInclude(include) };
129
+ function snapshotSelectionExclude(snapshot) {
130
+ return snapshot.selection === void 0 ? void 0 : portableSnapshotSelection(snapshot.selection).exclude;
131
+ }
132
+ function selectionForSnapshot(include, exclude) {
133
+ const normalized = normalizeSyncInclude(include);
134
+ return exclude === void 0 ? { version: 1, include: normalized } : { version: 2, include: normalized, exclude: normalizeSyncExclude(exclude) };
135
+ }
136
+ function sameSnapshotSelection(left, right) {
137
+ return JSON.stringify(left === void 0 ? null : portableSnapshotSelection(left)) === JSON.stringify(right === void 0 ? null : portableSnapshotSelection(right));
138
+ }
139
+ function validateSnapshotSelection(snapshot) {
140
+ const selection = snapshot.selection === void 0 ? void 0 : portableSnapshotSelection(snapshot.selection);
141
+ if (snapshot.version === 4 !== (selection?.version === 2))
142
+ throw new Error("Exclude policy requires snapshot version 4 and selection version 2.");
126
143
  }
127
144
  function sameSyncInclude(left, right) {
128
145
  const normalizedLeft = normalizeSyncInclude(left);
@@ -140,23 +157,29 @@ function compareSyncInclude(local, remote) {
140
157
  localOnly: localInclude.filter((item) => !remoteSet.has(item))
141
158
  };
142
159
  }
143
- function inspectRemoteSelection(localInclude, snapshot) {
160
+ function inspectRemoteSelection(localInclude, snapshot, localExclude) {
144
161
  const remoteInclude = snapshotSelectionInclude(snapshot);
145
- if (!remoteInclude) {
146
- return { kind: "legacy", discovered: discoverLegacySnapshotInclude(snapshot) };
147
- }
162
+ if (!remoteInclude) return { kind: "legacy", discovered: discoverLegacySnapshotInclude(snapshot) };
163
+ const exclude = snapshotSelectionExclude(snapshot);
148
164
  const comparison = compareSyncInclude(localInclude, remoteInclude);
149
- return comparison.same ? { kind: "same", include: remoteInclude } : { kind: "different", include: remoteInclude, ...comparison };
165
+ const rules = exclude === void 0 ? {} : { exclude };
166
+ return comparison.same && sameSyncExclude(localExclude, exclude) ? { kind: "same", include: remoteInclude, ...rules } : {
167
+ kind: "different",
168
+ include: remoteInclude,
169
+ ...comparison,
170
+ ...rules,
171
+ ...!sameSyncExclude(localExclude, exclude) ? { excludeChanged: true } : {}
172
+ };
150
173
  }
151
174
  var RemoteSelectionMismatchError = class extends Error {
152
175
  decision;
153
176
  setupName;
154
177
  localInclude;
155
178
  remoteInclude;
156
- constructor(setupName, localInclude, remoteInclude, configIdentity = JSON.stringify([setupName, normalizeSyncInclude(localInclude)])) {
179
+ constructor(setupName, localInclude, remoteInclude, configIdentity = JSON.stringify([setupName, normalizeSyncInclude(localInclude)]), localExclude, remoteExclude) {
157
180
  const local = normalizeSyncInclude(localInclude);
158
181
  const remote = normalizeSyncInclude(remoteInclude);
159
- super(formatRemoteSelectionMismatch(setupName, local, remote));
182
+ super(formatRemoteSelectionMismatch(setupName, local, remote, localExclude, remoteExclude));
160
183
  this.name = "RemoteSelectionMismatchError";
161
184
  this.setupName = setupName;
162
185
  this.localInclude = local;
@@ -165,21 +188,35 @@ var RemoteSelectionMismatchError = class extends Error {
165
188
  setupName,
166
189
  configIdentity,
167
190
  localInclude: [...local],
168
- remoteInclude: [...remote]
191
+ remoteInclude: [...remote],
192
+ ...localExclude === void 0 ? {} : { localExclude: normalizeSyncExclude(localExclude) },
193
+ ...remoteExclude === void 0 ? {} : { remoteExclude: normalizeSyncExclude(remoteExclude) }
169
194
  };
170
195
  }
171
196
  };
172
- function remoteSelectionMismatch(config, remoteInclude, configIdentity) {
173
- return new RemoteSelectionMismatchError(config.setupName, config.include, remoteInclude, configIdentity);
197
+ function remoteSelectionMismatch(config, remoteInclude, configIdentity, remoteExclude) {
198
+ return new RemoteSelectionMismatchError(
199
+ config.setupName,
200
+ config.include,
201
+ remoteInclude,
202
+ configIdentity,
203
+ config.exclude,
204
+ remoteExclude
205
+ );
174
206
  }
175
- function formatRemoteSelectionMismatch(setupName, localInclude, remoteInclude) {
207
+ function formatRemoteSelectionMismatch(setupName, localInclude, remoteInclude, localExclude, remoteExclude) {
176
208
  const comparison = compareSyncInclude(localInclude, remoteInclude);
177
209
  const lines = [
178
210
  `Synced content differs for sync setup \u201C${stripTerminalControls(setupName)}\u201D.`,
179
211
  `Remote-only: ${comparison.remoteOnly.join(", ") || "none"}`,
180
212
  `This-device-only: ${comparison.localOnly.join(", ") || "none"}`
181
213
  ];
182
- if (comparison.remoteOnly.length === 0 && comparison.localOnly.length === 0) {
214
+ if (!sameSyncExclude(localExclude, remoteExclude)) {
215
+ lines.push(
216
+ `Remote excluded paths: ${normalizeSyncExclude(remoteExclude).join(", ") || "none"}`,
217
+ `This device excluded paths: ${normalizeSyncExclude(localExclude).join(", ") || "none"}`
218
+ );
219
+ } else if (comparison.remoteOnly.length === 0 && comparison.localOnly.length === 0) {
183
220
  lines.push(
184
221
  "Only ordering differs.",
185
222
  `Remote order: ${remoteInclude.join(", ") || "none"}`,
@@ -238,23 +275,31 @@ function includeFromSelectionConfig(config) {
238
275
  ...config.syncSessions ? ["sessions"] : []
239
276
  ];
240
277
  }
278
+ function syncSessionsSelected(config) {
279
+ return includeFromSelectionConfig(config).includes("sessions") && !compileSyncExclude(config.exclude)("sessions");
280
+ }
241
281
  function isConfiguredSnapshotPath(relativePath, config, _legacyExtraFiles) {
242
- const normalized = toPosix(relativePath);
282
+ return configuredSnapshotPathMatcher(config)(relativePath);
283
+ }
284
+ function configuredSnapshotPathMatcher(config) {
243
285
  const selection = syncIncludeSelection(includeFromSelectionConfig(config));
244
- if (normalized.startsWith("sessions/")) return selection.sessions;
245
- const lower = normalized.toLowerCase();
246
- if (!normalized.includes("/")) {
247
- const builtIn = BUILT_IN_BY_LOWER.get(lower);
248
- if (builtIn) return selection.builtIns.includes(builtIn) && !TOP_LEVEL_DIRS.has(builtIn);
249
- }
250
- const topLevel = normalized.slice(0, normalized.indexOf("/"));
251
- if (selection.builtIns.includes(topLevel) && TOP_LEVEL_DIRS.has(topLevel)) {
252
- return true;
253
- }
254
- return selection.custom.some((candidate) => {
255
- const candidateLower = candidate.toLowerCase();
256
- return lower === candidateLower || lower.startsWith(`${candidateLower}/`);
257
- });
286
+ const excluded = compileSyncExclude(config.exclude);
287
+ return (relativePath) => {
288
+ const normalized = toPosix(relativePath);
289
+ if (excluded(normalized)) return false;
290
+ if (normalized.startsWith("sessions/")) return selection.sessions;
291
+ const lower = normalized.toLowerCase();
292
+ if (!normalized.includes("/")) {
293
+ const builtIn = BUILT_IN_BY_LOWER.get(lower);
294
+ if (builtIn) return selection.builtIns.includes(builtIn) && !TOP_LEVEL_DIRS.has(builtIn);
295
+ }
296
+ const topLevel = normalized.slice(0, normalized.indexOf("/"));
297
+ if (selection.builtIns.includes(topLevel) && TOP_LEVEL_DIRS.has(topLevel)) return true;
298
+ return selection.custom.some((candidate) => {
299
+ const key = candidate.toLowerCase();
300
+ return lower === key || lower.startsWith(`${key}/`);
301
+ });
302
+ };
258
303
  }
259
304
  function canonicalSnapshotPathForConfig(relativePath, includePaths) {
260
305
  const normalized = toPosix(relativePath);
@@ -299,7 +344,10 @@ export {
299
344
  normalizeSyncInclude,
300
345
  portableSnapshotSelection,
301
346
  snapshotSelectionInclude,
347
+ snapshotSelectionExclude,
302
348
  selectionForSnapshot,
349
+ sameSnapshotSelection,
350
+ validateSnapshotSelection,
303
351
  sameSyncInclude,
304
352
  compareSyncInclude,
305
353
  inspectRemoteSelection,
@@ -309,11 +357,13 @@ export {
309
357
  syncIncludeSelection,
310
358
  customIncludePathsByLower,
311
359
  includeFromSelectionConfig,
360
+ syncSessionsSelected,
312
361
  isConfiguredSnapshotPath,
362
+ configuredSnapshotPathMatcher,
313
363
  canonicalSnapshotPathForConfig,
314
364
  isPreservableUnmanagedSnapshotPath,
315
365
  isSafeCustomIncludePath,
316
366
  normalizeSyncFiles,
317
367
  normalizeExtraFiles
318
368
  };
319
- //# sourceMappingURL=chunk-KYTT7KV4.ts.map
369
+ //# sourceMappingURL=chunk-WUHRVSWI.ts.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/sync/sync-policy.ts"],
4
+ "sourcesContent": ["import path from \"node:path\";\nimport { isDeniedPath, toPosix } from \"../paths.js\";\nimport type { Snapshot, SnapshotSelection } from \"../snapshot/snapshot-types.js\";\nimport { compileSyncExclude, normalizeSyncExclude, sameSyncExclude } from \"./exclude-policy.js\";\n\nexport const BUILT_IN_SYNC_ROOTS = [\n \"settings.json\",\n \"keybindings.json\",\n \"models.json\",\n \"AGENTS.md\",\n \"APPEND_SYSTEM.md\",\n \"skills\",\n \"prompts\",\n \"themes\",\n \"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 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 selected?: string;\n children: Map<string, IncludePathNode>;\n}\n\nconst BUILT_IN_BY_LOWER = new Map<string, BuiltInSyncFile>(\n BUILT_IN_SYNC_ROOTS.map((fileName) => [fileName.toLowerCase(), fileName]),\n);\nconst TOP_LEVEL_FILE_PATHS = new Map<string, string>(\n BUILT_IN_SYNC_ROOTS.filter((fileName) => fileName.includes(\".\")).map((fileName) => [\n fileName.toLowerCase(),\n fileName,\n ]),\n);\nconst TOP_LEVEL_DIRS = new Set<string>(BUILT_IN_SYNC_ROOTS.filter((fileName) => !fileName.includes(\".\")));\nconst RESERVED_TOP_LEVEL_NAMES = new Set<string>([...BUILT_IN_BY_LOWER.keys(), \"sessions\"]);\n\nexport function normalizeSyncInclude(value: unknown): string[] {\n if (!Array.isArray(value)) {\n throw new Error(\"Invalid pi-sync settings: sync.include must be an array.\");\n }\n if (value.length > MAX_SYNC_INCLUDE_ITEMS) {\n throw new Error(`Invalid pi-sync settings: sync.include has too many items; limit: ${MAX_SYNC_INCLUDE_ITEMS}.`);\n }\n const result: string[] = [];\n const seen = new Set<string>();\n const pathRoot: IncludePathNode = { children: new Map() };\n let totalBytes = 0;\n for (const item of value) {\n if (typeof item !== \"string\") {\n throw new Error(\"Invalid pi-sync settings: sync.include items must be strings.\");\n }\n const itemBytes = Buffer.byteLength(item, \"utf8\");\n if (itemBytes > MAX_SYNC_INCLUDE_PATH_BYTES) {\n throw new Error(\n `Invalid pi-sync settings: sync.include item is too long; limit: ${MAX_SYNC_INCLUDE_PATH_BYTES} bytes.`,\n );\n }\n totalBytes += itemBytes;\n if (totalBytes > MAX_SYNC_INCLUDE_TOTAL_BYTES) {\n throw new Error(\n `Invalid pi-sync settings: sync.include is too large; limit: ${MAX_SYNC_INCLUDE_TOTAL_BYTES} bytes.`,\n );\n }\n const trimmed = item.trim();\n const builtIn = BUILT_IN_BY_LOWER.get(trimmed.toLowerCase());\n const normalized = builtIn ?? (trimmed.toLowerCase() === \"sessions\" ? \"sessions\" : trimmed);\n if (!builtIn && normalized !== \"sessions\") validateAgentRelativeInclude(normalized);\n const identity = normalized.toLowerCase();\n if (seen.has(identity)) {\n throw new Error(`Invalid pi-sync settings: duplicate sync.include item: ${item}`);\n }\n addIncludePath(pathRoot, identity, item);\n seen.add(identity);\n result.push(normalized);\n }\n return result;\n}\n\nfunction addIncludePath(root: IncludePathNode, identity: string, source: string) {\n let node = root;\n for (const segment of identity.split(\"/\")) {\n if (node.selected !== undefined) throwOverlappingInclude(source);\n let child = node.children.get(segment);\n if (!child) {\n child = { children: new Map() };\n node.children.set(segment, child);\n }\n node = child;\n }\n if (node.children.size > 0) throwOverlappingInclude(source);\n node.selected = identity;\n}\n\nfunction throwOverlappingInclude(item: string): never {\n throw new Error(`Invalid pi-sync settings: overlapping sync.include items are ambiguous: ${item}`);\n}\n\nfunction validateAgentRelativeInclude(value: string) {\n const normalized = toPosix(value);\n const topLevel = normalized.split(\"/\")[0]?.toLowerCase();\n if (\n !normalized ||\n normalized === \".\" ||\n normalized === \"..\" ||\n normalized.startsWith(\"../\") ||\n path.posix.isAbsolute(normalized) ||\n normalized.includes(\"\\\\\") ||\n path.posix.normalize(normalized) !== normalized ||\n // biome-ignore lint/suspicious/noControlCharactersInRegex: Include paths cannot contain controls.\n /[\\u0000-\\u001f\\u007f-\\u009f]/u.test(normalized)\n ) {\n throw new Error(`Invalid pi-sync settings: sync.include item must be a safe agent-relative path: ${value}`);\n }\n if (isDeniedPath(normalized)) {\n throw new Error(`Invalid pi-sync settings: ${value} cannot be synced.`);\n }\n if (topLevel && RESERVED_TOP_LEVEL_NAMES.has(topLevel)) {\n throw new Error(\n `Invalid pi-sync settings: use the canonical ${topLevel} root instead of a nested sync.include path.`,\n );\n }\n}\n\nexport function portableSnapshotSelection(value: unknown): SnapshotSelection {\n const selection = value as Partial<SnapshotSelection> | null;\n if (\n !selection ||\n typeof selection !== \"object\" ||\n Array.isArray(selection) ||\n (selection.version !== 1 && selection.version !== 2) ||\n !Object.hasOwn(selection, \"include\") ||\n (selection.version === 2 && !Object.hasOwn(selection, \"exclude\")) ||\n Object.keys(selection).some(\n (key) => key !== \"version\" && key !== \"include\" && !(selection.version === 2 && key === \"exclude\"),\n )\n )\n throw new Error(\"Invalid snapshot selection policy.\");\n const include = normalizeSyncInclude(selection.include);\n if (selection.version === 1) return { version: 1, include };\n if (!Array.isArray(selection.exclude)) throw new Error(\"Invalid snapshot exclude policy.\");\n return { version: 2, include, exclude: normalizeSyncExclude(selection.exclude) };\n}\n\nexport function snapshotSelectionInclude(snapshot: Pick<Snapshot, \"selection\">) {\n return snapshot.selection === undefined ? undefined : portableSnapshotSelection(snapshot.selection).include;\n}\n\nexport function snapshotSelectionExclude(snapshot: Pick<Snapshot, \"selection\">) {\n return snapshot.selection === undefined ? undefined : portableSnapshotSelection(snapshot.selection).exclude;\n}\n\nexport function selectionForSnapshot(include: unknown, exclude?: unknown): SnapshotSelection {\n const normalized = normalizeSyncInclude(include);\n return exclude === undefined\n ? { version: 1, include: normalized }\n : { version: 2, include: normalized, exclude: normalizeSyncExclude(exclude) };\n}\n\n/** Metadata equality, not policy compatibility: bind the whole projection to its immutable image. */\nexport function sameSnapshotSelection(left: SnapshotSelection | undefined, right: SnapshotSelection | undefined) {\n return (\n JSON.stringify(left === undefined ? null : portableSnapshotSelection(left)) ===\n JSON.stringify(right === undefined ? null : portableSnapshotSelection(right))\n );\n}\n\nexport function validateSnapshotSelection(snapshot: Pick<Snapshot, \"version\" | \"selection\">) {\n const selection = snapshot.selection === undefined ? undefined : portableSnapshotSelection(snapshot.selection);\n if ((snapshot.version === 4) !== (selection?.version === 2))\n throw new Error(\"Exclude policy requires snapshot version 4 and selection version 2.\");\n}\n\nexport function sameSyncInclude(left: unknown, right: unknown) {\n const normalizedLeft = normalizeSyncInclude(left);\n const normalizedRight = normalizeSyncInclude(right);\n return (\n normalizedLeft.length === normalizedRight.length &&\n normalizedLeft.every((item, index) => item === normalizedRight[index])\n );\n}\n\nexport function compareSyncInclude(local: unknown, remote: unknown) {\n const localInclude = normalizeSyncInclude(local);\n const remoteInclude = normalizeSyncInclude(remote);\n const localSet = new Set(localInclude);\n const remoteSet = new Set(remoteInclude);\n return {\n same: sameSyncInclude(localInclude, remoteInclude),\n remoteOnly: remoteInclude.filter((item) => !localSet.has(item)),\n localOnly: localInclude.filter((item) => !remoteSet.has(item)),\n };\n}\n\nexport type RemoteSelectionState =\n | { kind: \"legacy\"; discovered: string[] }\n | { kind: \"same\"; include: string[]; exclude?: string[] }\n | {\n kind: \"different\";\n include: string[];\n exclude?: string[];\n remoteOnly: string[];\n localOnly: string[];\n excludeChanged?: boolean;\n };\n\nexport function inspectRemoteSelection(\n localInclude: unknown,\n snapshot: Pick<Snapshot, \"selection\" | \"files\">,\n localExclude?: unknown,\n): RemoteSelectionState {\n const remoteInclude = snapshotSelectionInclude(snapshot);\n if (!remoteInclude) return { kind: \"legacy\", discovered: discoverLegacySnapshotInclude(snapshot) };\n const exclude = snapshotSelectionExclude(snapshot);\n const comparison = compareSyncInclude(localInclude, remoteInclude);\n const rules = exclude === undefined ? {} : { exclude };\n return comparison.same && sameSyncExclude(localExclude, exclude)\n ? { kind: \"same\", include: remoteInclude, ...rules }\n : {\n kind: \"different\",\n include: remoteInclude,\n ...comparison,\n ...rules,\n ...(!sameSyncExclude(localExclude, exclude) ? { excludeChanged: true } : {}),\n };\n}\n\nexport interface RemoteSelectionDecision {\n setupName: string;\n configIdentity: string;\n localInclude: readonly string[];\n remoteInclude: readonly string[];\n localExclude?: readonly string[];\n remoteExclude?: readonly string[];\n}\n\nexport class RemoteSelectionMismatchError extends Error {\n readonly decision: RemoteSelectionDecision;\n readonly setupName: string;\n readonly localInclude: string[];\n readonly remoteInclude: string[];\n\n constructor(\n setupName: string,\n localInclude: unknown,\n remoteInclude: unknown,\n configIdentity = JSON.stringify([setupName, normalizeSyncInclude(localInclude)]),\n localExclude?: string[],\n remoteExclude?: string[],\n ) {\n const local = normalizeSyncInclude(localInclude);\n const remote = normalizeSyncInclude(remoteInclude);\n super(formatRemoteSelectionMismatch(setupName, local, remote, localExclude, remoteExclude));\n this.name = \"RemoteSelectionMismatchError\";\n this.setupName = setupName;\n this.localInclude = local;\n this.remoteInclude = remote;\n this.decision = {\n setupName,\n configIdentity,\n localInclude: [...local],\n remoteInclude: [...remote],\n ...(localExclude === undefined ? {} : { localExclude: normalizeSyncExclude(localExclude) }),\n ...(remoteExclude === undefined ? {} : { remoteExclude: normalizeSyncExclude(remoteExclude) }),\n };\n }\n}\n\nexport function remoteSelectionMismatch(\n config: { setupName: string; include: unknown; exclude?: string[] },\n remoteInclude: unknown,\n configIdentity?: string,\n remoteExclude?: string[],\n) {\n return new RemoteSelectionMismatchError(\n config.setupName,\n config.include,\n remoteInclude,\n configIdentity,\n config.exclude,\n remoteExclude,\n );\n}\n\nexport function formatRemoteSelectionMismatch(\n setupName: string,\n localInclude: readonly string[],\n remoteInclude: readonly string[],\n localExclude?: readonly string[],\n remoteExclude?: readonly string[],\n) {\n const comparison = compareSyncInclude(localInclude, remoteInclude);\n const lines = [\n `Synced content differs for sync setup \u201C${stripTerminalControls(setupName)}\u201D.`,\n `Remote-only: ${comparison.remoteOnly.join(\", \") || \"none\"}`,\n `This-device-only: ${comparison.localOnly.join(\", \") || \"none\"}`,\n ];\n if (!sameSyncExclude(localExclude, remoteExclude)) {\n lines.push(\n `Remote excluded paths: ${normalizeSyncExclude(remoteExclude).join(\", \") || \"none\"}`,\n `This device excluded paths: ${normalizeSyncExclude(localExclude).join(\", \") || \"none\"}`,\n );\n } else if (comparison.remoteOnly.length === 0 && comparison.localOnly.length === 0) {\n lines.push(\n \"Only ordering differs.\",\n `Remote order: ${remoteInclude.join(\", \") || \"none\"}`,\n `This device order: ${localInclude.join(\", \") || \"none\"}`,\n );\n }\n lines.push(\"Run /sync in TUI to review both content lists and choose what happens next.\");\n return lines.join(\"\\n\");\n}\n\nfunction stripTerminalControls(value: string) {\n // biome-ignore lint/suspicious/noControlCharactersInRegex: Escape untrusted terminal controls.\n return value.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/gu, \"?\");\n}\n\nexport function discoverLegacySnapshotInclude(snapshot: Pick<Snapshot, \"files\">) {\n const builtIns = new Set<BuiltInSyncFile>();\n const custom = new Set<string>();\n let sessions = false;\n for (const file of snapshot.files) {\n const normalized = toPosix(file.path);\n if (\n !normalized ||\n file.path.includes(\"\\\\\") ||\n normalized.length > 4096 ||\n normalized.startsWith(\"../\") ||\n path.posix.isAbsolute(normalized) ||\n path.posix.normalize(normalized) !== normalized ||\n // biome-ignore lint/suspicious/noControlCharactersInRegex: Ignore unsafe legacy paths.\n /[\\u0000-\\u001f\\u007f-\\u009f]/u.test(normalized) ||\n isDeniedPath(normalized)\n ) {\n continue;\n }\n const [topLevel, ...rest] = normalized.split(\"/\");\n if (!topLevel) continue;\n if (topLevel === \"sessions\" && rest.length > 0) {\n sessions = true;\n continue;\n }\n const builtIn = BUILT_IN_BY_LOWER.get(topLevel.toLowerCase());\n if (\n builtIn &&\n ((TOP_LEVEL_DIRS.has(builtIn) && rest.length > 0) || (!TOP_LEVEL_DIRS.has(builtIn) && rest.length === 0))\n ) {\n builtIns.add(builtIn);\n continue;\n }\n if (isSafeCustomIncludePath(topLevel)) custom.add(topLevel);\n }\n return [\n ...BUILT_IN_SYNC_ROOTS.filter((item) => builtIns.has(item)),\n ...[...custom].sort((left, right) => left.localeCompare(right)),\n ...(sessions ? [\"sessions\"] : []),\n ];\n}\n\nexport function syncIncludeSelection(value: unknown) {\n const include = normalizeSyncInclude(value);\n const builtIns = include.filter((item): item is BuiltInSyncFile => BUILT_IN_BY_LOWER.has(item.toLowerCase()));\n const custom = include.filter((item) => item !== \"sessions\" && !BUILT_IN_BY_LOWER.has(item.toLowerCase()));\n return { include, builtIns, custom, sessions: include.includes(\"sessions\") };\n}\n\nexport function customIncludePathsByLower(value: unknown) {\n return new Map(syncIncludeSelection(value).custom.map((relativePath) => [relativePath.toLowerCase(), relativePath]));\n}\n\nexport interface SyncSelectionConfig {\n include?: unknown;\n exclude?: unknown;\n syncFiles?: unknown;\n syncSessions?: boolean;\n extraFiles?: unknown;\n}\n\nexport function includeFromSelectionConfig(config: SyncSelectionConfig) {\n if (config.include !== undefined) return normalizeSyncInclude(config.include);\n return [\n ...normalizeSyncFiles(config.syncFiles),\n ...normalizeExtraFiles(config.extraFiles),\n ...(config.syncSessions ? [\"sessions\"] : []),\n ];\n}\n\nexport function syncSessionsSelected(config: SyncSelectionConfig) {\n return includeFromSelectionConfig(config).includes(\"sessions\") && !compileSyncExclude(config.exclude)(\"sessions\");\n}\n\nexport function isConfiguredSnapshotPath(\n relativePath: string,\n config: SyncSelectionConfig,\n _legacyExtraFiles?: Set<string>,\n) {\n return configuredSnapshotPathMatcher(config)(relativePath);\n}\n\nexport function configuredSnapshotPathMatcher(config: SyncSelectionConfig) {\n const selection = syncIncludeSelection(includeFromSelectionConfig(config));\n const excluded = compileSyncExclude(config.exclude);\n return (relativePath: string) => {\n const normalized = toPosix(relativePath);\n if (excluded(normalized)) return false;\n if (normalized.startsWith(\"sessions/\")) return selection.sessions;\n const lower = normalized.toLowerCase();\n if (!normalized.includes(\"/\")) {\n const builtIn = BUILT_IN_BY_LOWER.get(lower);\n if (builtIn) return selection.builtIns.includes(builtIn) && !TOP_LEVEL_DIRS.has(builtIn);\n }\n const topLevel = normalized.slice(0, normalized.indexOf(\"/\"));\n if (selection.builtIns.includes(topLevel as BuiltInSyncFile) && TOP_LEVEL_DIRS.has(topLevel)) return true;\n return selection.custom.some((candidate) => {\n const key = candidate.toLowerCase();\n return lower === key || lower.startsWith(`${key}/`);\n });\n };\n}\n\nexport function canonicalSnapshotPathForConfig(relativePath: string, includePaths: Map<string, string>) {\n const normalized = toPosix(relativePath);\n const lower = normalized.toLowerCase();\n return TOP_LEVEL_FILE_PATHS.get(lower) ?? includePaths.get(lower) ?? normalized;\n}\n\nexport function isPreservableUnmanagedSnapshotPath(relativePath: string) {\n const normalized = toPosix(relativePath);\n if (!normalized || isDeniedPath(normalized)) return false;\n if (normalized.startsWith(\"sessions/\")) return normalized.endsWith(\".jsonl\");\n if (!normalized.includes(\"/\")) {\n const lower = normalized.toLowerCase();\n return TOP_LEVEL_FILE_PATHS.has(lower) || !RESERVED_TOP_LEVEL_NAMES.has(lower);\n }\n return true;\n}\n\nexport function isSafeCustomIncludePath(relativePath: string) {\n try {\n validateAgentRelativeInclude(relativePath);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function isBuiltInTopLevelFile(fileName: string) {\n return 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 if (value === undefined) return [...DEFAULT_SYNC_INCLUDE];\n if (Array.isArray(value)) {\n return normalizeSyncInclude(value).filter((item): item is BuiltInSyncFile =>\n BUILT_IN_BY_LOWER.has(item.toLowerCase()),\n );\n }\n throw 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 if (!Array.isArray(value)) return [];\n return value.filter((item): item is string => typeof item === \"string\" && isSafeCustomIncludePath(item));\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;AAKV,IAAM,sBAAsB;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,uBAAuB,CAAC,GAAG,mBAAmB;AAE3D,IAAM,yBAAyB;AAC/B,IAAM,8BAA8B;AACpC,IAAM,+BAA+B,MAAM;AAO3C,IAAM,oBAAoB,IAAI;AAAA,EAC5B,oBAAoB,IAAI,CAAC,aAAa,CAAC,SAAS,YAAY,GAAG,QAAQ,CAAC;AAC1E;AACA,IAAM,uBAAuB,IAAI;AAAA,EAC/B,oBAAoB,OAAO,CAAC,aAAa,SAAS,SAAS,GAAG,CAAC,EAAE,IAAI,CAAC,aAAa;AAAA,IACjF,SAAS,YAAY;AAAA,IACrB;AAAA,EACF,CAAC;AACH;AACA,IAAM,iBAAiB,IAAI,IAAY,oBAAoB,OAAO,CAAC,aAAa,CAAC,SAAS,SAAS,GAAG,CAAC,CAAC;AACxG,IAAM,2BAA2B,oBAAI,IAA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A,MAAO,CAAC,SACzC,kBAAkB,IAAI,KAAK,YAAY,CAAC;AAAA,IAC1C;AAAA,EACF;AACA,QAAM,IAAI,MAAM,sDAAsD;AACxE;AAGO,SAAS,oBAAoB,OAAgB;AAClD,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO,CAAC;AACnC,SAAO,MAAM,OAAO,CAAC,SAAyB,OAAO,SAAS,YAAY,wBAAwB,IAAI,CAAC;AACzG;",
6
+ "names": []
7
+ }
@@ -18,8 +18,12 @@ import {
18
18
  normalizeGitRemoteIdentity
19
19
  } from "./chunk-T2SJD3N7.ts";
20
20
  import {
21
- normalizeSyncInclude
22
- } from "./chunk-KYTT7KV4.ts";
21
+ normalizeSyncInclude,
22
+ syncSessionsSelected
23
+ } from "./chunk-WUHRVSWI.ts";
24
+ import {
25
+ normalizeSyncExclude
26
+ } from "./chunk-3JTZF7Z5.ts";
23
27
 
24
28
  // src/settings/config.ts
25
29
  import { createHash } from "node:crypto";
@@ -566,9 +570,9 @@ function normalizeOnSwitch(value) {
566
570
  );
567
571
  }
568
572
  function validateSettingsDocument(value) {
569
- if (value.version !== 3 && value.version !== 4 && value.version !== 5) {
573
+ if (value.version !== 3 && value.version !== 4 && value.version !== 5 && value.version !== 6) {
570
574
  throw new Error(
571
- `Unsupported pi-sync settings: version 3 or 4 or 5 is required. Keep the existing ${path2.basename(localConfigPath())} for recovery and use a compatible pi-sync client or review a separate supported setup; do not downgrade portable field policies. pi-sync will not migrate or overwrite unsupported settings.`
575
+ `Unsupported pi-sync settings: version 3, 4, 5 or 6 is required. Keep the existing ${path2.basename(localConfigPath())} for recovery and use a compatible pi-sync client or review a separate supported setup; do not downgrade portable field policies. pi-sync will not migrate or overwrite unsupported settings.`
572
576
  );
573
577
  }
574
578
  rejectLegacyFields(
@@ -633,12 +637,14 @@ function validateSettingsDocument(value) {
633
637
  }
634
638
  for (const setup of Object.values(syncSetups)) {
635
639
  const policy = setup.sync;
636
- if (policy.localFields !== void 0 && value.version !== 4 && value.version !== 5)
640
+ if (policy.localFields !== void 0 && value.version !== 4 && value.version !== 5 && value.version !== 6)
637
641
  throw new Error("localFields requires explicit settings version 4; older binaries must refuse portable state.");
638
642
  }
639
643
  for (const setup of Object.values(syncSetups)) {
640
644
  const policy = setup.sync;
641
- if ((policy.mergeContent || policy.partialSync) && value.version !== 5)
645
+ if (policy.exclude !== void 0 && value.version !== 6)
646
+ throw new Error("sync.exclude requires explicit settings version 6; older clients must refuse excluded content.");
647
+ if ((policy.mergeContent || policy.partialSync) && value.version !== 5 && value.version !== 6)
642
648
  throw new Error("Content/partial sync requires explicit settings version 5.");
643
649
  }
644
650
  validateUniqueRemoteSyncSetups(syncSetups, storageConnections);
@@ -741,6 +747,7 @@ function validateSyncSetup(name, value, connections) {
741
747
  throw new Error(`Invalid pi-sync settings: sync setup \u201C${name}\u201D is missing sync.include.`);
742
748
  }
743
749
  const include = normalizeSyncInclude(sync.include);
750
+ normalizeSyncExclude(sync.exclude);
744
751
  const localFields = normalizeLocalFields(sync.localFields);
745
752
  if (localFields.length > 0 && !include.includes("settings.json"))
746
753
  throw new Error("Nonempty localFields requires settings.json in sync.include.");
@@ -995,6 +1002,7 @@ async function loadPartialConfig(setupName) {
995
1002
  setupName: config.setupName,
996
1003
  ...storageReviewFromConfig(config),
997
1004
  include: [...config.include],
1005
+ ...config.exclude === void 0 ? {} : { exclude: [...config.exclude] },
998
1006
  automatic: config.automatic,
999
1007
  automaticTransfer: config.automaticTransfer ?? false,
1000
1008
  agentMode: config.agentMode ?? false,
@@ -1027,7 +1035,8 @@ function syncConfigReviewIdentity(config) {
1027
1035
  config.mergeContent ?? false,
1028
1036
  config.partialSync ?? false,
1029
1037
  // Preserve existing Off identities and cached candidates across the upgrade.
1030
- ...config.continuous ? ["continuous"] : []
1038
+ ...config.continuous ? ["continuous"] : [],
1039
+ ...config.exclude === void 0 ? [] : ["exclude", normalizeSyncExclude(config.exclude).map((rule) => rule.toLowerCase())]
1031
1040
  ]);
1032
1041
  }
1033
1042
  function syncConfigReviewFingerprint(config) {
@@ -1054,6 +1063,7 @@ function resolveSyncConfig(setupName, setup, connectionName, connection, onSwitc
1054
1063
  storagePath,
1055
1064
  snapshotIdentity: namespace,
1056
1065
  include,
1066
+ ...setup.sync.exclude === void 0 ? {} : { exclude: normalizeSyncExclude(setup.sync.exclude) },
1057
1067
  automatic: setup.sync.automatic,
1058
1068
  automaticTransfer: setup.sync.automaticTransfer ?? false,
1059
1069
  agentMode: setup.sync.agentMode ?? false,
@@ -1122,7 +1132,7 @@ function sessionTokenWarnings(config) {
1122
1132
  ];
1123
1133
  }
1124
1134
  function syncSessionsWarnings(config) {
1125
- if (!config.include.includes("sessions")) return [];
1135
+ if (!syncSessionsSelected(config)) return [];
1126
1136
  return [
1127
1137
  "sessions: included; Pi session JSONL can contain prompts, tool output, file paths, images, and secrets. Sync sessions only to storage you trust."
1128
1138
  ];
@@ -1171,4 +1181,4 @@ export {
1171
1181
  isEnabled,
1172
1182
  isExplicitlyEnabled
1173
1183
  };
1174
- //# sourceMappingURL=chunk-OVBAW7KV.ts.map
1184
+ //# sourceMappingURL=chunk-XZ3ZTHKR.ts.map