@narumitw/pi-sync-daemon 0.8.0 → 0.9.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 (61) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/cli.js +1 -1
  3. package/dist/consent.d.ts +14 -2
  4. package/dist/consent.js +134 -16
  5. package/dist/engine/backends/git/git-backend.d.ts +1 -2
  6. package/dist/engine/backends/git/git-backend.js +61 -30
  7. package/dist/engine/commands/command-types.d.ts +2 -1
  8. package/dist/engine/host.d.ts +1 -0
  9. package/dist/engine/ignore/ignore-initialization.d.ts +8 -1
  10. package/dist/engine/ignore/ignore-initialization.js +142 -40
  11. package/dist/engine/ignore/ignore-settings.d.ts +16 -1
  12. package/dist/engine/ignore/ignore-settings.js +94 -26
  13. package/dist/engine/ignore/ignore-source.d.ts +1 -1
  14. package/dist/engine/ignore/ignore-source.js +1 -1
  15. package/dist/engine/settings/config-file.js +1 -1
  16. package/dist/engine/settings/config.d.ts +3 -2
  17. package/dist/engine/settings/config.js +71 -28
  18. package/dist/engine/settings/settings-management.d.ts +3 -1
  19. package/dist/engine/settings/settings-management.js +8 -2
  20. package/dist/engine/settings/settings-types.d.ts +2 -0
  21. package/dist/engine/snapshot/session-paths.js +7 -2
  22. package/dist/engine/snapshot/snapshot-apply.d.ts +1 -1
  23. package/dist/engine/snapshot/snapshot-transaction-policy.d.ts +7 -2
  24. package/dist/engine/snapshot/snapshot-transaction-policy.js +37 -17
  25. package/dist/engine/snapshot/snapshot-transaction.js +55 -13
  26. package/dist/engine/snapshot/snapshot-types.d.ts +4 -0
  27. package/dist/engine/sync/agent-plan.js +1 -0
  28. package/dist/engine/sync/agent-sync.js +8 -1
  29. package/dist/engine/sync/continuous-sync.d.ts +3 -1
  30. package/dist/engine/sync/continuous-sync.js +32 -15
  31. package/dist/engine/sync/merge-acceptance.d.ts +8 -0
  32. package/dist/engine/sync/merge-acceptance.js +29 -0
  33. package/dist/engine/sync/merge-apply.js +7 -4
  34. package/dist/engine/sync/merge-journal.d.ts +6 -0
  35. package/dist/engine/sync/merge-journal.js +33 -14
  36. package/dist/engine/sync/merged-sync.js +31 -39
  37. package/dist/engine/sync/remote-snapshot.d.ts +2 -1
  38. package/dist/engine/sync/remote-snapshot.js +17 -2
  39. package/dist/engine/sync/session-push.js +20 -6
  40. package/dist/engine/sync/sync-error-guidance.js +16 -3
  41. package/dist/engine/sync/sync-mutations.js +75 -54
  42. package/dist/engine/sync/sync-policy.d.ts +5 -0
  43. package/dist/engine/sync/sync-policy.js +28 -3
  44. package/dist/engine/sync/sync-state.d.ts +2 -0
  45. package/dist/engine/sync/sync-state.js +3 -8
  46. package/dist/engine/sync/transfer-freshness.d.ts +31 -0
  47. package/dist/engine/sync/transfer-freshness.js +82 -0
  48. package/dist/engine/ui/sync-format.d.ts +16 -5
  49. package/dist/engine/ui/sync-format.js +23 -55
  50. package/dist/engine/ui/transfer-review.d.ts +2 -1
  51. package/dist/engine/ui/transfer-review.js +3 -3
  52. package/dist/engine-service.d.ts +1 -1
  53. package/dist/engine-service.js +124 -27
  54. package/dist/monitor.d.ts +4 -1
  55. package/dist/monitor.js +84 -32
  56. package/dist/server.d.ts +1 -0
  57. package/dist/server.js +46 -5
  58. package/dist/service-host.d.ts +1 -1
  59. package/dist/service-host.js +2 -1
  60. package/docs/architecture.md +14 -6
  61. package/package.json +1 -1
