@narumitw/pi-sync 0.67.1 → 0.67.3

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 (58) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +7 -5
  3. package/dist/chunks/{chunk-JNTDIVP6.ts → chunk-33EDXDLC.ts} +2 -2
  4. package/dist/chunks/{chunk-W7DSN33J.ts → chunk-AVTW6WNP.ts} +3 -3
  5. package/dist/chunks/{chunk-XPKHWTGT.ts → chunk-CQ4DMLH3.ts} +61 -11
  6. package/dist/chunks/chunk-CQ4DMLH3.ts.map +7 -0
  7. package/dist/chunks/{chunk-CQXGMESM.ts → chunk-HLJIRWFL.ts} +2 -2
  8. package/dist/chunks/{chunk-3CO7QIYB.ts → chunk-X344HTVV.ts} +2 -2
  9. package/dist/chunks/{command-handler-H5X3BX5D.ts → command-handler-WF2TDDRZ.ts} +59 -16
  10. package/dist/chunks/command-handler-WF2TDDRZ.ts.map +7 -0
  11. package/dist/chunks/{conflict-review-SSY37F4P.ts → conflict-review-GWEL4S6C.ts} +2 -2
  12. package/dist/chunks/{ignore-file-ui-UY2TEK4C.ts → ignore-file-ui-BEZZZIEE.ts} +3 -3
  13. package/dist/chunks/{manager-result-dispatcher-PEVIGLOS.ts → manager-result-dispatcher-BXN46NRC.ts} +3 -3
  14. package/dist/chunks/{manager-ui-R5XHYRXK.ts → manager-ui-FS4QIKRA.ts} +9 -9
  15. package/dist/chunks/{remote-selection-ui-WFLX6MAJ.ts → remote-selection-ui-DOYKUMER.ts} +2 -2
  16. package/dist/chunks/{setup-wizard-5OMFSFPJ.ts → setup-wizard-PI45SF2C.ts} +4 -4
  17. package/dist/chunks/{sync-inspection-S2GHDBAD.ts → sync-inspection-DI5J6EUH.ts} +2 -2
  18. package/dist/chunks/{sync-operations-LQ63CU2T.ts → sync-operations-AGNL7QXA.ts} +2 -2
  19. package/dist/daemon/dist/build-id.json +1 -0
  20. package/dist/daemon/dist/build-version.js +24 -4
  21. package/dist/daemon/dist/cli.js +30 -65
  22. package/dist/daemon/dist/client-transport.js +13 -5
  23. package/dist/daemon/dist/consent.js +25 -16
  24. package/dist/daemon/dist/daemon-startup.js +135 -30
  25. package/dist/daemon/dist/daemon-status.js +56 -0
  26. package/dist/daemon/dist/engine/debug-log.js +19 -0
  27. package/dist/daemon/dist/engine/sync/merged-sync.js +1 -0
  28. package/dist/daemon/dist/engine/sync/sync-mutations.js +1 -0
  29. package/dist/daemon/dist/engine-service.js +20 -4
  30. package/dist/daemon/dist/index.js +2 -0
  31. package/dist/daemon/dist/server.js +97 -5
  32. package/dist/daemon/package.json +1 -1
  33. package/dist/index.ts +8 -7
  34. package/dist/index.ts.map +2 -2
  35. package/docs/agent-continuous-hardening.md +2 -0
  36. package/docs/daemon-migration.md +12 -12
  37. package/package.json +2 -2
  38. package/skills/configure-pi-sync/SKILL.md +6 -2
  39. package/skills/configure-pi-sync/references/configuration.md +3 -1
  40. package/src/commands/command-execution.ts +2 -9
  41. package/src/daemon/client-debug.ts +6 -3
  42. package/src/daemon/daemon-status-ui.ts +64 -0
  43. package/src/daemon/pi-client.ts +69 -9
  44. package/src/sync-extension.ts +4 -3
  45. package/dist/chunks/chunk-XPKHWTGT.ts.map +0 -7
  46. package/dist/chunks/command-handler-H5X3BX5D.ts.map +0 -7
  47. /package/dist/chunks/{chunk-JNTDIVP6.ts.map → chunk-33EDXDLC.ts.map} +0 -0
  48. /package/dist/chunks/{chunk-W7DSN33J.ts.map → chunk-AVTW6WNP.ts.map} +0 -0
  49. /package/dist/chunks/{chunk-CQXGMESM.ts.map → chunk-HLJIRWFL.ts.map} +0 -0
  50. /package/dist/chunks/{chunk-3CO7QIYB.ts.map → chunk-X344HTVV.ts.map} +0 -0
  51. /package/dist/chunks/{conflict-review-SSY37F4P.ts.map → conflict-review-GWEL4S6C.ts.map} +0 -0
  52. /package/dist/chunks/{ignore-file-ui-UY2TEK4C.ts.map → ignore-file-ui-BEZZZIEE.ts.map} +0 -0
  53. /package/dist/chunks/{manager-result-dispatcher-PEVIGLOS.ts.map → manager-result-dispatcher-BXN46NRC.ts.map} +0 -0
  54. /package/dist/chunks/{manager-ui-R5XHYRXK.ts.map → manager-ui-FS4QIKRA.ts.map} +0 -0
  55. /package/dist/chunks/{remote-selection-ui-WFLX6MAJ.ts.map → remote-selection-ui-DOYKUMER.ts.map} +0 -0
  56. /package/dist/chunks/{setup-wizard-5OMFSFPJ.ts.map → setup-wizard-PI45SF2C.ts.map} +0 -0
  57. /package/dist/chunks/{sync-inspection-S2GHDBAD.ts.map → sync-inspection-DI5J6EUH.ts.map} +0 -0
  58. /package/dist/chunks/{sync-operations-LQ63CU2T.ts.map → sync-operations-AGNL7QXA.ts.map} +0 -0
