@narumitw/pi-sync 0.69.1 → 0.70.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +2 -2
  3. package/dist/chunks/{chunk-EG6BUOUQ.ts → chunk-3XN4FR72.ts} +2 -2
  4. package/dist/chunks/{chunk-YX6DCQ7P.ts → chunk-5T4ZOHYF.ts} +2 -2
  5. package/dist/chunks/{chunk-RXZVLBPU.ts → chunk-7NQ7SFZK.ts} +3 -3
  6. package/dist/chunks/{chunk-2JNFEZ3V.ts → chunk-AMJRUXFT.ts} +6 -2
  7. package/dist/chunks/{chunk-2JNFEZ3V.ts.map → chunk-AMJRUXFT.ts.map} +1 -1
  8. package/dist/chunks/{chunk-XNUARYLR.ts → chunk-HFMGK6A6.ts} +2 -2
  9. package/dist/chunks/{chunk-OWSKD5XG.ts → chunk-JPTI4HFC.ts} +4 -4
  10. package/dist/chunks/{chunk-RZB2DPVU.ts → chunk-N24HEZSA.ts} +3 -3
  11. package/dist/chunks/{chunk-EI2J5Z4Q.ts → chunk-SPXEDJ2G.ts} +4 -4
  12. package/dist/chunks/{chunk-GXB74FYB.ts → chunk-V4IGBXBA.ts} +4 -4
  13. package/dist/chunks/{chunk-4KGDPLQ4.ts → chunk-ZWP6HAYV.ts} +16 -6
  14. package/dist/chunks/chunk-ZWP6HAYV.ts.map +7 -0
  15. package/dist/chunks/{command-handler-ZR26OSBX.ts → command-handler-4XHK5PVX.ts} +20 -15
  16. package/dist/chunks/command-handler-4XHK5PVX.ts.map +7 -0
  17. package/dist/chunks/{conflict-review-W5BCZIZG.ts → conflict-review-QI77P7KL.ts} +3 -3
  18. package/dist/chunks/diff-review-ILRZDQ4S.ts +143 -0
  19. package/dist/chunks/diff-review-ILRZDQ4S.ts.map +7 -0
  20. package/dist/chunks/diff-review-SOLP33TQ.ts +68 -0
  21. package/dist/chunks/diff-review-SOLP33TQ.ts.map +7 -0
  22. package/dist/chunks/{file-selection-STCIRKF6.ts → file-selection-2H3J2HTX.ts} +4 -4
  23. package/dist/chunks/{manager-result-dispatcher-MPLPDR2P.ts → manager-result-dispatcher-YXSDLTLV.ts} +5 -5
  24. package/dist/chunks/{manager-ui-OMZOBGYT.ts → manager-ui-RQSZLMJ5.ts} +19 -19
  25. package/dist/chunks/manager-ui-RQSZLMJ5.ts.map +7 -0
  26. package/dist/chunks/{merge-review-KTIQBRLL.ts → merge-review-DXSERTCK.ts} +3 -3
  27. package/dist/chunks/{ownership-recovery-UDDHSDSZ.ts → ownership-recovery-5KXAMFSL.ts} +2 -2
  28. package/dist/chunks/{remote-selection-ui-CCHMCAHQ.ts → remote-selection-ui-AE6FOEXH.ts} +4 -4
  29. package/dist/chunks/{setup-switch-J3YLBB6N.ts → setup-switch-LJPEZONY.ts} +3 -3
  30. package/dist/chunks/{setup-wizard-J3YOR7BR.ts → setup-wizard-FBX7RTZ6.ts} +4 -4
  31. package/dist/chunks/{sync-inspection-7OADBR57.ts → sync-inspection-TZ4EMSBN.ts} +3 -3
  32. package/dist/chunks/{sync-operations-3K6WLPXY.ts → sync-operations-QIQ3G66S.ts} +16 -5
  33. package/dist/chunks/{sync-operations-3K6WLPXY.ts.map → sync-operations-QIQ3G66S.ts.map} +2 -2
  34. package/dist/daemon/dist/build-id.json +1 -1
  35. package/dist/daemon/dist/client.js +131 -5
  36. package/dist/daemon/dist/diff-review-binding.js +11 -0
  37. package/dist/daemon/dist/diff-review-protocol.js +85 -0
  38. package/dist/daemon/dist/diff-review-rpc.js +37 -0
  39. package/dist/daemon/dist/diff-review-store.js +89 -0
  40. package/dist/daemon/dist/engine/backends/git/git-backend.js +10 -6
  41. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +3 -3
  42. package/dist/daemon/dist/engine/backends/s3/s3-client.js +16 -6
  43. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +3 -3
  44. package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +23 -10
  45. package/dist/daemon/dist/engine/snapshot/session-paths.js +12 -3
  46. package/dist/daemon/dist/engine/snapshot/snapshot-capture-limit.js +99 -0
  47. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +4 -1
  48. package/dist/daemon/dist/engine/snapshot/snapshot-difference.js +13 -0
  49. package/dist/daemon/dist/engine/snapshot/snapshot.js +44 -17
  50. package/dist/daemon/dist/engine/sync/diff-review-capture.js +210 -0
  51. package/dist/daemon/dist/engine/sync/diff-review-preview.js +114 -0
  52. package/dist/daemon/dist/engine/sync/remote-snapshot.js +6 -6
  53. package/dist/daemon/dist/engine/sync/sync-queries.js +32 -19
  54. package/dist/daemon/dist/engine/ui/sync-format.js +14 -24
  55. package/dist/daemon/dist/engine-service.js +5 -0
  56. package/dist/daemon/dist/index.js +1 -0
  57. package/dist/daemon/dist/server.js +97 -28
  58. package/dist/daemon/package.json +1 -1
  59. package/dist/index.ts +7 -7
  60. package/docs/tui-contract.md +1 -1
  61. package/package.json +3 -3
  62. package/skills/configure-pi-sync/references/configuration.md +1 -1
  63. package/src/commands/command-execution.ts +9 -4
  64. package/src/commands/command-handler.ts +3 -3
  65. package/src/commands/command-types.ts +1 -0
  66. package/src/daemon/diff-review.ts +68 -0
  67. package/src/sync/sync-operations.ts +12 -2
  68. package/src/ui/cancellable-operation.ts +32 -11
  69. package/src/ui/diff-review.ts +144 -0
  70. package/src/ui/manager-ui.ts +7 -6
  71. package/dist/chunks/chunk-4KGDPLQ4.ts.map +0 -7
  72. package/dist/chunks/command-handler-ZR26OSBX.ts.map +0 -7
  73. package/dist/chunks/manager-ui-OMZOBGYT.ts.map +0 -7
  74. /package/dist/chunks/{chunk-EG6BUOUQ.ts.map → chunk-3XN4FR72.ts.map} +0 -0
  75. /package/dist/chunks/{chunk-YX6DCQ7P.ts.map → chunk-5T4ZOHYF.ts.map} +0 -0
  76. /package/dist/chunks/{chunk-RXZVLBPU.ts.map → chunk-7NQ7SFZK.ts.map} +0 -0
  77. /package/dist/chunks/{chunk-XNUARYLR.ts.map → chunk-HFMGK6A6.ts.map} +0 -0
  78. /package/dist/chunks/{chunk-OWSKD5XG.ts.map → chunk-JPTI4HFC.ts.map} +0 -0
  79. /package/dist/chunks/{chunk-RZB2DPVU.ts.map → chunk-N24HEZSA.ts.map} +0 -0
  80. /package/dist/chunks/{chunk-EI2J5Z4Q.ts.map → chunk-SPXEDJ2G.ts.map} +0 -0
  81. /package/dist/chunks/{chunk-GXB74FYB.ts.map → chunk-V4IGBXBA.ts.map} +0 -0
  82. /package/dist/chunks/{conflict-review-W5BCZIZG.ts.map → conflict-review-QI77P7KL.ts.map} +0 -0
  83. /package/dist/chunks/{file-selection-STCIRKF6.ts.map → file-selection-2H3J2HTX.ts.map} +0 -0
  84. /package/dist/chunks/{manager-result-dispatcher-MPLPDR2P.ts.map → manager-result-dispatcher-YXSDLTLV.ts.map} +0 -0
  85. /package/dist/chunks/{merge-review-KTIQBRLL.ts.map → merge-review-DXSERTCK.ts.map} +0 -0
  86. /package/dist/chunks/{ownership-recovery-UDDHSDSZ.ts.map → ownership-recovery-5KXAMFSL.ts.map} +0 -0
  87. /package/dist/chunks/{remote-selection-ui-CCHMCAHQ.ts.map → remote-selection-ui-AE6FOEXH.ts.map} +0 -0
  88. /package/dist/chunks/{setup-switch-J3YLBB6N.ts.map → setup-switch-LJPEZONY.ts.map} +0 -0
  89. /package/dist/chunks/{setup-wizard-J3YOR7BR.ts.map → setup-wizard-FBX7RTZ6.ts.map} +0 -0
  90. /package/dist/chunks/{sync-inspection-7OADBR57.ts.map → sync-inspection-TZ4EMSBN.ts.map} +0 -0
