@narumitw/pi-sync 0.66.0 → 0.67.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 (31) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +10 -1
  3. package/dist/chunks/{command-handler-44EFGPWH.ts → command-handler-SQC2L2FJ.ts} +2 -2
  4. package/dist/chunks/{manager-ui-CVZLMXJ5.ts → manager-ui-DWOMAJKE.ts} +116 -3
  5. package/dist/chunks/manager-ui-DWOMAJKE.ts.map +7 -0
  6. package/dist/daemon/dist/engine/ignore/ignore-edit.js +2 -2
  7. package/dist/daemon/dist/engine/ignore/ignore-settings.js +2 -1
  8. package/dist/daemon/dist/engine/settings/config-file.js +3 -0
  9. package/dist/daemon/dist/engine/settings/config.js +5 -5
  10. package/dist/daemon/dist/engine/settings/settings-management.js +6 -1
  11. package/dist/daemon/dist/engine/settings/settings-validation.js +21 -2
  12. package/dist/daemon/dist/engine/sync/continuous-errors.js +6 -0
  13. package/dist/daemon/dist/engine/sync/continuous-sync.js +4 -2
  14. package/dist/daemon/dist/engine/sync/ignore-adoption.js +9 -0
  15. package/dist/daemon/dist/engine/sync/merge-apply.js +18 -1
  16. package/dist/daemon/dist/engine/sync/merged-sync.js +36 -4
  17. package/dist/daemon/dist/engine/sync/push-review.js +33 -0
  18. package/dist/daemon/dist/engine/sync/sync-mutations.js +38 -48
  19. package/dist/daemon/dist/engine/sync/sync-rollback.js +16 -2
  20. package/dist/daemon/dist/engine/sync/transfer-freshness.js +3 -2
  21. package/dist/daemon/dist/engine/sync/transfer-size-limits.js +92 -0
  22. package/dist/daemon/package.json +1 -1
  23. package/dist/index.ts +1 -1
  24. package/docs/daemon-migration.md +6 -0
  25. package/docs/tui-contract.md +4 -3
  26. package/package.json +2 -2
  27. package/skills/configure-pi-sync/SKILL.md +1 -1
  28. package/skills/configure-pi-sync/references/configuration.md +33 -6
  29. package/src/ui/settings-ui.ts +128 -4
  30. package/dist/chunks/manager-ui-CVZLMXJ5.ts.map +0 -7
  31. /package/dist/chunks/{command-handler-44EFGPWH.ts.map → command-handler-SQC2L2FJ.ts.map} +0 -0
@@ -0,0 +1,92 @@
1
+ import { parentPaths } from "../paths.js";
2
+ import { filterSnapshotForConfigPolicy } from "../snapshot/snapshot.js";
3
+ import { snapshotBase64Size } from "../snapshot/snapshot-payload.js";
4
+ import { snapshotPathLabel } from "../ui/terminal-text.js";
5
+ import { TransferSizeError } from "./continuous-errors.js";
6
+ const MIB = 1024 ** 2;
7
+ const MAX_FINDINGS = 8;
8
+ export function transferSizeLimitsEnabled(config) {
9
+ return config.maxFileSizeMiB !== undefined || config.maxDirectorySizeMiB !== undefined;
10
+ }
11
+ export function selectedPublicationImage(snapshot, config, sessionDir) {
12
+ return {
13
+ side: "Remote",
14
+ files: filterSnapshotForConfigPolicy(snapshot, config, { sessionDir }).files,
15
+ ignoreRules: snapshot.ignoreRules,
16
+ };
17
+ }
18
+ export function selectedPullImage(incoming, local, protectedPaths, ignoreRules) {
19
+ return {
20
+ side: "Local",
21
+ files: protectedPaths.size
22
+ ? [
23
+ ...incoming.files.filter((file) => !protectedPaths.has(file.path)),
24
+ ...local.files.filter((file) => protectedPaths.has(file.path)),
25
+ ]
26
+ : incoming.files,
27
+ ignoreRules,
28
+ };
29
+ }
30
+ function compareFindings(a, b) {
31
+ if (a.side !== b.side)
32
+ return a.side < b.side ? -1 : 1;
33
+ if (a.path !== b.path)
34
+ return a.path < b.path ? -1 : 1;
35
+ return a.kind === b.kind ? 0 : a.kind < b.kind ? -1 : 1;
36
+ }
37
+ export function transferSizeDetails(config, images) {
38
+ if (!transferSizeLimitsEnabled(config))
39
+ return;
40
+ const fileLimit = (config.maxFileSizeMiB ?? Infinity) * MIB;
41
+ const directoryLimit = (config.maxDirectorySizeMiB ?? Infinity) * MIB;
42
+ const findings = [];
43
+ let count = 0;
44
+ for (const { side, files, ignoreRules } of images) {
45
+ const directories = new Map();
46
+ const seen = new Set();
47
+ const measure = (path, size, kind, limit) => {
48
+ if (size <= limit)
49
+ return;
50
+ count++;
51
+ const finding = { side, path, size, kind, limit };
52
+ if (findings.length === MAX_FINDINGS && compareFindings(finding, findings[MAX_FINDINGS - 1]) >= 0)
53
+ return;
54
+ findings.push(finding);
55
+ findings.sort(compareFindings);
56
+ if (findings.length > MAX_FINDINGS)
57
+ findings.pop();
58
+ };
59
+ const measureFile = (path, size) => {
60
+ if (seen.has(path))
61
+ return;
62
+ seen.add(path);
63
+ measure(path, size, "file", fileLimit);
64
+ if (directoryLimit !== Infinity)
65
+ for (const parent of parentPaths(path))
66
+ directories.set(parent, (directories.get(parent) ?? 0) + size);
67
+ };
68
+ if (ignoreRules)
69
+ measureFile(ignoreRules.filename, Buffer.byteLength(ignoreRules.text, "utf8"));
70
+ for (const file of files)
71
+ measureFile(file.path, snapshotBase64Size(file.contentBase64, file.path));
72
+ for (const [path, size] of directories)
73
+ measure(path, size, "directory", directoryLimit);
74
+ }
75
+ if (!count)
76
+ return;
77
+ const omitted = count - findings.length;
78
+ return [
79
+ ...findings.map(({ path, side, size, kind, limit }) => {
80
+ const label = JSON.stringify(snapshotPathLabel(path.slice(0, 160))).slice(1, -1);
81
+ const shortened = path.length > 160 || label.length > 240;
82
+ return `${side} ${kind} "${label.slice(0, 240)}${shortened ? "…" : ""}": ${size} bytes (limit ${limit} bytes).`;
83
+ }),
84
+ ...(omitted ? [`${omitted} additional ${omitted === 1 ? "finding" : "findings"} omitted.`] : []),
85
+ `Use /sync diff, adjust ${config.pathPolicy === "ignore-file" ? ".syncignore (or your configured rule file)" : "exclusions in /sync → Settings"}, then review a Push or Pull.`,
86
+ ].join(" ");
87
+ }
88
+ export function requireTransferSize(config, ...images) {
89
+ const details = transferSizeDetails(config, images);
90
+ if (details)
91
+ throw new TransferSizeError(`Transfer blocked by size limits. ${details}`);
92
+ }
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.12.0"
2
+ "version": "0.13.0"
3
3
  }