@@ -1,6 +1,6 @@
1
1
  import { request as httpRequest } from "node:http";
2
2
  import { lt, valid } from "semver";
3
- import { DAEMON_BUILD_VERSION } from "./build-version.js";
3
+ import { DAEMON_BUILD_VERSION, isDaemonBuildId } from "./build-version.js";
4
4
  import { daemonPaths, readJsonBody } from "./identity.js";
5
5
  import { MAX_MESSAGE_BYTES, record } from "./protocol.js";
6
6
  export class DaemonError extends Error {
@@ -44,7 +44,7 @@ export async function requestDaemon(paths, identity, method, params, signal, opt
44
44
  })
45
45
  .catch(reject);
46
46
  });
47
- request.setTimeout(method === "attach" || method === "resume-contact" ? 0 : 30_000, () => request.destroy(new Error("Daemon request timed out.")));
47
+ request.setTimeout(["attach", "protect-session", "resume-contact"].includes(method) ? 0 : 30_000, () => request.destroy(new Error("Daemon request timed out.")));
48
48
  request.once("error", reject);
49
49
  if (options?.onSocket)
50
50
  request.once("socket", options.onSocket);
@@ -59,8 +59,16 @@ export async function hello(paths, identity, signal) {
59
59
  value.instance !== identity.instance ||
60
60
  value.pid !== identity.pid)
61
61
  throw new Error("Daemon handshake mismatch.");
62
- const version = value.buildVersion;
63
- if (Object.hasOwn(value, "buildVersion") && (typeof version !== "string" || valid(version) !== version))
62
+ const buildVersion = value.buildVersion;
63
+ if (buildVersion !== undefined && (typeof buildVersion !== "string" || valid(buildVersion) !== buildVersion))
64
64
  throw new Error("Invalid daemon build version.");
65
- return { needsUpgrade: typeof version !== "string" || lt(version, DAEMON_BUILD_VERSION) };
65
+ const buildId = value.buildId;
66
+ if (buildId !== undefined && !isDaemonBuildId(buildId))
67
+ throw new Error("Invalid daemon build identifier.");
68
+ return {
69
+ buildVersion,
70
+ buildId,
71
+ upgradeStop: value.upgradeStop === 1,
72
+ needsUpgrade: buildVersion === undefined || lt(buildVersion, DAEMON_BUILD_VERSION),
73
+ };
66
74
  }
@@ -190,7 +190,7 @@ function ignorePublicationConsentLines(config) {
190
190
  : "New snapshots include the rule file, including any rule comments and private path names.",
191
191
  ];
192
192
  }