@@ -0,0 +1,114 @@
1
+ import { DIFF_REVIEW_OUTPUT_BYTES, DIFF_REVIEW_OUTPUT_LINES, } from "../../diff-review-protocol.js";
2
+ import { edits, lines, text } from "./text-merge.js";
3
+ export const DIFF_REVIEW_FILE_BYTES = 64 * 1024;
4
+ export const DIFF_REVIEW_FILE_BASE64_CHARS = Math.ceil(DIFF_REVIEW_FILE_BYTES / 3) * 4;
5
+ const MAX_EDIT_CELLS = 1_000_000;
6
+ const CONTEXT = 3;
7
+ export const DIFF_REVIEW_LIMIT_NOTICE = "This file exceeds the text preview limits. No partial patch was returned.";
8
+ function notice(message) {
9
+ return { kind: "notice", message };
10
+ }
11
+ function* hunkGroups(changes) {
12
+ let group = [];
13
+ for (const change of changes) {
14
+ const previous = group.at(-1);
15
+ if (previous && change.start - previous.end > 2 * CONTEXT) {
16
+ yield group;
17
+ group = [];
18
+ }
19
+ group.push(change);
20
+ }
21
+ if (group.length)
22
+ yield group;
23
+ }
24
+ function range(start, count) {
25
+ if (count === 1)
26
+ return String(start + 1);
27
+ return `${count === 0 ? start : start + 1},${count}`;
28
+ }
29
+ class DiffOutputLimitError extends Error {
30
+ }
31
+ function unifiedDiff(base, changes, signal) {
32
+ const output = [];
33
+ let bytes = 0;
34
+ const append = (line) => {
35
+ bytes += Buffer.byteLength(line);
36
+ if (bytes > DIFF_REVIEW_OUTPUT_BYTES || output.length >= DIFF_REVIEW_OUTPUT_LINES)
37
+ throw new DiffOutputLimitError();
38
+ output.push(line);
39
+ };
40
+ const sourceLine = (prefix, line) => {
41
+ if (line.endsWith("\n"))
42
+ append(prefix + line);
43
+ else {
44
+ append(`${prefix}${line}\n`);
45
+ append("\\n");
46
+ }
47
+ };
48
+ append("--- Local\n");
49
+ append("+++ Remote\n");
50
+ let offset = 0;
51
+ for (const group of hunkGroups(changes)) {
52
+ signal?.throwIfAborted();
53
+ const first = group[0];
54
+ const last = group.at(-1);
55
+ if (!first || !last)
56
+ continue;
57
+ const start = Math.max(0, first.start - CONTEXT);
58
+ const end = Math.min(base.length, last.end + CONTEXT);
59
+ const delta = group.reduce((sum, change) => sum + change.lines.length - (change.end - change.start), 0);
60
+ append(`@@ -${range(start, end - start)} +${range(start + offset, end - start + delta)} @@\n`);
61
+ offset += delta;
62
+ let cursor = start;
63
+ for (const change of group) {
64
+ for (const line of base.slice(cursor, change.start))
65
+ sourceLine(" ", line);
66
+ for (const line of base.slice(change.start, change.end))
67
+ sourceLine("-", line);
68
+ for (const line of change.lines)
69
+ sourceLine("+", line);
70
+ cursor = change.end;
71
+ }
72
+ for (const line of base.slice(cursor, end))
73
+ sourceLine(" ", line);
74
+ }
75
+ return output.join("");
76
+ }
77
+ export function buildDiffReviewPreview(input, signal) {
78
+ signal?.throwIfAborted();
79
+ if ("notice" in input)
80
+ return notice(input.notice);
81
+ const localBytes = input.local ?? Buffer.alloc(0);
82
+ const remoteBytes = input.remote ?? Buffer.alloc(0);
83
+ if (Math.max(localBytes.length, remoteBytes.length) > DIFF_REVIEW_FILE_BYTES)
84
+ return notice(DIFF_REVIEW_LIMIT_NOTICE);
85
+ if (localBytes.length === 0 && remoteBytes.length === 0)
86
+ return notice("This empty file differs only in presence. There is no text hunk.");
87
+ let local;
88
+ let remote;
89
+ try {
90
+ const localText = text(localBytes);
91
+ const remoteText = text(remoteBytes);
92
+ if (/\r(?!\n)/u.test(localText) || /\r(?!\n)/u.test(remoteText))
93
+ throw new Error("Unsupported line endings.");
94
+ local = lines(localText);
95
+ remote = lines(remoteText);
96
+ }
97
+ catch {
98
+ return notice("This file is binary or is not supported UTF-8 text. Its contents were not returned.");
99
+ }
100
+ if (Math.max(local.length, remote.length) > DIFF_REVIEW_OUTPUT_LINES ||
101
+ (local.length + 1) * (remote.length + 1) > MAX_EDIT_CELLS)
102
+ return notice(DIFF_REVIEW_LIMIT_NOTICE);
103
+ const changes = edits(local, remote, signal);
104
+ if (!changes.length)
105
+ return notice("There are no text differences in this file.");
106
+ try {
107
+ return { kind: "diff", content: unifiedDiff(local, changes, signal) };
108
+ }
109
+ catch (error) {
110
+ if (error instanceof DiffOutputLimitError)
111
+ return notice(DIFF_REVIEW_LIMIT_NOTICE);
112
+ throw error;
113
+ }
114
+ }
@@ -5,8 +5,8 @@ import { sameLocalFields, validatePortableSnapshot } from "./local-fields.js";
5
5
  import { throwIfAborted } from "./signals.js";
