@narumitw/pi-sync 0.64.0 → 0.65.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.
- package/CHANGELOG.md +10 -0
- package/README.md +76 -7
- package/dist/chunks/{chunk-CKUGCBHP.ts → chunk-AYGMIMCV.ts} +2 -2
- package/dist/chunks/chunk-AYGMIMCV.ts.map +7 -0
- package/dist/chunks/{chunk-F3VODLVQ.ts → chunk-IOM6E5FW.ts} +3 -3
- package/dist/chunks/{chunk-RW44KNFD.ts → chunk-JQ5BAWW2.ts} +182 -12
- package/dist/chunks/chunk-JQ5BAWW2.ts.map +7 -0
- package/dist/chunks/{chunk-NDEZ52SS.ts → chunk-OBVJTKVY.ts} +5 -5
- package/dist/chunks/{chunk-TJ7YNITN.ts → chunk-OWEOZZZE.ts} +2 -2
- package/dist/chunks/{chunk-VPSC7BXM.ts → chunk-SZJOUVCL.ts} +2 -2
- package/dist/chunks/{chunk-YT6PDRMM.ts → chunk-WJQ4TGN5.ts} +17 -17
- package/dist/chunks/chunk-WJQ4TGN5.ts.map +7 -0
- package/dist/chunks/{chunk-4VKWHVUO.ts → chunk-XUZV4OGI.ts} +3 -2
- package/dist/chunks/{chunk-4VKWHVUO.ts.map → chunk-XUZV4OGI.ts.map} +2 -2
- package/dist/chunks/{command-handler-N45GY7AV.ts → command-handler-YZ4DXQ7N.ts} +49 -10
- package/dist/chunks/command-handler-YZ4DXQ7N.ts.map +7 -0
- package/dist/chunks/{conflict-review-5E4M44BA.ts → conflict-review-J7L7S4AR.ts} +2 -2
- package/dist/chunks/{manager-result-dispatcher-FKW55L7I.ts → manager-result-dispatcher-XB75YLEG.ts} +4 -4
- package/dist/chunks/{manager-ui-EV23DPZQ.ts → manager-ui-RGA26Z6G.ts} +40 -38
- package/dist/chunks/manager-ui-RGA26Z6G.ts.map +7 -0
- package/dist/chunks/{merge-review-6YSLSMGS.ts → merge-review-AAC674C6.ts} +3 -3
- package/dist/chunks/{remote-selection-ui-N4NMWFT2.ts → remote-selection-ui-WVMET5RI.ts} +3 -3
- package/dist/chunks/{setup-switch-HY7K3442.ts → setup-switch-644T6KHG.ts} +3 -3
- package/dist/chunks/{setup-wizard-LEKDQ3HK.ts → setup-wizard-YP2KF2WQ.ts} +5 -5
- package/dist/chunks/{sync-inspection-OS2LVOLV.ts → sync-inspection-NBBTSMKR.ts} +2 -2
- package/dist/chunks/{sync-operations-D3MDJUQQ.ts → sync-operations-AIEM2KL2.ts} +2 -2
- package/dist/daemon/dist/client.js +125 -287
- package/dist/daemon/dist/daemon-recovery.js +85 -2
- package/dist/daemon/dist/daemon-startup.js +257 -0
- package/dist/daemon/dist/engine/backends/git/git-backend.js +10 -1
- package/dist/daemon/dist/engine/backends/s3/s3-backend.js +20 -9
- package/dist/daemon/dist/engine/backends/sync-backend.js +16 -0
- package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +19 -6
- package/dist/daemon/dist/engine/sync/directional-action.js +124 -0
- package/dist/daemon/dist/engine/sync/remote-snapshot.js +3 -1
- package/dist/daemon/dist/engine/sync/sync-errors.js +20 -0
- package/dist/daemon/dist/engine/sync/sync-local.js +56 -3
- package/dist/daemon/dist/engine/sync/sync-mutations.js +300 -334
- package/dist/daemon/dist/engine/sync/sync-queries.js +2 -1
- package/dist/daemon/dist/engine/sync/sync-rollback.js +198 -0
- package/dist/daemon/dist/engine/sync/transfer-freshness.js +11 -5
- package/dist/daemon/dist/engine-service.js +68 -0
- package/dist/daemon/dist/foreground-queue-outcome.js +9 -0
- package/dist/daemon/dist/monitor.js +1 -0
- package/dist/daemon/dist/server.js +76 -11
- package/dist/daemon/dist/service-host.js +56 -8
- package/dist/daemon/package.json +1 -1
- package/dist/index.ts +6 -6
- package/docs/daemon-migration.md +3 -6
- package/package.json +2 -2
- package/src/commands/command-execution.ts +56 -2
- package/src/commands/command-handler.ts +2 -0
- package/src/commands/command.ts +2 -1
- package/src/daemon/directional-recovery.ts +103 -0
- package/src/daemon/pi-client.ts +112 -9
- package/src/ui/cancellable-operation.ts +5 -2
- package/src/ui/manager-state.ts +2 -2
- package/src/ui/manager-ui.ts +29 -24
- package/src/ui/merge-review.ts +8 -9
- package/src/ui/sync-confirmation.ts +7 -7
- package/dist/chunks/chunk-CKUGCBHP.ts.map +0 -7
- package/dist/chunks/chunk-RW44KNFD.ts.map +0 -7
- package/dist/chunks/chunk-YT6PDRMM.ts.map +0 -7
- package/dist/chunks/command-handler-N45GY7AV.ts.map +0 -7
- package/dist/chunks/manager-ui-EV23DPZQ.ts.map +0 -7
- /package/dist/chunks/{chunk-F3VODLVQ.ts.map → chunk-IOM6E5FW.ts.map} +0 -0
- /package/dist/chunks/{chunk-NDEZ52SS.ts.map → chunk-OBVJTKVY.ts.map} +0 -0
- /package/dist/chunks/{chunk-TJ7YNITN.ts.map → chunk-OWEOZZZE.ts.map} +0 -0
- /package/dist/chunks/{chunk-VPSC7BXM.ts.map → chunk-SZJOUVCL.ts.map} +0 -0
- /package/dist/chunks/{conflict-review-5E4M44BA.ts.map → conflict-review-J7L7S4AR.ts.map} +0 -0
- /package/dist/chunks/{manager-result-dispatcher-FKW55L7I.ts.map → manager-result-dispatcher-XB75YLEG.ts.map} +0 -0
- /package/dist/chunks/{merge-review-6YSLSMGS.ts.map → merge-review-AAC674C6.ts.map} +0 -0
- /package/dist/chunks/{remote-selection-ui-N4NMWFT2.ts.map → remote-selection-ui-WVMET5RI.ts.map} +0 -0
- /package/dist/chunks/{setup-switch-HY7K3442.ts.map → setup-switch-644T6KHG.ts.map} +0 -0
- /package/dist/chunks/{setup-wizard-LEKDQ3HK.ts.map → setup-wizard-YP2KF2WQ.ts.map} +0 -0
- /package/dist/chunks/{sync-inspection-OS2LVOLV.ts.map → sync-inspection-NBBTSMKR.ts.map} +0 -0
- /package/dist/chunks/{sync-operations-D3MDJUQQ.ts.map → sync-operations-AIEM2KL2.ts.map} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# @narumitw/pi-sync
|
|
2
2
|
|
|
3
|
+
## 0.65.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- c31f9c4: Make the `/sync` manager's Push and Pull actions apply the selected direction without another confirmation. Preserve a restore point before an overwrite, and recover eligible daemon file-queue failures within the same action without repeating a committed write. Direct slash commands retain their existing behavior.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- 25d766a: Show Yes in the first terminal transfer confirmation, even for large reviews. Open View details only when you want to see individual paths. The summary still defaults to No, and Pi Sync verifies the transfer before applying it.
|
|
12
|
+
|
|
3
13
|
## 0.64.0
|
|
4
14
|
|
|
5
15
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -83,7 +83,9 @@ Remote status: Not checked
|
|
|
83
83
|
Last applied: Never synced
|
|
84
84
|
```
|
|
85
85
|
|
|
86
|
-
Use **Sync…** (**Sync now** in RPC)
|
|
86
|
+
Use **Sync…** (**Sync now** in RPC) to merge both ways. **Push to remote** uses this device's version for managed files; **Pull from remote** uses the remote version. After initial daemon handover, each choice can replace or remove managed files at the destination without a second transfer confirmation. Push preserves the previous remote version in **History**; Pull creates a local backup before applying changes. History rollback still follows the current sync rules; see [Recover excluded files from History](#recover-excluded-files-from-history) for files those rules no longer select. Use **View differences** first if you want a preview. Selecting a direction does not authorize background transfers or model use. If a file-queue release cannot be confirmed, Pi Sync attempts recovery within the same action. It does not repeat a known commit or guess when the write outcome is unknown.
|
|
87
|
+
|
|
88
|
+
Type to filter actions; navigation scrolls the list. **Settings**, **History**, and **Diagnostics** remain directly available. Switching appears only when multiple valid setups exist; review and access-recovery actions appear when needed.
|
|
87
89
|
|
|
88
90
|
The summary distinguishes cached observations, recorded background state, and the last successful background transfer; none proves current remote equality. Missing or invalid background evidence is not shown as Waiting. Automatic-transfer permissions and possible AI costs remain visible when enabled; detailed preferences stay in Settings. Setup-specific actions stay bound to the displayed setup; if its configuration changes while the menu is open, review the refreshed setup before continuing. Choose **Check remote status** for a fresh check or **View differences** for file differences; `/sync status`, `/sync diff`, and `/sync help` remain available. Last applied shows a compact snapshot ID and states when application time is unavailable; History retains full IDs.
|
|
89
91
|
|
|
@@ -96,15 +98,15 @@ With Continuous sync configured, **Diagnostics** first opens a scrollable local
|
|
|
96
98
|
|
|
97
99
|
On secondary menus, **Back** and Escape return to the previous screen. In setup inputs and save reviews, cancellation (including Ctrl+C) discards the current unsaved draft and returns to its owning menu. Session replacement or shutdown closes the owning flow.
|
|
98
100
|
Specialized operation and masked-credential prompts show the effective cancellation bindings and keep Ctrl+C as a hard-cancel input when Back is remapped.
|
|
99
|
-
|
|
101
|
+
Other destructive, credential-bearing, and externally visible actions show previews and confirmations where applicable. Autonomous and automatic transfers require their own authorization.
|
|
100
102
|
|
|
101
103
|
### Review transfer changes
|
|
102
104
|
|
|
103
105
|
Unless Autonomous sync or another explicit transfer authorization applies, a merged **Sync now** transfer shows one confirmation with separate local and remote file changes, remote snapshot publication, session inclusion, and unresolved groups. **No, cancel** is initially selected in TUI mode. Up and Down select actions without scrolling the summary. If the summary does not fit, use Page Up and Page Down (or their configured selection-page bindings) to review it before confirming **Yes**. A terminal resize resets the review and selects **No**. Cancellation remains available throughout. This scrollable summary intentionally replaces Kit's clipped choice context, and the safe default differs from Pi's native Yes-first confirmation.
|
|
104
106
|
|
|
105
|
-
**View details** is optional
|
|
107
|
+
In TUI, select **Yes** from the first confirmation to proceed. **View details** is optional and shows the complete add/update/delete lists and unresolved paths. It cannot apply changes. Escape returns to confirmation with **No** selected; Ctrl+C cancels the whole TUI flow. RPC can show details in bounded pages and can require opening them first. RPC offers No first but the client controls visual selection, and protocol cancellation from details returns to confirmation. Session replacement or shutdown closes the flow; local files and remote state are rechecked before transfer.
|
|
106
108
|
|
|
107
|
-
Unresolved paths stay unchanged on each side. A backup and recovery journal protect the transfer; resources do not reload automatically. Remote snapshot publication is shown separately because it can occur without file-content changes. File lists on the main screen are shortened when needed; details retain every path. `--yes` does not bypass a required policy-transition review. Automatic transfers require their own authorization and a compatible policy.
|
|
109
|
+
Unresolved paths stay unchanged on each side. A backup and recovery journal protect the transfer; resources do not reload automatically. Remote snapshot publication is shown separately because it can occur without file-content changes. File lists on the main screen are shortened when needed; details retain every path. `--yes` does not bypass a required policy-transition review. Automatic transfers require their own authorization and a compatible policy. The direct `/sync push` and `/sync pull` routes retain their reviewed behavior and existing flags. Their TUI previews show directional add/update/remove counts and safety notes. Individual file paths are in **View details**, so a large file list does not delay confirmation. Loaded sessions are excluded from local change counts. Pull and rollback also list case-variant path cleanup; changed aliases invalidate approval. Push describes changes to the active immutable snapshot, not physical deletion of retained history. RPC and History rollback keep their existing confirmation protocols, with the complete directional summary. Local bytes, settings, baseline, and remote head are rechecked before applying a reviewed transfer.
|
|
108
110
|
|
|
109
111
|
### Restore sync access
|
|
110
112
|
|
|
@@ -126,7 +128,7 @@ After the same no-other-sync verification, `/sync unlock --stale` provides a det
|
|
|
126
128
|
|
|
127
129
|
**Sync now** merges independent file additions, edits, and deletions against an established baseline. Equal concurrent edits are accepted. With the settings field merge opt-in enabled, supported `settings.json` fields can also merge using a verified accepted ancestor; arrays, nested objects and coupled fields remain atomic. Other divergent file edits, delete/modify conflicts, protected-session changes, selection changes, and case/file-directory collisions still require review; one unresolved path stops the entire merged transfer unless partial sync is explicitly enabled. Explicit push and pull remain directional.
|
|
128
130
|
|
|
129
|
-
When **Sync now
|
|
131
|
+
When **Sync now** requires a direction choice, the manager opens **Resolve sync conflict**.
|
|
130
132
|
The flow names the current setup and explains whether local content, remote content, or the included-content policy changed.
|
|
131
133
|
|
|
132
134
|
An explicit remote content-list mismatch opens **Synced content differs** in the same manager flow.
|
|
@@ -325,7 +327,7 @@ Use `/sync` for initial setup, masked credential entry, and operations that requ
|
|
|
325
327
|
| `/sync` | Set up storage, manage synced content, and review sync operations or recovery. |
|
|
326
328
|
| `/sync help` | Show command usage. |
|
|
327
329
|
| `/sync daemon [status\|handover\|allow-after-exit\|revoke-after-exit]` | Connect to the service or review ownership and unattended permission; no argument connects and shows status. |
|
|
328
|
-
| `/sync daemon recover` |
|
|
330
|
+
| `/sync daemon recover` | Diagnostic fallback: review and stop the current daemon in TUI or RPC without starting a replacement or retrying a transfer. |
|
|
329
331
|
| `/sync use <setup>` | Switch the active local sync setup, following its switch policy. |
|
|
330
332
|
| `/sync init` | Create a local configuration template. |
|
|
331
333
|
| `/sync config` | Show resolved configuration. |
|
|
@@ -393,7 +395,7 @@ S3/R2 publishes `latest.json` and history using ETag `If-Match`, or `If-None-Mat
|
|
|
393
395
|
|
|
394
396
|
Snapshot recovery is guarded: new journals record before/after images, older journals are retired only when their unchanged preimages are provable, and unrecognized bytes remain untouched for manual review. Current-session targets are never restored during startup. Preserve a blocked transaction and its backup, close Pi, and review the private evidence before restoring selected paths; malformed/unsupported journals are not disposable. Pi may have loaded resources before lifecycle recovery, so reload or restart explicitly after recovery if loaded resources need to match the restored files.
|
|
395
397
|
|
|
396
|
-
Before pull or rollback, Pi Sync writes a backup under `<agent-dir>/pi-sync/backups/`. It leaves byte-identical regular files in place when their exact paths already match and no structural change is needed. It checks those files again before accepting the transfer.
|
|
398
|
+
Before pull or rollback, Pi Sync writes a backup under `<agent-dir>/pi-sync/backups/`. It leaves byte-identical regular files in place when their exact paths already match and no structural change is needed. It checks those files again before accepting the transfer. See [Restore a local backup](#restore-a-local-backup) for local edits that were never published.
|
|
397
399
|
Snapshot apply and recovery require canonical agent and session paths. Preflight refuses parent aliases it detects because Pi's file queue uses different keys for existing and missing aliases. Node's path-based writes and deletes cannot prevent another process from replacing a parent directory after a check. Use directories you control, and pause tools that move or replace their directories during sync. Preserve any pending recovery evidence; an unresolved startup recovery barrier still blocks transfers. Old journals recorded under an alias require manual review because their exact root and target paths remain pinned. Changing the agent path alone does not authorize recovery or rewriting those journals.
|
|
398
400
|
Apply preflights paths and checksums, journals mutations, and restores prior state only when current bytes match verified preimages or planned postimages. Unknown intermediate directory states and newer edits require review rather than a blind rollback. An interruption after replacement is armed can require manual recovery even if installation never ran; a later deletion of installed content is not treated as an unfinished remove.
|
|
399
401
|
The file queue coordinates one Pi runtime, not separate processes or lock-unaware editors. Hash-based journals cannot distinguish a later write of identical recorded bytes; they do not provide a cross-process compare-and-swap.
|
|
@@ -401,6 +403,73 @@ Merged transfers instead retain a private publication/apply/baseline journal and
|
|
|
401
403
|
|
|
402
404
|
Removing a local setup or connection never deletes remote data.
|
|
403
405
|
|
|
406
|
+
### Recover excluded files from History
|
|
407
|
+
|
|
408
|
+
Use the snapshot reference reported by Push (use its snapshot ID if no separate reference is shown). History rollback follows the current sync rules and does not restore excluded files. To recover one excluded file without changing the sync rules or remote data, run this example with Node.js 22.19.0 or later from a directory where the installed `@narumitw/pi-sync-daemon` package resolves. Use the same sync setup and storage location as the original Push. The example writes only the selected file to a new private temporary directory; Git may also update its private local cache.
|
|
409
|
+
|
|
410
|
+
```sh
|
|
411
|
+
node --input-type=module - "$HOME/.pi/agent" 'home' 'snapshot-reference' 'sessions/example.jsonl' <<'JS'
|
|
412
|
+
import { createHash } from 'node:crypto';
|
|
413
|
+
import { mkdtemp, realpath, writeFile } from 'node:fs/promises';
|
|
414
|
+
import { tmpdir } from 'node:os';
|
|
415
|
+
import { join } from 'node:path';
|
|
416
|
+
import { configureEngineHost } from '@narumitw/pi-sync-daemon/engine/host';
|
|
417
|
+
import { loadSettingsConfig } from '@narumitw/pi-sync-daemon/engine/settings/config';
|
|
418
|
+
import { withStateDirectoryAccess } from '@narumitw/pi-sync-daemon/engine/state/state-directory';
|
|
419
|
+
import { createSyncBackend } from '@narumitw/pi-sync-daemon/engine/backends/backend-factory';
|
|
420
|
+
|
|
421
|
+
const [agentDir, setup, reference, relative] = process.argv.slice(2);
|
|
422
|
+
const root = await realpath(agentDir);
|
|
423
|
+
configureEngineHost({
|
|
424
|
+
root: () => root,
|
|
425
|
+
mutate: () => { throw new Error('This example only reads the remote snapshot.'); },
|
|
426
|
+
review: async () => false,
|
|
427
|
+
});
|
|
428
|
+
const file = await withStateDirectoryAccess(async () => {
|
|
429
|
+
const backend = await createSyncBackend(await loadSettingsConfig(setup));
|
|
430
|
+
const signal = AbortSignal.timeout(60_000);
|
|
431
|
+
const entry = (await backend.listHistory(signal)).find((item) => item.snapshotRef === reference);
|
|
432
|
+
if (!entry) throw new Error('Snapshot reference not found in History.');
|
|
433
|
+
const snapshot = await backend.readSnapshot(reference, signal);
|
|
434
|
+
const files = snapshot.files.filter((item) => item.path === relative);
|
|
435
|
+
if (snapshot.id !== entry.snapshotId || files.length !== 1) throw new Error('Snapshot or path did not match.');
|
|
436
|
+
return files[0];
|
|
437
|
+
});
|
|
438
|
+
const bytes = Buffer.from(file.contentBase64, 'base64');
|
|
439
|
+
if (createHash('sha256').update(bytes).digest('hex') !== file.sha256) throw new Error('Snapshot checksum mismatch.');
|
|
440
|
+
const output = join(await mkdtemp(join(tmpdir(), 'pi-sync-history-')), 'restored');
|
|
441
|
+
await writeFile(output, bytes, { flag: 'wx', mode: 0o600 });
|
|
442
|
+
console.log(output);
|
|
443
|
+
JS
|
|
444
|
+
```
|
|
445
|
+
|
|
446
|
+
Compare the recovered file with any current copy. If you need to put it back, close Pi first and copy it to the intended local path. For a logical `sessions/` path, use the original session directory. Do not overwrite a symlink or publish the temporary file. Remove the temporary copy when finished.
|
|
447
|
+
|
|
448
|
+
### Restore a local backup
|
|
449
|
+
|
|
450
|
+
Use the exact backup path reported by Pull. Close all Pi processes using the affected agent directory. The backup is private and can contain unpushed settings and sessions. Extract the file you want to restore into a private temporary directory before replacing any local file. This example verifies the file's stored checksum and does not contact remote storage:
|
|
451
|
+
|
|
452
|
+
```sh
|
|
453
|
+
backup='/path/reported/by/pull.json.gz'
|
|
454
|
+
relative='settings.json'
|
|
455
|
+
scratch=$(mktemp -d)
|
|
456
|
+
node --input-type=commonjs - "$backup" "$relative" "$scratch/restored" <<'JS'
|
|
457
|
+
const { createHash } = require('node:crypto');
|
|
458
|
+
const { readFileSync, writeFileSync } = require('node:fs');
|
|
459
|
+
const { gunzipSync } = require('node:zlib');
|
|
460
|
+
const [archive, relative, output] = process.argv.slice(2);
|
|
461
|
+
const snapshot = JSON.parse(gunzipSync(readFileSync(archive), { maxOutputLength: 512 * 1024 * 1024 }));
|
|
462
|
+
const entries = snapshot.files.filter((file) => file.path === relative);
|
|
463
|
+
if (entries.length !== 1) throw new Error('Expected exactly one matching backup path.');
|
|
464
|
+
const bytes = Buffer.from(entries[0].contentBase64, 'base64');
|
|
465
|
+
if (createHash('sha256').update(bytes).digest('hex') !== entries[0].sha256) throw new Error('Backup checksum mismatch.');
|
|
466
|
+
writeFileSync(output, bytes, { flag: 'wx', mode: 0o600 });
|
|
467
|
+
JS
|
|
468
|
+
printf '%s\n' "$scratch/restored"
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
Compare the extracted file with the current version. Keep any newer changes you need, then copy the verified file back to its original path. For a logical `sessions/` path, use the session directory from before Pull, not necessarily `<agent-dir>/sessions/`. Do not copy over a symlink, publish a local backup, or extract it wholesale over the agent directory. Remove the temporary copy after verifying your restored file.
|
|
472
|
+
|
|
404
473
|
The operational state root is `<agent-dir>/pi-sync/`.
|
|
405
474
|
An existing installation continues using `<agent-dir>/.pisync/` and shows migration guidance on startup; it is never moved merely because no sync is active.
|
|
406
475
|
Close every other Pi process, then run `/sync migrate-state` and confirm the review (or pass `--yes` for an already reviewed RPC workflow).
|
|
@@ -9,7 +9,7 @@ async function runCancellableOperation(ctx, message, route, runRoute, options =
|
|
|
9
9
|
const result = await runCancellableTask(
|
|
10
10
|
ctx,
|
|
11
11
|
message,
|
|
12
|
-
(signal, onCommit, onDialog) => runRoute(route, signal, onCommit, options.target, onDialog),
|
|
12
|
+
(signal, onCommit, onDialog) => runRoute(route, signal, onCommit, options.target, onDialog, void 0, options.directionalFingerprint),
|
|
13
13
|
options
|
|
14
14
|
);
|
|
15
15
|
return result.kind === "completed" ? result.value ?? { kind: "failed" } : result;
|
|
@@ -111,4 +111,4 @@ export {
|
|
|
111
111
|
runCancellableOperation,
|
|
112
112
|
runCancellableTask
|
|
113
113
|
};
|
|
114
|
-
//# sourceMappingURL=chunk-
|
|
114
|
+
//# sourceMappingURL=chunk-AYGMIMCV.ts.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/ui/cancellable-operation.ts"],
|
|
4
|
+
"sourcesContent": ["import { BorderedLoader, type ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { isKeyRelease, Key, matchesKey, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport { formatInteractionHints, runCustomInteraction } from \"@narumitw/pi-tui-kit\";\nimport type { SetupPullOutcome } from \"../sync/setup-switch.js\";\nimport type { SyncDecision } from \"../sync/sync-decision.js\";\nimport type { RemoteSelectionDecision } from \"../sync/sync-policy.js\";\n\nexport type RunRouteResult =\n | { kind: \"completed\"; outcome?: SetupPullOutcome }\n | { kind: \"decision-required\"; decision: SyncDecision }\n | { kind: \"remote-selection-required\"; decision: RemoteSelectionDecision }\n | { kind: \"failed\" };\n\nexport type RunRoute = (\n route: string,\n signal?: AbortSignal,\n onCommit?: () => void,\n target?: string,\n onDialog?: (active: boolean) => void,\n retryRefusal?: boolean,\n directionalFingerprint?: string,\n) => Promise<RunRouteResult | undefined>;\n\nexport type CancellableOperationResult = RunRouteResult | { kind: \"closed\" } | { kind: \"cancelled\" };\n\ninterface CancellableOperationOptions {\n commitAware?: boolean;\n cancelAcrossDialogs?: boolean;\n cancelledMessage?: string | null;\n target?: string;\n directionalFingerprint?: string;\n signal?: AbortSignal;\n isCurrent?: () => boolean;\n}\n\nexport async function runCancellableOperation(\n ctx: ExtensionContext,\n message: string,\n route: string,\n runRoute: RunRoute,\n options: CancellableOperationOptions = {},\n): Promise<CancellableOperationResult> {\n const result = await runCancellableTask(\n ctx,\n message,\n (signal, onCommit, onDialog) =>\n runRoute(route, signal, onCommit, options.target, onDialog, undefined, options.directionalFingerprint),\n options,\n );\n return result.kind === \"completed\" ? (result.value ?? { kind: \"failed\" }) : result;\n}\n\nexport type CancellableTaskResult<Value> =\n | { kind: \"completed\"; value: Value }\n | { kind: \"closed\" }\n | { kind: \"cancelled\" };\n\n/** Keep non-route work under the same cancellation and drain owner as transfers. */\nexport async function runCancellableTask<Value>(\n ctx: ExtensionContext,\n message: string,\n task: (\n signal: AbortSignal | undefined,\n onCommit?: () => void,\n onDialog?: (active: boolean) => void,\n ) => Promise<Value>,\n options: Omit<CancellableOperationOptions, \"target\" | \"directionalFingerprint\"> = {},\n): Promise<CancellableTaskResult<Value>> {\n const {\n commitAware = false,\n cancelAcrossDialogs = false,\n cancelledMessage = \"Check cancelled; no settings or files were changed.\",\n signal,\n isCurrent = () => true,\n } = options;\n if (signal?.aborted || !isCurrent()) return { kind: \"closed\" };\n if (ctx.mode !== \"tui\") return { kind: \"completed\", value: await task(signal) };\n let commitStarted = false;\n let taskResult!: Value;\n const interaction = await runCustomInteraction<{ cancelled?: boolean; error?: unknown }, ExtensionContext>(ctx, {\n signal,\n isCurrent: () => !signal?.aborted && isCurrent(),\n create: ({ tui, theme, keybindings, signal: interactionSignal, complete }) => {\n const loader = new BorderedLoader(tui, theme, message, { cancellable: false });\n const cancelHint = formatInteractionHints(keybindings, [\n {\n keys: [...keybindings.getKeys(\"tui.select.cancel\").filter((key) => !hasControlCharacter(key)), \"ctrl+c\"],\n label: \"cancel\",\n },\n ]);\n const cancel = (data: string) => {\n // Raw terminal listeners run before Pi filters Kitty key releases.\n if (isKeyRelease(data)) return false;\n if (!matchesKey(data, Key.ctrl(\"c\")) && !keybindings.matches(data, \"tui.select.cancel\")) return false;\n if (commitStarted) {\n ctx.ui.notify(\"Applying or publishing has started and cannot be cancelled safely.\", \"warning\");\n } else complete({ cancelled: true });\n return true;\n };\n // Pi dialogs replace this loader and restore the normal editor. Defer\n // ordinary keys while they are open; retain raw cancellation afterward.\n // Ctrl+C remains the root flow's hard-cancel path regardless of focus.\n let activeDialogs = 0;\n const unsubscribe = cancelAcrossDialogs\n ? ctx.ui.onTerminalInput((data) => {\n if (isKeyRelease(data)) return;\n if (activeDialogs > 0 && !matchesKey(data, Key.ctrl(\"c\"))) return;\n return cancel(data) ? { consume: true } : undefined;\n })\n : undefined;\n let pendingTask: Promise<Value>;\n try {\n pendingTask = task(\n interactionSignal,\n commitAware ? () => (commitStarted = true) : undefined,\n cancelAcrossDialogs\n ? (active) => {\n activeDialogs += active ? 1 : -1;\n }\n : undefined,\n );\n } catch (error) {\n unsubscribe?.();\n loader.dispose();\n throw error;\n }\n const operation = pendingTask.then(\n (result) => {\n taskResult = result;\n complete({});\n },\n (error: unknown) => complete({ error }),\n );\n return {\n render(width: number) {\n if (width <= 0) return [];\n const safeWidth = Math.max(1, width);\n const lines = loader.render(safeWidth);\n const bottomBorder = lines.at(-1);\n return [\n ...lines.slice(0, -1),\n truncateToWidth(theme.fg(\"dim\", cancelHint), safeWidth, \"\"),\n ...(bottomBorder === undefined ? [] : [bottomBorder]),\n ];\n },\n invalidate: () => loader.invalidate(),\n handleInput: cancel,\n dispose() {\n unsubscribe?.();\n loader.dispose();\n },\n waitForPending: () => operation,\n };\n },\n });\n if (interaction.kind === \"error\") throw interaction.error;\n if (interaction.kind !== \"completed\") return { kind: \"closed\" };\n if (interaction.value.cancelled) {\n if (cancelledMessage) ctx.ui.notify(cancelledMessage, \"info\");\n return { kind: \"cancelled\" };\n }\n if (interaction.value.error) throw interaction.value.error;\n return { kind: \"completed\", value: taskResult };\n}\n\nfunction hasControlCharacter(value: string) {\n // biome-ignore lint/suspicious/noControlCharactersInRegex: Unsafe key labels must be omitted.\n return /[\\u0000-\\u001f\\u007f-\\u009f]/u.test(value);\n}\n"],
|
|
5
|
+
"mappings": "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",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
// @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
|
|
3
3
|
import {
|
|
4
4
|
showRemoteSelectionReview
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-OWEOZZZE.ts";
|
|
6
6
|
import {
|
|
7
7
|
runCancellableOperation
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-AYGMIMCV.ts";
|
|
9
9
|
import {
|
|
10
10
|
loadConfig,
|
|
11
11
|
syncConfigReviewIdentity
|
|
@@ -208,4 +208,4 @@ async function dispatchManagerResult(ctx, initialResult, origin, runRoute, signa
|
|
|
208
208
|
export {
|
|
209
209
|
dispatchManagerResult
|
|
210
210
|
};
|
|
211
|
-
//# sourceMappingURL=chunk-
|
|
211
|
+
//# sourceMappingURL=chunk-IOM6E5FW.ts.map
|
|
@@ -19,7 +19,7 @@ import {
|
|
|
19
19
|
// src/daemon/pi-client.ts
|
|
20
20
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
21
21
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
22
|
-
import { realpathSync } from "node:fs";
|
|
22
|
+
import { lstatSync, realpathSync } from "node:fs";
|
|
23
23
|
import fs from "node:fs/promises";
|
|
24
24
|
import path2 from "node:path";
|
|
25
25
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
@@ -198,6 +198,88 @@ function observeDebugJob(operation, append) {
|
|
|
198
198
|
};
|
|
199
199
|
}
|
|
200
200
|
|
|
201
|
+
// src/daemon/directional-recovery.ts
|
|
202
|
+
function isForegroundDirection(operation) {
|
|
203
|
+
return operation === "push.foreground" || operation === "pull.foreground";
|
|
204
|
+
}
|
|
205
|
+
var DirectionalCheckpoint = class {
|
|
206
|
+
constructor(connection, expected) {
|
|
207
|
+
this.connection = connection;
|
|
208
|
+
this.expected = expected;
|
|
209
|
+
}
|
|
210
|
+
connection;
|
|
211
|
+
expected;
|
|
212
|
+
job;
|
|
213
|
+
fingerprint;
|
|
214
|
+
accept(connection, job, fingerprint2) {
|
|
215
|
+
if (connection !== this.connection || this.job !== job || typeof fingerprint2 !== "string" || !/^[a-f0-9]{64}$/u.test(fingerprint2) || this.expected !== void 0 && fingerprint2 !== this.expected || this.fingerprint !== void 0 && fingerprint2 !== this.fingerprint)
|
|
216
|
+
return false;
|
|
217
|
+
this.fingerprint = fingerprint2;
|
|
218
|
+
return true;
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
function recoveryOutcome(value) {
|
|
222
|
+
if (!value || typeof value !== "object" || !("foregroundQueueCleanup" in value)) return;
|
|
223
|
+
if (value.foregroundQueueCleanup === "before-mutation") return { phase: "unchanged" };
|
|
224
|
+
if (value.foregroundQueueCleanup === "verified-result" && "result" in value)
|
|
225
|
+
return { phase: "completed", result: value.result };
|
|
226
|
+
}
|
|
227
|
+
function restoreMessage(value) {
|
|
228
|
+
return value && typeof value === "object" && "message" in value && typeof value.message === "string" ? ` ${value.message}` : "";
|
|
229
|
+
}
|
|
230
|
+
var CompletedDirectionalRecoveryError = class extends Error {
|
|
231
|
+
};
|
|
232
|
+
function cancelledAfterCompletion(result, cause) {
|
|
233
|
+
const error = new CompletedDirectionalRecoveryError(
|
|
234
|
+
`The transfer finished, but file-queue recovery was cancelled.${restoreMessage(result)}`,
|
|
235
|
+
{ cause }
|
|
236
|
+
);
|
|
237
|
+
error.name = "AbortError";
|
|
238
|
+
return error;
|
|
239
|
+
}
|
|
240
|
+
async function runDirectionalRecovery(connection, signal, run, recover, markCleanupRequired) {
|
|
241
|
+
signal.throwIfAborted();
|
|
242
|
+
const attempt2 = new DirectionalCheckpoint(connection);
|
|
243
|
+
const result = await run(attempt2);
|
|
244
|
+
const primary = recoveryOutcome(result);
|
|
245
|
+
if (!primary) return result;
|
|
246
|
+
markCleanupRequired();
|
|
247
|
+
let replacement;
|
|
248
|
+
const bounded = AbortSignal.any([signal, AbortSignal.timeout(45e3)]);
|
|
249
|
+
try {
|
|
250
|
+
bounded.throwIfAborted();
|
|
251
|
+
if (!attempt2.job || primary.phase === "unchanged" && !attempt2.fingerprint)
|
|
252
|
+
throw new Error("The original transfer scope could not be verified.");
|
|
253
|
+
replacement = await recover(connection, attempt2.job, bounded);
|
|
254
|
+
bounded.throwIfAborted();
|
|
255
|
+
} catch (error) {
|
|
256
|
+
if (signal.aborted) {
|
|
257
|
+
if (primary.phase === "completed") throw cancelledAfterCompletion(primary.result, signal.reason);
|
|
258
|
+
throw signal.reason;
|
|
259
|
+
}
|
|
260
|
+
const detail = bounded.aborted ? "The daemon did not recover in time." : errorMessage(error);
|
|
261
|
+
if (primary.phase === "completed")
|
|
262
|
+
throw new CompletedDirectionalRecoveryError(
|
|
263
|
+
`The transfer finished, but file-queue recovery stopped. ${detail}${restoreMessage(primary.result)}`,
|
|
264
|
+
{ cause: error }
|
|
265
|
+
);
|
|
266
|
+
throw new Error(`No transfer was applied, but file-queue recovery stopped. ${detail}`, { cause: error });
|
|
267
|
+
}
|
|
268
|
+
if (primary.phase === "completed") return primary.result;
|
|
269
|
+
const retry = new DirectionalCheckpoint(replacement, attempt2.fingerprint);
|
|
270
|
+
const retried = await run(retry, attempt2.fingerprint);
|
|
271
|
+
const remaining = recoveryOutcome(retried);
|
|
272
|
+
if (!remaining) return retried;
|
|
273
|
+
markCleanupRequired();
|
|
274
|
+
if (remaining.phase === "completed") {
|
|
275
|
+
if (signal.aborted) throw cancelledAfterCompletion(remaining.result, signal.reason);
|
|
276
|
+
throw new CompletedDirectionalRecoveryError(
|
|
277
|
+
`Transfer finished, but file-queue cleanup is still uncertain after one recovery attempt.${restoreMessage(remaining.result)}`
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
throw new Error("File-queue release could not be verified after one recovery attempt. No transfer was applied.");
|
|
281
|
+
}
|
|
282
|
+
|
|
201
283
|
// src/daemon/queue-release-ui.ts
|
|
202
284
|
function createQueueReleaseUI(show, warn) {
|
|
203
285
|
const retries = /* @__PURE__ */ new Map();
|
|
@@ -589,6 +671,8 @@ var PiDaemonClient = class {
|
|
|
589
671
|
uiContext;
|
|
590
672
|
reloadRequest;
|
|
591
673
|
pendingReload;
|
|
674
|
+
directionalCheckpoint;
|
|
675
|
+
recoveringDirectionalOwner = false;
|
|
592
676
|
busy = /* @__PURE__ */ new Set();
|
|
593
677
|
initialized = false;
|
|
594
678
|
startupDebug = false;
|
|
@@ -647,8 +731,8 @@ var PiDaemonClient = class {
|
|
|
647
731
|
cwd: this.ctx.cwd,
|
|
648
732
|
mode: this.ctx.mode,
|
|
649
733
|
hasUI: !protectionOnly && this.ctx.hasUI,
|
|
650
|
-
idle: !protectionOnly && !this.paused && !this.busy.size && this.ctx.isIdle(),
|
|
651
|
-
ready: !protectionOnly && this.initialized,
|
|
734
|
+
idle: !protectionOnly && !this.recoveringDirectionalOwner && !this.paused && !this.busy.size && this.ctx.isIdle(),
|
|
735
|
+
ready: !protectionOnly && !this.recoveringDirectionalOwner && this.initialized,
|
|
652
736
|
startupDebug: this.startupDebug,
|
|
653
737
|
sessionFile: canonicalPath(manager.getSessionFile?.()),
|
|
654
738
|
sessionId: manager.getSessionId?.(),
|
|
@@ -682,12 +766,14 @@ var PiDaemonClient = class {
|
|
|
682
766
|
}
|
|
683
767
|
async attachExisting({ allowUpgrade = false } = {}) {
|
|
684
768
|
this.validate();
|
|
769
|
+
this.assertNoDirectionalRecovery();
|
|
685
770
|
if (!allowUpgrade && !this.paused && this.connection?.contactState === "active") return !this.protectionOnly;
|
|
686
771
|
const address = await findDaemon2(this.root).catch((error) => {
|
|
687
772
|
this.recordDebug({ event: "connection", outcome: "failed" });
|
|
688
773
|
throw error;
|
|
689
774
|
});
|
|
690
775
|
this.validate();
|
|
776
|
+
this.assertNoDirectionalRecovery();
|
|
691
777
|
if (!address) {
|
|
692
778
|
this.recordDebug({ event: "connection", outcome: "skipped" });
|
|
693
779
|
return false;
|
|
@@ -701,7 +787,7 @@ var PiDaemonClient = class {
|
|
|
701
787
|
return true;
|
|
702
788
|
} catch (error) {
|
|
703
789
|
this.validate();
|
|
704
|
-
if (this.paused) throw error;
|
|
790
|
+
if (this.paused || this.recoveringDirectionalOwner) throw error;
|
|
705
791
|
upgradeFailure = safeTerminalText(errorMessage(error));
|
|
706
792
|
}
|
|
707
793
|
}
|
|
@@ -731,7 +817,15 @@ var PiDaemonClient = class {
|
|
|
731
817
|
this.validateFactsScope(connection);
|
|
732
818
|
});
|
|
733
819
|
}
|
|
820
|
+
assertNoDirectionalRecovery() {
|
|
821
|
+
if (this.recoveringDirectionalOwner)
|
|
822
|
+
throw new Error("Pi Sync is recovering the daemon for a transfer. Retry after recovery finishes.");
|
|
823
|
+
}
|
|
734
824
|
async connect(existing, requestSignal) {
|
|
825
|
+
this.assertNoDirectionalRecovery();
|
|
826
|
+
return this.attachConnection(existing, requestSignal);
|
|
827
|
+
}
|
|
828
|
+
async attachConnection(existing, requestSignal) {
|
|
735
829
|
const startupSignal = requestSignal ? AbortSignal.any([this.signal, requestSignal]) : this.signal;
|
|
736
830
|
const validateStartup = () => {
|
|
737
831
|
this.validate();
|
|
@@ -784,7 +878,7 @@ var PiDaemonClient = class {
|
|
|
784
878
|
contact: (state) => this.observeContact(connection2, state),
|
|
785
879
|
queueRelease: (event) => this.observeQueueRelease(connection2, event),
|
|
786
880
|
error: () => {
|
|
787
|
-
if (this.ownsContactUI() && connection2.facts.hasUI && !this.releaseUI.retrying)
|
|
881
|
+
if (!this.recoveringDirectionalOwner && this.ownsContactUI() && connection2.facts.hasUI && !this.releaseUI.retrying)
|
|
788
882
|
this.showContactStatus("sync service unavailable", "blocked", true);
|
|
789
883
|
}
|
|
790
884
|
});
|
|
@@ -986,9 +1080,11 @@ var PiDaemonClient = class {
|
|
|
986
1080
|
}
|
|
987
1081
|
async verifyConnection(signal) {
|
|
988
1082
|
const connection = await this.connect(void 0, signal);
|
|
989
|
-
signal
|
|
1083
|
+
this.validateFactsScope(connection, signal);
|
|
1084
|
+
this.assertNoDirectionalRecovery();
|
|
990
1085
|
await this.publishFacts(connection, signal);
|
|
991
|
-
signal
|
|
1086
|
+
this.validateFactsScope(connection, signal);
|
|
1087
|
+
this.assertNoDirectionalRecovery();
|
|
992
1088
|
return connection;
|
|
993
1089
|
}
|
|
994
1090
|
async readSettings(repair = false) {
|
|
@@ -1003,6 +1099,14 @@ var PiDaemonClient = class {
|
|
|
1003
1099
|
}
|
|
1004
1100
|
return decode(await this.run(repair ? "settings.repair-read" : "settings.read", {}));
|
|
1005
1101
|
}
|
|
1102
|
+
canReportDirectionalResult() {
|
|
1103
|
+
try {
|
|
1104
|
+
this.validateFactsScope();
|
|
1105
|
+
return !this.pendingReload;
|
|
1106
|
+
} catch {
|
|
1107
|
+
return false;
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1006
1110
|
get ownershipCleanupRequired() {
|
|
1007
1111
|
return this.cleanupRequired;
|
|
1008
1112
|
}
|
|
@@ -1029,6 +1133,33 @@ var PiDaemonClient = class {
|
|
|
1029
1133
|
);
|
|
1030
1134
|
return result;
|
|
1031
1135
|
}
|
|
1136
|
+
async recoverDirectionalOwner(connection, job, signal, assertRoot) {
|
|
1137
|
+
this.validateFactsScope(connection, signal);
|
|
1138
|
+
this.recoveringDirectionalOwner = true;
|
|
1139
|
+
try {
|
|
1140
|
+
this.stopContactRepair(true);
|
|
1141
|
+
await this.factsQueue;
|
|
1142
|
+
this.validateFactsScope(connection, signal);
|
|
1143
|
+
await connection.recoverForeground(job, signal);
|
|
1144
|
+
if (this.connection !== connection) throw new Error("The Pi participant changed during daemon recovery.");
|
|
1145
|
+
this.confirmRecoveryExit(connection.identity);
|
|
1146
|
+
await this.gate.releaseAfterDrain();
|
|
1147
|
+
this.connection = void 0;
|
|
1148
|
+
this.connecting = void 0;
|
|
1149
|
+
this.cleanupRequired = false;
|
|
1150
|
+
this.validateFactsScope(void 0, signal);
|
|
1151
|
+
assertRoot();
|
|
1152
|
+
const replacement = await ensureDaemon(this.root, signal, { compatibleOnly: true });
|
|
1153
|
+
this.validateFactsScope(void 0, signal);
|
|
1154
|
+
assertRoot();
|
|
1155
|
+
const attached = await this.attachConnection(replacement, signal);
|
|
1156
|
+
this.validateFactsScope(attached, signal);
|
|
1157
|
+
assertRoot();
|
|
1158
|
+
return attached;
|
|
1159
|
+
} finally {
|
|
1160
|
+
this.recoveringDirectionalOwner = false;
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1032
1163
|
async runCurrent(operation, payload, signal, ctx = this.ctx, onCommit, reload, diagnostics) {
|
|
1033
1164
|
this.validate();
|
|
1034
1165
|
signal?.throwIfAborted();
|
|
@@ -1057,7 +1188,41 @@ var PiDaemonClient = class {
|
|
|
1057
1188
|
const clearForeground = () => this.releaseUI.finishForeground(Boolean(this.releaseContext()));
|
|
1058
1189
|
runSignal.addEventListener("abort", clearForeground, { once: true });
|
|
1059
1190
|
try {
|
|
1060
|
-
const
|
|
1191
|
+
const root = isForegroundDirection(operation) ? lstatSync(this.root) : void 0;
|
|
1192
|
+
const assertRoot = () => {
|
|
1193
|
+
const current2 = lstatSync(this.root);
|
|
1194
|
+
if (!root || !current2.isDirectory() || current2.dev !== root.dev || current2.ino !== root.ino)
|
|
1195
|
+
throw new Error("The agent directory changed during the transfer.");
|
|
1196
|
+
};
|
|
1197
|
+
const intent = root ? structuredClone(payload) : payload;
|
|
1198
|
+
const result = root ? await runDirectionalRecovery(
|
|
1199
|
+
connection,
|
|
1200
|
+
runSignal,
|
|
1201
|
+
async (checkpoint, retryCheckpoint) => {
|
|
1202
|
+
const current2 = checkpoint.connection;
|
|
1203
|
+
this.validateFactsScope(current2, runSignal);
|
|
1204
|
+
assertRoot();
|
|
1205
|
+
this.directionalCheckpoint = checkpoint;
|
|
1206
|
+
try {
|
|
1207
|
+
return await current2.run(
|
|
1208
|
+
operation,
|
|
1209
|
+
retryCheckpoint === void 0 ? intent : { ...intent, retryCheckpoint },
|
|
1210
|
+
runSignal,
|
|
1211
|
+
onCommit,
|
|
1212
|
+
(id) => {
|
|
1213
|
+
checkpoint.job = id;
|
|
1214
|
+
diagnostics?.onSubmit(id);
|
|
1215
|
+
}
|
|
1216
|
+
);
|
|
1217
|
+
} finally {
|
|
1218
|
+
this.directionalCheckpoint = void 0;
|
|
1219
|
+
}
|
|
1220
|
+
},
|
|
1221
|
+
(owner, job, recoverySignal) => this.recoverDirectionalOwner(owner, job, recoverySignal, assertRoot),
|
|
1222
|
+
() => {
|
|
1223
|
+
this.cleanupRequired = true;
|
|
1224
|
+
}
|
|
1225
|
+
) : await connection.run(operation, payload, runSignal, onCommit, diagnostics?.onSubmit);
|
|
1061
1226
|
if (runSignal.aborted || reload?.signal.aborted) diagnostics?.rejected(void 0, true);
|
|
1062
1227
|
else diagnostics?.returned(result);
|
|
1063
1228
|
if (request?.received && reload && !this.paused && !reload.signal.aborted && !signal?.aborted) {
|
|
@@ -1176,7 +1341,7 @@ var PiDaemonClient = class {
|
|
|
1176
1341
|
this.validate();
|
|
1177
1342
|
}
|
|
1178
1343
|
async update() {
|
|
1179
|
-
if (this.connection && !this.paused && !this.disposed && !this.signal.aborted)
|
|
1344
|
+
if (this.connection && !this.recoveringDirectionalOwner && !this.paused && !this.disposed && !this.signal.aborted)
|
|
1180
1345
|
await this.publishFacts(this.connection);
|
|
1181
1346
|
}
|
|
1182
1347
|
async pagedMergeReview(connection, callback, loadDetails, signal) {
|
|
@@ -1188,7 +1353,7 @@ var PiDaemonClient = class {
|
|
|
1188
1353
|
this.validate();
|
|
1189
1354
|
if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) throw new Error("This client cannot present safety reviews.");
|
|
1190
1355
|
const { title, confirmationLabel, summaryLines } = callback.payload;
|
|
1191
|
-
const { confirmMergeReview } = await import("./merge-review-
|
|
1356
|
+
const { confirmMergeReview } = await import("./merge-review-AAC674C6.ts");
|
|
1192
1357
|
if (!isCurrent()) return false;
|
|
1193
1358
|
this.validate();
|
|
1194
1359
|
const result = await confirmMergeReview(
|
|
@@ -1214,6 +1379,10 @@ var PiDaemonClient = class {
|
|
|
1214
1379
|
this.validate();
|
|
1215
1380
|
signal.throwIfAborted();
|
|
1216
1381
|
if (this.paused) throw new Error("Pi session is changing; no new work is authorized.");
|
|
1382
|
+
if (callback.kind === "directional-checkpoint") {
|
|
1383
|
+
this.validateFactsScope(connection, this.runSignal);
|
|
1384
|
+
return !protectionOnly && this.directionalCheckpoint?.accept(connection, callback.job, payload?.fingerprint) === true;
|
|
1385
|
+
}
|
|
1217
1386
|
if (callback.kind === "queue-acquire") {
|
|
1218
1387
|
if (this.pendingReload) throw new Error("Pi resources are about to reload.");
|
|
1219
1388
|
if (payload.background && !this.facts().idle) throw new Error("Pi is busy; background apply was not granted.");
|
|
@@ -1244,7 +1413,7 @@ var PiDaemonClient = class {
|
|
|
1244
1413
|
if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) throw new Error("This client cannot present safety reviews.");
|
|
1245
1414
|
let result;
|
|
1246
1415
|
if (callback.kind === "merge-review" && typeof payload.title === "string" && typeof payload.content === "string") {
|
|
1247
|
-
const { confirmMergeReview } = await import("./merge-review-
|
|
1416
|
+
const { confirmMergeReview } = await import("./merge-review-AAC674C6.ts");
|
|
1248
1417
|
this.validate();
|
|
1249
1418
|
combined.throwIfAborted();
|
|
1250
1419
|
result = await confirmMergeReview(
|
|
@@ -1311,6 +1480,7 @@ var PiDaemonClient = class {
|
|
|
1311
1480
|
};
|
|
1312
1481
|
|
|
1313
1482
|
export {
|
|
1483
|
+
CompletedDirectionalRecoveryError,
|
|
1314
1484
|
currentPiDaemonClient,
|
|
1315
1485
|
installPiDaemonHost,
|
|
1316
1486
|
bindPiDaemonClient,
|
|
@@ -1318,4 +1488,4 @@ export {
|
|
|
1318
1488
|
withPiDaemonClient,
|
|
1319
1489
|
remoteOperation
|
|
1320
1490
|
};
|
|
1321
|
-
//# sourceMappingURL=chunk-
|
|
1491
|
+
//# sourceMappingURL=chunk-JQ5BAWW2.ts.map
|