@narumitw/pi-sync-daemon 0.7.0 → 0.9.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 (93) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +16 -2
  3. package/dist/cli.js +1 -1
  4. package/dist/consent.d.ts +14 -2
  5. package/dist/consent.js +147 -14
  6. package/dist/engine/backends/git/git-backend.d.ts +2 -3
  7. package/dist/engine/backends/git/git-backend.js +71 -25
  8. package/dist/engine/backends/git/git-storage.d.ts +1 -1
  9. package/dist/engine/backends/git/git-storage.js +30 -9
  10. package/dist/engine/backends/s3/s3-backend.js +8 -0
  11. package/dist/engine/backends/sync-backend.d.ts +1 -0
  12. package/dist/engine/backends/webdav/webdav-backend.js +8 -0
  13. package/dist/engine/commands/command-types.d.ts +2 -1
  14. package/dist/engine/host.d.ts +1 -0
  15. package/dist/engine/ignore/effective-ignore-policy.d.ts +10 -0
  16. package/dist/engine/ignore/effective-ignore-policy.js +33 -0
  17. package/dist/engine/ignore/ignore-edit.d.ts +13 -0
  18. package/dist/engine/ignore/ignore-edit.js +102 -0
  19. package/dist/engine/ignore/ignore-initialization.d.ts +9 -0
  20. package/dist/engine/ignore/ignore-initialization.js +252 -0
  21. package/dist/engine/ignore/ignore-migration-prompt.d.ts +7 -0
  22. package/dist/engine/ignore/ignore-migration-prompt.js +139 -0
  23. package/dist/engine/ignore/ignore-settings.d.ts +30 -0
  24. package/dist/engine/ignore/ignore-settings.js +393 -0
  25. package/dist/engine/ignore/ignore-source.d.ts +27 -0
  26. package/dist/engine/ignore/ignore-source.js +250 -0
  27. package/dist/engine/settings/config-file.d.ts +9 -2
  28. package/dist/engine/settings/config-file.js +124 -28
  29. package/dist/engine/settings/config.d.ts +6 -2
  30. package/dist/engine/settings/config.js +140 -11
  31. package/dist/engine/settings/settings-management.d.ts +5 -3
  32. package/dist/engine/settings/settings-management.js +24 -10
  33. package/dist/engine/settings/settings-types.d.ts +25 -2
  34. package/dist/engine/settings/settings-validation.js +23 -5
  35. package/dist/engine/snapshot/session-paths.d.ts +1 -1
  36. package/dist/engine/snapshot/session-paths.js +41 -13
  37. package/dist/engine/snapshot/snapshot-apply.d.ts +3 -3
  38. package/dist/engine/snapshot/snapshot-apply.js +23 -4
  39. package/dist/engine/snapshot/snapshot-codec.d.ts +1 -1
  40. package/dist/engine/snapshot/snapshot-codec.js +14 -5
  41. package/dist/engine/snapshot/snapshot-exclude-safety.d.ts +4 -2
  42. package/dist/engine/snapshot/snapshot-exclude-safety.js +76 -19
  43. package/dist/engine/snapshot/snapshot-transaction-images.d.ts +3 -1
  44. package/dist/engine/snapshot/snapshot-transaction-images.js +33 -3
  45. package/dist/engine/snapshot/snapshot-transaction-policy.d.ts +30 -2
  46. package/dist/engine/snapshot/snapshot-transaction-policy.js +135 -11
  47. package/dist/engine/snapshot/snapshot-transaction-verification.d.ts +7 -0
  48. package/dist/engine/snapshot/snapshot-transaction-verification.js +78 -0
  49. package/dist/engine/snapshot/snapshot-transaction.d.ts +1 -12
  50. package/dist/engine/snapshot/snapshot-transaction.js +129 -109
  51. package/dist/engine/snapshot/snapshot-types.d.ts +27 -1
  52. package/dist/engine/snapshot/snapshot-types.js +9 -1
  53. package/dist/engine/snapshot/snapshot.d.ts +6 -4
  54. package/dist/engine/snapshot/snapshot.js +91 -34
  55. package/dist/engine/state/state-types.d.ts +1 -0
  56. package/dist/engine/sync/agent-plan.js +1 -0
  57. package/dist/engine/sync/agent-sync.js +8 -1
  58. package/dist/engine/sync/continuous-sync.d.ts +3 -1
  59. package/dist/engine/sync/continuous-sync.js +50 -18
  60. package/dist/engine/sync/continuous-watch.js +4 -1
  61. package/dist/engine/sync/initialization.js +3 -2
  62. package/dist/engine/sync/local-fields.d.ts +3 -1
  63. package/dist/engine/sync/local-fields.js +62 -1
  64. package/dist/engine/sync/merge-acceptance.d.ts +8 -0
  65. package/dist/engine/sync/merge-acceptance.js +29 -0
  66. package/dist/engine/sync/merge-apply.js +42 -11
  67. package/dist/engine/sync/merge-journal.d.ts +24 -4
  68. package/dist/engine/sync/merge-journal.js +134 -8
  69. package/dist/engine/sync/merged-sync.d.ts +1 -1
  70. package/dist/engine/sync/merged-sync.js +128 -83
  71. package/dist/engine/sync/remote-snapshot.d.ts +11 -3
  72. package/dist/engine/sync/remote-snapshot.js +72 -18
  73. package/dist/engine/sync/session-push.js +20 -6
  74. package/dist/engine/sync/sync-inspection.js +7 -5
  75. package/dist/engine/sync/sync-mutations.d.ts +2 -1
  76. package/dist/engine/sync/sync-mutations.js +157 -73
  77. package/dist/engine/sync/sync-policy.d.ts +29 -8
  78. package/dist/engine/sync/sync-policy.js +152 -16
  79. package/dist/engine/sync/sync-queries.js +8 -1
  80. package/dist/engine/sync/sync-state.d.ts +4 -2
  81. package/dist/engine/sync/sync-state.js +15 -2
  82. package/dist/engine/sync/transfer-freshness.d.ts +31 -0
  83. package/dist/engine/sync/transfer-freshness.js +82 -0
  84. package/dist/engine-service.d.ts +1 -1
  85. package/dist/engine-service.js +146 -27
  86. package/dist/monitor.d.ts +4 -1
  87. package/dist/monitor.js +84 -32
  88. package/dist/server.d.ts +1 -0
  89. package/dist/server.js +46 -5
  90. package/dist/service-host.d.ts +1 -1
  91. package/dist/service-host.js +2 -1
  92. package/docs/architecture.md +30 -0
  93. package/package.json +2 -1