package/dist/index.ts CHANGED
@@ -334,7 +334,7 @@ function createStartupCheck(loaders, attention, timeoutMs = 3e4, publish) {
334
334
  // src/sync/sync-loaders.ts
335
335
  function createSyncLoaders(dependencies) {
336
336
  const loaders = {
337
- commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-44EFGPWH.ts"))),
337
+ commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-SQC2L2FJ.ts"))),
338
338
  inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-NBBTSMKR.ts"))),
339
339
  setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-644T6KHG.ts"))),
340
340
  snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import("./chunks/snapshot-ZUJJZCFW.ts"))),
@@ -68,6 +68,8 @@ Before the first daemon-owned transfer, close or upgrade every older Pi process
68
68
 
69
69
  Backend formats, `pi-sync.json`, `pi-sync/`, `.pisync/`, backups, and journals remain owned by the extracted engine. Legacy directory migration remains explicit. Coexisting or unsafe state roots must be reconciled without merging or deleting evidence automatically.
70
70
 
71
+ Before enabling [transfer size limits](../skills/configure-pi-sync/references/configuration.md#transfer-size-limits), make sure the running owner supports both saving and enforcing the limits. A healthy `status` handshake alone does not establish that support. If an old owner remains after an update or an in-place rebuild, use the exit checks above before reloading Pi. Upgrade or close all older clients using that agent directory. Enabling a limit requires version 9 for the entire local settings document, which older processes refuse. It does not change the IPC protocol or remote snapshots.
72
+
71
73
  ## Lifetime is not consent
72
74
 
73
75
  Old Continuous consent was limited to an open Pi session. Existing Automatic, Autonomous, and Continuous defaults stay unchanged. When no registered live client PID remains for that canonical root and no valid explicit after-exit grant covers the active setup, a fixed 30-second grace period starts. Explicit CLI start without clients follows the same policy. Live passive, disconnected, publishing, and orderly retired PIDs keep the owner alive; detach, heartbeat loss, and an empty active-participant list do not prove process exit. `/reload`, `/new`, fork, and resume retain protection while their Pi process lives. A client arriving before shutdown becomes final cancels automatic exit. No new setting, environment variable, or keep-alive flag is added.
@@ -145,6 +147,10 @@ Before rollback:
145
147
  65,536 bytes because it keeps all other fields when revoking grants. Builds with the old
146
148
  65,536-byte limit cannot read that file. Preserve it and use a build that supports the larger
147
149
  file. Do not delete it or restore an older copy to make the rollback work.
150
+ 5. Check settings compatibility. Version 9 remains after both transfer limits are cleared. Keep a
151
+ compatible owner; do not relabel the document as version 8 or replace it with older bytes to
152
+ bypass the check. Keep journals and backups and verify the local and remote snapshot IDs before
153
+ retrying uncertain work.
148
154
 
149
155
  Operation retries are instance-bound and deduplicated. An expired result or old instance requires journal reconciliation, not blind replay. A full bounded result ledger requires an explicit drained restart.
150
156
 
@@ -33,11 +33,12 @@ All settings are private to this device. There are no project overrides. Default
33
33
  | Manage storage connections | `storageConnections` | Shared by named setups | Existing affected-setup review; changes future operations |
34
34
  | Merge settings fields | `sync.mergeSettings`, false | Current setup | Immediate save; opt-in merge on subsequent sync with a verified ancestor |
35
35
  | Content merge / partial progress | `sync.mergeContent`, `sync.partialSync`, false/false | Current setup | Explicit compatibility review and atomic save; Off, Merge only, Merge + partial, Partial only preserve all combinations |
36
+ | Max file size / Max directory size | `sync.maxFileSizeMiB`, `sync.maxDirectorySizeMiB`, both absent | Current setup | Independent inputs; review before upgrading the settings document to version 9; subsequent transfers only. See [transfer size limits](../skills/configure-pi-sync/references/configuration.md#transfer-size-limits). |
36
37
  | Skip secret scan | `skipSecretScan`, false | All setups | Immediate save; subsequent manual/automatic pushes; Diagnostics still scans |
37
38
  | Show sync status | `showStatus`, true | All setups | Immediate save and immediate status visibility change; notifications/widgets remain |
38
39
  | Debug mode | `debug`, false | All setups | Immediate save; Pi logging and timing display use the next session start in TUI/RPC; daemon log uses the next owner, job, or Continuous sync cycle boundary |
39
40
 
40
- Opening foreground Settings cancels and drains startup work. Simple changes report saving, then one setting-specific confirmation or an error in Pi's notifications. Back does not undo successful saves; cancelling a draft or compatibility review leaves that change unsaved. A failed save retains the previous document and effective/displayed value. Completed transfers are never undone by changing a preference.
41
+ Opening foreground Settings cancels and drains startup work. Simple changes report saving, then one setting-specific confirmation or an error in Pi's notifications. Back does not undo successful saves; cancelling a draft or compatibility review leaves that change unsaved. In a transfer-size input or its version-upgrade review, Ctrl+C discards the draft and closes the `/sync` flow; ordinary cancellation returns to Settings. A failed save retains the previous document and effective/displayed value. Completed transfers are never undone by changing a preference.
41
42
 
42
43
  Writers queue the complete read-modify-write operation, hold the cross-process lock through validation and same-directory atomic replacement, preserve unknown fields and private permissions, and refuse invalid existing files. UI changes do not replace those writers.
43
44
 
@@ -49,7 +50,7 @@ Check the setting's save and rollback with non-default bindings and verify next-
49
50
 
50
51
  ## Presentation decisions
51
52
 
52
- Selecting **Settings** in `/sync` opens **Pi Sync Settings** directly as one searchable flat list, with 17 rows and no category navigation or headings. Included paths, Excluded paths, and Compare included paths keep both content policies together. Excluded paths has a transactional JSON-array draft and reviewed Save/Discard/Continue flow; other rows retain their existing actions and save behavior. Typing searches the list. Back returns directly to the manager; hard Ctrl+C closes the flow. No `/ Search` hint is added because slash is ordinary search text.
53
+ Selecting **Settings** in `/sync` opens **Pi Sync Settings** directly as one searchable flat list with no category navigation or headings. Included paths, Excluded paths, and Compare included paths keep both content policies together. Excluded paths has a transactional JSON-array draft and reviewed Save/Discard/Continue flow; other rows retain their existing actions and save behavior. Typing searches the list. Back returns directly to the manager; hard Ctrl+C closes the flow. No `/ Search` hint is added because slash is ordinary search text.
53
54
 
54
55
  The existing public Kit settings adapter is retained rather than adding a second selector or accessing private Pi fields. Installed `SettingsList` provides `updateValue()` and `selectItem()`, but has no injected keybinding or awaited-save/rejection contract and does not expose search focus. Kit already owns ordered pending changes, rollback, retained search/selection, IME focus, bounded frames, and clipped mouse coordinates. This is an intentional existing deviation from the literal native-component convention. No new Kit API, dependency floor, or release is required. A package-owned public rendering boundary returns no lines at zero width and retains the selected row (or search when nothing matches) below five content rows; compact mouse events map back to the original rendered row. It does not access private component state or add key handlers. Search placeholder and position-footer relocation remain unsupported by that public API; the existing native-style hints and position indicator are retained rather than patched through private fields.
55
56
 
@@ -71,7 +72,7 @@ Startup transfer summaries report the preference and prerequisites, not a claim
71
72
  | Conflicts | Review complete dependency group and separately choose authority | Artifact fingerprint, group versions, baseline, config, owner and head checks; `conflict-confirmation.test.ts`, `conflict-preview.test.ts` |
72
73
  | Case-variant cleanup | Pull/rollback include the apply engine’s additional top-level alias removals, even when canonical snapshot bytes are unchanged | `apply-review.ts` uses the authoritative apply planner, streams file hashes, records symlink identity without following its target, and rechecks the complete alias set before commit; `transfer-preview.test.ts` covers changed, added, removed, cancelled and symlink aliases plus descriptor cleanup on cancellation. Merge preflight rejects noncanonical changed targets instead of deleting aliases. |
73
74
  | History rollback | Historical snapshot → local and active remote head; backup and protected-session summary | Settings, local bytes, current head, selected backend/setup and baseline rechecked; `history-confirmation-cancellation.test.ts`, `history-cancellation.test.ts`, `rollback-field-policy.test.ts` |
74
- | Explicit `--yes` | Existing documented review bypass only | Mandatory migration and operation safety remain; existing route suites |
75
+ | Explicit `--yes` | Existing documented review bypass only | Mandatory migration, configured transfer size limits, and other safety checks remain |
75
76
  | Automatic startup / shutdown | No new modal; existing opt-in, capability, idle, all-or-nothing conflict and secret policies | `automatic-transfer.test.ts`, `startup-check.test.ts`, `backend-orchestration.test.ts` |
76
77
 
77
78
  On an ignore-policy mismatch, Push and Pull both require explicit directional approval. The review names the affected side and offers the available rule text and exact file changes in details. Pull does not offer an overwrite when the snapshot omits rule text; it does not change the remote or the Sessions setting. An aborted review performs no transfer. TUI Pull, Push, and ignore-file rollback show directional counts and safety notes in the confirmation. Exact path rows are available in the read-only **View details** document. Older daemons can send the complete file list as the directional summary; the TUI moves only recognized path groups with verified counts out of that summary, without changing the exact details or the approval requirement. The configured Up and Down actions always select an option; selection-page bindings and the mouse wheel scroll the summary independently. Approval still requires displaying every row of the compact summary; a resize restarts the review. On a terminal too short to show the summary, resize to continue or cancel. RPC and legacy History rollback retain full file lists in their existing confirmation protocols. All changed counts come from effective snapshot differences rather than raw merge decisions. Protected paths, preserved remote files, merged bytes, and withheld paths must be accounted for before rendering. Cancellation performs no transfer; pre-commit preparation may retain recovery evidence. After the commit boundary, existing completion/recovery rules apply instead of promising undo.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-sync",
3
- "version": "0.66.0",
3
+ "version": "0.67.0",
4
4
  "description": "Pi extension that syncs Pi configuration through Git, WebDAV, Cloudflare R2, or S3-compatible storage.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -57,7 +57,7 @@
57
57
  "devDependencies": {
58
58
  "@earendil-works/pi-coding-agent": "1.6.0",
59
59
  "@earendil-works/pi-tui": "1.6.0",
60
- "@narumitw/pi-sync-daemon": "^0.12.0",
60
+ "@narumitw/pi-sync-daemon": "^0.13.0",
61
61
  "@types/proper-lockfile": "^4.1.4",
62
62
  "@types/semver": "^7.8.0",
63
63
  "esbuild": "0.28.2",
@@ -128,7 +128,7 @@ Check which [automatic sync control](references/configuration.md#automatic-sync-
128
128
  Inspect only the necessary local metadata and relevant non-secret configuration facts; do not expose raw settings, credentials, session contents, daemon records, journals, or backups in tool output or chat.
129
129
  Do not ask the user to paste those contents or execute text copied from them.
130
130
 
131
- Leave operations that Pi Sync requires the user to review in `/sync`, including initial setup, credential and destination changes, reviewed legacy path selection and policy changes, session opt-in, secret-scan bypass, enabling automatic behavior, rule-file activation or switching, and remote policy publication.
131
+ Leave operations that Pi Sync requires the user to review in `/sync`, including initial setup, credential and destination changes, reviewed legacy path selection and policy changes, session opt-in, secret-scan bypass, enabling automatic behavior, upgrading the settings document to enable a [transfer size limit](references/configuration.md#transfer-size-limits), rule-file activation or switching, and remote policy publication.
132
132
  Use the masked credential input in Pi; do not infer transfer or model consent from a settings edit.
133
133
  Do not start sync, run `/sync doctor` or backend/network commands, remove locks or recovery evidence, or bypass scan checks.
134
134
 
@@ -4,7 +4,7 @@ This is the authoritative public settings reference for Pi Sync.
4
4
  The configuration skill applies explicitly requested local settings and ignore-rule edits and investigates Pi Sync errors. The user performs operations that require a separate review.
5
5
 
6
6
  - **Configure a setup:** [Required fields](#settings-ownership-and-required-fields), [Manager](#editing-in-the-manager), [Version 3 example](#complete-version-3-example), [Backends](#required-backend-shapes)
7
- - **Choose what syncs:** [Ignore-file policy](#ignore-file-policy), [Legacy directory scope](#agent-directory-scope), [Included content](#included-content), [Excluded paths](#excluded-paths), [Machine-local settings fields](#settings-field-merge-and-machine-local-fields)
7
+ - **Choose what syncs:** [Ignore-file policy](#ignore-file-policy), [Legacy directory scope](#agent-directory-scope), [Included content](#included-content), [Excluded paths](#excluded-paths), [Transfer size limits](#transfer-size-limits), [Machine-local settings fields](#settings-field-merge-and-machine-local-fields)
8
8
  - **Manage automatic work:** [Controls and approval](#automatic-sync-controls), [Startup transfer](#automatic-startup-transfer), [Autonomous sync](#autonomous-sync), [Daemon lifetime](#daemon-lifetime-and-unattended-permission), [Continuous sync](#continuous-sync)
9
9
  - **Handle problems:** [Status](#status-display), [Debug mode](#debug-mode), [Secret scanning](#secret-scanning), [Diagnostics](#diagnostics), [Local troubleshooting](#local-troubleshooting), [Merge and partial progress](#content-merge-and-partial-progress), [Old settings and recovery](#unsupported-old-settings-and-recovery)
10
10
 
@@ -42,12 +42,13 @@ Global settings apply to all setups on this device; they are not remote policy.
42
42
 
43
43
  | Scope | Fields | Required values and defaults |
44
44
  | --- | --- | --- |
45
- | Document | `version`, `onSwitch`, `storageConnections`, `syncSetups` | All are required in a manually written document; versions 3 through 8 are supported. |
45
+ | Document | `version`, `onSwitch`, `storageConnections`, `syncSetups` | All are required in a manually written document; versions 3 through 9 are supported. |
46
46
  | Current setup | `activeSyncSetup` | Required when setups exist; absent when the setup catalog is empty. |
47
47
  | Global preferences | `skipSecretScan`, `showStatus`, `debug` | Optional booleans; defaults are false, true, and false. |
48
48
  | Setup selection | `sync.scope`, `sync.include`, `sync.automatic` | Legacy directory scope requires version 7 or later and omits `include`; selected-path setups require `include`. Both require explicit `automatic`. |
49
- | Ignore-file selection | `sync.scope`, `sync.pathPolicy`, `sync.ignoreFile`, `sync.sessions` | Version 8, `scope: "agent-directory"`, `pathPolicy: "ignore-file"`. `ignoreFile` defaults to `.syncignore`; sessions require `true` and the rules must allow them. Use reviewed setup or migration, not manual JSON edits. |
49
+ | Ignore-file selection | `sync.scope`, `sync.pathPolicy`, `sync.ignoreFile`, `sync.sessions` | Version 8 or later, `scope: "agent-directory"`, `pathPolicy: "ignore-file"`. `ignoreFile` defaults to `.syncignore`; sessions require `true` and the rules must allow them. Use reviewed setup or migration, not manual JSON edits. |
50
50
  | Setup behavior | `sync.automaticTransfer`, `sync.agentMode`, `sync.continuous`, `sync.mergeSettings`, `sync.mergeContent`, `sync.partialSync` | Optional booleans; all default to false. |
51
+ | Transfer size limits | `sync.maxFileSizeMiB`, `sync.maxDirectorySizeMiB` | Independent optional positive whole numbers; absence means Off. Either value requires version 9. |
51
52
  | Portable policy | `sync.localFields` | Optional array; any explicit array, including `[]`, requires version 4 or later. |
52
53
  | Content/partial policy | `sync.mergeContent`, `sync.partialSync` | Enabling either requires version 5 or later. |
53
54
  | Path exclusions | `sync.exclude` | Optional array; an explicit array, including `[]`, requires version 6 or later. |
@@ -307,6 +308,7 @@ Use the first concrete error, not a generic recovery hint appended to it. Start
307
308
  | --- | --- |
308
309
  | **Autonomous sync requires a separate policy review** | The selected setup has Autonomous sync enabled, but its current policy has no matching automatic-transfer approval. This does not mean that `pi-sync.json` is malformed. Check which setup the operation used and whether settings or rules changed. The user can review **Settings → Review automatic transfers** for the current setup or choose a reviewed directional push or pull. |
309
310
  | **Agent directory changed or has an unsafe filesystem layout** | The local scan could not establish a stable filesystem view. Use file metadata to check the agent root, Pi's `settings.json`, the effective session directory (including any `--session-dir` override), and in-scope paths. Symlinks in the session directory path and hard-linked candidate files can trigger this error; ordinary symlinks encountered in the directory scan are skipped. Check whether another Pi process or editor is changing files during the scan. Do not change synchronization settings unless the evidence identifies a relevant setting; this error alone does not identify a path or field. |
311
+ | **Transfer blocked by size limits** | Check the reported paths and byte counts. Use `/sync diff`, then narrow the selection or review a different source. See [transfer size limits](#transfer-size-limits). |
310
312
  | **Malformed or unsupported settings** | Check the canonical path and documented version and field constraints. Preserve the original private bytes and follow [settings recovery](#unsupported-old-settings-and-recovery); do not replace the document with defaults. |
311
313
  | **Backend access or publication failure** | Use the reported error class to distinguish credentials, a missing location, transport, and publication safety. A 404 alone does not identify which remote resource is missing. If local checks are insufficient, explain the backend-specific effects of [Diagnostics](#diagnostics) and leave that action to the user. |
312
314
 
@@ -314,7 +316,7 @@ A local check does not verify remote connectivity or permissions. Diagnostics ca
314
316
 
315
317
  ### Ignore-file policy
316
318
 
317
- New TUI setups use `.syncignore` when the daemon advertises support. Existing setups keep their policy and can coexist with ignore-file setups in version 8.
319
+ New TUI setups use `.syncignore` when the daemon advertises support. Existing setups keep their policy and can coexist with ignore-file setups in version 8 or later.
318
320
  To migrate a legacy setup, choose **Review migration now** when first offered in the TUI manager, or **Settings → Migrate to ignore file…** later. **Not now** defers the offer for that setup on this device; closing the prompt without a choice does not save a deferral. Review local and remote paths that enter or leave scope, including what the rules would do for future files. Legacy selected paths and `reinclude` rules do not always translate directly.
319
321
 
320
322
  This version 8 `sync` fragment shows a setup using the default rule file. It is not a complete settings document or a substitute for review:
@@ -491,6 +493,29 @@ Clearing rules retains `[]` and the newer versions; never downgrade in place.
491
493
  A pending transaction or merge journal under different rules remains available for reviewed recovery rather than replaying old writes.
492
494
  To return to an older client, stop automatic work, resolve pending recovery with a compatible client, preserve backups, and create a separate reviewed legacy-compatible setup/location.
493
495
 
496
+ ### Transfer size limits
497
+
498
+ Use **/sync → Settings → Max file size** or **Max directory size** for the current setup. The file limit applies to each included file. The directory limit applies to the sum of included files in each directory below the logical sync root, including the logical `sessions/` tree. A nested file contributes once to each of its parent directories below that root. The root itself has no size limit from this setting. A size equal to the limit passes.
499
+
500
+ Both settings default to **Off** and can be set independently. Enter `Off` or a positive whole number of MiB (`1 MiB = 1,048,576 bytes`) whose byte count is a safe integer. The settings file takes JSON numbers, not strings, booleans, zero, fractions, or `null`. In RPC or other non-TUI use, close Pi Sync clients, drain and stop the daemon, and verify owner exit before editing the canonical private `pi-sync.json`. Keep unrelated fields and private permissions. For example, in a version-9 document, add the following fields to the existing `syncSetups.<name>.sync` object:
501
+
502
+ ```json
503
+ {
504
+ "maxFileSizeMiB": 4,
505
+ "maxDirectorySizeMiB": 8
506
+ }
507
+ ```
508
+
509
+ Omit a key to turn that limit Off. There is no project or environment override. Older documents are not changed merely because both limits are Off. To enable a limit manually, set the document's top-level `version` to `9` in the same edit. In the TUI, review the compatibility warning before the first save that upgrades the file. **Close or upgrade older Pi Sync clients and daemon builds that share this agent directory before enabling a limit.** Older processes cannot use any setup in the version-9 document, even after both limits are cleared. Each device enforces its own limits, with no snapshot format change or remote settings migration. See [daemon ownership and upgrade](https://github.com/narumiruna/pi-extensions/blob/main/packages/pi-sync/docs/daemon-migration.md#ownership-and-upgrade) if the running owner does not support the limits.
510
+
511
+ A saved change applies to subsequent transfer attempts. It starts no transfer and grants no new automatic permission. If the change invalidates existing permission, review automatic transfers again through the existing controls. The daemon measures the actual uncompressed bytes after content selection, portable field projection, and any applicable merge or conflict resolution. It checks each side's proposed image separately, so the same path on both sides does not count twice. With partial sync or live-session protection, count only what belongs to that side's selected result. Ignored paths, preserved out-of-scope content, and old destination bytes outside that result do not count. Neither do transport encoding, backups, or History. If the active ignore file is included and the transfer writes or publishes it as rule metadata, its actual UTF-8 bytes count toward the limits.
512
+
513
+ A violation blocks new publication or local apply without skipping the offending files or advancing the accepted baseline. This applies to automatic work, reviewed rollback, and Pull that adopts remote rules. Neither `--force` nor `--yes` bypasses it. The error lists a bounded set of relative paths, measured sizes, and limits, plus the omitted count if there are more findings. An unchanged automatic size violation is a safety block, not a transient retry. The existing scan, decode, merge, and backend bounds still apply and can stop work earlier.
514
+
515
+ Use `/sync diff` to inspect the difference or policy mismatch. For example, if `skills/local-cache/` makes `skills/` exceed an 8 MiB directory cap, add `/skills/local-cache/` to the active ignore file, or exclude `skills/local-cache` through the legacy Settings editor. Check the new selection, then use `/sync push` and confirm the reviewed direction if this device is authoritative. Review any policy replacement separately; a legacy policy mismatch can require a reviewed `/sync push --force` without `--yes`. If the remote is authoritative, use a reviewed `/sync pull` with an applicable selection. Previous remote versions remain in History; Pull keeps its local backup, so a compliant source can replace larger managed destination bytes without losing the restore point.
516
+
517
+ Read-only reviews remain available. A new limit does not prevent verified reconciliation of an already committed transfer. A pending local-only merge or rule adoption that has not installed its rule file can still be blocked: matching local files do not prove that the interrupted transfer wrote them. When a limit is on, local-only merge recovery also stops if it finds new or changed included files outside the journal's recorded images. Keep the settings, backups, and journals. Review the limits and verify the local and remote snapshots with a compatible daemon before retrying. Turning both limits Off restores the previous size policy for future transfers without changing version 9 or rewriting history.
518
+
494
519
  ### Automatic startup transfer
495
520
 
496
521
  `sync.automaticTransfer` is optional and accepts only a boolean; absent means `false`.
@@ -526,7 +551,7 @@ Unknown fields remain preserved and malformed/invalid files block saves, just as
526
551
 
527
552
  ### Autonomous sync
528
553
 
529
- Autonomous sync uses the unchanged `sync.agentMode` key, an optional per-setup boolean, default `false`, in settings versions 3 through 8.
554
+ Autonomous sync uses the unchanged `sync.agentMode` key, an optional per-setup boolean that defaults to `false`.
530
555
  Open **Settings → Autonomous sync** and review the setup, destination, content policy, transfer authorization, model disclosure, costs, and autonomous writes before enabling. For directory scope, the review shows session opt-in separately from path rules.
531
556
  In a legacy-only settings file, RPC users can authorize Autonomous sync by explicitly setting this field to `true`. If any setup uses an ignore file, follow the [separate approval step](#automatic-sync-controls) after enabling it.
532
557
 
@@ -650,7 +675,7 @@ A failed consent write blocks automatic work in that service instance. Uncertain
650
675
 
651
676
  ### Continuous sync
652
677
 
653
- `sync.continuous` is an optional per-setup boolean, default `false`, in settings versions 3 through 8.
678
+ `sync.continuous` is an optional per-setup boolean that defaults to `false`.
654
679
  Open **Settings → Continuous sync** after enabling Autonomous sync. For directory scope, the review shows session opt-in separately from path rules.
655
680
  In a legacy-only settings file, RPC users can opt in by explicitly setting this field to `true`. If any setup uses an ignore file, follow the [separate approval step](#automatic-sync-controls) after enabling it.
656
681
  Existing Autonomous sync consent does not enable recurring requests.
@@ -882,5 +907,7 @@ Recovery:
882
907
  4. run `/sync doctor`, inspect the exact storage path, and review the first pull or push;
883
908
  5. restore the retained file and a compatible older package only if rolling back.
884
909
 
910
+ If your processes reject a newer settings version, keep the document and use compatible Pi Sync and daemon builds. In particular, [clearing transfer size limits](#transfer-size-limits) never downgrades version 9. Do not use the recovery steps above to replace a newer document.
911
+
885
912
  Malformed, invalid, unsupported, symlinked, or concurrently changed documents remain untouched.
886
913
  Failed UI saves keep the previous file and displayed/effective state.
@@ -1,4 +1,5 @@
1
1
  import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import { isKeyRelease, Key, matchesKey } from "@earendil-works/pi-tui";
2
3
  import { defineMenu, type MenuSettingItem, runMenu } from "@narumitw/pi-tui-kit";
3
4
  import { piDaemonClient } from "../daemon/pi-client.js";
4
5
  import { configFromSettings, loadSettingsConfig, syncCheckConfigFingerprint } from "../settings/config.js";
@@ -37,6 +38,22 @@ import { safeTerminalText } from "./terminal-text.js";
37
38
 
38
39
  export type SyncSettingsRoute = RunRoute;
39
40
 
41
+ type SettingsState = Awaited<ReturnType<typeof loadSettingsConfig>>;
42
+ const transferSizeLimits = [
43
+ {
44
+ field: "maxFileSizeMiB",
45
+ label: "Max file size",
46
+ description: "Block a transfer when an included file exceeds this uncompressed size.",
47
+ },
48
+ {
49
+ field: "maxDirectorySizeMiB",
50
+ label: "Max directory size",
51
+ description:
52
+ "Block a transfer when a directory below the sync root exceeds this total uncompressed size, counting included files in its subdirectories too.",
53
+ },
54
+ ] as const;
55
+ type TransferSizeLimit = (typeof transferSizeLimits)[number];
56
+
40
57
  export async function showSyncSettings(
41
58
  ctx: ExtensionCommandContext,
42
59
  runRoute: SyncSettingsRoute,
@@ -63,7 +80,7 @@ export async function showSyncSettings(
63
80
  const document = await readActiveLocalConfigDocumentForRepair().catch(() => null);
64
81
  if (!isCurrent()) return disposition;
65
82
  const settingsPath = document?.path ?? localConfigPath();
66
- let config: Awaited<ReturnType<typeof loadSettingsConfig>> | undefined;
83
+ let config: ReturnType<typeof configFromSettings> | undefined;
67
84
  try {
68
85
  if (document) config = configFromSettings(validateSettingsDocument(document.parsed), reviewedSetup);
69
86
  } catch {
@@ -77,6 +94,12 @@ export async function showSyncSettings(
77
94
  ? "Could not read the active pi-sync settings file. Check file access or repair the JSON before reopening /sync."
78
95
  : `Edit pi-sync settings manually: ${safeTerminalText(settingsPath)}`,
79
96
  ...(limited ? [IGNORE_SETUP_MANAGEMENT_LIMIT, ...ignoreSetupRecovery(settingsPath)] : []),
97
+ ...(!limited && config
98
+ ? [
99
+ "In the active entry in syncSetups, set sync.maxFileSizeMiB or sync.maxDirectorySizeMiB to a positive whole number of MiB with a safe byte count. Remove a field to turn that limit Off.",
100
+ "A limit requires settings version 9. Upgrade all Pi Sync clients and daemons that share this agent directory before enabling a limit. Keep version 9 even if both limits are later Off.",
101
+ ]
102
+ : []),
80
103
  ...(!limited && config?.reservedIgnoreNames !== undefined
81
104
  ? ["Use TUI Settings → Review automatic transfers to approve the current setup separately."]
82
105
  : []),
@@ -120,8 +143,8 @@ export async function showSyncSettings(
120
143
  const ignoreAvailable = await ignoreFileSettingsAvailable(ctx, signal);
121
144
  if (!isCurrent()) return disposition;
122
145
  const setupName = initial.setupName;
123
- type SettingsState = Awaited<ReturnType<typeof loadSettingsConfig>>;
124
146
  type Action =
147
+ | TransferSizeLimit["field"]
125
148
  | "automatic"
126
149
  | "automatic-transfer"
127
150
  | "agent-mode"
@@ -238,6 +261,13 @@ export async function showSyncSettings(
238
261
  currentValue: `${state.localFields?.length ?? 0} fields · Edit`,
239
262
  action: "local-fields",
240
263
  },
264
+ ...transferSizeLimits.map(({ field, label, description }) => ({
265
+ id: field,
266
+ label,
267
+ description: `This setup: ${description} Also applies to automatic transfers. Saving starts no transfer.`,
268
+ currentValue: transferSizeLimitLabel(state[field]),
269
+ action: field,
270
+ })),
241
271
  {
242
272
  id: "storageLocation",
243
273
  label: "Storage location",
@@ -386,6 +416,8 @@ export async function showSyncSettings(
386
416
  }),
387
417
  },
388
418
  actions: {
419
+ maxFileSizeMiB: transferSizeLimitAction(transferSizeLimits[0]),
420
+ maxDirectorySizeMiB: transferSizeLimitAction(transferSizeLimits[1]),
389
421
  "storage-location": async ({ signal: actionSignal }) => {
390
422
  const editorSignal = signal ? AbortSignal.any([signal, actionSignal]) : actionSignal;
391
423
  await showEditSyncSetupStorage(ctx, setupName, editorSignal);
@@ -412,7 +444,7 @@ export async function showSyncSettings(
412
444
  if (
413
445
  !(await ctx.ui.confirm(
414
446
  "Save content policy?",
415
- `${previous.pathPolicy === "ignore-file" ? "Ignore-file policy keeps settings version 8 and publishes snapshot version 7; upgrade older clients first." : previous.scope === "agent-directory" ? "Agent directory scope uses snapshot version 5; older clients must refuse it." : "This explicitly upgrades settings to at least version 5; partial snapshots use version 3, or version 4 with exclusions, and older clients must refuse them."} Text/session merge is conservative. Partial sync preserves withheld versions and old baselines. Disabling does not clear unresolved groups or recovery evidence. Review a directional migration first if portable policy changes.`,
447
+ `${previous.pathPolicy === "ignore-file" ? `Ignore-file policy keeps settings version ${previous.settingsVersion} and publishes snapshot version 7; upgrade older clients first.` : previous.scope === "agent-directory" ? "Agent directory scope uses snapshot version 5; older clients must refuse it." : "This explicitly upgrades settings to at least version 5; partial snapshots use version 3, or version 4 with exclusions, and older clients must refuse them."} Text/session merge is conservative. Partial sync preserves withheld versions and old baselines. Disabling does not clear unresolved groups or recovery evidence. Review a directional migration first if portable policy changes.`,
416
448
  { signal: mutationSignal },
417
449
  ))
418
450
  )
@@ -488,7 +520,7 @@ export async function showSyncSettings(
488
520
  if (sameLocalFields(previous.localFields, fields)) return { kind: "stay" };
489
521
  const confirmed = await ctx.ui.confirm(
490
522
  "Save portable field policy?",
491
- `${previous.pathPolicy === "ignore-file" ? "Ignore-file policy keeps settings version 8 and publishes snapshot version 7." : previous.scope === "agent-directory" ? "Agent directory scope uses snapshot version 5." : "This opts into at least settings/snapshot version 4/2; exclude-enabled setups retain snapshot version 4."} Older clients must refuse unsupported formats. Future snapshots omit these fields, but old remote history is NOT erased. Review an explicit force push/pull migration before further sync. Removed rules can expose or replace local-only values.`,
523
+ `${previous.pathPolicy === "ignore-file" ? `Ignore-file policy keeps settings version ${previous.settingsVersion} and publishes snapshot version 7.` : previous.scope === "agent-directory" ? "Agent directory scope uses snapshot version 5." : "This opts into at least settings/snapshot version 4/2; exclude-enabled setups retain snapshot version 4."} Older clients must refuse unsupported formats. Future snapshots omit these fields, but old remote history is NOT erased. Review an explicit force push/pull migration before further sync. Removed rules can expose or replace local-only values.`,
492
524
  { signal: mutationSignal },
493
525
  );
494
526
  validate();
@@ -768,6 +800,84 @@ export async function showSyncSettings(
768
800
  return result;
769
801
  };
770
802
  }
803
+ function transferSizeLimitAction({ field, label }: TransferSizeLimit) {
804
+ return async ({ state, signal: actionSignal }: { state: SettingsState; signal: AbortSignal }) => {
805
+ const cancel = new AbortController();
806
+ const mutationSignal = AbortSignal.any([actionSignal, cancel.signal, ...(signal ? [signal] : [])]);
807
+ const validate = captureMutationOwner(ctx, mutationSignal);
808
+ const rejected = { kind: "rejected" } as const;
809
+ const stay = { kind: "stay" } as const;
810
+ const setupLabel = safeTerminalText(setupName);
811
+ let limit: number | undefined;
812
+ try {
813
+ const expectedConfigFingerprint = syncCheckConfigFingerprint(state);
814
+ const active = await loadSettingsConfig();
815
+ validate();
816
+ if (active.setupName !== setupName || syncCheckConfigFingerprint(active) !== expectedConfigFingerprint) {
817
+ throw new Error("Current sync setup changed while Settings was open; reopen Settings.");
818
+ }
819
+ const stop = ctx.ui.onTerminalInput((data) => {
820
+ if (!isKeyRelease(data) && matchesKey(data, Key.ctrl("c"))) {
821
+ cancel.abort();
822
+ return { consume: true };
823
+ }
824
+ });
825
+ try {
826
+ const input = await ctx.ui.input(
827
+ `${label} for “${setupLabel}” (current: ${transferSizeLimitLabel(state[field])})\nEnter Off or a positive whole number of MiB.`,
828
+ undefined,
829
+ { signal: mutationSignal },
830
+ );
831
+ validate();
832
+ if (input === undefined) return rejected;
833
+ limit = parseTransferSizeLimit(input);
834
+ if (limit === state[field]) return stay;
835
+ if (limit !== undefined && active.settingsVersion < 9) {
836
+ const confirmed = await ctx.ui.confirm(
837
+ "Upgrade Pi Sync settings to version 9?",
838
+ `${label} for “${setupLabel}”: ${transferSizeLimitLabel(limit)}. Older Pi Sync clients and daemons cannot read this settings file for any setup. Upgrade all processes that share this agent directory before continuing. Turning both limits Off later does not downgrade the file. Remote snapshots are unchanged.`,
839
+ { signal: mutationSignal },
840
+ );
841
+ validate();
842
+ if (!confirmed) return rejected;
843
+ }
844
+ } finally {
845
+ stop();
846
+ }
847
+ validate();
848
+ ctx.ui.notify("Saving Pi Sync setting…", "info");
849
+ await updateSyncSetup(
850
+ setupName,
851
+ (setup) => {
852
+ validate();
853
+ if (limit === undefined) delete setup.sync[field];
854
+ else setup.sync[field] = limit;
855
+ return setup;
856
+ },
857
+ { expectedActiveSetup: true, expectedConfigFingerprint, signal: mutationSignal },
858
+ );
859
+ } catch (error) {
860
+ if (cancel.signal.aborted) return exitSettings();
861
+ if (!mutationSignal.aborted && isCurrent()) notifySaveFailure(ctx, error);
862
+ return rejected;
863
+ }
864
+ try {
865
+ validate();
866
+ const approval =
867
+ state.reservedIgnoreNames !== undefined &&
868
+ (startupTransferEnabled(state) || (state.automatic && syncSessionsSelected(state)))
869
+ ? " Use Review automatic transfers to approve this policy separately."
870
+ : "";
871
+ ctx.ui.notify(
872
+ `Saved. ${label} for “${setupLabel}”: ${transferSizeLimitLabel(limit)}. Applies to subsequent transfers; no transfer started.${approval}`,
873
+ "info",
874
+ );
875
+ } catch {
876
+ return stay;
877
+ }
878
+ return stay;
879
+ };
880
+ }
771
881
  function ignoreAction(action: Parameters<typeof showIgnoreFileAction>[2]) {
772
882
  return async ({ state, signal: actionSignal }: { state: SettingsState; signal: AbortSignal }) => {
773
883
  if (!ignoreAvailable || (state.pathPolicy === "ignore-file") === (action === "migrate"))
@@ -802,6 +912,20 @@ export async function showSyncSettings(
802
912
  return disposition;
803
913
  }
804
914
 
915
+ function transferSizeLimitLabel(limit: number | undefined) {
916
+ return limit === undefined ? "Off" : `${limit} MiB`;
917
+ }
918
+
919
+ function parseTransferSizeLimit(input: string) {
920
+ const value = input.trim();
921
+ if (value.toLowerCase() === "off") return undefined;
922
+ const limit = Number(value);
923
+ if (!/^[0-9]+$/u.test(value) || limit <= 0 || !Number.isSafeInteger(limit * 1_048_576)) {
924
+ throw new Error("Enter Off or a positive whole number of MiB that fits in a safe byte count.");
925
+ }
926
+ return limit;
927
+ }
928
+
805
929
  function notifySaveFailure(ctx: ExtensionCommandContext, error: unknown) {
806
930
  ctx.ui.notify(
807
931
  `Pi Sync settings save failed: ${safeTerminalText(error instanceof Error ? error.message : String(error))}`,