@narumitw/pi-sync 0.63.0 → 0.64.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 (135) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +28 -18
  3. package/dist/chunks/{chunk-HLCML3OW.ts → chunk-4VKWHVUO.ts} +4 -3
  4. package/dist/chunks/chunk-4VKWHVUO.ts.map +7 -0
  5. package/dist/chunks/{chunk-27F5W7DX.ts → chunk-DAZZ5BEJ.ts} +3 -1
  6. package/dist/chunks/chunk-DAZZ5BEJ.ts.map +7 -0
  7. package/dist/chunks/{chunk-V76KCWHO.ts → chunk-F3VODLVQ.ts} +3 -3
  8. package/dist/chunks/{chunk-VQ47JBLF.ts → chunk-FI2F5JBS.ts} +2 -2
  9. package/dist/chunks/{chunk-S6FUUWV5.ts → chunk-NDEZ52SS.ts} +13 -13
  10. package/dist/chunks/{chunk-S6FUUWV5.ts.map → chunk-NDEZ52SS.ts.map} +1 -1
  11. package/dist/chunks/{chunk-UGS6RYDZ.ts → chunk-RW44KNFD.ts} +304 -70
  12. package/dist/chunks/chunk-RW44KNFD.ts.map +7 -0
  13. package/dist/chunks/{chunk-EXDWEFIJ.ts → chunk-TJ7YNITN.ts} +5 -5
  14. package/dist/chunks/{chunk-HSCAFOT5.ts → chunk-TZMVSTAM.ts} +5 -5
  15. package/dist/chunks/{chunk-SXCH4Q5O.ts → chunk-VPSC7BXM.ts} +3 -3
  16. package/dist/chunks/chunk-YT6PDRMM.ts +282 -0
  17. package/dist/chunks/chunk-YT6PDRMM.ts.map +7 -0
  18. package/dist/chunks/{command-handler-VINMQ7ZM.ts → command-handler-N45GY7AV.ts} +39 -27
  19. package/dist/chunks/command-handler-N45GY7AV.ts.map +7 -0
  20. package/dist/chunks/{conflict-review-PCDFRIVB.ts → conflict-review-5E4M44BA.ts} +2 -2
  21. package/dist/chunks/{file-selection-KID23GAD.ts → file-selection-DDQN4LVD.ts} +9 -9
  22. package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts → manager-result-dispatcher-FKW55L7I.ts} +5 -5
  23. package/dist/chunks/{manager-ui-YHDECYKI.ts → manager-ui-EV23DPZQ.ts} +104 -77
  24. package/dist/chunks/manager-ui-EV23DPZQ.ts.map +7 -0
  25. package/dist/chunks/{merge-review-SGDLMVS4.ts → merge-review-6YSLSMGS.ts} +3 -2
  26. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts +59 -0
  27. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts.map +7 -0
  28. package/dist/chunks/{remote-selection-ui-GPITNEBF.ts → remote-selection-ui-N4NMWFT2.ts} +4 -4
  29. package/dist/chunks/{setup-switch-L54X5U5I.ts → setup-switch-HY7K3442.ts} +4 -4
  30. package/dist/chunks/{setup-wizard-YO4MCPUF.ts → setup-wizard-LEKDQ3HK.ts} +9 -9
  31. package/dist/chunks/{sync-inspection-H2WX5SUT.ts → sync-inspection-OS2LVOLV.ts} +5 -5
  32. package/dist/chunks/{sync-operations-2MZAYHL2.ts → sync-operations-D3MDJUQQ.ts} +2 -2
  33. package/dist/daemon/dist/cli.js +2 -0
  34. package/dist/daemon/dist/client-transport.js +66 -0
  35. package/dist/daemon/dist/client.js +116 -86
  36. package/dist/daemon/dist/consent.js +33 -11
  37. package/dist/daemon/dist/daemon-debug.js +33 -0
  38. package/dist/daemon/dist/daemon-recovery.js +75 -0
  39. package/dist/daemon/dist/engine/backends/git/git-backend.js +39 -12
  40. package/dist/daemon/dist/engine/backends/git/git-runner.js +6 -1
  41. package/dist/daemon/dist/engine/backends/git/git-storage.js +5 -9
  42. package/dist/daemon/dist/engine/backends/publication-encoding.js +19 -0
  43. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +10 -12
  44. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +15 -26
  45. package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +10 -0
  46. package/dist/daemon/dist/engine/debug-log.js +134 -0
  47. package/dist/daemon/dist/engine/ignore/ignore-initialization.js +50 -14
  48. package/dist/daemon/dist/engine/ignore/ignore-settings.js +11 -14
  49. package/dist/daemon/dist/engine/ignore/ignore-source.js +1 -1
  50. package/dist/daemon/dist/engine/paths.js +7 -1
  51. package/dist/daemon/dist/engine/settings/config-file.js +62 -17
  52. package/dist/daemon/dist/engine/settings/config.js +49 -14
  53. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +30 -8
  54. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +3 -1
  55. package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +32 -0
  56. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +34 -0
  57. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +50 -7
  58. package/dist/daemon/dist/engine/snapshot/snapshot.js +64 -25
  59. package/dist/daemon/dist/engine/state/lock.js +157 -17
  60. package/dist/daemon/dist/engine/sync/continuous-sync.js +35 -11
  61. package/dist/daemon/dist/engine/sync/initialization.js +2 -2
  62. package/dist/daemon/dist/engine/sync/local-fields.js +42 -19
  63. package/dist/daemon/dist/engine/sync/merged-sync.js +13 -10
  64. package/dist/daemon/dist/engine/sync/remote-snapshot.js +18 -3
  65. package/dist/daemon/dist/engine/sync/session-push.js +13 -4
  66. package/dist/daemon/dist/engine/sync/startup-bootstrap.js +105 -0
  67. package/dist/daemon/dist/engine/sync/startup-recovery-evidence.js +37 -0
  68. package/dist/daemon/dist/engine/sync/startup-timings.js +80 -8
  69. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +22 -4
  70. package/dist/daemon/dist/engine/sync/sync-inspection.js +4 -7
  71. package/dist/daemon/dist/engine/sync/sync-local.js +3 -1
  72. package/dist/daemon/dist/engine/sync/sync-mutations.js +13 -7
  73. package/dist/daemon/dist/engine/sync/sync-policy.js +9 -1
  74. package/dist/daemon/dist/engine/sync/sync-state.js +12 -4
  75. package/dist/daemon/dist/engine/ui/sync-format.js +23 -55
  76. package/dist/daemon/dist/engine/ui/transfer-review.js +3 -3
  77. package/dist/daemon/dist/engine-service.js +54 -10
  78. package/dist/daemon/dist/identity.js +36 -6
  79. package/dist/daemon/dist/index.js +2 -1
  80. package/dist/daemon/dist/monitor.js +20 -1
  81. package/dist/daemon/dist/paged-review.js +177 -0
  82. package/dist/daemon/dist/participant-ledger.js +149 -0
  83. package/dist/daemon/dist/protocol.js +4 -0
  84. package/dist/daemon/dist/server.js +268 -120
  85. package/dist/daemon/dist/service-host.js +29 -9
  86. package/dist/daemon/dist/state-wait-jobs.js +23 -0
  87. package/dist/daemon/dist/state-wait.js +34 -0
  88. package/dist/daemon/package.json +1 -1
  89. package/dist/index.ts +128 -48
  90. package/dist/index.ts.map +2 -2
  91. package/docs/continuous-sync-verification.md +2 -0
  92. package/docs/daemon-migration.md +30 -2
  93. package/docs/tui-contract.md +8 -2
  94. package/package.json +2 -2
  95. package/skills/configure-pi-sync/SKILL.md +119 -18
  96. package/skills/configure-pi-sync/references/configuration.md +88 -48
  97. package/src/commands/command-execution.ts +11 -3
  98. package/src/commands/command-handler.ts +10 -3
  99. package/src/commands/command.ts +3 -2
  100. package/src/daemon/client-debug.ts +45 -0
  101. package/src/daemon/ownership-recovery.ts +50 -0
  102. package/src/daemon/pi-client.ts +288 -63
  103. package/src/daemon/startup-bootstrap-client.ts +26 -0
  104. package/src/settings/config.ts +1 -0
  105. package/src/sync/automatic-sync.ts +61 -18
  106. package/src/sync/startup-check.ts +13 -5
  107. package/src/sync-extension.ts +46 -8
  108. package/src/ui/manager-state.ts +35 -24
  109. package/src/ui/manager-ui.ts +39 -18
  110. package/src/ui/merge-review.ts +75 -12
  111. package/src/ui/settings-ui.ts +2 -2
  112. package/src/ui/setup/webdav-ui.ts +1 -1
  113. package/src/ui/sync-confirmation.ts +81 -65
  114. package/src/ui/sync-setups-ui.ts +15 -12
  115. package/dist/chunks/chunk-27F5W7DX.ts.map +0 -7
  116. package/dist/chunks/chunk-GSQGBVKG.ts +0 -218
  117. package/dist/chunks/chunk-GSQGBVKG.ts.map +0 -7
  118. package/dist/chunks/chunk-HLCML3OW.ts.map +0 -7
  119. package/dist/chunks/chunk-UGS6RYDZ.ts.map +0 -7
  120. package/dist/chunks/command-handler-VINMQ7ZM.ts.map +0 -7
  121. package/dist/chunks/manager-ui-YHDECYKI.ts.map +0 -7
  122. /package/dist/chunks/{chunk-V76KCWHO.ts.map → chunk-F3VODLVQ.ts.map} +0 -0
  123. /package/dist/chunks/{chunk-VQ47JBLF.ts.map → chunk-FI2F5JBS.ts.map} +0 -0
  124. /package/dist/chunks/{chunk-EXDWEFIJ.ts.map → chunk-TJ7YNITN.ts.map} +0 -0
  125. /package/dist/chunks/{chunk-HSCAFOT5.ts.map → chunk-TZMVSTAM.ts.map} +0 -0
  126. /package/dist/chunks/{chunk-SXCH4Q5O.ts.map → chunk-VPSC7BXM.ts.map} +0 -0
  127. /package/dist/chunks/{conflict-review-PCDFRIVB.ts.map → conflict-review-5E4M44BA.ts.map} +0 -0
  128. /package/dist/chunks/{file-selection-KID23GAD.ts.map → file-selection-DDQN4LVD.ts.map} +0 -0
  129. /package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts.map → manager-result-dispatcher-FKW55L7I.ts.map} +0 -0
  130. /package/dist/chunks/{merge-review-SGDLMVS4.ts.map → merge-review-6YSLSMGS.ts.map} +0 -0
  131. /package/dist/chunks/{remote-selection-ui-GPITNEBF.ts.map → remote-selection-ui-N4NMWFT2.ts.map} +0 -0
  132. /package/dist/chunks/{setup-switch-L54X5U5I.ts.map → setup-switch-HY7K3442.ts.map} +0 -0
  133. /package/dist/chunks/{setup-wizard-YO4MCPUF.ts.map → setup-wizard-LEKDQ3HK.ts.map} +0 -0
  134. /package/dist/chunks/{sync-inspection-H2WX5SUT.ts.map → sync-inspection-OS2LVOLV.ts.map} +0 -0
  135. /package/dist/chunks/{sync-operations-2MZAYHL2.ts.map → sync-operations-D3MDJUQQ.ts.map} +0 -0
