@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
@@ -1,4 +1,68 @@
1
1
  import { performance } from "node:perf_hooks";
2
+ const startupStages = [
3
+ "daemon initialization",
4
+ "transaction recovery",
5
+ "settings read",
6
+ "config resolution",
7
+ "inspection import",
8
+ "inspection and guards",
9
+ "backend initialization",
10
+ "local snapshot",
11
+ "sync state read",
12
+ "remote head",
13
+ "operations import",
14
+ "automatic transfer",
15
+ "transfer authorization",
16
+ "transfer backend initialization",
17
+ "transfer journal read",
18
+ "transfer journal recovery",
19
+ "transfer state read",
20
+ "transfer local snapshot",
21
+ "transfer remote head",
22
+ "transfer snapshot download",
23
+ "transfer unchanged verification",
24
+ "transfer merge planning",
25
+ "transfer settings merge",
26
+ "transfer content merge",
27
+ "transfer preflight",
28
+ "transfer backup",
29
+ "transfer journal write",
30
+ "transfer remote publication",
31
+ "transfer local apply",
32
+ "transfer baseline write",
33
+ "transfer cleanup",
34
+ ];
35
+ const startupScopes = [
36
+ "local initialization",
37
+ "background startup",
38
+ "continuous startup",
39
+ "daemon inspection",
40
+ "daemon transfer",
41
+ ];
42
+ const outcomes = ["completed", "stopped"];
43
+ const unchangedLine = "transfer result: unchanged (fast path)";
44
+ const end = "(?![\\s\\S])";
45
+ const duration = "(?:0|[1-9][0-9]{0,15})\\.[0-9] ms";
46
+ const headingPattern = new RegExp(`^pi-sync debug: (?:${startupScopes.join("|")}) \\((?:${outcomes.join("|")})\\)${end}`, "u");
47
+ const stagePattern = new RegExp(`^(${startupStages.join("|")}): ${duration}(?: \\((?:[2-9]|[1-9][0-9]{1,15}) calls\\))?(?: \\(interrupted\\))?${end}`, "u");
48
+ const totalPattern = new RegExp(`^total: ${duration}${end}`, "u");
49
+ export function isStartupTimingReport(value) {
50
+ if (value.length > 4096)
51
+ return false;
52
+ const lines = value.split("\n");
53
+ if (!headingPattern.test(lines.shift() ?? "") || !totalPattern.test(lines.pop() ?? ""))
54
+ return false;
55
+ if (lines.at(-1) === unchangedLine)
56
+ lines.pop();
57
+ const seen = new Set();
58
+ for (const line of lines) {
59
+ const stage = stagePattern.exec(line)?.[1];
60
+ if (!stage || seen.has(stage))
61
+ return false;
62
+ seen.add(stage);
63
+ }
64
+ return true;
65
+ }
2
66
  /** Fixed labels and durations only: never retain errors, paths, settings, or payloads. */
3
67
  export function createStartupTimings(publishReport = (ctx, report) => ctx.ui.notify(report, "info")) {
4
68
  const started = performance.now();
@@ -8,6 +72,7 @@ export function createStartupTimings(publishReport = (ctx, report) => ctx.ui.not
8
72
  markUnchanged() {
9
73
  unchanged = true;
10
74
  },
75
+ wasUnchanged: () => unchanged,
11
76
  async measure(stage, run) {
12
77
  const start = performance.now();
13
78
  let completed = false;
@@ -25,16 +90,23 @@ export function createStartupTimings(publishReport = (ctx, report) => ctx.ui.not
25
90
  });
26
91
  }
27
92
  },
