@narumitw/pi-sync 0.62.0 → 0.63.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +40 -23
  3. package/dist/chunks/{chunk-MNYRU5U5.ts → chunk-27F5W7DX.ts} +3 -2
  4. package/dist/chunks/{chunk-MNYRU5U5.ts.map → chunk-27F5W7DX.ts.map} +2 -2
  5. package/dist/chunks/{chunk-INECVQNR.ts → chunk-B5F3JLD3.ts} +6 -4
  6. package/dist/chunks/chunk-B5F3JLD3.ts.map +7 -0
  7. package/dist/chunks/chunk-CKUGCBHP.ts +114 -0
  8. package/dist/chunks/chunk-CKUGCBHP.ts.map +7 -0
  9. package/dist/chunks/chunk-EJDDRS6O.ts +17 -0
  10. package/dist/chunks/chunk-EJDDRS6O.ts.map +7 -0
  11. package/dist/chunks/{chunk-6PFZUEUG.ts → chunk-EXDWEFIJ.ts} +52 -135
  12. package/dist/chunks/chunk-EXDWEFIJ.ts.map +7 -0
  13. package/dist/chunks/{chunk-NHFGAZEC.ts → chunk-HSCAFOT5.ts} +7 -7
  14. package/dist/chunks/chunk-HSCAFOT5.ts.map +7 -0
  15. package/dist/chunks/{chunk-ZB3GNX3P.ts → chunk-LBNC5AOM.ts} +140 -13
  16. package/dist/chunks/chunk-LBNC5AOM.ts.map +7 -0
  17. package/dist/chunks/chunk-MANNB4WZ.ts +36 -0
  18. package/dist/chunks/chunk-MANNB4WZ.ts.map +7 -0
  19. package/dist/chunks/{chunk-GSQGBVKG.ts → chunk-POWOMJ7S.ts} +87 -50
  20. package/dist/chunks/chunk-POWOMJ7S.ts.map +7 -0
  21. package/dist/chunks/{chunk-PWESMTH6.ts → chunk-SXCH4Q5O.ts} +38 -20
  22. package/dist/chunks/chunk-SXCH4Q5O.ts.map +7 -0
  23. package/dist/chunks/{chunk-3E3TR3JE.ts → chunk-V76KCWHO.ts} +6 -4
  24. package/dist/chunks/{chunk-3E3TR3JE.ts.map → chunk-V76KCWHO.ts.map} +1 -1
  25. package/dist/chunks/{chunk-GSCZ4VXV.ts → chunk-VQ47JBLF.ts} +2 -2
  26. package/dist/chunks/chunk-WFBHWYI6.ts +18 -0
  27. package/dist/chunks/chunk-WFBHWYI6.ts.map +7 -0
  28. package/dist/chunks/{command-handler-6ATREPG7.ts → command-handler-GMRRFWOL.ts} +19 -36
  29. package/dist/chunks/command-handler-GMRRFWOL.ts.map +7 -0
  30. package/dist/chunks/{conflict-review-MAOGTIAI.ts → conflict-review-JWEA7DPQ.ts} +2 -2
  31. package/dist/chunks/{file-selection-QR2KZVGD.ts → file-selection-KID23GAD.ts} +15 -8
  32. package/dist/chunks/file-selection-KID23GAD.ts.map +7 -0
  33. package/dist/chunks/{manager-result-dispatcher-MC6EQOQY.ts → manager-result-dispatcher-GDB74IOP.ts} +6 -5
  34. package/dist/chunks/{manager-ui-AOFUNXAJ.ts → manager-ui-T5J5WG7T.ts} +227 -343
  35. package/dist/chunks/manager-ui-T5J5WG7T.ts.map +7 -0
  36. package/dist/chunks/{merge-review-SGDLMVS4.ts → merge-review-OQDXNTJU.ts} +2 -2
  37. package/dist/chunks/{remote-selection-ui-4BTP2OJR.ts → remote-selection-ui-GPITNEBF.ts} +5 -4
  38. package/dist/chunks/{setup-switch-Y6AMFFNK.ts → setup-switch-L54X5U5I.ts} +4 -4
  39. package/dist/chunks/{setup-wizard-5G426MOZ.ts → setup-wizard-LL6YMGUR.ts} +7 -3
  40. package/dist/chunks/{setup-wizard-5G426MOZ.ts.map → setup-wizard-LL6YMGUR.ts.map} +1 -1
  41. package/dist/chunks/{sync-inspection-ITZ6Z4DE.ts → sync-inspection-SRU6HGGK.ts} +3 -3
  42. package/dist/chunks/{sync-operations-NMVKF7SE.ts → sync-operations-UGSCONZ7.ts} +2 -2
  43. package/dist/daemon/dist/cli.js +1 -1
  44. package/dist/daemon/dist/consent.js +134 -16
  45. package/dist/daemon/dist/engine/backends/git/git-backend.js +61 -30
  46. package/dist/daemon/dist/engine/ignore/ignore-initialization.js +142 -40
  47. package/dist/daemon/dist/engine/ignore/ignore-settings.js +94 -26
  48. package/dist/daemon/dist/engine/ignore/ignore-source.js +1 -1
  49. package/dist/daemon/dist/engine/settings/config-file.js +1 -1
  50. package/dist/daemon/dist/engine/settings/config.js +71 -28
  51. package/dist/daemon/dist/engine/settings/settings-management.js +8 -2
  52. package/dist/daemon/dist/engine/snapshot/session-paths.js +7 -2
  53. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-policy.js +37 -17
  54. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +55 -13
  55. package/dist/daemon/dist/engine/sync/agent-plan.js +1 -0
  56. package/dist/daemon/dist/engine/sync/agent-sync.js +8 -1
  57. package/dist/daemon/dist/engine/sync/continuous-sync.js +32 -15
  58. package/dist/daemon/dist/engine/sync/merge-acceptance.js +29 -0
  59. package/dist/daemon/dist/engine/sync/merge-apply.js +7 -4
  60. package/dist/daemon/dist/engine/sync/merge-journal.js +33 -14
  61. package/dist/daemon/dist/engine/sync/merged-sync.js +31 -39
  62. package/dist/daemon/dist/engine/sync/remote-snapshot.js +17 -2
  63. package/dist/daemon/dist/engine/sync/session-push.js +20 -6
  64. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +16 -3
  65. package/dist/daemon/dist/engine/sync/sync-mutations.js +75 -54
  66. package/dist/daemon/dist/engine/sync/sync-policy.js +28 -3
  67. package/dist/daemon/dist/engine/sync/sync-state.js +3 -8
  68. package/dist/daemon/dist/engine/sync/transfer-freshness.js +82 -0
  69. package/dist/daemon/dist/engine/ui/sync-format.js +23 -55
  70. package/dist/daemon/dist/engine/ui/transfer-review.js +3 -3
  71. package/dist/daemon/dist/engine-service.js +124 -27
  72. package/dist/daemon/dist/monitor.js +84 -32
  73. package/dist/daemon/dist/server.js +46 -5
  74. package/dist/daemon/dist/service-host.js +2 -1
  75. package/dist/daemon/package.json +1 -1
  76. package/dist/index.ts +28 -25
  77. package/dist/index.ts.map +4 -4
  78. package/docs/tui-contract.md +1 -1
  79. package/package.json +3 -3
  80. package/skills/configure-pi-sync/SKILL.md +128 -74
  81. package/skills/configure-pi-sync/references/configuration.md +115 -45
  82. package/src/commands/command-execution.ts +12 -8
  83. package/src/commands/command-types.ts +1 -0
  84. package/src/daemon/pi-client.ts +4 -2
  85. package/src/settings/config.ts +1 -0
  86. package/src/sync/automatic-sync.ts +9 -2
  87. package/src/sync/setup-switch.ts +38 -15
  88. package/src/sync/startup-check.ts +7 -4
  89. package/src/ui/excluded-paths-ui.ts +2 -2
  90. package/src/ui/file-selection.ts +7 -2
  91. package/src/ui/ignore-file-guidance.ts +7 -0
  92. package/src/ui/ignore-file-ui.ts +28 -202
  93. package/src/ui/manager-state.ts +33 -18
  94. package/src/ui/manager-ui.ts +27 -18
  95. package/src/ui/merge-review.ts +28 -1
  96. package/src/ui/remote-selection-ui.ts +51 -24
  97. package/src/ui/settings-ui.ts +132 -81
  98. package/src/ui/setup/setup-actions.ts +16 -4
  99. package/src/ui/setup/setup-prompts.ts +55 -9
  100. package/src/ui/setup/setup-switcher.ts +24 -11
  101. package/src/ui/setup/webdav-ui.ts +1 -1
  102. package/src/ui/storage-connections-ui.ts +33 -11
  103. package/src/ui/sync-confirmation.ts +67 -48
  104. package/src/ui/sync-setups-ui.ts +24 -7
  105. package/dist/chunks/chunk-6PFZUEUG.ts.map +0 -7
  106. package/dist/chunks/chunk-ECYCNZOE.ts +0 -12
  107. package/dist/chunks/chunk-ECYCNZOE.ts.map +0 -7
  108. package/dist/chunks/chunk-GSQGBVKG.ts.map +0 -7
  109. package/dist/chunks/chunk-INECVQNR.ts.map +0 -7
  110. package/dist/chunks/chunk-NHFGAZEC.ts.map +0 -7
  111. package/dist/chunks/chunk-PWESMTH6.ts.map +0 -7
  112. package/dist/chunks/chunk-ZB3GNX3P.ts.map +0 -7
  113. package/dist/chunks/command-handler-6ATREPG7.ts.map +0 -7
  114. package/dist/chunks/file-selection-QR2KZVGD.ts.map +0 -7
  115. package/dist/chunks/manager-ui-AOFUNXAJ.ts.map +0 -7
  116. /package/dist/chunks/{chunk-GSCZ4VXV.ts.map → chunk-VQ47JBLF.ts.map} +0 -0
  117. /package/dist/chunks/{conflict-review-MAOGTIAI.ts.map → conflict-review-JWEA7DPQ.ts.map} +0 -0
  118. /package/dist/chunks/{manager-result-dispatcher-MC6EQOQY.ts.map → manager-result-dispatcher-GDB74IOP.ts.map} +0 -0
  119. /package/dist/chunks/{merge-review-SGDLMVS4.ts.map → merge-review-OQDXNTJU.ts.map} +0 -0
  120. /package/dist/chunks/{remote-selection-ui-4BTP2OJR.ts.map → remote-selection-ui-GPITNEBF.ts.map} +0 -0
  121. /package/dist/chunks/{setup-switch-Y6AMFFNK.ts.map → setup-switch-L54X5U5I.ts.map} +0 -0
  122. /package/dist/chunks/{sync-inspection-ITZ6Z4DE.ts.map → sync-inspection-SRU6HGGK.ts.map} +0 -0
  123. /package/dist/chunks/{sync-operations-NMVKF7SE.ts.map → sync-operations-UGSCONZ7.ts.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # @narumitw/pi-sync
2
2
 
3
+ ## 0.63.1
4
+
5
+ ### Patch Changes
6
+
7
+ - fc5228d: Make the configuration skill verify the active ignore file with the existing local daemon before editing it. Stop on older daemon builds, and leave settings changes that require consent or policy review in `/sync`.
8
+ - 9d382d1: Show the active setup in the sync menu heading and include the configured path in R2/S3 and Git storage summaries.
9
+ - fc80c0c: Keep directional confirmation summaries short when a running older daemon still sends the full file list as the summary. Exact paths remain available in View details.
10
+ - f1dc5d2: Add guidelines and local verification workflows to `/skill:configure-pi-sync` for drafting, editing, and auditing `.syncignore` rules. Keep file creation, activation, and transfer approval in the user-reviewed Pi Sync flows.
11
+ - eb17fcc: Explain how to reduce sync scope when the agent-directory scan exceeds its limit. Replace outdated Check setup directions with current Diagnostics and storage settings paths.
12
+ - 26f8c59: Let `/skill:configure-pi-sync` apply requested local edits to `pi-sync.json` and the active ignore file, and investigate sync errors before suggesting changes. Keep transfers and other reviewed operations in `/sync`.
13
+ - aa99878: Let Up and Down select sync confirmation actions immediately. Show directional counts and safety notes in the summary, with exact file paths available in View details instead of requiring a scroll through the entire file list.
14
+ - 8e32b4b: Exclude top-level `git/` package checkouts in new `.syncignore` starter files and list the starter rules in alphabetical order. Preserve existing rule files and recover interrupted creation with its original rules.
15
+
16
+ ## 0.63.0
17
+
18
+ ### Minor Changes
19
+
20
+ - 5dfa289: Use local `.syncignore` rules for new TUI setups. Keep existing setup policies until the user reviews and confirms migration. Review the scope before transferring, upgrade peers before publishing version 6 snapshots, and edit existing rule files locally. Setup, migration, and rule-file switching do not start or authorize a transfer, and exclusions do not erase retained history. The bundled configuration skill can edit an explicitly identified local rule file on request; it no longer edits private JSON settings.
21
+
22
+ ### Patch Changes
23
+
24
+ - 25777f7: Read Git history manifests in bounded batches to reduce subprocess launches. Keep the same history preview and validate all retained publications in the original order.
25
+ - e3f2537: Keep the `/sync help` route from loading the interactive ignore-file editor or a second Pi TUI runtime from the extension install.
26
+ - Updated dependencies [1cbb470]
27
+ - @narumitw/pi-tui-kit@0.71.0
28
+
3
29
  ## 0.62.0
4
30
 
5
31
  ### Minor Changes
package/README.md CHANGED
@@ -17,7 +17,7 @@ Reusable storage connections hold credentials, while named sync setups define ex
17
17
  - Writes settings atomically, preserves unknown fields, rejects stale edits, and fails closed on unsafe configuration.
18
18
  - Offers default-off Autonomous sync for eligible startup and Sync now transfers without another transfer confirmation, with model-assisted conflict resolution and a separate Continuous sync opt-in.
19
19
  - Shares one detached synchronization service across Pi clients, with a generated split UI client runtime.
20
- - Bundles an on-demand skill for agent-assisted settings edits and configuration questions.
20
+ - Bundles an on-demand skill for configuration questions and scoped edits to a known local ignore file.
21
21
 
22
22
  ## 📦 Install
23
23
 
@@ -61,10 +61,10 @@ All new setups default to storage path `./`: the Git repository root, the WebDAV
61
61
  Git also suggests branch `main`.
62
62
  Use different folders or prefixes for independent setups sharing a WebDAV collection or bucket; existing settings and paths are unchanged.
63
63
  If another configured setup already uses the chosen location, setup asks for a different path before the content selection and review; Git requires a different branch, even when the directory differs.
64
- New setups default to the Pi agent directory. All eligible files are selected except `sessions/`, `bin/`, and `npm/`; you can review and change these rules before starting a transfer. Sessions require explicit opt-in. Automatic sync is off unless you enable it. Choose **Join an existing remote** to save with both options off and then review its policy, without transferring files. Selected-path setups remain available for compatibility.
64
+ With ignore-file support available, new TUI setups start with eligible files in the Pi agent directory and use `.syncignore` to exclude paths. Sessions require separate opt-in and must also be allowed by the rules. Automatic sync starts off. Choose **Join an existing remote** to save with sessions and automatic sync off, then review the remote policy. Existing setups keep their policy unless you migrate them.
65
65
  Before saving, review the exact destination, scope and rules, automatic-sync choice, and hidden-credential summary. R2/S3 always asks for an existing bucket; an example bucket name is not a default.
66
66
 
67
- Invalid fields ask for a correction without restarting setup. A temporary local save failure keeps the review for another Save; changed settings require reopening and reviewing the current values. Saving only changes local settings, not remote data. A connection saved through **Add a new storage connection…** remains saved if you later cancel the setup.
67
+ Invalid fields ask for a correction without restarting setup. A temporary local save failure keeps the review for another Save; changed settings require reopening and reviewing the current values. Saving writes local settings and may create a starter rule file. It does not start a transfer or grant permission for one. A connection saved through **Add a new storage connection…** remains saved if you later cancel the setup.
68
68
 
69
69
  Buckets and remote repositories must already exist.
70
70
  Git uses existing non-interactive SSH or credential-helper configuration and never stores Git credentials.
@@ -74,11 +74,11 @@ WebDAV and R2/S3 store `latest.json`, `history.json`, and `snapshots/` directly
74
74
 
75
75
  ## 🧭 Manager, conflicts, and recovery
76
76
 
77
- The `/sync` manager opens a searchable action palette in TUI mode, with up to five visible choices and help for only the selected action. Its compact summary uses local state without contacting remote storage:
77
+ The `/sync` manager opens a searchable action palette in TUI mode, with up to five visible choices and help for only the selected action. The heading identifies the active setup without relying on the summary, which can be hidden in a short terminal. The summary uses local state without contacting remote storage and shows the configured storage path:
78
78
 
79
79
  ```text
80
- Current sync setup: home
81
- Storage: Cloudflare R2 · r2 · personal-pi
80
+ Manage sync · home
81
+ Storage: Cloudflare R2 · r2 · personal-pi · pi-sync/home
82
82
  Remote status: Not checked
83
83
  Last applied: Never synced
84
84
  ```
@@ -90,7 +90,7 @@ The summary distinguishes cached observations, recorded background state, and th
90
90
  After Pi Sync detects an included-content mismatch, the manager shows **Sync status: Review needed** and puts **Review synced content (recommended)** first.
91
91
  **Sync now** remains unavailable until you review the mismatch.
92
92
  Opening the manager does not make another remote request.
93
- **Settings** opens **Pi Sync Settings** directly: one searchable flat list with 17 rows and no category navigation or headings. **Included paths**, **Excluded paths**, and **Compare included paths** keep content policy together; comparison covers include/exclude rules, not file contents. **Storage location** edits only the current setup's bucket, branch, or path; it does not change the connection or included content. **Manage sync setups** and **Manage storage connections** open the existing catalogs. Connections hold reusable server addresses and sign-in details, and edits show every affected setup. Make another setup current before changing its preferences. Each description identifies the setup, device-wide, or shared-connection scope. Simple preferences report saving and durable save results; Back does not undo saved changes. Complex editors and risky changes retain their reviews. RPC reports the manual settings path and preserves catalog management without opening the TUI preference editor.
93
+ **Settings** opens **Pi Sync Settings** directly as one searchable list. It shows the content-policy controls for the current setup. For an ignore-file setup, **Compare sync policies** compares policy, not file contents, and cannot apply a remote policy. Legacy setups retain their existing content-list review. **Storage location** edits only the current setup's bucket, branch, or path; it does not change the connection or included content. **Manage sync setups** and **Manage storage connections** open the existing catalogs. Connections hold reusable server addresses and sign-in details, and edits show every affected setup. Make another setup current before changing its preferences. Each description identifies the setup, device-wide, or shared-connection scope. Simple preferences report saving and durable save results; Back does not undo saved changes. Complex editors and risky changes retain their reviews. RPC reports the manual settings path and preserves catalog management without opening the TUI preference editor.
94
94
 
95
95
  With Continuous sync configured, **Diagnostics** first opens a scrollable local report containing scheduler ownership, request limits, accounting, and recovery guidance. Back returns without running backend checks; continuing retains a separate backend-check confirmation. RPC presents bounded report pages. `/sync doctor` remains the direct configuration and backend-check route. S3/R2 performs a read-only request: success does not prove write access or snapshot validity, and an ambiguous 404 does not prove a bucket is missing. Check the indicated credentials, address, bucket, or path before retrying. Git checks remote reads and the local cache, not write access. WebDAV uses an isolated write/cleanup probe and repairs the active snapshot's history entry if missing. **History** opens the snapshot list directly for reviewed rollback. Recorded unresolved groups have a separate **Review unresolved conflicts** action.
96
96
 
@@ -100,11 +100,11 @@ Destructive, credential-bearing, and externally visible operations show exact pr
100
100
 
101
101
  ### Review transfer changes
102
102
 
103
- Unless Autonomous sync or another explicit transfer authorization applies, a merged **Sync now** transfer shows one confirmation with separate local and remote file changes, remote snapshot publication, session inclusion, and unresolved groups. **No, cancel** is initially selected in TUI mode. On short or narrow terminals, the configured navigation keys first scroll the summary. **Yes** can apply changes only after every summary row has been displayed. A terminal resize resets the review and selects **No**. Cancellation remains available throughout. This scrollable summary intentionally replaces Kit's clipped choice context, and the safe default differs from Pi's native Yes-first confirmation.
103
+ Unless Autonomous sync or another explicit transfer authorization applies, a merged **Sync now** transfer shows one confirmation with separate local and remote file changes, remote snapshot publication, session inclusion, and unresolved groups. **No, cancel** is initially selected in TUI mode. Up and Down select actions without scrolling the summary. If the summary does not fit, use Page Up and Page Down (or their configured selection-page bindings) to review it before confirming **Yes**. A terminal resize resets the review and selects **No**. Cancellation remains available throughout. This scrollable summary intentionally replaces Kit's clipped choice context, and the safe default differs from Pi's native Yes-first confirmation.
104
104
 
105
105
  **View details** is optional. It shows the complete add/update/delete lists and unresolved paths in an exact scrolling review, or bounded pages in RPC. The review cannot apply changes. Back or Escape returns to confirmation with **No** selected; Ctrl+C cancels the whole TUI flow. RPC offers No first but the client controls visual selection, and protocol cancellation from details returns to confirmation. Session replacement or shutdown closes the flow; local files and remote state are rechecked before transfer.
106
106
 
107
- Unresolved paths stay unchanged on each side. A backup and recovery journal protect the transfer; resources do not reload automatically. Remote snapshot publication is shown separately because it can occur without file-content changes. File lists on the main screen are shortened when needed; details retain every path. `--yes` and automatic-transfer policy are unchanged. Interactive TUI Push and Pull use the same safe-default scrollable confirmation with exact directional add/update/remove counts and paths. Loaded sessions are excluded from local change counts. Pull and rollback also list case-variant path cleanup; changed aliases invalidate approval. Push describes changes to the active immutable snapshot, not physical deletion of retained history. RPC and History rollback keep their existing confirmation protocols, with the complete directional summary. Local bytes, settings, baseline, and remote head are rechecked before applying a reviewed transfer.
107
+ Unresolved paths stay unchanged on each side. A backup and recovery journal protect the transfer; resources do not reload automatically. Remote snapshot publication is shown separately because it can occur without file-content changes. File lists on the main screen are shortened when needed; details retain every path. `--yes` does not bypass a required policy-transition review. Automatic transfers require their own authorization and a compatible policy. Interactive TUI Push and Pull show directional add/update/remove counts and safety notes in the summary. Individual file paths are in **View details**, so a large file list does not delay confirmation. Loaded sessions are excluded from local change counts. Pull and rollback also list case-variant path cleanup; changed aliases invalidate approval. Push describes changes to the active immutable snapshot, not physical deletion of retained history. RPC and History rollback keep their existing confirmation protocols, with the complete directional summary. Local bytes, settings, baseline, and remote head are rechecked before applying a reviewed transfer.
108
108
 
109
109
  ### Restore sync access
110
110
 
@@ -172,11 +172,9 @@ Print and JSON modes do not support `/sync` because UI output is not observable
172
172
 
173
173
  Run `/sync` → **Set up sync** to create the canonical private user file at `<getAgentDir()>/pi-sync.json` (normally `~/.pi/agent/pi-sync.json`).
174
174
  Use **Settings** to manage an existing setup.
175
- Missing settings stay unconfigured without creating files or locks. Ignore-file transfers and daemon rule-file saves are not enabled. If a setup already references an ignore file, **Settings** shows the rule-file path for manual editing. In RPC mode, it also shows the active settings file, including `pi-sync.local.json` if it supplied the settings, without renaming it.
175
+ Missing settings stay unconfigured without creating files or locks. Legacy and ignore-file setups can share a settings document. Reviewed migration and rule-file switching require the canonical `pi-sync.json`; they do not promote `pi-sync.local.json` themselves.
176
176
 
177
- If any setup references an ignore file, transfers and policy comparison are unavailable for all setups in that document. You can still inspect the setup catalog, but switching or removal can be unavailable. To return to legacy transfers, close Pi and back up the active settings file and any pending recovery journal and backup. Remove the unsupported setup entries or restore a known-good legacy-only settings document. If you remove the current setup, update `activeSyncSetup` to a remaining setup, or omit it if none remain. Do not delete pending recovery files.
178
-
179
- Directory scope selects all eligible files, applies `exclude`, then restores matches from `reinclude`. Pi login credentials, project trust, and Pi Sync's own state stay local regardless of those rules. Folder-wide sync may include private files that the secret scan cannot identify. Review the content before transferring to a trusted destination. Existing setups keep their selected paths and are not migrated automatically. See [Agent-directory scope](./skills/configure-pi-sync/references/configuration.md#agent-directory-scope) for formats, precedence, and recovery.
177
+ Legacy directory scope selects all eligible files, applies `exclude`, then restores matches from `reinclude`. Pi login credentials, project trust, and Pi Sync's own state stay local regardless of those rules. Folder-wide sync may include private files that the secret scan cannot identify. Review the content before transferring to a trusted destination. Existing setups keep their selected paths and are not migrated automatically. See [Agent-directory scope](./skills/configure-pi-sync/references/configuration.md#agent-directory-scope) for formats, precedence, and recovery.
180
178
 
181
179
  ### Debug startup timings
182
180
 
@@ -214,6 +212,10 @@ Ordinary **Sync now** reuses a cached refusal. Use **Retry refused model result
214
212
 
215
213
  ### Continuous sync
216
214
 
215
+ When any setup in the document uses an ignore file, first enable the automatic modes you want, then use **Settings → Review automatic transfers** to authorize those modes for the current policy. Saving or switching a setup does not grant permission or start a transfer. Settings and rule-file changes require a new review; work after the last Pi exits still requires its own authorization.
216
+
217
+ Removing the last ignore-file setup does not resume Continuous sync in the already attached sessions. To resume it if enabled, close `/sync` and run `/reload` in an attached TUI session, or close and reopen one Pi client.
218
+
217
219
  **Settings → Continuous sync** controls separate per-setup `sync.continuous`, default **Off**. Autonomous sync must also be enabled. A separate review authorizes recurring network access, model costs and automatic transfers while Pi is open. Upgrade all Pi processes sharing the agent directory before enabling it. Monitoring starts after the `/sync` command or manager closes, and replaces the duplicate one-shot startup transfer.
218
220
 
219
221
  Selected-file hints are coalesced after one quiet second. A 60–66 second remote/local check covers missed events. Temporary failures and proven pre-publication edit races use bounded backoff. Removing flagged secret content or repairing unsupported conflicts permits a fresh inspection; unchanged blocks do not repeatedly call the model. One daemon owns monitoring for each shared canonical agent directory; each computer remains a separate replica. Busy sessions and foreground commands release ownership after draining work. After the last registered live client PID for the canonical agent directory exits, the service starts a fixed 30-second grace period unless a valid active-setup after-exit grant keeps it running, then drains work before safe exit. Live passive, disconnected, publishing, and orderly retired PIDs still count; `/reload`, `/new`, fork, and resume do not end shared ownership while their Pi process is alive. A client arriving before shutdown becomes final cancels automatic exit. A valid explicit after-exit grant for the active setup keeps the service running without expanding existing transfer or model permissions; see [Daemon lifetime and unattended permission](./skills/configure-pi-sync/references/configuration.md#daemon-lifetime-and-unattended-permission). Resources never reload automatically.
@@ -234,9 +236,9 @@ Successful transfers show one summary. They do not reload resources, activate ex
234
236
 
235
237
  **Settings → Merge settings fields** controls the per-setup `sync.mergeSettings` opt-in, default **Off**. It combines independent global `settings.json` fields, not arbitrary JSON or keybindings. Missing/corrupt ancestors, unsupported syntax, and incompatible fields retain whole-transfer review. Sensitive accepted content is cached privately under the denied state root; disabling does not delete evidence.
236
238
 
237
- **Settings → Machine-local fields** edits explicit `sync.localFields` root field names for global `settings.json` (default none). Excluded values and absence stay local; future portable snapshots omit them. An explicit array requires at least settings version 4 and snapshot version 2; directory scope keeps settings version 7 and snapshot version 5. Nonempty rules require `settings.json` in `sync.include` only for selected-path setups. All receiving machines must configure compatible rules. Additions/removals require a separately confirmed force-direction migration, even with `--yes`; old remote history is **not erased**. See [settings merge and local fields](./skills/configure-pi-sync/references/configuration.md#settings-field-merge-and-machine-local-fields) for formats, compatibility and recovery.
239
+ **Settings → Machine-local fields** edits explicit `sync.localFields` root field names for global `settings.json` (default none). Excluded values and absence stay local; future portable snapshots omit them. An explicit array requires at least settings version 4 and snapshot version 2; legacy directory scope keeps settings version 7 or later and snapshot version 5; ignore-file setups use settings version 8 and snapshot version 6. Nonempty rules require `settings.json` in `sync.include` only for selected-path setups. All receiving machines must configure compatible rules. Additions/removals require a separately confirmed force-direction migration, even with `--yes`; old remote history is **not erased**. See [settings merge and local fields](./skills/configure-pi-sync/references/configuration.md#settings-field-merge-and-machine-local-fields) for formats, compatibility and recovery.
238
240
 
239
- **Settings → Content merge / partial progress** controls independent `sync.mergeContent` and `sync.partialSync` opt-ins, both default **Off**. Saving opts into at least settings version 5; partial publications use snapshot version 3 for selected paths, version 4 with selected-path exclusions, or version 5 for directory scope. Older readers must refuse unsupported formats. Supported Markdown/plain-text resources merge bounded independent line edits without Git or conflict markers. Diff grids and hunk comparisons share an eight-million-work-unit budget across the operation and its retries; exhausted paths remain conflicts for review. Same-session reconciliation only accepts validated complete byte-prefix extensions; divergent histories and the loaded session require review. A syntactically clean text merge is **not a semantic correctness guarantee**.
241
+ **Settings → Content merge / partial progress** controls independent `sync.mergeContent` and `sync.partialSync` opt-ins, both default **Off**. Saving opts into at least settings version 5; partial publications use snapshot version 3 for selected paths, version 4 with selected-path exclusions, version 5 for legacy directory scope, or version 6 for ignore-file policy. Older readers must refuse unsupported formats. Supported Markdown/plain-text resources merge bounded independent line edits without Git or conflict markers. Diff grids and hunk comparisons share an eight-million-work-unit budget across the operation and its retries; exhausted paths remain conflicts for review. Same-session reconciliation only accepts validated complete byte-prefix extensions; divergent histories and the loaded session require review. A syntactically clean text merge is **not a semantic correctness guarantee**.
240
242
 
241
243
  Partial sync keeps each side's unresolved versions, preserves their previous accepted hashes/ancestors, and advances only independent paths. Resource/collision dependency groups are withheld together, including local-only files, never represented as deletion. The conditional **Review unresolved conflicts** action, or `/sync conflicts`, opens exact private versions on request and resolves one freshly validated whole group. Automatic pushes, non-forced push/pull, and rollback refuse unresolved groups; use group review or an explicit manual push/pull force direction instead. Artifacts remain below the denied state root, with stable conflict identity and at most 32 proven-completed records retained; unresolved or unrecognized evidence is never automatically pruned. Failed attempts release only newly created artifacts whose inode/content ownership and lack of state/journal references are verified. See [content merge and partial recovery](./docs/content-merge-audit.md).
242
244
 
@@ -278,7 +280,7 @@ A minimal Git setup uses an existing private remote and keeps automatic sync off
278
280
  }
279
281
  ```
280
282
 
281
- Setup saves are atomic and private (`0600` on POSIX), preserve unknown fields, and coordinate across pi-sync processes.
283
+ The existing daemon settings writer uses a private same-directory temporary file and rename (`0600` on POSIX), preserves unknown fields, and coordinates cooperating Pi Sync processes. The lock does not cover external editors.
282
284
  Do not save from a lock-unaware editor during a pi-sync settings operation.
283
285
  Malformed, invalid, unsupported, symlinked, or concurrently changed documents remain untouched.
284
286
  Version 1, version 2, and non-empty unversioned settings require manual recovery rather than automatic migration.
@@ -286,16 +288,31 @@ Version 1, version 2, and non-empty unversioned settings require manual recovery
286
288
  Adding `sessions` can upload prompts, tool output, paths, images, and secrets; interactive flows require a privacy acknowledgement.
287
289
  Startup checks report included-content differences without changing anything. Transfers retain their existing included-content policy checks instead of silently expanding local scope.
288
290
 
291
+ ### Ignore-file policy
292
+
293
+ These routes require ignore-file support in the running daemon. In TUI, eligible legacy setups can review migration the first time you open `/sync`. **Not now** keeps your existing policy and defers the prompt for that setup. To review it later, use **Settings → Migrate to ignore file…**. Check which local and remote paths enter or leave scope. Directory-wide rules can also include files created later. Review the transfer itself before approving it. An ignore file is not a secret scanner.
294
+
295
+ An existing valid rule file is reused as-is. After confirmation, the daemon can create a missing default `.syncignore` on Linux, macOS, and Windows without overwriting an existing file. If automatic creation is unavailable on your filesystem, follow the displayed path and starter rules: create a regular UTF-8 file there without replacing an existing file, then reopen the setup or migration review. **Settings → Ignore file** shows the current path and lets you review a switch to another existing file. Edit the file manually; there is no in-app rule save. Edits affect every setup that uses that file. Setup, migration, switching the file, and editing rules do not authorize or trigger a transfer.
296
+
297
+ The [starter rules](./skills/configure-pi-sync/references/configuration.md#ignore-file-policy) exclude top-level `git/` package checkouts and `/sessions/`, even if you opt into session sync. To sync sessions, both opt in and adjust the rule. Pi credentials, trust, Pi Sync settings and state, and rule files stay local regardless of the rules. Excluded files stay untouched locally, including on rollback. New publications omit excluded paths; retained snapshots and backups are **not erased**.
298
+
299
+ Upgrade all peers to compatible Pi Sync clients and daemons before the first version 6 snapshot publication. The remote stores a policy fingerprint, not the filename or rules. Configure matching rules and session opt-in on each device before pulling. For an existing remote with a different policy, review an explicit direction; background sync cannot make that transition. See [Ignore-file policy and recovery](./skills/configure-pi-sync/references/configuration.md#ignore-file-policy) for starter rules, matching, and safe recovery.
300
+
301
+ ### Legacy path rules
302
+
289
303
  For selected-path setups, **Settings → Excluded paths** edits `sync.exclude` rules that win over `include`; saving opts into at least settings version 6 and snapshot version 4. For directory scope, **Settings → Agent directory scope** also edits `reinclude` and session opt-in. Excluded local files remain untouched, including on rollback. New publications omit matching remote paths, but old history is **not erased**. Removing rules can expose or replace content. See [Excluded paths](./skills/configure-pi-sync/references/configuration.md#excluded-paths) for syntax, review, and recovery.
290
304
 
305
+ ### Scan limits
306
+
307
+ If the agent-directory scan exceeds 64 MiB, use `/sync config` to find the active ignore file. Exclude large files or folders you do not need to sync, verify the rules, and reopen the transfer review. For a legacy agent-directory setup, use **Settings → Agent directory scope** to edit exclusions instead. Storage diagnostics do not change the local scan limit.
308
+
291
309
  Read the [settings reference](./skills/configure-pi-sync/references/configuration.md) for complete S3/R2, Git, and WebDAV examples, backend fields, content policy, legacy paths, and recovery steps.
292
310
 
293
311
  ## 🧠 Skills
294
312
 
295
- Run `/skill:configure-pi-sync Exclude npm/` to have the agent add an exclusion to the active setup and verify the saved change. The [configuration skill](./skills/configure-pi-sync/SKILL.md) is loaded only on request and uses the running local daemon for authorized settings edits. It can also answer configuration questions.
296
- Use `/sync` for initial setup, masked credential entry, and changes or transfers that require a separate review. The skill does not run diagnostics, check remote connectivity, or start a transfer.
297
- The skill's instructions are not a permission sandbox for the agent's other tools.
298
- Read the [settings reference](./skills/configure-pi-sync/references/configuration.md) directly when no agent assistance is needed.
313
+ Run `/skill:configure-pi-sync` with the edit you want, the rule draft or audit you need, or the error you saw. For example, use `/skill:configure-pi-sync exclude npm/ from the ignore file for my home setup` or `/skill:configure-pi-sync draft a .syncignore without writing it`. The [configuration skill](./skills/configure-pi-sync/SKILL.md) loads only on request. It applies authorized edits to `pi-sync.json` through the running local daemon for routine preferences, or verifies the ignore file for a setup you name through the daemon before editing it. For an error, it checks the local cause before proposing a change.
314
+
315
+ Use `/sync` for initial setup, masked credential entry, and operations that require a separate review. The skill does not run backend diagnostics, check remote connectivity, or start transfers. See the [settings reference](./skills/configure-pi-sync/references/configuration.md) for manual configuration and troubleshooting.
299
316
 
300
317
  ## 💬 Commands
301
318
 
@@ -307,7 +324,7 @@ Read the [settings reference](./skills/configure-pi-sync/references/configuratio
307
324
  | `/sync use <setup>` | Switch the active local sync setup, following its switch policy. |
308
325
  | `/sync init` | Create a local configuration template. |
309
326
  | `/sync config` | Show resolved configuration. |
310
- | `/sync files` | List included local files. |
327
+ | `/sync files` | Show the active rule-file path for ignore-file setups or open content selection for legacy setups in TUI. |
311
328
  | `/sync status` | Compare local and remote snapshot state. |
312
329
  | `/sync diff` | Show local and remote differences. |
313
330
  | `/sync conflicts` | Review private unresolved dependency groups and choose local or remote group versions after fresh validation. |
@@ -373,7 +390,7 @@ Before pull or rollback, pi-sync writes a backup under `<agent-dir>/pi-sync/back
373
390
  Snapshot apply and recovery require canonical agent and session paths. Preflight refuses parent aliases it detects because Pi's file queue uses different keys for existing and missing aliases. Node's path-based writes and deletes cannot prevent another process from replacing a parent directory after a check. Use directories you control, and pause tools that move or replace their directories during sync. Preserve any pending recovery evidence; an unresolved startup recovery barrier still blocks transfers. Old journals recorded under an alias require manual review because their exact root and target paths remain pinned. Changing the agent path alone does not authorize recovery or rewriting those journals.
374
391
  Apply preflights paths and checksums, journals mutations, and restores prior state only when current bytes match verified preimages or planned postimages. Unknown intermediate directory states and newer edits require review rather than a blind rollback. An interruption after replacement is armed can require manual recovery even if installation never ran; a later deletion of installed content is not treated as an unfinished remove.
375
392
  The file queue coordinates one Pi runtime, not separate processes or lock-unaware editors. Hash-based journals cannot distinguish a later write of identical recorded bytes; they do not provide a cross-process compare-and-swap.
376
- Merged transfers instead retain a private publication/apply/baseline journal and roll forward only when the active remote candidate and every changed local preimage/postimage can be verified. A crash or uncertain publication is reconciled through `/sync sync` without blind republishing. If newer local or remote changes prevent reconciliation, preserve the evidence, review `/sync diff`, and explicitly choose `push --force` or `pull --force`; the chosen direction archives the old journal. These commands require a settings document with no ignore-file setups, even if the affected setup uses a legacy policy. If mixed settings block recovery, preserve the journal and its backup before changing settings. Disabling automatic transfer does not undo completed transfers. Do not downgrade while a merge or snapshot recovery journal is pending.
393
+ Merged transfers instead retain a private publication/apply/baseline journal and roll forward only when the active remote candidate and every changed local preimage/postimage can be verified. A crash or uncertain publication is reconciled through `/sync sync` without blind republishing. If newer local or remote changes prevent reconciliation, preserve the evidence and review `/sync diff`. With a legacy policy, an explicitly reviewed `push --force` or `pull --force` can archive the old journal. With an ignore-file policy, keep the originating setup and exact rule source; a mismatch blocks replay and force direction does not bypass pending recovery. Follow the [ignore-file recovery guidance](./skills/configure-pi-sync/references/configuration.md#ignore-file-policy). Disabling automatic transfer does not undo completed transfers. Do not downgrade while a merge or snapshot recovery journal is pending.
377
394
 
378
395
  Removing a local setup or connection never deletes remote data.
379
396
 
@@ -421,7 +438,7 @@ packages/pi-sync/
421
438
  ├── dist/ # Published Jiti runtime and separate daemon files
422
439
  ├── scripts/build-runtime.mjs # Runtime builder
423
440
  ├── docs/ # Operational audits and settings link compatibility
424
- ├── skills/configure-pi-sync/ # Agent settings edits and authoritative settings reference
441
+ ├── skills/configure-pi-sync/ # Local configuration edits and troubleshooting
425
442
  └── test/ # Behavior and lifecycle coverage
426
443
  ```
427
444
 
@@ -15,6 +15,7 @@ import {
15
15
  syncConfigReviewFingerprint,
16
16
  syncConfigReviewIdentity,
17
17
  syncSessionsWarnings,
18
+ syncSettingsConfigFingerprint,
18
19
  syncSetupReviewIdentity,
19
20
  syncSetupStorageReview
20
21
  } from "#pi-sync-daemon/engine/settings/config";
@@ -30,6 +31,6 @@ export {
30
31
  syncConfigReviewFingerprint,
31
32
  syncConfigReviewIdentity,
32
33
  syncSessionsWarnings,
33
- syncSetupReviewIdentity
34
+ syncSettingsConfigFingerprint
34
35
  };
35
- //# sourceMappingURL=chunk-MNYRU5U5.ts.map
36
+ //# sourceMappingURL=chunk-27F5W7DX.ts.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/settings/config.ts"],
4
- "sourcesContent": ["export type * from \"@narumitw/pi-sync-daemon/engine/settings/config\";\nexport {\n configFromSettings,\n isEnabled,\n isExplicitlyEnabled,\n loadConfig,\n loadConfigForCheck,\n loadPartialConfig,\n loadSettingsConfig,\n sessionTokenWarnings,\n syncCheckConfigFingerprint,\n syncConfigReviewFingerprint,\n syncConfigReviewIdentity,\n syncSessionsWarnings,\n syncSetupReviewIdentity,\n syncSetupStorageReview,\n} from \"@narumitw/pi-sync-daemon/engine/settings/config\";\n"],
5
- "mappings": ";;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;",
4
+ "sourcesContent": ["export type * from \"@narumitw/pi-sync-daemon/engine/settings/config\";\nexport {\n configFromSettings,\n isEnabled,\n isExplicitlyEnabled,\n loadConfig,\n loadConfigForCheck,\n loadPartialConfig,\n loadSettingsConfig,\n sessionTokenWarnings,\n syncCheckConfigFingerprint,\n syncConfigReviewFingerprint,\n syncConfigReviewIdentity,\n syncSessionsWarnings,\n syncSettingsConfigFingerprint,\n syncSetupReviewIdentity,\n syncSetupStorageReview,\n} from \"@narumitw/pi-sync-daemon/engine/settings/config\";\n"],
5
+ "mappings": ";;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;",
6
6
  "names": []
7
7
  }
@@ -472,6 +472,7 @@ async function remoteOperation(ctx, operation, options) {
472
472
  const payload = {
473
473
  args,
474
474
  ...setup === void 0 ? {} : { setup },
475
+ ...options.automaticFingerprint === void 0 ? {} : { automaticFingerprint: options.automaticFingerprint },
475
476
  yes: options.yes,
476
477
  force: options.force,
477
478
  stale: options.stale,
@@ -584,13 +585,14 @@ var PiDaemonClient = class {
584
585
  model: protectionOnly ? void 0 : this.modelBinding()
585
586
  };
586
587
  }
587
- async configured() {
588
+ async configured(matches) {
588
589
  this.validate();
589
590
  await settingsQueue;
590
591
  this.validate();
591
592
  const document = await peekLocalConfigDocument();
592
593
  this.validate();
593
- return Boolean(document && validateSettingsDocument(document.parsed).activeSyncSetup);
594
+ const settings = document && validateSettingsDocument(document.parsed);
595
+ return Boolean(settings?.activeSyncSetup && (matches?.(settings) ?? true));
594
596
  }
595
597
  async pauseForSessionChange() {
596
598
  this.validate();
@@ -1011,7 +1013,7 @@ var PiDaemonClient = class {
1011
1013
  if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) throw new Error("This client cannot present safety reviews.");
1012
1014
  let result;
1013
1015
  if (callback.kind === "merge-review" && typeof payload.title === "string" && typeof payload.content === "string") {
1014
- const { confirmMergeReview } = await import("./merge-review-SGDLMVS4.ts");
1016
+ const { confirmMergeReview } = await import("./merge-review-OQDXNTJU.ts");
1015
1017
  this.validate();
1016
1018
  combined.throwIfAborted();
1017
1019
  result = await confirmMergeReview(
@@ -1082,4 +1084,4 @@ export {
1082
1084
  withPiDaemonClient,
1083
1085
  remoteOperation
1084
1086
  };
1085
- //# sourceMappingURL=chunk-INECVQNR.ts.map
1087
+ //# sourceMappingURL=chunk-B5F3JLD3.ts.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/daemon/pi-client.ts", "../../src/daemon/apply-gate.ts", "../../src/daemon/queue-release-ui.ts", "../../src/daemon/recovery.ts"],
4
+ "sourcesContent": ["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { randomUUID } from \"node:crypto\";\nimport { realpathSync } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { type ExtensionContext, getAgentDir } from \"@earendil-works/pi-coding-agent\";\nimport {\n type Callback,\n type ClientFacts,\n type ClientHandoff,\n type ContactState,\n DaemonConnection,\n DaemonError,\n type DocumentView,\n documentFingerprint,\n ensureDaemon,\n findDaemon,\n MAX_SETTINGS_BYTES,\n modelSignature,\n waitForDaemonExit,\n} from \"@narumitw/pi-sync-daemon\";\nimport { type ConfigAuthority, configureEngineHost } from \"@narumitw/pi-sync-daemon/engine/host\";\nimport {\n type LocalConfigDocument,\n peekLocalConfigDocument,\n} from \"@narumitw/pi-sync-daemon/engine/settings/config-file\";\nimport { validateSettingsDocument } from \"@narumitw/pi-sync-daemon/engine/settings/settings-validation\";\nimport { sessionDirFromContext } from \"@narumitw/pi-sync-daemon/engine/snapshot/session-paths\";\nimport type { CommandOptions } from \"../commands/command-types.js\";\nimport type { StartupTimingPublisher } from \"../sync/startup-timings.js\";\nimport { errorMessage, SyncDecisionRequiredError } from \"../sync/sync-errors.js\";\nimport { RemoteSelectionMismatchError } from \"../sync/sync-policy.js\";\nimport {\n type SyncStatusPresentation,\n setSyncStatus,\n showSyncConnectionStatus,\n showSyncQueueReleaseRecovery,\n} from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { PiApplyGate } from \"./apply-gate.js\";\nimport { createQueueReleaseUI, type QueueReleaseEvent } from \"./queue-release-ui.js\";\nimport { quarantineClient, recoverDetachedClients } from \"./recovery.js\";\n\nconst scope = new AsyncLocalStorage<{ client: PiDaemonClient; reload?: AbortController }>();\nconst clients = new WeakMap<ExtensionContext[\"sessionManager\"], PiDaemonClient>();\nexport function currentPiDaemonClient() {\n return current();\n}\nfunction current() {\n const client = scope.getStore()?.client;\n if (!client) throw new Error(\"Pi synchronization requires a current session-bound daemon client.\");\n client.validate();\n return client;\n}\nfunction canonicalPath(value: string | undefined): string | undefined {\n // An in-memory session (`pi --no-session`) reports an empty session dir instead of\n // omitting it, so an empty path means \"no path to publish\", not a broken caller.\n if (value === undefined || value === \"\") return undefined;\n if (!path.isAbsolute(value)) throw new Error(\"Pi session paths must be absolute.\");\n const parts: string[] = [];\n let cursor = path.resolve(value);\n for (;;) {\n try {\n return path.join(realpathSync(cursor), ...parts.toReversed());\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\" || path.dirname(cursor) === cursor) throw error;\n parts.push(path.basename(cursor));\n cursor = path.dirname(cursor);\n }\n }\n}\nfunction decode(value: unknown): LocalConfigDocument | undefined {\n if (value === null) return undefined;\n const document = value as DocumentView;\n if (\n !document ||\n typeof document.path !== \"string\" ||\n typeof document.bytes !== \"string\" ||\n !document.identity ||\n !document.parsed\n )\n throw new Error(\"Invalid settings response.\");\n return { ...document, bytes: Buffer.from(document.bytes, \"base64\") };\n}\nfunction fingerprint(document: LocalConfigDocument | undefined) {\n return documentFingerprint(\n document ? { bytes: document.bytes.toString(\"base64\"), identity: document.identity } : undefined,\n );\n}\nlet settingsQueue = Promise.resolve();\nconst authority: ConfigAuthority = {\n read: (repair) => {\n const client = current();\n return settingsQueue.then(() => {\n client.validate();\n return client.readSettings(repair);\n });\n },\n update: <T extends Record<string, unknown>>(\n fallback: T,\n update: (value: T) => T,\n validate: (value: Record<string, unknown>) => void,\n signal?: AbortSignal,\n ): Promise<T> => {\n const client = current();\n // Capture ownership and invocation order before prerequisite awaits.\n const operation = settingsQueue.then(async () => {\n client.validate();\n signal?.throwIfAborted();\n const document = await client.readSettings(true);\n client.validate();\n signal?.throwIfAborted();\n if (document) validate(document.parsed);\n const next = update(structuredClone(document?.parsed ?? fallback) as T);\n validate(next);\n await client.run(\"settings.cas\", { expected: fingerprint(document), next }, signal);\n client.validate();\n return next;\n });\n settingsQueue = operation.then(\n () => undefined,\n () => undefined,\n );\n return operation;\n },\n create: async (next, signal) => {\n await current().run(\"settings.cas\", { expected: null, next }, signal);\n },\n replace: async (document, next) => {\n await current().run(\"settings.cas\", { expected: fingerprint(document), next });\n },\n};\n/** Factory registration installs only adapters; it starts no process and performs no I/O. */\nexport function installPiDaemonHost() {\n configureEngineHost({\n root: () => scope.getStore()?.client.root ?? path.resolve(getAgentDir()),\n config: authority,\n mutate: async () => {\n throw new Error(\"File mutation belongs to pi-sync-daemon; no in-process fallback is permitted.\");\n },\n review: async () => {\n throw new Error(\"Engine reviews must arrive through the daemon API.\");\n },\n });\n}\nexport function bindPiDaemonClient(ctx: ExtensionContext, signal: AbortSignal, publish?: StartupTimingPublisher) {\n const client = new PiDaemonClient(ctx, signal, publish);\n clients.set(ctx.sessionManager, client);\n return client;\n}\nexport function piDaemonClient(ctx: ExtensionContext) {\n const client = clients.get(ctx.sessionManager);\n if (!client) throw new Error(\"The Pi synchronization client is not attached to this session.\");\n client.validate();\n return client;\n}\nexport function withPiDaemonClient<Context extends ExtensionContext, T>(\n ctx: Context,\n action: (owned: Context) => Promise<T>,\n reload?: AbortController,\n) {\n const owner = { client: piDaemonClient(ctx), reload };\n // TUI input arrives from Pi's event loop, outside the command's async call tree.\n // Bind public component methods so later menu actions retain this exact owner,\n // never a replacement session selected through a global fallback.\n const ui = new Proxy(ctx.ui, {\n get(target, property) {\n if (property !== \"custom\") return Reflect.get(target, property, target);\n return (...args: Parameters<ExtensionContext[\"ui\"][\"custom\"]>) => {\n const [factory, options] = args;\n const wrap = (component: Awaited<ReturnType<typeof factory>>) => {\n const methods = new Map<PropertyKey, { source: unknown; bound: unknown }>();\n return new Proxy(component, {\n get(original, key) {\n const value: unknown = Reflect.get(original, key, original);\n if (typeof value !== \"function\") return value;\n const saved = methods.get(key);\n if (saved?.source === value) return saved.bound;\n const bound = (...values: unknown[]) => scope.run(owner, () => Reflect.apply(value, original, values));\n methods.set(key, { source: value, bound });\n return bound;\n },\n });\n };\n const invoke = (...provided: Parameters<typeof factory>) => {\n const component = scope.run(owner, () => factory(...provided));\n return component instanceof Promise ? component.then(wrap) : wrap(component);\n };\n // Do not turn synchronous editors/reviews into asynchronous factories.\n return target.custom(\n factory.constructor.name === \"AsyncFunction\" ? async (...provided) => invoke(...provided) : invoke,\n options,\n );\n };\n },\n });\n const owned = new Proxy(ctx, {\n get(target, key) {\n return key === \"ui\" ? ui : Reflect.get(target, key, target);\n },\n });\n return scope.run(owner, () => action(owned));\n}\nexport async function remoteOperation(ctx: ExtensionContext, operation: string, options: CommandOptions) {\n const client = piDaemonClient(ctx);\n const { signal, onCommit, args, setup } = options;\n const owner = scope.getStore();\n const reload = options.reload && owner?.client === client ? owner.reload : undefined;\n reload?.signal.throwIfAborted();\n const payload = {\n args,\n ...(setup === undefined ? {} : { setup }),\n ...(options.automaticFingerprint === undefined ? {} : { automaticFingerprint: options.automaticFingerprint }),\n yes: options.yes,\n force: options.force,\n stale: options.stale,\n silent: options.silent,\n reload: reload !== undefined,\n ...(options.agentRetryRefusal ? { agentRetryRefusal: true } : {}),\n };\n return client.run(operation, payload, signal, ctx, onCommit, reload);\n}\nfunction remoteErrorNamed(error: unknown, name: string) {\n return error instanceof DaemonError && error.remote.name === name;\n}\n\nexport class PiDaemonClient {\n private connection?: DaemonConnection;\n private protectionOnly = false;\n private partialConnection?: DaemonConnection;\n private work = Promise.resolve();\n private closing = false;\n private paused = false;\n private pausing?: Promise<void>;\n private connecting?: Promise<DaemonConnection>;\n private contactRepair?: { controller: AbortController; done: Promise<void> };\n private contactAttempt?: { error?: unknown };\n private contactFactsUnpublished = false;\n private contactStatus?: { clear(redraw?: boolean): void; unavailable: boolean };\n private releaseUIEnabled = true;\n private runSignal?: AbortSignal;\n private readonly releaseUI = createQueueReleaseUI(\n () => {\n const ctx = this.releaseContext();\n if (ctx) return showSyncQueueReleaseRecovery(ctx);\n },\n () =>\n this.releaseContext()?.ui.notify(\n \"Pi Sync could not confirm the file write queue release. Sync may be paused; check /sync daemon status before retrying.\",\n \"warning\",\n ),\n );\n private readonly stopReleaseUI = () => {\n // Withdraw while the SDK owner is still active, but never redraw through a replaced context.\n this.releaseUIEnabled = false;\n this.releaseUI.clear(Boolean(this.releaseContext(true)));\n };\n private disposed = false;\n private disposing?: Promise<void>;\n private uiContext: ExtensionContext;\n private reloadRequest?: { received: boolean };\n private pendingReload?: AbortController;\n private readonly busy = new Set<string>();\n private initialized = false;\n private startupDebug = false;\n private participantIdentity = { id: randomUUID(), generation: randomUUID() };\n get id() {\n return this.participantIdentity.id;\n }\n get generation() {\n return this.participantIdentity.generation;\n }\n readonly root: string;\n private readonly rawRoot: string;\n private readonly gate: PiApplyGate;\n private readonly manager: ExtensionContext[\"sessionManager\"];\n constructor(\n private readonly ctx: ExtensionContext,\n private readonly signal: AbortSignal,\n private readonly publish?: StartupTimingPublisher,\n ) {\n this.uiContext = ctx;\n this.manager = ctx.sessionManager;\n this.rawRoot = getAgentDir();\n const root = canonicalPath(path.resolve(this.rawRoot));\n if (!root) throw new Error(\"Agent directory is unavailable.\");\n this.root = root;\n this.gate = new PiApplyGate(() => this.validate());\n this.signal.addEventListener(\"abort\", this.stopReleaseUI, { once: true });\n }\n validate() {\n this.signal.throwIfAborted();\n if (this.disposed || this.closing || clients.get(this.manager) !== this)\n throw new Error(\"Synchronization session was replaced.\");\n // Public context access verifies the SDK runner is still active after awaits.\n this.ctx.isIdle();\n if (getAgentDir() !== this.rawRoot || canonicalPath(path.resolve(this.rawRoot)) !== this.root)\n throw new Error(\"Agent directory changed; reload before synchronization.\");\n }\n private modelBinding(): ClientFacts[\"model\"] {\n const model = this.ctx.model;\n if (!model) return undefined;\n const registry = this.ctx.modelRegistry;\n if (registry.getRegisteredProviderIds().includes(model.provider)) return undefined;\n const source = registry.getProviderAuthStatus(model.provider).source;\n if (\n source !== \"stored\" &&\n source !== \"environment\" &&\n source !== \"models_json_key\" &&\n source !== \"models_json_command\"\n )\n return undefined;\n return { provider: model.provider, id: model.id, signature: modelSignature(model), authSource: source };\n }\n private facts(protectionOnly = this.protectionOnly): ClientFacts {\n const manager = this.ctx.sessionManager;\n return {\n id: this.id,\n generation: this.generation,\n pid: process.pid,\n cwd: this.ctx.cwd,\n mode: this.ctx.mode,\n hasUI: !protectionOnly && this.ctx.hasUI,\n idle: !protectionOnly && !this.paused && !this.busy.size && this.ctx.isIdle(),\n ready: !protectionOnly && this.initialized,\n startupDebug: this.startupDebug,\n sessionFile: canonicalPath(manager.getSessionFile?.()),\n sessionId: manager.getSessionId?.(),\n sessionDir: canonicalPath(sessionDirFromContext(this.ctx)),\n model: protectionOnly ? undefined : this.modelBinding(),\n };\n }\n async configured(matches?: (settings: ReturnType<typeof validateSettingsDocument>) => boolean) {\n this.validate();\n await settingsQueue;\n this.validate();\n const document = await peekLocalConfigDocument();\n this.validate();\n const settings = document && validateSettingsDocument(document.parsed);\n return Boolean(settings?.activeSyncSetup && (matches?.(settings) ?? true));\n }\n async pauseForSessionChange() {\n this.validate();\n this.paused = true;\n this.stopReleaseUI();\n this.stopContactRepair(true);\n this.gate.cancelPending();\n this.pausing ??= (async () => {\n const connection = this.connection ?? this.partialConnection ?? (await this.connecting?.catch(() => undefined));\n if (connection) {\n await connection.pause();\n await this.gate.releaseAfterDrain();\n }\n })();\n return this.pausing;\n }\n async attachExisting({ allowUpgrade = false } = {}) {\n this.validate();\n const address = await findDaemon(this.root);\n this.validate();\n if (!address) return false;\n const upgrade = allowUpgrade && address.needsUpgrade && this.ctx.hasUI && [\"tui\", \"rpc\"].includes(this.ctx.mode);\n let upgradeFailure: string | undefined;\n if (upgrade) {\n try {\n await this.connect();\n this.validate();\n return true;\n } catch (error) {\n this.validate();\n if (this.paused) throw error;\n upgradeFailure = safeTerminalText(errorMessage(error));\n }\n }\n try {\n // If upgrade failed, try only the original owner, with its protection-only facts.\n await this.connect(address);\n } catch (error) {\n this.validate();\n if (remoteErrorNamed(error, \"DaemonStoppingError\")) return false;\n throw error;\n } finally {\n if (upgradeFailure !== undefined) {\n this.validate();\n this.ctx.ui.notify(`pi-sync daemon upgrade failed: ${upgradeFailure}`, \"error\");\n }\n }\n this.validate();\n // Headless, shutdown, and failed-upgrade paths must not schedule transfers on an older build.\n return !this.protectionOnly;\n }\n async finishReattachment() {\n this.validate();\n if (this.connection) {\n await recoverDetachedClients({ paths: this.connection.paths, identity: this.connection.identity });\n this.validate();\n await this.connection.attach(this.signal);\n this.validate();\n }\n }\n async connect(existing?: Awaited<ReturnType<typeof ensureDaemon>>, requestSignal?: AbortSignal) {\n const startupSignal = requestSignal ? AbortSignal.any([this.signal, requestSignal]) : this.signal;\n const validateStartup = () => {\n this.validate();\n startupSignal.throwIfAborted();\n };\n validateStartup();\n if (this.connection) {\n if (!existing && this.protectionOnly)\n throw new Error(\n \"This session is only protecting its files on an older Pi Sync daemon. Use /reload to upgrade.\",\n );\n return this.connection;\n }\n this.connecting ??= (async () => {\n if (this.partialConnection) {\n // A failed unpublished attempt may already be retired or own queue grants.\n // Confirm drain before replacing its identity; failed cleanup must block retry.\n await this.partialConnection.dispose();\n // Finish acknowledged cleanup even if this new startup was cancelled meanwhile.\n await this.gate.releaseAfterDrain();\n validateStartup();\n this.partialConnection = undefined;\n this.participantIdentity = { id: randomUUID(), generation: randomUUID() };\n }\n // Only explicit setup/command paths or a configured interactive session call connect.\n if (!existing) await fs.mkdir(this.root, { recursive: true, mode: 0o700 });\n validateStartup();\n let retried = false;\n for (;;) {\n validateStartup();\n const daemon = existing ?? (await ensureDaemon(this.root, startupSignal));\n validateStartup();\n if (daemon.paths.root !== this.root) throw new Error(\"Daemon root changed before attach.\");\n const protectionOnly = daemon.needsUpgrade === true;\n const connection = new DaemonConnection(daemon.paths, daemon.identity, this.facts(protectionOnly), {\n callback: (callback, signal) => this.callback(callback, signal, protectionOnly),\n event: (event) => {\n if (event.kind === \"commit\") return;\n if (this.signal.aborted || this.disposed || this.closing || clients.get(this.manager) !== this) return;\n const payload = event.payload as {\n message?: string;\n level?: \"info\" | \"warning\" | \"error\";\n report?: string;\n value?: string;\n presentation?: SyncStatusPresentation;\n };\n if (event.kind === \"notify\" && typeof payload?.message === \"string\")\n this.uiContext.ui.notify(safeTerminalText(payload.message), payload.level ?? \"info\");\n if (event.kind === \"timings\" && typeof payload?.report === \"string\") {\n this.publish?.(this.ctx, payload.report.split(\"\\n\").map(safeTerminalText).join(\"\\n\"));\n }\n if (event.kind === \"status\")\n setSyncStatus(\n this.uiContext,\n typeof payload?.value === \"string\" ? safeTerminalText(payload.value) : undefined,\n payload.presentation,\n );\n },\n contact: (state) => this.observeContact(connection, state),\n queueRelease: (event) => this.observeQueueRelease(connection, event),\n error: () => {\n if (this.ownsContactUI() && connection.facts.hasUI && !this.releaseUI.retrying)\n this.showContactStatus(\"sync service unavailable\", \"blocked\", true);\n },\n });\n this.partialConnection = connection;\n try {\n await connection.attach(startupSignal);\n } catch (error) {\n if (!(error instanceof DaemonError) || error.remote.name !== \"DaemonStoppingError\") throw error;\n // The final idle fence rejected publication, so this connection owns no queue grants.\n await connection.dispose().catch(() => {});\n this.partialConnection = undefined;\n validateStartup();\n if (existing || retried) throw error;\n retried = true;\n await waitForDaemonExit(daemon.identity, startupSignal);\n validateStartup();\n continue;\n }\n this.validate();\n await recoverDetachedClients(daemon);\n if (this.signal.aborted || this.disposed || this.closing) {\n await connection.dispose();\n this.validate();\n }\n this.validate();\n this.connection = connection;\n this.protectionOnly = protectionOnly;\n this.partialConnection = undefined;\n return connection;\n }\n })().catch((error) => {\n this.connecting = undefined;\n throw error;\n });\n const connection = await this.connecting;\n validateStartup();\n if (!existing && this.protectionOnly)\n throw new Error(\"This session is only protecting its files on an older Pi Sync daemon. Use /reload to upgrade.\");\n return connection;\n }\n private ownsContactUI() {\n return (\n !this.signal.aborted && !this.disposed && !this.closing && !this.paused && clients.get(this.manager) === this\n );\n }\n private releaseContext(cleanup = false) {\n if (clients.get(this.manager) !== this) return;\n if (!cleanup && (!this.releaseUIEnabled || !this.ownsContactUI() || this.busy.has(\"shutdown\"))) return;\n try {\n this.ctx.isIdle(); // Also verifies the SDK context has not been retired.\n if (this.ctx.hasUI && (this.ctx.mode === \"tui\" || this.ctx.mode === \"rpc\")) return this.ctx;\n } catch {\n // Detached cleanup can outlive its UI.\n }\n }\n disableQueueReleaseUI() {\n this.stopReleaseUI();\n }\n private observeQueueRelease(connection: DaemonConnection, event: QueueReleaseEvent) {\n if (connection !== this.connection || !connection.facts.hasUI || !this.releaseContext()) return;\n if (event.state === \"retrying\" && this.contactStatus?.unavailable) this.clearConnectionStatus();\n this.releaseUI.observe(event, this.busy.has(\"command\"), !this.runSignal || this.runSignal.aborted);\n }\n private showContactStatus(text: string, activity: \"retry\" | \"blocked\", unavailable = false) {\n const previous = this.contactStatus;\n this.contactStatus = {\n clear: showSyncConnectionStatus(this.ctx, text, { activity, reason: activity === \"retry\" ? \"temp\" : \"repair\" }),\n unavailable,\n };\n previous?.clear();\n }\n private clearConnectionStatus(redraw = true) {\n const status = this.contactStatus;\n this.contactStatus = undefined;\n status?.clear(redraw);\n }\n private stopContactRepair(redraw: boolean) {\n this.contactRepair?.controller.abort(new DOMException(\"Pi session is changing\", \"AbortError\"));\n this.clearConnectionStatus(redraw);\n }\n private observeContact(connection: DaemonConnection, state: ContactState) {\n if (connection !== this.connection || !this.ownsContactUI()) return;\n if (state === \"active\") {\n if (this.contactRepair || this.contactFactsUnpublished || connection.contactResumeState === \"uncertain\") return;\n this.clearRestoredContact();\n } else if (state === \"expired\" && connection.facts.hasUI && !this.contactAttempt && !this.contactRepair) {\n if (this.gate.size || connection.hasPendingWork || this.releaseUI.retrying) return;\n void this.resumeContact(connection).catch(() => {\n // The owning repair updates the status; a later command reports the error.\n });\n }\n }\n private clearRestoredContact() {\n this.contactAttempt = undefined;\n this.contactFactsUnpublished = false;\n this.clearConnectionStatus();\n }\n private async resumeContact(connection: DaemonConnection) {\n this.validate();\n if (this.paused || this.connection !== connection) throw new Error(\"Pi Sync is paused for a session change.\");\n if (this.contactRepair) return this.contactRepair.done;\n if (connection.contactState === \"active\" && connection.contactResumeState !== \"uncertain\") return;\n if (this.gate.size || connection.hasPendingWork || connection.contactResumeState === \"uncertain\") {\n throw new Error(\n \"Pi Sync cannot reconnect while previous work is still running or uncertain. Check sync recovery before retrying.\",\n );\n }\n const earlier = this.contactAttempt;\n if (connection.contactState !== \"expired\" || earlier) {\n throw new Error(\"Pi Sync could not restore contact. Review pending work before using /reload.\", {\n cause: earlier?.error,\n });\n }\n const controller = new AbortController();\n const signal = AbortSignal.any([this.signal, controller.signal]);\n const attempt: { error?: unknown } = {};\n this.contactAttempt = attempt;\n const done = Promise.resolve().then(async () => {\n try {\n this.validate();\n signal.throwIfAborted();\n this.showContactStatus(\"sync reconnecting\", \"retry\");\n // Admission can wait behind an apply. Do not advertise readiness using\n // facts sampled before that wait; publish current facts after the ack.\n await connection.resumeContact({ ...this.facts(), idle: false, ready: false }, signal);\n this.validate();\n signal.throwIfAborted();\n this.contactFactsUnpublished = true;\n this.contactAttempt = undefined;\n await connection.update(this.facts());\n this.validate();\n signal.throwIfAborted();\n this.confirmContact(connection);\n } catch (error) {\n attempt.error = error;\n if (this.ownsContactUI() && !signal.aborted)\n this.showContactStatus(\"sync reconnect blocked; check /sync daemon status\", \"blocked\");\n throw error;\n } finally {\n if (this.contactRepair?.controller === controller) this.contactRepair = undefined;\n }\n });\n this.contactRepair = { controller, done };\n return done;\n }\n private async publishFacts(connection: DaemonConnection) {\n if (this.contactRepair) await this.contactRepair.done;\n this.validate();\n if (this.paused) throw new Error(\"Pi Sync is paused for a session change.\");\n if (connection.contactResumeState === \"uncertain\")\n throw new Error(\"Pi Sync cannot verify the previous reconnect. Review pending work before using /reload.\");\n try {\n await connection.update(this.facts());\n } catch (error) {\n if (!connection.facts.hasUI || !remoteErrorNamed(error, \"ClientContactExpiredError\")) throw error;\n await this.resumeContact(connection);\n this.validate();\n // A shared repair might have started before these facts changed.\n await connection.update(this.facts());\n }\n this.validate();\n this.confirmContact(connection);\n }\n private confirmContact(connection: DaemonConnection) {\n if (connection.contactState === \"expired\" || connection.contactState === \"inactive\")\n throw new Error(\"Pi Sync did not confirm active participation in the daemon.\");\n this.clearRestoredContact();\n }\n async verifyConnection(signal?: AbortSignal) {\n const connection = await this.connect(undefined, signal);\n signal?.throwIfAborted();\n await this.publishFacts(connection);\n signal?.throwIfAborted();\n return connection;\n }\n async readSettings(repair = false) {\n this.validate();\n if (!this.connection || this.paused) {\n const document = await peekLocalConfigDocument();\n this.validate();\n if (document && document.bytes.length > MAX_SETTINGS_BYTES)\n throw new Error(\"Settings exceed the local API byte limit; the source document is unchanged.\");\n if (document && !repair) validateSettingsDocument(document.parsed);\n return document;\n }\n return decode(await this.run(repair ? \"settings.repair-read\" : \"settings.read\", {}));\n }\n run(\n operation: string,\n payload: unknown,\n signal?: AbortSignal,\n ctx = this.ctx,\n onCommit?: () => void,\n reload?: AbortController,\n ) {\n const result = this.work.then(() => this.runCurrent(operation, payload, signal, ctx, onCommit, reload));\n this.work = result.then(\n () => {},\n () => {},\n );\n return result;\n }\n private async runCurrent(\n operation: string,\n payload: unknown,\n signal?: AbortSignal,\n ctx = this.ctx,\n onCommit?: () => void,\n reload?: AbortController,\n ) {\n this.validate();\n signal?.throwIfAborted();\n reload?.signal.throwIfAborted();\n if (this.pendingReload) throw new Error(\"Pi resources are about to reload.\");\n if (this.paused && operation !== \"shutdown\")\n throw new Error(\"Synchronization is paused for a session change; if it was cancelled, use /reload to reattach.\");\n const connection = await this.connect(undefined, signal);\n if (this.paused && operation === \"shutdown\") {\n Object.assign(connection.facts, { ...this.facts(), idle: false, ready: false });\n await connection.attach(signal ? AbortSignal.any([signal, this.signal]) : this.signal);\n this.validate();\n }\n this.validate();\n signal?.throwIfAborted();\n if (this.paused)\n await connection.update(this.facts()); // Existing, explicitly attached shutdown path.\n else await this.publishFacts(connection);\n this.validate();\n signal?.throwIfAborted();\n this.uiContext = ctx;\n // The daemon directs reload only to the submitting client, and run() serializes its jobs.\n const request = reload ? { received: false } : undefined;\n this.reloadRequest = request;\n const runSignal = signal ? AbortSignal.any([signal, this.signal]) : this.signal;\n this.runSignal = runSignal;\n const clearForeground = () => this.releaseUI.finishForeground(Boolean(this.releaseContext()));\n runSignal.addEventListener(\"abort\", clearForeground, { once: true });\n try {\n const result = await connection.run(operation, payload, runSignal, onCommit);\n if (request?.received && reload && !this.paused && !reload.signal.aborted && !signal?.aborted) {\n this.validate();\n this.pendingReload = reload;\n // Close the command's UI, not the session. Pi reload must run after this job and its UI drain.\n reload.abort(new DOMException(\"Pi resource reload requested\", \"AbortError\"));\n }\n return result;\n } catch (error) {\n if (error instanceof DaemonError) {\n const prototype =\n error.name === \"RemoteSelectionMismatchError\"\n ? RemoteSelectionMismatchError.prototype\n : error.name === \"SyncDecisionRequiredError\"\n ? SyncDecisionRequiredError.prototype\n : undefined;\n if (prototype) {\n const restored = Object.create(prototype) as Error;\n Object.assign(restored, error.remote.properties, { name: error.name, message: error.message });\n throw restored;\n }\n Object.assign(error, error.remote.properties);\n }\n throw error;\n } finally {\n runSignal.removeEventListener(\"abort\", clearForeground);\n clearForeground();\n this.runSignal = undefined;\n this.uiContext = this.ctx;\n this.reloadRequest = undefined;\n }\n }\n canReload(owner: AbortController) {\n if (this.pendingReload !== owner || this.paused) return false;\n this.validate();\n return true;\n }\n releaseReload(owner: AbortController) {\n if (this.pendingReload === owner) this.pendingReload = undefined;\n }\n async markReady(debug: boolean) {\n this.validate();\n this.startupDebug = debug;\n this.initialized = true;\n await this.update();\n this.validate();\n }\n async setBusy(reason: string, busy: boolean, publish = true) {\n this.validate();\n if (busy) this.busy.add(reason);\n else if (this.busy.delete(reason) && reason === \"command\") {\n // Local command completion does not depend on publishing idle facts.\n this.releaseUI.flushWarnings();\n }\n if (publish) await this.update();\n this.validate();\n }\n async update() {\n if (this.connection && !this.paused && !this.disposed && !this.signal.aborted)\n await this.publishFacts(this.connection);\n }\n private async callback(callback: Callback, signal: AbortSignal, protectionOnly: boolean) {\n const payload = callback.payload as {\n reservation?: string;\n targets?: string[];\n generation?: string;\n title?: string;\n message?: string;\n content?: string;\n confirmationLabel?: string;\n summaryLines?: string[];\n items?: string[];\n helpText?: string;\n background?: boolean;\n };\n if (callback.kind === \"queue-release\") {\n if (typeof payload?.reservation !== \"string\") throw new Error(\"Invalid queue release.\");\n await this.gate.releaseRequest(payload.reservation);\n return true;\n }\n this.validate();\n signal.throwIfAborted();\n if (this.paused) throw new Error(\"Pi session is changing; no new work is authorized.\");\n if (callback.kind === \"queue-acquire\") {\n if (this.pendingReload) throw new Error(\"Pi resources are about to reload.\");\n if (payload.background && !this.facts().idle) throw new Error(\"Pi is busy; background apply was not granted.\");\n if (\n payload.generation !== this.generation ||\n typeof payload.reservation !== \"string\" ||\n !Array.isArray(payload.targets)\n )\n throw new Error(\"Stale file-queue request.\");\n return this.gate.acquire(payload.reservation, payload.targets, AbortSignal.any([signal, this.signal]));\n }\n const ctx = this.uiContext;\n const combined = AbortSignal.any([signal, this.signal]);\n if (callback.kind === \"model-binding\") {\n if (protectionOnly) return null;\n const facts = this.facts();\n const connection = this.connection ?? this.partialConnection;\n if (connection && JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model)) {\n await connection.update(facts);\n this.validate();\n }\n return payload.background && !facts.idle ? null : (facts.model ?? null);\n }\n if (callback.kind === \"reload\") {\n if (!this.reloadRequest) throw new Error(\"No active Pi command can reload resources.\");\n this.reloadRequest.received = true;\n return true;\n }\n if (!ctx.hasUI || ![\"tui\", \"rpc\"].includes(ctx.mode)) throw new Error(\"This client cannot present safety reviews.\");\n let result: unknown;\n if (callback.kind === \"merge-review\" && typeof payload.title === \"string\" && typeof payload.content === \"string\") {\n const { confirmMergeReview } = await import(\"../ui/merge-review.js\");\n this.validate();\n combined.throwIfAborted();\n result = await confirmMergeReview(\n ctx,\n payload.title,\n payload.content,\n combined,\n () => !combined.aborted && !this.disposed,\n payload.confirmationLabel,\n payload.summaryLines,\n );\n } else if (\n callback.kind === \"confirm\" &&\n typeof payload.title === \"string\" &&\n typeof payload.message === \"string\"\n ) {\n result = await ctx.ui.confirm(safeTerminalText(payload.title), safeTerminalText(payload.message), {\n signal: combined,\n });\n } else if (\n callback.kind === \"select\" &&\n typeof payload.title === \"string\" &&\n Array.isArray(payload.items) &&\n payload.items.every((item) => typeof item === \"string\")\n ) {\n const labels = payload.items.map(safeTerminalText);\n if (new Set(labels).size !== labels.length) throw new Error(\"Daemon choices have ambiguous terminal labels.\");\n const selected = await ctx.ui.select(safeTerminalText(payload.title), labels, { signal: combined });\n const index = selected === undefined ? -1 : labels.indexOf(selected);\n result = index < 0 ? undefined : payload.items[index];\n } else throw new Error(\"Unsupported daemon UI callback.\");\n this.validate();\n combined.throwIfAborted();\n return result;\n }\n disposeForShutdown(reason: string | undefined, targetFile?: string) {\n const facts = this.connection?.facts ?? this.partialConnection?.facts;\n return this.dispose({\n kind: [\"new\", \"resume\", \"fork\", \"reload\"].includes(reason ?? \"\") ? \"replace\" : \"exit\",\n ...(targetFile !== undefined\n ? { file: canonicalPath(targetFile) }\n : reason === \"reload\"\n ? { file: facts?.sessionFile, sessionId: facts?.sessionId }\n : {}),\n cwd: facts?.cwd,\n });\n }\n async dispose(handoff?: ClientHandoff) {\n if (this.disposing) return this.disposing;\n this.closing = true;\n this.signal.removeEventListener(\"abort\", this.stopReleaseUI);\n this.stopReleaseUI();\n this.stopContactRepair(false);\n this.disposing = (async () => {\n const connection = this.connection ?? this.partialConnection ?? (await this.connecting?.catch(() => undefined));\n let confirmed = false;\n try {\n await connection?.dispose(handoff);\n confirmed = Boolean(connection);\n } finally {\n this.disposed = true;\n if (clients.get(this.manager) === this) clients.delete(this.manager);\n const gate = this.gate;\n gate.detach();\n if (connection) {\n if (confirmed) await gate.releaseAfterDrain();\n else quarantineClient(gate, connection.paths.root, connection.identity, connection.facts);\n }\n await this.work;\n }\n })();\n return this.disposing;\n }\n}\n", "import { randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\nimport { withFileMutationQueue } from \"@earendil-works/pi-coding-agent\";\nimport { withTargetQueues } from \"@narumitw/pi-sync-daemon/engine/snapshot/snapshot-mutation-queues\";\n\ninterface Gate {\n token: string;\n paths: readonly string[];\n entered: Promise<string>;\n task: Promise<void>;\n granted: boolean;\n cancelled: boolean;\n reject(error: unknown): void;\n release(): void;\n}\n/**\n * Holds the running Pi's actual public file queues; it does not authorize filesystem writes.\n * The engine owns reviewed destinations, which can differ from every participant's current roots.\n */\nexport class PiApplyGate {\n private gates = new Map<string, Gate>();\n constructor(private validate: () => void) {}\n async acquire(requestId: string, targets: readonly string[], signal?: AbortSignal) {\n this.validate();\n signal?.throwIfAborted();\n if (\n !targets.length ||\n targets.length > 16_384 ||\n targets.some((target) => typeof target !== \"string\" || target.includes(\"\\0\") || !path.isAbsolute(target))\n )\n throw new Error(\"Invalid daemon mutation targets.\");\n const normalized = [...new Set(targets.map((target) => path.resolve(target)))].sort();\n const existing = this.gates.get(requestId);\n if (existing) {\n if (JSON.stringify(existing.paths) !== JSON.stringify(normalized)) throw new Error(\"File-queue request changed.\");\n return existing.entered;\n }\n const token = randomUUID();\n let entered!: (token: string) => void;\n let rejected!: (error: unknown) => void;\n const ready = new Promise<string>((resolve, reject) => {\n entered = resolve;\n rejected = reject;\n });\n let release!: () => void;\n const held = new Promise<void>((resolve) => {\n release = resolve;\n });\n const gate: Gate = {\n token,\n paths: normalized,\n entered: ready,\n task: Promise.resolve(),\n release,\n reject: rejected,\n granted: false,\n cancelled: false,\n };\n this.gates.set(requestId, gate);\n const validate = () => {\n if (gate.cancelled) throw new DOMException(\"File-queue reservation was cancelled\", \"AbortError\");\n this.validate();\n };\n gate.task = withTargetQueues(\n normalized,\n { signal, validateMutation: validate },\n async () => {\n validate();\n signal?.throwIfAborted();\n gate.granted = true;\n entered(token);\n // Prompt cancellation cannot revoke a grant while a remote writer may still run.\n await held;\n },\n { mutate: withFileMutationQueue },\n )\n .catch((error) => {\n rejected(error);\n })\n .finally(() => {\n if (this.gates.get(requestId) === gate) this.gates.delete(requestId);\n });\n const abort = () => {\n if (!gate.granted) {\n gate.cancelled = true;\n rejected(signal?.reason);\n release();\n }\n };\n signal?.addEventListener(\"abort\", abort, { once: true });\n void gate.task.finally(() => signal?.removeEventListener(\"abort\", abort));\n return ready;\n }\n async release(token: string) {\n const gate = [...this.gates.values()].find((value) => value.token === token);\n if (!gate) throw new Error(\"Unknown file-queue grant.\");\n await this.releaseGate(gate);\n }\n private async releaseGate(gate: Gate) {\n if (!gate.granted) {\n gate.cancelled = true;\n gate.reject(new DOMException(\"File-queue reservation was released\", \"AbortError\"));\n }\n gate.release();\n // A queued, ungranted placeholder cannot write after cancellation and need not\n // wait for another Pi tool to finish before acknowledgement.\n if (gate.granted) await gate.task;\n }\n async releaseRequest(requestId: string) {\n const gate = this.gates.get(requestId);\n if (!gate) return;\n await this.releaseGate(gate);\n }\n detach() {\n const failure = new DOMException(\"Pi session detached\", \"AbortError\");\n this.validate = () => {\n throw failure;\n };\n this.cancelPending(failure);\n }\n cancelPending(failure: unknown = new DOMException(\"Pi session changing\", \"AbortError\")) {\n for (const gate of this.gates.values())\n if (!gate.granted) {\n gate.cancelled = true;\n gate.reject(failure);\n gate.release();\n }\n }\n get size() {\n return [...this.gates.values()].filter((gate) => gate.granted || !gate.cancelled).length;\n }\n /** Release only after establishing that the associated service cannot still write. */\n async releaseAfterOwnerExit(pid: number) {\n try {\n process.kill(pid, 0);\n throw new Error(\"Daemon owner is still alive; grants remain held.\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ESRCH\") throw error;\n }\n await this.releaseAfterDrain();\n }\n /** Caller must first receive an authenticated same-owner detach/drain acknowledgement. */\n async releaseAfterDrain() {\n await Promise.all([...this.gates.values()].map((gate) => this.releaseGate(gate)));\n }\n}\n", "import type { ConnectionOptions } from \"@narumitw/pi-sync-daemon\";\n\nexport type QueueReleaseEvent = Parameters<NonNullable<ConnectionOptions[\"queueRelease\"]>>[0];\ntype ClearStatus = (redraw?: boolean) => void;\n\n/** Session-owned presentation only; it neither controls delivery nor infers a job's outcome. */\nexport function createQueueReleaseUI(show: () => ClearStatus | undefined, warn: () => void) {\n const retries = new Map<string, { job: string; foreground: boolean }>();\n const handledJobs = new Set<string>();\n const deferredWarnings = new Set<string>();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let clearStatus: ClearStatus | undefined;\n\n function remember(job: string) {\n deferredWarnings.delete(job);\n if (handledJobs.has(job)) return false;\n if (handledJobs.size >= 128) {\n const oldest = handledJobs.values().next();\n if (!oldest.done) handledJobs.delete(oldest.value);\n }\n handledJobs.add(job);\n return true;\n }\n function clearPresentation(redraw: boolean) {\n clearTimeout(timer);\n timer = undefined;\n const release = clearStatus;\n clearStatus = undefined;\n release?.(redraw);\n }\n\n return {\n get retrying() {\n return retries.size > 0;\n },\n observe({ id, job, state, foreground }: QueueReleaseEvent, commandBusy: boolean, cancelled: boolean) {\n if (state === \"retrying\") {\n if (foreground && cancelled) {\n remember(job);\n return;\n }\n if (retries.has(id)) return;\n retries.set(id, { job, foreground });\n if (retries.size !== 1) return;\n timer = setTimeout(() => {\n timer = undefined;\n const release = show();\n if (retries.size) clearStatus = release;\n else release?.(false); // Presentation may have synchronously reentered lifecycle cleanup.\n }, 2_000);\n timer.unref?.();\n return;\n }\n const retry = retries.get(id);\n retries.delete(id);\n if (!retries.size) clearPresentation(true);\n if (state !== \"unconfirmed\") return;\n const background = !foreground && !retry?.foreground;\n if (background && commandBusy) {\n if (!handledJobs.has(job)) deferredWarnings.add(job);\n } else if (remember(job) && background) warn();\n },\n flushWarnings() {\n if (!deferredWarnings.size) return;\n // One warning covers the background releases deferred by this command.\n for (const job of deferredWarnings) remember(job);\n try {\n warn();\n } catch {\n // Presentation must not interrupt publication of the new idle state.\n }\n },\n finishForeground(redraw: boolean) {\n for (const [id, { job, foreground }] of retries) {\n if (!foreground) continue;\n retries.delete(id);\n remember(job); // Late observations of this job should not duplicate its command result.\n }\n if (!retries.size) clearPresentation(redraw);\n },\n clear(redraw: boolean) {\n retries.clear();\n handledJobs.clear();\n deferredWarnings.clear();\n clearPresentation(redraw);\n },\n };\n}\n", "import { type ClientFacts, DaemonConnection, findDaemon, type Identity } from \"@narumitw/pi-sync-daemon\";\nimport type { PiApplyGate } from \"./apply-gate.js\";\n\ntype Address = { paths: DaemonConnection[\"paths\"]; identity: Identity };\ninterface Recovery {\n gate: PiApplyGate;\n root: string;\n identity: Identity;\n facts: ClientFacts;\n timer?: ReturnType<typeof setInterval>;\n attempt?: Promise<boolean>;\n}\nconst recoveries = new Set<Recovery>();\nfunction alive(pid: number) {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code !== \"ESRCH\";\n }\n}\nfunction finish(record: Recovery) {\n if (record.timer) clearInterval(record.timer);\n recoveries.delete(record);\n}\nfunction attempt(record: Recovery, known?: Address): Promise<boolean> {\n record.attempt ??= (async () => {\n const exited = !alive(record.identity.pid);\n if (exited) await record.gate.releaseAfterOwnerExit(record.identity.pid);\n const address = known ?? (await findDaemon(record.root));\n if (!address || (!exited && address.identity.instance !== record.identity.instance)) return false;\n // Only plain closed-session facts and detached grants cross this recovery boundary.\n // Reclaim the obsolete participant on a compatible owner, reject all new work,\n // and service release callbacks until an authenticated detach confirms drain.\n const connection = new DaemonConnection(\n address.paths,\n address.identity,\n {\n ...record.facts,\n hasUI: false,\n idle: false,\n ready: false,\n },\n {\n callback: async (callback) => {\n const data = callback.payload;\n if (\n callback.kind === \"queue-release\" &&\n data !== null &&\n typeof data === \"object\" &&\n \"reservation\" in data &&\n typeof data.reservation === \"string\"\n ) {\n await record.gate.releaseRequest(data.reservation);\n return true;\n }\n throw new Error(\"Closed Pi participant cannot authorize new work.\");\n },\n },\n );\n try {\n // Cleanup polling does not attach or recreate a retired participant.\n await connection.dispose();\n await record.gate.releaseAfterDrain();\n finish(record);\n return true;\n } finally {\n await connection.dispose();\n }\n })()\n .catch(() => false)\n .finally(() => {\n record.attempt = undefined;\n });\n return record.attempt;\n}\n\n/** Intentionally shared cleanup may outlive a session, but never retains its ctx or UI. */\nexport function quarantineClient(gate: PiApplyGate, root: string, identity: Identity, facts: ClientFacts) {\n gate.detach();\n const record: Recovery = { gate, root, identity: structuredClone(identity), facts: structuredClone(facts) };\n recoveries.add(record);\n record.timer = setInterval(() => {\n void attempt(record);\n }, 1000);\n record.timer.unref();\n void attempt(record);\n}\n\n/** A newly attached client stays unready until obsolete local participants are retired. */\nexport async function recoverDetachedClients(address: Address) {\n const pending = [...recoveries].filter((record) => record.root === address.paths.root);\n const results = await Promise.all(\n pending.map(async (record) => {\n const done = await attempt(record, address);\n return done || !recoveries.has(record) || (await attempt(record, address));\n }),\n );\n if (results.some((done) => !done))\n throw new Error(\n \"Previous Pi cleanup is still uncertain; stop or repair the existing daemon before retrying /reload.\",\n );\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;AAAA,SAAS,yBAAyB;AAClC,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,oBAAoB;AAC7B,OAAO,QAAQ;AACf,OAAOC,WAAU;AACjB,SAAgC,mBAAmB;AACnD;AAAA,EAKE,oBAAAC;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA,cAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAA+B,2BAA2B;AAC1D;AAAA,EAEE;AAAA,OACK;AACP,SAAS,gCAAgC;AACzC,SAAS,6BAA6B;;;AC3BtC,SAAS,kBAAkB;AAC3B,OAAO,UAAU;AACjB,SAAS,6BAA6B;AACtC,SAAS,wBAAwB;AAgB1B,IAAM,cAAN,MAAkB;AAAA,EAEvB,YAAoB,UAAsB;AAAtB;AAAA,EAAuB;AAAA,EAAvB;AAAA,EADZ,QAAQ,oBAAI,IAAkB;AAAA,EAEtC,MAAM,QAAQ,WAAmB,SAA4B,QAAsB;AACjF,SAAK,SAAS;AACd,YAAQ,eAAe;AACvB,QACE,CAAC,QAAQ,UACT,QAAQ,SAAS,SACjB,QAAQ,KAAK,CAAC,WAAW,OAAO,WAAW,YAAY,OAAO,SAAS,IAAI,KAAK,CAAC,KAAK,WAAW,MAAM,CAAC;AAExG,YAAM,IAAI,MAAM,kCAAkC;AACpD,UAAM,aAAa,CAAC,GAAG,I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;AAChB,YAAI,QAAQ,IAAI,KAAK,OAAO,MAAM,KAAM,SAAQ,OAAO,KAAK,OAAO;AACnE,cAAM,OAAO,KAAK;AAClB,aAAK,OAAO;AACZ,YAAI,YAAY;AACd,cAAI,UAAW,OAAM,KAAK,kBAAkB;AAAA,cACvC,kBAAiB,MAAM,WAAW,MAAM,MAAM,WAAW,UAAU,WAAW,KAAK;AAAA,QAC1F;AACA,cAAM,KAAK;AAAA,MACb;AAAA,IACF,GAAG;AACH,WAAO,KAAK;AAAA,EACd;AACF;",
6
+ "names": ["randomUUID", "path", "DaemonConnection", "findDaemon", "path", "randomUUID", "findDaemon", "connection", "DaemonConnection", "attempt"]
7
+ }