@@ -2,13 +2,13 @@
2
2
  // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
3
  import {
4
4
  showRemoteSelectionReview
5
- } from "./chunk-EXDWEFIJ.ts";
6
- import "./chunk-CKUGCBHP.ts";
5
+ } from "./chunk-TJ7YNITN.ts";
7
6
  import "./chunk-UMPA5S7X.ts";
7
+ import "./chunk-CKUGCBHP.ts";
8
8
  import "./chunk-NXWHPVXR.ts";
9
9
  import "./chunk-GELYN4UC.ts";
10
10
  import "./chunk-ZO52JM4H.ts";
11
- import "./chunk-27F5W7DX.ts";
11
+ import "./chunk-DAZZ5BEJ.ts";
12
12
  import "./chunk-H7VOTY5N.ts";
13
13
  import "./chunk-6YKOHBSC.ts";
14
14
  import "./chunk-R3SAMXB6.ts";
@@ -16,4 +16,4 @@ import "./chunk-2JNFEZ3V.ts";
16
16
  export {
17
17
  showRemoteSelectionReview
18
18
  };
19
- //# sourceMappingURL=remote-selection-ui-GPITNEBF.ts.map
19
+ //# sourceMappingURL=remote-selection-ui-N4NMWFT2.ts.map
@@ -6,12 +6,12 @@ import {
6
6
  setupSwitchActionFromLabel,
7
7
  setupSwitchActionLabel,
8
8
  useSyncSetup
9
- } from "./chunk-SXCH4Q5O.ts";
9
+ } from "./chunk-VPSC7BXM.ts";
10
10
  import "./chunk-APZVJAEW.ts";