@@ -37,29 +37,22 @@ export function formatSnapshotOnlyDiff(title, snapshot) {
37
37
  ...snapshot.files.map((file) => `Add: ${snapshotPathLabel(file.path)}`),
38
38
  ].join("\n");
39
39
  }
40
+ export function formatTransferReview(...sections) {
41
+ return {
42
+ lines: sections.flatMap((section) => (typeof section === "string" ? section.split("\n") : section.lines)),
43
+ content: sections.map((section) => (typeof section === "string" ? section : section.content)).join("\n"),
44
+ };
45
+ }
40
46
  export function formatPushSummary(config, destination, upload, head, preservedRemoteFileCount = 0, remote) {
41
- return [
42
- `Sync setup: ${safeTerminalText(config.setupName)}`,
43
- `Storage location: ${safeTerminalText(destination)}`,
44
- `Direction: Local → Remote. Source: ${safeTerminalText(agentDir())}.`,
45
- `Publish a snapshot containing ${upload.files.length} files; unchanged and preserved files are not counted as changes.`,
46
- `Sessions: ${upload.syncSessions ? "included — may contain private conversations" : "not included"}`,
47
- ...excludedPolicyLines(config),
48
- head ? `Remote latest: ${safeTerminalText(head.snapshotId)}` : "Remote latest: empty",
49
- "Publication effect: the backend's active head will reference the new immutable snapshot. Removed paths leave the active snapshot; retained history is not erased.",
50
- ...(remote && inspectRemoteSelection(config.include, remote, config.exclude, config).kind === "different"
51
- ? ["Included-content policy effect: replace the differing remote selection with this setup's local selection."]
52
- : []),
53
- formatPublicationPreview(remote, upload),
54
- config.skipSecretScan
55
- ? "Warning: possible-secret scanning is disabled for this push."
56
- : preservedRemoteFileCount > 0
57
- ? `Possible secrets in locally managed files were scanned before this prompt; ${preservedRemoteFileCount} preserved remote file(s) were not rescanned.`
58
- : "Possible secrets were scanned before this prompt.",
59
- ...(config.scope === "agent-directory"
60
- ? ["Warning: synced files may contain secrets or other sensitive data that the scanner cannot identify."]
61
- : []),
62
- ].join("\n");
47
+ return formatTransferReview(`Sync setup: ${safeTerminalText(config.setupName)}`, `Storage location: ${safeTerminalText(destination)}`, `Direction: Local → Remote. Source: ${safeTerminalText(agentDir())}.`, `Publish a snapshot containing ${upload.files.length} files; unchanged and preserved files are not counted as changes.`, `Sessions: ${upload.syncSessions ? "included — may contain private conversations" : "not included"}`, ...excludedPolicyLines(config), head ? `Remote latest: ${safeTerminalText(head.snapshotId)}` : "Remote latest: empty", "Publication effect: the backend's active head will reference the new immutable snapshot. Removed paths leave the active snapshot; retained history is not erased.", ...(remote && inspectRemoteSelection(config.include, remote, config.exclude, config).kind === "different"
48
+ ? ["Included-content policy effect: replace the differing remote selection with this setup's local selection."]
49
+ : []), formatPublicationPreview(remote, upload), config.skipSecretScan
50
+ ? "Warning: possible-secret scanning is disabled for this push."
51
+ : preservedRemoteFileCount > 0
52
+ ? `Possible secrets in locally managed files were scanned before this prompt; ${preservedRemoteFileCount} preserved remote file(s) were not rescanned.`
53
+ : "Possible secrets were scanned before this prompt.", ...(config.scope === "agent-directory"
54
+ ? ["Warning: synced files may contain secrets or other sensitive data that the scanner cannot identify."]
55
+ : []));
63
56
  }
64
57
  function excludedPolicyLines(config) {
65
58
  const scoped = config.scope === "agent-directory";
@@ -89,36 +82,10 @@ export function formatApplyPreview(local, remote, protectedPaths = new Set(), ad
89
82
  }, protectedPaths, additionalRemovals);
90
83
  }
