@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
package/dist/index.ts.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/settings/config-errors.ts", "../src/sync/automatic-sync.ts", "../src/sync/startup-check.ts", "../src/sync/sync-loaders.ts", "../src/ui/startup-timings-entry.ts", "../src/sync-extension.ts"],
4
- "sourcesContent": ["export function isMissingConfigError(error: unknown) {\n return (\n error instanceof Error &&\n (error.message.startsWith(\"Missing pi-sync settings.\") || error.message === \"No sync setups are configured.\")\n );\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { setSyncSetupCompletions } from \"../commands/command.js\";\nimport type { CommandOptions } from \"../commands/command-types.js\";\nimport { loadConfig, loadPartialConfig } from \"../settings/config.js\";\nimport { isMissingConfigError } from \"../settings/config-errors.js\";\nimport { consumeLocalConfigMigrationNotice } from \"../settings/config-file.js\";\nimport { readLocalConfigObject } from \"../settings/settings-store.js\";\nimport type { AnySyncConfig } from \"../settings/settings-types.js\";\nimport { sessionDirFromContext, snapshotOptionsForContext } from \"../snapshot/session-paths.js\";\nimport { pendingTransactionEntries } from \"../snapshot/snapshot-transaction-directory.js\";\nimport { withLock } from \"../state/lock.js\";\nimport { stateDirectoryMigrationNotice } from \"../state/state-directory.js\";\nimport { ensureStateDir, readStateForConfig } from \"../state/sync-state-store.js\";\nimport { configureSyncStatus, setSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { captureMutationOwner } from \"./mutation-owner.js\";\nimport { throwIfAborted } from \"./signals.js\";\nimport { createStartupTimings, type StartupTimingPublisher } from \"./startup-timings.js\";\nimport { errorMessage } from \"./sync-errors.js\";\nimport type { SyncLoaders } from \"./sync-loaders.js\";\n\nconst AUTO_SYNC_OPTIONS: CommandOptions = {\n yes: true,\n force: false,\n stale: false,\n silent: true,\n reload: false,\n auto: true,\n args: [],\n};\n\nexport async function startSession(\n ctx: ExtensionContext,\n signal: AbortSignal,\n publish?: StartupTimingPublisher,\n): Promise<{ debug: boolean; config?: AnySyncConfig } | undefined> {\n const timings = createStartupTimings(publish);\n let debug = false;\n let outcome: \"completed\" | \"stopped\" = \"stopped\";\n try {\n throwIfAborted(signal);\n const stateNotice = stateDirectoryMigrationNotice();\n if (stateNotice && ctx.hasUI) ctx.ui.notify(stateNotice, \"warning\");\n // Recovery can restore managed files: finish it before Pi accepts user edits.\n // Unlike remote inspection, it must never be detached behind startup.\n const validateMutation = captureMutationOwner(ctx, signal);\n const currentFile = ctx.sessionManager.getSessionFile?.();\n await timings.measure(\"transaction recovery\", async () => {\n const pending = await pendingTransactionEntries();\n validateMutation();\n if (!pending.some((entry) => entry.isDirectory())) return;\n // Normal startup needs only the directory probe, not the recovery/snapshot graph.\n const { recoverSnapshotTransactionsOnStartup } = await import(\"../snapshot/snapshot-transaction.js\");\n validateMutation();\n await recoverSnapshotTransactionsOnStartup({\n signal,\n sessionDir: sessionDirFromContext(ctx),\n protectedTargets: currentFile ? [currentFile] : [],\n validateMutation,\n });\n });\n throwIfAborted(signal);\n try {\n const settings = await timings.measure(\"settings read\", () => readLocalConfigObject());\n throwIfAborted(signal);\n debug = settings?.debug ?? false;\n const names = settings ? Object.keys(settings.syncSetups).sort((left, right) => left.localeCompare(right)) : [];\n setSyncSetupCompletions(names);\n configureSyncStatus(ctx, settings?.showStatus ?? true);\n } catch {\n if (signal.aborted) return;\n setSyncSetupCompletions([]);\n }\n const migrationNotice = consumeLocalConfigMigrationNotice();\n if (migrationNotice && ctx.hasUI) ctx.ui.notify(migrationNotice, \"warning\");\n throwIfAborted(signal);\n if (!ctx.hasUI) return { debug };\n try {\n const config = await timings.measure(\"config resolution\", () => loadConfig());\n throwIfAborted(signal);\n configureSyncStatus(ctx, config.showStatus);\n outcome = \"completed\";\n return { debug, config };\n } catch (error) {\n throwIfAborted(signal);\n if (!isMissingConfigError(error)) {\n ctx.ui.notify(`pi-sync startup check skipped: ${safeTerminalText(errorMessage(error))}`, \"warning\");\n }\n }\n return { debug };\n } finally {\n timings.publish(ctx, debug, signal, \"local initialization\", outcome);\n }\n}\n\nexport async function autoPushSessions(ctx: ExtensionContext, signal: AbortSignal, loaders: SyncLoaders) {\n try {\n const partial = await loadPartialConfig();\n throwIfAborted(signal);\n if (!partial.automatic) return;\n if (!partial.include.includes(\"sessions\")) return;\n await ensureStateDir();\n throwIfAborted(signal);\n const config = await loadConfig();\n throwIfAborted(signal);\n if (!config.include.includes(\"sessions\")) return;\n const [operations, snapshotModule, syncStateModule] = await Promise.all([\n loaders.operations(),\n loaders.snapshot(),\n loaders.syncState(),\n ]);\n throwIfAborted(signal);\n await withLock(\"auto-session-push\", async () => {\n throwIfAborted(signal);\n const state = await readStateForConfig(config);\n throwIfAborted(signal);\n const local = await snapshotModule.createSnapshot(config.snapshotIdentity, {\n ...snapshotOptionsForContext(ctx, config),\n signal,\n });\n throwIfAborted(signal);\n if (!syncStateModule.hasLocalChanges(local, state, config)) return;\n await operations.push(ctx, { ...AUTO_SYNC_OPTIONS, signal }, { config, state, local });\n });\n } catch (error) {\n if (signal.aborted || isMissingConfigError(error)) return;\n setSyncStatus(ctx, undefined);\n ctx.ui.notify(`pi-sync session push skipped: ${errorMessage(error)}`, \"warning\");\n }\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { loadConfigForCheck, syncCheckConfigFingerprint } from \"../settings/config.js\";\nimport { isMissingConfigError } from \"../settings/config-errors.js\";\nimport type { AnySyncConfig } from \"../settings/settings-types.js\";\nimport { snapshotOptionsForContext } from \"../snapshot/session-paths.js\";\nimport { withLock } from \"../state/lock.js\";\nimport { withStateDirectoryAccess } from \"../state/state-directory.js\";\nimport { readStateForConfig, syncStateFingerprint } from \"../state/sync-state-store.js\";\nimport type { SyncAttentionController } from \"../ui/sync-attention.js\";\nimport { setSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { startupTransferEnabled } from \"./agent-policy.js\";\nimport { combineSignals, throwIfAborted } from \"./signals.js\";\nimport { createStartupTimings, type StartupTimingPublisher } from \"./startup-timings.js\";\nimport { errorMessage } from \"./sync-errors.js\";\nimport type { SyncLoaders } from \"./sync-loaders.js\";\n\n/** One owned task per extension session, never keyed by the shared headless UI. */\nexport function createStartupCheck(\n loaders: SyncLoaders,\n attention: SyncAttentionController,\n timeoutMs = 30_000,\n publish?: StartupTimingPublisher,\n) {\n let active:\n | {\n controller: AbortController;\n promise: Promise<void>;\n owner: ExtensionContext[\"sessionManager\"];\n transfer: boolean;\n }\n | undefined;\n\n let pending: { ctx: ExtensionContext; signal: AbortSignal; config: AnySyncConfig } | undefined;\n\n const controllerApi = {\n async interrupt(ctx: ExtensionContext) {\n const task = active;\n if (!task?.transfer || task.owner !== ctx.sessionManager) return;\n task.controller.abort(new DOMException(\"Agent became busy\", \"AbortError\"));\n await task.promise;\n },\n settled(ctx: ExtensionContext) {\n const queued = pending;\n if (!queued || queued.ctx.sessionManager !== ctx.sessionManager || queued.signal.aborted || !ctx.isIdle()) return;\n pending = undefined;\n controllerApi.start(ctx, queued.signal, queued.config);\n },\n start(ctx: ExtensionContext, sessionSignal: AbortSignal, initialConfig?: AnySyncConfig) {\n if (!ctx.hasUI || sessionSignal.aborted) return;\n if (initialConfig && startupTransferEnabled(initialConfig) && !ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: initialConfig };\n return;\n }\n if (active) throw new Error(\"Previous startup check has not been drained.\");\n const timings = createStartupTimings(publish);\n const controller = new AbortController();\n const signal = combineSignals(sessionSignal, controller.signal);\n const task = {\n controller,\n owner: ctx.sessionManager,\n promise: Promise.resolve(),\n transfer: Boolean(initialConfig && startupTransferEnabled(initialConfig)),\n };\n active = task;\n const isCurrent = () => !sessionSignal.aborted && active === task && task.owner === ctx.sessionManager;\n const timer = setTimeout(\n () => controller.abort(new DOMException(\"Startup check timed out\", \"TimeoutError\")),\n timeoutMs,\n );\n timer.unref();\n let config: AnySyncConfig | undefined;\n let checking = false;\n let stopped = false;\n // Handle every detached rejection here; Pi's awaited event runner cannot catch it.\n task.promise = Promise.resolve()\n .then(async () => {\n try {\n throwIfAborted(signal);\n config = initialConfig ?? (await loadConfigForCheck());\n task.transfer = startupTransferEnabled(config);\n throwIfAborted(signal);\n if (!config.automatic && !startupTransferEnabled(config)) return;\n const captured = config;\n const identity = syncCheckConfigFingerprint(captured);\n checking = true;\n setSyncStatus(ctx, \"sync ...\", { activity: \"checking\" });\n const { inspectSync } = await timings.measure(\"inspection import\", () => loaders.inspection());\n throwIfAborted(signal);\n const currentConfig = await loadConfigForCheck();\n throwIfAborted(signal);\n if (syncCheckConfigFingerprint(currentConfig) !== identity) return;\n // Lock order: state migration guard \u2192 sync operation \u2192 backend cache.\n // Read heads may write only private cache data. Never call doctor/syncBoth.\n const inspection = await timings.measure(\"inspection and guards\", () =>\n withStateDirectoryAccess(() => {\n throwIfAborted(signal);\n return withLock(\"startup-check\", () => {\n throwIfAborted(signal);\n return inspectSync(captured, snapshotOptionsForContext(ctx, captured), signal, undefined, timings);\n });\n }),\n );\n throwIfAborted(signal);\n const latest = await loadConfigForCheck();\n throwIfAborted(signal);\n if (syncCheckConfigFingerprint(latest) !== identity) return;\n const state = await withStateDirectoryAccess(() => readStateForConfig(latest));\n throwIfAborted(signal);\n if (syncStateFingerprint(state) !== inspection.stateIdentity || !isCurrent()) return;\n attention.observe({\n setupName: captured.setupName,\n configIdentity: identity,\n checkedAt: new Date().toISOString(),\n inspection,\n automaticTransfer: startupTransferEnabled(captured),\n });\n if (\n startupTransferEnabled(captured) &&\n !inspection.firstSync &&\n inspection.head &&\n inspection.selectionState?.kind === \"same\"\n ) {\n const [operations, { withAgentSyncLock }] = await timings.measure(\"operations import\", () =>\n Promise.all([loaders.operations(), import(\"./agent-sync.js\")]),\n );\n throwIfAborted(signal);\n if (!isCurrent()) return;\n if (!ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: captured };\n return;\n }\n await timings.measure(\"automatic transfer\", () =>\n withStateDirectoryAccess(() =>\n withAgentSyncLock(\n ctx,\n {\n args: [],\n yes: true,\n force: false,\n stale: false,\n silent: true,\n reload: false,\n auto: true,\n signal,\n startupTimings: timings,\n onCommit: () => attention.clearObservation(),\n },\n (options) => operations.syncBoth(ctx, options),\n ),\n ),\n );\n throwIfAborted(signal);\n if (!isCurrent()) return;\n attention.clearObservation();\n return;\n }\n attention.observe({\n setupName: captured.setupName,\n configIdentity: identity,\n checkedAt: new Date().toISOString(),\n inspection,\n automaticTransfer: startupTransferEnabled(captured),\n });\n if (ctx.mode === \"rpc\") attention.notifyObservation(ctx);\n } catch (error) {\n stopped = true;\n if (!isCurrent() || sessionSignal.aborted || isMissingConfigError(error)) return;\n if (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\") return;\n // A settings edit invalidates failures as well as successful observations.\n if (config) {\n const latest = await loadConfigForCheck().catch(() => undefined);\n if (!isCurrent() || (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\")) return;\n if (!latest || syncCheckConfigFingerprint(latest) !== syncCheckConfigFingerprint(config)) return;\n }\n ctx.ui.notify(\n config && startupTransferEnabled(config)\n ? `pi-sync automatic transfer stopped: ${safeTerminalText(errorMessage(error))}. Run /sync to review or reconcile retained recovery evidence. No resources were reloaded.`\n : `pi-sync startup check skipped: ${safeTerminalText(errorMessage(error))}. Run /sync status to retry. No startup transfer was performed.`,\n \"warning\",\n );\n } finally {\n clearTimeout(timer);\n if (isCurrent() && checking) {\n if (!signal.aborted || controller.signal.reason?.name === \"TimeoutError\") {\n const latest = await loadConfigForCheck().catch(() => undefined);\n if (isCurrent()) {\n if (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\")\n setSyncStatus(ctx, undefined);\n else if (\n config &&\n latest &&\n syncCheckConfigFingerprint(latest) === syncCheckConfigFingerprint(config)\n )\n await attention.publish(ctx, sessionSignal);\n else attention.reset(ctx);\n }\n } else setSyncStatus(ctx, undefined);\n }\n if (isCurrent()) {\n timings.publish(\n ctx,\n config?.debug ?? false,\n sessionSignal,\n \"background startup\",\n signal.aborted || stopped ? \"stopped\" : \"completed\",\n );\n }\n if (active === task) active = undefined;\n }\n })\n .catch(() => {\n // UI teardown can itself throw. No unhandled rejection or retained timer.\n clearTimeout(timer);\n if (active === task) active = undefined;\n });\n },\n async stop() {\n pending = undefined;\n const task = active;\n if (!task) return;\n task.controller.abort(new DOMException(\"Startup check cancelled\", \"AbortError\"));\n // Drain the actual work, including child/ref cleanup, before foreground guards.\n await task.promise;\n },\n };\n return controllerApi;\n}\n", "type SetupSwitchModule = Pick<typeof import(\"./setup-switch.js\"), \"useSyncSetup\">;\ntype SnapshotModule = Pick<typeof import(\"../snapshot/snapshot.js\"), \"createSnapshot\">;\ntype SyncStateModule = Pick<typeof import(\"./sync-state.js\"), \"hasLocalChanges\">;\ntype SyncOperations = typeof import(\"./sync-operations.js\");\ntype CommandHandlerModule = Pick<typeof import(\"../commands/command-handler.js\"), \"handleCommand\">;\n\ntype SyncInspectionModule = Pick<typeof import(\"./sync-inspection.js\"), \"inspectSync\">;\n\nexport interface SyncDependencies {\n loadCommandHandler(): Promise<CommandHandlerModule>;\n loadSyncInspection(): Promise<SyncInspectionModule>;\n loadSetupSwitch(): Promise<SetupSwitchModule>;\n loadSnapshot(): Promise<SnapshotModule>;\n loadSyncState(): Promise<SyncStateModule>;\n loadSyncOperations(): Promise<SyncOperations>;\n}\n\nexport interface SyncLoaders {\n commands(): Promise<CommandHandlerModule>;\n inspection(): Promise<SyncInspectionModule>;\n setupSwitch(): Promise<SetupSwitchModule>;\n snapshot(): Promise<SnapshotModule>;\n syncState(): Promise<SyncStateModule>;\n operations(): Promise<SyncOperations>;\n}\n\nexport function createSyncLoaders(dependencies: Partial<SyncDependencies>): SyncLoaders {\n const loaders: SyncLoaders = {\n commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import(\"../commands/command-handler.js\"))),\n inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import(\"./sync-inspection.js\"))),\n setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import(\"./setup-switch.js\"))),\n snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import(\"../snapshot/snapshot.js\"))),\n syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import(\"./sync-state.js\"))),\n operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import(\"./sync-operations.js\"))),\n };\n return loaders;\n}\n\nfunction cachedModuleLoader<Module>(load: () => Promise<Module>): () => Promise<Module> {\n let pending: Promise<Module> | undefined;\n return () => {\n if (!pending) {\n pending = load().catch((error) => {\n pending = undefined;\n throw error;\n });\n }\n return pending;\n };\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport type { StartupTimingPublisher } from \"../sync/startup-timings.js\";\nimport { safeTerminalText } from \"./terminal-text.js\";\n\nexport const STARTUP_TIMING_ENTRY = \"pi-sync-startup-timings\";\n\nexport interface StartupTimingEntry {\n version: 1;\n report: string;\n}\n\nexport function registerStartupTimings(pi: ExtensionAPI): StartupTimingPublisher {\n pi.registerEntryRenderer<StartupTimingEntry>(STARTUP_TIMING_ENTRY, (entry, _options, theme) => {\n const data = entry.data;\n if (data?.version !== 1 || typeof data.report !== \"string\") return undefined;\n const text = new Text(\n data.report\n .split(\"\\n\")\n .map((line, index) => theme.fg(index === 0 ? \"accent\" : \"muted\", safeTerminalText(line)))\n .join(\"\\n\"),\n 0,\n 0,\n );\n return {\n render: (width) => (width > 0 ? text.render(width).map((line) => truncateToWidth(line, width)) : []),\n invalidate: () => text.invalidate(),\n };\n });\n return (ctx, report) => {\n // Pi coalesces consecutive info notifications, including the final /reload notice.\n // Custom entries remain visible without adding messages to model context.\n if (ctx.mode === \"tui\") pi.appendEntry<StartupTimingEntry>(STARTUP_TIMING_ENTRY, { version: 1, report });\n else ctx.ui.notify(report, \"info\");\n };\n}\n", "import type { ExtensionAPI, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { completeSyncArguments, splitArgs } from \"./commands/command.js\";\nimport type { AnySyncConfig } from \"./settings/settings-types.js\";\nimport { withStateDirectoryAccess } from \"./state/state-directory.js\";\nimport { startupTransferEnabled } from \"./sync/agent-policy.js\";\nimport { autoPushSessions, startSession } from \"./sync/automatic-sync.js\";\nimport { combineSignals } from \"./sync/signals.js\";\nimport { createStartupCheck } from \"./sync/startup-check.js\";\nimport { errorMessage } from \"./sync/sync-errors.js\";\nimport { createSyncLoaders, type SyncDependencies } from \"./sync/sync-loaders.js\";\nimport { registerStartupTimings } from \"./ui/startup-timings-entry.js\";\nimport { createSyncAttentionController } from \"./ui/sync-attention.js\";\nimport { createSyncStatusPublisher, setSyncStatus } from \"./ui/sync-status.js\";\nimport { safeTerminalText } from \"./ui/terminal-text.js\";\n\nexport default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDependencies> = {}) {\n const loaders = createSyncLoaders(dependencies);\n const attention = createSyncAttentionController();\n const status = createSyncStatusPublisher(pi.events);\n const publishTimings = registerStartupTimings(pi);\n const check = createStartupCheck(loaders, attention, 30_000, publishTimings);\n let sessionAbort = new AbortController();\n let shutdownAbort: AbortController | undefined;\n let initialization = Promise.resolve<AnySyncConfig | false | undefined>(undefined);\n let continuous: ReturnType<typeof import(\"./sync/continuous-sync.js\")[\"createContinuousSync\"]> | undefined;\n let owner: ExtensionContext[\"sessionManager\"] | undefined;\n let continuousPossible = false;\n let startupDebug = false;\n const foreground = new Map<ExtensionContext[\"sessionManager\"], number>();\n async function resumeContinuous(ctx: ExtensionContext, signal: AbortSignal, retry?: { setup?: string }) {\n const isCurrent = () => !signal.aborted && !foreground.has(ctx.sessionManager) && owner === ctx.sessionManager;\n if (!isCurrent() || !ctx.hasUI) return;\n try {\n const { loadConfigForCheck } = await import(\"./settings/config.js\");\n if (!isCurrent()) return;\n const config = await loadConfigForCheck();\n if (!isCurrent()) return;\n continuousPossible = Boolean(config.continuous && config.agentMode);\n if (!continuousPossible) {\n await continuous?.stop(ctx.sessionManager);\n return;\n }\n const { createContinuousSync } = await import(\"./sync/continuous-sync.js\");\n if (!isCurrent()) return;\n continuous ??= createContinuousSync(loaders, undefined, publishTimings);\n continuous.start(\n ctx,\n signal,\n Boolean(retry && (retry.setup === undefined || retry.setup === config.setupName)),\n startupDebug,\n );\n } catch {\n /* Existing initialization/command paths report settings errors. */\n }\n }\n\n pi.registerCommand(\"sync\", {\n description: \"Sync Pi settings through Git, WebDAV, R2, or S3-compatible storage\",\n getArgumentCompletions: completeSyncArguments,\n handler: async (args, ctx) => {\n if (!ctx.hasUI) {\n throw new Error(\"/sync requires TUI or RPC mode so results and safety prompts are observable.\");\n }\n status.bind(ctx);\n const signal = sessionAbort.signal;\n const manager = ctx.sessionManager;\n const command = splitArgs(args)[0];\n let retry: { setup?: string } | undefined;\n let mayResume = false;\n foreground.set(manager, (foreground.get(manager) ?? 0) + 1);\n try {\n const ready = await initialization;\n mayResume = ready !== false;\n if (signal.aborted) return;\n await continuous?.stop(manager);\n if (signal.aborted) return;\n await check.stop();\n if (signal.aborted) return;\n if (ready === false && command !== \"help\" && command !== \"unlock\" && command !== \"migrate-state\") {\n ctx.ui.notify(\n \"pi-sync recovery required. Repair the startup error, then /reload before syncing. Use /sync help for recovery guidance.\",\n \"error\",\n );\n return;\n }\n const commands = await loaders.commands().catch((error) => {\n if (!signal.aborted) {\n ctx.ui.notify(`pi-sync command unavailable: ${safeTerminalText(errorMessage(error))}`, \"error\");\n }\n });\n if (signal.aborted || !commands) return;\n const run = () =>\n commands.handleCommand(args, ctx, signal, loaders, attention, (setup) => {\n retry = { setup };\n });\n // Drain background children before foreground guards. Help remains reachable during repair.\n if (command === \"migrate-state\" || command === \"help\") await run();\n else await withStateDirectoryAccess(run);\n } finally {\n const count = (foreground.get(manager) ?? 1) - 1;\n if (count) foreground.set(manager, count);\n else foreground.delete(manager);\n if (mayResume) await resumeContinuous(ctx, signal, retry);\n }\n },\n });\n\n pi.on(\"session_start\", async (_event, ctx) => {\n const releaseStatus = status.start(ctx);\n try {\n shutdownAbort?.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n shutdownAbort = undefined;\n sessionAbort.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n sessionAbort = new AbortController();\n const signal = sessionAbort.signal;\n owner = ctx.sessionManager;\n continuousPossible = false;\n startupDebug = false;\n attention.reset(ctx);\n const previous = initialization;\n initialization = (async () => {\n await previous;\n if (signal.aborted) return false;\n await continuous?.stop();\n if (signal.aborted) return false;\n await check.stop();\n if (signal.aborted) return false;\n try {\n const startup = await withStateDirectoryAccess(() => startSession(ctx, signal, publishTimings));\n if (signal.aborted) return false;\n startupDebug = startup?.debug ?? false;\n return startup?.config;\n } catch (error) {\n if (!signal.aborted && ctx.hasUI) {\n ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}`, \"error\");\n }\n return false;\n }\n })();\n const ready = await initialization;\n if (ready === false) releaseStatus();\n if (ready && !signal.aborted) {\n if (ready.continuous && ready.agentMode) await resumeContinuous(ctx, signal);\n else if (ready.automatic || startupTransferEnabled(ready)) check.start(ctx, signal, ready);\n }\n } catch (error) {\n releaseStatus();\n throw error;\n }\n });\n\n pi.on(\"agent_start\", async (_event, ctx) => {\n await continuous?.stop(ctx.sessionManager);\n await check.interrupt(ctx);\n });\n\n pi.on(\"agent_settled\", async (_event, ctx) => {\n const signal = sessionAbort.signal;\n if (!signal.aborted) {\n check.settled(ctx);\n if (continuousPossible) await resumeContinuous(ctx, signal);\n }\n });\n\n pi.on(\"session_shutdown\", async (event, ctx) => {\n const releaseStatus = status.cleanupFor(ctx);\n try {\n if (continuous && owner && owner !== ctx.sessionManager) return;\n sessionAbort.abort(new DOMException(\"Session shut down\", \"AbortError\"));\n attention.reset(ctx);\n shutdownAbort?.abort(new DOMException(\"Session shut down again\", \"AbortError\"));\n const controller = new AbortController();\n shutdownAbort = controller;\n const signal = combineSignals(controller.signal, AbortSignal.timeout(30_000));\n const reason = typeof event === \"object\" && event ? (event as { reason?: string }).reason : undefined;\n try {\n const ready = await initialization;\n if (signal.aborted) return;\n await continuous?.stop(ctx.sessionManager);\n if (signal.aborted) return;\n await check.stop();\n if (signal.aborted) return;\n if (ready !== false && reason !== \"reload\") {\n await withStateDirectoryAccess(async () => {\n if (signal.aborted) return;\n await autoPushSessions(ctx, signal, loaders);\n });\n }\n } catch (error) {\n if (!signal.aborted) {\n ctx.ui.notify(`pi-sync session push skipped: ${errorMessage(error)}`, \"warning\");\n }\n } finally {\n if (shutdownAbort === controller) shutdownAbort = undefined;\n }\n if (signal.aborted) return;\n setSyncStatus(ctx, undefined);\n } finally {\n releaseStatus();\n }\n });\n}\n\nexport type { Sy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AAO,iCAAiC,aAAa,KAAK,CAAC,IAAI,SAAS;AAAA,QACjF;AAAA,MACF,UAAE;AACA,YAAI,kBAAkB,WAAY,iBAAgB;AAAA,MACpD;AACA,UAAI,OAAO,QAAS;AACpB,oBAAc,KAAK,MAAS;AAAA,IAC9B,UAAE;AACA,oBAAc;AAAA,IAChB;AAAA,EACF,CAAC;AACH;",
4
+ "sourcesContent": ["export function isMissingConfigError(error: unknown) {\n return (\n error instanceof Error &&\n (error.message.startsWith(\"Missing pi-sync settings.\") || error.message === \"No sync setups are configured.\")\n );\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { setSyncSetupCompletions } from \"../commands/command.js\";\nimport type { CommandOptions } from \"../commands/command-types.js\";\nimport { loadConfig, loadPartialConfig } from \"../settings/config.js\";\nimport { isMissingConfigError } from \"../settings/config-errors.js\";\nimport { consumeLocalConfigMigrationNotice } from \"../settings/config-file.js\";\nimport { readLocalConfigObject } from \"../settings/settings-store.js\";\nimport type { AnySyncConfig } from \"../settings/settings-types.js\";\nimport { sessionDirFromContext, snapshotOptionsForContext } from \"../snapshot/session-paths.js\";\nimport { pendingTransactionEntries } from \"../snapshot/snapshot-transaction-directory.js\";\nimport { withLock } from \"../state/lock.js\";\nimport { stateDirectoryMigrationNotice } from \"../state/state-directory.js\";\nimport { ensureStateDir, readStateForConfig } from \"../state/sync-state-store.js\";\nimport { configureSyncStatus, setSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { captureMutationOwner } from \"./mutation-owner.js\";\nimport { throwIfAborted } from \"./signals.js\";\nimport { createStartupTimings, type StartupTimingPublisher } from \"./startup-timings.js\";\nimport { errorMessage } from \"./sync-errors.js\";\nimport type { SyncLoaders } from \"./sync-loaders.js\";\nimport { syncSessionsSelected } from \"./sync-policy.js\";\n\nconst AUTO_SYNC_OPTIONS: CommandOptions = {\n yes: true,\n force: false,\n stale: false,\n silent: true,\n reload: false,\n auto: true,\n args: [],\n};\n\nexport async function startSession(\n ctx: ExtensionContext,\n signal: AbortSignal,\n publish?: StartupTimingPublisher,\n): Promise<{ debug: boolean; config?: AnySyncConfig } | undefined> {\n const timings = createStartupTimings(publish);\n let debug = false;\n let outcome: \"completed\" | \"stopped\" = \"stopped\";\n try {\n throwIfAborted(signal);\n const stateNotice = stateDirectoryMigrationNotice();\n if (stateNotice && ctx.hasUI) ctx.ui.notify(stateNotice, \"warning\");\n // Recovery can restore managed files: finish it before Pi accepts user edits.\n // Unlike remote inspection, it must never be detached behind startup.\n const validateMutation = captureMutationOwner(ctx, signal);\n const currentFile = ctx.sessionManager.getSessionFile?.();\n await timings.measure(\"transaction recovery\", async () => {\n const pending = await pendingTransactionEntries();\n validateMutation();\n if (!pending.some((entry) => entry.isDirectory())) return;\n // Normal startup needs only the directory probe, not the recovery/snapshot graph.\n const { recoverSnapshotTransactionsOnStartup } = await import(\"../snapshot/snapshot-transaction.js\");\n validateMutation();\n const recoverySettings = await readLocalConfigObject();\n validateMutation();\n const recoverySetup = recoverySettings?.activeSyncSetup;\n await recoverSnapshotTransactionsOnStartup({\n exclude: recoverySetup ? recoverySettings.syncSetups[recoverySetup]?.sync.exclude : undefined,\n signal,\n sessionDir: sessionDirFromContext(ctx),\n protectedTargets: currentFile ? [currentFile] : [],\n validateMutation,\n });\n });\n throwIfAborted(signal);\n try {\n const settings = await timings.measure(\"settings read\", () => readLocalConfigObject());\n throwIfAborted(signal);\n debug = settings?.debug ?? false;\n const names = settings ? Object.keys(settings.syncSetups).sort((left, right) => left.localeCompare(right)) : [];\n setSyncSetupCompletions(names);\n configureSyncStatus(ctx, settings?.showStatus ?? true);\n } catch {\n if (signal.aborted) return;\n setSyncSetupCompletions([]);\n }\n const migrationNotice = consumeLocalConfigMigrationNotice();\n if (migrationNotice && ctx.hasUI) ctx.ui.notify(migrationNotice, \"warning\");\n throwIfAborted(signal);\n if (!ctx.hasUI) return { debug };\n try {\n const config = await timings.measure(\"config resolution\", () => loadConfig());\n throwIfAborted(signal);\n configureSyncStatus(ctx, config.showStatus);\n outcome = \"completed\";\n return { debug, config };\n } catch (error) {\n throwIfAborted(signal);\n if (!isMissingConfigError(error)) {\n ctx.ui.notify(`pi-sync startup check skipped: ${safeTerminalText(errorMessage(error))}`, \"warning\");\n }\n }\n return { debug };\n } finally {\n timings.publish(ctx, debug, signal, \"local initialization\", outcome);\n }\n}\n\nexport async function autoPushSessions(ctx: ExtensionContext, signal: AbortSignal, loaders: SyncLoaders) {\n try {\n const partial = await loadPartialConfig();\n throwIfAborted(signal);\n if (!partial.automatic) return;\n if (!syncSessionsSelected(partial)) return;\n await ensureStateDir();\n throwIfAborted(signal);\n const config = await loadConfig();\n throwIfAborted(signal);\n if (!syncSessionsSelected(config)) return;\n const [operations, snapshotModule, syncStateModule] = await Promise.all([\n loaders.operations(),\n loaders.snapshot(),\n loaders.syncState(),\n ]);\n throwIfAborted(signal);\n await withLock(\"auto-session-push\", async () => {\n throwIfAborted(signal);\n const state = await readStateForConfig(config);\n throwIfAborted(signal);\n const local = await snapshotModule.createSnapshot(config.snapshotIdentity, {\n ...snapshotOptionsForContext(ctx, config),\n signal,\n });\n throwIfAborted(signal);\n if (!syncStateModule.hasLocalChanges(local, state, config)) return;\n await operations.push(ctx, { ...AUTO_SYNC_OPTIONS, signal }, { config, state, local });\n });\n } catch (error) {\n if (signal.aborted || isMissingConfigError(error)) return;\n setSyncStatus(ctx, undefined);\n ctx.ui.notify(`pi-sync session push skipped: ${errorMessage(error)}`, \"warning\");\n }\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { loadConfigForCheck, syncCheckConfigFingerprint } from \"../settings/config.js\";\nimport { isMissingConfigError } from \"../settings/config-errors.js\";\nimport type { AnySyncConfig } from \"../settings/settings-types.js\";\nimport { snapshotOptionsForContext } from \"../snapshot/session-paths.js\";\nimport { withLock } from \"../state/lock.js\";\nimport { withStateDirectoryAccess } from \"../state/state-directory.js\";\nimport { readStateForConfig, syncStateFingerprint } from \"../state/sync-state-store.js\";\nimport type { SyncAttentionController } from \"../ui/sync-attention.js\";\nimport { setSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { startupTransferEnabled } from \"./agent-policy.js\";\nimport { combineSignals, throwIfAborted } from \"./signals.js\";\nimport { createStartupTimings, type StartupTimingPublisher } from \"./startup-timings.js\";\nimport { errorMessage } from \"./sync-errors.js\";\nimport type { SyncLoaders } from \"./sync-loaders.js\";\n\n/** One owned task per extension session, never keyed by the shared headless UI. */\nexport function createStartupCheck(\n loaders: SyncLoaders,\n attention: SyncAttentionController,\n timeoutMs = 30_000,\n publish?: StartupTimingPublisher,\n) {\n let active:\n | {\n controller: AbortController;\n promise: Promise<void>;\n owner: ExtensionContext[\"sessionManager\"];\n transfer: boolean;\n }\n | undefined;\n\n let pending: { ctx: ExtensionContext; signal: AbortSignal; config: AnySyncConfig } | undefined;\n\n const controllerApi = {\n async interrupt(ctx: ExtensionContext) {\n const task = active;\n if (!task?.transfer || task.owner !== ctx.sessionManager) return;\n task.controller.abort(new DOMException(\"Agent became busy\", \"AbortError\"));\n await task.promise;\n },\n settled(ctx: ExtensionContext) {\n const queued = pending;\n if (!queued || queued.ctx.sessionManager !== ctx.sessionManager || queued.signal.aborted || !ctx.isIdle()) return;\n pending = undefined;\n controllerApi.start(ctx, queued.signal, queued.config);\n },\n start(ctx: ExtensionContext, sessionSignal: AbortSignal, initialConfig?: AnySyncConfig) {\n if (!ctx.hasUI || sessionSignal.aborted) return;\n if (initialConfig && startupTransferEnabled(initialConfig) && !ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: initialConfig };\n return;\n }\n if (active) throw new Error(\"Previous startup check has not been drained.\");\n const timings = createStartupTimings(publish);\n const controller = new AbortController();\n const signal = combineSignals(sessionSignal, controller.signal);\n const task = {\n controller,\n owner: ctx.sessionManager,\n promise: Promise.resolve(),\n transfer: Boolean(initialConfig && startupTransferEnabled(initialConfig)),\n };\n active = task;\n const isCurrent = () => !sessionSignal.aborted && active === task && task.owner === ctx.sessionManager;\n const timer = setTimeout(\n () => controller.abort(new DOMException(\"Startup check timed out\", \"TimeoutError\")),\n timeoutMs,\n );\n timer.unref();\n let config: AnySyncConfig | undefined;\n let checking = false;\n let stopped = false;\n // Handle every detached rejection here; Pi's awaited event runner cannot catch it.\n task.promise = Promise.resolve()\n .then(async () => {\n try {\n throwIfAborted(signal);\n config = initialConfig ?? (await loadConfigForCheck());\n task.transfer = startupTransferEnabled(config);\n throwIfAborted(signal);\n if (!config.automatic && !startupTransferEnabled(config)) return;\n const captured = config;\n const identity = syncCheckConfigFingerprint(captured);\n checking = true;\n setSyncStatus(ctx, \"sync ...\", { activity: \"checking\" });\n const { inspectSync } = await timings.measure(\"inspection import\", () => loaders.inspection());\n throwIfAborted(signal);\n const currentConfig = await loadConfigForCheck();\n throwIfAborted(signal);\n if (syncCheckConfigFingerprint(currentConfig) !== identity) return;\n // Lock order: state migration guard \u2192 sync operation \u2192 backend cache.\n // Read heads may write only private cache data. Never call doctor/syncBoth.\n const inspection = await timings.measure(\"inspection and guards\", () =>\n withStateDirectoryAccess(() => {\n throwIfAborted(signal);\n return withLock(\"startup-check\", () => {\n throwIfAborted(signal);\n return inspectSync(captured, snapshotOptionsForContext(ctx, captured), signal, undefined, timings);\n });\n }),\n );\n throwIfAborted(signal);\n const latest = await loadConfigForCheck();\n throwIfAborted(signal);\n if (syncCheckConfigFingerprint(latest) !== identity) return;\n const state = await withStateDirectoryAccess(() => readStateForConfig(latest));\n throwIfAborted(signal);\n if (syncStateFingerprint(state) !== inspection.stateIdentity || !isCurrent()) return;\n attention.observe({\n setupName: captured.setupName,\n configIdentity: identity,\n checkedAt: new Date().toISOString(),\n inspection,\n automaticTransfer: startupTransferEnabled(captured),\n });\n if (\n startupTransferEnabled(captured) &&\n !inspection.firstSync &&\n inspection.head &&\n inspection.selectionState?.kind === \"same\"\n ) {\n const [operations, { withAgentSyncLock }] = await timings.measure(\"operations import\", () =>\n Promise.all([loaders.operations(), import(\"./agent-sync.js\")]),\n );\n throwIfAborted(signal);\n if (!isCurrent()) return;\n if (!ctx.isIdle()) {\n pending = { ctx, signal: sessionSignal, config: captured };\n return;\n }\n await timings.measure(\"automatic transfer\", () =>\n withStateDirectoryAccess(() =>\n withAgentSyncLock(\n ctx,\n {\n args: [],\n yes: true,\n force: false,\n stale: false,\n silent: true,\n reload: false,\n auto: true,\n signal,\n startupTimings: timings,\n onCommit: () => attention.clearObservation(),\n },\n (options) => operations.syncBoth(ctx, options),\n ),\n ),\n );\n throwIfAborted(signal);\n if (!isCurrent()) return;\n attention.clearObservation();\n return;\n }\n attention.observe({\n setupName: captured.setupName,\n configIdentity: identity,\n checkedAt: new Date().toISOString(),\n inspection,\n automaticTransfer: startupTransferEnabled(captured),\n });\n if (ctx.mode === \"rpc\") attention.notifyObservation(ctx);\n } catch (error) {\n stopped = true;\n if (!isCurrent() || sessionSignal.aborted || isMissingConfigError(error)) return;\n if (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\") return;\n // A settings edit invalidates failures as well as successful observations.\n if (config) {\n const latest = await loadConfigForCheck().catch(() => undefined);\n if (!isCurrent() || (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\")) return;\n if (!latest || syncCheckConfigFingerprint(latest) !== syncCheckConfigFingerprint(config)) return;\n }\n ctx.ui.notify(\n config && startupTransferEnabled(config)\n ? `pi-sync automatic transfer stopped: ${safeTerminalText(errorMessage(error))}. Run /sync to review or reconcile retained recovery evidence. No resources were reloaded.`\n : `pi-sync startup check skipped: ${safeTerminalText(errorMessage(error))}. Run /sync status to retry. No startup transfer was performed.`,\n \"warning\",\n );\n } finally {\n clearTimeout(timer);\n if (isCurrent() && checking) {\n if (!signal.aborted || controller.signal.reason?.name === \"TimeoutError\") {\n const latest = await loadConfigForCheck().catch(() => undefined);\n if (isCurrent()) {\n if (signal.aborted && controller.signal.reason?.name !== \"TimeoutError\")\n setSyncStatus(ctx, undefined);\n else if (\n config &&\n latest &&\n syncCheckConfigFingerprint(latest) === syncCheckConfigFingerprint(config)\n )\n await attention.publish(ctx, sessionSignal);\n else attention.reset(ctx);\n }\n } else setSyncStatus(ctx, undefined);\n }\n if (isCurrent()) {\n timings.publish(\n ctx,\n config?.debug ?? false,\n sessionSignal,\n \"background startup\",\n signal.aborted || stopped ? \"stopped\" : \"completed\",\n );\n }\n if (active === task) active = undefined;\n }\n })\n .catch(() => {\n // UI teardown can itself throw. No unhandled rejection or retained timer.\n clearTimeout(timer);\n if (active === task) active = undefined;\n });\n },\n async stop() {\n pending = undefined;\n const task = active;\n if (!task) return;\n task.controller.abort(new DOMException(\"Startup check cancelled\", \"AbortError\"));\n // Drain the actual work, including child/ref cleanup, before foreground guards.\n await task.promise;\n },\n };\n return controllerApi;\n}\n", "type SetupSwitchModule = Pick<typeof import(\"./setup-switch.js\"), \"useSyncSetup\">;\ntype SnapshotModule = Pick<typeof import(\"../snapshot/snapshot.js\"), \"createSnapshot\">;\ntype SyncStateModule = Pick<typeof import(\"./sync-state.js\"), \"hasLocalChanges\">;\ntype SyncOperations = typeof import(\"./sync-operations.js\");\ntype CommandHandlerModule = Pick<typeof import(\"../commands/command-handler.js\"), \"handleCommand\">;\n\ntype SyncInspectionModule = Pick<typeof import(\"./sync-inspection.js\"), \"inspectSync\">;\n\nexport interface SyncDependencies {\n loadCommandHandler(): Promise<CommandHandlerModule>;\n loadSyncInspection(): Promise<SyncInspectionModule>;\n loadSetupSwitch(): Promise<SetupSwitchModule>;\n loadSnapshot(): Promise<SnapshotModule>;\n loadSyncState(): Promise<SyncStateModule>;\n loadSyncOperations(): Promise<SyncOperations>;\n}\n\nexport interface SyncLoaders {\n commands(): Promise<CommandHandlerModule>;\n inspection(): Promise<SyncInspectionModule>;\n setupSwitch(): Promise<SetupSwitchModule>;\n snapshot(): Promise<SnapshotModule>;\n syncState(): Promise<SyncStateModule>;\n operations(): Promise<SyncOperations>;\n}\n\nexport function createSyncLoaders(dependencies: Partial<SyncDependencies>): SyncLoaders {\n const loaders: SyncLoaders = {\n commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import(\"../commands/command-handler.js\"))),\n inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import(\"./sync-inspection.js\"))),\n setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import(\"./setup-switch.js\"))),\n snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import(\"../snapshot/snapshot.js\"))),\n syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import(\"./sync-state.js\"))),\n operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import(\"./sync-operations.js\"))),\n };\n return loaders;\n}\n\nfunction cachedModuleLoader<Module>(load: () => Promise<Module>): () => Promise<Module> {\n let pending: Promise<Module> | undefined;\n return () => {\n if (!pending) {\n pending = load().catch((error) => {\n pending = undefined;\n throw error;\n });\n }\n return pending;\n };\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport type { StartupTimingPublisher } from \"../sync/startup-timings.js\";\nimport { safeTerminalText } from \"./terminal-text.js\";\n\nexport const STARTUP_TIMING_ENTRY = \"pi-sync-startup-timings\";\n\nexport interface StartupTimingEntry {\n version: 1;\n report: string;\n}\n\nexport function registerStartupTimings(pi: ExtensionAPI): StartupTimingPublisher {\n pi.registerEntryRenderer<StartupTimingEntry>(STARTUP_TIMING_ENTRY, (entry, _options, theme) => {\n const data = entry.data;\n if (data?.version !== 1 || typeof data.report !== \"string\") return undefined;\n const text = new Text(\n data.report\n .split(\"\\n\")\n .map((line, index) => theme.fg(index === 0 ? \"accent\" : \"muted\", safeTerminalText(line)))\n .join(\"\\n\"),\n 0,\n 0,\n );\n return {\n render: (width) => (width > 0 ? text.render(width).map((line) => truncateToWidth(line, width)) : []),\n invalidate: () => text.invalidate(),\n };\n });\n return (ctx, report) => {\n // Pi coalesces consecutive info notifications, including the final /reload notice.\n // Custom entries remain visible without adding messages to model context.\n if (ctx.mode === \"tui\") pi.appendEntry<StartupTimingEntry>(STARTUP_TIMING_ENTRY, { version: 1, report });\n else ctx.ui.notify(report, \"info\");\n };\n}\n", "import type { ExtensionAPI, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { completeSyncArguments, splitArgs } from \"./commands/command.js\";\nimport type { AnySyncConfig } from \"./settings/settings-types.js\";\nimport { withStateDirectoryAccess } from \"./state/state-directory.js\";\nimport { startupTransferEnabled } from \"./sync/agent-policy.js\";\nimport { autoPushSessions, startSession } from \"./sync/automatic-sync.js\";\nimport { combineSignals } from \"./sync/signals.js\";\nimport { createStartupCheck } from \"./sync/startup-check.js\";\nimport { errorMessage } from \"./sync/sync-errors.js\";\nimport { createSyncLoaders, type SyncDependencies } from \"./sync/sync-loaders.js\";\nimport { registerStartupTimings } from \"./ui/startup-timings-entry.js\";\nimport { createSyncAttentionController } from \"./ui/sync-attention.js\";\nimport { createSyncStatusPublisher, setSyncStatus } from \"./ui/sync-status.js\";\nimport { safeTerminalText } from \"./ui/terminal-text.js\";\n\nexport default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDependencies> = {}) {\n const loaders = createSyncLoaders(dependencies);\n const attention = createSyncAttentionController();\n const status = createSyncStatusPublisher(pi.events);\n const publishTimings = registerStartupTimings(pi);\n const check = createStartupCheck(loaders, attention, 30_000, publishTimings);\n let sessionAbort = new AbortController();\n let shutdownAbort: AbortController | undefined;\n let initialization = Promise.resolve<AnySyncConfig | false | undefined>(undefined);\n let continuous: ReturnType<typeof import(\"./sync/continuous-sync.js\")[\"createContinuousSync\"]> | undefined;\n let owner: ExtensionContext[\"sessionManager\"] | undefined;\n let continuousPossible = false;\n let startupDebug = false;\n const foreground = new Map<ExtensionContext[\"sessionManager\"], number>();\n async function resumeContinuous(ctx: ExtensionContext, signal: AbortSignal, retry?: { setup?: string }) {\n const isCurrent = () => !signal.aborted && !foreground.has(ctx.sessionManager) && owner === ctx.sessionManager;\n if (!isCurrent() || !ctx.hasUI) return;\n try {\n const { loadConfigForCheck } = await import(\"./settings/config.js\");\n if (!isCurrent()) return;\n const config = await loadConfigForCheck();\n if (!isCurrent()) return;\n continuousPossible = Boolean(config.continuous && config.agentMode);\n if (!continuousPossible) {\n await continuous?.stop(ctx.sessionManager);\n return;\n }\n const { createContinuousSync } = await import(\"./sync/continuous-sync.js\");\n if (!isCurrent()) return;\n continuous ??= createContinuousSync(loaders, undefined, publishTimings);\n continuous.start(\n ctx,\n signal,\n Boolean(retry && (retry.setup === undefined || retry.setup === config.setupName)),\n startupDebug,\n );\n } catch {\n /* Existing initialization/command paths report settings errors. */\n }\n }\n\n pi.registerCommand(\"sync\", {\n description: \"Sync Pi settings through Git, WebDAV, R2, or S3-compatible storage\",\n getArgumentCompletions: completeSyncArguments,\n handler: async (args, ctx) => {\n if (!ctx.hasUI) {\n throw new Error(\"/sync requires TUI or RPC mode so results and safety prompts are observable.\");\n }\n status.bind(ctx);\n const signal = sessionAbort.signal;\n const manager = ctx.sessionManager;\n const command = splitArgs(args)[0];\n let retry: { setup?: string } | undefined;\n let mayResume = false;\n foreground.set(manager, (foreground.get(manager) ?? 0) + 1);\n try {\n const ready = await initialization;\n mayResume = ready !== false;\n if (signal.aborted) return;\n await continuous?.stop(manager);\n if (signal.aborted) return;\n await check.stop();\n if (signal.aborted) return;\n if (ready === false && command !== \"help\" && command !== \"unlock\" && command !== \"migrate-state\") {\n ctx.ui.notify(\n \"pi-sync recovery required. Repair the startup error, then /reload before syncing. Use /sync help for recovery guidance.\",\n \"error\",\n );\n return;\n }\n const commands = await loaders.commands().catch((error) => {\n if (!signal.aborted) {\n ctx.ui.notify(`pi-sync command unavailable: ${safeTerminalText(errorMessage(error))}`, \"error\");\n }\n });\n if (signal.aborted || !commands) return;\n const run = () =>\n commands.handleCommand(args, ctx, signal, loaders, attention, (setup) => {\n retry = { setup };\n });\n // Drain background children before foreground guards. Help remains reachable during repair.\n if (command === \"migrate-state\" || command === \"help\") await run();\n else await withStateDirectoryAccess(run);\n } finally {\n const count = (foreground.get(manager) ?? 1) - 1;\n if (count) foreground.set(manager, count);\n else foreground.delete(manager);\n if (mayResume) await resumeContinuous(ctx, signal, retry);\n }\n },\n });\n\n pi.on(\"session_start\", async (_event, ctx) => {\n const releaseStatus = status.start(ctx);\n try {\n shutdownAbort?.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n shutdownAbort = undefined;\n sessionAbort.abort(new DOMException(\"Session replaced\", \"AbortError\"));\n sessionAbort = new AbortController();\n const signal = sessionAbort.signal;\n owner = ctx.sessionManager;\n continuousPossible = false;\n startupDebug = false;\n attention.reset(ctx);\n const previous = initialization;\n initialization = (async () => {\n await previous;\n if (signal.aborted) return false;\n await continuous?.stop();\n if (signal.aborted) return false;\n await check.stop();\n if (signal.aborted) return false;\n try {\n const startup = await withStateDirectoryAccess(() => startSession(ctx, signal, publishTimings));\n if (signal.aborted) return false;\n startupDebug = startup?.debug ?? false;\n return startup?.config;\n } catch (error) {\n if (!signal.aborted && ctx.hasUI) {\n ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}`, \"error\");\n }\n return false;\n }\n })();\n const ready = await initialization;\n if (ready === false) releaseStatus();\n if (ready && !signal.aborted) {\n if (ready.continuous && ready.agentMode) await resumeContinuous(ctx, signal);\n else if (ready.automatic || startupTransferEnabled(ready)) check.start(ctx, signal, ready);\n }\n } catch (error) {\n releaseStatus();\n throw error;\n }\n });\n\n pi.on(\"agent_start\", async (_event, ctx) => {\n await continuous?.stop(ctx.sessionManager);\n await check.interrupt(ctx);\n });\n\n pi.on(\"agent_settled\", async (_event, ctx) => {\n const signal = sessionAbort.signal;\n if (!signal.aborted) {\n check.settled(ctx);\n if (continuousPossible) await resumeContinuous(ctx, signal);\n }\n });\n\n pi.on(\"session_shutdown\", async (event, ctx) => {\n const releaseStatus = status.cleanupFor(ctx);\n try {\n if (continuous && owner && owner !== ctx.sessionManager) return;\n sessionAbort.abort(new DOMException(\"Session shut down\", \"AbortError\"));\n attention.reset(ctx);\n shutdownAbort?.abort(new DOMException(\"Session shut down again\", \"AbortError\"));\n const controller = new AbortController();\n shutdownAbort = controller;\n const signal = combineSignals(controller.signal, AbortSignal.timeout(30_000));\n const reason = typeof event === \"object\" && event ? (event as { reason?: string }).reason : undefined;\n try {\n const ready = await initialization;\n if (signal.aborted) return;\n await continuous?.stop(ctx.sessionManager);\n if (signal.aborted) return;\n await check.stop();\n if (signal.aborted) return;\n if (ready !== false && reason !== \"reload\") {\n await withStateDirectoryAccess(async () => {\n if (signal.aborted) return;\n await autoPushSessions(ctx, signal, loaders);\n });\n }\n } catch (error) {\n if (!signal.aborted) {\n ctx.ui.notify(`pi-sync session push skipped: ${errorMessage(error)}`, \"warning\");\n }\n } finally {\n if (shutdownAbort === controller) shutdownAbort = undefined;\n }\n if (signal.aborted) return;\n setSyncStatus(ctx, undefined);\n } finally {\n releaseStatus();\n }\n });\n}\n\nexport type { SyncDependencies } from \"./sync/sync-loaders.js\";\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAO,SAAS,qBAAqB,OAAgB;AACnD,SACE,iBAAiB,UAChB,MAAM,QAAQ,WAAW,2BAA2B,KAAK,MAAM,YAAY;AAEhF;;;ACiBA,IAAM,oBAAoC;AAAA,EACxC,KAAK;AAAA,EACL,OAAO;AAAA,EACP,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,MAAM,CAAC;AACT;AAEA,eAAsB,aACpB,KACA,QACA,SACiE;AACjE,QAAM,UAAU,qBAAqB,OAAO;AAC5C,MAAI,QAAQ;AACZ,MAAI,UAAmC;AACvC,MAAI;AACF,mBAAe,MAAM;AACrB,UAAM,cAAc,8BAA8B;AAClD,QAAI,eAAe,IAAI,MAAO,KAAI,GAAG,OAAO,aAAa,SAAS;AAGl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I,cAAc,SAAS,UAAU,IAAI,eAAgB;AACzD,mBAAa,MAAM,IAAI,aAAa,qBAAqB,YAAY,CAAC;AACtE,gBAAU,MAAM,GAAG;AACnB,qBAAe,MAAM,IAAI,aAAa,2BAA2B,YAAY,CAAC;AAC9E,YAAM,aAAa,IAAI,gBAAgB;AACvC,sBAAgB;AAChB,YAAM,SAAS,eAAe,WAAW,QAAQ,YAAY,QAAQ,GAAM,CAAC;AAC5E,YAAM,SAAS,OAAO,UAAU,YAAY,QAAS,MAA8B,SAAS;AAC5F,UAAI;AACF,cAAM,QAAQ,MAAM;AACpB,YAAI,OAAO,QAAS;AACpB,cAAM,YAAY,KAAK,IAAI,cAAc;AACzC,YAAI,OAAO,QAAS;AACpB,cAAM,MAAM,KAAK;AACjB,YAAI,OAAO,QAAS;AACpB,YAAI,UAAU,SAAS,WAAW,UAAU;AAC1C,gBAAM,yBAAyB,YAAY;AACzC,gBAAI,OAAO,QAAS;AACpB,kBAAM,iBAAiB,KAAK,QAAQ,OAAO;AAAA,UAC7C,CAAC;AAAA,QACH;AAAA,MACF,SAAS,OAAO;AACd,YAAI,CAAC,OAAO,SAAS;AACnB,cAAI,GAAG,OAAO,iCAAiC,aAAa,KAAK,CAAC,IAAI,SAAS;AAAA,QACjF;AAAA,MACF,UAAE;AACA,YAAI,kBAAkB,WAAY,iBAAgB;AAAA,MACpD;AACA,UAAI,OAAO,QAAS;AACpB,oBAAc,KAAK,MAAS;AAAA,IAC9B,UAAE;AACA,oBAAc;AAAA,IAChB;AAAA,EACF,CAAC;AACH;",
6
6
  "names": ["loadConfigForCheck"]
7
7
  }
@@ -0,0 +1,54 @@
1
+ # Exclude policy safety audit
2
+
3
+ Pi Sync owns one include-minus-exclude policy; transports validate its versioned representation but do not choose sync scope. See the [user reference](../skills/configure-pi-sync/references/configuration.md#excluded-paths) for configuration and recovery.
4
+
5
+ ## Decision branches and verification map
6
+
7
+ | Boundary | Authoritative implementation | Representative evidence |
8
+ | --- | --- | --- |
9
+ | Grammar and matching | `sync/exclude-policy.ts`: bounded validation, basic glob grammar, explicit Minimatch options, full-path and ancestor matching | `exclude-policy.test.ts`: literals, segment boundaries, zero-depth/nested globstar, dotfiles, case, sessions, invalid inputs, count/UTF-8 limits |
10
+ | Settings and persistence | `settings-validation.ts`, `config.ts`, `settings-management.ts`; existing locked, ordered, private atomic store | `exclude-settings.test.ts`, existing settings publication/ordering/filename suites |
11
+ | Wire compatibility | Settings 6, snapshot 4, selection 2; old formats still read without exclusions | `exclude-policy.test.ts`, `exclude-snapshot.test.ts`, shared backend contracts on Git (both paths), S3, WebDAV |
12
+ | Metadata integrity | `remote-snapshot.ts`, Git manifest validation, object pointer projection; compare the complete versioned policy | Tampered head and malformed/inconsistent payload tests, shared backend contracts |
13
+ | Collection | `createSnapshot`, `collectFiles`, directory traversal; prune before content reads, logical virtual session paths | Read/readdir spies in `exclude-snapshot.test.ts`; default session-root tests remain unchanged |
14
+ | Directional/force transfer | `sync-mutations.ts`, filtered snapshot options, excluded-path safety preflight | `exclude-sync.test.ts`: reviewed force push, pull, policy mismatch, stale settings, retained unmanaged content/history |
15
+ | Local mutation/recovery | `snapshot-apply.ts`, `snapshot-exclude-safety.ts`, transaction rule binding; protect excluded descendants before backup/removal | Apply/deletion/ancestor and changed-policy transaction tests; existing transaction/alias/root-transition recovery suites |
16
+ | Merged/partial/field composition | Version-preserving field and partial projections; metadata-only merged target preflight | `exclude-snapshot.test.ts`, `exclude-sync.test.ts`, existing field/partial/journal suites |
17
+ | State, ancestors, model authorization | Exclusions in accepted state, review/config/merge/cache identity; excluded ancestors removed before conflict/model evidence | Policy-only identity tests, merged-sync tests, baseline and agent regression suites |
18
+ | Continuous work | Filter content watcher hints, retain settings/ancestor hints and periodic scanning; storage-owner binding unchanged | `continuous-watch.test.ts`, existing continuous authorization/freshness/lifecycle suites |
19
+ | UI and adoption | Native abortable input, Kit review, full-policy atomic adoption, explicit version review, no implicit transfer | `exclude-settings.test.ts`, `exclude-remote-ui.test.ts`, original selection/disposal/lifecycle suites |
20
+ | Generated runtime | External matcher dependency and unchanged package-owned lazy module boundary | Generated-runtime/Jiti tests, pack inspection, controlled RPC CLI smoke |
21
+
22
+ Matcher audit: Pi's public root exports provide no suitable matcher. `minimatch` is declared directly rather than imported through Pi. `platform: "linux"` removes Windows root/magic differences; `dot` and `nocase` are explicit; negation, comments, braces, and extglobs are disabled and unsupported syntax is rejected before compilation. Match-base and partial matching are not enabled. Repeated slashes, traversal and backslashes are rejected rather than delegated to matcher normalization. A trailing globstar is reduced to its zero-segment root before ancestor matching, so `sessions/**` prunes the root as well as descendants.
23
+ Effective-session checks also gate legacy shutdown pushes, session-root guards and status; they do not rely on include membership alone.
24
+ Canonical rule sorting uses code-point order, not host locale.
25
+
26
+ ## Semantic audit checklist
27
+
28
+ Review the complete diff against `docs/extension-conventions.md`, `docs/extension-settings.md`, `docs/readme-conventions.md`, and package `AGENTS.md`. Preserve no-exclude wire formats and legacy identities; inspect every settings/snapshot version branch and constructor. Check exclusion-only differences in direct guidance, attention, adoption, startup, and shutdown. Audit settings read/write ordering, malformed-file protection, unknown fields, and failure rollback together. Audit cancellation, disposal, session replacement and shutdown, including revalidation after awaited reads and dialogs.
29
+
30
+ Excluded content is absent from future portable publications, not erased from history/backups. Pi session-root configuration resolution remains separate from collection. Locks do not prevent arbitrary external editors from racing filesystem writes; existing preimage/journal safeguards remain in force. Production backend credentials/services and physical-terminal subjective acceptance are not verified by local/mock tests. No package publication, tags, or release workflow dispatch is part of this change.
31
+
32
+ ## Execution evidence
33
+
34
+ - `npm run format` and `npm run check`: passed, including builds, Biome, package boundaries and all workspace typechecks.
35
+ - `npm test`: 22,957 passed, 18 existing platform/conditional skips, 1,005 passing files and one skipped macOS-only file; no failed tests or unhandled errors.
36
+ - Shared backend contracts: version-4 snapshot/head round trips and excluded-payload rejection passed for S3, WebDAV, and both Git publication paths.
37
+ - Actual base-client smoke at `ff7d07be`: archived original settings validation, object codec and Git manifest reader all refused the new formats before apply.
38
+ - Package build and `npm run package:pack -- sync`: passed. A real temporary tarball declared the matcher dependency and contained its entrypoint, notices, docs and skill; all relative imports in 83 generated modules resolved.
39
+ - Controlled `pi --no-extensions -e <package> --mode rpc` smokes: both the repository package and extracted tarball registered `/sync`, exercised lazy `/sync files` with an exclude summary, and shut down cleanly. Deadlines started after readiness; no model request or backend transfer ran.
40
+ - Fenced-code-aware README foundation/heading/order audit: 37 active packages passed. Skill tests validate both the complete example and version-6 policy fragment.
41
+ - `npm run changeset:status`: only Pi Sync has a minor release entry; no versions, tags, publications or release workflows were created.
42
+ - Complete-diff semantic review: settings ordering/failure/atomicity, full-policy freshness, legacy formats and identities, all transfer/recovery directions, field/partial/model composition, terminal sanitization, cancellation/disposal/session replacement/shutdown, and generated package boundaries checked against the guides above. No essential acceptance criteria were waived.
43
+
44
+ The review also caught and corrected the whole-session exclusion class: root pruning, zero-segment trailing globstars, effective-session summaries/root guards, and the legacy shutdown push now agree. A legacy state without an explicit include list retains its original refresh behavior. Native abortable Input and Kit reviews are reused; no custom editing or key-matching implementation was added.
45
+
46
+ ## Review follow-up
47
+
48
+ The [review ledger](./exclude-review-ledger.md) records each review item, its evidence and its final outcome.
49
+ Excluded paths are also omitted from apply preimage assertions; included-file stale checks remain active.
50
+ The manager reports include and exclusion differences without calling an exclusion-only change an order change, and its Sessions label uses effective selection.
51
+
52
+ ## External handoff
53
+
54
+ Maintainer, optional live-service acceptance: after separately authorizing disposable backend writes and configuring credentials outside chat, exercise the existing Git/S3/WebDAV workflows against that service and retain concurrency/recovery evidence. Expected result is the same exclusion policy and local-file protection as the deterministic contracts. Real credentials, provider-specific service behavior, and native Windows/macOS filesystem behavior remain unverified here; do not describe this PR as a live-service or native-platform acceptance run. No publication or release operation is authorized by the implementation plan.
@@ -0,0 +1,36 @@
1
+ # Exclude review ledger
2
+
3
+ Target: [PR #1903](https://github.com/narumiruna/pi-extensions/pull/1903), branch `narumi/feat/pi-sync-exclude`, reviewed head `58cb3c5a`. The checkout belongs to `narumiruna/pi-extensions`. The original complete diff and instructions are unchanged from the first implementation review. All existing GitHub check runs passed at review intake.
4
+
5
+ All pages of reviews, inline comments, issue comments, commits and review threads were fetched. There is one submitted review, three conversation comments, no inline comments, and no review threads. The two off-diff findings are in [review 5909654162](https://github.com/narumiruna/pi-extensions/pull/1903#pullrequestreview-5909654162). No Resolve API target exists for those findings.
6
+
7
+ ## Applicable requirements before changes
8
+
9
+ | Area | MUST rules | Verification |
10
+ | --- | --- | --- |
11
+ | Apply preimages | Keep excluded files outside the managed scope; preserve included-file preimage checks, mutation queues and recovery evidence. Follow package `AGENTS.md` and `docs/extension-conventions.md`. | **Test:** pull, forced pull, rollback, literal/glob/case exclusions and included-file stale guards. **Review:** both `expectedFileHashes` callers and every transaction preimage consumer. |
12
+ | Manager summary | Report complete include/exclude policy state. Keep text safe and preserve lifecycle, UI modes and standard controls. Follow `docs/extension-conventions.md` and `docs/extension-settings.md`. | **Test:** non-interactive manager descriptions for exclusion-only, membership, order-only, combined and effective-session cases. **Review:** all ordering-only messages and session summary branches. |
13
+ | Documentation and checks | Keep behavior and evidence aligned. Keep the existing independent Changeset for this feature. | **Validator:** `npm run check`. **Test:** `npm test` and focused regressions. Existing runtime/pack smokes remain valid unless their boundaries change. |
14
+
15
+ ## Review items
16
+
17
+ | ID | Feedback and scope | Severity | Evidence at the reviewed head | Outcome |
18
+ | --- | --- | --- | --- | --- |
19
+ | R1 | Excluded keys remain in apply preimage assertions. This breaks the new exclusion/local-field composition in pull and rollback. | P2 | `sync-mutations.ts` supplies `settings.json: null` when collection omits the file. `applySnapshot()` maps that entry without exclusion filtering. `applySnapshotTransaction()` checks every expected preimage, including paths outside the mutation plan. | Already addressed. Excluded assertion keys are filtered with the existing matcher. Eleven regressions cover pull, forced pull, rollback, glob/case variants and included-file stale guards. Pi session-root metadata resolution is unchanged. |
20
+ | R2 | The manager calls an exclusion-only difference an order difference. This hides the reason that the new policy blocks sync. | P3 | `describeManagerState()` checks only the two include-difference arrays. The remote review, direct mismatch message and attention widget already compare exclusion rules. | Already addressed. The manager checks the canonical exclusion sets. It keeps path counts for membership changes, reports combined differences, and reserves order-only text for matching exclusions. The manager regression matrix passes. |
21
+ | R3 | Codex security review failed. The summary and account-limit comment describe the same external failure, not a supplied vulnerability. | Not a code severity | [Summary](https://github.com/narumiruna/pi-extensions/pull/1903#issuecomment-6890995358) says the review could not complete. [Account-limit notice](https://github.com/narumiruna/pi-extensions/pull/1903#issuecomment-6890995649) states that the payer reached Codex usage limits. No security finding text or inline thread was supplied. | Blocked: external review only. The paying account owner must restore capacity before that service can complete a review. Do not enable paid credits or repeat the service call as part of this fix. Independent code/security checks remain required. |
22
+ | R4 | The walkthrough links PR #1902 as a possible contract conflict. | None; no active conflict | GitHub reports #1902 as CLOSED with `mergedAt: null`. Current `main` has no merge of that alternative `.syncignore` design. Its head is not part of this target. | Outdated or superseded. Do not import the closed design or change this PR's approved version boundary. No separate issue is needed. |
23
+ | R5 | The manager's Sessions label uses include membership alone. This audit finding is in the same incomplete-summary class as R2 and is exposed by whole-session exclusions. | P3 | Other new summaries use `syncSessionsSelected()`, but the manager still reads `syncIncludeSelection(config.include).sessions`. A setup excluding `sessions/**` is displayed as Sessions on. | Already addressed. The label uses `syncSessionsSelected()`. Tests cover no exclusions, whole-session literal/glob exclusions and a partial session-file exclusion. |
24
+
25
+ The completed Codex code review reports no findings. CodeRabbit's risk summary repeats R1 and R2. Its architecture assessment and title checks add no further defect. Test-generation and autofix widgets are service controls, not approved instructions. Existing feature tests cover matching, transfer, lifecycle, metadata and recovery. The added tests cover the verified defects above.
26
+
27
+ ## Validation and publication
28
+
29
+ - Before the code fixes, the two new test files had 15 failures and four passes at `58cb3c5a`.
30
+ - After the fixes, all 19 tests pass. The broader local-field, manager, attention and resolution regression set passes all 379 tests.
31
+ - `npm run format` and `npm run check` pass. `npm test` passes 22,957 tests, with 18 existing conditional/platform skips and no unhandled errors.
32
+ - The complete original diff and review fix were checked for scope, security, compatibility and lifecycle safety. Only excluded preimage keys are omitted; included checks, queues, post-await guards and recovery rules remain active. No public version boundary, settings persistence policy or custom key handling changed.
33
+ - `npm run package:pack -- sync` passes and includes this ledger. A fresh RPC smoke verifies package registration, the corrected Sessions label, menu cancellation, the lazy files route and clean shutdown without a model or backend transfer.
34
+ - The existing feature Changeset still covers this unpublished PR. No package publication, tag or release workflow is part of the review fix.
35
+
36
+ This ledger travels with the review-fix commit on PR #1903. The closing PR comment records its commit and publication result. No inline review thread exists, so there is no Resolve API target. R3 remains an external service-capacity blocker, not a failed local test or a supplied vulnerability. No out-of-scope issue was created.
@@ -31,7 +31,7 @@ Writers queue the complete read-modify-write operation, hold the cross-process l
31
31
 
32
32
  ## Presentation decisions
33
33
 
34
- Selecting **Settings** in `/sync` opens **Pi Sync Settings** directly as one searchable flat list, with all 16 rows in their existing order and no category navigation or headings. Row values, descriptions, actions, reviews, and save behavior are unchanged. Typing searches the list. Back returns directly to the manager; hard Ctrl+C closes the flow. No `/ Search` hint is added because slash is ordinary search text.
34
+ Selecting **Settings** in `/sync` opens **Pi Sync Settings** directly as one searchable flat list, with 17 rows and no category navigation or headings. Included paths, Excluded paths, and Compare included paths keep both content policies together. Excluded paths has a transactional JSON-array draft and reviewed Save/Discard/Continue flow; other rows retain their existing actions and save behavior. Typing searches the list. Back returns directly to the manager; hard Ctrl+C closes the flow. No `/ Search` hint is added because slash is ordinary search text.
35
35
 
36
36
  The existing public Kit settings adapter is retained rather than adding a second selector or accessing private Pi fields. Installed `SettingsList` provides `updateValue()` and `selectItem()`, but has no injected keybinding or awaited-save/rejection contract and does not expose search focus. Kit already owns ordered pending changes, rollback, retained search/selection, IME focus, bounded frames, and clipped mouse coordinates. This is an intentional existing deviation from the literal native-component convention. No new Kit API, dependency floor, or release is required. A package-owned public rendering boundary returns no lines at zero width and retains the selected row (or search when nothing matches) below five content rows; compact mouse events map back to the original rendered row. It does not access private component state or add key handlers. Search placeholder and position-footer relocation remain unsupported by that public API; the existing native-style hints and position indicator are retained rather than patched through private fields.
37
37
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-sync",
3
- "version": "0.58.1",
3
+ "version": "0.59.0",
4
4
  "description": "Pi extension that syncs Pi configuration through Git, WebDAV, Cloudflare R2, or S3-compatible storage.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -48,6 +48,7 @@
48
48
  "dependencies": {
49
49
  "@narumitw/pi-tui-kit": "^0.70.0",
50
50
  "fast-xml-parser": "^5.12.0",
51
+ "minimatch": "^11.0.3",
51
52
  "proper-lockfile": "^4.1.2",
52
53
  "semver": "^7.8.6"
53
54
  },
@@ -14,9 +14,9 @@ This skill provides guidance only, even when the request asks you to apply a cha
14
14
 
15
15
  Read the relevant headings in the [settings reference](references/configuration.md), not the user's private settings file.
16
16
  Use **Settings ownership and required fields**, **Complete version 3 example**, and **Required backend shapes** for schema, backend, and destination questions.
17
- Use **Included content** for path selection and session privacy.
17
+ Use **Included content** and **Excluded paths** for path selection, exclusions, schema compatibility, and session privacy.
18
18
  Use **Required backend shapes**, **Automatic startup transfer**, **Autonomous sync**, and **Continuous sync** to distinguish automatic controls.
19
- Use **Settings field merge and machine-local fields** and **Content merge and partial progress** for versions 4 and 5.
19
+ Use **Settings field merge and machine-local fields**, **Content merge and partial progress**, and **Excluded paths** for the explicit version boundaries.
20
20
  Use **Diagnostics** and **Unsupported old settings and recovery** for diagnostic side effects and recovery boundaries.
21
21
  If the reference does not establish an answer, state the missing evidence instead of inventing a field, default, migration, or compatibility guarantee.
22
22
 
@@ -46,7 +46,8 @@ Explain session privacy, secret-scan bypass, autonomous writes, provider disclos
46
46
  Do not infer consent for one option from consent for another.
47
47
  Review the exact branch, bucket or collection, path, and included content in the proposed guidance before handing it off.
48
48
  Warn that Git owns the whole selected branch and that saving setup settings does not create a bucket/repository or transfer data.
49
- Keep first-source choice, changed include/local-field policies, conflicts, and force-direction migrations in their existing user-reviewed flows.
49
+ Keep first-source choice, changed include/exclude/local-field policies, conflicts, and force-direction migrations in their existing user-reviewed flows.
50
+ Explain that exclusions protect local files and omit matching paths from new publications, not retained history; removing rules can expose or replace content.
50
51
 
51
52
  ## Stop and hand off
52
53
 
@@ -10,6 +10,7 @@ The configuration skill provides guidance only; the user performs settings chang
10
10
  - [Autonomous sync](#autonomous-sync)
11
11
  - [Continuous sync](#continuous-sync)
12
12
  - [Included content](#included-content)
13
+ - [Excluded paths](#excluded-paths)
13
14
  - [Unsupported old settings and recovery](#unsupported-old-settings-and-recovery)
14
15
 
15
16
  ## ⚙️ Settings
@@ -46,15 +47,16 @@ Global settings apply to all setups on this device; they are not remote policy.
46
47
 
47
48
  | Scope | Fields | Required values and defaults |
48
49
  | --- | --- | --- |
49
- | Document | `version`, `onSwitch`, `storageConnections`, `syncSetups` | All are required in a manually written document; supported versions are 3, 4, and 5. |
50
+ | Document | `version`, `onSwitch`, `storageConnections`, `syncSetups` | All are required in a manually written document; supported versions are 3, 4, 5, and 6. |
50
51
  | Current setup | `activeSyncSetup` | Required when setups exist; absent when the setup catalog is empty. |
51
52
  | Global preferences | `skipSecretScan`, `showStatus`, `debug` | Optional booleans; defaults are false, true, and false. |
52
53
  | Setup selection | `sync.include`, `sync.automatic` | Both are required; the manager starts with automatic sync Off. |
53
54
  | Setup behavior | `sync.automaticTransfer`, `sync.agentMode`, `sync.continuous`, `sync.mergeSettings`, `sync.mergeContent`, `sync.partialSync` | Optional booleans; all default to false. |
54
- | Portable policy | `sync.localFields` | Optional array; any explicit array, including `[]`, requires version 4 or 5. |
55
- | Content/partial policy | `sync.mergeContent`, `sync.partialSync` | Enabling either requires version 5. |
55
+ | Portable policy | `sync.localFields` | Optional array; any explicit array, including `[]`, requires version 4, 5, or 6. |
56
+ | Content/partial policy | `sync.mergeContent`, `sync.partialSync` | Enabling either requires version 5 or 6. |
57
+ | Path exclusions | `sync.exclude` | Optional array; an explicit array, including `[]`, requires version 6. |
56
58
 
57
- Do not downgrade version 4 or 5 merely because an option is turned off.
59
+ Do not downgrade version 4, 5, or 6 merely because an option is turned off.
58
60
  The four automatic controls have separate effects:
59
61
 
60
62
  - **Automatic sync** (`sync.automatic`) enables startup observation and selected-content shutdown pushes when sessions are included.
@@ -67,8 +69,8 @@ None of these controls is enabled by invoking the configuration skill.
67
69
  ### Editing in the manager
68
70
 
69
71
  Open `/sync` → **Settings** to go directly to **Pi Sync Settings**.
70
- The screen has one searchable flat list with all 16 rows in their existing order and no category navigation or headings.
71
- **Included paths** and **Compare included paths** are adjacent; the latter compares path policies, not file contents.
72
+ The screen has one searchable flat list with 17 rows and no category navigation or headings.
73
+ **Included paths**, **Excluded paths**, and **Compare included paths** keep content policy together; comparison covers both rule lists, not file contents.
72
74
  **Storage location** edits the current setup's coordinates, while **Manage sync setups** and **Manage storage connections** retain the catalog and affected-setup reviews.
73
75
  Returning from catalog management refreshes the rows; switching or removing the owning setup closes its old Settings screen.
74
76
 
@@ -316,7 +318,8 @@ This preserves selected-but-missing paths without syncing `pi-sync.json`, storag
316
318
  Adoption revalidates the remote head, immutable snapshot, and complete reviewed setup configuration, including the shared connection and credentials, before one atomic settings update.
317
319
  Cancelling the network check leaves the content list unchanged.
318
320
  A settings save that has started its atomic replacement can still finish; later cancellation does not undo it.
319
- The saved state changes only `sync.include`, preserves unknown settings fields, and never pulls files or writes sync state.
321
+ The saved state changes `sync.include` and exclusion rules together, preserves unknown settings fields, and never pulls files or writes sync state.
322
+ Adopting an explicit remote exclude policy also reviews the version-6 upgrade; adopting a legacy no-exclude list clears existing rules to `[]` without downgrading.
320
323
  Its explicit Continue action starts a fresh **Sync now** route, while **Done** leaves the reviewed settings change saved without implying a file operation.
321
324
  Keeping this device's list opens the reviewed force-push path and explicitly replaces the remote policy while preserving eligible unmanaged remote files.
322
325
 
@@ -331,6 +334,59 @@ Adding `sessions` requires a privacy acknowledgement in interactive flows.
331
334
  Session JSONL can contain prompts, tool output, file paths, images, and secrets.
332
335
  Pull protects the currently open session file; restart Pi or resume a pulled session to use newly synchronized conversations.
333
336
 
337
+ ### Excluded paths
338
+
339
+ `sync.exclude` is an optional per-setup array of relative paths or basic glob patterns; absence means no rules.
340
+ An explicit array requires settings version 6 and publishes snapshot version 4 with selection policy version 2.
341
+ Other setups without an explicit array keep their existing snapshot format.
342
+ New clients still read old settings and snapshots; older clients must refuse the opted-in formats.
343
+
344
+ For an existing setup in a version-6 document, the `sync` object can contain:
345
+
346
+ ```json
347
+ {
348
+ "include": ["settings.json", "skills", "extensions"],
349
+ "exclude": ["skills/private", "extensions/**/*.test.ts"],
350
+ "automatic": false
351
+ }
352
+ ```
353
+
354
+ Rules win over includes and are anchored to the logical snapshot root, with `/` separators on every platform.
355
+ Literal paths match themselves and their descendants; `skills/private` does not match `skills/private-copy`.
356
+ `*` and `?` match within one segment; whole-segment `**` matches zero or more segments.
357
+ A matching directory excludes its whole subtree, including hidden files.
358
+ Matching is case-insensitive, includes dotfiles, and combines rules with OR, independent of rule order.
359
+ Use `**/*.log` for a filename pattern at any depth; `*.log` matches only at the root.
360
+ Sessions use virtual `sessions/...` paths even when stored in a custom physical directory.
361
+ A trailing `/**` also excludes its root; excluding `sessions` or `sessions/**` disables the legacy sessions-enabled shutdown push before state/backend work.
362
+
363
+ Negation/re-inclusion, comments, braces, character classes, extglobs, absolute/drive/UNC paths, traversal, backslashes, controls, empty rules, and case-equivalent duplicates are rejected.
364
+ The limits are 1,024 rules, 4,096 UTF-8 bytes per rule, and 256 KiB total.
365
+ Overlapping rules and rules for currently absent or unselected paths are allowed.
366
+ This syntax is not Git ignore compatibility and does not load an ignore file.
367
+
368
+ **Settings → Excluded paths** uses a JSON-array draft and an exact **Save changes**, **Discard changes**, or **Continue editing** review.
369
+ Empty input keeps the current draft; `[]` clears rules.
370
+ Only Save writes settings and upgrades to version 6; cancelling or a stale/failed save leaves the previous valid settings intact.
371
+ Changes apply to subsequent operations and do not start a transfer.
372
+ The canonical user file is the only scope; no project override or environment-variable mirror is added.
373
+ RPC remains read-only and shows the manual settings path.
374
+
375
+ Collection skips excluded content before reading its bytes and prunes excluded directories.
376
+ Pi's own session-directory configuration may still need to be read to resolve a session root; exclusions do not replace Pi configuration resolution.
377
+ Push, pull, merged/automatic sync, previews, rollback, accepted hashes, conflict/model evidence, and watcher hints honor the same rules.
378
+ Excluded local files are not overwritten or deleted; ancestor replacements that would remove excluded descendants are refused.
379
+ New publications omit matching remote files even if those files were previously preserved, while other unselected remote content retains its preservation behavior.
380
+ Old history and backups are **not erased**.
381
+
382
+ Comparison and adoption include both lists, even when no matching file exists.
383
+ Ordinary and automatic transfers, including forced pull, pause on a remote-policy difference.
384
+ Review the rules and use the existing confirmed force push to publish this device's authoritative policy.
385
+ Removing a rule can expose local content or permit remote replacement.
386
+ Clearing rules retains `[]` and the newer versions; never downgrade in place.
387
+ A pending transaction or merge journal under different rules remains available for reviewed recovery rather than replaying old writes.
388
+ To return to an older client, stop automatic work, resolve pending recovery with a compatible client, preserve backups, and create a separate reviewed legacy-compatible setup/location.
389
+
334
390
  ### Automatic startup transfer
335
391
 
336
392
  `sync.automaticTransfer` is optional and accepts only a boolean; absent means `false`.
@@ -366,7 +422,7 @@ Unknown fields remain preserved and malformed/invalid files block saves, just as
366
422
 
367
423
  ### Autonomous sync
368
424
 
369
- Autonomous sync uses the unchanged `sync.agentMode` key, an optional per-setup boolean, default `false`, in settings versions 3, 4, and 5.
425
+ Autonomous sync uses the unchanged `sync.agentMode` key, an optional per-setup boolean, default `false`, in settings versions 3, 4, 5, and 6.
370
426
  Open **Settings → Autonomous sync** and review the setup, destination, selected paths, transfer authorization, model disclosure, costs, and autonomous writes before enabling.
371
427
  RPC users can explicitly set the same field in the private settings file.
372
428
  Setting it to `true` is authorization, not just a display preference.
@@ -467,7 +523,7 @@ No Pi core changes or other extension are required.
467
523
 
468
524
  ### Continuous sync
469
525
 
470
- `sync.continuous` is an optional per-setup boolean, default `false`, in settings versions 3, 4 and 5.
526
+ `sync.continuous` is an optional per-setup boolean, default `false`, in settings versions 3, 4, 5 and 6.
471
527
  Open **Settings → Continuous sync** after enabling Autonomous sync.
472
528
  RPC users can set the field explicitly in the private settings file.
473
529
  Existing Autonomous sync consent does not enable recurring requests.
@@ -601,9 +657,11 @@ Field merging and nonempty portable projections also refuse unsafe integers, non
601
657
  Example: `"localFields": ["shellPath"]`.
602
658
  Coupled fields must be excluded together.
603
659
  Nonempty rules require `settings.json` in `sync.include`; absent or explicitly empty rules remain valid for other selections.
604
- Saving nonempty rules in Settings confirms an upgrade to settings version 4; manual edits must declare version 4 too.
660
+ Saving nonempty rules in Settings confirms an upgrade to at least settings version 4; manual edits must declare version 4 or newer.
661
+ Existing version-5/6 settings are never downgraded by a field-policy edit.
605
662
  Absent rules keep a setup nonportable, including unrelated setups in a version-4 document.
606
- An explicit array opts that setup into snapshot version 2; `[]` after rule removal retains this reviewed opt-in and differs from absence.
663
+ An explicit array opts that setup into at least snapshot version 2; exclude-enabled setups retain version 4.
664
+ `[]` after rule removal retains this reviewed opt-in and differs from absence.
607
665
  Older clients must refuse portable data rather than replace local-only values.
608
666
 
609
667
  Portable projections normalize remote JSON deterministically while local overlay preserves unaffected local member/value bytes and excluded values or absence.
@@ -640,8 +698,9 @@ Never reinterpret portable snapshots with an old binary.
640
698
  ### Content merge and partial progress
641
699
 
642
700
  `sync.mergeContent` and `sync.partialSync` are independent opt-in booleans, both default `false`.
643
- The owning **Settings → Content merge / partial progress** setting offers Off, Merge only, Merge + partial, and Partial only and confirms an explicit settings-version-5 upgrade.
644
- Manual configuration must also declare version 5.
701
+ The owning **Settings → Content merge / partial progress** setting offers Off, Merge only, Merge + partial, and Partial only and confirms an explicit upgrade to at least settings version 5.
702
+ Manual configuration must also declare version 5 or 6.
703
+ Exclude-enabled partial publications retain snapshot version 4 instead of downgrading to version 3.
645
704
  Settings version 5 retains the portable-policy behavior of version 4; moving from a legacy setup can require the existing separately confirmed directional policy migration.
646
705
  Disabling options retains the schema and recovery evidence.
647
706
 
@@ -1,7 +1,12 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import type { Snapshot, SnapshotSelection } from "../../snapshot/snapshot-types.js";
3
3
  import { sameLocalFields, validatePortableSnapshot, validateSnapshotFieldPolicy } from "../../sync/local-fields.js";
4
- import { portableSnapshotSelection, snapshotSelectionInclude } from "../../sync/sync-policy.js";
4
+ import {
5
+ portableSnapshotSelection,
6
+ sameSnapshotSelection,
7
+ snapshotSelectionInclude,
8
+ validateSnapshotSelection,
9
+ } from "../../sync/sync-policy.js";
5
10
 
6
11
  export const GIT_MANIFEST_VERSION = 2;
7
12
  export const MAX_GIT_MANIFEST_BYTES = 1024 * 1024;
@@ -56,7 +61,10 @@ export function requireGitManifest(value: unknown): GitManifest {
56
61
  }
57
62
  if (
58
63
  manifest.version !== GIT_MANIFEST_VERSION ||
59
- (manifest.snapshotVersion !== 1 && manifest.snapshotVersion !== 2 && manifest.snapshotVersion !== 3) ||
64
+ (manifest.snapshotVersion !== 1 &&
65
+ manifest.snapshotVersion !== 2 &&
66
+ manifest.snapshotVersion !== 3 &&
67
+ manifest.snapshotVersion !== 4) ||
60
68
  typeof manifest.snapshotId !== "string" ||
61
69
  manifest.snapshotId.length > 512 ||
62
70
  !/^[A-Za-z0-9._-]+$/u.test(manifest.snapshotId) ||
@@ -92,6 +100,7 @@ export function requireGitManifest(value: unknown): GitManifest {
92
100
  }
93
101
  validateSnapshotFieldPolicy({ version: manifest.snapshotVersion, localFields: manifest.localFields });
94
102
  if (manifest.selection !== undefined) portableSnapshotSelection(manifest.selection);
103
+ validateSnapshotSelection({ version: manifest.snapshotVersion, selection: manifest.selection });
95
104
  let total = 0;
96
105
  const paths = new Set<string>();
97
106
  for (const rawFile of manifest.files) {
@@ -133,10 +142,7 @@ export function validateGitSnapshot(snapshot: Snapshot, manifest: GitManifest, n
133
142
  snapshot.profile !== manifest.profile ||
134
143
  snapshot.syncSessions !== manifest.snapshotSyncSessions ||
135
144
  syncSessions !== manifest.syncSessions ||
136
- !sameOptionalInclude(
137
- snapshotSelectionInclude(snapshot),
138
- manifest.selection === undefined ? undefined : portableSnapshotSelection(manifest.selection).include,
139
- ) ||
145
+ !sameSnapshotSelection(snapshot.selection, manifest.selection) ||
140
146
  prepared.length !== manifest.files.length ||
141
147
  prepared.some((file, index) => {
142
148
  const expected = manifest.files[index];
@@ -246,11 +252,6 @@ export function validateGitPublicationTree(
246
252
  return manifest.files.map((file) => byPath.get(filePath(file.path)) as GitTreeEntry);
247
253
  }
248
254
 
249
- function sameOptionalInclude(left: string[] | undefined, right: string[] | undefined) {
250
- if (!left || !right) return left === right;
251
- return left.length === right.length && left.every((item, index) => item === right[index]);
252
- }
253
-
254
255
  function isSafeSnapshotPath(value: unknown): value is string {
255
256
  return (
256
257
  typeof value === "string" &&