@narumitw/pi-sync 0.64.0 → 0.66.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 (116) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +80 -11
  3. package/dist/chunks/{chunk-TJ7YNITN.ts → chunk-5YOLQKNZ.ts} +39 -3
  4. package/dist/chunks/chunk-5YOLQKNZ.ts.map +7 -0
  5. package/dist/chunks/{chunk-NDEZ52SS.ts → chunk-ASU3GZPW.ts} +11 -93
  6. package/dist/chunks/chunk-ASU3GZPW.ts.map +7 -0
  7. package/dist/chunks/{chunk-CKUGCBHP.ts → chunk-AYGMIMCV.ts} +2 -2
  8. package/dist/chunks/chunk-AYGMIMCV.ts.map +7 -0
  9. package/dist/chunks/{chunk-F3VODLVQ.ts → chunk-BESRBKVO.ts} +3 -3
  10. package/dist/chunks/{chunk-TZMVSTAM.ts → chunk-BYVHABNR.ts} +4 -4
  11. package/dist/chunks/chunk-ECYCNZOE.ts +12 -0
  12. package/dist/chunks/chunk-ECYCNZOE.ts.map +7 -0
  13. package/dist/chunks/{chunk-RW44KNFD.ts → chunk-JQ5BAWW2.ts} +182 -12
  14. package/dist/chunks/chunk-JQ5BAWW2.ts.map +7 -0
  15. package/dist/chunks/{chunk-MANNB4WZ.ts → chunk-KNEUL4XN.ts} +1 -7
  16. package/dist/chunks/chunk-KNEUL4XN.ts.map +7 -0
  17. package/dist/chunks/{chunk-VPSC7BXM.ts → chunk-SZJOUVCL.ts} +2 -2
  18. package/dist/chunks/{chunk-YT6PDRMM.ts → chunk-WJQ4TGN5.ts} +17 -17
  19. package/dist/chunks/chunk-WJQ4TGN5.ts.map +7 -0
  20. package/dist/chunks/{chunk-4VKWHVUO.ts → chunk-XUZV4OGI.ts} +3 -2
  21. package/dist/chunks/{chunk-4VKWHVUO.ts.map → chunk-XUZV4OGI.ts.map} +2 -2
  22. package/dist/chunks/chunk-Z5JMOXJM.ts +106 -0
  23. package/dist/chunks/chunk-Z5JMOXJM.ts.map +7 -0
  24. package/dist/chunks/{command-handler-N45GY7AV.ts → command-handler-44EFGPWH.ts} +54 -13
  25. package/dist/chunks/command-handler-44EFGPWH.ts.map +7 -0
  26. package/dist/chunks/{conflict-review-5E4M44BA.ts → conflict-review-J7L7S4AR.ts} +2 -2
  27. package/dist/chunks/{file-selection-DDQN4LVD.ts → file-selection-XWACUTAH.ts} +8 -8
  28. package/dist/chunks/ignore-file-ui-OHFISFVC.ts +21 -0
  29. package/dist/chunks/{manager-result-dispatcher-FKW55L7I.ts → manager-result-dispatcher-WXE2BAQO.ts} +4 -4
  30. package/dist/chunks/{manager-ui-EV23DPZQ.ts → manager-ui-CVZLMXJ5.ts} +90 -76
  31. package/dist/chunks/manager-ui-CVZLMXJ5.ts.map +7 -0
  32. package/dist/chunks/{merge-review-6YSLSMGS.ts → merge-review-AAC674C6.ts} +3 -3
  33. package/dist/chunks/{remote-selection-ui-N4NMWFT2.ts → remote-selection-ui-E4XZCQ7A.ts} +3 -3
  34. package/dist/chunks/{setup-switch-HY7K3442.ts → setup-switch-644T6KHG.ts} +3 -3
  35. package/dist/chunks/setup-switch-644T6KHG.ts.map +7 -0
  36. package/dist/chunks/{setup-wizard-LEKDQ3HK.ts → setup-wizard-IEW56AZE.ts} +10 -8
  37. package/dist/chunks/{setup-wizard-LEKDQ3HK.ts.map → setup-wizard-IEW56AZE.ts.map} +1 -1
  38. package/dist/chunks/{sync-inspection-OS2LVOLV.ts → sync-inspection-NBBTSMKR.ts} +2 -2
  39. package/dist/chunks/{sync-operations-D3MDJUQQ.ts → sync-operations-AIEM2KL2.ts} +2 -2
  40. package/dist/daemon/dist/client.js +125 -287
  41. package/dist/daemon/dist/consent.js +14 -2
  42. package/dist/daemon/dist/daemon-recovery.js +85 -2
  43. package/dist/daemon/dist/daemon-startup.js +257 -0
  44. package/dist/daemon/dist/engine/backends/git/git-backend.js +15 -4
  45. package/dist/daemon/dist/engine/backends/git/git-storage.js +15 -3
  46. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +20 -9
  47. package/dist/daemon/dist/engine/backends/sync-backend.js +16 -0
  48. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +19 -6
  49. package/dist/daemon/dist/engine/ignore/adoption-journal.js +143 -0
  50. package/dist/daemon/dist/engine/ignore/snapshot-ignore-rules.js +39 -0
  51. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +2 -2
  52. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +6 -6
  53. package/dist/daemon/dist/engine/snapshot/snapshot-types.js +5 -1
  54. package/dist/daemon/dist/engine/snapshot/snapshot.js +5 -2
  55. package/dist/daemon/dist/engine/sync/conflict-review.js +2 -0
  56. package/dist/daemon/dist/engine/sync/continuous-watch.js +3 -2
  57. package/dist/daemon/dist/engine/sync/directional-action.js +119 -0
  58. package/dist/daemon/dist/engine/sync/ignore-adoption-recovery.js +50 -0
  59. package/dist/daemon/dist/engine/sync/ignore-adoption.js +401 -0
  60. package/dist/daemon/dist/engine/sync/ignore-publication.js +23 -0
  61. package/dist/daemon/dist/engine/sync/initialization.js +12 -0
  62. package/dist/daemon/dist/engine/sync/local-fields.js +6 -3
  63. package/dist/daemon/dist/engine/sync/merge-journal.js +2 -2
  64. package/dist/daemon/dist/engine/sync/merged-sync.js +14 -3
  65. package/dist/daemon/dist/engine/sync/remote-snapshot.js +3 -1
  66. package/dist/daemon/dist/engine/sync/sync-errors.js +20 -0
  67. package/dist/daemon/dist/engine/sync/sync-local.js +57 -3
  68. package/dist/daemon/dist/engine/sync/sync-mutations.js +375 -346
  69. package/dist/daemon/dist/engine/sync/sync-policy.js +5 -5
  70. package/dist/daemon/dist/engine/sync/sync-queries.js +3 -2
  71. package/dist/daemon/dist/engine/sync/sync-rollback.js +204 -0
  72. package/dist/daemon/dist/engine/sync/transfer-freshness.js +11 -5
  73. package/dist/daemon/dist/engine/ui/ignore-rule-preview.js +18 -0
  74. package/dist/daemon/dist/engine-service.js +69 -1
  75. package/dist/daemon/dist/foreground-queue-outcome.js +9 -0
  76. package/dist/daemon/dist/monitor.js +1 -0
  77. package/dist/daemon/dist/server.js +76 -11
  78. package/dist/daemon/dist/service-host.js +56 -8
  79. package/dist/daemon/package.json +1 -1
  80. package/dist/index.ts +6 -6
  81. package/docs/daemon-migration.md +3 -6
  82. package/docs/tui-contract.md +3 -3
  83. package/package.json +2 -2
  84. package/skills/configure-pi-sync/references/configuration.md +10 -8
  85. package/src/commands/command-execution.ts +56 -2
  86. package/src/commands/command-handler.ts +2 -0
  87. package/src/commands/command.ts +2 -1
  88. package/src/daemon/directional-recovery.ts +103 -0
  89. package/src/daemon/pi-client.ts +112 -9
  90. package/src/ui/cancellable-operation.ts +5 -2
  91. package/src/ui/ignore-file-ui.ts +13 -5
  92. package/src/ui/manager-state.ts +17 -10
  93. package/src/ui/manager-ui.ts +30 -25
  94. package/src/ui/merge-review.ts +8 -9
  95. package/src/ui/remote-selection-ui.ts +43 -2
  96. package/src/ui/settings-ui.ts +30 -30
  97. package/src/ui/sync-confirmation.ts +7 -7
  98. package/dist/chunks/chunk-CKUGCBHP.ts.map +0 -7
  99. package/dist/chunks/chunk-MANNB4WZ.ts.map +0 -7
  100. package/dist/chunks/chunk-NDEZ52SS.ts.map +0 -7
  101. package/dist/chunks/chunk-RW44KNFD.ts.map +0 -7
  102. package/dist/chunks/chunk-TJ7YNITN.ts.map +0 -7
  103. package/dist/chunks/chunk-YT6PDRMM.ts.map +0 -7
  104. package/dist/chunks/command-handler-N45GY7AV.ts.map +0 -7
  105. package/dist/chunks/manager-ui-EV23DPZQ.ts.map +0 -7
  106. /package/dist/chunks/{chunk-F3VODLVQ.ts.map → chunk-BESRBKVO.ts.map} +0 -0
  107. /package/dist/chunks/{chunk-TZMVSTAM.ts.map → chunk-BYVHABNR.ts.map} +0 -0
  108. /package/dist/chunks/{chunk-VPSC7BXM.ts.map → chunk-SZJOUVCL.ts.map} +0 -0
  109. /package/dist/chunks/{conflict-review-5E4M44BA.ts.map → conflict-review-J7L7S4AR.ts.map} +0 -0
  110. /package/dist/chunks/{file-selection-DDQN4LVD.ts.map → file-selection-XWACUTAH.ts.map} +0 -0
  111. /package/dist/chunks/{manager-result-dispatcher-FKW55L7I.ts.map → ignore-file-ui-OHFISFVC.ts.map} +0 -0
  112. /package/dist/chunks/{merge-review-6YSLSMGS.ts.map → manager-result-dispatcher-WXE2BAQO.ts.map} +0 -0
  113. /package/dist/chunks/{remote-selection-ui-N4NMWFT2.ts.map → merge-review-AAC674C6.ts.map} +0 -0
  114. /package/dist/chunks/{setup-switch-HY7K3442.ts.map → remote-selection-ui-E4XZCQ7A.ts.map} +0 -0
  115. /package/dist/chunks/{sync-inspection-OS2LVOLV.ts.map → sync-inspection-NBBTSMKR.ts.map} +0 -0
  116. /package/dist/chunks/{sync-operations-D3MDJUQQ.ts.map → sync-operations-AIEM2KL2.ts.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import path from "node:path";
3
3
  import { DEBUG_LOG_FILENAME, isDebugLogPath, isDeniedPath, toPosix } from "../paths.js";
4
- import { IGNORE_SNAPSHOT_VERSION, } from "../snapshot/snapshot-types.js";
4
+ import { isIgnoreSnapshotVersion, } from "../snapshot/snapshot-types.js";
5
5
  import { compilePathRules, compileSyncExclude, normalizeSyncExclude, sameSyncExclude } from "./exclude-policy.js";
6
6
  export const BUILT_IN_SYNC_ROOTS = [
7
7
  "settings.json",
@@ -199,8 +199,8 @@ export function validateSnapshotSelection(snapshot) {
199
199
  throw new Error("Exclude policy requires snapshot version 4 and selection version 2.");
200
200
  if ((snapshot.version === 5) !== (selection?.version === 3))
201
201
  throw new Error("Agent-directory policy requires snapshot version 5 and selection version 3.");
202
- if ((snapshot.version === IGNORE_SNAPSHOT_VERSION) !== (selection?.version === 4))
203
- throw new Error("Ignore-file policy requires snapshot version 6 and selection version 4.");
202
+ if (isIgnoreSnapshotVersion(snapshot.version) !== (selection?.version === 4))
203
+ throw new Error("Ignore-file policy requires snapshot version 6 or 7 and selection version 4.");
204
204
  }
205
205
  export function assertSnapshotPathExcludesDebugLog(filePath) {
206
206
  if (typeof filePath === "string" && isDebugLogPath(filePath))
@@ -211,7 +211,7 @@ export function assertSnapshotExcludesDebugLog(snapshot) {
211
211
  assertSnapshotPathExcludesDebugLog(file?.path);
212
212
  }
213
213
  export function requireLegacyTransferPolicy(snapshot) {
214
- if (snapshot.version === IGNORE_SNAPSHOT_VERSION || snapshot.selection?.version === 4)
214
+ if (isIgnoreSnapshotVersion(snapshot.version) || snapshot.selection?.version === 4)
215
215
  throw new Error("This setup cannot transfer an ignore-file snapshot without a reviewed local ignore policy.");
216
216
  }
217
217
  export function sameSyncInclude(left, right) {
@@ -243,7 +243,7 @@ export function formatIgnorePolicyComparison(comparison) {
243
243
  case "match":
244
244
  return "Remote ignore-file policy matches this device.";
245
245
  case "mismatch":
246
- return "Remote ignore-file policy differs. Edit local rules to match, or review publishing this device's policy.";
246
+ return "Remote ignore-file policy differs. Review a directional Push or Pull; Pull needs the remote rule text.";
247
247
  case "local-ignore-remote-legacy":
248
248
  return "Remote uses a legacy content policy. Review publishing this device's ignore-file policy.";
249
249
  case "local-legacy-remote-ignore":
@@ -1,4 +1,5 @@
1
1
  import { createSyncBackend } from "../backends/backend-factory.js";
2
+ import { HISTORY_PREVIEW_LIMIT } from "../backends/sync-backend.js";
2
3
  import { loadConfig, syncSessionsWarnings } from "../settings/config.js";
3
4
  import { resolvedSnapshotOptionsForContext } from "../snapshot/session-paths.js";
4
5
  import { createSnapshot, scanSnapshot } from "../snapshot/snapshot.js";
@@ -19,7 +20,7 @@ function contentLines(config) {
19
20
  config.scope === "agent-directory"
20
21
  ? "included content: eligible files in the Pi agent directory"
21
22
  : `included content: ${config.include.map(safeTerminalText).join(", ") || "none"}`,
22
- ...(config.ignorePolicy ? ["path policy: local ignore file (rule text is not published)"] : []),
23
+ ...(config.ignorePolicy ? ["path policy: local ignore file (published unless it excludes itself)"] : []),
23
24
  ...(config.exclude === undefined
24
25
  ? []
25
26
  : [`excluded paths: ${config.exclude.map(safeTerminalText).join(", ") || "none"}`]),
@@ -174,7 +175,7 @@ export async function history(ctx, options, factory = createSyncBackend) {
174
175
  const config = await loadConfig(options.setup);
175
176
  throwIfAborted(options.signal);
176
177
  const backend = await factory(config);
177
- const snapshots = (await backend.listHistory(options.signal)).slice(-20).reverse();
178
+ const snapshots = (await backend.listHistory(options.signal)).slice(-HISTORY_PREVIEW_LIMIT).reverse();
178
179
  throwIfAborted(options.signal);
179
180
  const lastApplied = await readStateForConfig(config)
180
181
  .then((state) => state.lastAppliedSnapshot)
@@ -0,0 +1,204 @@
1
+ import { createSyncBackend } from "../backends/backend-factory.js";
2
+ import { expectedRemoteHead } from "../backends/sync-backend.js";
3
+ import { requireNoPendingAdoption } from "../ignore/adoption-journal.js";
4
+ import { loadConfig, syncCheckConfigFingerprint } from "../settings/config.js";
5
+ import { effectiveSessionRoot, requireStableMergeSessionRoot, resolvedSnapshotOptionsForContext, sessionDirForApply, } from "../snapshot/session-paths.js";
6
+ import { createSnapshot, filterSnapshotForConfigPolicy, regenerateSnapshotIdentity, scanSnapshot, snapshotIncludesSessions, snapshotWithoutSessions, } from "../snapshot/snapshot.js";
7
+ import { applySnapshot } from "../snapshot/snapshot-apply.js";
8
+ import { ignorePolicyValidator } from "../snapshot/snapshot-transaction-policy.js";
9
+ import { pruneMergeBaselines } from "../state/merge-baseline-store.js";
10
+ import { readStateForConfig, syncStateFingerprint, writeStateForConfig } from "../state/sync-state-store.js";
11
+ import { formatPublicationPreview, formatRollbackSummary, formatTransferReview } from "../ui/sync-format.js";
12
+ import { confirmTransferReview } from "../ui/transfer-review.js";
13
+ import { inspectCaseCleanup, revalidateCaseCleanup } from "./apply-review.js";
14
+ import { confirmFieldMigration } from "./field-migration.js";
15
+ import { ignorePublicationNotice, withPublishedIgnoreRules } from "./ignore-publication.js";
16
+ import { overlayLocalFields, portableSnapshot, sameLocalFields, validatePortableSnapshot } from "./local-fields.js";
17
+ import { requireNoMergeJournal, retireMergeJournal } from "./merge-journal.js";
18
+ import { readSnapshotForHead, requireCompatibleRemoteSelection, sameRemoteHead, snapshotForUpload, } from "./remote-snapshot.js";
19
+ import { throwIfAborted } from "./signals.js";
20
+ import { PublicationStatePersistenceError, RollbackPublicationError } from "./sync-errors.js";
21
+ import { backupLocal, captureMutationOwner, maybeReload, protectedSessionPaths } from "./sync-local.js";
22
+ import { requireLegacyTransferPolicy, syncSessionsSelected } from "./sync-policy.js";
23
+ import { acceptedSelection, fileHashMap, sameHashes } from "./sync-state.js";
24
+ import { directionalApplyGuards, requireIgnoreBaselineReview, requireResolvedDirectionalProgress, validateDirectionalPublication, } from "./transfer-freshness.js";
25
+ const VERSION = 1;
26
+ const POST_LOCAL_COMMIT_TIMEOUT_MS = 30_000;
27
+ export async function rollback(ctx, options, factory = createSyncBackend, expectedSelection) {
28
+ if (options.directionalAction)
29
+ throw new Error("Single-action transfer cannot authorize rollback.");
30
+ requireNoPendingAdoption();
31
+ const validateMutation = captureMutationOwner(ctx, options.signal);
32
+ const validateCommittedOwner = captureMutationOwner(ctx);
33
+ const target = options.args[0];
34
+ if (!target)
35
+ throw new Error("Usage: /sync rollback <snapshot-id> [--yes]");
36
+ const config = await loadConfig(options.setup);
37
+ validateMutation();
38
+ if (config.ignorePolicy && (options.yes || options.auto || !ctx.hasUI))
39
+ throw new Error("Ignore-file rollback requires a separate foreground review; --yes cannot confirm it.");
40
+ const backend = await factory(config);
41
+ if (expectedSelection &&
42
+ (backend.identity !== expectedSelection.backendIdentity || config.setupName !== expectedSelection.setup)) {
43
+ throw new Error("Sync setup or storage location changed while history was open; reopen history and retry.");
44
+ }
45
+ await requireNoMergeJournal(config);
46
+ const state = await readStateForConfig(config);
47
+ validateMutation();
48
+ requireIgnoreBaselineReview(ctx, config, state, options);
49
+ requireResolvedDirectionalProgress(state, options, false);
50
+ const decoded = await backend.readSnapshot(target, options.signal);
51
+ validateMutation();
52
+ validatePortableSnapshot(decoded);
53
+ if (!config.ignorePolicy)
54
+ requireLegacyTransferPolicy(decoded);
55
+ if (config.ignorePolicy && expectedSelection?.snapshotId && decoded.id !== expectedSelection.snapshotId)
56
+ throw new Error("Historical snapshot changed while history was open; reopen history and retry.");
57
+ if (!sameLocalFields(decoded.localFields, config.localFields))
58
+ throw new Error("Rollback requires the historical snapshot local-field policy to match the configured rules. Review push --force from current local bytes to migrate policy first; choose matching history afterward.");
59
+ const snapshotOptions = await resolvedSnapshotOptionsForContext(ctx, config, options.signal);
60
+ validateMutation();
61
+ const validateIgnorePolicy = ignorePolicyValidator({ ...snapshotOptions, validateMutation });
62
+ const selected = filterSnapshotForConfigPolicy(config.ignorePolicy || syncSessionsSelected(config) ? decoded : snapshotWithoutSessions(decoded), config, snapshotOptions);
63
+ const remote = portableSnapshot(regenerateSnapshotIdentity(selected), config.localFields);
64
+ const local = await createSnapshot(config.snapshotIdentity, snapshotOptions);
65
+ const expectedHead = await backend.readHead(options.signal);
66
+ const currentRemote = expectedHead
67
+ ? await readSnapshotForHead(backend, expectedHead, options.signal, config)
68
+ : undefined;
69
+ validateMutation();
70
+ if (config.ignorePolicy && currentRemote)
71
+ requireCompatibleRemoteSelection(config, currentRemote);
72
+ if (!(await confirmFieldMigration(ctx, config, state, currentRemote, true, options.signal)))
73
+ return;
74
+ validateMutation();
75
+ const physical = overlayLocalFields(remote, local, config.localFields);
76
+ if (config.scope === "agent-directory")
77
+ requireStableMergeSessionRoot(local, physical, config.scope);
78
+ const upload = config.ignorePolicy
79
+ ? await withPublishedIgnoreRules(remote, config, options.signal)
80
+ : await snapshotForUpload(backend, config, remote, expectedHead, currentRemote, snapshotOptions);
81
+ validateMutation();
82
+ if (config.scope === "agent-directory")
83
+ validatePortableSnapshot(upload);
84
+ if (upload.ignoreRules && !config.skipSecretScan && scanSnapshot({ ...upload, files: [] }).length)
85
+ throw new Error("Refusing to publish possible secrets in the ignore file.");
86
+ const caseCleanup = options.yes ? [] : await inspectCaseCleanup(physical, snapshotOptions);
87
+ validateMutation();
88
+ const reviewedProtectedPaths = protectedSessionPaths(ctx, snapshotOptions.sessionDir);
89
+ if (!options.yes) {
90
+ const title = snapshotIncludesSessions(remote) ? "Rollback pi settings and sessions?" : "Rollback pi settings?";
91
+ const summary = formatRollbackSummary(config, backend.destination, local, physical, target, reviewedProtectedPaths, caseCleanup.map((item) => item.path));
92
+ const confirmed = config.ignorePolicy
93
+ ? await confirmTransferReview(ctx, title, formatTransferReview("Historical files are projected through this device's current ignore rules. Historical rules are not adopted. Retained history is not erased.", ignorePublicationNotice(upload) ?? "", summary, "", "Remote publication:", formatPublicationPreview(currentRemote, upload)), options.signal, validateMutation)
94
+ : await ctx.ui.confirm(title, summary.content, { signal: options.signal });
95
+ validateMutation();
96
+ if (!confirmed) {
97
+ ctx.ui.notify("Rollback cancelled.", "info");
98
+ return;
99
+ }
100
+ }
101
+ validateMutation();
102
+ const currentLocal = await createSnapshot(config.snapshotIdentity, snapshotOptions);
103
+ if (!sameHashes(fileHashMap(currentLocal), fileHashMap(local)))
104
+ throw new Error("Local bytes changed during rollback review.");
105
+ if (syncCheckConfigFingerprint(config) !== syncCheckConfigFingerprint(await loadConfig(options.setup)))
106
+ throw new Error("Settings changed during rollback review.");
107
+ if (!sameRemoteHead(backend, expectedHead, await backend.readHead(options.signal)))
108
+ throw new Error("Remote changed during rollback review.");
109
+ validateMutation();
110
+ throwIfAborted(options.signal);
111
+ const backup = await backupLocal(config.snapshotIdentity, snapshotOptions, options.signal);
112
+ const applySessionDir = await sessionDirForApply(ctx, config.scope ? physical : remote, snapshotOptions);
113
+ const currentState = await readStateForConfig(config);
114
+ if ((validateIgnorePolicy || !options.yes) && syncStateFingerprint(currentState) !== syncStateFingerprint(state))
115
+ throw new Error("Baseline changed during rollback review.");
116
+ requireResolvedDirectionalProgress(currentState, options, false);
117
+ if (!options.yes)
118
+ await revalidateCaseCleanup(caseCleanup, physical, snapshotOptions);
119
+ if (config.scope && applySessionDir !== (await effectiveSessionRoot(ctx, config, options.signal)))
120
+ throw new Error("Pi session storage changed during rollback review.");
121
+ validateMutation();
122
+ if (syncCheckConfigFingerprint(config) !== syncCheckConfigFingerprint(await loadConfig(options.setup)))
123
+ throw new Error("Settings changed during rollback review.");
124
+ validateMutation();
125
+ if (validateIgnorePolicy) {
126
+ if (!sameRemoteHead(backend, expectedHead, await backend.readHead(options.signal)))
127
+ throw new Error("Remote changed during rollback review.");
128
+ await validateIgnorePolicy();
129
+ }
130
+ const protectedPaths = protectedSessionPaths(ctx, snapshotOptions.sessionDir);
131
+ const applyGuards = directionalApplyGuards({
132
+ ctx,
133
+ config,
134
+ backend,
135
+ state,
136
+ sessionDir: snapshotOptions.sessionDir,
137
+ head: expectedHead,
138
+ protectedPaths: reviewedProtectedPaths,
139
+ signal: options.signal,
140
+ onCommit: options.onCommit,
141
+ validateMutation,
142
+ validateIgnorePolicy,
143
+ });
144
+ applyGuards.validateMutation();
145
+ if (!validateIgnorePolicy)
146
+ options.onCommit?.();
147
+ const lastFileHashes = await applySnapshot(physical, protectedPaths, {
148
+ ...snapshotOptions,
149
+ sessionDir: applySessionDir,
150
+ ...applyGuards,
151
+ ...(config.scope === "agent-directory" || validateIgnorePolicy ? { reviewedLocal: local } : {}),
152
+ expectedFileHashes: config.localFields?.length
153
+ ? { "settings.json": fileHashMap(local)["settings.json"] ?? null }
154
+ : undefined,
155
+ });
156
+ validateCommittedOwner();
157
+ let result;
158
+ try {
159
+ const signal = AbortSignal.timeout(POST_LOCAL_COMMIT_TIMEOUT_MS);
160
+ const validatePolicy = ignorePolicyValidator({
161
+ ...snapshotOptions,
162
+ signal,
163
+ validateMutation: validateCommittedOwner,
164
+ });
165
+ const validatePublication = validatePolicy
166
+ ? () => validateDirectionalPublication(ctx, config, { ...snapshotOptions, sessionDir: applySessionDir, signal }, state, lastFileHashes, validatePolicy, "rollback")
167
+ : undefined;
168
+ result = await backend.publishSnapshot(upload, expectedRemoteHead(expectedHead), {
169
+ signal,
170
+ ...(validatePublication ? { validateIgnorePolicy: validatePublication } : {}),
171
+ });
172
+ }
173
+ catch (error) {
174
+ throw new RollbackPublicationError(backup, error);
175
+ }
176
+ try {
177
+ await writeStateForConfig(config, {
178
+ version: VERSION,
179
+ profile: config.snapshotIdentity,
180
+ lastAppliedSnapshot: result.head.snapshotId,
181
+ lastRemoteRevision: result.head.revision,
182
+ lastFileHashes: config.localFields?.length
183
+ ? { ...lastFileHashes, "settings.json": fileHashMap(remote)["settings.json"] }
184
+ : lastFileHashes,
185
+ ...acceptedSelection(config),
186
+ ...(config.localFields !== undefined ? { localFields: config.localFields } : {}),
187
+ }, remote, validateCommittedOwner);
188
+ }
189
+ catch (error) {
190
+ throw new PublicationStatePersistenceError(result.head, error, backup);
191
+ }
192
+ await retireMergeJournal(config);
193
+ await pruneMergeBaselines(config, await readStateForConfig(config), validateCommittedOwner);
194
+ validateCommittedOwner();
195
+ if (options.signal?.aborted)
196
+ return;
197
+ ctx.ui.notify([
198
+ `Rolled back sync setup “${config.setupName}” to ${target}; latest: ${result.head.snapshotId}. Backup: ${backup}`,
199
+ ...result.warnings,
200
+ ]
201
+ .filter(Boolean)
202
+ .join("\n"), result.warnings.length > 0 ? "warning" : "info");
203
+ await maybeReload(ctx, options.signal, validateMutation);
204
+ }
@@ -1,4 +1,4 @@
1
- import { resolvedSnapshotOptionsForContext } from "../snapshot/session-paths.js";
1
+ import { effectiveSessionRoot, resolvedSnapshotOptionsForContext } from "../snapshot/session-paths.js";
2
2
  import { createSnapshot } from "../snapshot/snapshot.js";
3
3
  import { StaleIgnorePolicyError } from "../snapshot/snapshot-transaction-policy.js";
4
4
  import { readStateForConfig, syncStateFingerprint } from "../state/sync-state-store.js";
@@ -19,14 +19,17 @@ export function requireIgnoreBaselineReview(ctx, config, state, options) {
19
19
  throw new Error("Local ignore-file policy or source changed since the last accepted baseline. Review a foreground directional transfer.");
20
20
  }
21
21
  }
22
- export async function validateDirectionalPublication(ctx, config, options, state, expectedHashes, validatePolicy, direction) {
22
+ export async function validateDirectionalPublication(ctx, config, options, state, expectedHashes, validatePolicy, direction, effectiveRoot = false) {
23
23
  const current = await createSnapshot(config.snapshotIdentity, options);
24
24
  if (!sameHashes(fileHashMap(current), expectedHashes))
25
25
  throw new Error(`Local bytes changed at the ${direction} publication boundary.`);
26
26
  if (syncStateFingerprint(await readStateForConfig(config)) !== syncStateFingerprint(state))
27
27
  throw new Error(`Baseline changed at the ${direction} publication boundary.`);
28
28
  if ((config.scope === "agent-directory" || direction === "push") &&
29
- options.sessionDir !== (await resolvedSnapshotOptionsForContext(ctx, config, options.signal)).sessionDir)
29
+ options.sessionDir !==
30
+ (effectiveRoot
31
+ ? await effectiveSessionRoot(ctx, config, options.signal)
32
+ : (await resolvedSnapshotOptionsForContext(ctx, config, options.signal)).sessionDir))
30
33
  throw new Error(`Pi session storage changed at the ${direction} publication boundary.`);
31
34
  await validatePolicy();
32
35
  }
@@ -35,7 +38,7 @@ export function checkLiveProtection(ctx, sessionDir, reviewed) {
35
38
  if (current.size !== reviewed.size || [...current].some((item) => !reviewed.has(item)))
36
39
  throw new StaleIgnorePolicyError("Live session protection changed during review; reopen the review.");
37
40
  }
38
- export function directionalApplyGuards({ ctx, config, backend, state, sessionDir, head, protectedPaths, signal, validateMutation, validateIgnorePolicy, onCommit, }) {
41
+ export function directionalApplyGuards({ ctx, config, backend, state, sessionDir, head, protectedPaths, signal, validateMutation, validateIgnorePolicy, onCommit, effectiveRoot = false, }) {
39
42
  if (!validateIgnorePolicy)
40
43
  return { validateMutation };
41
44
  const validateOwner = () => {
@@ -50,7 +53,10 @@ export function directionalApplyGuards({ ctx, config, backend, state, sessionDir
50
53
  throw new StaleIgnorePolicyError("Remote changed before local apply; reopen the review.");
51
54
  if (syncStateFingerprint(await readStateForConfig(config)) !== syncStateFingerprint(state))
52
55
  throw new StaleIgnorePolicyError("Baseline changed before local apply; reopen the review.");
53
- if (sessionDir !== (await resolvedSnapshotOptionsForContext(ctx, config, signal)).sessionDir)
56
+ if (sessionDir !==
57
+ (effectiveRoot
58
+ ? await effectiveSessionRoot(ctx, config, signal)
59
+ : (await resolvedSnapshotOptionsForContext(ctx, config, signal)).sessionDir))
54
60
  throw new StaleIgnorePolicyError("Pi session storage changed before local apply; reopen the review.");
55
61
  await validateIgnorePolicy();
56
62
  validateOwner();
@@ -0,0 +1,18 @@
1
+ import { snapshotPathLabel } from "./terminal-text.js";
2
+ export function formatRuleChanges(before, after) {
3
+ if (before === after) {
4
+ const message = before === undefined ? "Rule text is unavailable on both sides." : "Rule text is unchanged.";
5
+ return { lines: [message], content: message };
6
+ }
7
+ const lines = (text, prefix) => text === undefined
8
+ ? [`${prefix} (rule text not in snapshot)`]
9
+ : text.split(/(?<=\n)/u).map((line) => `${prefix} ${snapshotPathLabel(JSON.stringify(line))}`);
10
+ return {
11
+ lines: ["Rule text changes. View details for the exact lines."],
12
+ content: [
13
+ "Rule text (− before, + after; JSON quotes show whitespace):",
14
+ ...lines(before, "-"),
15
+ ...lines(after, "+"),
16
+ ].join("\n"),
17
+ };
18
+ }
@@ -49,7 +49,7 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
49
49
  const execute = (operation, payload, execution) => host.run(execution, async () => {
50
50
  if (operation === "ignore.capabilities") {
51
51
  execution.validate();
52
- return { available: ignoreFileSettingsAvailable };
52
+ return { available: ignoreFileSettingsAvailable, ...(ignoreFileSettingsAvailable ? { portableRules: 1 } : {}) };
53
53
  }
54
54
  if (operation === "ignore.migration-offer" || operation === "ignore.migration-defer") {
55
55
  execution.validate();
@@ -225,6 +225,10 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
225
225
  return inspectSync(config, snapshotOptionsForContext(ctx, config), execution.signal, undefined, timings);
226
226
  })));
227
227
  }
228
+ if (operation === "push.foreground" || operation === "pull.foreground") {
229
+ const direction = operation === "push.foreground" ? "push" : "pull";
230
+ return runForegroundDirectional(host, execution, ctx, direction, payload);
231
+ }
228
232
  const supported = [
229
233
  "status",
230
234
  "diff",
@@ -419,9 +423,73 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
419
423
  lifetime: () => (host.cleanupRequired() ? Promise.resolve("pause") : monitor.lifetime()),
420
424
  quiesce: monitor.pause,
421
425
  failure: monitor.blockAutomatic,
426
+ foregroundRecoveryAllowed: monitor.foregroundRecoveryAllowed,
422
427
  },
423
428
  };
424
429
  }
430
+ async function runForegroundDirectional(host, execution, ctx, direction, payload) {
431
+ const fingerprintPattern = /^[a-f0-9]{64}$/u;
432
+ if (!execution.clientId ||
433
+ !ctx.hasUI ||
434
+ !["tui", "rpc"].includes(ctx.mode) ||
435
+ !record(payload) ||
436
+ Object.keys(payload).some((key) => !["setup", "fingerprint", "retryCheckpoint"].includes(key)) ||
437
+ typeof payload.setup !== "string" ||
438
+ !payload.setup ||
439
+ payload.setup.length > 512 ||
440
+ typeof payload.fingerprint !== "string" ||
441
+ !fingerprintPattern.test(payload.fingerprint) ||
442
+ (payload.retryCheckpoint !== undefined &&
443
+ (typeof payload.retryCheckpoint !== "string" || !fingerprintPattern.test(payload.retryCheckpoint)))) {
444
+ throw new Error("Invalid foreground directional request.");
445
+ }
446
+ const { setup, fingerprint, retryCheckpoint } = payload;
447
+ const { withStateDirectoryAccess } = await import("./engine/state/state-directory.js");
448
+ const { withLock } = await import("./engine/state/lock.js");
449
+ const { loadConfigForCheck, syncCheckConfigFingerprint } = await import("./engine/settings/config.js");
450
+ const operations = await import("./engine/sync/sync-operations.js");
451
+ const validate = (config) => {
452
+ execution.validate();
453
+ if (config.setupName !== setup || syncCheckConfigFingerprint(config) !== fingerprint)
454
+ throw new Error("The sync setup changed after the action was selected. No transfer was started for the changed setup.");
455
+ };
456
+ execution.validate();
457
+ return withStateDirectoryAccess(async () => {
458
+ validate(await loadConfigForCheck(undefined, execution.signal));
459
+ if (retryCheckpoint === undefined) {
460
+ await requireHandover(execution);
461
+ validate(await loadConfigForCheck(undefined, execution.signal));
462
+ await initialize(ctx, execution, false);
463
+ }
464
+ else {
465
+ if (!readConsent(execution.root))
466
+ throw new Error("Daemon handover is no longer valid; the transfer was not replayed.");
467
+ await requireStartupRecoveryCleared(execution);
468
+ }
469
+ return host.runForeground(execution, () => withLock(direction, async () => {
470
+ validate(await loadConfigForCheck(undefined, execution.signal));
471
+ let message;
472
+ const outcome = await operations[direction](ctx, {
473
+ ...optionsFrom({ setup, args: [] }, execution, false),
474
+ directionalAction: {
475
+ validate,
476
+ async checkpoint(current) {
477
+ execution.validate();
478
+ if (retryCheckpoint !== undefined && retryCheckpoint !== current)
479
+ throw new Error("The transfer source or destination changed during recovery. The transfer was not replayed.");
480
+ if ((await execution.request("directional-checkpoint", { fingerprint: current })) !== true)
481
+ throw new Error("The original transfer could not be retained for recovery. No transfer was started.");
482
+ execution.validate();
483
+ },
484
+ notifySuccess(value) {
485
+ message = value;
486
+ },
487
+ },
488
+ });
489
+ return { outcome, ...(message === undefined ? {} : { message }) };
490
+ }));
491
+ });
492
+ }
425
493
  async function withJobTimings(ctx, execution, label, action) {
426
494
  const { createStartupTimings } = await import("./engine/sync/startup-timings.js");
427
495
  const timings = createStartupTimings((_ctx, report) => execution.emit("timings", { report }));
@@ -0,0 +1,9 @@
1
+ export function isForegroundDirection(operation) {
2
+ return operation === "push.foreground" || operation === "pull.foreground";
3
+ }
4
+ export function isForegroundQueueOutcome(value) {
5
+ if (!value || typeof value !== "object" || !("foregroundQueueCleanup" in value))
6
+ return false;
7
+ return (value.foregroundQueueCleanup === "before-mutation" ||
8
+ (value.foregroundQueueCleanup === "verified-result" && Object.hasOwn(value, "result")));
9
+ }
@@ -287,6 +287,7 @@ export function createMonitor(root, host) {
287
287
  schedule,
288
288
  lifetime,
289
289
  blockAutomatic,
290
+ foregroundRecoveryAllowed: () => !authorizationFailed,
290
291
  explicitSync(config, execution) {
291
292
  const peer = execution.facts();
292
293
  if (closed || !peer)
@@ -5,16 +5,18 @@ import fs from "node:fs/promises";
5
5
  import { createServer } from "node:http";
6
6
  import lockfile from "proper-lockfile";
7
7
  import { DAEMON_BUILD_VERSION } from "./build-version.js";
8
+ import { ConsentPublicationError, readConsent } from "./consent.js";
8
9
  import { endpointOwner } from "./endpoint.js";
9
10
  import { debugOperation } from "./engine/debug-log.js";
10
11
  import { SyncDecisionRequiredError } from "./engine/sync/sync-errors.js";
12
+ import { isForegroundDirection, isForegroundQueueOutcome } from "./foreground-queue-outcome.js";
11
13
  import { canonicalRootGuard, daemonPaths, matchesPublishedIdentity, privateDirectory, processExists, publishIdentity, readIdentity, readJsonBody, readUpgradeOwner, runtimePaths, } from "./identity.js";
12
14
  import { createIdleExit } from "./idle-exit.js";
13
15
  import { withCleanup } from "./lifecycle.js";
14
16
  import { createPagedReviewOffer, reviewScope } from "./paged-review.js";
15
17
  import { ParticipantAdmission } from "./participant-admission.js";
16
18
  import { createParticipantLedger } from "./participant-ledger.js";
17
- import { ClientContactExpiredError, DAEMON_JOB_CAPACITY, DaemonStoppingError, MAX_MESSAGE_BYTES, MAX_REVIEW_BYTES, operationPrefix, PROTOCOL_VERSION, REVIEW_PAGE_CHARS, record, remoteError, UNKNOWN_JOB_RESULT, validateFacts, validateHandoff, validId, } from "./protocol.js";
19
+ import { ClientContactExpiredError, DAEMON_JOB_CAPACITY, DaemonStoppingError, MAX_MESSAGE_BYTES, MAX_REVIEW_BYTES, OWNERSHIP_CLEANUP_REQUIRED, operationPrefix, PROTOCOL_VERSION, REVIEW_PAGE_CHARS, record, remoteError, UNKNOWN_JOB_RESULT, validateFacts, validateHandoff, validId, } from "./protocol.js";
18
20
  import { ParticipantStateWait } from "./state-wait.js";
19
21
  export async function startServer(root, execute, hooks = {}) {
20
22
  const base = await runtimePaths(root);
@@ -81,6 +83,8 @@ export async function startServer(root, execute, hooks = {}) {
81
83
  let participantGeneration = 0;
82
84
  let closed = false;
83
85
  let stopRequested = false;
86
+ let foregroundRecoveryJob;
87
+ let consentPublicationFailed = false;
84
88
  let automaticClosing = false;
85
89
  let idleExit;
86
90
  let expiring;
@@ -327,6 +331,12 @@ export async function startServer(root, execute, hooks = {}) {
327
331
  },
328
332
  };
329
333
  }
334
+ function assertForegroundQueueReady() {
335
+ if (foregroundRecoveryJob)
336
+ throw Object.assign(new Error("File-queue cleanup is pending; no new daemon work can start."), {
337
+ code: OWNERSHIP_CLEANUP_REQUIRED,
338
+ });
339
+ }
330
340
  function enqueue(id, client, operation, payload) {
331
341
  const peer = requireParticipant(client);
332
342
  if (!id.startsWith(operationPrefix(identity)))
@@ -338,6 +348,7 @@ export async function startServer(root, execute, hooks = {}) {
338
348
  throw new Error("Operation ID was reused with different input.");
339
349
  return duplicate;
340
350
  }
351
+ assertForegroundQueueReady();
341
352
  if (retired.has(id))
342
353
  throw new Error("Operation result expired; reconcile the existing journal before starting new work.");
343
354
  if (retired.size + jobs.size >= 4096)
@@ -384,16 +395,26 @@ export async function startServer(root, execute, hooks = {}) {
384
395
  job.promise = queue
385
396
  .then(async () => {
386
397
  execution.validate();
398
+ assertForegroundQueueReady();
387
399
  job.view.phase = "running";
388
400
  note("started");
389
401
  const result = await execute(operation, payload, execution);
390
402
  if (Buffer.byteLength(JSON.stringify(result ?? null)) > MAX_MESSAGE_BYTES / 2)
391
403
  throw new Error("Operation result exceeds its byte limit; use bounded inspection.");
404
+ if (isForegroundDirection(operation) && isForegroundQueueOutcome(result)) {
405
+ if (result.foregroundQueueCleanup === "before-mutation" && job.committed)
406
+ throw Object.assign(new Error("File-queue release and transfer outcome could not be verified."), {
407
+ code: OWNERSHIP_CLEANUP_REQUIRED,
408
+ });
409
+ foregroundRecoveryJob ??= job;
410
+ }
392
411
  job.view.result = result;
393
412
  job.view.phase = "done";
394
413
  note(result === "cancelled" ? "cancelled" : (job.debugOutcome ?? "completed"));
395
414
  })
396
415
  .catch((error) => {
416
+ if (error instanceof ConsentPublicationError)
417
+ consentPublicationFailed = true;
397
418
  job.view.phase = "failed";
398
419
  job.view.error = remoteError(error);
399
420
  note(!job.committed && (job.controller.signal.aborted || (error instanceof Error && error.name === "AbortError"))
@@ -594,6 +615,52 @@ export async function startServer(root, execute, hooks = {}) {
594
615
  hooks.idle?.();
595
616
  return result;
596
617
  }
618
+ function stop() {
619
+ stopRequested = true;
620
+ for (const peer of participants.values())
621
+ waiters.get(peer)?.changed();
622
+ setImmediate(() => {
623
+ void close().catch(() => { });
624
+ });
625
+ return { stopping: true };
626
+ }
627
+ async function stopForeground(params, signal) {
628
+ if (params.check !== undefined && params.check !== true)
629
+ throw new Error("Invalid foreground stop request.");
630
+ const barrier = await readUpgradeOwner(paths);
631
+ signal?.throwIfAborted();
632
+ assertOwner();
633
+ if (params.check === true
634
+ ? barrier !== undefined
635
+ : barrier?.purpose !== "cleanup" || barrier.instance !== identity.instance || barrier.pid !== identity.pid)
636
+ return { blocked: "A daemon upgrade or recovery is already pending." };
637
+ if (!published || !matchesPublishedIdentity(paths, identity))
638
+ return { blocked: "Daemon owner changed during queue cleanup." };
639
+ const job = foregroundRecoveryJob;
640
+ const requester = validId(params.client) ? participants.get(params.client) : undefined;
641
+ if (job?.view.phase !== "done" ||
642
+ job.view.id !== params.job ||
643
+ !requester ||
644
+ requester.facts.id !== job.client ||
645
+ requester.facts.generation !== params.generation ||
646
+ requester.facts.generation !== job.generation ||
647
+ contactState(requester) !== "active")
648
+ return { blocked: "The completed transfer is not owned by the current Pi session." };
649
+ if (ledger.failed ||
650
+ consentPublicationFailed ||
651
+ hooks.foregroundRecoveryAllowed?.() !== true ||
652
+ Object.values(readConsent(paths.root)?.setups ?? {}).some((setup) => setup.afterExit))
653
+ return { blocked: "Daemon authorization or ownership evidence needs repair before a restart." };
654
+ if (peerOperations.size ||
655
+ expiring ||
656
+ backgroundJobs.size ||
657
+ pending.size ||
658
+ [...jobs.values()].some(({ view }) => view.phase === "queued" || view.phase === "running"))
659
+ return { blocked: "Another daemon operation may still be running; no restart was attempted." };
660
+ if ([...participants.values()].some((peer) => peer !== requester && participates(peer) && processExists(peer.facts.pid)))
661
+ return { blocked: "Another live Pi session still uses this daemon; no restart was attempted." };
662
+ return params.check === true ? { eligible: true } : stop();
663
+ }
597
664
  async function handle(method, params, signal, reviewDetails = false) {
598
665
  if (automaticClosing && method !== "stop")
599
666
  throw new DaemonStoppingError();
@@ -690,6 +757,8 @@ export async function startServer(root, execute, hooks = {}) {
690
757
  return resumeContact(params, signal);
691
758
  }
692
759
  if (method === "startup.bootstrap" && hooks.startup) {
760
+ if (foregroundRecoveryJob)
761
+ throw new Error("File-queue cleanup is pending; startup work did not begin.");
693
762
  if (!record(params) ||
694
763
  Object.keys(params).length !== 4 ||
695
764
  !validId(params.client) ||
@@ -858,15 +927,10 @@ export async function startServer(root, execute, hooks = {}) {
858
927
  await job.promise;
859
928
  return job.view;
860
929
  }
861
- if (method === "stop") {
862
- stopRequested = true;
863
- for (const peer of participants.values())
864
- waiters.get(peer)?.changed();
865
- setImmediate(() => {
866
- void close().catch(() => { });
867
- });
868
- return { stopping: true };
869
- }
930
+ if (method === "foreground-stop")
931
+ return stopForeground(params, signal);
932
+ if (method === "stop")
933
+ return stop();
870
934
  throw new Error("Unknown daemon method.");
871
935
  }
872
936
  const respond = (response, status, value) => {
@@ -898,7 +962,7 @@ export async function startServer(root, execute, hooks = {}) {
898
962
  respond(response, 403, { error: { name: "Error", message: "Invalid daemon identity or protocol." } });
899
963
  return;
900
964
  }
901
- if (["attach", "resume-contact", "startup.bootstrap", "state-wait"].includes(body.method)) {
965
+ if (["attach", "resume-contact", "startup.bootstrap", "state-wait", "foreground-stop"].includes(body.method)) {
902
966
  admissionController = new AbortController();
903
967
  response.once("close", disconnect);
904
968
  if (response.destroyed)
@@ -1134,6 +1198,7 @@ export async function startServer(root, execute, hooks = {}) {
1134
1198
  checkLifetime: () => idleExit?.tick() ?? Promise.resolve(),
1135
1199
  isIdle: () => !closed &&
1136
1200
  !stopRequested &&
1201
+ !foregroundRecoveryJob &&
1137
1202
  [...jobs.values()].every((job) => job.view.phase !== "queued" && job.view.phase !== "running"),
1138
1203
  get closed() {
1139
1204
  return closed;