28
- publish(ctx, enabled, sessionSignal, scope, outcome = "completed") {
29
- if (!enabled || !ctx.hasUI || sessionSignal.aborted)
93
+ publish(ctx, enabled, sessionSignal, scope, outcome = "completed", observe) {
94
+ const display = enabled && ctx.hasUI && !sessionSignal.aborted;
95
+ if (!display && !observe)
30
96
  return;
97
+ const report = [
98
+ `pi-sync debug: ${scope} (${outcome})`,
99
+ ...Array.from(stages, ([stage, value]) => `${stage}: ${value.ms.toFixed(1)} ms${value.calls > 1 ? ` (${value.calls} calls)` : ""}${value.interrupted ? " (interrupted)" : ""}`),
100
+ ...(unchanged ? [unchangedLine] : []),
101
+ `total: ${(performance.now() - started).toFixed(1)} ms`,
102
+ ].join("\n");
103
+ try {
104
+ observe?.(report);
105
+ }
106
+ catch { }
31
107
  try {
32
- publishReport(ctx, [
33
- `pi-sync debug: ${scope} (${outcome})`,
34
- ...Array.from(stages, ([stage, value]) => `${stage}: ${value.ms.toFixed(1)} ms${value.calls > 1 ? ` (${value.calls} calls)` : ""}${value.interrupted ? " (interrupted)" : ""}`),
35
- ...(unchanged ? ["transfer result: unchanged (fast path)"] : []),
36
- `total: ${(performance.now() - started).toFixed(1)} ms`,
37
- ].join("\n"));
108
+ if (display)
109
+ publishReport(ctx, report);
38
110
  }
39
111
  catch {
40
112
  // Diagnostics must not change sync behavior if the UI is unavailable during teardown.
@@ -1,3 +1,4 @@
1
+ import { OWNERSHIP_CLEANUP_REQUIRED } from "../../protocol.js";
1
2
  import { errorMessage } from "./sync-errors.js";
2
3
  /** Add recovery advice without changing backend outcome semantics or printing error causes. */
3
4
  export function syncErrorGuidance(error) {
@@ -6,7 +7,11 @@ export function syncErrorGuidance(error) {
6
7
  const code = error?.code;
7
8
  const status = error?.status;
8
9
  let next;
9
- if (code === "ENOSPC") {
10
+ if (code === OWNERSHIP_CLEANUP_REQUIRED) {
11
+ next =
12
+ "Open /sync and choose Stop daemon for recovery, or run /sync daemon recover. Do not retry the transfer yet.";
13
+ }
14
+ else if (code === "ENOSPC") {
10
15
  next = "Free disk space for the private pi-sync settings/state directory, then retry.";
11
16
  }
12
17
  else if (code && ["EACCES", "EPERM", "EROFS"].includes(code)) {
@@ -15,20 +20,33 @@ export function syncErrorGuidance(error) {
15
20
  else if (code && ["EBUSY", "EIO", "EMFILE", "ENFILE"].includes(code)) {
16
21
  next = "Check local disk availability and other processes using the private settings file, then retry.";
17
22
  }
23
+ else if (/\bagent directory exceeds the scan entry bound\b/iu.test(message)) {
24
+ next =
25
+ "Reduce the number of entries Pi Sync must scan before retrying. Exclude whole subdirectories to skip their contents. Use /sync config to review the active scope.";
26
+ }
27
+ else if (/\bprojected agent directory exceeds the (64 MiB scan byte|scan file) bound\b/iu.test(message)) {
28
+ next =
29
+ "The resulting files would exceed the sync limit. Review the current scope with /sync config and reduce the local or incoming sync content before retrying.";
30
+ }
31
+ else if (/\bagent directory exceeds the (64 MiB scan byte|scan file) bound\b/iu.test(message)) {
32
+ next =
33
+ "Reduce the files managed by this setup before retrying. Use /sync config to find the active ignore file, or edit Agent directory scope in /sync → Settings for legacy rules.";
34
+ }
18
35
  else if (/changed while|type changed|reopen/iu.test(message)) {
19
36
  next = "Reopen the item in /sync and review its current settings before saving again.";
20
37
  }
21
38
  else if (status === 401 ||
22
39
  status === 403 ||
23
40
  /Permission denied|Authentication failed|HTTP (401|403)|failed \((401|403)\)/iu.test(message)) {
24
- next = "Check the storage connection's credentials and remote permissions in /sync → More → Storage connections.";
41
+ next =
42
+ "Check the storage connection's credentials and remote permissions. In the TUI, open /sync → Settings → Manage storage connections.";
25
43
  }
26
44
  else if (status === 404 || /HTTP 404|failed \(404\)/iu.test(message)) {
27
45
  next =
28
46
  "Verify the connection address and setup's bucket, branch, or path with your provider; this response alone does not prove which resource is missing.";
29
47
  }
30
48
  else if (status !== undefined && status >= 500) {
31
- next = "Check your storage provider's service status, then retry Check setup before syncing.";
49
+ next = "Check your storage provider's service status, then run /sync doctor before syncing.";
32
50
  }
33
51
  else if (/timed out|timeout|request failed|resolve host|Could not resolve|ENOTFOUND|ECONNREFUSED/iu.test(message)) {
34
52
  next = "Check the server address and network connection, then run /sync doctor for the affected setup.";
@@ -49,7 +67,7 @@ export function syncErrorGuidance(error) {
49
67
  "Correct the named field or item in /sync. If the settings file is invalid, repair it before retrying; do not replace it with defaults.";
50
68
  }
51
69
  else {
52
- next = "Open /sync → More → Check setup and review the reported checks before retrying.";
70
+ next = "For setup and storage checks, run /sync doctor or choose Diagnostics in /sync.";
53
71
  }
54
72
  return `${message}\n${next}`;
55
73
  }
@@ -1,18 +1,17 @@
1
- import { createHash } from "node:crypto";
2
1
  import { createSyncBackend } from "../backends/backend-factory.js";
3
- import { createSnapshot } from "../snapshot/snapshot.js";
2
+ import { observeSnapshot } from "../snapshot/snapshot.js";
4
3
  import { readStateForConfig, syncStateFingerprint } from "../state/sync-state-store.js";
5
4
  import { inspectHeadSelection } from "./remote-snapshot.js";
6
5
  import { throwIfAborted } from "./signals.js";
7
6
  import { createStartupTimings } from "./startup-timings.js";
8
7
  import { syncSelectionHasContent } from "./sync-policy.js";
9
- import { fileHashMap, hasLocalChanges, remoteChangedSinceState } from "./sync-state.js";
8
+ import { hasLocalChanges, rawSnapshotHashIdentity, remoteChangedSinceState } from "./sync-state.js";
10
9
  /** Advisory baseline-relative observation, never an authorization to transfer files. */
11
10
  export async function inspectSync(config, options, signal, factory = createSyncBackend, timings = createStartupTimings()) {
12
11
  throwIfAborted(signal);
13
12
  const backend = await timings.measure("backend initialization", () => factory(config));
14
13
  throwIfAborted(signal);
15
- const local = await timings.measure("local snapshot", () => createSnapshot(config.snapshotIdentity, { ...options, signal }));
14
+ const local = await timings.measure("local snapshot", () => observeSnapshot({ ...options, signal }, Boolean(config.localFields?.length)));
16
15
  throwIfAborted(signal);
17
16
  const state = await timings.measure("sync state read", () => readStateForConfig(config));
18
17
  throwIfAborted(signal);
@@ -21,9 +20,7 @@ export async function inspectSync(config, options, signal, factory = createSyncB
21
20
  const selectionState = head ? await inspectHeadSelection(backend, config, head, signal) : undefined;
22
21
  throwIfAborted(signal);
23
22
  const freshness = {
24
- localIdentity: createHash("sha256")
25
- .update(JSON.stringify(fileHashMap(local)))
26
- .digest("hex"),
23
+ localIdentity: rawSnapshotHashIdentity(local),
27
24
  };
28
25
  return {
29
26
  ...freshness,
@@ -19,7 +19,9 @@ export function protectedSessionPaths(ctx, sessionRoot = sessionDirFromContext(c
19
19
  export { captureMutationOwner } from "./mutation-owner.js";
20
20
  export async function backupLocal(profile, options = {}, signal) {
21
21
  throwIfAborted(signal);
22
- const snapshot = await createSnapshot(profile, { ...options, signal });
22
+ return backupSnapshot(await createSnapshot(profile, { ...options, signal }), signal);
23
+ }
24
+ export async function backupSnapshot(snapshot, signal) {
23
25
  throwIfAborted(signal);
24
26
  const backupDirectory = path.join(stateDir(), "backups");
25
27
  await fs.mkdir(backupDirectory, { recursive: true, mode: 0o700 });
@@ -7,7 +7,7 @@ import { applySnapshot } from "../snapshot/snapshot-apply.js";
7
7
  import { ignorePolicyValidator } from "../snapshot/snapshot-transaction-policy.js";
8
8
  import { pruneMergeBaselines } from "../state/merge-baseline-store.js";
9
9
  import { readStateForConfig, syncStateFingerprint, writeStateForConfig } from "../state/sync-state-store.js";
10
- import { countPreservedRemoteFiles, formatPublicationPreview, formatPullSummary, formatPushSummary, formatRollbackSummary, } from "../ui/sync-format.js";
10
+ import { countPreservedRemoteFiles, formatPublicationPreview, formatPullSummary, formatPushSummary, formatRollbackSummary, formatTransferReview, } from "../ui/sync-format.js";
11
11
  import { setSyncStatus } from "../ui/sync-status.js";
12
12
  import { confirmTransferReview } from "../ui/transfer-review.js";
13
13
  import { startupTransferEnabled } from "./agent-policy.js";
@@ -422,6 +422,7 @@ export async function syncBoth(ctx, options, factory = createSyncBackend) {
422
422
  if (!options.auto && syncSelectionHasContent(config) && state.lastAppliedSnapshot)
423
423
  return mergeSync(ctx, options, factory);
424
424
  if (!syncSelectionHasContent(config)) {
425
+ options.noteDebugOutcome?.("skipped");
425
426
  if (!options.silent) {
426
427
  ctx.ui.notify(`Sync setup “${config.setupName}” includes no files. Choose included content in /sync Settings before syncing.`, "warning");
427
428
  }
@@ -512,7 +513,8 @@ export async function syncBoth(ctx, options, factory = createSyncBackend) {
512
513
  directMessage: "Remote settings match, but local and remote Pi sessions differ. Run /sync diff, then manually choose /sync pull or /sync push.",
513
514
  });
514
515
  }
515
- await pullInitialSource();
516
+ if ((await pullInitialSource()) === "cancelled")
517
+ options.noteDebugOutcome?.("cancelled");
516
518
  return;
517
519
  }
518
520
  await acceptMatchingState(remote);
@@ -531,16 +533,20 @@ export async function syncBoth(ctx, options, factory = createSyncBackend) {
531
533
  return;
532
534
  }
533
535
  if (remoteChanged) {
534
- await pullInitialSource();
536
+ if ((await pullInitialSource()) === "cancelled")
537
+ options.noteDebugOutcome?.("cancelled");
535
538
  return;
536
539
  }
537
540
  if (localChanged || !remote) {
538
- await push(ctx, options, { config, state, local, backend }, factory);
541
+ if ((await push(ctx, options, { config, state, local, backend }, factory)) === "cancelled")
542
+ options.noteDebugOutcome?.("cancelled");
539
543
  return;
540
544
  }
541
545
  if (shouldRefreshSyncedState(remote, head, state, config, (left, right) => backend.sameRevision(left, right))) {
542
546
  await acceptMatchingState(remote);
543
547
  }
548
+ else
549
+ options.noteDebugOutcome?.("skipped");
544
550
  if (!options.silent)
545
551
  ctx.ui.notify("pi-sync is already up to date.", "info");
546
552
  }
@@ -605,8 +611,8 @@ export async function rollback(ctx, options, factory = createSyncBackend, expect
605
611
  const title = snapshotIncludesSessions(remote) ? "Rollback pi settings and sessions?" : "Rollback pi settings?";
606
612
  const summary = formatRollbackSummary(config, backend.destination, local, physical, target, reviewedProtectedPaths, caseCleanup.map((item) => item.path));
607
613
  const confirmed = config.ignorePolicy
608
- ? await confirmTransferReview(ctx, title, `Historical files are projected through this device's current ignore rules. Historical rules are not adopted. Retained history is not erased.\n\n${summary}\n\nRemote publication:\n${formatPublicationPreview(currentRemote, upload)}`, options.signal, validateMutation)
609
- : await ctx.ui.confirm(title, summary, { signal: options.signal });
614
+ ? await confirmTransferReview(ctx, title, formatTransferReview("Historical files are projected through this device's current ignore rules. Historical rules are not adopted. Retained history is not erased.", "", summary, "", "Remote publication:", formatPublicationPreview(currentRemote, upload)), options.signal, validateMutation)
615
+ : await ctx.ui.confirm(title, summary.content, { signal: options.signal });
610
616
  validateMutation();
611
617
  if (!confirmed) {
612
618
  ctx.ui.notify("Rollback cancelled.", "info");
@@ -739,7 +745,7 @@ async function confirmPush(ctx, options, config, backend, local, upload, head, r
739
745
  ? inspectRemoteSelection(config.include, remote, config.exclude, config).ignorePolicyComparison
740
746
  : undefined;
741
747
  const confirmed = await confirmTransferReview(ctx, title, comparison && comparison !== "match"
742
- ? `${formatIgnorePolicyComparison(comparison)}\nOnly files selected by this device's rules are published. Remote rules are not adopted.\n\n${summary}`
748
+ ? formatTransferReview(formatIgnorePolicyComparison(comparison), "Only files selected by this device's rules are published. Remote rules are not adopted.", "", summary)
743
749
  : summary, options.signal, validateMutation);
744
750
  throwIfAborted(options.signal);
745
751
  if (confirmed)
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import path from "node:path";
3
- import { isDeniedPath, toPosix } from "../paths.js";
3
+ import { DEBUG_LOG_FILENAME, isDebugLogPath, isDeniedPath, toPosix } from "../paths.js";
4
4
  import { IGNORE_SNAPSHOT_VERSION, } from "../snapshot/snapshot-types.js";
5
5
  import { compilePathRules, compileSyncExclude, normalizeSyncExclude, sameSyncExclude } from "./exclude-policy.js";
6
6
  export const BUILT_IN_SYNC_ROOTS = [
@@ -202,6 +202,14 @@ export function validateSnapshotSelection(snapshot) {
202
202
  if ((snapshot.version === IGNORE_SNAPSHOT_VERSION) !== (selection?.version === 4))
203
203
  throw new Error("Ignore-file policy requires snapshot version 6 and selection version 4.");
204
204
  }
205
+ export function assertSnapshotPathExcludesDebugLog(filePath) {
206
+ if (typeof filePath === "string" && isDebugLogPath(filePath))
207
+ throw new Error(`Snapshot contains the local-only ${DEBUG_LOG_FILENAME}. Review the old snapshot before retrying sync.`);
208
+ }
209
+ export function assertSnapshotExcludesDebugLog(snapshot) {
210
+ for (const file of snapshot.files)
211
+ assertSnapshotPathExcludesDebugLog(file?.path);
212
+ }
205
213
  export function requireLegacyTransferPolicy(snapshot) {
206
214
  if (snapshot.version === IGNORE_SNAPSHOT_VERSION || snapshot.selection?.version === 4)
207
215
  throw new Error("This setup cannot transfer an ignore-file snapshot without a reviewed local ignore policy.");
@@ -1,14 +1,17 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { toPosix } from "../paths.js";
2
3
  import { canonicalSnapshotPathForConfig, filterSnapshotForConfigPolicy, isSessionPath } from "../snapshot/snapshot.js";
3
4
  import { sameSyncExclude } from "./exclude-policy.js";
4
- import { portableSnapshot, sameLocalFields } from "./local-fields.js";
5
+ import { portableObservation, portableSnapshot, sameLocalFields } from "./local-fields.js";
5
6
  import { compareIgnorePolicy, configuredSnapshotPathMatcher, customIncludePathsByLower, includeFromSelectionConfig, localIgnorePolicyKey, normalizeSyncInclude, syncDirectoryPolicyKey, syncSessionsSelected, } from "./sync-policy.js";
6
7
  export function hasLocalChanges(local, state, config) {
7
- return ((Boolean(state.lastAppliedSnapshot) &&
8
+ if (state.lastAppliedSnapshot &&
8
9
  (state.scope !== config.scope ||
9
10
  !sameLocalFields(state.localFields, config.localFields) ||
10
- !sameSelectionRules(state, config))) ||
11
- !sameHashes(fileHashMap(portableSnapshot(local, config.localFields)), stateHashMapForConfig(state, config)));
11
+ !sameSelectionRules(state, config)))
12
+ return true;
13
+ const portable = "version" in local ? portableSnapshot(local, config.localFields) : portableObservation(local, config.localFields);
14
+ return !sameHashes(fileHashMap(portable), stateHashMapForConfig(state, config));
12
15
  }
13
16
  export function remoteChangedSinceState(head, state, config, sameRevision) {
14
17
  if (!head)
@@ -46,6 +49,11 @@ export function sameHashes(left, right) {
46
49
  export function fileHashMap(snapshot) {
47
50
  return Object.fromEntries(snapshot.files.map((file) => [file.path, file.sha256]));
48
51
  }
52
+ export function rawSnapshotHashIdentity(snapshot) {
53
+ return createHash("sha256")
54
+ .update(JSON.stringify(fileHashMap(snapshot)))
55
+ .digest("hex");
56
+ }
49
57
  function stateHashMapForConfig(state, config) {
50
58
  const includePaths = customIncludePathsByLower(includeFromSelectionConfig(config));
51
59
  const configured = configuredSnapshotPathMatcher(config);
@@ -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,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,5 +1,7 @@
1
1
  import { authorizeAfterExit, automaticPolicyAuthorized, captureAutomaticAuthorization, consentFingerprint, readConsent, requireHandover, reviewAutomaticPolicy, revokeAfterExitGrants, } from "./consent.js";
2
+ import { createDaemonDebug } from "./daemon-debug.js";
2
3
  import { documentFingerprint } from "./document.js";
4
+ import { captureStartupReviewLock } from "./engine/state/lock.js";
3
5
  import { createMonitor } from "./monitor.js";
4
6
  import { MAX_SETTINGS_BYTES, record } from "./protocol.js";
5
7
  import { createServiceContext, installServiceHost } from "./service-host.js";
@@ -37,6 +39,7 @@ function optionsFrom(value, execution, automatic) {
37
39
  ...(typeof value.automaticFingerprint === "string" ? { automaticFingerprint: value.automaticFingerprint } : {}),
38
40
  signal: execution.signal,
39
41
  onCommit: execution.committed,
42
+ noteDebugOutcome: execution.noteDebugOutcome,
40
43
  };
41
44
  }
42
45
  /** Engine dispatch is loaded only by the service, never by the public IPC client. */
@@ -248,18 +251,24 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
248
251
  const { syncSessionsSelected } = await import("./engine/sync/sync-policy.js");
249
252
  const config = await loadConfigForCheck(undefined, execution.signal);
250
253
  execution.validate();
251
- if (!config.automatic || !syncSessionsSelected(config))
254
+ if (!config.automatic || !syncSessionsSelected(config)) {
255
+ execution.noteDebugOutcome?.("skipped");
252
256
  return;
257
+ }
253
258
  }
254
- if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode))
259
+ if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) {
260
+ execution.noteDebugOutcome?.("blocked");
255
261
  throw new Error("Synchronization requires an observable TUI or RPC client.");
262
+ }
256
263
  const { withStateDirectoryAccess, migrateLegacyStateDirectory } = await import("./engine/state/state-directory.js");
257
264
  if (operation === "migrate-state") {
258
265
  if (!options.yes) {
259
266
  const accepted = await ctx.ui.confirm("Migrate pi-sync state directory", "Confirm that every older Pi process is closed. Preserve both roots and pending journals on failure.", { signal: execution.signal });
260
267
  execution.validate();
261
- if (!accepted)
268
+ if (!accepted) {
269
+ execution.noteDebugOutcome?.("cancelled");
262
270
  return { status: "cancelled", message: "pi-sync state migration cancelled." };
271
+ }
263
272
  }
264
273
  execution.validate();
265
274
  const result = await migrateLegacyStateDirectory();
@@ -294,8 +303,10 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
294
303
  }
295
304
  if (operation === "startup-transfer") {
296
305
  const { startupTransferEnabled } = await import("./engine/sync/agent-policy.js");
297
- if (!automatic || !startupTransferEnabled(automatic.config) || !ctx.isIdle())
306
+ if (!automatic || !startupTransferEnabled(automatic.config) || !ctx.isIdle()) {
307
+ execution.noteDebugOutcome?.("blocked");
298
308
  throw new Error("Startup transfer is no longer authorized or idle.");
309
+ }
299
310
  options.auto = true;
300
311
  options.yes = true;
301
312
  options.silent = true;
@@ -310,6 +321,7 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
310
321
  automatic?.validate(config);
311
322
  execution.validate();
312
323
  if (config.agentMode && !automaticPolicyAuthorized(root, config)) {
324
+ execution.noteDebugOutcome?.("blocked");
313
325
  throw new Error("Autonomous sync requires a separate policy review. Use Settings → Review automatic transfers, or choose a reviewed push or pull.");
314
326
  }
315
327
  if (operation === "sync" && !options.agentRetryRefusal)
@@ -360,8 +372,10 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
360
372
  execution.participants().some((peer) => peer.ready !== true) ||
361
373
  inspection.firstSync ||
362
374
  !inspection.head ||
363
- inspection.selectionState?.kind !== "same")
375
+ inspection.selectionState?.kind !== "same") {
376
+ execution.noteDebugOutcome?.("blocked");
364
377
  throw new Error("Startup transfer requires a fresh initialized baseline, matching selection, and idle ready clients; use the reviewed foreground command.");
378
+ }
365
379
  }
366
380
  return operations.syncBoth(ctx, current);
367
381
  });
@@ -371,9 +385,12 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
371
385
  }
372
386
  };
373
387
  return operation === "startup-transfer"
374
- ? withJobTimings(ctx, execution, "daemon transfer", (timings) => {
388
+ ? withJobTimings(ctx, execution, "daemon transfer", async (timings) => {
375
389
  options.startupTimings = timings;
376
- return run();
390
+ const result = await run();
391
+ if (timings.wasUnchanged())
392
+ execution.noteDebugOutcome?.("skipped");
393
+ return result;
377
394
  })
378
395
  : run();
379
396
  }
@@ -388,10 +405,18 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
388
405
  execute,
389
406
  bind: monitor.bind,
390
407
  hooks: {
408
+ diagnostic: createDaemonDebug(root),
409
+ startup: {
410
+ captureReviewLock: captureStartupReviewLock,
411
+ async probe(fingerprint, signal, reviewLock) {
412
+ const { captureStartupBootstrap } = await import("./engine/sync/startup-bootstrap.js");
413
+ return captureStartupBootstrap(root, fingerprint, signal, reviewLock);
414
+ },
415
+ },
391
416
  factsChanged: monitor.factsChanged,
392
417
  idle: monitor.schedule,
393
418
  close: monitor.close,
394
- lifetime: monitor.lifetime,
419
+ lifetime: () => (host.cleanupRequired() ? Promise.resolve("pause") : monitor.lifetime()),
395
420
  quiesce: monitor.pause,
396
421
  failure: monitor.blockAutomatic,
397
422
  },
@@ -407,9 +432,17 @@ async function withJobTimings(ctx, execution, label, action) {
407
432
  return result;
408
433
  }
409
434
  finally {
410
- timings.publish(ctx, execution.facts()?.startupDebug ?? false, execution.signal, label, completed ? "completed" : "stopped");
435
+ timings.publish(ctx, execution.facts()?.startupDebug ?? false, execution.signal, label, completed ? "completed" : "stopped", timingObserver(execution));
411
436
  }
412
437
  }
438
+ async function requireStartupRecoveryCleared(execution) {
439
+ const { pendingTransactionEntries } = await import("./engine/snapshot/snapshot-transaction-directory.js");
440
+ execution.validate();
441
+ const pending = await pendingTransactionEntries();
442
+ execution.validate();
443
+ if (pending.length)
444
+ throw new Error("Pi Sync startup cannot confirm recovery is clear. Preserve recovery files and check /sync doctor before retrying.");
445
+ }
413
446
  async function initialize(ctx, execution, diagnostics = true) {
414
447
  const { pendingTransactionEntries } = await import("./engine/snapshot/snapshot-transaction-directory.js");
415
448
  const pending = await pendingTransactionEntries();
@@ -430,12 +463,23 @@ async function initialize(ctx, execution, diagnostics = true) {
430
463
  execution.validate();
431
464
  const settings = document ? validateSettingsDocument(document.parsed) : undefined;
432
465
  const config = settings?.activeSyncSetup ? configFromSettings(settings) : undefined;
466
+ if (diagnostics)
467
+ await requireStartupRecoveryCleared(execution);
468
+ execution.noteDebugOutcome?.("blocked");
433
469
  return { debug: settings?.debug ?? false, settings, config, handoverRequired: true };
434
470
  }
435
471
  const { initializeSync } = await import("./engine/sync/initialization.js");
436
472
  const initialized = await initializeSync(ctx, execution.signal, (_ctx, report) => {
437
473
  if (diagnostics)
438
474
  execution.emit("timings", { report });
439
- });
475
+ }, diagnostics ? timingObserver(execution) : undefined);
476
+ execution.validate();
477
+ if (diagnostics)
478
+ await requireStartupRecoveryCleared(execution);
479
+ execution.validate();
440
480
  return { ...initialized, handoverRequired: !readConsent(execution.root) };
441
481
  }
482
+ function timingObserver(execution) {
483
+ const debug = execution.debug;
484
+ return debug ? (report) => debug({ event: "startup-timings", report }) : undefined;
485
+ }