@narumitw/pi-sync 0.67.3 → 0.68.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +26 -48
  3. package/dist/chunks/{chunk-XUZV4OGI.ts → chunk-335XTMMZ.ts} +3 -2
  4. package/dist/chunks/{chunk-XUZV4OGI.ts.map → chunk-335XTMMZ.ts.map} +2 -2
  5. package/dist/chunks/{chunk-PUSMSKIM.ts → chunk-AYGMIMCV.ts} +2 -11
  6. package/dist/chunks/chunk-AYGMIMCV.ts.map +7 -0
  7. package/dist/chunks/{chunk-HLJIRWFL.ts → chunk-BCDBT4X3.ts} +7 -7
  8. package/dist/chunks/{chunk-AVTW6WNP.ts → chunk-FQKWGVMA.ts} +20 -54
  9. package/dist/chunks/chunk-FQKWGVMA.ts.map +7 -0
  10. package/dist/chunks/{chunk-DGVZYS7T.ts → chunk-FR6A7ASZ.ts} +8 -11
  11. package/dist/chunks/chunk-FR6A7ASZ.ts.map +7 -0
  12. package/dist/chunks/{chunk-3NS4PMCI.ts → chunk-J52GYZO6.ts} +2 -8
  13. package/dist/chunks/{chunk-3NS4PMCI.ts.map → chunk-J52GYZO6.ts.map} +2 -2
  14. package/dist/chunks/{chunk-2MUAR5GH.ts → chunk-KAIVTJIQ.ts} +7 -10
  15. package/dist/chunks/chunk-KAIVTJIQ.ts.map +7 -0
  16. package/dist/chunks/{chunk-WBIOSK76.ts → chunk-R7PN3KIY.ts} +1 -2
  17. package/dist/chunks/{chunk-3Q3DMMID.ts → chunk-TLYT6HVI.ts} +8 -8
  18. package/dist/chunks/{chunk-X344HTVV.ts → chunk-WCGLU526.ts} +39 -118
  19. package/dist/chunks/chunk-WCGLU526.ts.map +7 -0
  20. package/dist/chunks/{chunk-JREGWM2B.ts → chunk-XNUARYLR.ts} +1 -2
  21. package/dist/chunks/{chunk-CQ4DMLH3.ts → chunk-YV2R5SJU.ts} +21 -81
  22. package/dist/chunks/chunk-YV2R5SJU.ts.map +7 -0
  23. package/dist/chunks/{command-handler-WF2TDDRZ.ts → command-handler-S6BRZMPW.ts} +64 -59
  24. package/dist/chunks/command-handler-S6BRZMPW.ts.map +7 -0
  25. package/dist/chunks/{conflict-review-GWEL4S6C.ts → conflict-review-3XMYDJIK.ts} +2 -2
  26. package/dist/chunks/{file-selection-GASCVN45.ts → file-selection-4BOQBXS7.ts} +10 -17
  27. package/dist/chunks/file-selection-4BOQBXS7.ts.map +7 -0
  28. package/dist/chunks/{manager-result-dispatcher-BXN46NRC.ts → manager-result-dispatcher-A4IWLS4J.ts} +7 -7
  29. package/dist/chunks/{manager-ui-FS4QIKRA.ts → manager-ui-KHMCSLLV.ts} +114 -581
  30. package/dist/chunks/manager-ui-KHMCSLLV.ts.map +7 -0
  31. package/dist/chunks/{chunk-ECUCXF5Y.ts → merge-review-LWMUE5IW.ts} +2 -3
  32. package/dist/chunks/{remote-selection-ui-DOYKUMER.ts → remote-selection-ui-F6NJBQ3Y.ts} +6 -6
  33. package/dist/chunks/{setup-switch-JZDFQPVW.ts → setup-switch-7LMIRMZ7.ts} +6 -6
  34. package/dist/chunks/{setup-wizard-PI45SF2C.ts → setup-wizard-2NRPR433.ts} +11 -16
  35. package/dist/chunks/{setup-wizard-PI45SF2C.ts.map → setup-wizard-2NRPR433.ts.map} +1 -1
  36. package/dist/chunks/{sync-inspection-DI5J6EUH.ts → sync-inspection-QGM54YCM.ts} +5 -5
  37. package/dist/chunks/{sync-operations-AGNL7QXA.ts → sync-operations-DTQMKVRQ.ts} +2 -2
  38. package/dist/daemon/dist/build-id.json +1 -1
  39. package/dist/daemon/dist/cli.js +22 -3
  40. package/dist/daemon/dist/client-transport.js +2 -0
  41. package/dist/daemon/dist/client.js +2 -10
  42. package/dist/daemon/dist/consent.js +13 -135
  43. package/dist/daemon/dist/engine/backends/git/git-backend.js +4 -17
  44. package/dist/daemon/dist/engine/backends/git/git-storage.js +11 -44
  45. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +6 -6
  46. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +6 -6
  47. package/dist/daemon/dist/engine/settings/config.js +16 -149
  48. package/dist/daemon/dist/engine/settings/retired-ignore-policy.js +16 -0
  49. package/dist/daemon/dist/engine/settings/retired-ignore-recovery.js +14 -0
  50. package/dist/daemon/dist/engine/settings/settings-management.js +2 -10
  51. package/dist/daemon/dist/engine/settings/settings-validation.js +8 -21
  52. package/dist/daemon/dist/engine/snapshot/session-paths.js +13 -41
  53. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +8 -24
  54. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +7 -11
  55. package/dist/daemon/dist/engine/snapshot/snapshot-exclude-safety.js +19 -76
  56. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +1 -7
  57. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-policy.js +8 -102
  58. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +20 -100
  59. package/dist/daemon/dist/engine/snapshot/snapshot-types.js +1 -11
  60. package/dist/daemon/dist/engine/snapshot/snapshot.js +26 -78
  61. package/dist/daemon/dist/engine/state/sync-state-store.js +5 -1
  62. package/dist/daemon/dist/engine/sync/agent-plan.js +0 -1
  63. package/dist/daemon/dist/engine/sync/agent-policy.js +1 -1
  64. package/dist/daemon/dist/engine/sync/conflict-review.js +0 -2
  65. package/dist/daemon/dist/engine/sync/continuous-sync.js +2 -17
  66. package/dist/daemon/dist/engine/sync/continuous-watch.js +3 -7
  67. package/dist/daemon/dist/engine/sync/directional-action.js +3 -21
  68. package/dist/daemon/dist/engine/sync/initialization.js +4 -15
  69. package/dist/daemon/dist/engine/sync/local-fields.js +4 -65
  70. package/dist/daemon/dist/engine/sync/merge-apply.js +8 -31
  71. package/dist/daemon/dist/engine/sync/merge-journal.js +8 -118
  72. package/dist/daemon/dist/engine/sync/merged-sync.js +12 -70
  73. package/dist/daemon/dist/engine/sync/push-review.js +1 -16
  74. package/dist/daemon/dist/engine/sync/remote-snapshot.js +48 -65
  75. package/dist/daemon/dist/engine/sync/startup-bootstrap.js +3 -3
  76. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +1 -1
  77. package/dist/daemon/dist/engine/sync/sync-inspection.js +1 -2
  78. package/dist/daemon/dist/engine/sync/sync-mutations.js +25 -118
  79. package/dist/daemon/dist/engine/sync/sync-policy.js +26 -150
  80. package/dist/daemon/dist/engine/sync/sync-queries.js +1 -8
  81. package/dist/daemon/dist/engine/sync/sync-rollback.js +12 -50
  82. package/dist/daemon/dist/engine/sync/sync-state.js +2 -15
  83. package/dist/daemon/dist/engine/sync/transfer-freshness.js +7 -17
  84. package/dist/daemon/dist/engine/sync/transfer-size-limits.js +3 -7
  85. package/dist/daemon/dist/engine-service.js +60 -219
  86. package/dist/daemon/dist/foreground-queue-outcome.js +0 -4
  87. package/dist/daemon/dist/legacy-consent-guard.js +34 -0
  88. package/dist/daemon/dist/server.js +4 -8
  89. package/dist/daemon/dist/service-host.js +3 -9
  90. package/dist/daemon/package.json +1 -1
  91. package/dist/index.ts +45 -46
  92. package/dist/index.ts.map +3 -3
  93. package/docs/continuous-sync-verification.md +1 -1
  94. package/docs/daemon-migration.md +7 -5
  95. package/docs/tui-contract.md +4 -6
  96. package/package.json +2 -3
  97. package/skills/configure-pi-sync/SKILL.md +18 -77
  98. package/skills/configure-pi-sync/references/configuration.md +58 -75
  99. package/src/commands/command-execution.ts +13 -29
  100. package/src/commands/command-handler.ts +0 -4
  101. package/src/commands/command.ts +2 -1
  102. package/src/daemon/directional-recovery.ts +4 -33
  103. package/src/daemon/pi-client.ts +20 -88
  104. package/src/settings/config.ts +0 -1
  105. package/src/sync/setup-switch.ts +1 -4
  106. package/src/sync-extension.ts +10 -24
  107. package/src/ui/cancellable-operation.ts +2 -13
  108. package/src/ui/excluded-paths-ui.ts +1 -4
  109. package/src/ui/file-selection.ts +0 -5
  110. package/src/ui/manager-state.ts +12 -75
  111. package/src/ui/manager-ui.ts +7 -96
  112. package/src/ui/remote-selection-ui.ts +29 -130
  113. package/src/ui/settings-ui.ts +169 -388
  114. package/src/ui/setup/setup-actions.ts +4 -16
  115. package/src/ui/setup/setup-prompts.ts +12 -49
  116. package/src/ui/setup/setup-switcher.ts +8 -14
  117. package/src/ui/storage-connections-ui.ts +21 -32
  118. package/src/ui/sync-setups-ui.ts +27 -53
  119. package/dist/chunks/chunk-2MUAR5GH.ts.map +0 -7
  120. package/dist/chunks/chunk-33EDXDLC.ts +0 -106
  121. package/dist/chunks/chunk-33EDXDLC.ts.map +0 -7
  122. package/dist/chunks/chunk-AVTW6WNP.ts.map +0 -7
  123. package/dist/chunks/chunk-CQ4DMLH3.ts.map +0 -7
  124. package/dist/chunks/chunk-DGVZYS7T.ts.map +0 -7
  125. package/dist/chunks/chunk-EJDDRS6O.ts +0 -17
  126. package/dist/chunks/chunk-EJDDRS6O.ts.map +0 -7
  127. package/dist/chunks/chunk-KNEUL4XN.ts +0 -30
  128. package/dist/chunks/chunk-KNEUL4XN.ts.map +0 -7
  129. package/dist/chunks/chunk-PUSMSKIM.ts.map +0 -7
  130. package/dist/chunks/chunk-WFBHWYI6.ts +0 -18
  131. package/dist/chunks/chunk-WFBHWYI6.ts.map +0 -7
  132. package/dist/chunks/chunk-X344HTVV.ts.map +0 -7
  133. package/dist/chunks/command-handler-WF2TDDRZ.ts.map +0 -7
  134. package/dist/chunks/config-P54GGMXY.ts +0 -39
  135. package/dist/chunks/continuous-record-3SKJ6I3V.ts +0 -23
  136. package/dist/chunks/continuous-record-3SKJ6I3V.ts.map +0 -7
  137. package/dist/chunks/continuous-storage-3EU6I7Z3.ts +0 -27
  138. package/dist/chunks/continuous-storage-3EU6I7Z3.ts.map +0 -7
  139. package/dist/chunks/file-selection-GASCVN45.ts.map +0 -7
  140. package/dist/chunks/ignore-file-ui-BEZZZIEE.ts +0 -21
  141. package/dist/chunks/manager-ui-FS4QIKRA.ts.map +0 -7
  142. package/dist/chunks/merge-review-C2KETZKY.ts +0 -11
  143. package/dist/chunks/merge-review-C2KETZKY.ts.map +0 -7
  144. package/dist/chunks/remote-selection-ui-DOYKUMER.ts.map +0 -7
  145. package/dist/chunks/setup-switch-JZDFQPVW.ts.map +0 -7
  146. package/dist/daemon/dist/engine/ignore/adoption-journal.js +0 -146
  147. package/dist/daemon/dist/engine/ignore/effective-ignore-policy.js +0 -33
  148. package/dist/daemon/dist/engine/ignore/ignore-edit.js +0 -102
  149. package/dist/daemon/dist/engine/ignore/ignore-initialization.js +0 -288
  150. package/dist/daemon/dist/engine/ignore/ignore-migration-prompt.js +0 -139
  151. package/dist/daemon/dist/engine/ignore/ignore-settings.js +0 -391
  152. package/dist/daemon/dist/engine/ignore/ignore-source.js +0 -250
  153. package/dist/daemon/dist/engine/ignore/snapshot-ignore-rules.js +0 -39
  154. package/dist/daemon/dist/engine/sync/ignore-adoption-recovery.js +0 -50
  155. package/dist/daemon/dist/engine/sync/ignore-adoption.js +0 -416
  156. package/dist/daemon/dist/engine/sync/ignore-publication.js +0 -23
  157. package/dist/daemon/dist/engine/ui/ignore-rule-preview.js +0 -18
  158. package/dist/daemon/dist/monitor.js +0 -344
  159. package/src/ui/agent-mode-setting.ts +0 -99
  160. package/src/ui/ignore-file-guidance.ts +0 -7
  161. package/src/ui/ignore-file-ui.ts +0 -105
  162. package/src/ui/ignore-migration-prompt.ts +0 -65
  163. package/src/ui/settings-review.ts +0 -26
  164. /package/dist/chunks/{chunk-HLJIRWFL.ts.map → chunk-BCDBT4X3.ts.map} +0 -0
  165. /package/dist/chunks/{chunk-WBIOSK76.ts.map → chunk-R7PN3KIY.ts.map} +0 -0
  166. /package/dist/chunks/{chunk-3Q3DMMID.ts.map → chunk-TLYT6HVI.ts.map} +0 -0
  167. /package/dist/chunks/{chunk-JREGWM2B.ts.map → chunk-XNUARYLR.ts.map} +0 -0
  168. /package/dist/chunks/{conflict-review-GWEL4S6C.ts.map → conflict-review-3XMYDJIK.ts.map} +0 -0
  169. /package/dist/chunks/{config-P54GGMXY.ts.map → manager-result-dispatcher-A4IWLS4J.ts.map} +0 -0
  170. /package/dist/chunks/{chunk-ECUCXF5Y.ts.map → merge-review-LWMUE5IW.ts.map} +0 -0
  171. /package/dist/chunks/{ignore-file-ui-BEZZZIEE.ts.map → remote-selection-ui-F6NJBQ3Y.ts.map} +0 -0
  172. /package/dist/chunks/{manager-result-dispatcher-BXN46NRC.ts.map → setup-switch-7LMIRMZ7.ts.map} +0 -0
  173. /package/dist/chunks/{sync-inspection-DI5J6EUH.ts.map → sync-inspection-QGM54YCM.ts.map} +0 -0
  174. /package/dist/chunks/{sync-operations-AGNL7QXA.ts.map → sync-operations-DTQMKVRQ.ts.map} +0 -0