91
84
  export function formatPullSummary(config, destination, local, remote, protectedPaths, additionalRemovals = []) {
92
- return [
93
- `Sync setup: ${safeTerminalText(config.setupName)}`,
94
- `Storage location: ${safeTerminalText(destination)}`,
95
- "Direction: Remote → Local.",
96
- `Snapshot: ${safeTerminalText(remote.id)}`,
97
- ...excludedPolicyLines(config),
98
- `Sessions: ${remote.syncSessions ? "included — may contain private conversations" : "not included"}`,
99
- `Protected live sessions: ${protectedPaths.size || "none"}`,
100
- formatApplyPreview(local, remote, protectedPaths, additionalRemovals),
101
- ...(additionalRemovals.length
102
- ? ["Case-variant aliases listed above are removed before writing canonical paths."]
103
- : []),
104
- "A local backup is created before these writes/deletes. The remote active snapshot is unchanged.",
105
- ].join("\n");
85
+ return formatTransferReview(`Sync setup: ${safeTerminalText(config.setupName)}`, `Storage location: ${safeTerminalText(destination)}`, "Direction: Remote → Local.", `Snapshot: ${safeTerminalText(remote.id)}`, ...excludedPolicyLines(config), `Sessions: ${remote.syncSessions ? "included — may contain private conversations" : "not included"}`, `Protected live sessions: ${protectedPaths.size || "none"}`, formatApplyPreview(local, remote, protectedPaths, additionalRemovals), ...(additionalRemovals.length ? ["Case-variant aliases are removed before writing canonical paths."] : []), "A local backup is created before these writes/deletes. The remote active snapshot is unchanged.");
106
86
  }
107
87
  export function formatRollbackSummary(config, destination, local, remote, requestedSnapshot, protectedPaths, additionalRemovals = []) {
108
- return [
109
- `Sync setup: ${safeTerminalText(config.setupName)}`,
110
- `Storage location: ${safeTerminalText(destination)}`,
111
- "Direction: Historical snapshot → Local and remote active head.",
112
- `Snapshot: ${safeTerminalText(requestedSnapshot)}`,
113
- ...excludedPolicyLines(config),
114
- `Sessions: ${remote.syncSessions ? "included — may contain private conversations" : "not included"}`,
115
- `Protected live sessions: ${protectedPaths.size || "none"}`,
116
- formatApplyPreview(local, remote, protectedPaths, additionalRemovals),
117
- ...(additionalRemovals.length
118
- ? ["Case-variant aliases listed above are removed before writing canonical paths."]
119
- : []),
120
- "A local backup is created before applying; the backend's active head will change.",
121
- ].join("\n");
88
+ return formatTransferReview(`Sync setup: ${safeTerminalText(config.setupName)}`, `Storage location: ${safeTerminalText(destination)}`, "Direction: Historical snapshot → Local and remote active head.", `Snapshot: ${safeTerminalText(requestedSnapshot)}`, ...excludedPolicyLines(config), `Sessions: ${remote.syncSessions ? "included — may contain private conversations" : "not included"}`, `Protected live sessions: ${protectedPaths.size || "none"}`, formatApplyPreview(local, remote, protectedPaths, additionalRemovals), ...(additionalRemovals.length ? ["Case-variant aliases are removed before writing canonical paths."] : []), "A local backup is created before applying; the backend's active head will change.");
122
89
  }