11
11
  import "./chunk-WBIOSK76.ts";
12
- import "./chunk-HLCML3OW.ts";
12
+ import "./chunk-4VKWHVUO.ts";
13
13
  import "./chunk-GELYN4UC.ts";
14
- import "./chunk-27F5W7DX.ts";
14
+ import "./chunk-DAZZ5BEJ.ts";
15
15
  import {
16
16
  SetupPullRequiresUiError
17
17
  } from "./chunk-6YKOHBSC.ts";
@@ -24,4 +24,4 @@ export {
24
24
  setupSwitchActionLabel,
25
25
  useSyncSetup
26
26
  };
27
- //# sourceMappingURL=setup-switch-L54X5U5I.ts.map
27
+ //# sourceMappingURL=setup-switch-HY7K3442.ts.map
@@ -5,24 +5,24 @@ import {
5
5
  showGitSetup,
6
6
  showS3Setup,
7
7
  showWebDavSetup
8
- } from "./chunk-S6FUUWV5.ts";
8
+ } from "./chunk-NDEZ52SS.ts";
9
9
  import {
10
10
  validateConfigName
11
11
  } from "./chunk-APZVJAEW.ts";
12
12
  import "./chunk-MANNB4WZ.ts";
13
13
  import "./chunk-WBIOSK76.ts";
14
- import "./chunk-HLCML3OW.ts";
15
- import "./chunk-JREGWM2B.ts";
16
- import {
17
- localConfigPath
18
- } from "./chunk-IBXEM35O.ts";
19
- import "./chunk-UGS6RYDZ.ts";
20
- import "./chunk-CKUGCBHP.ts";
21
14
  import {
22
15
  throwIfAborted
23
16
  } from "./chunk-UMPA5S7X.ts";
17
+ import "./chunk-4VKWHVUO.ts";
18
+ import "./chunk-CKUGCBHP.ts";
19
+ import "./chunk-JREGWM2B.ts";
24
20
  import "./chunk-NXWHPVXR.ts";
25
21
  import "./chunk-GELYN4UC.ts";
22
+ import {
23
+ localConfigPath
24
+ } from "./chunk-IBXEM35O.ts";
25
+ import "./chunk-RW44KNFD.ts";
26
26
  import "./chunk-H7VOTY5N.ts";
27
27
  import {
28
28
  errorMessage
@@ -93,4 +93,4 @@ async function showSetupWizard(ctx, signal) {
93
93
  export {
94
94
  showSetupWizard
95
95
  };
96
- //# sourceMappingURL=setup-wizard-YO4MCPUF.ts.map
96
+ //# sourceMappingURL=setup-wizard-LEKDQ3HK.ts.map
@@ -1,11 +1,11 @@
1
1
  // @generated by scripts/build-runtime.mjs; do not edit.
2
2
  // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
- import {
4
- currentPiDaemonClient
5
- } from "./chunk-UGS6RYDZ.ts";
6
3
  import {
7
4
  syncCheckConfigFingerprint
8
- } from "./chunk-27F5W7DX.ts";
5
+ } from "./chunk-DAZZ5BEJ.ts";
6
+ import {
7
+ currentPiDaemonClient
8
+ } from "./chunk-RW44KNFD.ts";
9
9
  import "./chunk-H7VOTY5N.ts";
10
10
  import "./chunk-6YKOHBSC.ts";
11
11
  import "./chunk-R3SAMXB6.ts";
@@ -20,4 +20,4 @@ var inspectSync = async (config, _options, signal) => await currentPiDaemonClien
20
20
  export {
21
21
  inspectSync
22
22
  };
23
- //# sourceMappingURL=sync-inspection-H2WX5SUT.ts.map
23
+ //# sourceMappingURL=sync-inspection-OS2LVOLV.ts.map
@@ -2,7 +2,7 @@
2
2
  // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
3
  import {
4
4
  remoteOperation
5
- } from "./chunk-UGS6RYDZ.ts";
5
+ } from "./chunk-RW44KNFD.ts";
6
6
  import "./chunk-H7VOTY5N.ts";
7
7
  import "./chunk-6YKOHBSC.ts";
8
8
  import "./chunk-R3SAMXB6.ts";
