@narumitw/pi-sync 0.63.1 → 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 (127) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +12 -5
  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-LBNC5AOM.ts → chunk-NDEZ52SS.ts} +12 -12
  10. package/dist/chunks/{chunk-B5F3JLD3.ts → chunk-RW44KNFD.ts} +304 -70
  11. package/dist/chunks/chunk-RW44KNFD.ts.map +7 -0
  12. package/dist/chunks/{chunk-EXDWEFIJ.ts → chunk-TJ7YNITN.ts} +5 -5
  13. package/dist/chunks/{chunk-HSCAFOT5.ts → chunk-TZMVSTAM.ts} +5 -5
  14. package/dist/chunks/{chunk-SXCH4Q5O.ts → chunk-VPSC7BXM.ts} +3 -3
  15. package/dist/chunks/{chunk-POWOMJ7S.ts → chunk-YT6PDRMM.ts} +58 -31
  16. package/dist/chunks/chunk-YT6PDRMM.ts.map +7 -0
  17. package/dist/chunks/{command-handler-GMRRFWOL.ts → command-handler-N45GY7AV.ts} +39 -27
  18. package/dist/chunks/command-handler-N45GY7AV.ts.map +7 -0
  19. package/dist/chunks/{conflict-review-JWEA7DPQ.ts → conflict-review-5E4M44BA.ts} +2 -2
  20. package/dist/chunks/{file-selection-KID23GAD.ts → file-selection-DDQN4LVD.ts} +9 -9
  21. package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts → manager-result-dispatcher-FKW55L7I.ts} +5 -5
  22. package/dist/chunks/{manager-ui-T5J5WG7T.ts → manager-ui-EV23DPZQ.ts} +75 -57
  23. package/dist/chunks/manager-ui-EV23DPZQ.ts.map +7 -0
  24. package/dist/chunks/{merge-review-OQDXNTJU.ts → merge-review-6YSLSMGS.ts} +3 -2
  25. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts +59 -0
  26. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts.map +7 -0
  27. package/dist/chunks/{remote-selection-ui-GPITNEBF.ts → remote-selection-ui-N4NMWFT2.ts} +4 -4
  28. package/dist/chunks/{setup-switch-L54X5U5I.ts → setup-switch-HY7K3442.ts} +4 -4
  29. package/dist/chunks/{setup-wizard-LL6YMGUR.ts → setup-wizard-LEKDQ3HK.ts} +9 -9
  30. package/dist/chunks/{sync-inspection-SRU6HGGK.ts → sync-inspection-OS2LVOLV.ts} +5 -5
  31. package/dist/chunks/{sync-operations-UGSCONZ7.ts → sync-operations-D3MDJUQQ.ts} +2 -2
  32. package/dist/daemon/dist/cli.js +2 -0
  33. package/dist/daemon/dist/client-transport.js +66 -0
  34. package/dist/daemon/dist/client.js +116 -86
  35. package/dist/daemon/dist/consent.js +33 -11
  36. package/dist/daemon/dist/daemon-debug.js +33 -0
  37. package/dist/daemon/dist/daemon-recovery.js +75 -0
  38. package/dist/daemon/dist/engine/backends/git/git-backend.js +39 -12
  39. package/dist/daemon/dist/engine/backends/git/git-runner.js +6 -1
  40. package/dist/daemon/dist/engine/backends/git/git-storage.js +5 -9
  41. package/dist/daemon/dist/engine/backends/publication-encoding.js +19 -0
  42. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +10 -12
  43. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +15 -26
  44. package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +10 -0
  45. package/dist/daemon/dist/engine/debug-log.js +134 -0
  46. package/dist/daemon/dist/engine/paths.js +7 -1
  47. package/dist/daemon/dist/engine/settings/config-file.js +62 -17
  48. package/dist/daemon/dist/engine/settings/config.js +49 -14
  49. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +30 -8
  50. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +3 -1
  51. package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +32 -0
  52. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +34 -0
  53. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +50 -7
  54. package/dist/daemon/dist/engine/snapshot/snapshot.js +64 -25
  55. package/dist/daemon/dist/engine/state/lock.js +157 -17
  56. package/dist/daemon/dist/engine/sync/continuous-sync.js +35 -11
  57. package/dist/daemon/dist/engine/sync/initialization.js +2 -2
  58. package/dist/daemon/dist/engine/sync/local-fields.js +42 -19
  59. package/dist/daemon/dist/engine/sync/merged-sync.js +13 -10
  60. package/dist/daemon/dist/engine/sync/remote-snapshot.js +18 -3
  61. package/dist/daemon/dist/engine/sync/session-push.js +13 -4
  62. package/dist/daemon/dist/engine/sync/startup-bootstrap.js +105 -0
  63. package/dist/daemon/dist/engine/sync/startup-recovery-evidence.js +37 -0
  64. package/dist/daemon/dist/engine/sync/startup-timings.js +80 -8
  65. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +6 -1
  66. package/dist/daemon/dist/engine/sync/sync-inspection.js +4 -7
  67. package/dist/daemon/dist/engine/sync/sync-local.js +3 -1
  68. package/dist/daemon/dist/engine/sync/sync-mutations.js +9 -3
  69. package/dist/daemon/dist/engine/sync/sync-policy.js +9 -1
  70. package/dist/daemon/dist/engine/sync/sync-state.js +12 -4
  71. package/dist/daemon/dist/engine-service.js +54 -10
  72. package/dist/daemon/dist/identity.js +36 -6
  73. package/dist/daemon/dist/index.js +2 -1
  74. package/dist/daemon/dist/monitor.js +20 -1
  75. package/dist/daemon/dist/paged-review.js +177 -0
  76. package/dist/daemon/dist/participant-ledger.js +149 -0
  77. package/dist/daemon/dist/protocol.js +4 -0
  78. package/dist/daemon/dist/server.js +268 -120
  79. package/dist/daemon/dist/service-host.js +29 -9
  80. package/dist/daemon/dist/state-wait-jobs.js +23 -0
  81. package/dist/daemon/dist/state-wait.js +34 -0
  82. package/dist/daemon/package.json +1 -1
  83. package/dist/index.ts +128 -48
  84. package/dist/index.ts.map +2 -2
  85. package/docs/continuous-sync-verification.md +2 -0
  86. package/docs/daemon-migration.md +30 -2
  87. package/docs/tui-contract.md +7 -1
  88. package/package.json +2 -2
  89. package/skills/configure-pi-sync/references/configuration.md +23 -13
  90. package/src/commands/command-execution.ts +11 -3
  91. package/src/commands/command-handler.ts +10 -3
  92. package/src/commands/command.ts +3 -2
  93. package/src/daemon/client-debug.ts +45 -0
  94. package/src/daemon/ownership-recovery.ts +50 -0
  95. package/src/daemon/pi-client.ts +288 -63
  96. package/src/daemon/startup-bootstrap-client.ts +26 -0
  97. package/src/settings/config.ts +1 -0
  98. package/src/sync/automatic-sync.ts +61 -18
  99. package/src/sync/startup-check.ts +13 -5
  100. package/src/sync-extension.ts +46 -8
  101. package/src/ui/manager-state.ts +29 -21
  102. package/src/ui/manager-ui.ts +16 -1
  103. package/src/ui/merge-review.ts +52 -16
  104. package/src/ui/settings-ui.ts +2 -2
  105. package/src/ui/sync-confirmation.ts +16 -19
  106. package/src/ui/sync-setups-ui.ts +15 -12
  107. package/dist/chunks/chunk-27F5W7DX.ts.map +0 -7
  108. package/dist/chunks/chunk-B5F3JLD3.ts.map +0 -7
  109. package/dist/chunks/chunk-HLCML3OW.ts.map +0 -7
  110. package/dist/chunks/chunk-POWOMJ7S.ts.map +0 -7
  111. package/dist/chunks/command-handler-GMRRFWOL.ts.map +0 -7
  112. package/dist/chunks/manager-ui-T5J5WG7T.ts.map +0 -7
  113. /package/dist/chunks/{chunk-V76KCWHO.ts.map → chunk-F3VODLVQ.ts.map} +0 -0
  114. /package/dist/chunks/{chunk-VQ47JBLF.ts.map → chunk-FI2F5JBS.ts.map} +0 -0
  115. /package/dist/chunks/{chunk-LBNC5AOM.ts.map → chunk-NDEZ52SS.ts.map} +0 -0
  116. /package/dist/chunks/{chunk-EXDWEFIJ.ts.map → chunk-TJ7YNITN.ts.map} +0 -0
  117. /package/dist/chunks/{chunk-HSCAFOT5.ts.map → chunk-TZMVSTAM.ts.map} +0 -0
  118. /package/dist/chunks/{chunk-SXCH4Q5O.ts.map → chunk-VPSC7BXM.ts.map} +0 -0
  119. /package/dist/chunks/{conflict-review-JWEA7DPQ.ts.map → conflict-review-5E4M44BA.ts.map} +0 -0
  120. /package/dist/chunks/{file-selection-KID23GAD.ts.map → file-selection-DDQN4LVD.ts.map} +0 -0
  121. /package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts.map → manager-result-dispatcher-FKW55L7I.ts.map} +0 -0
  122. /package/dist/chunks/{merge-review-OQDXNTJU.ts.map → merge-review-6YSLSMGS.ts.map} +0 -0
  123. /package/dist/chunks/{remote-selection-ui-GPITNEBF.ts.map → remote-selection-ui-N4NMWFT2.ts.map} +0 -0
  124. /package/dist/chunks/{setup-switch-L54X5U5I.ts.map → setup-switch-HY7K3442.ts.map} +0 -0
  125. /package/dist/chunks/{setup-wizard-LL6YMGUR.ts.map → setup-wizard-LEKDQ3HK.ts.map} +0 -0
  126. /package/dist/chunks/{sync-inspection-SRU6HGGK.ts.map → sync-inspection-OS2LVOLV.ts.map} +0 -0
  127. /package/dist/chunks/{sync-operations-UGSCONZ7.ts.map → sync-operations-D3MDJUQQ.ts.map} +0 -0
