@narumitw/pi-sync 0.69.1 → 0.70.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 (90) hide show
  1. package/CHANGELOG.md +11 -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
@@ -40,17 +40,17 @@ export class WebDavSyncBackend {
40
40
  this.registerChecksum(pointer.snapshot, pointer.sha256);
41
41
  return remoteHead(pointer, this.identity, object.etag);
42
42
  }
43
- async readSnapshot(reference, signal) {
43
+ async readSnapshot(reference, signal, maxBytes) {
44
44
  requireSnapshotReference(reference);
45
45
  const expectedChecksum = this.checksums.get(reference) ?? (await this.resolveChecksum(reference, signal));
46
- const object = await new WebDavClient(this.config, signal).getBuffer(snapshotPath(this.config, reference));
46
+ const object = await new WebDavClient(this.config, signal).getBuffer(snapshotPath(this.config, reference), maxBytes);
47
47
  throwIfAborted(signal);
48
48
  if (!object.value)
49
49
  throw new Error(`Snapshot not found: ${reference}`);
50
50
  if (!expectedChecksum || sha256(object.value) !== expectedChecksum) {
51
51
  throw new Error("Remote snapshot checksum mismatch.");
52
52
  }
53
- const snapshot = await decodeSnapshot(object.value, { signal });
53
+ const snapshot = await decodeSnapshot(object.value, { signal, maxOutputLength: maxBytes });
54
54
  if (snapshot.id !== reference || snapshot.profile !== this.config.destination.namespace) {
55
55
  throw new Error("Remote snapshot identity mismatch.");
56
56
  }
@@ -1,4 +1,5 @@
1
1
  import { XMLParser } from "fast-xml-parser";
2
+ import { SnapshotCaptureLimitError } from "../../snapshot/snapshot-capture-limit.js";
2
3
  import { ContinuousError, continuousFailure, retryAfter } from "../../sync/continuous-errors.js";
3
4
  import { throwIfAborted } from "../../sync/signals.js";
4
5
  const JSON_LIMIT = 1024 * 1024;
@@ -44,15 +45,24 @@ export class WebDavClient {
44
45
  }
45
46
  this.authorization = `Basic ${Buffer.from(`${config.profile.username}:${config.profile.password}`).toString("base64")}`;
46
47
  }
47
- async getBuffer(remotePath) {
48
- const response = await this.request(remotePath, { method: "GET" });
48
+ async getBuffer(remotePath, maxBytes) {
49
+ const response = await this.request(remotePath, {
50
+ method: "GET",
51
+ ...(maxBytes === undefined ? {} : { headers: { "accept-encoding": "identity" } }),
52
+ });
49
53
  if (response.status === 404) {
50
54
  await response.body?.cancel();
51
55
  return { missing: true };
52
56
  }
53
57
  await this.requireOk(response, "read");
58
+ const encoding = response.headers.get("content-encoding")?.toLowerCase();
59
+ if (maxBytes !== undefined && encoding && encoding !== "identity") {
60
+ await response.body?.cancel().catch(() => undefined);
61
+ throw new SnapshotCaptureLimitError();
62
+ }
63
+ const limit = Math.min(maxBytes ?? SNAPSHOT_LIMIT, SNAPSHOT_LIMIT);
54
64
  return {
55
- value: await readBounded(response, SNAPSHOT_LIMIT, "WebDAV response is too large"),
65
+ value: await readBounded(response, limit, () => maxBytes === undefined ? new Error("WebDAV response is too large") : new SnapshotCaptureLimitError()),
56
66
  etag: response.headers.get("etag") ?? undefined,
57
67
  missing: false,
58
68
  };
@@ -64,7 +74,7 @@ export class WebDavClient {
64
74
  return { missing: true };
65
75
  }
66
76
  await this.requireOk(response, "read");
67
- const bytes = await readBounded(response, JSON_LIMIT, "WebDAV JSON response is too large");
77
+ const bytes = await readBounded(response, JSON_LIMIT, () => new Error("WebDAV JSON response is too large"));
68
78
  try {
69
79
  return {
70
80
  value: JSON.parse(bytes.toString("utf8")),
@@ -136,7 +146,7 @@ export class WebDavClient {
136
146
  }
137
147
  if (response.status !== 207)
138
148
  await this.requireOk(response, "list collection");
139
- const xml = (await readBounded(response, XML_LIMIT, "WebDAV directory response is too large")).toString("utf8");
149
+ const xml = (await readBounded(response, XML_LIMIT, () => new Error("WebDAV directory response is too large"))).toString("utf8");
140
150
  try {
141
151
  const parsed = new XMLParser({
142
152
  removeNSPrefix: true,
@@ -213,7 +223,7 @@ export class WebDavClient {
213
223
  async requireOk(response, action) {
214
224
  if (response.ok)
215
225
  return;
216
- const body = (await readBounded(response, ERROR_LIMIT, "WebDAV error body is too large"))
226
+ const body = (await readBounded(response, ERROR_LIMIT, () => new Error("WebDAV error body is too large")))
217
227
  .toString("utf8")
218
228
  // biome-ignore lint/suspicious/noControlCharactersInRegex: Remote error text is untrusted terminal input.
219
229
  .replace(/[\u0000-\u001f\u007f-\u009f]/gu, " ")
@@ -257,11 +267,11 @@ function safeSegments(value) {
257
267
  }
258
268
  return segments;
259
269
  }
260
- async function readBounded(response, limit, message) {
270
+ async function readBounded(response, limit, limitError) {
261
271
  const length = Number(response.headers.get("content-length"));
262
272
  if (Number.isFinite(length) && length > limit) {
263
- await response.body?.cancel();
264
- throw new Error(message);
273
+ await response.body?.cancel().catch(() => undefined);
274
+ throw limitError();
265
275
  }
266
276
  if (!response.body)
267
277
  return Buffer.alloc(0);
@@ -275,7 +285,7 @@ async function readBounded(response, limit, message) {
275
285
  break;
276
286
  total += value.byteLength;
277
287
  if (total > limit)
278
- throw new Error(message);
288
+ throw limitError();
279
289
  chunks.push(Buffer.from(value));
280
290
  }
281
291
  }
@@ -283,6 +293,9 @@ async function readBounded(response, limit, message) {
283
293
  await reader.cancel().catch(() => undefined);
284
294
  throw error;
285
295
  }
296
+ finally {
297
+ reader.releaseLock();
298
+ }
286
299
  return Buffer.concat(chunks, total);
287
300
  }
288
301
  function parseEntry(value) {
@@ -14,13 +14,22 @@ export function sessionDirFromContext(ctx) {
14
14
  const getSessionDir = manager.getSessionDir;
15
15
  return typeof getSessionDir === "function" ? getSessionDir.call(manager) : undefined;
16
16
  }
17
- export async function configuredSessionDir() {
17
+ export async function configuredSessionDir(readFile) {
18
18
  let content;
19
+ let discovered = false;
19
20
  try {
20
- content = await fs.readFile(path.join(agentDir(), "settings.json"), "utf8");
21
+ const file = path.join(agentDir(), "settings.json");
22
+ if (readFile) {
23
+ await fs.lstat(file);
24
+ discovered = true;
25
+ content = (await readFile(file)).toString("utf8");
26
+ }
27
+ else {
28
+ content = await fs.readFile(file, "utf8");
29
+ }
21
30
  }
22
31
  catch (error) {
23
- if (error.code === "ENOENT")
32
+ if (!discovered && error.code === "ENOENT")
24
33
  return undefined;
25
34
  throw error;
26
35
  }
@@ -0,0 +1,99 @@
1
+ import { constants } from "node:fs";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ export class SnapshotCaptureLimitError extends Error {
5
+ constructor() {
6
+ super("Snapshot exceeds the file review capture limits.");
7
+ }
8
+ }
9
+ function unsafeSource() {
10
+ throw new Error("Snapshot source changed or has an unsafe filesystem layout.");
11
+ }
12
+ async function identifySource(file, signal) {
13
+ signal?.throwIfAborted();
14
+ const stat = await fs.lstat(file);
15
+ if (stat.isSymbolicLink() || (await fs.realpath(file)) !== file)
16
+ unsafeSource();
17
+ signal?.throwIfAborted();
18
+ return stat;
19
+ }
20
+ function requireSameSource(before, after) {
21
+ if (after.dev !== before.dev ||
22
+ after.ino !== before.ino ||
23
+ after.mode !== before.mode ||
24
+ after.nlink !== before.nlink ||
25
+ after.size !== before.size ||
26
+ after.mtimeMs !== before.mtimeMs ||
27
+ after.ctimeMs !== before.ctimeMs)
28
+ unsafeSource();
29
+ }
30
+ export function createSnapshotCaptureLimits(limits) {
31
+ let { bytes, entries, files } = limits;
32
+ function examineEntry() {
33
+ if (entries < 1)
34
+ throw new SnapshotCaptureLimitError();
35
+ entries--;
36
+ }
37
+ function admitFile(size) {
38
+ if (files < 1 || size > bytes)
39
+ throw new SnapshotCaptureLimitError();
40
+ files--;
41
+ bytes -= size;
42
+ }
43
+ return {
44
+ maxDepth: limits.depth,
45
+ examineEntry,
46
+ admitFile,
47
+ async readEntries(directory, signal) {
48
+ const absolute = path.resolve(directory);
49
+ const stat = await identifySource(absolute, signal);
50
+ if (!stat.isDirectory())
51
+ unsafeSource();
52
+ const handle = await fs.opendir(absolute);
53
+ try {
54
+ requireSameSource(stat, await identifySource(absolute, signal));
55
+ const result = [];
56
+ for (;;) {
57
+ signal?.throwIfAborted();
58
+ const entry = await handle.read();
59
+ if (!entry)
60
+ break;
61
+ examineEntry();
62
+ result.push(entry);
63
+ }
64
+ requireSameSource(stat, await identifySource(absolute, signal));
65
+ return result;
66
+ }
67
+ finally {
68
+ await handle.close();
69
+ }
70
+ },
71
+ async readFile(file, signal) {
72
+ signal?.throwIfAborted();
73
+ const absolute = path.resolve(file);
74
+ const stat = await identifySource(absolute, signal);
75
+ if (!stat.isFile() || stat.nlink !== 1)
76
+ unsafeSource();
77
+ admitFile(stat.size);
78
+ const handle = await fs.open(absolute, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
79
+ try {
80
+ requireSameSource(stat, await handle.stat());
81
+ requireSameSource(stat, await identifySource(absolute, signal));
82
+ const content = Buffer.alloc(stat.size);
83
+ for (let offset = 0; offset < content.length;) {
84
+ signal?.throwIfAborted();
85
+ const { bytesRead } = await handle.read(content, offset, content.length - offset, offset);
86
+ if (bytesRead === 0)
87
+ unsafeSource();
88
+ offset += bytesRead;
89
+ }
90
+ requireSameSource(stat, await handle.stat());
91
+ requireSameSource(stat, await identifySource(absolute, signal));
92
+ return content;
93
+ }
94
+ finally {
95
+ await handle.close();
96
+ }
97
+ },
98
+ };
99
+ }
@@ -4,6 +4,7 @@ import { promisify } from "node:util";
4
4
  import { createGunzip, gzip } from "node:zlib";
5
5
  import { throwIfAborted } from "../sync/signals.js";
6
6
  import { assertSnapshotExcludesDebugLog, requireLegacyTransferPolicy, validateSnapshotSelection, } from "../sync/sync-policy.js";
7
+ import { SnapshotCaptureLimitError } from "./snapshot-capture-limit.js";
7
8
  import { isSupportedSnapshotVersion } from "./snapshot-types.js";
8
9
  const VERSION = 1;
9
10
  const MAX_DECOMPRESSED_SNAPSHOT_BYTES = 512 * 1024 * 1024;
@@ -29,7 +30,9 @@ export async function decodeSnapshot(buffer, options = {}) {
29
30
  write(chunk, _encoding, callback) {
30
31
  total += chunk.byteLength;
31
32
  if (total > limit) {
32
- callback(new Error(`Decompressed snapshot exceeds the ${limit}-byte limit.`));
33
+ callback(options.maxOutputLength === undefined
34
+ ? new Error(`Decompressed snapshot exceeds the ${limit}-byte limit.`)
35
+ : new SnapshotCaptureLimitError());
33
36
  return;
34
37
  }
35
38
  chunks.push(Buffer.from(chunk));
@@ -0,0 +1,13 @@
1
+ export function snapshotDifferences(local, remote = []) {
2
+ const left = new Map(local.map((file) => [file.path, file]));
3
+ const right = new Map(remote.map((file) => [file.path, file]));
4
+ const differences = [];
5
+ for (const path of [...new Set([...left.keys(), ...right.keys()])].sort()) {
6
+ const local = left.get(path);
7
+ const remote = right.get(path);
8
+ if (local?.sha256 === remote?.sha256)
9
+ continue;
10
+ differences.push({ path, status: !local ? "remote-only" : !remote ? "local-only" : "different", local, remote });
11
+ }
12
+ return differences;
13
+ }
@@ -6,6 +6,7 @@ import path from "node:path";
6
6
  import { isDeniedPath, posixJoin, safeJoin, toPosix } from "../paths.js";
7
7
  import { agentDir, configuredSessionDir, expandSessionDir } from "./session-paths.js";
8
8
  import { assertAgentDirectorySettingsSize, MAX_AGENT_DIRECTORY_BYTES } from "./snapshot-bounds.js";
9
+ import { SnapshotCaptureLimitError } from "./snapshot-capture-limit.js";
9
10
  import { agentDirectoryAnchor, agentDirectoryPhysicalSessionPath, agentDirectorySessionRoot, } from "./snapshot-exclude-safety.js";
10
11
  import { sessionStorageRoot } from "./snapshot-paths.js";
11
12
  export { isDeniedPath } from "../paths.js";
@@ -74,7 +75,7 @@ const SCAN_FILE_BATCH_SIZE = 8;
74
75
  function materializeSnapshotFile(filePath, content) {
75
76
  return { path: filePath, contentBase64: content.toString("base64"), sha256: sha256(content) };
76
77
  }
77
- async function collectSnapshotFiles(options, materialize) {
78
+ async function collectSnapshotFiles(options, materialize, limits) {
78
79
  options.signal?.throwIfAborted();
79
80
  const include = effectiveInclude(options);
80
81
  const policy = { ...options, include };
@@ -83,9 +84,12 @@ async function collectSnapshotFiles(options, materialize) {
83
84
  const needsSessionConfig = syncSessions || !excluded("settings.json");
84
85
  const sessionDir = options.scope === "agent-directory"
85
86
  ? options.sessionDir
86
- : (options.sessionDir ?? (needsSessionConfig ? await configuredSessionDir() : undefined));
87
+ : (options.sessionDir ??
88
+ (needsSessionConfig
89
+ ? await configuredSessionDir(limits && ((file) => limits.readFile(file, options.signal)))
90
+ : undefined));
87
91
  options.signal?.throwIfAborted();
88
- const collectionOptions = { ...policy, sessionDir };
92
+ const collectionOptions = { ...policy, sessionDir, limits };
89
93
  const collected = options.scope === "agent-directory"
90
94
  ? await collectAgentDirectory(agentDir(), collectionOptions, materialize)
91
95
  : undefined;
@@ -117,8 +121,8 @@ export function snapshotWithObservedInventory(snapshot, observation) {
117
121
  scanInventories.set(refreshed, inventory);
118
122
  return refreshed;
119
123
  }
120
- export async function createSnapshot(profile, options = {}) {
121
- const { files, inventory, include, syncSessions } = await collectSnapshotFiles(options, materializeSnapshotFile);
124
+ export async function createSnapshot(profile, options = {}, limits) {
125
+ const { files, inventory, include, syncSessions } = await collectSnapshotFiles(options, materializeSnapshotFile, limits);
122
126
  options.signal?.throwIfAborted();
123
127
  const selection = selectionForSnapshot(include, options.exclude, options);
124
128
  const snapshot = {
@@ -152,11 +156,11 @@ export async function collectFiles(root, options = {}, excluded = compileSyncPol
152
156
  return collectSelectedFiles(root, options, excluded, materializeSnapshotFile);
153
157
  }
154
158
  async function collectSelectedFiles(root, options, excluded, materialize) {
155
- const signal = options.signal;
156
- const collection = { signal, excluded, materialize };
159
+ const { signal, limits } = options;
160
+ const collection = { signal, excluded, materialize, limits };
157
161
  signal?.throwIfAborted();
158
162
  const results = [];
159
- const entries = await fs.readdir(root, { withFileTypes: true });
163
+ const entries = await (limits ? limits.readEntries(root, signal) : fs.readdir(root, { withFileTypes: true }));
160
164
  signal?.throwIfAborted();
161
165
  const selection = syncIncludeSelection(effectiveInclude(options));
162
166
  const selectedFiles = new Set(selection.builtIns);
@@ -180,15 +184,21 @@ async function collectSelectedFiles(root, options, excluded, materialize) {
180
184
  await collectIncludedPath(results, root, relativePath, collection);
181
185
  }
182
186
  if (selection.sessions && !excluded("sessions")) {
187
+ const sessionRoot = sessionStorageRoot(root, options.sessionDir);
188
+ let discovered = false;
183
189
  try {
184
- await collectDirectory(results, sessionStorageRoot(root, options.sessionDir), "", {
190
+ if (limits) {
191
+ await fs.lstat(sessionRoot);
192
+ discovered = true;
193
+ }
194
+ await collectDirectory(results, sessionRoot, "", {
185
195
  ...collection,
186
196
  sessionsOnly: true,
187
197
  virtualPrefix: "sessions",
188
198
  });
189
199
  }
190
200
  catch (error) {
191
- if (error.code !== "ENOENT")
201
+ if (discovered || error.code !== "ENOENT")
192
202
  throw error;
193
203
  }
194
204
  }
@@ -294,7 +304,7 @@ export async function scanAgentDirectoryInventory(root, options, pendingStateEnt
294
304
  return (await collectAgentDirectory(root, options, undefined, pendingStateEntry)).inventory;
295
305
  }
296
306
  async function collectAgentDirectory(root, options, materialize, pendingStateEntry) {
297
- const signal = options.signal;
307
+ const { signal, limits } = options;
298
308
  const excluded = compileSyncPolicyExclude(options);
299
309
  const canTraverse = compileSyncPolicyTraversal(options);
300
310
  const sessionDir = options.sessionDir ?? (await agentDirectoryConfiguredSessionDir(signal, root));
@@ -306,12 +316,15 @@ async function collectAgentDirectory(root, options, materialize, pendingStateEnt
306
316
  const routingDirectories = new Set();
307
317
  let bytes = 0;
308
318
  async function walk(directory, prefix, sessions) {
319
+ if (limits && prefix && prefix.split("/").length >= limits.maxDepth)
320
+ throw new SnapshotCaptureLimitError();
309
321
  if (!directory.stat.isDirectory())
310
322
  changedScan();
311
323
  directories.push(directory);
312
324
  const children = [];
313
325
  for await (const entry of await fs.opendir(directory.absolute)) {
314
326
  signal?.throwIfAborted();
327
+ limits?.examineEntry();
315
328
  const absolute = path.join(directory.absolute, entry.name);
316
329
  entries.set(absolute, "unreviewed");
317
330
  const allowance = pendingStateEntry !== undefined && entries.has(pendingStateEntry) ? 1 : 0;
@@ -329,6 +342,8 @@ async function collectAgentDirectory(root, options, materialize, pendingStateEnt
329
342
  continue;
330
343
  if (!entry.isDirectory() && sessions && !isSessionFilePath(snapshotPath))
331
344
  continue;
345
+ if (limits && !entry.isDirectory() && snapshotPath.split("/").length > limits.maxDepth)
346
+ throw new SnapshotCaptureLimitError();
332
347
  const candidate = await identify(path.join(directory.absolute, entry.name), path.join(directory.canonical, entry.name), signal);
333
348
  if (entry.isDirectory()) {
334
349
  if (!excluded(snapshotPath))
@@ -345,6 +360,7 @@ async function collectAgentDirectory(root, options, materialize, pendingStateEnt
345
360
  throw new Error("Agent directory exceeds the 64 MiB scan byte bound.");
346
361
  if (candidates.length >= MAX_AGENT_DIRECTORY_FILES)
347
362
  throw new Error("Agent directory exceeds the scan file bound.");
363
+ limits?.admitFile(candidate.stat.size);
348
364
  entries.set(candidate.absolute, "file");
349
365
  candidates.push({ ...candidate, snapshotPath });
350
366
  }
@@ -420,8 +436,10 @@ async function collectIncludedPath(results, root, relativePath, options) {
420
436
  const { signal } = options;
421
437
  signal?.throwIfAborted();
422
438
  const absolutePath = safeJoin(root, relativePath);
439
+ let discovered = false;
423
440
  try {
424
441
  const stat = await fs.lstat(absolutePath);
442
+ discovered = true;
425
443
  signal?.throwIfAborted();
426
444
  if (stat.isFile())
427
445
  await addFile(results, root, relativePath, relativePath, options);
@@ -429,10 +447,12 @@ async function collectIncludedPath(results, root, relativePath, options) {
429
447
  await collectDirectory(results, root, relativePath, options);
430
448
  }
431
449
  catch (error) {
432
- if (error.code !== "ENOENT")
450
+ if ((options.limits && discovered) || error.code !== "ENOENT")
433
451
  throw error;
434
452
  if (!relativePath.includes("/")) {
435
- const entries = await fs.readdir(root, { withFileTypes: true });
453
+ const entries = await (options.limits
454
+ ? options.limits.readEntries(root, signal)
455
+ : fs.readdir(root, { withFileTypes: true }));
436
456
  signal?.throwIfAborted();
437
457
  const entry = selectTopLevelFileEntry(entries, relativePath);
438
458
  if (entry)
@@ -442,9 +462,14 @@ async function collectIncludedPath(results, root, relativePath, options) {
442
462
  }
443
463
  async function collectDirectory(results, root, relativeDirectory, options) {
444
464
  options.signal?.throwIfAborted();
465
+ const prefix = posixJoin(options.virtualPrefix ?? "", relativeDirectory);
466
+ if (options.limits && prefix && prefix.split("/").length >= options.limits.maxDepth)
467
+ throw new SnapshotCaptureLimitError();
445
468
  const absoluteDirectory = path.join(root, relativeDirectory);
446
- options.signal?.throwIfAborted();
447
- for (const entry of await fs.readdir(absoluteDirectory, { withFileTypes: true })) {
469
+ const entries = await (options.limits
470
+ ? options.limits.readEntries(absoluteDirectory, options.signal)
471
+ : fs.readdir(absoluteDirectory, { withFileTypes: true }));
472
+ for (const entry of entries) {
448
473
  options.signal?.throwIfAborted();
449
474
  const relativePath = relativeDirectory ? posixJoin(relativeDirectory, entry.name) : entry.name;
450
475
  const snapshotPath = options.virtualPrefix ? posixJoin(options.virtualPrefix, relativePath) : relativePath;
@@ -458,12 +483,14 @@ async function collectDirectory(results, root, relativeDirectory, options) {
458
483
  }
459
484
  }
460
485
  }
461
- async function addFile(results, root, relativePath, snapshotPath, { signal, materialize }) {
486
+ async function addFile(results, root, relativePath, snapshotPath, { signal, materialize, limits }) {
462
487
  signal?.throwIfAborted();
463
488
  if (!isSafeSnapshotPath(snapshotPath))
464
489
  return;
490
+ if (limits && snapshotPath.split("/").length > limits.maxDepth)
491
+ throw new SnapshotCaptureLimitError();
465
492
  const absolutePath = safeJoin(root, relativePath);
466
- const content = await fs.readFile(absolutePath, { signal });
493
+ const content = await (limits ? limits.readFile(absolutePath, signal) : fs.readFile(absolutePath, { signal }));
467
494
  signal?.throwIfAborted();
468
495
  results.push(materialize(snapshotPath, content));
469
496
  }
@@ -0,0 +1,210 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { DIFF_REVIEW_CATALOG_BYTES, DIFF_REVIEW_CATALOG_FILES, DIFF_REVIEW_PATH_DEPTH, isDiffReviewPath, } from "../../diff-review-protocol.js";
3
+ import { DIFF_REVIEW_RETAINED_BYTES } from "../../diff-review-store.js";
4
+ import { OWNERSHIP_CLEANUP_REQUIRED, record } from "../../protocol.js";
5
+ import { configFromSettings, syncCheckConfigFingerprint } from "../settings/config.js";
6
+ import { readLocalConfigForDiagnostics } from "../settings/config-file.js";
7
+ import { assertNoRetiredRuleJournal } from "../settings/retired-ignore-recovery.js";
8
+ import { validateSettingsDocument } from "../settings/settings-validation.js";
9
+ import { createSnapshotCaptureLimits, SnapshotCaptureLimitError } from "../snapshot/snapshot-capture-limit.js";
10
+ import { snapshotDifferences } from "../snapshot/snapshot-difference.js";
11
+ import { withStateDirectoryAccess } from "../state/state-directory.js";
12
+ import { formatDiffCounts, formatDiffRow } from "../ui/sync-format.js";
13
+ import { safeTerminalText, snapshotPathLabel } from "../ui/terminal-text.js";
14
+ import { DIFF_REVIEW_FILE_BASE64_CHARS, DIFF_REVIEW_FILE_BYTES, DIFF_REVIEW_LIMIT_NOTICE, } from "./diff-review-preview.js";
15
+ import { sameLocalFields } from "./local-fields.js";
16
+ import { MAX_AGENT_DIRECTORY_ENTRIES, MAX_AGENT_DIRECTORY_FILES } from "./sync-policy.js";
17
+ import { captureDiffComparison } from "./sync-queries.js";
18
+ const CAPTURE_MS = 30_000;
19
+ const CAPTURE_BYTES = 64 * 1024 * 1024;
20
+ const CAPTURE_LIMIT = "The comparison exceeds the file review limits.";
21
+ const RETAINED_LIMIT = "There is not enough review memory for this comparison.";
22
+ const FAILURE = "Could not capture file differences. Check the selected setup and storage, then reopen the review.";
23
+ const SESSION_NOTICE = "Session and JSONL files are metadata-only. Their contents were not returned.";
24
+ const FIELD_NOTICE = "The local and remote settings field policies differ. Settings contents were not returned.";
25
+ function unavailable(message) {
26
+ return { kind: "unavailable", message };
27
+ }
28
+ function inputFor(change, fieldPoliciesMatch) {
29
+ const path = change.path.toLowerCase();
30
+ if (path.startsWith("sessions/") || path.endsWith(".jsonl"))
31
+ return { notice: SESSION_NOTICE };
32
+ if (path === "settings.json" && !fieldPoliciesMatch)
33
+ return { notice: FIELD_NOTICE };
34
+ const local = change.local?.contentBase64;
35
+ const remote = change.remote?.contentBase64;
36
+ if ([local, remote].some((value) => (value?.length ?? 0) > DIFF_REVIEW_FILE_BASE64_CHARS))
37
+ return { notice: DIFF_REVIEW_LIMIT_NOTICE };
38
+ const left = local === undefined ? undefined : Buffer.from(local, "base64");
39
+ const right = remote === undefined ? undefined : Buffer.from(remote, "base64");
40
+ if (Math.max(left?.length ?? 0, right?.length ?? 0) > DIFF_REVIEW_FILE_BYTES)
41
+ return { notice: DIFF_REVIEW_LIMIT_NOTICE };
42
+ return { local: left, remote: right };
43
+ }
44
+ function copyText(value) {
45
+ return Buffer.from(value, "utf16le").toString("utf16le");
46
+ }
47
+ function boundedSummary(reason, comparison, counts, changes) {
48
+ const { local, remote, warnings, selectionState } = comparison;
49
+ const headline = `${reason} File previews are unavailable. Summary only.`;
50
+ const essential = [
51
+ headline,
52
+ ...counts,
53
+ ...(selectionState?.kind === "different" ? ["Remote included content differs from this setup."] : []),
54
+ ...warnings,
55
+ ];
56
+ let used = Buffer.byteLength(JSON.stringify(unavailable(essential.join("\n"))));
57
+ let omitted = !changes;
58
+ const truncation = "More summary details were omitted to stay within the overview limits.";
59
+ const add = (line) => {
60
+ const size = Buffer.byteLength(JSON.stringify(line));
61
+ if (used + size + truncation.length + 2 > DIFF_REVIEW_CATALOG_BYTES) {
62
+ omitted = true;
63
+ return false;
64
+ }
65
+ used += size;
66
+ essential.push(line);
67
+ return true;
68
+ };
69
+ for (const line of comparison.lines) {
70
+ if (!warnings.includes(line) && !add(safeTerminalText(line)))
71
+ break;
72
+ }
73
+ if (changes) {
74
+ if (!remote)
75
+ add(`Remote is empty. Local push would upload: ${safeTerminalText(local.id)}`);
76
+ else if (!changes.length)
77
+ add("No file differences.");
78
+ for (const change of changes) {
79
+ if (!isDiffReviewPath(change.path)) {
80
+ omitted = true;
81
+ continue;
82
+ }
83
+ if (!add(remote ? formatDiffRow(change) : `Add: ${snapshotPathLabel(change.path)}`))
84
+ break;
85
+ }
86
+ }
87
+ if (omitted)
88
+ essential.push(truncation);
89
+ return unavailable(essential.join("\n"));
90
+ }
91
+ export function prepareDiffReview(comparison, staleSetup) {
92
+ const { local, remote } = comparison;
93
+ const counts = remote ? formatDiffCounts(local, remote) : [`local: ${local.files.length} files`, "Remote is empty."];
94
+ if (local.files.length + (remote?.files.length ?? 0) > 2 * MAX_AGENT_DIRECTORY_FILES)
95
+ return { unavailable: boundedSummary(CAPTURE_LIMIT, comparison, counts) };
96
+ const changes = snapshotDifferences(local.files, remote?.files);
97
+ const fallback = (reason) => boundedSummary(reason, comparison, counts, changes);
98
+ if (changes.length > DIFF_REVIEW_CATALOG_FILES)
99
+ return { unavailable: fallback(CAPTURE_LIMIT) };
100
+ const lines = [
101
+ ...comparison.lines.map(safeTerminalText),
102
+ ...counts,
103
+ ...(changes.length ? [] : ["No file differences."]),
104
+ "Read-only comparison. − Local, + Remote. Neither side is a proposed transfer.",
105
+ ].map(copyText);
106
+ const files = [];
107
+ const inventory = { kind: "review", id: randomUUID(), lines, files };
108
+ const rows = new Map();
109
+ let catalogBytes = Buffer.byteLength(JSON.stringify(inventory));
110
+ if (catalogBytes > DIFF_REVIEW_CATALOG_BYTES)
111
+ return { unavailable: fallback(CAPTURE_LIMIT) };
112
+ let retainedBytes = 0;
113
+ const fieldPoliciesMatch = !remote || sameLocalFields(local.localFields ?? [], remote.localFields ?? []);
114
+ for (const change of changes) {
115
+ const { path, status } = change;
116
+ if (!isDiffReviewPath(path))
117
+ return { unavailable: fallback(CAPTURE_LIMIT) };
118
+ const file = { id: randomUUID(), path: copyText(path), status };
119
+ catalogBytes += Buffer.byteLength(JSON.stringify(file)) + 1;
120
+ if (catalogBytes > DIFF_REVIEW_CATALOG_BYTES)
121
+ return { unavailable: fallback(CAPTURE_LIMIT) };
122
+ const input = inputFor(change, fieldPoliciesMatch);
123
+ if (!("notice" in input))
124
+ retainedBytes += (input.local?.length ?? 0) + (input.remote?.length ?? 0);
125
+ files.push(file);
126
+ rows.set(file.id, input);
127
+ if (retainedBytes + 2 * catalogBytes + 512 * files.length > DIFF_REVIEW_RETAINED_BYTES)
128
+ return { unavailable: fallback(RETAINED_LIMIT) };
129
+ }
130
+ return {
131
+ prepared: { inventory, rows, bytes: retainedBytes + 2 * catalogBytes + 512 * files.length, staleSetup },
132
+ fallback,
133
+ };
134
+ }
135
+ function readDiffSetup(root, setup, signal) {
136
+ return withStateDirectoryAccess(async () => {
137
+ signal.throwIfAborted();
138
+ assertNoRetiredRuleJournal(root);
139
+ const observation = await readLocalConfigForDiagnostics(root);
140
+ signal.throwIfAborted();
141
+ if (!observation?.stillCurrent())
142
+ throw new Error("Sync setup is unavailable or changed.");
143
+ assertNoRetiredRuleJournal(root);
144
+ return configFromSettings(validateSettingsDocument(observation.document.parsed), setup);
145
+ });
146
+ }
147
+ function setupFreshness(root, setup, fingerprint) {
148
+ return async (signal) => {
149
+ try {
150
+ const current = await readDiffSetup(root, setup, signal);
151
+ return syncCheckConfigFingerprint(current) !== fingerprint;
152
+ }
153
+ catch {
154
+ return true;
155
+ }
156
+ };
157
+ }
158
+ export async function captureDiffReview(ctx, payload, execution) {
159
+ if (!execution.diffReview || ctx.mode !== "tui" || !ctx.hasUI)
160
+ throw new Error("File previews require a live TUI client.");
161
+ if (!record(payload) ||
162
+ Object.keys(payload).some((key) => key !== "setup" && key !== "fingerprint") ||
163
+ (payload.setup !== undefined && (typeof payload.setup !== "string" || payload.setup.length > 512)) ||
164
+ (payload.fingerprint !== undefined &&
165
+ (typeof payload.fingerprint !== "string" || !/^[0-9a-f]{64}$/u.test(payload.fingerprint) || !payload.setup)))
166
+ throw new Error("Invalid diff review request.");
167
+ execution.diffReview.clear();
168
+ const setup = typeof payload.setup === "string" ? payload.setup : undefined;
169
+ const selectedSetup = payload.fingerprint === undefined ? setup : undefined;
170
+ const deadline = AbortSignal.timeout(CAPTURE_MS);
171
+ const signal = AbortSignal.any([execution.signal, deadline]);
172
+ const changed = () => unavailable("The sync setup changed. Reopen the review.");
173
+ try {
174
+ const config = await readDiffSetup(execution.root, selectedSetup, signal);
175
+ execution.validate();
176
+ signal.throwIfAborted();
177
+ const fingerprint = syncCheckConfigFingerprint(config);
178
+ if (payload.fingerprint !== undefined && (setup !== config.setupName || payload.fingerprint !== fingerprint))
179
+ return changed();
180
+ const staleSetup = setupFreshness(execution.root, selectedSetup, fingerprint);
181
+ const local = createSnapshotCaptureLimits({
182
+ bytes: CAPTURE_BYTES,
183
+ entries: MAX_AGENT_DIRECTORY_ENTRIES,
184
+ files: MAX_AGENT_DIRECTORY_FILES + 1,
185
+ depth: DIFF_REVIEW_PATH_DEPTH,
186
+ });
187
+ const comparison = await withStateDirectoryAccess(() => captureDiffComparison(ctx, config, signal, undefined, { local, remoteBytes: CAPTURE_BYTES }));
188
+ execution.validate();
189
+ const stale = await staleSetup(signal);
190
+ execution.validate();
191
+ signal.throwIfAborted();
192
+ if (stale)
193
+ return changed();
194
+ const result = prepareDiffReview(comparison, staleSetup);
195
+ if ("unavailable" in result)
196
+ return result.unavailable;
197
+ return execution.diffReview.retain(result.prepared) ? result.prepared.inventory : result.fallback(RETAINED_LIMIT);
198
+ }
199
+ catch (error) {
200
+ if (record(error) && error.code === OWNERSHIP_CLEANUP_REQUIRED) {
201
+ throw Object.assign(new Error("Daemon ownership cleanup is required."), { code: OWNERSHIP_CLEANUP_REQUIRED });
202
+ }
203
+ execution.validate();
204
+ if (deadline.aborted)
205
+ return unavailable("Capturing the comparison timed out. No file previews are available.");
206
+ if (error instanceof SnapshotCaptureLimitError)
207
+ return unavailable(`${CAPTURE_LIMIT} The summary could not be completed within those limits.`);
208
+ return unavailable(FAILURE);
209
+ }
210
+ }