123
90
  export function formatPublicationPreview(remote, upload) {
124
91
  return formatDirectionalChanges(remote, upload, {
@@ -138,11 +105,12 @@ function formatDirectionalChanges(before, after, labels, protectedPaths = new Se
138
105
  }
139
106
  const counts = transferCounts(changes);
140
107
  const label = { Add: labels.add, Update: labels.update, Delete: labels.remove };
141
- return [
142
- `Changes: ${counts.add} add · ${counts.update} update · ${counts.remove} remove`,
143
- ...changes.map((change) => `${label[change.action]}: ${snapshotPathLabel(change.path)}`),
144
- ...(changes.length ? [] : ["No file changes."]),
145
- ].join("\n");
108
+ const heading = `Changes: ${counts.add} add · ${counts.update} update · ${counts.remove} remove`;
109
+ const lines = changes.length ? [heading] : [heading, "No file changes."];
110
+ return {
111
+ lines,
112
+ content: [...lines, ...changes.map((change) => `${label[change.action]}: ${snapshotPathLabel(change.path)}`)].join("\n"),
113
+ };
146
114
  }
147
115
  export function countPreservedRemoteFiles(local, upload) {
148
116
  const localPaths = new Set(local.files.map((file) => file.path));
@@ -1,3 +1,4 @@
1
1
  import type { EngineContext } from "../host.js";
2
+ import type { TransferReview } from "./sync-format.js";
2
3
  /** Presentation is supplied by the host; RPC keeps its existing directional confirmation. */
3
- export declare function confirmTransferReview(ctx: EngineContext, title: string, content: string, signal: AbortSignal | undefined, validate: () => void): Promise<boolean>;
4
+ export declare function confirmTransferReview(ctx: EngineContext, title: string, review: TransferReview, signal: AbortSignal | undefined, validate: () => void): Promise<boolean>;
@@ -1,6 +1,6 @@
1
1
  import { confirmMergeReview } from "./merge-review.js";
2
2
  /** Presentation is supplied by the host; RPC keeps its existing directional confirmation. */
3
- export async function confirmTransferReview(ctx, title, content, signal, validate) {
3
+ export async function confirmTransferReview(ctx, title, review, signal, validate) {
4
4
  validate();
5
5
  const isCurrent = () => {
6
6
  try {
@@ -12,8 +12,8 @@ export async function confirmTransferReview(ctx, title, content, signal, validat
12
12
  }
13
13
  };
14
14
  const confirmed = ctx.mode === "tui" && ctx.hasUI
15
- ? await confirmMergeReview(ctx, title, content, signal, isCurrent, "apply reviewed transfer", content.split("\n"))
16
- : await ctx.ui.confirm(title, content, { signal });
15
+ ? await confirmMergeReview(ctx, title, review.content, signal, isCurrent, "apply reviewed transfer", review.lines)
16
+ : await ctx.ui.confirm(title, review.content, { signal });
17
17
  validate();
18
18
  return confirmed;
19
19
  }
@@ -1,6 +1,6 @@
1
1
  import { type Execute } from "./protocol.js";
2
2
  /** Engine dispatch is loaded only by the service, never by the public IPC client. */
3
- export declare function createEngineService(root: string): {
3
+ export declare function createEngineService(root: string, ignoreFileSettingsAvailable?: boolean): {
4
4
  execute: Execute;
5
5
  bind: (value: Awaited<ReturnType<typeof import("./server.js").startServer>>) => void;
6
6
  hooks: {
@@ -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,18 +34,19 @@ 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 () => {
35
47
  if (operation === "ignore.capabilities") {
36
48
  execution.validate();
37
- return { available: false };
49
+ return { available: ignoreFileSettingsAvailable };
38
50
  }
39
51
  if (operation === "ignore.migration-offer" || operation === "ignore.migration-defer") {
40
52
  execution.validate();
@@ -47,23 +59,60 @@ export function createEngineService(root) {
47
59
  execution.validate();
48
60
  throw new Error("Daemon ignore-file saves are unavailable. Edit the existing rule file manually.");
49
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
+ }
50
67
  await monitor.pause();
51
68
  execution.validate();
52
- if (operation === "daemon.authorize")
53
- 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
+ }
54
101
  if (operation === "daemon.handover") {
55
102
  await requireHandover(execution);
56
103
  return true;
57
104
  }
58
105
  if (operation === "daemon.policy") {
59
- const { loadConfig } = await import("./engine/settings/config.js");
60
- const config = await loadConfig();
106
+ const { loadConfigForCheck } = await import("./engine/settings/config.js");
107
+ const config = await loadConfigForCheck(undefined, execution.signal);
108
+ execution.validate();
61
109
  const fingerprint = consentFingerprint(root, config);
62
110
  const saved = readConsent(root)?.setups[config.setupName];
63
111
  const facts = execution.facts();
64
112
  return {
65
113
  setup: config.setupName,
66
114
  fingerprint,
115
+ automatic: automaticPolicyAuthorized(root, config),
67
116
  afterExit: Boolean(saved?.afterExit &&
68
117
  saved.fingerprint === fingerprint &&
69
118
  JSON.stringify(saved.model) === JSON.stringify(facts?.model) &&
@@ -98,11 +147,12 @@ export function createEngineService(root) {
98
147
  (typeof payload.expected !== "string" || !/^[a-f0-9]{64}$/u.test(payload.expected))) ||
99
148
  !record(payload.next))
100
149
  throw new Error("Invalid settings mutation.");
101
- const { updateLocalConfigDocument, peekLocalConfigDocument } = await import("./engine/settings/config-file.js");
150
+ const { localConfigPath, updateLocalConfigDocument, peekLocalConfigDocument } = await import("./engine/settings/config-file.js");
102
151
  const { localConfigTemplate } = await import("./engine/settings/settings-store.js");
103
152
  const { validateSettingsDocument } = await import("./engine/settings/settings-validation.js");
104
153
  const next = validateSettingsDocument(payload.next);
105
- if (Object.values(next.syncSetups).some((setup) => setup.sync.pathPolicy === "ignore-file")) {
154
+ const nextMixed = Object.values(next.syncSetups).some((setup) => setup.sync.pathPolicy === "ignore-file");
155
+ if (!ignoreFileSettingsAvailable && nextMixed) {
106
156
  throw new Error("Ignore-file setup activation is not available in this Daemon build.");
107
157
  }
108
158
  if (Buffer.byteLength(JSON.stringify(next)) > MAX_SETTINGS_BYTES)
@@ -113,14 +163,44 @@ export function createEngineService(root) {
113
163
  if (documentFingerprint(view) !== payload.expected)
114
164
  throw new Error("Settings changed; reopen the review before saving.");
115
165
  };
116
- 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
+ }
117
192
  await requireHandover(execution);
118
193
  execution.validate();
119
- return updateLocalConfigDocument(localConfigTemplate(), () => {
194
+ const saved = await updateLocalConfigDocument(localConfigTemplate(), () => {
120
195
  execution.validate();
121
196
  validateSettingsDocument(next);
122
197
  return next;
123
- }, 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;
124
204
  }
125
205
  const ctx = createServiceContext(execution);
126
206
  if (operation === "initialize")
@@ -131,8 +211,8 @@ export function createEngineService(root) {
131
211
  const { withStateDirectoryAccess } = await import("./engine/state/state-directory.js");
132
212
  const { withLock } = await import("./engine/state/lock.js");
133
213
  return withJobTimings(ctx, execution, "daemon inspection", (timings) => withStateDirectoryAccess(() => withLock("startup-check", async () => {
134
- const { loadConfig, syncCheckConfigFingerprint } = await import("./engine/settings/config.js");
135
- 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);
136
216
  execution.validate();
137
217
  if (payload.fingerprint !== syncCheckConfigFingerprint(config))
138
218
  throw new Error("Settings changed before inspection.");
@@ -159,13 +239,14 @@ export function createEngineService(root) {
159
239
  ];
160
240
  if (!supported.includes(operation))
161
241
  throw new Error("Unsupported engine operation.");
162
- const options = optionsFrom(payload, execution);
242
+ const isAutomatic = operation === "startup-transfer" || operation === "shutdown";
243
+ const options = optionsFrom(payload, execution, isAutomatic);
163
244
  if (!options.reload)
164
245
  ctx.reload = undefined;
165
246
  if (operation === "shutdown") {
166
247
  const { loadConfigForCheck } = await import("./engine/settings/config.js");
167
248
  const { syncSessionsSelected } = await import("./engine/sync/sync-policy.js");
168
- const config = await loadConfigForCheck();
249
+ const config = await loadConfigForCheck(undefined, execution.signal);
169
250
  execution.validate();
170
251
  if (!config.automatic || !syncSessionsSelected(config))
171
252
  return;
@@ -188,11 +269,16 @@ export function createEngineService(root) {
188
269
  return result;
189
270
  }
190
271
  return withStateDirectoryAccess(async () => {
191
- if (["startup-transfer", "shutdown"].includes(operation) && !readConsent(root))
192
- 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 };
193
277
  if (["push", "pull", "sync", "startup-transfer", "shutdown", "conflicts", "rollback"].includes(operation)) {
194
278
  await requireHandover(execution);
279
+ await automatic?.refresh();
195
280
  await initialize(ctx, execution, false);
281
+ await automatic?.refresh();
196
282
  }
197
283
  const { withLock, unlock } = await import("./engine/state/lock.js");
198
284
  if (operation === "unlock")
@@ -207,9 +293,8 @@ export function createEngineService(root) {
207
293
  return pushSessionsOnShutdown(ctx, options, { operations: async () => operations });
208
294
  }
209
295
  if (operation === "startup-transfer") {
210
- const { loadConfig } = await import("./engine/settings/config.js");
211
296
  const { startupTransferEnabled } = await import("./engine/sync/agent-policy.js");
212
- if (!startupTransferEnabled(await loadConfig(options.setup)) || !ctx.isIdle())
297
+ if (!automatic || !startupTransferEnabled(automatic.config) || !ctx.isIdle())
213
298
  throw new Error("Startup transfer is no longer authorized or idle.");
214
299
  options.auto = true;
215
300
  options.yes = true;
@@ -220,25 +305,33 @@ export function createEngineService(root) {
220
305
  const run = async () => {
221
306
  const { prepareResolverHost } = await import("./resolver-host.js");
222
307
  const { loadConfig } = await import("./engine/settings/config.js");
223
- const config = await loadConfig(options.setup);
308
+ const config = await loadConfig(options.setup, execution.signal);
309
+ await automatic?.refresh();
310
+ automatic?.validate(config);
224
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
+ }
225
315
  if (operation === "sync" && !options.agentRetryRefusal)
226
- monitor.explicitSync(config.setupName, execution);
316
+ monitor.explicitSync(config, execution);
227
317
  const binding = JSON.stringify(execution.facts()?.model);
228
318
  const resolver = await prepareResolverHost(root, config.agentMode ? execution.facts()?.model : undefined, execution.signal);
229
319
  try {
320
+ await automatic?.refresh();
230
321
  ctx.modelUnavailableReason = resolver.unavailable;
231
322
  Object.defineProperty(ctx, "model", {
232
323
  get: () => (JSON.stringify(execution.facts()?.model) === binding ? resolver.model : undefined),
233
324
  });
234
325
  ctx.validateModel = async () => {
235
326
  const fresh = await execution.request("model-binding", {});
327
+ await automatic?.refresh();
236
328
  execution.validate();
237
329
  if (JSON.stringify(fresh ?? undefined) !== binding)
238
330
  throw new Error("Selected provider/model capability changed before dispatch.");
239
331
  };
240
332
  ctx.modelRegistry = {
241
333
  streamSimple: (model, context, options) => {
334
+ automatic?.validate();
242
335
  execution.validate();
243
336
  if (JSON.stringify(execution.facts()?.model) !== binding)
244
337
  throw new Error("Selected model changed before dispatch.");
@@ -250,13 +343,17 @@ export function createEngineService(root) {
250
343
  const { withAgentSyncLock } = await import("./engine/sync/agent-sync.js");
251
344
  return await withAgentSyncLock(ctx, options, async (current) => {
252
345
  if (operation === "startup-transfer") {
253
- const { loadConfig } = await import("./engine/settings/config.js");
254
346
  const { startupTransferEnabled } = await import("./engine/sync/agent-policy.js");
255
- 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;
256
351
  execution.validate();
257
352
  const { inspectSync } = await import("./engine/sync/sync-inspection.js");
258
353
  const { snapshotOptionsForContext } = await import("./engine/snapshot/session-paths.js");
354
+ await automatic.refresh();
259
355
  const inspection = await inspectSync(config, snapshotOptionsForContext(ctx, config), current.signal);
356
+ await automatic.refresh();
260
357
  execution.validate();
261
358
  if (!startupTransferEnabled(config) ||
262
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>;