@@ -46,4 +46,4 @@ export {
46
46
  status,
47
47
  syncBoth
48
48
  };
49
- //# sourceMappingURL=sync-operations-2MZAYHL2.ts.map
49
+ //# sourceMappingURL=sync-operations-D3MDJUQQ.ts.map
@@ -59,6 +59,7 @@ export async function main(args) {
59
59
  log = openLifecycleLog(paths.directory);
60
60
  }
61
61
  catch (error) {
62
+ server.recordBootOutcome("failed");
62
63
  await server.close();
63
64
  throw error;
64
65
  }
@@ -71,6 +72,7 @@ export async function main(args) {
71
72
  throw error;
72
73
  }
73
74
  note("ready");
75
+ server.recordBootOutcome("ready");
74
76
  let stopping;
75
77
  const stop = () => {
76
78
  stopping ??= server.close().catch(() => {
@@ -0,0 +1,66 @@
1
+ import { request as httpRequest } from "node:http";
2
+ import { lt, valid } from "semver";
3
+ import { DAEMON_BUILD_VERSION } from "./build-version.js";
4
+ import { daemonPaths, readJsonBody } from "./identity.js";
5
+ import { MAX_MESSAGE_BYTES, record } from "./protocol.js";
6
+ export class DaemonError extends Error {
7
+ remote;
8
+ constructor(remote) {
9
+ super(remote.message);
10
+ this.name = remote.name;
11
+ this.remote = remote;
12
+ }
13
+ }
14
+ export async function requestDaemon(paths, identity, method, params, signal, options) {
15
+ signal?.throwIfAborted();
16
+ const body = JSON.stringify({
17
+ version: 1,
18
+ root: paths.root,
19
+ instance: identity.instance,
20
+ token: identity.token,
21
+ method,
22
+ params,
23
+ ...(method === "attach" && options?.reviewDetails === 1 ? { reviewDetails: 1 } : {}),
24
+ });
25
+ if (Buffer.byteLength(body) > MAX_MESSAGE_BYTES)
26
+ throw new Error("Daemon request exceeds its byte limit.");
27
+ return new Promise((resolve, reject) => {
28
+ const request = httpRequest({
29
+ socketPath: daemonPaths(paths, identity.instance).endpoint,
30
+ path: "/v1",
31
+ method: "POST",
32
+ signal,
33
+ headers: { "content-type": "application/json", "content-length": Buffer.byteLength(body) },
34
+ }, (response) => {
35
+ void readJsonBody(response)
36
+ .then((value) => {
37
+ if (!record(value))
38
+ throw new Error("Invalid daemon response.");
39
+ if (record(value.error) && typeof value.error.message === "string")
40
+ throw new DaemonError(value.error);
41
+ if (response.statusCode !== 200 || !Object.hasOwn(value, "result"))
42
+ throw new Error("Invalid daemon response.");
43
+ resolve(value.result);
44
+ })
45
+ .catch(reject);
46
+ });
47
+ request.setTimeout(method === "attach" || method === "resume-contact" ? 0 : 30_000, () => request.destroy(new Error("Daemon request timed out.")));
48
+ request.once("error", reject);
49
+ if (options?.onSocket)
50
+ request.once("socket", options.onSocket);
51
+ request.end(body);
52
+ });
53
+ }
54
+ export async function hello(paths, identity, signal) {
55
+ const value = await requestDaemon(paths, identity, "hello", {}, signal);
56
+ if (!record(value) ||
57
+ value.version !== 1 ||
58
+ value.root !== paths.root ||
59
+ value.instance !== identity.instance ||
60
+ value.pid !== identity.pid)
61
+ throw new Error("Daemon handshake mismatch.");
62
+ const version = value.buildVersion;
63
+ if (Object.hasOwn(value, "buildVersion") && (typeof version !== "string" || valid(version) !== version))
64
+ throw new Error("Invalid daemon build version.");
65
+ return { needsUpgrade: typeof version !== "string" || lt(version, DAEMON_BUILD_VERSION) };
66
+ }
@@ -1,76 +1,16 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
- import { request as httpRequest } from "node:http";
4
3
  import { setTimeout as delay } from "node:timers/promises";
5
4
  import { fileURLToPath } from "node:url";
6
5
  import lockfile from "proper-lockfile";
7
- import { lt, valid } from "semver";
8
- import { DAEMON_BUILD_VERSION } from "./build-version.js";
9
- import { canonicalRootGuard, clearUpgradeOwner, daemonPaths, privateDirectory, processExists, processExited, readIdentity, readJsonBody, readProcessBirth, readUpgradeOwner, recordUpgradeOwner, runtimePaths, upgradeRepairStarted, } from "./identity.js";
6
+ import { DaemonError, hello, requestDaemon } from "./client-transport.js";
7
+ import { canonicalRootGuard, clearUpgradeOwner, daemonPaths, privateDirectory, processExists, processExited, readIdentity, readProcessBirth, readUpgradeOwner, recordUpgradeOwner, runtimePaths, upgradeRepairStarted, } from "./identity.js";
10
8
  import { withCleanup } from "./lifecycle.js";
11
- import { MAX_MESSAGE_BYTES, MAX_REVIEW_BYTES, operationPrefix, REVIEW_PAGE_CHARS, record, } from "./protocol.js";
12
- export class DaemonError extends Error {
13
- remote;
14
- constructor(remote) {
15
- super(remote.message);
16
- this.name = remote.name;
17
- this.remote = remote;
18
- }
19
- }
20
- export async function requestDaemon(paths, identity, method, params, signal) {
21
- signal?.throwIfAborted();
22
- const body = JSON.stringify({
23
- version: 1,
24
- root: paths.root,
25
- instance: identity.instance,
26
- token: identity.token,
27
- method,
28
- params,
29
- });
30
- if (Buffer.byteLength(body) > MAX_MESSAGE_BYTES)
31
- throw new Error("Daemon request exceeds its byte limit.");
32
- return new Promise((resolve, reject) => {
33
- const request = httpRequest({
34
- socketPath: daemonPaths(paths, identity.instance).endpoint,
35
- path: "/v1",
36
- method: "POST",
37
- signal,
38
- headers: { "content-type": "application/json", "content-length": Buffer.byteLength(body) },
39
- }, (response) => {
40
- void readJsonBody(response)
41
- .then((value) => {
42
- if (!record(value))
43
- throw new Error("Invalid daemon response.");
44
- if (record(value.error) && typeof value.error.message === "string")
45
- throw new DaemonError(value.error);
46
- if (response.statusCode !== 200 || !Object.hasOwn(value, "result"))
47
- throw new Error("Invalid daemon response.");
48
- resolve(value.result);
49
- })
50
- .catch(reject);
51
- });
52
- // Admission can wait behind a complete apply. The request owner's signal
53
- // cancels that wait; an idle timeout must not let admission escape the fence.
54
- request.setTimeout(method === "attach" || method === "resume-contact" ? 0 : 30_000, () => request.destroy(new Error("Daemon request timed out.")));
55
- request.once("error", reject);
56
- request.end(body);
57
- });
58
- }
59
- async function hello(paths, identity, signal) {
60
- const value = await requestDaemon(paths, identity, "hello", {}, signal);
61
- if (!record(value) ||
62
- value.version !== 1 ||
63
- value.root !== paths.root ||
64
- value.instance !== identity.instance ||
65
- value.pid !== identity.pid)
66
- throw new Error("Daemon handshake mismatch.");
67
- const version = value.buildVersion;
68
- if (Object.hasOwn(value, "buildVersion") && (typeof version !== "string" || valid(version) !== version))
69
- throw new Error("Invalid daemon build version.");
70
- // The old @narumitw/sync-daemon used the same wire protocol without a build version.
71
- return { needsUpgrade: typeof version !== "string" || lt(version, DAEMON_BUILD_VERSION) };
72
- }
73
- async function checkUpgradeConsent(paths, assertRoot, signal) {
9
+ import { presentPagedReview, reviewScope } from "./paged-review.js";
10
+ import { MAX_REVIEW_BYTES, OWNERSHIP_CLEANUP_REQUIRED, operationPrefix, REVIEW_PAGE_CHARS, record, UNKNOWN_JOB_RESULT, } from "./protocol.js";
11
+ import { STATE_WAIT_FAILURE_LIMIT, stateWaitJobs, stateWaitResult } from "./state-wait-jobs.js";
12
+ export { DaemonError, hello, requestDaemon } from "./client-transport.js";
13
+ export async function checkUpgradeConsent(paths, assertRoot, signal) {
74
14
  const { readConsent } = await import("./consent.js");
75
15
  const { withStateDirectoryGuardForRoot } = await import("./engine/state/state-directory.js");
76
16
  signal?.throwIfAborted();
@@ -80,15 +20,18 @@ async function checkUpgradeConsent(paths, assertRoot, signal) {
80
20
  // An older owner cannot report an in-memory revocation failure.
81
21
  const consent = readConsent(paths.root);
82
22
  if (consent && Object.values(consent.setups).some((setup) => setup.afterExit))
83
- throw new Error("Review or revoke unattended Pi Sync permission before restarting the older daemon.");
23
+ throw new Error("Review or revoke unattended Pi Sync permission before stopping or replacing the daemon.");
84
24
  });
85
25
  signal?.throwIfAborted();
86
26
  assertRoot();
87
27
  }
88
- async function finishUpgrade(paths, owner, assertRoot, signal) {
28
+ export async function finishUpgrade(paths, owner, assertRoot, signal) {
89
29
  await waitForProcessExit(owner, signal);
90
- if ((await readIdentity(paths))?.instance === owner.instance)
30
+ const current = await readIdentity(paths);
31
+ if (current?.instance === owner.instance)
91
32
  throw new Error("The daemon exited without releasing its identity.");
33
+ if (current && owner.purpose === "cleanup")
34
+ throw new Error("Daemon owner changed during recovery. Review the current owner before retrying.");
92
35
  await checkUpgradeConsent(paths, assertRoot, signal);
93
36
  await clearUpgradeOwner(paths);
94
37
  signal?.throwIfAborted();
@@ -160,6 +103,8 @@ export async function ensureDaemon(root, signal) {
160
103
  upgraded = true;
161
104
  continue;
162
105
  }
106
+ if (upgrade?.purpose === "cleanup")
107
+ throw Object.assign(new Error("Daemon recovery is incomplete. Use /sync daemon recover to finish the reviewed stop."), { code: OWNERSHIP_CLEANUP_REQUIRED });
163
108
  if (!existing)
164
109
  break;
165
110
  // A sample taken only after hello could describe an unrelated process reusing the PID.
@@ -347,6 +292,10 @@ export class DaemonConnection {
347
292
  resuming;
348
293
  resumeUncertain = false;
349
294
  pendingJobs = new Set();
295
+ observesState = false;
296
+ stateRevision;
297
+ terminalJobs = new Set();
298
+ jobWaiters = new Map();
350
299
  uncertain = false;
351
300
  reportedError = false;
352
301
  commits = new Map();
@@ -388,7 +337,7 @@ export class DaemonConnection {
388
337
  this.admitting = true;
389
338
  this.lifecycleRevision++;
390
339
  this.contactRevision++;
391
- const request = requestDaemon(this.paths, this.identity, "attach", this.facts, signal ? AbortSignal.any([signal, this.controller.signal]) : this.controller.signal);
340
+ const request = requestDaemon(this.paths, this.identity, "attach", this.facts, signal ? AbortSignal.any([signal, this.controller.signal]) : this.controller.signal, this.options.mergeReview ? { reviewDetails: 1 } : undefined);
392
341
  // Poll during attach: stopping a previous controller may need release answers
393
342
  // from this reattached participant before the attach response can complete.
394
343
  this.polling ??= this.poll();
@@ -397,6 +346,9 @@ export class DaemonConnection {
397
346
  const result = await request;
398
347
  admitted = true;
399
348
  this.publishContact(this.consume(result));
349
+ this.observesState = record(result) && result.stateWait === 1;
350
+ this.stateRevision = undefined;
351
+ this.terminalJobs.clear();
400
352
  this.attached = true;
401
353
  return this;
402
354
  }
@@ -519,7 +471,7 @@ export class DaemonConnection {
519
471
  sameClient(facts) {
520
472
  return facts.id === this.facts.id && facts.pid === this.facts.pid && facts.generation === this.facts.generation;
521
473
  }
522
- async run(operation, payload, signal, onCommit) {
474
+ async run(operation, payload, signal, onCommit, onSubmit) {
523
475
  if (this.closed ||
524
476
  this.uncertain ||
525
477
  this.contactResumeState !== "idle" ||
@@ -529,10 +481,13 @@ export class DaemonConnection {
529
481
  this.contactState === "inactive")
530
482
  throw new Error("Daemon client is unavailable; confirm contact and drain work before submitting.");
531
483
  signal?.throwIfAborted();
532
- const id = `${operationPrefix(this.identity)}${randomUUID()}`;
484
+ const { paths, identity } = this;
485
+ const id = `${operationPrefix(identity)}${randomUUID()}`;
486
+ const jobParams = { id, client: this.facts.id };
487
+ const transport = this.controller.signal;
533
488
  this.pendingJobs.add(id);
534
489
  const abort = () => {
535
- void requestDaemon(this.paths, this.identity, "cancel", { id, client: this.facts.id }, this.controller.signal).catch(() => { });
490
+ void requestDaemon(paths, identity, "cancel", jobParams, transport).catch(() => { });
536
491
  };
537
492
  let terminal = false;
538
493
  if (onCommit)
@@ -541,11 +496,37 @@ export class DaemonConnection {
541
496
  if (signal?.aborted)
542
497
  abort();
543
498
  return withCleanup(async () => {
544
- await requestDaemon(this.paths, this.identity, "submit", { id, client: this.facts.id, operation, payload }, this.controller.signal);
499
+ try {
500
+ onSubmit?.(id);
501
+ }
502
+ catch { }
503
+ await requestDaemon(paths, identity, "submit", { ...jobParams, operation, payload }, transport);
504
+ let terminalObserved = this.observesState;
505
+ if (terminalObserved && !this.terminalJobs.has(id)) {
506
+ const completion = Promise.withResolvers();
507
+ this.jobWaiters.set(id, completion);
508
+ const keepAlive = setInterval(() => { }, 30_000);
509
+ try {
510
+ terminalObserved = (await completion.promise) === "terminal";
511
+ }
512
+ finally {
513
+ this.jobWaiters.delete(id);
514
+ clearInterval(keepAlive);
515
+ }
516
+ }
545
517
  while (!this.closed) {
546
- const reply = await requestDaemon(this.paths, this.identity, "poll", { client: this.facts.id, cursor: this.cursor, job: id }, this.controller.signal);
547
- this.consume(reply);
518
+ const reply = await requestDaemon(paths, identity, "poll", { client: jobParams.client, cursor: this.cursor, job: id }, transport).catch((error) => {
519
+ if (error instanceof DaemonError && error.message === UNKNOWN_JOB_RESULT)
520
+ this.markWorkUncertain();
521
+ throw error;
522
+ });
548
523
  const job = record(reply) ? reply.job : undefined;
524
+ const missing = terminalObserved && (job?.id !== id || (job.phase !== "done" && job.phase !== "failed"));
525
+ if (missing)
526
+ this.markWorkUncertain();
527
+ this.consume(reply);
528
+ if (missing)
529
+ throw new Error(UNKNOWN_JOB_RESULT);
549
530
  if (job?.id === id && job.phase === "failed") {
550
531
  terminal = true;
551
532
  throw new DaemonError(job.error ?? { name: "Error", message: "Daemon operation failed." });
@@ -566,17 +547,22 @@ export class DaemonConnection {
566
547
  if (callback.job === id && !callback.kind.startsWith("queue-"))
567
548
  callback.controller.abort();
568
549
  try {
569
- await requestDaemon(this.paths, this.identity, "cancel", { id, client: this.facts.id });
550
+ await requestDaemon(paths, identity, "cancel", jobParams);
570
551
  }
571
552
  catch (error) {
572
- this.uncertain = true;
573
- for (const callback of this.callbacks.values())
574
- if (callback.kind !== "queue-release")
575
- callback.controller.abort();
553
+ this.markWorkUncertain();
576
554
  throw new Error("Operation outcome is uncertain; reload to reconnect and reconcile, never replay the write.", { cause: error });
577
555
  }
578
556
  }
579
- }).finally(() => this.pendingJobs.delete(id));
557
+ }).finally(() => {
558
+ this.pendingJobs.delete(id);
559
+ });
560
+ }
561
+ markWorkUncertain() {
562
+ this.uncertain = true;
563
+ for (const callback of this.callbacks.values())
564
+ if (callback.kind !== "queue-release")
565
+ callback.controller.abort();
580
566
  }
581
567
  publishContact(contact) {
582
568
  this.contactRevision++;
@@ -637,6 +623,7 @@ export class DaemonConnection {
637
623
  this.uncertain = true;
638
624
  const controller = new AbortController();
639
625
  const foreground = this.pendingJobs.has(callback.job);
626
+ const reviewGeneration = callback.review?.offer !== undefined ? this.facts.generation : undefined;
640
627
  this.callbacks.set(callback.id, {
641
628
  controller,
642
629
  kind: callback.kind,
@@ -665,7 +652,10 @@ export class DaemonConnection {
665
652
  await requestDaemon(this.paths, this.identity, "answer", {
666
653
  client: this.facts.id,
667
654
  id: callback.id,
668
- ...(failed ? { error: "Client callback cancelled or failed." } : { value }),
655
+ ...(reviewGeneration !== undefined ? { generation: reviewGeneration } : {}),
656
+ ...(failed || (reviewGeneration !== undefined && controller.signal.aborted)
657
+ ? { error: "Client callback cancelled or failed." }
658
+ : { value }),
669
659
  }, this.callbackIO.signal);
670
660
  }
671
661
  finally {
@@ -755,6 +745,11 @@ export class DaemonConnection {
755
745
  const reference = callback.review;
756
746
  if (!reference)
757
747
  return this.options.callback(callback, signal);
748
+ if (reference.offer !== undefined) {
749
+ if (!this.options.mergeReview)
750
+ throw new Error("Exact review offer requires an opted-in presenter.");
751
+ return presentPagedReview(reviewScope(this.identity, this.facts, callback), callback, AbortSignal.any([signal, this.callbackIO.signal]), this.options.mergeReview, (params, owned) => requestDaemon(this.paths, this.identity, "review-page", params, owned));
752
+ }
758
753
  if (callback.kind !== "merge-review" ||
759
754
  !record(callback.payload) ||
760
755
  !Number.isSafeInteger(reference.pages) ||
@@ -816,14 +811,44 @@ export class DaemonConnection {
816
811
  /* Error presentation must not own a task. */
817
812
  }
818
813
  }
814
+ async observeState() {
815
+ const jobs = stateWaitJobs(this.jobWaiters);
816
+ const reply = await requestDaemon(this.paths, this.identity, "state-wait", {
817
+ client: this.facts.id,
818
+ generation: this.facts.generation,
819
+ cursor: this.cursor,
820
+ revision: this.stateRevision,
821
+ jobs,
822
+ }, this.controller.signal, { onSocket: (socket) => socket.unref() });
823
+ return stateWaitResult(reply);
824
+ }
819
825
  async poll() {
826
+ await withCleanup(() => this.pollUntilClosed(), async () => {
827
+ for (const waiter of this.jobWaiters.values())
828
+ waiter.reject(this.controller.signal.reason ?? new Error("Daemon client closed."));
829
+ });
830
+ }
831
+ async pollUntilClosed() {
832
+ let failures = 0;
820
833
  while (!this.closed) {
821
834
  try {
822
835
  const revision = this.contactRevision;
823
- const reply = await requestDaemon(this.paths, this.identity, "poll", { client: this.facts.id, cursor: this.cursor }, this.controller.signal);
836
+ const state = this.observesState && !this.admitting ? await this.observeState() : undefined;
837
+ const reply = state?.reply ??
838
+ (await requestDaemon(this.paths, this.identity, "poll", { client: this.facts.id, cursor: this.cursor }, this.controller.signal));
824
839
  // An older poll must not undo typed update expiry or a successful resume.
825
840
  if (revision === this.contactRevision) {
841
+ if (state?.missing.some((id) => this.jobWaiters.has(id)))
842
+ this.markWorkUncertain();
826
843
  const contact = this.consume(reply);
844
+ if (state) {
845
+ this.stateRevision = state.version;
846
+ this.terminalJobs = new Set(state.finished);
847
+ for (const id of state.missing)
848
+ this.jobWaiters.get(id)?.reject(new Error(UNKNOWN_JOB_RESULT));
849
+ for (const id of state.finished)
850
+ this.jobWaiters.get(id)?.resolve("terminal");
851
+ }
827
852
  this.reportedError = false;
828
853
  if (revision === this.contactRevision &&
829
854
  this.attached &&
@@ -838,11 +863,16 @@ export class DaemonConnection {
838
863
  this.options.contact?.(contact);
839
864
  }
840
865
  }
841
- await this.wait(100);
866
+ failures = 0;
867
+ if (!state)
868
+ await this.wait(100);
842
869
  }
843
870
  catch (error) {
844
871
  if (this.closed)
845
872
  return;
873
+ if (++failures >= STATE_WAIT_FAILURE_LIMIT)
874
+ for (const waiter of this.jobWaiters.values())
875
+ waiter.resolve("poll");
846
876
  if (this.attached)
847
877
  this.reportError(error);
848
878
  try {
@@ -182,11 +182,15 @@ export function automaticPolicyAuthorized(root, config) {
182
182
  export async function reviewAutomaticPolicy(execution, config, expectedFingerprint) {
183
183
  if (consentFingerprint(execution.root, config) !== expectedFingerprint)
184
184
  throw new Error("Setup changed; reopen the automatic transfer review.");
185
- if (config.reservedIgnoreNames === undefined || automaticPolicyAuthorized(execution.root, config))
185
+ if (config.reservedIgnoreNames === undefined || automaticPolicyAuthorized(execution.root, config)) {
186
+ execution.noteDebugOutcome?.("skipped");
186
187
  return false;
188
+ }
187
189
  const consent = readConsent(execution.root);
188
- if (!consent)
190
+ if (!consent) {
191
+ execution.noteDebugOutcome?.("blocked");
189
192
  return false;
193
+ }
190
194
  const consentToken = JSON.stringify(consent);
191
195
  const peers = participantBinding(execution);
192
196
  const binding = JSON.stringify(execution.facts());
@@ -202,8 +206,10 @@ export async function reviewAutomaticPolicy(execution, config, expectedFingerpri
202
206
  };
203
207
  const current = await loadConfigForCheck(undefined, execution.signal);
204
208
  validate();
205
- if (syncCheckConfigFingerprint(current) !== fingerprint)
209
+ if (syncCheckConfigFingerprint(current) !== fingerprint) {
210
+ execution.noteDebugOutcome?.("blocked");
206
211
  return false;
212
+ }
207
213
  const modes = [
208
214
  startupTransferEnabled(config) && "Automatic transfer at startup",
209
215
  config.automatic &&
@@ -229,8 +235,10 @@ export async function reviewAutomaticPolicy(execution, config, expectedFingerpri
229
235
  ].join("\n"),
230
236
  });
231
237
  validate();
232
- if (accepted !== true)
238
+ if (accepted !== true) {
239
+ execution.noteDebugOutcome?.("cancelled");
233
240
  return false;
241
+ }
234
242
  const latest = await loadConfigForCheck(undefined, execution.signal);
235
243
  await config.validateIgnorePolicy?.();
236
244
  validate();
@@ -254,28 +262,38 @@ export async function reviewAutomaticPolicy(execution, config, expectedFingerpri
254
262
  }
255
263
  export async function captureAutomaticAuthorization(execution, expectedFingerprint) {
256
264
  const consent = readConsent(execution.root);
257
- if (!consent)
265
+ if (!consent) {
266
+ execution.noteDebugOutcome?.("blocked");
258
267
  throw new Error("Automatic work requires reviewed daemon handover first.");
268
+ }
259
269
  const consentToken = JSON.stringify(consent);
260
270
  const peers = participantBinding(execution);
261
271
  const { loadConfigForCheck } = await import("./engine/settings/config.js");
262
272
  const validateParticipants = () => {
263
273
  execution.validate();
264
- if (participantBinding(execution) !== peers || JSON.stringify(readConsent(execution.root)) !== consentToken)
274
+ if (participantBinding(execution) !== peers || JSON.stringify(readConsent(execution.root)) !== consentToken) {
275
+ execution.noteDebugOutcome?.("blocked");
265
276
  throw new Error("Daemon participants or consent changed before automatic work completed.");
277
+ }
266
278
  };
267
279
  validateParticipants();
268
280
  const config = await loadConfigForCheck(undefined, execution.signal);
269
281
  validateParticipants();
270
282
  const fingerprint = syncCheckConfigFingerprint(config);
271
- if (expectedFingerprint !== undefined ? fingerprint !== expectedFingerprint : config.reservedIgnoreNames !== undefined)
283
+ if (expectedFingerprint !== undefined ? fingerprint !== expectedFingerprint : config.reservedIgnoreNames !== undefined) {
284
+ execution.noteDebugOutcome?.("blocked");
272
285
  throw new Error("Settings changed before automatic work; use the reviewed foreground command.");
273
- if (!automaticPolicyAuthorized(execution.root, config))
286
+ }
287
+ if (!automaticPolicyAuthorized(execution.root, config)) {
288
+ execution.noteDebugOutcome?.("blocked");
274
289
  throw new Error("Automatic transfer requires separate approval for the current setup and policy. Run reviewed /sync first.");
290
+ }
275
291
  const validate = (current) => {
276
292
  validateParticipants();
277
- if (current && syncCheckConfigFingerprint(current) !== fingerprint)
293
+ if (current && syncCheckConfigFingerprint(current) !== fingerprint) {
294
+ execution.noteDebugOutcome?.("blocked");
278
295
  throw new Error("Settings changed before automatic work completed.");
296
+ }
279
297
  };
280
298
  const refresh = async () => {
281
299
  validate();
@@ -294,8 +312,10 @@ export async function requireHandover(execution) {
294
312
  message: "Close or upgrade every older Pi process before continuing. An idle older Pi cannot be detected from an absent sync lock. The daemon will own transfers; Pi keeps presentation and live file queues. Autonomous resolution uses independently available auth.json/models.json configuration and the environment captured when the service starts, not Pi runtime accounts or providers. Credential commands run non-interactively from the canonical agent root. Review this independent provider/account configuration; restart the service after changing its environment. This does not authorize transfers or model requests after the last Pi exits.",
295
313
  });
296
314
  execution.validate();
297
- if (accepted !== true)
315
+ if (accepted !== true) {
316
+ execution.noteDebugOutcome?.("cancelled");
298
317
  throw new Error("Daemon handover was not approved; no transfer was started.");
318
+ }
299
319
  const { withLock } = await import("./engine/state/lock.js");
300
320
  await withLock("daemon-handover", async () => {
301
321
  execution.validate();
@@ -347,8 +367,10 @@ export async function authorizeAfterExit(execution, payload) {
347
367
  message: `Setup: ${safeTerminalText(config.setupName)}\n${selection}\nModel: ${safeTerminalText(facts?.model?.provider ?? "unavailable")}/${safeTerminalText(facts?.model?.id ?? "unavailable")}\n\n${payload.afterExit ? `The daemon may transfer selected private content and send conflict evidence to this independently available provider after Pi exits. Existing budgets, exclusions, journals, and stale-evidence checks still apply. No parent conversation or tools are sent. Changing this setup or model invalidates this permission.${config.reservedIgnoreNames !== undefined ? " This also approves the enabled automatic modes for this setup while Pi clients are attached." : ""}` : "The daemon may remain alive, but no new transfer or model request may start with zero clients."}`,
348
368
  });
349
369
  execution.validate();
350
- if (accepted !== true)
370
+ if (accepted !== true) {
371
+ execution.noteDebugOutcome?.("cancelled");
351
372
  return undefined;
373
+ }
352
374
  const latest = await loadConfigForCheck(undefined, execution.signal);
353
375
  execution.validate();
354
376
  await config.validateIgnorePolicy?.();