6
6
  import { inspectRemoteSelection, remoteSelectionMismatch, requireLegacyTransferPolicy, sameSnapshotSelection, } from "./sync-policy.js";
7
7
  import { syncPolicyChanged } from "./sync-state.js";
8
- async function readValidatedSnapshotForHead(backend, head, signal) {
9
- const snapshot = await backend.readSnapshot(head.snapshotRef, signal);
8
+ async function readValidatedSnapshotForHead(backend, head, signal, maxBytes) {
9
+ const snapshot = await backend.readSnapshot(head.snapshotRef, signal, maxBytes);
10
10
  throwIfAborted(signal);
11
11
  return validateSnapshotForHead(snapshot, head);
12
12
  }
@@ -52,7 +52,7 @@ function safeList(values) {
52
52
  return values.length > 0 ? values.map(safeTerminalText).join(", ") : "none";
53
53
  }
54
54
  export async function readRemoteSnapshot(backend, config, signal, options = {}) {
55
- const observed = await readCurrentSnapshot(backend, config.scope === "agent-directory", signal);
55
+ const observed = await readCurrentSnapshot(backend, config.scope === "agent-directory", signal, options.maxBytes);
56
56
  if (!observed)
57
57
  return { head: undefined, snapshot: undefined, selectionState: undefined };
58
58
  const { head, snapshot: rawSnapshot } = observed;
@@ -64,9 +64,9 @@ export async function readRemoteSnapshot(backend, config, signal, options = {})
64
64
  const snapshot = filterSnapshotForConfigPolicy(rawSnapshot, config, { sessionDir: options.sessionDir });
65
65
  return { head, snapshot, selectionState };
66
66
  }
67
- async function readCurrentSnapshot(backend, singleObservation, signal) {
67
+ async function readCurrentSnapshot(backend, singleObservation, signal, maxBytes) {
68
68
  if (singleObservation && backend.readHeadAndSnapshot) {
69
- const observed = await backend.readHeadAndSnapshot(signal);
69
+ const observed = await backend.readHeadAndSnapshot(signal, maxBytes);
70
70
  throwIfAborted(signal);
71
71
  if (observed)
72
72
  validateSnapshotForHead(observed.snapshot, observed.head);
@@ -74,7 +74,7 @@ async function readCurrentSnapshot(backend, singleObservation, signal) {
74
74
  }
75
75
  const head = await backend.readHead(signal);
76
76
  throwIfAborted(signal);
77
- return head && { head, snapshot: await readValidatedSnapshotForHead(backend, head, signal) };
77
+ return head && { head, snapshot: await readValidatedSnapshotForHead(backend, head, signal, maxBytes) };
78
78
  }
79
79
  export async function readSnapshotForHead(backend, head, signal) {
80
80
  const snapshot = await readValidatedSnapshotForHead(backend, head, signal);
@@ -88,31 +88,44 @@ export async function diff(ctx, options, factory = createSyncBackend) {
88
88
  const config = await loadConfig(options.setup);
89
89
  throwIfAborted(options.signal);
90
90
  setSyncStatus(ctx, `checking ${config.setupName}`, { activity: "checking" });
91
- const backend = await factory(config);
92
- const snapshotOptions = await resolvedSnapshotOptionsForContext(ctx, config, options.signal);
93
- const local = portableSnapshot(await createSnapshot(config.snapshotIdentity, snapshotOptions), config.localFields);
94
- throwIfAborted(options.signal);
95
- const { snapshot: remote, selectionState } = await readRemoteSnapshot(backend, config, options.signal, {
96
- allowSelectionDifference: true,
97
- sessionDir: snapshotOptions.sessionDir,
98
- });
99
- throwIfAborted(options.signal);
91
+ const { local, remote, lines, warnings, selectionState } = await captureDiffComparison(ctx, config, options.signal, factory);
100
92
  setSyncStatus(ctx, undefined);
101
- const warnings = syncSessionsWarnings(config);
102
- const header = [
103
- `sync setup: ${config.setupName}`,
104
- `storage connection: ${config.connectionName}`,
105
- `storage location: ${safeTerminalText(backend.destination)}`,
106
- ...contentLines(config),
107
- formatRemoteSelectionStatus(selectionState),
108
- ...warnings,
109
- ].join("\n");
93
+ const header = lines.join("\n");
110
94
  const level = warnings.length > 0 || selectionState?.kind === "different" ? "warning" : "info";
111
95
  if (!remote) {
112
96
  ctx.ui.notify(`${header}\n\n${formatSnapshotOnlyDiff("Remote is empty. Local push would upload", local)}`, level);
113
97
  return;
114
98
  }
115
- ctx.ui.notify(`${header}\n\n${formatDiff(local, portableSnapshot(remote, remote.localFields))}`, level);
99
+ ctx.ui.notify(`${header}\n\n${formatDiff(local, remote)}`, level);
100
+ }
101
+ export async function captureDiffComparison(ctx, config, signal, factory = createSyncBackend, limits) {
102
+ const backend = await factory(config);
103
+ throwIfAborted(signal);
104
+ const snapshotOptions = await resolvedSnapshotOptionsForContext(ctx, config, signal);
105
+ throwIfAborted(signal);
106
+ const local = portableSnapshot(await createSnapshot(config.snapshotIdentity, snapshotOptions, limits?.local), config.localFields);
107
+ throwIfAborted(signal);
108
+ const { snapshot: remote, selectionState } = await readRemoteSnapshot(backend, config, signal, {
109
+ allowSelectionDifference: true,
110
+ sessionDir: snapshotOptions.sessionDir,
111
+ maxBytes: limits?.remoteBytes,
112
+ });
113
+ throwIfAborted(signal);
114
+ const warnings = syncSessionsWarnings(config);
115
+ return {
116
+ local,
117
+ remote: remote && portableSnapshot(remote, remote.localFields),
118
+ warnings,
119
+ selectionState,
120
+ lines: [
121
+ `sync setup: ${config.setupName}`,
122
+ `storage connection: ${config.connectionName}`,
123
+ `storage location: ${safeTerminalText(backend.destination)}`,
124
+ ...contentLines(config),
125
+ ...formatRemoteSelectionStatus(selectionState).split("\n"),
126
+ ...warnings,
127
+ ],
128
+ };
116
129
  }
117
130
  export async function doctor(ctx, options, factory = createSyncBackend) {
118
131
  const attention = [];
@@ -1,35 +1,25 @@
1
1
  import { agentDir } from "../snapshot/session-paths.js";
2
+ import { snapshotDifferences } from "../snapshot/snapshot-difference.js";
2
3
  import { inspectRemoteSelection } from "../sync/sync-policy.js";
3
- import { fileHashMap } from "../sync/sync-state.js";
4
4
  import { safeTerminalText, snapshotPathLabel } from "./terminal-text.js";
5
5
  import { transferChanges, transferCounts } from "./transfer-changes.js";
6
6
  export function formatDiff(local, remote) {
7
- const localMap = fileHashMap(local);
8
- const remoteMap = fileHashMap(remote);
9
- const allPaths = [...new Set([...Object.keys(localMap), ...Object.keys(remoteMap)])].sort();
10
- const lines = [
7
+ const changes = snapshotDifferences(local.files, remote.files);
8
+ return [
9
+ ...formatDiffCounts(local, remote),
10
+ "",
11
+ ...(changes.length ? changes.map(formatDiffRow) : ["No file differences."]),
12
+ ].join("\n");
13
+ }
14
+ export function formatDiffCounts(local, remote) {
15
+ return [
11
16
  `local: ${local.files.length} files`,
12
17
  `remote: ${safeTerminalText(remote.id)} (${remote.files.length} files)`,
13
- "",
14
18
  ];
15
- let changed = 0;
16
- for (const filePath of allPaths) {
17
- if (!Object.hasOwn(localMap, filePath)) {
18
- lines.push(`Remote only: ${snapshotPathLabel(filePath)}`);
19
- changed += 1;
20
- }
21
- else if (!Object.hasOwn(remoteMap, filePath)) {
22
- lines.push(`Local only: ${snapshotPathLabel(filePath)}`);
23
- changed += 1;
24
- }
25
- else if (localMap[filePath] !== remoteMap[filePath]) {
26
- lines.push(`Different: ${snapshotPathLabel(filePath)}`);
27
- changed += 1;
28
- }
29
- }
30
- if (changed === 0)
31
- lines.push("No file differences.");
32
- return lines.join("\n");
19
+ }
20
+ export function formatDiffRow(change) {
21
+ const label = { "local-only": "Local only", "remote-only": "Remote only", different: "Different" };
22
+ return `${label[change.status]}: ${snapshotPathLabel(change.path)}`;
33
23
  }
34
24
  export function formatSnapshotOnlyDiff(title, snapshot) {
35
25
  return [
@@ -57,6 +57,11 @@ export function createEngineService(root) {
57
57
  execution.validate();
58
58
  if (operation !== "settings.repair-read" && operation !== "monitor.pause")
59
59
  assertNoRetiredRuleJournal();
60
+ if (operation === "diff.review") {
61
+ const { captureDiffReview } = await import("./engine/sync/diff-review-capture.js");
62
+ execution.validate();
63
+ return captureDiffReview(createServiceContext(execution), payload, execution);
64
+ }
60
65
  if (operation === "daemon.authorize") {
61
66
  return Boolean(await authorizeAfterExit(execution, payload));
62
67
  }
@@ -2,6 +2,7 @@ export { DaemonConnection, DaemonError, ensureDaemon, findDaemon, requestDaemon,
2
2
  export { inspectDaemonRecovery, stopDaemonForRecovery, } from "./daemon-recovery.js";
3
3
  export { DaemonUpgradeBlockedError } from "./daemon-startup.js";
4
4
  export { inspectDaemonStatus } from "./daemon-status.js";
5
+ export { parseDiffReviewInventory } from "./diff-review-protocol.js";
5
6
  export { documentFingerprint } from "./document.js";
6
7
  export { isDestinationConflict } from "./foreground-transfer.js";
7
8
  export { modelSignature } from "./model-signature.js";
@@ -6,6 +6,9 @@ import { createServer } from "node:http";
6
6
  import lockfile from "proper-lockfile";
7
7
  import { DAEMON_BUILD_ID, DAEMON_BUILD_VERSION } from "./build-version.js";
8
8
  import { ConsentPublicationError, readConsent } from "./consent.js";
9
+ import { sameDiffReviewBinding } from "./diff-review-binding.js";
10
+ import { handleDiffReviewRequest } from "./diff-review-rpc.js";
11
+ import { createDiffReviewStore } from "./diff-review-store.js";
9
12
  import { endpointOwner } from "./endpoint.js";
10
13
  import { debugJobResult, debugOperation } from "./engine/debug-log.js";
11
14
  import { SyncDecisionRequiredError } from "./engine/sync/sync-errors.js";
@@ -69,6 +72,15 @@ export async function startServer(root, execute, hooks = {}) {
69
72
  hooks.failure?.();
70
73
  };
71
74
  const participants = new Map();
75
+ const diffReviews = createDiffReviewStore();
76
+ const invalidateDiffReview = (peer) => {
77
+ const owner = peer.diffReviewOwner;
78
+ if (!owner)
79
+ return;
80
+ peer.diffReviewOwner = undefined;
81
+ diffReviews.release(owner);
82
+ owner.abort(new DOMException("File review owner changed", "AbortError"));
83
+ };
72
84
  const waiters = new WeakMap();
73
85
  const admission = new ParticipantAdmission();
74
86
  const jobs = new Map();
@@ -190,7 +202,10 @@ export async function startServer(root, execute, hooks = {}) {
190
202
  events: peer.events.filter((event) => event.id > (typeof cursor === "number" && Number.isSafeInteger(cursor) ? cursor : 0)),
191
203
  job: job?.view,
192
204
  });
193
- function makeExecution(job) {
205
+ function makeExecution(job, diffReviewOwner) {
206
+ const signal = diffReviewOwner
207
+ ? AbortSignal.any([job.controller.signal, diffReviewOwner.signal])
208
+ : job.controller.signal;
194
209
  const validate = () => {
195
210
  if (compromised)
196
211
  throw new Error("Daemon ownership is no longer valid.");
@@ -200,16 +215,16 @@ export async function startServer(root, execute, hooks = {}) {
200
215
  return;
201
216
  }
202
217
  assertOwner();
203
- job.controller.signal.throwIfAborted();
218
+ signal.throwIfAborted();
204
219
  if (job.participantGeneration !== undefined && job.participantGeneration !== participantGeneration)
205
220
  throw new Error("Daemon participants changed before automatic work completed.");
206
221
  if (job.client) {
207
222
  const peer = requireParticipant(job.client);
208
- if (peer.facts.generation !== job.generation)
223
+ if (peer.facts.generation !== job.generation || (diffReviewOwner && peer.diffReviewOwner !== diffReviewOwner))
209
224
  throw new Error("Client session generation changed.");
210
225
  }
211
226
  };
212
- const request = (kind, data, target = job.client, signal = job.controller.signal) => {
227
+ const request = (kind, data, target = job.client, requestSignal = signal) => {
213
228
  const cleanup = kind === "queue-release";
214
229
  if (!cleanup)
215
230
  validate();
@@ -259,7 +274,7 @@ export async function startServer(root, execute, hooks = {}) {
259
274
  }
260
275
  return new Promise((resolve, reject) => {
261
276
  let timer;
262
- const effectiveSignal = cleanup ? undefined : signal;
277
+ const effectiveSignal = cleanup ? undefined : requestSignal;
263
278
  const abort = () => finish(undefined, effectiveSignal?.reason);
264
279
  const finish = (value, error) => {
265
280
  if (timer)
@@ -310,15 +325,27 @@ export async function startServer(root, execute, hooks = {}) {
310
325
  return {
311
326
  root: paths.root,
312
327
  clientId: job.client,
313
- signal: job.controller.signal,
328
+ signal,
314
329
  facts: () => (job.client ? participants.get(job.client)?.facts : undefined),
315
330
  participants: participantFacts,
316
331
  liveClients: liveClientFacts,
317
332
  withParticipants: (action) => admission.run(async () => {
318
333
  validate();
319
334
  return action(participantFacts());
320
- }, job.committed ? undefined : job.controller.signal),
335
+ }, job.committed ? undefined : signal),
321
336
  validate,
337
+ ...(diffReviewOwner && {
338
+ diffReview: {
339
+ clear() {
340
+ validate();
341
+ diffReviews.release(diffReviewOwner);
342
+ },
343
+ retain(prepared) {
344
+ validate();
345
+ return diffReviews.retain(diffReviewOwner, prepared, signal);
346
+ },
347
+ },
348
+ }),
322
349
  request,
323
350
  emit: (kind, data, target = job.client) => emit(kind, data, target),
324
351
  debug: debug &&
@@ -382,7 +409,12 @@ export async function startServer(root, execute, hooks = {}) {
382
409
  };
383
410
  if (cancelled.has(`${client}:${id}`))
384
411
  job.controller.abort(new DOMException("Operation cancelled before dispatch", "AbortError"));
385
- const execution = makeExecution(job);
412
+ let diffReviewOwner;
413
+ if (operation === "diff.review" && peer.facts.mode === "tui" && peer.facts.hasUI) {
414
+ peer.diffReviewOwner ??= new AbortController();
415
+ diffReviewOwner = peer.diffReviewOwner;
416
+ }
417
+ const execution = makeExecution(job, diffReviewOwner);
386
418
  const kind = debug && debugOperation(operation);
387
419
  const waitForInspectionLog = kind === "inspect";
388
420
  const note = (outcome, current) => {
@@ -426,6 +458,8 @@ export async function startServer(root, execute, hooks = {}) {
426
458
  await logged;
427
459
  job.view.phase = "failed";
428
460
  job.view.error = remoteError(error);
461
+ if (diffReviewOwner)
462
+ job.controller.abort();
429
463
  if (job.committed)
430
464
  for (const id of new Set([client, ...job.peers])) {
431
465
  const affected = participants.get(id);
@@ -514,14 +548,7 @@ export async function startServer(root, execute, hooks = {}) {
514
548
  async function resumeContact(facts, disconnect) {
515
549
  const peer = requireParticipant(facts.id, true);
516
550
  const expiry = peer.expiry;
517
- const matchesSession = (old) => old.pid === facts.pid &&
518
- old.generation === facts.generation &&
519
- old.cwd === facts.cwd &&
520
- old.sessionId === facts.sessionId &&
521
- old.sessionFile === facts.sessionFile &&
522
- old.sessionDir === facts.sessionDir &&
523
- old.mode === facts.mode &&
524
- old.hasUI === facts.hasUI;
551
+ const matchesSession = (old) => sameDiffReviewBinding(old, facts);
525
552
  if (!expiry || contactState(peer) !== "expired" || peer.resumeFacts || !matchesSession(peer.facts))
526
553
  throw new Error("Client is not eligible to resume contact for this session.");
527
554
  const signal = disconnect ? AbortSignal.any([disconnect, expiry.signal]) : expiry.signal;
@@ -594,6 +621,7 @@ export async function startServer(root, execute, hooks = {}) {
594
621
  if (closedClients.has(id))
595
622
  return poll(peer, 0);
596
623
  peer.closing = true;
624
+ invalidateDiffReview(peer);
597
625
  participantsChanged();
598
626
  invalidateExpiry(peer);
599
627
  for (const waiting of [...pending.values()])
@@ -767,9 +795,12 @@ export async function startServer(root, execute, hooks = {}) {
767
795
  throw new Error("Client retirement ledger is full; stop and restart the service.");
768
796
  if (!processExists(params.pid))
769
797
  throw new Error("Client process is not alive.");
770
- for (const [id, peer] of participants)
771
- if (!processExists(peer.facts.pid) && !peer.callbacks.size)
798
+ for (const [id, peer] of participants) {
799
+ if (!processExists(peer.facts.pid) && !peer.callbacks.size) {
800
+ invalidateDiffReview(peer);
772
801
  participants.delete(id);
802
+ }
803
+ }
773
804
  if (!participants.has(params.id) && participants.size >= 64)
774
805
  throw new Error("Daemon client capacity reached.");
775
806
  const old = participants.get(params.id);
@@ -777,10 +808,12 @@ export async function startServer(root, execute, hooks = {}) {
777
808
  (old.facts.pid !== params.pid ||
778
809
  ((old.connected || old.suspected) && old.facts.generation !== params.generation)))
779
810
  throw new Error("Client identity collision.");
780
- if (old)
811
+ if (old) {
781
812
  invalidateExpiry(old);
813
+ invalidateDiffReview(old);
814
+ }
782
815
  participantsChanged();
783
- participants.set(params.id, {
816
+ const replacement = {
784
817
  facts: structuredClone(params),
785
818
  reviewDetails,
786
819
  reservations: old?.reservations,
@@ -792,16 +825,20 @@ export async function startServer(root, execute, hooks = {}) {
792
825
  suspected: false,
793
826
  seen: Date.now(),
794
827
  publishing: !old,
795
- });
828
+ };
829
+ participants.set(params.id, replacement);
796
830
  try {
797
831
  await savePeers();
798
832
  assertOwner();
799
833
  }
800
834
  catch (error) {
801
- if (old)
802
- participants.set(params.id, old);
803
- else
804
- participants.delete(params.id);
835
+ if (participants.get(params.id) === replacement) {
836
+ invalidateDiffReview(replacement);
837
+ if (old)
838
+ participants.set(params.id, old);
839
+ else
840
+ participants.delete(params.id);
841
+ }
805
842
  throw error;
806
843
  }
807
844
  const attached = requireParticipant(params.id, true);
@@ -819,6 +856,7 @@ export async function startServer(root, execute, hooks = {}) {
819
856
  ? next.sessionId === params.sessionId
820
857
  : params.sessionFile === undefined && next.cwd === params.cwd;
821
858
  if (matches) {
859
+ invalidateDiffReview(peer);
822
860
  participants.delete(id);
823
861
  closedClients.add(id);
824
862
  }
@@ -871,8 +909,11 @@ export async function startServer(root, execute, hooks = {}) {
871
909
  if (contactState(peer) === "expired")
872
910
  throw new ClientContactExpiredError();
873
911
  requireParticipant(params.facts.id);
874
- peer.facts = structuredClone(params.facts);
875
- const published = peer.facts;
912
+ const published = structuredClone(params.facts);
913
+ const bindingChanged = !sameDiffReviewBinding(old, published);
914
+ if (bindingChanged)
915
+ invalidateDiffReview(peer);
916
+ peer.facts = published;
876
917
  const unchanged = JSON.stringify(old) === JSON.stringify(published);
877
918
  if (!unchanged)
878
919
  participantsChanged();
@@ -880,8 +921,11 @@ export async function startServer(root, execute, hooks = {}) {
880
921
  await savePeers(undefined, unchanged);
881
922
  }
882
923
  catch (error) {
883
- if (peer.facts === published)
924
+ if (participants.get(published.id) === peer && peer.facts === published) {
884
925
  peer.facts = old;
926
+ if (bindingChanged)
927
+ invalidateDiffReview(peer);
928
+ }
885
929
  throw error;
886
930
  }
887
931
  await hooks.factsChanged?.();
@@ -1013,6 +1057,16 @@ export async function startServer(root, execute, hooks = {}) {
1013
1057
  return stop();
1014
1058
  throw new Error("Unknown daemon method.");
1015
1059
  }
1060
+ const diffReviewOwner = (client, generation) => {
1061
+ const peer = participants.get(client);
1062
+ if (peer &&
1063
+ peer.facts.generation === generation &&
1064
+ peer.facts.mode === "tui" &&
1065
+ peer.facts.hasUI &&
1066
+ contactState(peer) === "active" &&
1067
+ Date.now() - peer.seen <= 5_000)
1068
+ return peer.diffReviewOwner;
1069
+ };
1016
1070
  const respond = (response, status, value) => {
1017
1071
  let encoded = JSON.stringify(value);
1018
1072
  if (Buffer.byteLength(encoded) > MAX_MESSAGE_BYTES) {
@@ -1048,6 +1102,7 @@ export async function startServer(root, execute, hooks = {}) {
1048
1102
  "resume-contact",
1049
1103
  "startup.bootstrap",
1050
1104
  "state-wait",
1105
+ "diff-review-read",
1051
1106
  "foreground-stop",
1052
1107
  "upgrade-stop",
1053
1108
  ].includes(body.method)) {
@@ -1056,6 +1111,18 @@ export async function startServer(root, execute, hooks = {}) {
1056
1111
  if (response.destroyed)
1057
1112
  disconnect();
1058
1113
  }
1114
+ if (body.method === "diff-review-read" || body.method === "diff-review-close") {
1115
+ if (!published)
1116
+ throw new Error("Daemon readiness is not published.");
1117
+ assertOwner();
1118
+ if (!record(body.params))
1119
+ throw new Error("Invalid diff review request.");
1120
+ await handleDiffReviewRequest(body.method, body.params, admissionController?.signal, diffReviews, diffReviewOwner, assertOwner, (result) => {
1121
+ if (!response.destroyed)
1122
+ respond(response, 200, { result });
1123
+ });
1124
+ return;
1125
+ }
1059
1126
  const operation = handle(body.method, body.params, admissionController?.signal, body.reviewDetails === 1);
1060
1127
  if ([
1061
1128
  "attach",
@@ -1117,6 +1184,7 @@ export async function startServer(root, execute, hooks = {}) {
1117
1184
  if (!exited && (!peer.connected || Date.now() - peer.seen <= 5_000))
1118
1185
  continue;
1119
1186
  participationChanged ||= participates(peer);
1187
+ invalidateDiffReview(peer);
1120
1188
  peer.connected = false;
1121
1189
  peer.suspected = !exited;
1122
1190
  if (exited)
@@ -1204,6 +1272,7 @@ export async function startServer(root, execute, hooks = {}) {
1204
1272
  return closing;
1205
1273
  closing = (async () => {
1206
1274
  closed = true;
1275
+ diffReviews.close();
1207
1276
  for (const peer of participants.values()) {
1208
1277
  invalidateExpiry(peer);
1209
1278
  waiters.get(peer)?.changed();
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.15.1"
2
+ "version": "0.16.0"
3
3
  }
package/dist/index.ts CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  createSyncAttentionController,
5
5
  readStateForConfig,
6
6
  syncStateFingerprint
7
- } from "./chunks/chunk-YX6DCQ7P.ts";
7
+ } from "./chunks/chunk-5T4ZOHYF.ts";
8
8
  import {
9
9
  combineSignals,
10
10
  throwIfAborted
@@ -33,7 +33,7 @@ import {
33
33
  installPiDaemonHost,
34
34
  piDaemonClient,
35
35
  withPiDaemonClient
36
- } from "./chunks/chunk-EI2J5Z4Q.ts";
36
+ } from "./chunks/chunk-SPXEDJ2G.ts";
37
37
  import {
38
38
  configureSyncStatus,
39
39
  createSyncStatusPublisher,
@@ -47,7 +47,7 @@ import {
47
47
  } from "./chunks/chunk-R3SAMXB6.ts";
48
48
  import {
49
49
  safeTerminalText
50
- } from "./chunks/chunk-2JNFEZ3V.ts";
50
+ } from "./chunks/chunk-AMJRUXFT.ts";
51
51
 
52
52
  // src/sync/agent-policy.ts
53
53
  import {
@@ -433,12 +433,12 @@ function createStartupCheck(loaders, attention, timeoutMs = 3e4, publish) {
433
433
  // src/sync/sync-loaders.ts
434
434
  function createSyncLoaders(dependencies) {
435
435
  const loaders = {
436
- commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-ZR26OSBX.ts"))),
437
- inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-7OADBR57.ts"))),
438
- setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-J3YLBB6N.ts"))),
436
+ commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-4XHK5PVX.ts"))),
437
+ inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-TZ4EMSBN.ts"))),
438
+ setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-LJPEZONY.ts"))),
439
439
  snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import("./chunks/snapshot-ZUJJZCFW.ts"))),
440
440
  syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import("./chunks/sync-state-QIT64TKV.ts"))),
441
- operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-3K6WLPXY.ts")))
441
+ operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-QIQ3G66S.ts")))
442
442
  };
443
443
  return loaders;
444
444
  }
@@ -8,7 +8,7 @@ The `/sync` TUI manager uses Kit's public `ChoiceScreen` without search. It show
8
8
 
9
9
  The homepage shows setup/storage, cached remote observations, last applied state and relevant automatic-transfer permissions. It does not render scheduler owners, leases, request accounting or candidate limits. Recorded background phases and successful background-transfer timestamps are explicitly historical; neither replaces a fresh remote check. Missing records show **not yet observed**, and unreadable or invalid records show **Unknown**. Last applied does not invent a timestamp or direction.
10
10
 
11
- **View differences** remains an explicit read action. **History** offers repair only when the active WebDAV snapshot is missing from History. It discloses the temporary conditional-write probe and history update before asking for consent and revalidates the reviewed setup and remote head before changing history.
11
+ **View differences** and `/sync diff` share the same read-only comparison. TUI lists changed paths as **Local only**, **Remote only**, or **Different**. Select a file to load its unified diff (`− Local`, `+ Remote`). The review floats on terminals with at least 24 columns and five rows when opened; smaller terminals use the inline view. Escape returns to the selected file and filter; Ctrl+C closes the review. Binary, over-limit, and session files show a notice instead of text. If the retained comparison expires or the setup changes, reopen **View differences** to refresh. The comparison uses neither the last sync as a baseline nor transfer permission. RPC retains the summary and does not request file bodies. **History** offers repair only when the active WebDAV snapshot is missing from History. It discloses the temporary conditional-write probe and history update before asking for consent and revalidates the reviewed setup and remote head before changing history.
12
12
 
13
13
  The attention widget retains its labeled muted separator and one body row: **Open /sync to review** with the setup name. It remains passive, preserves collapse state and observation classification, and exposes detailed reasons through the manager and existing notifications. Session replacement, shutdown and stale asynchronous publication retain their existing cleanup guards.
14
14