@@ -1,344 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import path from "node:path";
3
- import { automaticPolicyAuthorized, ConsentPublicationError, consentFingerprint, participantBinding, readConsent, revokeChangedBindings, } from "./consent.js";
4
- import { loadConfigForCheck, syncCheckConfigFingerprint } from "./engine/settings/config.js";
5
- import { createEngineLoaders } from "./engine/sync/sync-loaders.js";
6
- import { createServiceContext } from "./service-host.js";
7
- export function createMonitor(root, host) {
8
- let server;
9
- let task;
10
- let transition = Promise.resolve();
11
- let closed = false;
12
- let authorizationFailed = false;
13
- let scheduled = false;
14
- let settingsGeneration = 0;
15
- let blockedParticipants;
16
- const participatingSessions = () => JSON.stringify(server
17
- ?.participants()
18
- .map(({ id, generation }) => `${id}:${generation}`)
19
- .sort() ?? []);
20
- const policyNeedsReview = () => blockedParticipants === participatingSessions();
21
- let monitoredPolicy;
22
- const retries = new Map();
23
- const retryOwner = (peer) => JSON.stringify([peer.generation, peer.cwd, peer.sessionId, peer.sessionFile, peer.sessionDir, peer.model]);
24
- let epoch;
25
- const timingOwners = new WeakMap();
26
- const cycleOutcomes = new Map();
27
- const loaders = createEngineLoaders();
28
- let continuous;
29
- function schedule() {
30
- if (closed || scheduled || !server)
31
- return;
32
- scheduled = true;
33
- setImmediate(() => {
34
- scheduled = false;
35
- transition = transition.then(start).catch(() => { });
36
- });
37
- }
38
- function blockAutomatic() {
39
- authorizationFailed = true;
40
- retries.clear();
41
- task?.controller.abort(new DOMException("Daemon safety barrier", "AbortError"));
42
- }
43
- async function stop() {
44
- const current = task;
45
- if (!current)
46
- return;
47
- task = undefined;
48
- current.controller.abort(new DOMException("Daemon monitoring interrupted", "AbortError"));
49
- await current.continuous.stop();
50
- await current.promise;
51
- }
52
- function unattendedGrant(config) {
53
- if (!config.continuous || !config.agentMode || !automaticPolicyAuthorized(root, config))
54
- return undefined;
55
- const saved = readConsent(root)?.setups[config.setupName];
56
- return saved?.afterExit && saved.fingerprint === consentFingerprint(root, config) ? saved : undefined;
57
- }
58
- async function lifetime() {
59
- if (closed || authorizationFailed)
60
- return "pause";
61
- try {
62
- const consent = readConsent(root);
63
- if (!consent || !Object.values(consent.setups).some((saved) => saved.afterExit))
64
- return "exit";
65
- const config = await loadConfigForCheck();
66
- if (closed || authorizationFailed)
67
- return "pause";
68
- return !policyNeedsReview() && unattendedGrant(config) ? "keep" : "exit";
69
- }
70
- catch {
71
- // Invalid evidence is not an implicit revocation or permission to discard a safety barrier.
72
- return "pause";
73
- }
74
- }
75
- async function start() {
76
- const service = server;
77
- if (!service)
78
- return;
79
- if (closed || authorizationFailed || policyNeedsReview() || task || !service.isIdle())
80
- return;
81
- const generation = settingsGeneration;
82
- const participants = service.participantGeneration?.();
83
- const participantsToken = participantBinding(service);
84
- const consentToken = JSON.stringify(readConsent(root));
85
- const sameAuthorization = () => !closed &&
86
- !authorizationFailed &&
87
- !policyNeedsReview() &&
88
- server === service &&
89
- generation === settingsGeneration &&
90
- participants === service.participantGeneration?.() &&
91
- participantsToken === participantBinding(service) &&
92
- consentToken === JSON.stringify(readConsent(root));
93
- const available = () => !task && service.isIdle() && sameAuthorization();
94
- if (!consentToken || !available())
95
- return;
96
- const config = await loadConfigForCheck();
97
- if (!available() || !automaticPolicyAuthorized(root, config))
98
- return;
99
- if (!config.continuous || !config.agentMode) {
100
- retries.clear();
101
- return;
102
- }
103
- const { pendingTransactionEntries } = await import("./engine/snapshot/snapshot-transaction-directory.js");
104
- if ((await pendingTransactionEntries()).some((entry) => entry.isDirectory()) || !available())
105
- return;
106
- const peers = service.participants();
107
- if (peers.some((peer) => !peer.idle || peer.ready !== true))
108
- return;
109
- const fingerprint = syncCheckConfigFingerprint(config);
110
- if (config.reservedIgnoreNames !== undefined && monitoredPolicy !== undefined && monitoredPolicy !== fingerprint)
111
- return;
112
- const authorized = unattendedGrant(config);
113
- const selected = peers.toSorted((a, b) => a.id.localeCompare(b.id))[0];
114
- if (!selected && !authorized)
115
- return;
116
- if (!continuous) {
117
- const { createContinuousSync } = await import("./engine/sync/continuous-sync.js");
118
- if (!available())
119
- return;
120
- continuous = createContinuousSync(loaders, undefined, (ctx, report) => timingOwners.get(ctx)?.emit("timings", { report }), {
121
- timing: (ctx, report) => timingOwners.get(ctx)?.debug?.({ event: "startup-timings", report }),
122
- cycle(ctx, setup, outcome) {
123
- const debug = timingOwners.get(ctx)?.debug;
124
- if (!debug)
125
- return;
126
- const key = `${outcome.outcome}:${outcome.reason ?? ""}`;
127
- if (outcome.outcome !== "completed" && cycleOutcomes.get(setup) === key)
128
- return;
129
- cycleOutcomes.delete(setup);
130
- cycleOutcomes.set(setup, key);
131
- if (cycleOutcomes.size > 64) {
132
- const oldest = cycleOutcomes.keys().next().value;
133
- if (oldest !== undefined)
134
- cycleOutcomes.delete(oldest);
135
- }
136
- debug({ event: "continuous-cycle", ...outcome });
137
- },
138
- });
139
- // Re-enter every eligibility branch after importing the full engine graph.
140
- return start();
141
- }
142
- const activeContinuous = continuous;
143
- const binding = selected?.model ?? authorized?.model;
144
- const sessionDir = selected ? selected.sessionDir : authorized?.sessionDir;
145
- const cwd = selected?.cwd ?? authorized?.cwd ?? root;
146
- const key = peers
147
- .map((peer) => `${peer.id}:${peer.generation}`)
148
- .sort()
149
- .join(",") || "unattended";
150
- if (epoch?.key !== key) {
151
- epoch?.controller.abort(new DOMException("Participating sessions changed", "AbortError"));
152
- const location = { sessionDir, cwd };
153
- const manager = {
154
- getSessionId: () => key,
155
- getCwd: () => location.cwd,
156
- getSessionDir: () => location.sessionDir ?? path.join(root, "sessions"),
157
- usesDefaultSessionDir: () => location.sessionDir === undefined,
158
- };
159
- epoch = { key, controller: new AbortController(), manager, location, debug: selected?.startupDebug ?? false };
160
- }
161
- epoch.location.sessionDir = sessionDir;
162
- epoch.location.cwd = cwd;
163
- const controller = new AbortController();
164
- const original = service.backgroundExecution(controller.signal);
165
- const stableFacts = {
166
- id: randomUUID(),
167
- generation: randomUUID(),
168
- pid: process.pid,
169
- cwd,
170
- mode: "rpc",
171
- hasUI: false,
172
- idle: true,
173
- sessionDir,
174
- model: binding,
175
- };
176
- const execution = { ...original, facts: () => stableFacts };
177
- const allowed = (currentConfig = config) => {
178
- if (controller.signal.aborted ||
179
- !sameAuthorization() ||
180
- syncCheckConfigFingerprint(currentConfig) !== fingerprint)
181
- return false;
182
- const current = service.participants();
183
- if (current.length)
184
- return current.every((peer) => peer.idle &&
185
- peer.ready === true &&
186
- JSON.stringify(peer.model) === JSON.stringify(binding) &&
187
- peer.sessionDir === sessionDir &&
188
- peer.cwd === cwd);
189
- const saved = unattendedGrant(currentConfig);
190
- return Boolean(saved &&
191
- JSON.stringify(saved.model) === JSON.stringify(binding) &&
192
- saved.sessionDir === sessionDir &&
193
- (saved.cwd ?? root) === cwd);
194
- };
195
- const ctx = createServiceContext(execution);
196
- ctx.reload = undefined;
197
- ctx.sessionManager = epoch.manager;
198
- Object.defineProperty(ctx, "hasUI", {
199
- get: () => service.participants().some((peer) => peer.hasUI && peer.ready === true),
200
- });
201
- timingOwners.set(ctx, execution);
202
- ctx.backgroundAuthorized = allowed;
203
- ctx.isIdle = () => Boolean(service.isIdle() && allowed());
204
- const refresh = async () => {
205
- execution.validate();
206
- if (!allowed(await loadConfigForCheck(undefined, controller.signal)))
207
- throw new Error("Daemon automatic authorization changed.");
208
- execution.validate();
209
- };
210
- const sessionSignal = epoch.controller.signal;
211
- const debug = epoch.debug;
212
- let finish;
213
- const promise = new Promise((resolve) => {
214
- finish = resolve;
215
- });
216
- const current = { controller, continuous: activeContinuous, promise };
217
- task = current;
218
- void host
219
- .run(execution, async () => {
220
- const { prepareResolverHost } = await import("./resolver-host.js");
221
- await refresh();
222
- const resolver = await prepareResolverHost(root, binding, controller.signal);
223
- try {
224
- await refresh();
225
- if (config.reservedIgnoreNames !== undefined)
226
- monitoredPolicy = fingerprint;
227
- ctx.model = resolver.model;
228
- ctx.modelUnavailableReason = resolver.unavailable;
229
- ctx.modelRegistry = {
230
- streamSimple: (model, context, options) => {
231
- execution.validate();
232
- if (!allowed())
233
- throw new Error("Daemon authorization changed before model dispatch.");
234
- return resolver.registry.streamSimple(model, context, options);
235
- },
236
- };
237
- ctx.validateModel = async () => {
238
- await refresh();
239
- for (const peer of peers) {
240
- const fresh = await execution.request("model-binding", { background: true }, peer.id);
241
- if (JSON.stringify(fresh ?? undefined) !== JSON.stringify(binding))
242
- throw new Error("Participating model changed before dispatch.");
243
- await refresh();
244
- }
245
- };
246
- const explicitRetry = service.participants().some((peer) => {
247
- const retry = retries.get(peer.id);
248
- return retry?.fingerprint === fingerprint && retry.owner === retryOwner(peer) && !retry.signal.aborted;
249
- });
250
- retries.clear();
251
- activeContinuous.start(ctx, sessionSignal, explicitRetry ? config.setupName : false, debug, async (run) => {
252
- await refresh();
253
- const attempt = new AbortController();
254
- const owner = service.backgroundExecution(AbortSignal.any([attempt.signal, controller.signal]));
255
- try {
256
- return await host.run({ ...owner, facts: execution.facts }, () => run(owner.committed));
257
- }
258
- finally {
259
- attempt.abort();
260
- }
261
- });
262
- await new Promise((resolve) => {
263
- if (controller.signal.aborted)
264
- resolve();
265
- else
266
- controller.signal.addEventListener("abort", () => resolve(), { once: true });
267
- });
268
- await activeContinuous.stop();
269
- }
270
- finally {
271
- await resolver.settle();
272
- }
273
- })
274
- .catch(() => { })
275
- .finally(() => {
276
- controller.abort();
277
- if (task === current)
278
- task = undefined;
279
- finish();
280
- });
281
- }
282
- return {
283
- bind(value) {
284
- server = value;
285
- schedule();
286
- },
287
- schedule,
288
- lifetime,
289
- blockAutomatic,
290
- foregroundRecoveryAllowed: () => !authorizationFailed,
291
- explicitSync(config, execution) {
292
- const peer = execution.facts();
293
- if (closed || !peer)
294
- return;
295
- const fingerprint = syncCheckConfigFingerprint(config);
296
- retries.set(peer.id, { fingerprint, owner: retryOwner(peer), signal: execution.signal });
297
- },
298
- reviewedPolicy(config) {
299
- blockedParticipants = undefined;
300
- monitoredPolicy = config.reservedIgnoreNames === undefined ? undefined : syncCheckConfigFingerprint(config);
301
- },
302
- settingsCommitted(blockNewPolicy) {
303
- settingsGeneration++;
304
- retries.clear();
305
- if (blockNewPolicy)
306
- blockedParticipants = participatingSessions();
307
- task?.controller.abort(new DOMException("Sync settings committed", "AbortError"));
308
- },
309
- async pause() {
310
- transition = transition.then(stop);
311
- await transition;
312
- },
313
- async factsChanged() {
314
- let failure;
315
- try {
316
- if (server) {
317
- const peers = server.participants();
318
- for (const [id, retry] of retries)
319
- if (retry.signal.aborted || !peers.some((peer) => peer.id === id && retryOwner(peer) === retry.owner))
320
- retries.delete(id);
321
- revokeChangedBindings(root, peers);
322
- }
323
- }
324
- catch (error) {
325
- blockAutomatic();
326
- // Recovery barriers must not prevent passive clients from registering protection.
327
- if (error instanceof ConsentPublicationError)
328
- failure = error;
329
- }
330
- transition = transition.then(stop);
331
- await transition;
332
- if (failure)
333
- throw new Error("Daemon authorization could not be saved. Automatic work is blocked for this instance; repair and revoke permission before an explicit restart.", { cause: failure });
334
- schedule();
335
- },
336
- async close() {
337
- closed = true;
338
- retries.clear();
339
- transition = transition.then(stop);
340
- await transition;
341
- epoch?.controller.abort();
342
- },
343
- };
344
- }
@@ -1,99 +0,0 @@
1
- import { isDeepStrictEqual } from "node:util";
2
- import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
3
- import { requireSettings, updateLocalConfig } from "../settings/settings-store.js";
4
- import { captureMutationOwner } from "../sync/sync-local.js";
5
- import { confirmMergeReview } from "./merge-review.js";
6
- import { directorySessionOptInLine } from "./setup/directory-rules.js";
7
- import { safeTerminalText } from "./terminal-text.js";
8
-
9
- export const AGENT_MODE_DESCRIPTION =
10
- "This setup: sync eligible changes at session startup and on Sync now without transfer confirmation. Use the selected Pi model to resolve supported text and settings conflicts. Eligible conflict content may be sent to its provider and incur costs. Selected local and remote content can be replaced or deleted. Unresolved conflicts pause unless partial sync permits independent progress. Continuous sync is a separate opt-in. No automatic reload.";
11
-
12
- export const CONTINUOUS_DESCRIPTION =
13
- "This setup: recurring sync while Pi is open. Requires Autonomous sync. Watches selected files, checks the remote every 60–66 seconds, and retries temporary failures. Local changes and retries can cause extra requests between polls. May disclose conflict text and incur model/storage costs. No automatic reload.";
14
-
15
- export function saveContinuousMode(
16
- ctx: ExtensionCommandContext,
17
- setupName: string,
18
- enabled: boolean,
19
- signal?: AbortSignal,
20
- ) {
21
- return saveAgentMode(ctx, setupName, enabled, signal, "continuous");
22
- }
23
-
24
- export async function saveAgentMode(
25
- ctx: ExtensionCommandContext,
26
- setupName: string,
27
- enabled: boolean,
28
- signal?: AbortSignal,
29
- preference: "agentMode" | "continuous" = "agentMode",
30
- ) {
31
- const validate = captureMutationOwner(ctx, signal);
32
- const settings = await requireSettings();
33
- validate();
34
- const setup = settings.syncSetups[setupName];
35
- if (!setup || settings.activeSyncSetup !== setupName) throw new Error("Current sync setup changed; reopen Settings.");
36
- const continuous = preference === "continuous";
37
- const label = continuous ? "Continuous sync" : "Autonomous sync";
38
- if (enabled && continuous && !setup.sync.agentMode) throw new Error("Enable Autonomous sync before Continuous sync.");
39
- if (Boolean(setup.sync[preference]) === enabled) return true;
40
- if (enabled) {
41
- const summary = [
42
- `Setup: ${safeTerminalText(setupName)}`,
43
- `Storage connection: ${safeTerminalText(setup.storage.connection)}`,
44
- `Storage path: ${safeTerminalText(setup.storage.path)}`,
45
- ...(setup.storage.bucket ? [`Bucket: ${safeTerminalText(String(setup.storage.bucket))}`] : []),
46
- ...(setup.storage.branch ? [`Branch: ${safeTerminalText(String(setup.storage.branch))}`] : []),
47
- ...(setup.sync.scope
48
- ? [
49
- "Sync scope: all eligible files in the Pi agent directory.",
50
- directorySessionOptInLine(setup.sync.sessions),
51
- `Excluded paths: ${setup.sync.exclude?.map(safeTerminalText).join(", ") || "none"}`,
52
- `Re-included paths: ${setup.sync.reinclude?.map(safeTerminalText).join(", ") || "none"}`,
53
- ]
54
- : [`Included paths: ${setup.sync.include.map(safeTerminalText).join(", ")}`]),
55
- continuous ? CONTINUOUS_DESCRIPTION : AGENT_MODE_DESCRIPTION,
56
- ...(continuous
57
- ? [
58
- "Upgrade all Pi processes sharing this agent directory before enabling Continuous sync. Monitoring starts after the /sync command or manager closes. An elected idle local session uses its selected Pi model; another session can use a different provider/model. Each computer is a separate replica.",
59
- "Automatic requests are limited to two per candidate and two per replica binding in a rolling 15-minute window, across restarts. Network/storage checks and requests may incur costs. Retries start at five seconds and grow to five minutes. These are request bounds, not a currency cap.",
60
- ]
61
- : setup.sync.continuous
62
- ? ["The saved Continuous sync preference will resume monitoring after the /sync command or manager closes."]
63
- : []),
64
- "Only bounded Markdown/plain-text conflicts and atomic global settings choices are eligible. Model errors can change intended behavior. Session histories, code, deletion conflicts and path collisions are not model-resolved.",
65
- "The existing baseline, selection, secret-scan and publication checks remain. Pi Sync cannot exclude arbitrary concurrent local writers. Disabling does not undo completed transfers or provider charges. No transfer starts from Settings.",
66
- ].join("\n\n");
67
- if (
68
- !(await confirmMergeReview(
69
- ctx,
70
- `Enable ${label}?`,
71
- summary,
72
- signal,
73
- () => !signal?.aborted,
74
- `Enable ${label}`,
75
- summary.split("\n"),
76
- ))
77
- )
78
- return false;
79
- validate();
80
- }
81
- await updateLocalConfig((current) => {
82
- validate();
83
- if (
84
- current.activeSyncSetup !== setupName ||
85
- !isDeepStrictEqual(current.syncSetups[setupName], setup) ||
86
- !isDeepStrictEqual(
87
- current.storageConnections[setup.storage.connection],
88
- settings.storageConnections[setup.storage.connection],
89
- )
90
- )
91
- throw new Error("Sync setup or connection changed during Autonomous sync review; reopen Settings.");
92
- return {
93
- ...current,
94
- syncSetups: { ...current.syncSetups, [setupName]: { ...setup, sync: { ...setup.sync, [preference]: enabled } } },
95
- };
96
- }, signal);
97
- // The atomic writer has committed. Later cancellation cannot undo this save.
98
- return true;
99
- }
@@ -1,7 +0,0 @@
1
- import { resolve } from "node:path";
2
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
3
- import { safeTerminalText } from "./terminal-text.js";
4
-
5
- export function manualIgnoreFileGuidance(filename: string) {
6
- return `Edit existing ignore rules manually: ${safeTerminalText(resolve(getAgentDir(), filename))}. Edits apply to every setup using this local file on its next sync; they do not rewrite remote history.`;
7
- }
@@ -1,105 +0,0 @@
1
- import type { ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { isKeyRelease, Key, matchesKey } from "@earendil-works/pi-tui";
3
- import { piDaemonClient } from "../daemon/pi-client.js";
4
- import { captureMutationOwner } from "../sync/sync-local.js";
5
- import { runCancellableTask } from "./cancellable-operation.js";
6
- import { trackOperationDialogs } from "./operation-dialogs.js";
7
- import { safeTerminalText } from "./terminal-text.js";
8
-
9
- type IgnoreOperation = "switch" | "migrate";
10
-
11
- async function ignoreCapabilities(ctx: ExtensionContext, signal?: AbortSignal) {
12
- if (signal?.aborted) return;
13
- try {
14
- const client = piDaemonClient(ctx);
15
- const result = await client.run("ignore.capabilities", {}, signal, ctx);
16
- client.validate();
17
- if (!signal?.aborted) return result as { available?: unknown; portableRules?: unknown } | undefined;
18
- } catch {
19
- return;
20
- }
21
- }
22
-
23
- export async function ignoreFileSettingsAvailable(ctx: ExtensionCommandContext, signal?: AbortSignal) {
24
- return (await ignoreCapabilities(ctx, signal))?.available === true;
25
- }
26
-
27
- export async function portableIgnoreRulesAvailable(ctx: ExtensionContext, signal?: AbortSignal) {
28
- return (await ignoreCapabilities(ctx, signal))?.portableRules === 1;
29
- }
30
-
31
- export async function showIgnoreFileAction(
32
- ctx: ExtensionCommandContext,
33
- setup: string,
34
- action: IgnoreOperation,
35
- filename: string,
36
- signal: AbortSignal,
37
- offerToken?: string,
38
- ) {
39
- if (signal.aborted || !ctx.hasUI || ctx.mode !== "tui") return;
40
- const validateOwner = captureMutationOwner(ctx, signal);
41
- const client = piDaemonClient(ctx);
42
- const isCurrent = () => {
43
- try {
44
- validateOwner();
45
- client.validate();
46
- return true;
47
- } catch {
48
- return false;
49
- }
50
- };
51
- try {
52
- let payload: Record<string, unknown> = offerToken ? { offerToken } : {};
53
- if (action === "switch") {
54
- const entered = await askIgnoreFilename(ctx, filename, signal);
55
- if (!isCurrent() || !entered || entered === filename) return;
56
- payload = { filename: entered, expectedFilename: filename };
57
- }
58
- if (!isCurrent()) return;
59
- const result = await runCancellableTask(
60
- ctx,
61
- action === "migrate"
62
- ? "Preparing ignore-file migration review…"
63
- : "Checking the selected ignore file for review…",
64
- (workSignal, onCommit, onDialog) =>
65
- client.run(
66
- `ignore.${action}`,
67
- { setup, ...payload },
68
- workSignal,
69
- trackOperationDialogs(ctx, onDialog),
70
- onCommit,
71
- ),
72
- { signal, isCurrent, cancelledMessage: null, commitAware: true, cancelAcrossDialogs: true },
73
- );
74
- if (isCurrent() && result.kind === "completed" && result.value === "saved") {
75
- ctx.ui.notify(
76
- action === "migrate"
77
- ? "Ignore-file policy saved locally. No transfer started."
78
- : "Ignore file selected. No transfer started.",
79
- "info",
80
- );
81
- }
82
- } catch (error) {
83
- if (isCurrent())
84
- ctx.ui.notify(`Pi Sync: ${safeTerminalText(error instanceof Error ? error.message : String(error))}`, "error");
85
- }
86
- }
87
-
88
- async function askIgnoreFilename(ctx: ExtensionCommandContext, filename: string, signal: AbortSignal) {
89
- const cancel = new AbortController();
90
- const stop = ctx.ui.onTerminalInput((data) => {
91
- if (!isKeyRelease(data) && matchesKey(data, Key.ctrl("c"))) {
92
- cancel.abort();
93
- return { consume: true };
94
- }
95
- });
96
- const inputSignal = AbortSignal.any([signal, cancel.signal]);
97
- try {
98
- const entered = await ctx.ui.input(`Existing ignore filename (current: ${safeTerminalText(filename)})`, undefined, {
99
- signal: inputSignal,
100
- });
101
- return inputSignal.aborted ? undefined : entered;
102
- } finally {
103
- stop();
104
- }
105
- }
@@ -1,65 +0,0 @@
1
- import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
- import { piDaemonClient } from "../daemon/pi-client.js";
3
- import { ignoreFileSettingsAvailable, showIgnoreFileAction } from "./ignore-file-ui.js";
4
- import { safeTerminalText } from "./terminal-text.js";
5
-
6
- const reviewNow = "Review migration now";
7
- const notNow = "Not now";
8
-
9
- export async function showIgnoreMigrationPrompt(
10
- ctx: ExtensionCommandContext,
11
- setup: string,
12
- signal: AbortSignal,
13
- isCurrent: () => boolean,
14
- ): Promise<boolean> {
15
- if (ctx.mode !== "tui" || !ctx.hasUI || signal.aborted || !isCurrent()) return false;
16
- if (!(await ignoreFileSettingsAvailable(ctx, signal)) || signal.aborted || !isCurrent()) return false;
17
-
18
- let shown = false;
19
- try {
20
- const client = piDaemonClient(ctx);
21
- const valid = () => {
22
- if (signal.aborted || !isCurrent()) return false;
23
- client.validate();
24
- return true;
25
- };
26
- const offer = await client.run("ignore.migration-offer", { setup }, signal, ctx);
27
- if (!valid()) return false;
28
- const token = readOfferToken(offer);
29
- if (!token) return false;
30
-
31
- shown = true;
32
- const choice = await ctx.ui.select(
33
- [
34
- `Review migration for sync setup “${safeTerminalText(setup)}”?`,
35
- "Your current rules still apply. Review the paths that would change before deciding.",
36
- "Migration does not start a transfer. You can review it later in Pi Sync Settings.",
37
- ].join("\n\n"),
38
- [reviewNow, notNow],
39
- { signal },
40
- );
41
- if (!valid()) return true;
42
- if (choice === notNow) {
43
- await client.run("ignore.migration-defer", { setup, token }, signal, ctx);
44
- } else if (choice === reviewNow) {
45
- await showIgnoreFileAction(ctx, setup, "migrate", ".syncignore", signal, token);
46
- }
47
- } catch (error) {
48
- if (!signal.aborted && isCurrent()) {
49
- ctx.ui.notify(
50
- `Pi Sync migration prompt: ${safeTerminalText(error instanceof Error ? error.message : String(error))}`,
51
- "warning",
52
- );
53
- }
54
- }
55
- return shown;
56
- }
57
-
58
- function readOfferToken(value: unknown) {
59
- if (value === null) return undefined;
60
- const token = (value as { token?: unknown } | undefined)?.token;
61
- if (typeof token !== "string" || !/^[0-9a-f]{64}$/u.test(token)) {
62
- throw new Error("Invalid migration offer from the daemon.");
63
- }
64
- return token;
65
- }
@@ -1,26 +0,0 @@
1
- import { readActiveLocalConfigDocumentForRepair } from "../settings/config-file.js";
2
- import { validateSettingsDocument } from "../settings/settings-validation.js";
3
- import { safeTerminalText } from "./terminal-text.js";
4
-
5
- export async function loadSettingsCatalog() {
6
- const document = await readActiveLocalConfigDocumentForRepair();
7
- if (!document) return undefined;
8
- const settings = validateSettingsDocument(document.parsed);
9
- const ignoreSetups = Object.entries(settings.syncSetups)
10
- .filter(([, setup]) => setup.sync.pathPolicy === "ignore-file")
11
- .map(([name]) => name);
12
- return { settings, path: document.path, ignoreSetups };
13
- }
14
-
15
- export const IGNORE_SETUP_MANAGEMENT_LIMIT =
16
- "Adding, editing, and switching setups are unavailable while any setup uses an ignore file.";
17
-
18
- export function ignoreSetupRecovery(settingsPath: string) {
19
- return [
20
- `For manual recovery, close Pi and back up: ${safeTerminalText(settingsPath)}`,
21
- "Remove the ignore-file entries from syncSetups.",
22
- "Set activeSyncSetup to a remaining setup, or remove it if none remain.",
23
- "Keep the settings version, ignore files, and remote data unchanged.",
24
- "Preserve any pending journal and backup. Review automatic sync before restarting Pi.",
25
- ];
26
- }