@@ -1,18 +1,29 @@
1
- import { authorizeAfterExit, consentFingerprint, readConsent, requireHandover } from "./consent.js";
1
+ import { authorizeAfterExit, automaticPolicyAuthorized, captureAutomaticAuthorization, consentFingerprint, readConsent, requireHandover, reviewAutomaticPolicy, revokeAfterExitGrants, } from "./consent.js";
2
2
  import { documentFingerprint } from "./document.js";
3
3
  import { createMonitor } from "./monitor.js";
4
4
  import { MAX_SETTINGS_BYTES, record } from "./protocol.js";
5
5
  import { createServiceContext, installServiceHost } from "./service-host.js";
6
- function optionsFrom(value, execution) {
6
+ function optionsFrom(value, execution, automatic) {
7
7
  if (!record(value))
8
8
  throw new Error("Invalid operation options.");
9
9
  const allowed = new Set(["yes", "force", "stale", "silent", "reload", "setup", "args", "agentRetryRefusal"]);
10
+ if (automatic)
11
+ allowed.add("automaticFingerprint");
10
12
  if (Object.keys(value).some((key) => !allowed.has(key)) ||
11
13
  ["yes", "force", "stale", "silent", "reload", "agentRetryRefusal"].some((key) => value[key] !== undefined && typeof value[key] !== "boolean") ||
12
14
  (value.setup !== undefined && (typeof value.setup !== "string" || value.setup.length > 512)) ||
13
15
  !Array.isArray(value.args) ||
14
16
  value.args.length > 16 ||
15
- value.args.some((arg) => typeof arg !== "string" || arg.length > 4096))
17
+ value.args.some((arg) => typeof arg !== "string" || arg.length > 4096) ||
18
+ (value.automaticFingerprint !== undefined &&
19
+ (typeof value.automaticFingerprint !== "string" || !/^[a-f0-9]{64}$/u.test(value.automaticFingerprint))) ||
20
+ (automatic &&
21
+ (value.setup !== undefined ||
22
+ value.force ||
23
+ value.stale ||
24
+ value.reload ||
25
+ value.agentRetryRefusal ||
26
+ value.args.length !== 0)))
16
27
  throw new Error("Invalid operation options.");
17
28
  return {
18
29
  yes: false,
@@ -23,32 +34,85 @@ function optionsFrom(value, execution) {
23
34
  auto: false,
24
35
  ...value,
25
36
  args: value.args,
37
+ ...(typeof value.automaticFingerprint === "string" ? { automaticFingerprint: value.automaticFingerprint } : {}),
26
38
  signal: execution.signal,
27
39
  onCommit: execution.committed,
28
40
  };
29
41
  }
30
42
  /** Engine dispatch is loaded only by the service, never by the public IPC client. */
31
- export function createEngineService(root) {
32
- const host = installServiceHost(root);
43
+ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
44
+ const host = installServiceHost(root, ignoreFileSettingsAvailable);
33
45
  const monitor = createMonitor(root, host);
34
46
  const execute = (operation, payload, execution) => host.run(execution, async () => {
47
+ if (operation === "ignore.capabilities") {
48
+ execution.validate();
49
+ return { available: ignoreFileSettingsAvailable };
50
+ }
51
+ if (operation === "ignore.migration-offer" || operation === "ignore.migration-defer") {
52
+ execution.validate();
53
+ const { readIgnoreMigrationOffer, deferIgnoreMigrationOffer } = await import("./engine/ignore/ignore-migration-prompt.js");
54
+ return operation === "ignore.migration-offer"
55
+ ? readIgnoreMigrationOffer(payload, execution)
56
+ : deferIgnoreMigrationOffer(payload, execution);
57
+ }
58
+ if (operation === "ignore.save") {
59
+ execution.validate();
60
+ throw new Error("Daemon ignore-file saves are unavailable. Edit the existing rule file manually.");
61
+ }
62
+ const ignoreFileChange = operation === "ignore.migrate" || operation === "ignore.switch";
63
+ if (ignoreFileChange && !ignoreFileSettingsAvailable) {
64
+ execution.validate();
65
+ throw new Error("Unsupported engine operation.");
66
+ }
35
67
  await monitor.pause();
36
68
  execution.validate();
37
- if (operation === "daemon.authorize")
38
- return authorizeAfterExit(execution, payload);
69
+ if (ignoreFileChange) {
70
+ const { runIgnorePolicyChange } = await import("./engine/ignore/ignore-settings.js");
71
+ execution.validate();
72
+ return runIgnorePolicyChange(operation, payload, {
73
+ ...execution,
74
+ committed() {
75
+ execution.committed();
76
+ monitor.settingsCommitted(true);
77
+ },
78
+ });
79
+ }
80
+ if (operation === "daemon.authorize") {
81
+ const authorized = await authorizeAfterExit(execution, payload);
82
+ if (authorized?.afterExit)
83
+ monitor.reviewedPolicy(authorized.config);
84
+ return Boolean(authorized);
85
+ }
86
+ if (operation === "daemon.authorize-connected") {
87
+ const facts = execution.facts();
88
+ if (!record(payload) ||
89
+ typeof payload.fingerprint !== "string" ||
90
+ !facts?.hasUI ||
91
+ !["tui", "rpc"].includes(facts.mode))
92
+ throw new Error("Automatic policy authorization requires an interactive review.");
93
+ const { loadConfigForCheck } = await import("./engine/settings/config.js");
94
+ const config = await loadConfigForCheck(undefined, execution.signal);
95
+ execution.validate();
96
+ const approved = await reviewAutomaticPolicy(execution, config, payload.fingerprint);
97
+ if (approved)
98
+ monitor.reviewedPolicy(config);
99
+ return approved;
100
+ }
39
101
  if (operation === "daemon.handover") {
40
102
  await requireHandover(execution);
41
103
  return true;
42
104
  }
43
105
  if (operation === "daemon.policy") {
44
- const { loadConfig } = await import("./engine/settings/config.js");
45
- const config = await loadConfig();
106
+ const { loadConfigForCheck } = await import("./engine/settings/config.js");
107
+ const config = await loadConfigForCheck(undefined, execution.signal);
108
+ execution.validate();
46
109
  const fingerprint = consentFingerprint(root, config);
47
110
  const saved = readConsent(root)?.setups[config.setupName];
48
111
  const facts = execution.facts();
49
112
  return {
50
113
  setup: config.setupName,
51
114
  fingerprint,
115
+ automatic: automaticPolicyAuthorized(root, config),
52
116
  afterExit: Boolean(saved?.afterExit &&
53
117
  saved.fingerprint === fingerprint &&
54
118
  JSON.stringify(saved.model) === JSON.stringify(facts?.model) &&
@@ -58,6 +122,11 @@ export function createEngineService(root) {
58
122
  }
59
123
  if (operation === "monitor.pause")
60
124
  return;
125
+ if (operation === "ignore.read") {
126
+ const { readIgnoreFileEdit } = await import("./engine/ignore/ignore-edit.js");
127
+ execution.validate();
128
+ return readIgnoreFileEdit(payload, execution);
129
+ }
61
130
  if (operation === "settings.read" || operation === "settings.repair-read") {
62
131
  const { readLocalConfigDocument } = await import("./engine/settings/settings-store.js");
63
132
  const { readActiveLocalConfigDocumentForRepair } = await import("./engine/settings/config-file.js");
@@ -78,11 +147,14 @@ export function createEngineService(root) {
78
147
  (typeof payload.expected !== "string" || !/^[a-f0-9]{64}$/u.test(payload.expected))) ||
79
148
  !record(payload.next))
80
149
  throw new Error("Invalid settings mutation.");
81
- const { updateLocalConfigDocument, peekLocalConfigDocument } = await import("./engine/settings/config-file.js");
150
+ const { localConfigPath, updateLocalConfigDocument, peekLocalConfigDocument } = await import("./engine/settings/config-file.js");
82
151
  const { localConfigTemplate } = await import("./engine/settings/settings-store.js");
83
152
  const { validateSettingsDocument } = await import("./engine/settings/settings-validation.js");
84
- const next = payload.next;
85
- validateSettingsDocument(next);
153
+ const next = validateSettingsDocument(payload.next);
154
+ const nextMixed = Object.values(next.syncSetups).some((setup) => setup.sync.pathPolicy === "ignore-file");
155
+ if (!ignoreFileSettingsAvailable && nextMixed) {
156
+ throw new Error("Ignore-file setup activation is not available in this Daemon build.");
157
+ }
86
158
  if (Buffer.byteLength(JSON.stringify(next)) > MAX_SETTINGS_BYTES)
87
159
  throw new Error("Settings exceed the editable local API byte limit; no fields were dropped.");
88
160
  const validateSource = (document) => {
@@ -91,14 +163,44 @@ export function createEngineService(root) {
91
163
  if (documentFingerprint(view) !== payload.expected)
92
164
  throw new Error("Settings changed; reopen the review before saving.");
93
165
  };
94
- validateSource(await peekLocalConfigDocument());
166
+ const original = await peekLocalConfigDocument();
167
+ validateSource(original);
168
+ const before = original && validateSettingsDocument(original.parsed);
169
+ const wasMixed = before && Object.values(before.syncSetups).some((setup) => setup.sync.pathPolicy === "ignore-file");
170
+ let prepareSource;
171
+ if (ignoreFileSettingsAvailable && (nextMixed || wasMixed)) {
172
+ if (original && original.path !== localConfigPath())
173
+ throw new Error("This settings change requires pi-sync.json. No settings were saved; use the canonical filename and reopen the review.");
174
+ const { newIgnoreFilename, reviewNewIgnoreSource, prepareReviewedIgnoreSource } = await import("./engine/ignore/ignore-settings.js");
175
+ execution.validate();
176
+ const filename = newIgnoreFilename(before, next);
177
+ if (filename) {
178
+ const reviewed = await reviewNewIgnoreSource(root, filename, execution);
179
+ validateSource(await peekLocalConfigDocument());
180
+ prepareSource = async () => {
181
+ await prepareReviewedIgnoreSource(root, reviewed, execution);
182
+ execution.validate();
183
+ };
184
+ }
185
+ else if (wasMixed && !nextMixed) {
186
+ prepareSource = async () => {
187
+ execution.validate();
188
+ revokeAfterExitGrants(root);
189
+ };
190
+ }
191
+ }
95
192
  await requireHandover(execution);
96
193
  execution.validate();
97
- return updateLocalConfigDocument(localConfigTemplate(), () => {
194
+ const saved = await updateLocalConfigDocument(localConfigTemplate(), () => {
98
195
  execution.validate();
99
196
  validateSettingsDocument(next);
100
197
  return next;
101
- }, validateSettingsDocument, execution.signal, validateSource);
198
+ }, validateSettingsDocument, execution.signal, validateSource, prepareSource);
199
+ if (!original || JSON.stringify(original.parsed) !== JSON.stringify(saved)) {
200
+ monitor.settingsCommitted(Boolean(wasMixed || nextMixed));
201
+ execution.committed();
202
+ }
203
+ return saved;
102
204
  }
103
205
  const ctx = createServiceContext(execution);
104
206
  if (operation === "initialize")
@@ -109,8 +211,8 @@ export function createEngineService(root) {
109
211
  const { withStateDirectoryAccess } = await import("./engine/state/state-directory.js");
110
212
  const { withLock } = await import("./engine/state/lock.js");
111
213
  return withJobTimings(ctx, execution, "daemon inspection", (timings) => withStateDirectoryAccess(() => withLock("startup-check", async () => {
112
- const { loadConfig, syncCheckConfigFingerprint } = await import("./engine/settings/config.js");
113
- const config = await loadConfig(payload.setup);
214
+ const { loadConfigForCheck, syncCheckConfigFingerprint } = await import("./engine/settings/config.js");
215
+ const config = await loadConfigForCheck(payload.setup, execution.signal);
114
216
  execution.validate();
115
217
  if (payload.fingerprint !== syncCheckConfigFingerprint(config))
116
218
  throw new Error("Settings changed before inspection.");
@@ -137,13 +239,14 @@ export function createEngineService(root) {
137
239
  ];
138
240
  if (!supported.includes(operation))
139
241
  throw new Error("Unsupported engine operation.");
140
- const options = optionsFrom(payload, execution);
242
+ const isAutomatic = operation === "startup-transfer" || operation === "shutdown";
243
+ const options = optionsFrom(payload, execution, isAutomatic);
141
244
  if (!options.reload)
142
245
  ctx.reload = undefined;
143
246
  if (operation === "shutdown") {
144
247
  const { loadConfigForCheck } = await import("./engine/settings/config.js");
145
248
  const { syncSessionsSelected } = await import("./engine/sync/sync-policy.js");
146
- const config = await loadConfigForCheck();
249
+ const config = await loadConfigForCheck(undefined, execution.signal);
147
250
  execution.validate();
148
251
  if (!config.automatic || !syncSessionsSelected(config))
149
252
  return;
@@ -166,11 +269,16 @@ export function createEngineService(root) {
166
269
  return result;
167
270
  }
168
271
  return withStateDirectoryAccess(async () => {
169
- if (["startup-transfer", "shutdown"].includes(operation) && !readConsent(root))
170
- throw new Error("Automatic work requires reviewed daemon handover first.");
272
+ const automatic = isAutomatic
273
+ ? await captureAutomaticAuthorization(execution, options.automaticFingerprint)
274
+ : undefined;
275
+ if (automatic)
276
+ options.background = { validate: automatic.validate };
171
277
  if (["push", "pull", "sync", "startup-transfer", "shutdown", "conflicts", "rollback"].includes(operation)) {
172
278
  await requireHandover(execution);
279
+ await automatic?.refresh();
173
280
  await initialize(ctx, execution, false);
281
+ await automatic?.refresh();
174
282
  }
175
283
  const { withLock, unlock } = await import("./engine/state/lock.js");
176
284
  if (operation === "unlock")
@@ -185,9 +293,8 @@ export function createEngineService(root) {
185
293
  return pushSessionsOnShutdown(ctx, options, { operations: async () => operations });
186
294
  }
187
295
  if (operation === "startup-transfer") {
188
- const { loadConfig } = await import("./engine/settings/config.js");
189
296
  const { startupTransferEnabled } = await import("./engine/sync/agent-policy.js");
190
- if (!startupTransferEnabled(await loadConfig(options.setup)) || !ctx.isIdle())
297
+ if (!automatic || !startupTransferEnabled(automatic.config) || !ctx.isIdle())
191
298
  throw new Error("Startup transfer is no longer authorized or idle.");
192
299
  options.auto = true;
193
300
  options.yes = true;
@@ -198,25 +305,33 @@ export function createEngineService(root) {
198
305
  const run = async () => {
199
306
  const { prepareResolverHost } = await import("./resolver-host.js");
200
307
  const { loadConfig } = await import("./engine/settings/config.js");
201
- const config = await loadConfig(options.setup);
308
+ const config = await loadConfig(options.setup, execution.signal);
309
+ await automatic?.refresh();
310
+ automatic?.validate(config);
202
311
  execution.validate();
312
+ if (config.agentMode && !automaticPolicyAuthorized(root, config)) {
313
+ throw new Error("Autonomous sync requires a separate policy review. Use Settings → Review automatic transfers, or choose a reviewed push or pull.");
314
+ }
203
315
  if (operation === "sync" && !options.agentRetryRefusal)
204
- monitor.explicitSync(config.setupName, execution);
316
+ monitor.explicitSync(config, execution);
205
317
  const binding = JSON.stringify(execution.facts()?.model);
206
318
  const resolver = await prepareResolverHost(root, config.agentMode ? execution.facts()?.model : undefined, execution.signal);
207
319
  try {
320
+ await automatic?.refresh();
208
321
  ctx.modelUnavailableReason = resolver.unavailable;
209
322
  Object.defineProperty(ctx, "model", {
210
323
  get: () => (JSON.stringify(execution.facts()?.model) === binding ? resolver.model : undefined),
211
324
  });
212
325
  ctx.validateModel = async () => {
213
326
  const fresh = await execution.request("model-binding", {});
327
+ await automatic?.refresh();
214
328
  execution.validate();
215
329
  if (JSON.stringify(fresh ?? undefined) !== binding)
216
330
  throw new Error("Selected provider/model capability changed before dispatch.");
217
331
  };
218
332
  ctx.modelRegistry = {
219
333
  streamSimple: (model, context, options) => {
334
+ automatic?.validate();
220
335
  execution.validate();
221
336
  if (JSON.stringify(execution.facts()?.model) !== binding)
222
337
  throw new Error("Selected model changed before dispatch.");
@@ -228,13 +343,17 @@ export function createEngineService(root) {
228
343
  const { withAgentSyncLock } = await import("./engine/sync/agent-sync.js");
229
344
  return await withAgentSyncLock(ctx, options, async (current) => {
230
345
  if (operation === "startup-transfer") {
231
- const { loadConfig } = await import("./engine/settings/config.js");
232
346
  const { startupTransferEnabled } = await import("./engine/sync/agent-policy.js");
233
- const config = await loadConfig(current.setup);
347
+ if (!automatic)
348
+ throw new Error("Missing startup transfer authorization.");
349
+ await automatic.refresh();
350
+ const config = automatic.config;
234
351
  execution.validate();
235
352
  const { inspectSync } = await import("./engine/sync/sync-inspection.js");
236
353
  const { snapshotOptionsForContext } = await import("./engine/snapshot/session-paths.js");
354
+ await automatic.refresh();
237
355
  const inspection = await inspectSync(config, snapshotOptionsForContext(ctx, config), current.signal);
356
+ await automatic.refresh();
238
357
  execution.validate();
239
358
  if (!startupTransferEnabled(config) ||
240
359
  !ctx.isIdle() ||
package/dist/monitor.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { AnySyncConfig } from "./engine/settings/settings-types.js";
1
2
  import type { IdleExitPolicy } from "./idle-exit.js";
2
3
  import type { Execution } from "./protocol.js";
3
4
  import type { startServer } from "./server.js";
@@ -7,7 +8,9 @@ export declare function createMonitor(root: string, host: ReturnType<typeof inst
7
8
  schedule: () => void;
8
9
  lifetime: () => Promise<IdleExitPolicy>;
9
10
  blockAutomatic: () => void;
10
- explicitSync(setup: string, execution: Execution): void;
11
+ explicitSync(config: AnySyncConfig, execution: Execution): void;
12
+ reviewedPolicy(config: AnySyncConfig): void;
13
+ settingsCommitted(blockNewPolicy: boolean): void;
11
14
  pause(): Promise<void>;
12
15
  factsChanged(): Promise<void>;
13
16
  close(): Promise<void>;
package/dist/monitor.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import path from "node:path";
3
- import { ConsentPublicationError, consentFingerprint, readConsent, revokeChangedBindings } from "./consent.js";
4
- import { loadConfigForCheck } from "./engine/settings/config.js";
3
+ import { automaticPolicyAuthorized, ConsentPublicationError, consentFingerprint, participantBinding, readConsent, revokeChangedBindings, } from "./consent.js";
4
+ import { loadConfigForCheck, syncCheckConfigFingerprint } from "./engine/settings/config.js";
5
5
  import { createEngineLoaders } from "./engine/sync/sync-loaders.js";
6
6
  import { createServiceContext } from "./service-host.js";
7
7
  export function createMonitor(root, host) {
@@ -11,12 +11,19 @@ export function createMonitor(root, host) {
11
11
  let closed = false;
12
12
  let authorizationFailed = false;
13
13
  let scheduled = false;
14
- // Keep each client's last validated route, not its Pi context or completed execution.
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;
15
22
  const retries = new Map();
23
+ const retryOwner = (peer) => JSON.stringify([peer.generation, peer.cwd, peer.sessionId, peer.sessionFile, peer.sessionDir, peer.model]);
16
24
  let epoch;
17
25
  const timingOwners = new WeakMap();
18
26
  const loaders = createEngineLoaders();
19
- const operations = loaders.operations;
20
27
  let continuous;
21
28
  function schedule() {
22
29
  if (closed || scheduled || !server)
@@ -42,7 +49,7 @@ export function createMonitor(root, host) {
42
49
  await current.promise;
43
50
  }
44
51
  function unattendedGrant(config) {
45
- if (!config.continuous || !config.agentMode)
52
+ if (!config.continuous || !config.agentMode || !automaticPolicyAuthorized(root, config))
46
53
  return undefined;
47
54
  const saved = readConsent(root)?.setups[config.setupName];
48
55
  return saved?.afterExit && saved.fingerprint === consentFingerprint(root, config) ? saved : undefined;
@@ -57,7 +64,7 @@ export function createMonitor(root, host) {
57
64
  const config = await loadConfigForCheck();
58
65
  if (closed || authorizationFailed)
59
66
  return "pause";
60
- return unattendedGrant(config) ? "keep" : "exit";
67
+ return !policyNeedsReview() && unattendedGrant(config) ? "keep" : "exit";
61
68
  }
62
69
  catch {
63
70
  // Invalid evidence is not an implicit revocation or permission to discard a safety barrier.
@@ -68,14 +75,25 @@ export function createMonitor(root, host) {
68
75
  const service = server;
69
76
  if (!service)
70
77
  return;
71
- const available = () => !closed && !authorizationFailed && !task && server === service && service.isIdle();
72
- if (!available())
78
+ if (closed || authorizationFailed || policyNeedsReview() || task || !service.isIdle())
73
79
  return;
74
- const consent = readConsent(root);
75
- if (!consent)
80
+ const generation = settingsGeneration;
81
+ const participants = service.participantGeneration?.();
82
+ const participantsToken = participantBinding(service);
83
+ const consentToken = JSON.stringify(readConsent(root));
84
+ const sameAuthorization = () => !closed &&
85
+ !authorizationFailed &&
86
+ !policyNeedsReview() &&
87
+ server === service &&
88
+ generation === settingsGeneration &&
89
+ participants === service.participantGeneration?.() &&
90
+ participantsToken === participantBinding(service) &&
91
+ consentToken === JSON.stringify(readConsent(root));
92
+ const available = () => !task && service.isIdle() && sameAuthorization();
93
+ if (!consentToken || !available())
76
94
  return;
77
95
  const config = await loadConfigForCheck();
78
- if (!available())
96
+ if (!available() || !automaticPolicyAuthorized(root, config))
79
97
  return;
80
98
  if (!config.continuous || !config.agentMode) {
81
99
  retries.clear();
@@ -87,6 +105,9 @@ export function createMonitor(root, host) {
87
105
  const peers = service.participants();
88
106
  if (peers.some((peer) => !peer.idle || peer.ready !== true))
89
107
  return;
108
+ const fingerprint = syncCheckConfigFingerprint(config);
109
+ if (config.reservedIgnoreNames !== undefined && monitoredPolicy !== undefined && monitoredPolicy !== fingerprint)
110
+ return;
90
111
  const authorized = unattendedGrant(config);
91
112
  const selected = peers.toSorted((a, b) => a.id.localeCompare(b.id))[0];
92
113
  if (!selected && !authorized)
@@ -135,7 +156,9 @@ export function createMonitor(root, host) {
135
156
  };
136
157
  const execution = { ...original, facts: () => stableFacts };
137
158
  const allowed = (currentConfig = config) => {
138
- if (closed || authorizationFailed || server !== service || controller.signal.aborted || !readConsent(root))
159
+ if (controller.signal.aborted ||
160
+ !sameAuthorization() ||
161
+ syncCheckConfigFingerprint(currentConfig) !== fingerprint)
139
162
  return false;
140
163
  const current = service.participants();
141
164
  if (current.length)
@@ -159,12 +182,11 @@ export function createMonitor(root, host) {
159
182
  timingOwners.set(ctx, execution);
160
183
  ctx.backgroundAuthorized = allowed;
161
184
  ctx.isIdle = () => Boolean(service.isIdle() && allowed());
162
- loaders.operations = async () => {
163
- const loaded = await operations();
164
- return {
165
- ...loaded,
166
- syncBoth: (context, options, ...rest) => loaded.syncBoth(context, { ...options, onCommit: execution.committed }, ...rest),
167
- };
185
+ const refresh = async () => {
186
+ execution.validate();
187
+ if (!allowed(await loadConfigForCheck(undefined, controller.signal)))
188
+ throw new Error("Daemon automatic authorization changed.");
189
+ execution.validate();
168
190
  };
169
191
  const sessionSignal = epoch.controller.signal;
170
192
  const debug = epoch.debug;
@@ -177,30 +199,47 @@ export function createMonitor(root, host) {
177
199
  void host
178
200
  .run(execution, async () => {
179
201
  const { prepareResolverHost } = await import("./resolver-host.js");
202
+ await refresh();
180
203
  const resolver = await prepareResolverHost(root, binding, controller.signal);
181
204
  try {
182
- if (!allowed())
183
- return;
205
+ await refresh();
206
+ if (config.reservedIgnoreNames !== undefined)
207
+ monitoredPolicy = fingerprint;
184
208
  ctx.model = resolver.model;
185
209
  ctx.modelUnavailableReason = resolver.unavailable;
186
- ctx.modelRegistry = resolver.registry;
210
+ ctx.modelRegistry = {
211
+ streamSimple: (model, context, options) => {
212
+ execution.validate();
213
+ if (!allowed())
214
+ throw new Error("Daemon authorization changed before model dispatch.");
215
+ return resolver.registry.streamSimple(model, context, options);
216
+ },
217
+ };
187
218
  ctx.validateModel = async () => {
188
- if (!allowed())
189
- throw new Error("Daemon authorization changed before model dispatch.");
190
- for (const peer of service.participants()) {
219
+ await refresh();
220
+ for (const peer of peers) {
191
221
  const fresh = await execution.request("model-binding", { background: true }, peer.id);
192
222
  if (JSON.stringify(fresh ?? undefined) !== JSON.stringify(binding))
193
223
  throw new Error("Participating model changed before dispatch.");
194
- if (!allowed())
195
- throw new Error("Daemon authorization changed during model validation.");
224
+ await refresh();
196
225
  }
197
226
  };
198
227
  const explicitRetry = service.participants().some((peer) => {
199
228
  const retry = retries.get(peer.id);
200
- return retry?.setup === config.setupName && retry.generation === peer.generation && !retry.signal.aborted;
229
+ return retry?.fingerprint === fingerprint && retry.owner === retryOwner(peer) && !retry.signal.aborted;
201
230
  });
202
231
  retries.clear();
203
- activeContinuous.start(ctx, sessionSignal, explicitRetry ? config.setupName : false, debug);
232
+ activeContinuous.start(ctx, sessionSignal, explicitRetry ? config.setupName : false, debug, async (run) => {
233
+ await refresh();
234
+ const attempt = new AbortController();
235
+ const owner = service.backgroundExecution(AbortSignal.any([attempt.signal, controller.signal]));
236
+ try {
237
+ return await host.run({ ...owner, facts: execution.facts }, () => run(owner.committed));
238
+ }
239
+ finally {
240
+ attempt.abort();
241
+ }
242
+ });
204
243
  await new Promise((resolve) => {
205
244
  if (controller.signal.aborted)
206
245
  resolve();
@@ -229,10 +268,23 @@ export function createMonitor(root, host) {
229
268
  schedule,
230
269
  lifetime,
231
270
  blockAutomatic,
232
- explicitSync(setup, execution) {
271
+ explicitSync(config, execution) {
233
272
  const peer = execution.facts();
234
- if (!closed && peer)
235
- retries.set(peer.id, { setup, generation: peer.generation, signal: execution.signal });
273
+ if (closed || !peer)
274
+ return;
275
+ const fingerprint = syncCheckConfigFingerprint(config);
276
+ retries.set(peer.id, { fingerprint, owner: retryOwner(peer), signal: execution.signal });
277
+ },
278
+ reviewedPolicy(config) {
279
+ blockedParticipants = undefined;
280
+ monitoredPolicy = config.reservedIgnoreNames === undefined ? undefined : syncCheckConfigFingerprint(config);
281
+ },
282
+ settingsCommitted(blockNewPolicy) {
283
+ settingsGeneration++;
284
+ retries.clear();
285
+ if (blockNewPolicy)
286
+ blockedParticipants = participatingSessions();
287
+ task?.controller.abort(new DOMException("Sync settings committed", "AbortError"));
236
288
  },
237
289
  async pause() {
238
290
  transition = transition.then(stop);
@@ -244,7 +296,7 @@ export function createMonitor(root, host) {
244
296
  if (server) {
245
297
  const peers = server.participants();
246
298
  for (const [id, retry] of retries)
247
- if (retry.signal.aborted || !peers.some((peer) => peer.id === id && peer.generation === retry.generation))
299
+ if (retry.signal.aborted || !peers.some((peer) => peer.id === id && retryOwner(peer) === retry.owner))
248
300
  retries.delete(id);
249
301
  revokeChangedBindings(root, peers);
250
302
  }
package/dist/server.d.ts CHANGED
@@ -16,6 +16,7 @@ export declare function startServer(root: string, execute: Execute, hooks?: Serv
16
16
  backgroundExecution: (signal: AbortSignal) => Execution;
17
17
  readonly retainedEndpoint: string | undefined;
18
18
  participants: () => ClientFacts[];
19
+ participantGeneration: () => number;
19
20
  liveClients: () => ClientFacts[];
20
21
  expireClients: () => Promise<void>;
21
22
  checkLifetime: () => Promise<void>;