193
- export async function reviewAutomaticPolicy(execution, config, expectedFingerprint) {
193
+ export async function reviewAutomaticPolicy(execution, config, expectedFingerprint, origin) {
194
194
  if (consentFingerprint(execution.root, config) !== expectedFingerprint)
195
195
  throw new Error("Setup changed; reopen the automatic transfer review.");
196
196
  if (config.reservedIgnoreNames === undefined || automaticPolicyAuthorized(execution.root, config)) {
@@ -230,21 +230,30 @@ export async function reviewAutomaticPolicy(execution, config, expectedFingerpri
230
230
  ].filter(Boolean);
231
231
  if (modes.length === 0)
232
232
  throw new Error("No automatic transfer mode is enabled under the current local rules.");
233
- const accepted = await execution.request("confirm", {
234
- title: "Allow the enabled automatic sync modes for this setup?",
235
- message: [
236
- `Setup: ${safeTerminalText(config.setupName)}`,
237
- `Destination: ${safeTerminalText(config.connectionName)} · ${safeTerminalText(config.storagePath)}`,
238
- ...(config.ignorePolicy
239
- ? [
240
- `Local ignore file: ${safeTerminalText(config.ignorePolicy.filename)}`,
241
- ...ignorePublicationConsentLines(config),
242
- ]
243
- : []),
244
- `Enabled modes: ${modes.join("; ")}`,
245
- "Their usual baseline, remote selection, and ownership checks still apply. This does not allow work after the last Pi exits. A settings or rule-file change requires a new review.",
246
- ].join("\n"),
247
- });
233
+ const title = "Allow the enabled automatic sync modes for this setup?";
234
+ const lines = [
235
+ `Setup: ${safeTerminalText(config.setupName)}`,
236
+ `Destination: ${safeTerminalText(config.connectionName)} · ${safeTerminalText(config.storagePath)}`,
237
+ ...(config.ignorePolicy
238
+ ? [
239
+ `Local ignore file: ${safeTerminalText(config.ignorePolicy.filename)}`,
240
+ ...ignorePublicationConsentLines(config),
241
+ ]
242
+ : []),
243
+ `Enabled modes: ${modes.join("; ")}`,
244
+ "Their usual baseline, remote selection, and ownership checks still apply. This does not allow work after the last Pi exits. A settings or rule-file change requires a new review.",
245
+ ];
246
+ if (origin === "retry")
247
+ lines.push("This approval is saved separately from the model retry. Sending conflict evidence again still requires its own confirmation.");
248
+ const content = lines.join("\n");
249
+ const accepted = origin === "retry"
250
+ ? await execution.request("merge-review", {
251
+ title,
252
+ content,
253
+ confirmationLabel: "Approve automatic transfers",
254
+ summaryLines: lines,
255
+ })
256
+ : await execution.request("confirm", { title, message: content });
248
257
  validate();
249
258
  if (accepted !== true) {
250
259
  execution.noteDebugOutcome?.("cancelled");
@@ -1,11 +1,41 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { lstat } from "node:fs/promises";
2
3
  import { setTimeout as delay } from "node:timers/promises";
3
4
  import { fileURLToPath } from "node:url";
4
5
  import lockfile from "proper-lockfile";
6
+ import { gt } from "semver";
7
+ import { DAEMON_BUILD_ID, DAEMON_BUILD_VERSION, readInstalledDaemonBuild } from "./build-version.js";
5
8
  import { DaemonError, hello, requestDaemon } from "./client-transport.js";
6
9
  import { canonicalRootGuard, clearUpgradeOwner, daemonPaths, privateDirectory, processExists, processExited, readIdentity, readProcessBirth, readUpgradeOwner, recordUpgradeOwner, runtimePaths, upgradeRepairStarted, } from "./identity.js";
7
10
  import { OWNERSHIP_CLEANUP_REQUIRED, record } from "./protocol.js";
8
- export async function checkUpgradeConsent(paths, assertRoot, signal) {
11
+ const upgradeBlockers = {
12
+ busy: "Daemon update deferred while sync work is active. Let it finish, then use /reload or retry the daemon CLI.",
13
+ repair: "Daemon update blocked by uncertain consent or queue cleanup. Follow the daemon recovery guide before retrying.",
14
+ unattended: "Review or revoke unattended Pi Sync permission before stopping or replacing the daemon.",
15
+ legacy: "This older daemon does not support guarded upgrades. Let sync work finish, run restart from the intended daemon CLI, then /reload.",
16
+ };
17
+ export class DaemonUpgradeBlockedError extends Error {
18
+ instance;
19
+ constructor(instance, reason) {
20
+ super(upgradeBlockers[reason]);
21
+ this.instance = instance;
22
+ this.name = "DaemonUpgradeBlockedError";
23
+ }
24
+ }
25
+ function matchesBuild(version, id) {
26
+ return version === DAEMON_BUILD_VERSION && id === DAEMON_BUILD_ID;
27
+ }
28
+ function assertInstalledBuild() {
29
+ const { version, id } = readInstalledDaemonBuild();
30
+ if (!matchesBuild(version, id))
31
+ throw new Error("The daemon installation changed. Reload the intended Pi Sync build before retrying.");
32
+ }
33
+ const sameIdentity = (left, right) => left?.instance === right?.instance && left?.pid === right?.pid && left?.token === right?.token;
34
+ const sameBarrier = (left, right) => left?.instance === right.instance &&
35
+ left.pid === right.pid &&
36
+ left.birth === right.birth &&
37
+ left.purpose === right.purpose;
38
+ export async function checkUpgradeConsent(paths, assertRoot, signal, instance) {
9
39
  const { readConsent } = await import("./consent.js");
10
40
  const { withStateDirectoryGuardForRoot } = await import("./engine/state/state-directory.js");
11
41
  signal?.throwIfAborted();
@@ -13,8 +43,11 @@ export async function checkUpgradeConsent(paths, assertRoot, signal) {
13
43
  signal?.throwIfAborted();
14
44
  assertRoot();
15
45
  const consent = readConsent(paths.root);
16
- if (consent && Object.values(consent.setups).some((setup) => setup.afterExit))
17
- throw new Error("Review or revoke unattended Pi Sync permission before stopping or replacing the daemon.");
46
+ if (consent && Object.values(consent.setups).some((setup) => setup.afterExit)) {
47
+ if (instance)
48
+ throw new DaemonUpgradeBlockedError(instance, "unattended");
49
+ throw new Error(upgradeBlockers.unattended);
50
+ }
18
51
  });
19
52
  signal?.throwIfAborted();
20
53
  assertRoot();
@@ -24,30 +57,62 @@ export async function finishUpgrade(paths, owner, assertRoot, signal) {
24
57
  const current = await readIdentity(paths);
25
58
  if (current?.instance === owner.instance)
26
59
  throw new Error("The daemon exited without releasing its identity.");
27
- if (current && owner.purpose === "cleanup")
60
+ if (current)
28
61
  throw new Error("Daemon owner changed during recovery. Review the current owner before retrying.");
62
+ const ownerLock = await lstat(paths.owner).catch((error) => {
63
+ if (error.code === "ENOENT")
64
+ return undefined;
65
+ throw error;
66
+ });
67
+ if (ownerLock)
68
+ throw new Error("The daemon exited without releasing its owner lock. Follow daemon recovery.");
29
69
  await checkUpgradeConsent(paths, assertRoot, signal);
70
+ if (!sameBarrier(await readUpgradeOwner(paths), owner))
71
+ throw new Error("Daemon upgrade record changed; private state was retained.");
72
+ signal?.throwIfAborted();
73
+ assertRoot();
30
74
  await clearUpgradeOwner(paths);
31
75
  signal?.throwIfAborted();
32
76
  assertRoot();
33
77
  }
34
- async function drainForUpgrade(paths, owner, { recorded, birth }, assertRoot, signal) {
35
- await checkUpgradeConsent(paths, assertRoot, signal);
78
+ async function drainForUpgrade(paths, owner, { recorded, birth, guarded }, assertRoot, signal) {
79
+ await checkUpgradeConsent(paths, assertRoot, signal, owner.instance);
36
80
  const barrier = recorded ?? { ...owner, birth };
81
+ if (!sameIdentity(await readIdentity(paths), owner))
82
+ throw new Error("Daemon owner changed before stop.");
83
+ signal?.throwIfAborted();
84
+ assertRoot();
85
+ assertInstalledBuild();
86
+ if (!recorded)
87
+ await recordUpgradeOwner(paths, barrier);
88
+ let reply;
37
89
  try {
38
- if (!recorded)
39
- await recordUpgradeOwner(paths, barrier);
90
+ signal?.throwIfAborted();
40
91
  assertRoot();
41
- const reply = await requestDaemon(paths, owner, "stop", {}, signal);
42
- if (!record(reply) || reply.stopping !== true)
92
+ assertInstalledBuild();
93
+ reply = await requestDaemon(paths, owner, guarded ? "upgrade-stop" : "stop", {}, signal);
94
+ if (!record(reply) || (reply.stopping !== true && (!guarded || !isDeferral(reply.deferred))))
43
95
  throw new Error("Daemon did not acknowledge stop.");
44
96
  }
45
97
  catch (error) {
46
98
  signal?.throwIfAborted();
47
- throw new Error("Pi Sync could not upgrade the older daemon safely. Check `pi-sync-daemon status --root <agent-directory>`. Do not force a second owner or remove recovery files.", { cause: error });
99
+ throw new Error("Pi Sync could not replace the daemon safely. Check `pi-sync-daemon status --root <agent-directory>`. Do not force a second owner or remove recovery files.", { cause: error });
100
+ }
101
+ if (guarded && isDeferral(reply.deferred) && reply.stopping !== true) {
102
+ const current = await readIdentity(paths);
103
+ const pending = await readUpgradeOwner(paths);
104
+ signal?.throwIfAborted();
105
+ assertRoot();
106
+ if (!sameIdentity(current, owner) || !sameBarrier(pending, barrier))
107
+ throw new Error("Daemon owner or upgrade record changed; private state was retained.");
108
+ await clearUpgradeOwner(paths);
109
+ throw new DaemonUpgradeBlockedError(owner.instance, reply.deferred);
48
110
  }
49
111
  await finishUpgrade(paths, barrier, assertRoot, signal);
50
112
  }
113
+ function isDeferral(value) {
114
+ return value === "busy" || value === "unattended" || value === "repair";
115
+ }
51
116
  export async function acquireStartupLock(paths, signal) {
52
117
  const deadline = performance.now() + 150_000;
53
118
  for (;;) {
@@ -70,25 +135,38 @@ export async function acquireStartupLock(paths, signal) {
70
135
  }
71
136
  }
72
137
  }
73
- export async function ensureDaemon(root, signal, options) {
138
+ export function ensureDaemon(root, signal, options) {
139
+ return startDaemon(root, signal, options?.compatibleOnly ? "compatible-only" : "ensure");
140
+ }
141
+ export function restartDaemon(root, signal) {
142
+ return startDaemon(root, signal, "restart");
143
+ }
144
+ async function startDaemon(root, signal, intent) {
74
145
  const paths = await runtimePaths(root);
75
146
  const assertRoot = canonicalRootGuard(paths.root);
76
147
  signal?.throwIfAborted();
77
148
  await privateDirectory(paths.directory);
149
+ const restartTarget = intent === "restart" ? { identity: await readIdentity(paths) } : undefined;
78
150
  signal?.throwIfAborted();
79
151
  const release = await acquireStartupLock(paths, signal);
80
152
  try {
81
153
  signal?.throwIfAborted();
82
154
  let waited = false;
83
155
  let upgraded = false;
156
+ let verifyRestartTarget = restartTarget !== undefined;
84
157
  for (;;) {
85
158
  signal?.throwIfAborted();
86
159
  const upgrade = await readUpgradeOwner(paths);
87
- if (upgrade && options?.compatibleOnly)
160
+ if (upgrade && intent === "compatible-only")
88
161
  throw new Error("A daemon upgrade or recovery is pending; no replacement was attempted.");
89
162
  if (upgrade && (await upgradeRepairStarted(paths, upgrade)))
90
163
  throw new Error("A daemon upgrade repair is incomplete. Run `pi-sync-daemon repair-upgrade` for this root.");
91
164
  const existing = await readIdentity(paths);
165
+ if (verifyRestartTarget) {
166
+ if (!sameIdentity(existing, restartTarget?.identity))
167
+ throw new Error("Daemon owner changed while waiting to restart. Check status before retrying.");
168
+ verifyRestartTarget = false;
169
+ }
92
170
  if (upgrade && existing?.instance === upgrade.instance && existing.pid !== upgrade.pid)
93
171
  throw new Error("The recorded upgrade owner changed; private state was retained.");
94
172
  if (upgrade && (existing?.instance !== upgrade.instance || (await processExited(upgrade)))) {
@@ -124,38 +202,53 @@ export async function ensureDaemon(root, signal, options) {
124
202
  }
125
203
  signal?.throwIfAborted();
126
204
  assertRoot();
127
- if (!status.needsUpgrade) {
205
+ const restart = intent === "restart" && !upgraded;
206
+ if (restart && status.buildVersion && gt(status.buildVersion, DAEMON_BUILD_VERSION))
207
+ throw new Error("The running daemon is newer than this CLI. Use the intended Pi Sync build to restart it.");
208
+ if (!status.needsUpgrade && !restart) {
128
209
  if (upgrade)
129
210
  throw new Error("The recorded upgrade owner changed; private state was retained.");
130
- return { paths: daemonPaths(paths, existing.instance), identity: existing, ...status };
211
+ return { paths: daemonPaths(paths, existing.instance), identity: existing, ...status, replacedOwner: false };
131
212
  }
132
- if (options?.compatibleOnly)
213
+ if (intent === "compatible-only")
133
214
  throw new Error("A compatible daemon could not be attached; an older owner was left unchanged.");
134
215
  if (upgraded)
135
216
  throw new Error("An older Pi Sync daemon started again. Close or upgrade other Pi sessions, then use /reload.");
217
+ if (!status.upgradeStop && !restart)
218
+ throw new DaemonUpgradeBlockedError(existing.instance, "legacy");
136
219
  const birth = beforeHello === undefined ? undefined : await readProcessBirth(existing.pid);
137
- if (birth !== undefined && birth !== beforeHello)
220
+ if (birth !== beforeHello || (upgrade?.birth !== undefined && (await processExited(upgrade))))
138
221
  throw new Error("The daemon process changed during authentication; private state was retained.");
139
- await drainForUpgrade(paths, existing, { recorded: upgrade, birth }, assertRoot, signal);
222
+ await drainForUpgrade(paths, existing, { recorded: upgrade, birth, guarded: status.upgradeStop }, assertRoot, signal);
140
223
  upgraded = true;
141
224
  }
142
225
  signal?.throwIfAborted();
143
226
  assertRoot();
227
+ assertInstalledBuild();
144
228
  const executable = process.versions.bun ? "node" : process.execPath;
145
- const child = spawn(executable, [fileURLToPath(new URL("./cli.js", import.meta.url)), "serve", "--root", paths.root], {
229
+ const child = spawn(executable, [
230
+ fileURLToPath(new URL("./cli.js", import.meta.url)),
231
+ "serve",
232
+ "--root",
233
+ paths.root,
234
+ "--expect-build",
235
+ DAEMON_BUILD_VERSION,
236
+ DAEMON_BUILD_ID ?? "",
237
+ ], {
146
238
  detached: true,
147
239
  stdio: ["ignore", "ignore", "ignore", "ipc"],
148
240
  windowsHide: true,
149
241
  });
150
242
  const ready = await new Promise((resolve, reject) => {
151
- let timer;
243
+ let booting = false;
244
+ let timer = setTimeout(() => failed(new Error("Daemon bootstrap timed out before the child handshake.")), 60_000);
245
+ timer.unref?.();
152
246
  const abort = () => {
153
247
  cleanup();
154
248
  reject(signal?.reason);
155
249
  };
156
250
  const cleanup = () => {
157
- if (timer)
158
- clearTimeout(timer);
251
+ clearTimeout(timer);
159
252
  signal?.removeEventListener("abort", abort);
160
253
  child.off("message", message);
161
254
  child.off("error", failed);
@@ -169,15 +262,20 @@ export async function ensureDaemon(root, signal, options) {
169
262
  const message = (value) => {
170
263
  if (!record(value))
171
264
  return;
172
- if (value.type === "booting") {
265
+ if (value.type === "booting" && !booting) {
266
+ booting = true;
267
+ clearTimeout(timer);
173
268
  timer = setTimeout(() => failed(new Error("Daemon readiness timed out.")), 15_000);
174
269
  timer.unref?.();
175
270
  }
176
271
  if (value.type === "error")
177
272
  failed(new Error(typeof value.message === "string" ? value.message : "Daemon startup failed."));
178
- if (value.type === "ready" && record(value.identity)) {
273
+ if (value.type === "ready") {
274
+ const candidate = value.identity;
275
+ if (!record(candidate) || candidate.pid !== child.pid || candidate.root !== paths.root)
276
+ return failed(new Error("Daemon readiness identity did not match the launched process."));
179
277
  cleanup();
180
- resolve(value.identity);
278
+ resolve(candidate);
181
279
  }
182
280
  };
183
281
  signal?.addEventListener("abort", abort, { once: true });
@@ -187,16 +285,21 @@ export async function ensureDaemon(root, signal, options) {
187
285
  if (signal?.aborted)
188
286
  abort();
189
287
  }).finally(() => {
288
+ if (!child.pid)
289
+ child.once("error", () => { });
190
290
  if (child.connected)
191
291
  child.disconnect();
192
292
  child.unref();
193
293
  });
194
- const status = await hello(paths, ready, signal);
294
+ const published = await readIdentity(paths);
295
+ if (!published || !sameIdentity(published, ready))
296
+ throw new Error("Ready daemon was not the published owner.");
297
+ const status = await hello(paths, published, signal);
195
298
  signal?.throwIfAborted();
196
299
  assertRoot();
197
- if (status.needsUpgrade)
300
+ if (!matchesBuild(status.buildVersion, status.buildId))
198
301
  throw new Error("The daemon installation changed during startup. Use /reload to retry.");
199
- return { paths: daemonPaths(paths, ready.instance), identity: ready, ...status };
302
+ return { paths: daemonPaths(paths, ready.instance), identity: ready, ...status, replacedOwner: upgraded };
200
303
  }
201
304
  finally {
202
305
  await release();
@@ -216,7 +319,8 @@ async function waitForProcessExit(owner, signal) {
216
319
  }
217
320
  signal?.throwIfAborted();
218
321
  }
219
- export async function findDaemon(root) {
322
+ export async function findDaemon(root, signal) {
323
+ signal?.throwIfAborted();
220
324
  let paths;
221
325
  try {
222
326
  paths = await runtimePaths(root);
@@ -227,10 +331,11 @@ export async function findDaemon(root) {
227
331
  throw error;
228
332
  }
229
333
  const identity = await readIdentity(paths);
334
+ signal?.throwIfAborted();
230
335
  if (!identity || !processExists(identity.pid))
231
336
  return undefined;
232
337
  try {
233
- const status = await hello(paths, identity);
338
+ const status = await hello(paths, identity, signal);
234
339
  return { paths: daemonPaths(paths, identity.instance), identity, ...status };
235
340
  }
236
341
  catch (error) {
@@ -0,0 +1,56 @@
1
+ import path from "node:path";
2
+ import { gt } from "semver";
3
+ import { DAEMON_BUILD_ID, DAEMON_BUILD_VERSION } from "./build-version.js";
4
+ import { hello } from "./client-transport.js";
5
+ import { processExited, readIdentity, readUpgradeOwner, runtimePaths } from "./identity.js";
6
+ import { PROTOCOL_VERSION } from "./protocol.js";
7
+ export async function inspectDaemonStatus(root, signal) {
8
+ signal?.throwIfAborted();
9
+ const paths = await runtimePaths(root);
10
+ const identity = await readIdentity(paths);
11
+ const pending = await readUpgradeOwner(paths);
12
+ const summary = {
13
+ root: paths.root,
14
+ expectedBuildVersion: DAEMON_BUILD_VERSION,
15
+ ...(DAEMON_BUILD_ID && { expectedBuildId: DAEMON_BUILD_ID }),
16
+ ...(identity && { recordedPid: identity.pid }),
17
+ ...(pending && { pendingUpgradePid: pending.pid }),
18
+ };
19
+ signal?.throwIfAborted();
20
+ if (!identity ||
21
+ (pending?.instance === identity.instance && pending.pid === identity.pid && (await processExited(pending)))) {
22
+ signal?.throwIfAborted();
23
+ return { running: false, ...summary };
24
+ }
25
+ try {
26
+ const build = await hello(paths, identity, signal);
27
+ signal?.throwIfAborted();
28
+ return {
29
+ running: true,
30
+ ...summary,
31
+ version: PROTOCOL_VERSION,
32
+ instance: identity.instance,
33
+ pid: identity.pid,
34
+ ...(build.buildVersion && { buildVersion: build.buildVersion }),
35
+ ...(build.buildId && { buildId: build.buildId }),
36
+ buildComparison: compareBuild(build),
37
+ ...(build.upgradeStop && { guardedUpgrade: true }),
38
+ lifecycleLog: path.join(paths.directory, "lifecycle.log"),
39
+ };
40
+ }
41
+ catch {
42
+ signal?.throwIfAborted();
43
+ return { running: null, ...summary };
44
+ }
45
+ }
46
+ function compareBuild({ buildVersion, buildId, needsUpgrade }) {
47
+ if (!buildVersion)
48
+ return "unversioned";
49
+ if (needsUpgrade)
50
+ return "older";
51
+ if (gt(buildVersion, DAEMON_BUILD_VERSION))
52
+ return "newer";
53
+ if (!buildId || !DAEMON_BUILD_ID)
54
+ return "unverified";
55
+ return buildId === DAEMON_BUILD_ID ? "match" : "different";
56
+ }
@@ -1,5 +1,6 @@
1
1
  import { closeSync, constants, fstatSync, lstatSync, openSync, realpathSync, writeSync, } from "node:fs";
2
2
  import path from "node:path";
3
+ import { isForegroundDirection, isForegroundQueueOutcome } from "../foreground-queue-outcome.js";
3
4
  import { DEBUG_LOG_FILENAME } from "./paths.js";
4
5
  import { isStartupTimingReport } from "./sync/startup-timings.js";
5
6
  const OPERATIONS = [
@@ -11,6 +12,8 @@ const OPERATIONS = [
11
12
  "history",
12
13
  "push",
13
14
  "pull",
15
+ "push.foreground",
16
+ "pull.foreground",
14
17
  "sync",
15
18
  "startup-transfer",
16
19
  "shutdown",
@@ -39,6 +42,22 @@ const CYCLE_REASONS = [
39
42
  export function debugOperation(operation) {
40
43
  return OPERATIONS.find((known) => known === operation);
41
44
  }
45
+ export function debugJobResult(operation, result) {
46
+ if (!isForegroundDirection(operation))
47
+ return result === "cancelled" ? "cancelled" : undefined;
48
+ if (isForegroundQueueOutcome(result)) {
49
+ if (result.foregroundQueueCleanup !== "verified-result")
50
+ return "blocked";
51
+ result = result.result;
52
+ }
53
+ if (result && typeof result === "object" && "outcome" in result) {
54
+ if (result.outcome === "applied")
55
+ return "completed";
56
+ if (result.outcome === "cancelled")
57
+ return "cancelled";
58
+ }
59
+ return "failed";
60
+ }
42
61
  function safeFields(event) {
43
62
  switch (event.event) {
44
63
  case "startup-timings":
@@ -55,6 +55,7 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
55
55
  }
56
56
  };
57
57
  const validateRetryAuthorization = (config) => {
58
+ options.validateAgentRetryPolicy?.(config);
58
59
  if (options.agentRetryRefusal &&
59
60
  (!config.agentMode || options.auto || options.background || !ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)))
60
61
  throw new Error("Refused-candidate retry requires foreground Autonomous sync in TUI or RPC.");
@@ -629,6 +629,7 @@ export async function syncBoth(ctx, options, factory = createSyncBackend) {
629
629
  throwIfAborted(options.signal);
630
630
  options.background?.validate(config);
631
631
  if (options.agentRetryRefusal) {
632
+ options.validateAgentRetryPolicy?.(config);
632
633
  if (!config.agentMode || options.auto || options.background || !ctx.hasUI)
633
634
  throw new Error("Enable Autonomous sync and use the foreground manager to retry a cached refusal.");
634
635
  const state = await readStateForConfig(config);
@@ -319,16 +319,31 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
319
319
  if (operation === "sync" || operation === "startup-transfer") {
320
320
  const run = async () => {
321
321
  const { prepareResolverHost } = await import("./resolver-host.js");
322
- const { loadConfig } = await import("./engine/settings/config.js");
322
+ const { loadConfig, syncCheckConfigFingerprint } = await import("./engine/settings/config.js");
323
323
  const config = await loadConfig(options.setup, execution.signal);
324
324
  await automatic?.refresh();
325
325
  automatic?.validate(config);
326
326
  execution.validate();
327
327
  if (config.agentMode && !automaticPolicyAuthorized(root, config)) {
328
- execution.noteDebugOutcome?.("blocked");
329
- throw new Error("Autonomous sync requires a separate policy review. Use Settings → Review automatic transfers, or choose a reviewed push or pull.");
328
+ if (!options.agentRetryRefusal) {
329
+ execution.noteDebugOutcome?.("blocked");
330
+ throw new Error("Autonomous sync requires a separate policy review. Use Settings → Review automatic transfers, or choose a reviewed push or pull.");
331
+ }
332
+ const approved = await reviewAutomaticPolicy(execution, config, consentFingerprint(root, config), "retry");
333
+ execution.validate();
334
+ if (!approved)
335
+ return "cancelled";
336
+ monitor.reviewedPolicy(config);
337
+ }
338
+ if (options.agentRetryRefusal) {
339
+ const fingerprint = syncCheckConfigFingerprint(config);
340
+ options.validateAgentRetryPolicy = (current) => {
341
+ execution.validate();
342
+ if (syncCheckConfigFingerprint(current) !== fingerprint || !automaticPolicyAuthorized(root, current))
343
+ throw new Error("Sync setup or automatic transfer approval changed; reopen the retry.");
344
+ };
330
345
  }
331
- if (operation === "sync" && !options.agentRetryRefusal)
346
+ else if (operation === "sync")
332
347
  monitor.explicitSync(config, execution);
333
348
  const binding = JSON.stringify(execution.facts()?.model);
334
349
  const resolver = await prepareResolverHost(root, config.agentMode ? execution.facts()?.model : undefined, execution.signal);
@@ -424,6 +439,7 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
424
439
  quiesce: monitor.pause,
425
440
  failure: monitor.blockAutomatic,
426
441
  foregroundRecoveryAllowed: monitor.foregroundRecoveryAllowed,
442
+ upgradeAllowed: () => !host.cleanupRequired() && monitor.foregroundRecoveryAllowed(),
427
443
  },
428
444
  };
429
445
  }
@@ -1,5 +1,7 @@
1
1
  export { DaemonConnection, DaemonError, ensureDaemon, findDaemon, requestDaemon, stopDaemon, waitForDaemonExit, } from "./client.js";
2
2
  export { inspectDaemonRecovery, stopDaemonForRecovery, } from "./daemon-recovery.js";
3
+ export { DaemonUpgradeBlockedError } from "./daemon-startup.js";
4
+ export { inspectDaemonStatus } from "./daemon-status.js";
3
5
  export { documentFingerprint } from "./document.js";
4
6
  export { modelSignature } from "./model-signature.js";
5
7
  export { MAX_SETTINGS_BYTES, OWNERSHIP_CLEANUP_REQUIRED, PROTOCOL_VERSION } from "./protocol.js";