@@ -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
+ }
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { lstatSync, realpathSync } from "node:fs";
2
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs";
3
3
  import fs from "node:fs/promises";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
@@ -84,13 +84,15 @@ export async function readUpgradeOwner(paths) {
84
84
  const value = await readPrivateRecord(upgradeFile(paths));
85
85
  if (value === undefined)
86
86
  return;
87
- if (!validOwner(value, paths.root) || (value.birth !== undefined && !validBirth(value.birth)))
87
+ if (!validOwner(value, paths.root) ||
88
+ (value.birth !== undefined && !validBirth(value.birth)) ||
89
+ (value.purpose !== undefined && value.purpose !== "cleanup"))
88
90
  throw new Error("Invalid daemon upgrade record; state retained.");
89
- const { version, root, instance, pid, birth } = value;
90
- return birth === undefined ? { version, root, instance, pid } : { version, root, instance, pid, birth };
91
+ const { version, root, instance, pid, birth, purpose } = value;
92
+ return { version, root, instance, pid, ...(birth && { birth }), ...(purpose && { purpose }) };
91
93
  }
92
- export function recordUpgradeOwner(paths, { version, root, instance, pid, birth }) {
93
- return publishPrivateRecord(paths, upgradeFile(paths), { version, root, instance, pid, birth });
94
+ export function recordUpgradeOwner(paths, { version, root, instance, pid, birth, purpose }) {
95
+ return publishPrivateRecord(paths, upgradeFile(paths), { version, root, instance, pid, birth, purpose });
94
96
  }
95
97
  export function clearUpgradeOwner(paths) {
96
98
  return fs.rm(upgradeFile(paths), { force: true });
@@ -103,6 +105,34 @@ export async function readIdentity(paths) {
103
105
  throw new Error("Invalid or incompatible daemon identity; state retained.");
104
106
  return { ...value, token: value.token };
105
107
  }
108
+ export function matchesPublishedIdentity(paths, identity) {
109
+ const expected = Buffer.from(JSON.stringify(identity));
110
+ if (expected.length > 8192)
111
+ return false;
112
+ const before = lstatSync(paths.identity, { bigint: true, throwIfNoEntry: false });
113
+ if (!before?.isFile() ||
114
+ before.size !== BigInt(expected.length) ||
115
+ (process.getuid && before.uid !== BigInt(process.getuid())) ||
116
+ (process.platform !== "win32" && (before.mode & 63n) !== 0n))
117
+ return false;
118
+ const sameFile = (info) => info?.dev === before.dev &&
119
+ info.ino === before.ino &&
120
+ info.size === before.size &&
121
+ info.ctimeNs === before.ctimeNs &&
122
+ info.mtimeNs === before.mtimeNs;
123
+ const fd = openSync(paths.identity, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
124
+ try {
125
+ if (!sameFile(fstatSync(fd, { bigint: true })))
126
+ return false;
127
+ const observed = Buffer.alloc(expected.length + 1);
128
+ return (readSync(fd, observed) === expected.length &&
129
+ observed.subarray(0, expected.length).equals(expected) &&
130
+ sameFile(lstatSync(paths.identity, { bigint: true, throwIfNoEntry: false })));
131
+ }
132
+ finally {
133
+ closeSync(fd);
134
+ }
135
+ }
106
136
  function validBirth(value) {
107
137
  const fields = typeof value === "string" && birthPattern.exec(value);
108
138
  return (!!fields &&
@@ -1,4 +1,5 @@
1
1
  export { DaemonConnection, DaemonError, ensureDaemon, findDaemon, requestDaemon, stopDaemon, waitForDaemonExit, } from "./client.js";
2
+ export { inspectDaemonRecovery, stopDaemonForRecovery, } from "./daemon-recovery.js";
2
3
  export { documentFingerprint } from "./document.js";
3
4
  export { modelSignature } from "./model-signature.js";
4
- export { MAX_SETTINGS_BYTES, PROTOCOL_VERSION } from "./protocol.js";
5
+ export { MAX_SETTINGS_BYTES, OWNERSHIP_CLEANUP_REQUIRED, PROTOCOL_VERSION } from "./protocol.js";
@@ -23,6 +23,7 @@ export function createMonitor(root, host) {
23
23
  const retryOwner = (peer) => JSON.stringify([peer.generation, peer.cwd, peer.sessionId, peer.sessionFile, peer.sessionDir, peer.model]);
24
24
  let epoch;
25
25
  const timingOwners = new WeakMap();
26
+ const cycleOutcomes = new Map();
26
27
  const loaders = createEngineLoaders();
27
28
  let continuous;
28
29
  function schedule() {
@@ -116,7 +117,25 @@ export function createMonitor(root, host) {
116
117
  const { createContinuousSync } = await import("./engine/sync/continuous-sync.js");
117
118
  if (!available())
118
119
  return;
119
- continuous = createContinuousSync(loaders, undefined, (ctx, report) => timingOwners.get(ctx)?.emit("timings", { report }));
120
+ continuous = createContinuousSync(loaders, undefined, (ctx, report) => timingOwners.get(ctx)?.emit("timings", { report }), {
121
+ timing: (ctx, report) => timingOwners.get(ctx)?.debug?.({ event: "startup-timings", report }),
122
+ cycle(ctx, setup, outcome) {
123
+ const debug = timingOwners.get(ctx)?.debug;
124
+ if (!debug)
125
+ return;
126
+ const key = `${outcome.outcome}:${outcome.reason ?? ""}`;
127
+ if (outcome.outcome !== "completed" && cycleOutcomes.get(setup) === key)
128
+ return;
129
+ cycleOutcomes.delete(setup);
130
+ cycleOutcomes.set(setup, key);
131
+ if (cycleOutcomes.size > 64) {
132
+ const oldest = cycleOutcomes.keys().next().value;
133
+ if (oldest !== undefined)
134
+ cycleOutcomes.delete(oldest);
135
+ }
136
+ debug({ event: "continuous-cycle", ...outcome });
137
+ },
138
+ });
120
139
  // Re-enter every eligibility branch after importing the full engine graph.
121
140
  return start();
122
141
  }
@@ -0,0 +1,177 @@
1
+ import { createHash } from "node:crypto";
2
+ import { MAX_REVIEW_BYTES, REVIEW_PAGE_CHARS, record, } from "./protocol.js";
3
+ const SUMMARY_ROWS = 12;
4
+ const SUMMARY_ROW_CHARS = 240;
5
+ const HASH = /^[a-f0-9]{64}$/u;
6
+ export function reviewScope(identity, facts, callback) {
7
+ return {
8
+ instance: identity.instance,
9
+ client: facts.id,
10
+ generation: facts.generation,
11
+ id: callback.id,
12
+ job: callback.job,
13
+ };
14
+ }
15
+ function commitment(scope, summary, body) {
16
+ return createHash("sha256")
17
+ .update(JSON.stringify([
18
+ "pi-sync-merge-review-v1",
19
+ scope.instance,
20
+ scope.client,
21
+ scope.generation,
22
+ scope.id,
23
+ scope.job,
24
+ summary.title,
25
+ summary.confirmationLabel ?? null,
26
+ summary.summaryLines,
27
+ body.pages,
28
+ body.bytes,
29
+ body.sha256,
30
+ ]))
31
+ .digest("hex");
32
+ }
33
+ function exactHash(content) {
34
+ return createHash("sha256").update(content, "utf16le").digest("hex");
35
+ }
36
+ function presentation(value) {
37
+ return (record(value) &&
38
+ typeof value.title === "string" &&
39
+ value.title.length > 0 &&
40
+ value.title.length <= 512 &&
41
+ (value.confirmationLabel === undefined ||
42
+ (typeof value.confirmationLabel === "string" && value.confirmationLabel.length <= 256)));
43
+ }
44
+ export function createPagedReviewOffer(scope, data, content, bytes) {
45
+ if (!presentation(data))
46
+ return undefined;
47
+ const supplied = data.summaryLines;
48
+ const candidates = Array.isArray(supplied) && supplied.length > 0
49
+ ? supplied.slice(0, SUMMARY_ROWS)
50
+ : content.slice(0, SUMMARY_ROWS * SUMMARY_ROW_CHARS).split("\n", SUMMARY_ROWS);
51
+ const summaryLines = Object.freeze(candidates
52
+ .filter((line) => typeof line === "string")
53
+ .map((line) => line.slice(0, SUMMARY_ROW_CHARS)));
54
+ const summary = Object.freeze({ title: data.title, confirmationLabel: data.confirmationLabel, summaryLines });
55
+ const body = { pages: Math.ceil(content.length / REVIEW_PAGE_CHARS), bytes, sha256: exactHash(content) };
56
+ const reference = Object.freeze({ ...body, offer: commitment(scope, summary, body) });
57
+ let nextPage = 0;
58
+ return {
59
+ summary,
60
+ reference,
61
+ generation: scope.generation,
62
+ page(params) {
63
+ const index = params.index;
64
+ if (params.client !== scope.client ||
65
+ params.generation !== scope.generation ||
66
+ params.id !== scope.id ||
67
+ params.offer !== reference.offer ||
68
+ typeof index !== "number" ||
69
+ !Number.isSafeInteger(index) ||
70
+ index < 0 ||
71
+ index > nextPage ||
72
+ index >= reference.pages)
73
+ throw new Error("Stale, foreign, or invalid review page.");
74
+ if (index === nextPage)
75
+ nextPage++;
76
+ const start = index * REVIEW_PAGE_CHARS;
77
+ return { id: scope.id, index, offer: reference.offer, content: content.slice(start, start + REVIEW_PAGE_CHARS) };
78
+ },
79
+ approved(value) {
80
+ if (!record(value) || value.approvedReview !== reference.offer || nextPage !== reference.pages)
81
+ throw new Error("Exact review approval did not match the complete current offer.");
82
+ return true;
83
+ },
84
+ };
85
+ }
86
+ function verifyPagedReview(scope, payload, reference) {
87
+ if (!presentation(payload) ||
88
+ payload.content !== undefined ||
89
+ !Array.isArray(payload.summaryLines) ||
90
+ payload.summaryLines.length > SUMMARY_ROWS ||
91
+ !payload.summaryLines.every((line) => typeof line === "string" && line.length <= SUMMARY_ROW_CHARS) ||
92
+ !record(reference) ||
93
+ typeof reference.pages !== "number" ||
94
+ !Number.isSafeInteger(reference.pages) ||
95
+ reference.pages < 1 ||
96
+ reference.pages > Math.ceil(MAX_REVIEW_BYTES / REVIEW_PAGE_CHARS) ||
97
+ typeof reference.bytes !== "number" ||
98
+ !Number.isSafeInteger(reference.bytes) ||
99
+ reference.bytes <= REVIEW_PAGE_CHARS ||
100
+ reference.bytes > MAX_REVIEW_BYTES ||
101
+ typeof reference.sha256 !== "string" ||
102
+ !HASH.test(reference.sha256) ||
103
+ typeof reference.offer !== "string" ||
104
+ !HASH.test(reference.offer))
105
+ throw new Error("Invalid exact-review offer.");
106
+ const summary = Object.freeze({
107
+ title: payload.title,
108
+ confirmationLabel: payload.confirmationLabel,
109
+ summaryLines: Object.freeze([...payload.summaryLines]),
110
+ });
111
+ const verified = Object.freeze({
112
+ pages: reference.pages,
113
+ bytes: reference.bytes,
114
+ sha256: reference.sha256,
115
+ offer: reference.offer,
116
+ });
117
+ if (commitment(scope, summary, verified) !== verified.offer)
118
+ throw new Error("Exact-review offer changed; approval was refused.");
119
+ return { summary, reference: verified };
120
+ }
121
+ async function loadPagedReview(scope, reference, signal, pageRequest) {
122
+ const pages = [];
123
+ const { client, generation, id } = scope;
124
+ for (let index = 0; index < reference.pages; index++) {
125
+ signal.throwIfAborted();
126
+ const page = await pageRequest({ client, generation, id, offer: reference.offer, index });
127
+ signal.throwIfAborted();
128
+ if (!record(page) ||
129
+ page.id !== id ||
130
+ page.index !== index ||
131
+ page.offer !== reference.offer ||
132
+ typeof page.content !== "string" ||
133
+ page.content.length < 1 ||
134
+ page.content.length > REVIEW_PAGE_CHARS ||
135
+ (index < reference.pages - 1 && page.content.length !== REVIEW_PAGE_CHARS))
136
+ throw new Error("Invalid exact-review page.");
137
+ pages.push(page.content);
138
+ }
139
+ const content = pages.join("");
140
+ if (Buffer.byteLength(content) !== reference.bytes || exactHash(content) !== reference.sha256)
141
+ throw new Error("Exact-review contents changed; approval was refused.");
142
+ return content;
143
+ }
144
+ export async function presentPagedReview(scope, callback, signal, present, requestPage) {
145
+ if (callback.kind !== "merge-review")
146
+ throw new Error("Invalid exact-review callback.");
147
+ const { summary, reference } = verifyPagedReview(scope, callback.payload, callback.review);
148
+ const lifetime = new AbortController();
149
+ const owned = AbortSignal.any([signal, lifetime.signal]);
150
+ let loading;
151
+ let verified = false;
152
+ try {
153
+ owned.throwIfAborted();
154
+ const approved = await present({ ...callback, payload: summary, review: reference }, (requestSignal) => {
155
+ const pageSignal = requestSignal ? AbortSignal.any([owned, requestSignal]) : owned;
156
+ if (!loading) {
157
+ loading = loadPagedReview(scope, reference, pageSignal, (params) => requestPage(params, pageSignal)).then((content) => {
158
+ pageSignal.throwIfAborted();
159
+ verified = true;
160
+ return content;
161
+ });
162
+ void loading.catch(() => { });
163
+ }
164
+ return loading;
165
+ }, owned);
166
+ owned.throwIfAborted();
167
+ if (approved === false)
168
+ return false;
169
+ if (approved !== true || !verified)
170
+ throw new Error("Exact review details were not verified before approval.");
171
+ return { approvedReview: reference.offer };
172
+ }
173
+ finally {
174
+ lifetime.abort();
175
+ await loading?.catch(() => { });
176
+ }
177
+ }
@@ -0,0 +1,149 @@
1
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
2
+ if (value !== null && value !== void 0) {
3
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
+ var dispose, inner;
5
+ if (async) {
6
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
+ dispose = value[Symbol.asyncDispose];
8
+ }
9
+ if (dispose === void 0) {
10
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
+ dispose = value[Symbol.dispose];
12
+ if (async) inner = dispose;
13
+ }
14
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
16
+ env.stack.push({ value: value, dispose: dispose, async: async });
17
+ }
18
+ else if (async) {
19
+ env.stack.push({ async: true });
20
+ }
21
+ return value;
22
+ };
23
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
24
+ return function (env) {
25
+ function fail(e) {
26
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
27
+ env.hasError = true;
28
+ }
29
+ var r, s = 0;
30
+ function next() {
31
+ while (r = env.stack.pop()) {
32
+ try {
33
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
34
+ if (r.dispose) {
35
+ var result = r.dispose.call(r.value);
36
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
37
+ }
38
+ else s |= 1;
39
+ }
40
+ catch (e) {
41
+ fail(e);
42
+ }
43
+ }
44
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
45
+ if (env.hasError) throw env.error;
46
+ }
47
+ return next();
48
+ };
49
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
50
+ var e = new Error(message);
51
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
52
+ });
53
+ import { randomUUID } from "node:crypto";
54
+ import fs from "node:fs/promises";
55
+ import path from "node:path";
56
+ import { processExists } from "./identity.js";
57
+ import { MAX_MESSAGE_BYTES, record, validateFacts, validateHandoff, } from "./protocol.js";
58
+ export function createParticipantLedger(paths, participants, onFailure) {
59
+ const file = path.join(paths.directory, "clients.json");
60
+ let writes = Promise.resolve();
61
+ let published;
62
+ let failed = false;
63
+ async function write(candidate, allowNoop) {
64
+ const bytes = JSON.stringify({
65
+ version: 1,
66
+ root: paths.root,
67
+ clients: [...participants()]
68
+ .filter((peer) => processExists(peer.facts.pid))
69
+ .map((peer) => ({ ...(candidate?.peer === peer ? candidate.facts : peer.facts), handoff: peer.handoff })),
70
+ });
71
+ if (allowNoop && !failed && bytes === published)
72
+ return;
73
+ const temporary = path.join(paths.directory, `.${randomUUID()}.clients`);
74
+ const handle = await fs.open(temporary, "wx", 0o600);
75
+ try {
76
+ await handle.writeFile(bytes);
77
+ await handle.sync();
78
+ await handle.close();
79
+ await fs.rename(temporary, file);
80
+ published = bytes;
81
+ }
82
+ finally {
83
+ await handle.close().catch(() => { });
84
+ await fs.rm(temporary, { force: true });
85
+ }
86
+ }
87
+ return {
88
+ get failed() {
89
+ return failed;
90
+ },
91
+ drain: () => writes,
92
+ save(candidate, allowNoop) {
93
+ const operation = writes.then(() => write(candidate, allowNoop));
94
+ writes = operation.catch(() => {
95
+ failed = true;
96
+ onFailure();
97
+ });
98
+ return operation;
99
+ },
100
+ async restore() {
101
+ try {
102
+ const env_1 = { stack: [], error: void 0, hasError: false };
103
+ try {
104
+ const before = await fs.lstat(file);
105
+ if (!before.isFile() ||
106
+ before.isSymbolicLink() ||
107
+ before.size > MAX_MESSAGE_BYTES ||
108
+ (process.getuid && before.uid !== process.getuid()) ||
109
+ (process.platform !== "win32" && before.mode & 0o077))
110
+ throw new Error("Unsafe daemon client record.");
111
+ const handle = __addDisposableResource(env_1, await fs.open(file, "r"), true);
112
+ const opened = await handle.stat();
113
+ if (opened.dev !== before.dev || opened.ino !== before.ino)
114
+ throw new Error("Daemon client record changed while opening.");
115
+ const data = JSON.parse(await handle.readFile("utf8"));
116
+ if (!record(data) ||
117
+ data.version !== 1 ||
118
+ data.root !== paths.root ||
119
+ !Array.isArray(data.clients) ||
120
+ data.clients.length > 64)
121
+ throw new Error("Invalid daemon client record; evidence retained.");
122
+ return data.clients.map((stored) => {
123
+ if (!record(stored))
124
+ throw new Error("Invalid stored participant.");
125
+ const { handoff, ...facts } = stored;
126
+ validateFacts(facts);
127
+ if (handoff !== undefined)
128
+ validateHandoff(handoff);
129
+ return { facts, handoff };
130
+ });
131
+ }
132
+ catch (e_1) {
133
+ env_1.error = e_1;
134
+ env_1.hasError = true;
135
+ }
136
+ finally {
137
+ const result_1 = __disposeResources(env_1);
138
+ if (result_1)
139
+ await result_1;
140
+ }
141
+ }
142
+ catch (error) {
143
+ if (error.code === "ENOENT")
144
+ return [];
145
+ throw error;
146
+ }
147
+ },
148
+ };
149
+ }
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import path from "node:path";
3
3
  export const PROTOCOL_VERSION = 1;
4
+ export const OWNERSHIP_CLEANUP_REQUIRED = "DAEMON_OWNERSHIP_CLEANUP";
4
5
  /** Authenticated idle shutdown after work is drained; callers may wait for this owner to exit. */
5
6
  export class DaemonStoppingError extends Error {
6
7
  name = "DaemonStoppingError";
@@ -27,6 +28,9 @@ export function validateHandoff(value) {
27
28
  ["file", "cwd"].some((key) => typeof value[key] === "string" && !path.isAbsolute(value[key])))
28
29
  throw new Error("Invalid client handoff.");
29
30
  }
31
+ export const DAEMON_JOB_CAPACITY = 64;
32
+ export const UNKNOWN_JOB_RESULT = "Operation is unknown or its result expired; reconcile journals instead of replaying.";
33
+ export const STATE_WAIT_HEARTBEAT_MS = 1_000;
30
34
  export function record(value) {
31
35
  return typeof value === "object" && value !== null && !Array.isArray(value);
32
36
  }