@narumitw/pi-sync-daemon 0.9.0 → 0.10.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 +19 -0
- package/README.md +11 -1
- package/dist/cli.js +2 -0
- package/dist/client-transport.d.ts +14 -0
- package/dist/client-transport.js +66 -0
- package/dist/client.d.ts +15 -8
- package/dist/client.js +116 -86
- package/dist/consent.js +33 -11
- package/dist/daemon-debug.d.ts +3 -0
- package/dist/daemon-debug.js +33 -0
- package/dist/daemon-recovery.d.ts +4 -0
- package/dist/daemon-recovery.js +75 -0
- package/dist/engine/backends/git/git-backend.d.ts +8 -0
- package/dist/engine/backends/git/git-backend.js +39 -12
- package/dist/engine/backends/git/git-runner.js +6 -1
- package/dist/engine/backends/git/git-storage.js +5 -9
- package/dist/engine/backends/publication-encoding.d.ts +3 -0
- package/dist/engine/backends/publication-encoding.js +19 -0
- package/dist/engine/backends/s3/s3-backend.js +10 -12
- package/dist/engine/backends/sync-backend.d.ts +4 -0
- package/dist/engine/backends/webdav/webdav-backend.d.ts +0 -2
- package/dist/engine/backends/webdav/webdav-backend.js +15 -26
- package/dist/engine/backends/webdav/webdav-client.js +10 -0
- package/dist/engine/commands/command-types.d.ts +1 -0
- package/dist/engine/debug-log.d.ts +27 -0
- package/dist/engine/debug-log.js +134 -0
- package/dist/engine/ignore/ignore-initialization.d.ts +5 -1
- package/dist/engine/ignore/ignore-initialization.js +50 -14
- package/dist/engine/ignore/ignore-settings.js +11 -14
- package/dist/engine/ignore/ignore-source.d.ts +1 -1
- package/dist/engine/ignore/ignore-source.js +1 -1
- package/dist/engine/paths.d.ts +2 -0
- package/dist/engine/paths.js +7 -1
- package/dist/engine/settings/config-file.d.ts +10 -1
- package/dist/engine/settings/config-file.js +62 -17
- package/dist/engine/settings/config.d.ts +7 -0
- package/dist/engine/settings/config.js +49 -14
- package/dist/engine/snapshot/snapshot-apply.d.ts +2 -1
- package/dist/engine/snapshot/snapshot-apply.js +30 -8
- package/dist/engine/snapshot/snapshot-codec.js +3 -1
- package/dist/engine/snapshot/snapshot-payload.d.ts +4 -0
- package/dist/engine/snapshot/snapshot-payload.js +32 -0
- package/dist/engine/snapshot/snapshot-transaction-images.d.ts +2 -0
- package/dist/engine/snapshot/snapshot-transaction-images.js +34 -0
- package/dist/engine/snapshot/snapshot-transaction.d.ts +4 -1
- package/dist/engine/snapshot/snapshot-transaction.js +50 -7
- package/dist/engine/snapshot/snapshot-types.d.ts +10 -2
- package/dist/engine/snapshot/snapshot.d.ts +3 -1
- package/dist/engine/snapshot/snapshot.js +64 -25
- package/dist/engine/state/lock.d.ts +2 -1
- package/dist/engine/state/lock.js +157 -17
- package/dist/engine/sync/continuous-sync.d.ts +10 -1
- package/dist/engine/sync/continuous-sync.js +35 -11
- package/dist/engine/sync/initialization.d.ts +1 -1
- package/dist/engine/sync/initialization.js +2 -2
- package/dist/engine/sync/local-fields.d.ts +6 -1
- package/dist/engine/sync/local-fields.js +42 -19
- package/dist/engine/sync/merged-sync.js +13 -10
- package/dist/engine/sync/remote-snapshot.js +18 -3
- package/dist/engine/sync/session-push.js +13 -4
- package/dist/engine/sync/startup-bootstrap.d.ts +1 -0
- package/dist/engine/sync/startup-bootstrap.js +105 -0
- package/dist/engine/sync/startup-recovery-evidence.d.ts +1 -0
- package/dist/engine/sync/startup-recovery-evidence.js +37 -0
- package/dist/engine/sync/startup-timings.d.ts +9 -2
- package/dist/engine/sync/startup-timings.js +80 -8
- package/dist/engine/sync/sync-error-guidance.js +22 -4
- package/dist/engine/sync/sync-inspection.js +4 -7
- package/dist/engine/sync/sync-local.d.ts +2 -1
- package/dist/engine/sync/sync-local.js +3 -1
- package/dist/engine/sync/sync-mutations.js +13 -7
- package/dist/engine/sync/sync-policy.d.ts +2 -0
- package/dist/engine/sync/sync-policy.js +9 -1
- package/dist/engine/sync/sync-state.d.ts +8 -3
- package/dist/engine/sync/sync-state.js +12 -4
- package/dist/engine/ui/sync-format.d.ts +16 -5
- package/dist/engine/ui/sync-format.js +23 -55
- package/dist/engine/ui/transfer-review.d.ts +2 -1
- package/dist/engine/ui/transfer-review.js +3 -3
- package/dist/engine-service.d.ts +6 -0
- package/dist/engine-service.js +54 -10
- package/dist/identity.d.ts +5 -2
- package/dist/identity.js +36 -6
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/monitor.js +20 -1
- package/dist/paged-review.d.ts +35 -0
- package/dist/paged-review.js +177 -0
- package/dist/participant-ledger.d.ts +16 -0
- package/dist/participant-ledger.js +149 -0
- package/dist/protocol.d.ts +15 -0
- package/dist/protocol.js +4 -0
- package/dist/server.d.ts +7 -0
- package/dist/server.js +268 -120
- package/dist/service-host.d.ts +2 -1
- package/dist/service-host.js +29 -9
- package/dist/state-wait-jobs.d.ts +8 -0
- package/dist/state-wait-jobs.js +23 -0
- package/dist/state-wait.d.ts +7 -0
- package/dist/state-wait.js +34 -0
- package/docs/architecture.md +23 -1
- package/package.json +1 -1
|
@@ -19,7 +19,9 @@ export function protectedSessionPaths(ctx, sessionRoot = sessionDirFromContext(c
|
|
|
19
19
|
export { captureMutationOwner } from "./mutation-owner.js";
|
|
20
20
|
export async function backupLocal(profile, options = {}, signal) {
|
|
21
21
|
throwIfAborted(signal);
|
|
22
|
-
|
|
22
|
+
return backupSnapshot(await createSnapshot(profile, { ...options, signal }), signal);
|
|
23
|
+
}
|
|
24
|
+
export async function backupSnapshot(snapshot, signal) {
|
|
23
25
|
throwIfAborted(signal);
|
|
24
26
|
const backupDirectory = path.join(stateDir(), "backups");
|
|
25
27
|
await fs.mkdir(backupDirectory, { recursive: true, mode: 0o700 });
|
|
@@ -7,7 +7,7 @@ import { applySnapshot } from "../snapshot/snapshot-apply.js";
|
|
|
7
7
|
import { ignorePolicyValidator } from "../snapshot/snapshot-transaction-policy.js";
|
|
8
8
|
import { pruneMergeBaselines } from "../state/merge-baseline-store.js";
|
|
9
9
|
import { readStateForConfig, syncStateFingerprint, writeStateForConfig } from "../state/sync-state-store.js";
|
|
10
|
-
import { countPreservedRemoteFiles, formatPublicationPreview, formatPullSummary, formatPushSummary, formatRollbackSummary, } from "../ui/sync-format.js";
|
|
10
|
+
import { countPreservedRemoteFiles, formatPublicationPreview, formatPullSummary, formatPushSummary, formatRollbackSummary, formatTransferReview, } from "../ui/sync-format.js";
|
|
11
11
|
import { setSyncStatus } from "../ui/sync-status.js";
|
|
12
12
|
import { confirmTransferReview } from "../ui/transfer-review.js";
|
|
13
13
|
import { startupTransferEnabled } from "./agent-policy.js";
|
|
@@ -422,6 +422,7 @@ export async function syncBoth(ctx, options, factory = createSyncBackend) {
|
|
|
422
422
|
if (!options.auto && syncSelectionHasContent(config) && state.lastAppliedSnapshot)
|
|
423
423
|
return mergeSync(ctx, options, factory);
|
|
424
424
|
if (!syncSelectionHasContent(config)) {
|
|
425
|
+
options.noteDebugOutcome?.("skipped");
|
|
425
426
|
if (!options.silent) {
|
|
426
427
|
ctx.ui.notify(`Sync setup “${config.setupName}” includes no files. Choose included content in /sync Settings before syncing.`, "warning");
|
|
427
428
|
}
|
|
@@ -512,7 +513,8 @@ export async function syncBoth(ctx, options, factory = createSyncBackend) {
|
|
|
512
513
|
directMessage: "Remote settings match, but local and remote Pi sessions differ. Run /sync diff, then manually choose /sync pull or /sync push.",
|
|
513
514
|
});
|
|
514
515
|
}
|
|
515
|
-
await pullInitialSource()
|
|
516
|
+
if ((await pullInitialSource()) === "cancelled")
|
|
517
|
+
options.noteDebugOutcome?.("cancelled");
|
|
516
518
|
return;
|
|
517
519
|
}
|
|
518
520
|
await acceptMatchingState(remote);
|
|
@@ -531,16 +533,20 @@ export async function syncBoth(ctx, options, factory = createSyncBackend) {
|
|
|
531
533
|
return;
|
|
532
534
|
}
|
|
533
535
|
if (remoteChanged) {
|
|
534
|
-
await pullInitialSource()
|
|
536
|
+
if ((await pullInitialSource()) === "cancelled")
|
|
537
|
+
options.noteDebugOutcome?.("cancelled");
|
|
535
538
|
return;
|
|
536
539
|
}
|
|
537
540
|
if (localChanged || !remote) {
|
|
538
|
-
await push(ctx, options, { config, state, local, backend }, factory)
|
|
541
|
+
if ((await push(ctx, options, { config, state, local, backend }, factory)) === "cancelled")
|
|
542
|
+
options.noteDebugOutcome?.("cancelled");
|
|
539
543
|
return;
|
|
540
544
|
}
|
|
541
545
|
if (shouldRefreshSyncedState(remote, head, state, config, (left, right) => backend.sameRevision(left, right))) {
|
|
542
546
|
await acceptMatchingState(remote);
|
|
543
547
|
}
|
|
548
|
+
else
|
|
549
|
+
options.noteDebugOutcome?.("skipped");
|
|
544
550
|
if (!options.silent)
|
|
545
551
|
ctx.ui.notify("pi-sync is already up to date.", "info");
|
|
546
552
|
}
|
|
@@ -605,8 +611,8 @@ export async function rollback(ctx, options, factory = createSyncBackend, expect
|
|
|
605
611
|
const title = snapshotIncludesSessions(remote) ? "Rollback pi settings and sessions?" : "Rollback pi settings?";
|
|
606
612
|
const summary = formatRollbackSummary(config, backend.destination, local, physical, target, reviewedProtectedPaths, caseCleanup.map((item) => item.path));
|
|
607
613
|
const confirmed = config.ignorePolicy
|
|
608
|
-
? await confirmTransferReview(ctx, title,
|
|
609
|
-
: await ctx.ui.confirm(title, summary, { signal: options.signal });
|
|
614
|
+
? 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.", "", summary, "", "Remote publication:", formatPublicationPreview(currentRemote, upload)), options.signal, validateMutation)
|
|
615
|
+
: await ctx.ui.confirm(title, summary.content, { signal: options.signal });
|
|
610
616
|
validateMutation();
|
|
611
617
|
if (!confirmed) {
|
|
612
618
|
ctx.ui.notify("Rollback cancelled.", "info");
|
|
@@ -739,7 +745,7 @@ async function confirmPush(ctx, options, config, backend, local, upload, head, r
|
|
|
739
745
|
? inspectRemoteSelection(config.include, remote, config.exclude, config).ignorePolicyComparison
|
|
740
746
|
: undefined;
|
|
741
747
|
const confirmed = await confirmTransferReview(ctx, title, comparison && comparison !== "match"
|
|
742
|
-
?
|
|
748
|
+
? formatTransferReview(formatIgnorePolicyComparison(comparison), "Only files selected by this device's rules are published. Remote rules are not adopted.", "", summary)
|
|
743
749
|
: summary, options.signal, validateMutation);
|
|
744
750
|
throwIfAborted(options.signal);
|
|
745
751
|
if (confirmed)
|
|
@@ -11,6 +11,8 @@ export declare function selectionForSnapshot(include: unknown, exclude?: unknown
|
|
|
11
11
|
/** Metadata equality, not policy compatibility: bind the whole projection to its immutable image. */
|
|
12
12
|
export declare function sameSnapshotSelection(left: SnapshotSelection | undefined, right: SnapshotSelection | undefined): boolean;
|
|
13
13
|
export declare function validateSnapshotSelection(snapshot: Pick<Snapshot, "version" | "selection">): void;
|
|
14
|
+
export declare function assertSnapshotPathExcludesDebugLog(filePath: unknown): void;
|
|
15
|
+
export declare function assertSnapshotExcludesDebugLog(snapshot: Pick<Snapshot, "files">): void;
|
|
14
16
|
export declare function requireLegacyTransferPolicy(snapshot: Partial<Pick<Snapshot, "version" | "selection">>): void;
|
|
15
17
|
export declare function sameSyncInclude(left: unknown, right: unknown): boolean;
|
|
16
18
|
export declare function compareSyncInclude(local: unknown, remote: unknown): {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { isDeniedPath, toPosix } from "../paths.js";
|
|
3
|
+
import { DEBUG_LOG_FILENAME, isDebugLogPath, isDeniedPath, toPosix } from "../paths.js";
|
|
4
4
|
import { IGNORE_SNAPSHOT_VERSION, } from "../snapshot/snapshot-types.js";
|
|
5
5
|
import { compilePathRules, compileSyncExclude, normalizeSyncExclude, sameSyncExclude } from "./exclude-policy.js";
|
|
6
6
|
export const BUILT_IN_SYNC_ROOTS = [
|
|
@@ -202,6 +202,14 @@ export function validateSnapshotSelection(snapshot) {
|
|
|
202
202
|
if ((snapshot.version === IGNORE_SNAPSHOT_VERSION) !== (selection?.version === 4))
|
|
203
203
|
throw new Error("Ignore-file policy requires snapshot version 6 and selection version 4.");
|
|
204
204
|
}
|
|
205
|
+
export function assertSnapshotPathExcludesDebugLog(filePath) {
|
|
206
|
+
if (typeof filePath === "string" && isDebugLogPath(filePath))
|
|
207
|
+
throw new Error(`Snapshot contains the local-only ${DEBUG_LOG_FILENAME}. Review the old snapshot before retrying sync.`);
|
|
208
|
+
}
|
|
209
|
+
export function assertSnapshotExcludesDebugLog(snapshot) {
|
|
210
|
+
for (const file of snapshot.files)
|
|
211
|
+
assertSnapshotPathExcludesDebugLog(file?.path);
|
|
212
|
+
}
|
|
205
213
|
export function requireLegacyTransferPolicy(snapshot) {
|
|
206
214
|
if (snapshot.version === IGNORE_SNAPSHOT_VERSION || snapshot.selection?.version === 4)
|
|
207
215
|
throw new Error("This setup cannot transfer an ignore-file snapshot without a reviewed local ignore policy.");
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { RemoteHead } from "../backends/sync-backend.js";
|
|
2
|
-
import type { Snapshot } from "../snapshot/snapshot-types.js";
|
|
2
|
+
import type { Snapshot, SnapshotFileHash, SnapshotObservation } from "../snapshot/snapshot-types.js";
|
|
3
3
|
import type { SyncState } from "../state/state-types.js";
|
|
4
4
|
import { type SyncSelectionConfig } from "./sync-policy.js";
|
|
5
5
|
type SyncPolicyConfig = SyncSelectionConfig & {
|
|
@@ -7,13 +7,18 @@ type SyncPolicyConfig = SyncSelectionConfig & {
|
|
|
7
7
|
setupName?: string;
|
|
8
8
|
ignoreSourceIdentity?: string;
|
|
9
9
|
};
|
|
10
|
-
export declare function hasLocalChanges(local: Snapshot, state: SyncState, config: SyncPolicyConfig): boolean;
|
|
10
|
+
export declare function hasLocalChanges(local: Snapshot | SnapshotObservation, state: SyncState, config: SyncPolicyConfig): boolean;
|
|
11
11
|
export declare function remoteChangedSinceState(head: RemoteHead | undefined, state: SyncState, config: SyncPolicyConfig, sameRevision: (left: string, right: string) => boolean): boolean;
|
|
12
12
|
export declare function hasRemoteChanges(remote: Snapshot, state: SyncState, config: SyncPolicyConfig, ignoredPaths?: Set<string>): boolean;
|
|
13
13
|
export declare function sameHashes(left: Record<string, string>, right: Record<string, string>): boolean;
|
|
14
|
-
export declare function fileHashMap(snapshot:
|
|
14
|
+
export declare function fileHashMap(snapshot: {
|
|
15
|
+
files: readonly SnapshotFileHash[];
|
|
16
|
+
}): {
|
|
15
17
|
[k: string]: string;
|
|
16
18
|
};
|
|
19
|
+
export declare function rawSnapshotHashIdentity(snapshot: {
|
|
20
|
+
files: readonly SnapshotFileHash[];
|
|
21
|
+
}): string;
|
|
17
22
|
export declare function snapshotHashesMatchState(snapshot: Snapshot, state: SyncState, config: SyncPolicyConfig, ignoredPaths?: Set<string>): boolean;
|
|
18
23
|
export declare function snapshotsMatch(left: Snapshot, right: Snapshot): boolean;
|
|
19
24
|
export declare function syncPolicyChanged(state: SyncState, config: SyncPolicyConfig): boolean;
|
|
@@ -1,14 +1,17 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
1
2
|
import { toPosix } from "../paths.js";
|
|
2
3
|
import { canonicalSnapshotPathForConfig, filterSnapshotForConfigPolicy, isSessionPath } from "../snapshot/snapshot.js";
|
|
3
4
|
import { sameSyncExclude } from "./exclude-policy.js";
|
|
4
|
-
import { portableSnapshot, sameLocalFields } from "./local-fields.js";
|
|
5
|
+
import { portableObservation, portableSnapshot, sameLocalFields } from "./local-fields.js";
|
|
5
6
|
import { compareIgnorePolicy, configuredSnapshotPathMatcher, customIncludePathsByLower, includeFromSelectionConfig, localIgnorePolicyKey, normalizeSyncInclude, syncDirectoryPolicyKey, syncSessionsSelected, } from "./sync-policy.js";
|
|
6
7
|
export function hasLocalChanges(local, state, config) {
|
|
7
|
-
|
|
8
|
+
if (state.lastAppliedSnapshot &&
|
|
8
9
|
(state.scope !== config.scope ||
|
|
9
10
|
!sameLocalFields(state.localFields, config.localFields) ||
|
|
10
|
-
!sameSelectionRules(state, config)))
|
|
11
|
-
|
|
11
|
+
!sameSelectionRules(state, config)))
|
|
12
|
+
return true;
|
|
13
|
+
const portable = "version" in local ? portableSnapshot(local, config.localFields) : portableObservation(local, config.localFields);
|
|
14
|
+
return !sameHashes(fileHashMap(portable), stateHashMapForConfig(state, config));
|
|
12
15
|
}
|
|
13
16
|
export function remoteChangedSinceState(head, state, config, sameRevision) {
|
|
14
17
|
if (!head)
|
|
@@ -46,6 +49,11 @@ export function sameHashes(left, right) {
|
|
|
46
49
|
export function fileHashMap(snapshot) {
|
|
47
50
|
return Object.fromEntries(snapshot.files.map((file) => [file.path, file.sha256]));
|
|
48
51
|
}
|
|
52
|
+
export function rawSnapshotHashIdentity(snapshot) {
|
|
53
|
+
return createHash("sha256")
|
|
54
|
+
.update(JSON.stringify(fileHashMap(snapshot)))
|
|
55
|
+
.digest("hex");
|
|
56
|
+
}
|
|
49
57
|
function stateHashMapForConfig(state, config) {
|
|
50
58
|
const includePaths = customIncludePathsByLower(includeFromSelectionConfig(config));
|
|
51
59
|
const configured = configuredSnapshotPathMatcher(config);
|
|
@@ -3,11 +3,22 @@ import type { CommonSyncConfig } from "../settings/settings-types.js";
|
|
|
3
3
|
import type { Snapshot } from "../snapshot/snapshot-types.js";
|
|
4
4
|
export declare function formatDiff(local: Snapshot, remote: Snapshot): string;
|
|
5
5
|
export declare function formatSnapshotOnlyDiff(title: string, snapshot: Snapshot): string;
|
|
6
|
-
export
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
export declare function
|
|
6
|
+
export interface TransferReview {
|
|
7
|
+
lines: readonly string[];
|
|
8
|
+
content: string;
|
|
9
|
+
}
|
|
10
|
+
export declare function formatTransferReview(...sections: (string | TransferReview)[]): TransferReview;
|
|
11
|
+
export declare function formatPushSummary(config: CommonSyncConfig, destination: string, upload: Snapshot, head: RemoteHead | undefined, preservedRemoteFileCount?: number, remote?: Snapshot): TransferReview;
|
|
12
|
+
export declare function formatApplyPreview(local: Snapshot, remote: Snapshot, protectedPaths?: ReadonlySet<string>, additionalRemovals?: readonly string[]): {
|
|
13
|
+
lines: string[];
|
|
14
|
+
content: string;
|
|
15
|
+
};
|
|
16
|
+
export declare function formatPullSummary(config: CommonSyncConfig, destination: string, local: Snapshot, remote: Snapshot, protectedPaths: ReadonlySet<string>, additionalRemovals?: readonly string[]): TransferReview;
|
|
17
|
+
export declare function formatRollbackSummary(config: CommonSyncConfig, destination: string, local: Snapshot, remote: Snapshot, requestedSnapshot: string, protectedPaths: ReadonlySet<string>, additionalRemovals?: readonly string[]): TransferReview;
|
|
18
|
+
export declare function formatPublicationPreview(remote: Snapshot | undefined, upload: Snapshot): {
|
|
19
|
+
lines: string[];
|
|
20
|
+
content: string;
|
|
21
|
+
};
|
|
11
22
|
export declare function countPreservedRemoteFiles(local: Snapshot, upload: Snapshot): number;
|
|
12
23
|
export declare function publicationCapabilityDescription(capability: PublicationCapability): "atomic-conditional (verified atomic precondition)" | "conditional-required (read-only until atomic preconditions are verified)" | "lease-protected (exact expected-ref update)" | "read-check-write-verify (visible races rejected; simultaneous unseen races remain possible)";
|
|
13
24
|
export declare function redact(value: string): string;
|
|
@@ -37,29 +37,22 @@ export function formatSnapshotOnlyDiff(title, snapshot) {
|
|
|
37
37
|
...snapshot.files.map((file) => `Add: ${snapshotPathLabel(file.path)}`),
|
|
38
38
|
].join("\n");
|
|
39
39
|
}
|
|
40
|
+
export function formatTransferReview(...sections) {
|
|
41
|
+
return {
|
|
42
|
+
lines: sections.flatMap((section) => (typeof section === "string" ? section.split("\n") : section.lines)),
|
|
43
|
+
content: sections.map((section) => (typeof section === "string" ? section : section.content)).join("\n"),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
40
46
|
export function formatPushSummary(config, destination, upload, head, preservedRemoteFileCount = 0, remote) {
|
|
41
|
-
return
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
...(remote && inspectRemoteSelection(config.include, remote, config.exclude, config).kind === "different"
|
|
51
|
-
? ["Included-content policy effect: replace the differing remote selection with this setup's local selection."]
|
|
52
|
-
: []),
|
|
53
|
-
formatPublicationPreview(remote, upload),
|
|
54
|
-
config.skipSecretScan
|
|
55
|
-
? "Warning: possible-secret scanning is disabled for this push."
|
|
56
|
-
: preservedRemoteFileCount > 0
|
|
57
|
-
? `Possible secrets in locally managed files were scanned before this prompt; ${preservedRemoteFileCount} preserved remote file(s) were not rescanned.`
|
|
58
|
-
: "Possible secrets were scanned before this prompt.",
|
|
59
|
-
...(config.scope === "agent-directory"
|
|
60
|
-
? ["Warning: synced files may contain secrets or other sensitive data that the scanner cannot identify."]
|
|
61
|
-
: []),
|
|
62
|
-
].join("\n");
|
|
47
|
+
return formatTransferReview(`Sync setup: ${safeTerminalText(config.setupName)}`, `Storage location: ${safeTerminalText(destination)}`, `Direction: Local → Remote. Source: ${safeTerminalText(agentDir())}.`, `Publish a snapshot containing ${upload.files.length} files; unchanged and preserved files are not counted as changes.`, `Sessions: ${upload.syncSessions ? "included — may contain private conversations" : "not included"}`, ...excludedPolicyLines(config), head ? `Remote latest: ${safeTerminalText(head.snapshotId)}` : "Remote latest: empty", "Publication effect: the backend's active head will reference the new immutable snapshot. Removed paths leave the active snapshot; retained history is not erased.", ...(remote && inspectRemoteSelection(config.include, remote, config.exclude, config).kind === "different"
|
|
48
|
+
? ["Included-content policy effect: replace the differing remote selection with this setup's local selection."]
|
|
49
|
+
: []), formatPublicationPreview(remote, upload), config.skipSecretScan
|
|
50
|
+
? "Warning: possible-secret scanning is disabled for this push."
|
|
51
|
+
: preservedRemoteFileCount > 0
|
|
52
|
+
? `Possible secrets in locally managed files were scanned before this prompt; ${preservedRemoteFileCount} preserved remote file(s) were not rescanned.`
|
|
53
|
+
: "Possible secrets were scanned before this prompt.", ...(config.scope === "agent-directory"
|
|
54
|
+
? ["Warning: synced files may contain secrets or other sensitive data that the scanner cannot identify."]
|
|
55
|
+
: []));
|
|
63
56
|
}
|
|
64
57
|
function excludedPolicyLines(config) {
|
|
65
58
|
const scoped = config.scope === "agent-directory";
|
|
@@ -89,36 +82,10 @@ export function formatApplyPreview(local, remote, protectedPaths = new Set(), ad
|
|
|
89
82
|
}, protectedPaths, additionalRemovals);
|
|
90
83
|
}
|
|
91
84
|
export function formatPullSummary(config, destination, local, remote, protectedPaths, additionalRemovals = []) {
|
|
92
|
-
return [
|
|
93
|
-
`Sync setup: ${safeTerminalText(config.setupName)}`,
|
|
94
|
-
`Storage location: ${safeTerminalText(destination)}`,
|
|
95
|
-
"Direction: Remote → Local.",
|
|
96
|
-
`Snapshot: ${safeTerminalText(remote.id)}`,
|
|
97
|
-
...excludedPolicyLines(config),
|
|
98
|
-
`Sessions: ${remote.syncSessions ? "included — may contain private conversations" : "not included"}`,
|
|
99
|
-
`Protected live sessions: ${protectedPaths.size || "none"}`,
|
|
100
|
-
formatApplyPreview(local, remote, protectedPaths, additionalRemovals),
|
|
101
|
-
...(additionalRemovals.length
|
|
102
|
-
? ["Case-variant aliases listed above are removed before writing canonical paths."]
|
|
103
|
-
: []),
|
|
104
|
-
"A local backup is created before these writes/deletes. The remote active snapshot is unchanged.",
|
|
105
|
-
].join("\n");
|
|
85
|
+
return formatTransferReview(`Sync setup: ${safeTerminalText(config.setupName)}`, `Storage location: ${safeTerminalText(destination)}`, "Direction: Remote → Local.", `Snapshot: ${safeTerminalText(remote.id)}`, ...excludedPolicyLines(config), `Sessions: ${remote.syncSessions ? "included — may contain private conversations" : "not included"}`, `Protected live sessions: ${protectedPaths.size || "none"}`, formatApplyPreview(local, remote, protectedPaths, additionalRemovals), ...(additionalRemovals.length ? ["Case-variant aliases are removed before writing canonical paths."] : []), "A local backup is created before these writes/deletes. The remote active snapshot is unchanged.");
|
|
106
86
|
}
|
|
107
87
|
export function formatRollbackSummary(config, destination, local, remote, requestedSnapshot, protectedPaths, additionalRemovals = []) {
|
|
108
|
-
return [
|
|
109
|
-
`Sync setup: ${safeTerminalText(config.setupName)}`,
|
|
110
|
-
`Storage location: ${safeTerminalText(destination)}`,
|
|
111
|
-
"Direction: Historical snapshot → Local and remote active head.",
|
|
112
|
-
`Snapshot: ${safeTerminalText(requestedSnapshot)}`,
|
|
113
|
-
...excludedPolicyLines(config),
|
|
114
|
-
`Sessions: ${remote.syncSessions ? "included — may contain private conversations" : "not included"}`,
|
|
115
|
-
`Protected live sessions: ${protectedPaths.size || "none"}`,
|
|
116
|
-
formatApplyPreview(local, remote, protectedPaths, additionalRemovals),
|
|
117
|
-
...(additionalRemovals.length
|
|
118
|
-
? ["Case-variant aliases listed above are removed before writing canonical paths."]
|
|
119
|
-
: []),
|
|
120
|
-
"A local backup is created before applying; the backend's active head will change.",
|
|
121
|
-
].join("\n");
|
|
88
|
+
return formatTransferReview(`Sync setup: ${safeTerminalText(config.setupName)}`, `Storage location: ${safeTerminalText(destination)}`, "Direction: Historical snapshot → Local and remote active head.", `Snapshot: ${safeTerminalText(requestedSnapshot)}`, ...excludedPolicyLines(config), `Sessions: ${remote.syncSessions ? "included — may contain private conversations" : "not included"}`, `Protected live sessions: ${protectedPaths.size || "none"}`, formatApplyPreview(local, remote, protectedPaths, additionalRemovals), ...(additionalRemovals.length ? ["Case-variant aliases are removed before writing canonical paths."] : []), "A local backup is created before applying; the backend's active head will change.");
|
|
122
89
|
}
|
|
123
90
|
export function formatPublicationPreview(remote, upload) {
|
|
124
91
|
return formatDirectionalChanges(remote, upload, {
|
|
@@ -138,11 +105,12 @@ function formatDirectionalChanges(before, after, labels, protectedPaths = new Se
|
|
|
138
105
|
}
|
|
139
106
|
const counts = transferCounts(changes);
|
|
140
107
|
const label = { Add: labels.add, Update: labels.update, Delete: labels.remove };
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
108
|
+
const heading = `Changes: ${counts.add} add · ${counts.update} update · ${counts.remove} remove`;
|
|
109
|
+
const lines = changes.length ? [heading] : [heading, "No file changes."];
|
|
110
|
+
return {
|
|
111
|
+
lines,
|
|
112
|
+
content: [...lines, ...changes.map((change) => `${label[change.action]}: ${snapshotPathLabel(change.path)}`)].join("\n"),
|
|
113
|
+
};
|
|
146
114
|
}
|
|
147
115
|
export function countPreservedRemoteFiles(local, upload) {
|
|
148
116
|
const localPaths = new Set(local.files.map((file) => file.path));
|
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import type { EngineContext } from "../host.js";
|
|
2
|
+
import type { TransferReview } from "./sync-format.js";
|
|
2
3
|
/** Presentation is supplied by the host; RPC keeps its existing directional confirmation. */
|
|
3
|
-
export declare function confirmTransferReview(ctx: EngineContext, title: string,
|
|
4
|
+
export declare function confirmTransferReview(ctx: EngineContext, title: string, review: TransferReview, signal: AbortSignal | undefined, validate: () => void): Promise<boolean>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { confirmMergeReview } from "./merge-review.js";
|
|
2
2
|
/** Presentation is supplied by the host; RPC keeps its existing directional confirmation. */
|
|
3
|
-
export async function confirmTransferReview(ctx, title,
|
|
3
|
+
export async function confirmTransferReview(ctx, title, review, signal, validate) {
|
|
4
4
|
validate();
|
|
5
5
|
const isCurrent = () => {
|
|
6
6
|
try {
|
|
@@ -12,8 +12,8 @@ export async function confirmTransferReview(ctx, title, content, signal, validat
|
|
|
12
12
|
}
|
|
13
13
|
};
|
|
14
14
|
const confirmed = ctx.mode === "tui" && ctx.hasUI
|
|
15
|
-
? await confirmMergeReview(ctx, title, content, signal, isCurrent, "apply reviewed transfer",
|
|
16
|
-
: await ctx.ui.confirm(title, content, { signal });
|
|
15
|
+
? await confirmMergeReview(ctx, title, review.content, signal, isCurrent, "apply reviewed transfer", review.lines)
|
|
16
|
+
: await ctx.ui.confirm(title, review.content, { signal });
|
|
17
17
|
validate();
|
|
18
18
|
return confirmed;
|
|
19
19
|
}
|
package/dist/engine-service.d.ts
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
|
+
import { captureStartupReviewLock } from "./engine/state/lock.js";
|
|
1
2
|
import { type Execute } from "./protocol.js";
|
|
2
3
|
/** Engine dispatch is loaded only by the service, never by the public IPC client. */
|
|
3
4
|
export declare function createEngineService(root: string, ignoreFileSettingsAvailable?: boolean): {
|
|
4
5
|
execute: Execute;
|
|
5
6
|
bind: (value: Awaited<ReturnType<typeof import("./server.js").startServer>>) => void;
|
|
6
7
|
hooks: {
|
|
8
|
+
diagnostic: import("./daemon-debug.js").DaemonDiagnosticSink;
|
|
9
|
+
startup: {
|
|
10
|
+
captureReviewLock: typeof captureStartupReviewLock;
|
|
11
|
+
probe(fingerprint: string, signal: AbortSignal, reviewLock?: () => boolean): Promise<(() => boolean) | undefined>;
|
|
12
|
+
};
|
|
7
13
|
factsChanged: () => Promise<void>;
|
|
8
14
|
idle: () => void;
|
|
9
15
|
close: () => Promise<void>;
|
package/dist/engine-service.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { authorizeAfterExit, automaticPolicyAuthorized, captureAutomaticAuthorization, consentFingerprint, readConsent, requireHandover, reviewAutomaticPolicy, revokeAfterExitGrants, } from "./consent.js";
|
|
2
|
+
import { createDaemonDebug } from "./daemon-debug.js";
|
|
2
3
|
import { documentFingerprint } from "./document.js";
|
|
4
|
+
import { captureStartupReviewLock } from "./engine/state/lock.js";
|
|
3
5
|
import { createMonitor } from "./monitor.js";
|
|
4
6
|
import { MAX_SETTINGS_BYTES, record } from "./protocol.js";
|
|
5
7
|
import { createServiceContext, installServiceHost } from "./service-host.js";
|
|
@@ -37,6 +39,7 @@ function optionsFrom(value, execution, automatic) {
|
|
|
37
39
|
...(typeof value.automaticFingerprint === "string" ? { automaticFingerprint: value.automaticFingerprint } : {}),
|
|
38
40
|
signal: execution.signal,
|
|
39
41
|
onCommit: execution.committed,
|
|
42
|
+
noteDebugOutcome: execution.noteDebugOutcome,
|
|
40
43
|
};
|
|
41
44
|
}
|
|
42
45
|
/** Engine dispatch is loaded only by the service, never by the public IPC client. */
|
|
@@ -248,18 +251,24 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
|
|
|
248
251
|
const { syncSessionsSelected } = await import("./engine/sync/sync-policy.js");
|
|
249
252
|
const config = await loadConfigForCheck(undefined, execution.signal);
|
|
250
253
|
execution.validate();
|
|
251
|
-
if (!config.automatic || !syncSessionsSelected(config))
|
|
254
|
+
if (!config.automatic || !syncSessionsSelected(config)) {
|
|
255
|
+
execution.noteDebugOutcome?.("skipped");
|
|
252
256
|
return;
|
|
257
|
+
}
|
|
253
258
|
}
|
|
254
|
-
if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode))
|
|
259
|
+
if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) {
|
|
260
|
+
execution.noteDebugOutcome?.("blocked");
|
|
255
261
|
throw new Error("Synchronization requires an observable TUI or RPC client.");
|
|
262
|
+
}
|
|
256
263
|
const { withStateDirectoryAccess, migrateLegacyStateDirectory } = await import("./engine/state/state-directory.js");
|
|
257
264
|
if (operation === "migrate-state") {
|
|
258
265
|
if (!options.yes) {
|
|
259
266
|
const accepted = await ctx.ui.confirm("Migrate pi-sync state directory", "Confirm that every older Pi process is closed. Preserve both roots and pending journals on failure.", { signal: execution.signal });
|
|
260
267
|
execution.validate();
|
|
261
|
-
if (!accepted)
|
|
268
|
+
if (!accepted) {
|
|
269
|
+
execution.noteDebugOutcome?.("cancelled");
|
|
262
270
|
return { status: "cancelled", message: "pi-sync state migration cancelled." };
|
|
271
|
+
}
|
|
263
272
|
}
|
|
264
273
|
execution.validate();
|
|
265
274
|
const result = await migrateLegacyStateDirectory();
|
|
@@ -294,8 +303,10 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
|
|
|
294
303
|
}
|
|
295
304
|
if (operation === "startup-transfer") {
|
|
296
305
|
const { startupTransferEnabled } = await import("./engine/sync/agent-policy.js");
|
|
297
|
-
if (!automatic || !startupTransferEnabled(automatic.config) || !ctx.isIdle())
|
|
306
|
+
if (!automatic || !startupTransferEnabled(automatic.config) || !ctx.isIdle()) {
|
|
307
|
+
execution.noteDebugOutcome?.("blocked");
|
|
298
308
|
throw new Error("Startup transfer is no longer authorized or idle.");
|
|
309
|
+
}
|
|
299
310
|
options.auto = true;
|
|
300
311
|
options.yes = true;
|
|
301
312
|
options.silent = true;
|
|
@@ -310,6 +321,7 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
|
|
|
310
321
|
automatic?.validate(config);
|
|
311
322
|
execution.validate();
|
|
312
323
|
if (config.agentMode && !automaticPolicyAuthorized(root, config)) {
|
|
324
|
+
execution.noteDebugOutcome?.("blocked");
|
|
313
325
|
throw new Error("Autonomous sync requires a separate policy review. Use Settings → Review automatic transfers, or choose a reviewed push or pull.");
|
|
314
326
|
}
|
|
315
327
|
if (operation === "sync" && !options.agentRetryRefusal)
|
|
@@ -360,8 +372,10 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
|
|
|
360
372
|
execution.participants().some((peer) => peer.ready !== true) ||
|
|
361
373
|
inspection.firstSync ||
|
|
362
374
|
!inspection.head ||
|
|
363
|
-
inspection.selectionState?.kind !== "same")
|
|
375
|
+
inspection.selectionState?.kind !== "same") {
|
|
376
|
+
execution.noteDebugOutcome?.("blocked");
|
|
364
377
|
throw new Error("Startup transfer requires a fresh initialized baseline, matching selection, and idle ready clients; use the reviewed foreground command.");
|
|
378
|
+
}
|
|
365
379
|
}
|
|
366
380
|
return operations.syncBoth(ctx, current);
|
|
367
381
|
});
|
|
@@ -371,9 +385,12 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
|
|
|
371
385
|
}
|
|
372
386
|
};
|
|
373
387
|
return operation === "startup-transfer"
|
|
374
|
-
? withJobTimings(ctx, execution, "daemon transfer", (timings) => {
|
|
388
|
+
? withJobTimings(ctx, execution, "daemon transfer", async (timings) => {
|
|
375
389
|
options.startupTimings = timings;
|
|
376
|
-
|
|
390
|
+
const result = await run();
|
|
391
|
+
if (timings.wasUnchanged())
|
|
392
|
+
execution.noteDebugOutcome?.("skipped");
|
|
393
|
+
return result;
|
|
377
394
|
})
|
|
378
395
|
: run();
|
|
379
396
|
}
|
|
@@ -388,10 +405,18 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
|
|
|
388
405
|
execute,
|
|
389
406
|
bind: monitor.bind,
|
|
390
407
|
hooks: {
|
|
408
|
+
diagnostic: createDaemonDebug(root),
|
|
409
|
+
startup: {
|
|
410
|
+
captureReviewLock: captureStartupReviewLock,
|
|
411
|
+
async probe(fingerprint, signal, reviewLock) {
|
|
412
|
+
const { captureStartupBootstrap } = await import("./engine/sync/startup-bootstrap.js");
|
|
413
|
+
return captureStartupBootstrap(root, fingerprint, signal, reviewLock);
|
|
414
|
+
},
|
|
415
|
+
},
|
|
391
416
|
factsChanged: monitor.factsChanged,
|
|
392
417
|
idle: monitor.schedule,
|
|
393
418
|
close: monitor.close,
|
|
394
|
-
lifetime: monitor.lifetime,
|
|
419
|
+
lifetime: () => (host.cleanupRequired() ? Promise.resolve("pause") : monitor.lifetime()),
|
|
395
420
|
quiesce: monitor.pause,
|
|
396
421
|
failure: monitor.blockAutomatic,
|
|
397
422
|
},
|
|
@@ -407,9 +432,17 @@ async function withJobTimings(ctx, execution, label, action) {
|
|
|
407
432
|
return result;
|
|
408
433
|
}
|
|
409
434
|
finally {
|
|
410
|
-
timings.publish(ctx, execution.facts()?.startupDebug ?? false, execution.signal, label, completed ? "completed" : "stopped");
|
|
435
|
+
timings.publish(ctx, execution.facts()?.startupDebug ?? false, execution.signal, label, completed ? "completed" : "stopped", timingObserver(execution));
|
|
411
436
|
}
|
|
412
437
|
}
|
|
438
|
+
async function requireStartupRecoveryCleared(execution) {
|
|
439
|
+
const { pendingTransactionEntries } = await import("./engine/snapshot/snapshot-transaction-directory.js");
|
|
440
|
+
execution.validate();
|
|
441
|
+
const pending = await pendingTransactionEntries();
|
|
442
|
+
execution.validate();
|
|
443
|
+
if (pending.length)
|
|
444
|
+
throw new Error("Pi Sync startup cannot confirm recovery is clear. Preserve recovery files and check /sync doctor before retrying.");
|
|
445
|
+
}
|
|
413
446
|
async function initialize(ctx, execution, diagnostics = true) {
|
|
414
447
|
const { pendingTransactionEntries } = await import("./engine/snapshot/snapshot-transaction-directory.js");
|
|
415
448
|
const pending = await pendingTransactionEntries();
|
|
@@ -430,12 +463,23 @@ async function initialize(ctx, execution, diagnostics = true) {
|
|
|
430
463
|
execution.validate();
|
|
431
464
|
const settings = document ? validateSettingsDocument(document.parsed) : undefined;
|
|
432
465
|
const config = settings?.activeSyncSetup ? configFromSettings(settings) : undefined;
|
|
466
|
+
if (diagnostics)
|
|
467
|
+
await requireStartupRecoveryCleared(execution);
|
|
468
|
+
execution.noteDebugOutcome?.("blocked");
|
|
433
469
|
return { debug: settings?.debug ?? false, settings, config, handoverRequired: true };
|
|
434
470
|
}
|
|
435
471
|
const { initializeSync } = await import("./engine/sync/initialization.js");
|
|
436
472
|
const initialized = await initializeSync(ctx, execution.signal, (_ctx, report) => {
|
|
437
473
|
if (diagnostics)
|
|
438
474
|
execution.emit("timings", { report });
|
|
439
|
-
});
|
|
475
|
+
}, diagnostics ? timingObserver(execution) : undefined);
|
|
476
|
+
execution.validate();
|
|
477
|
+
if (diagnostics)
|
|
478
|
+
await requireStartupRecoveryCleared(execution);
|
|
479
|
+
execution.validate();
|
|
440
480
|
return { ...initialized, handoverRequired: !readConsent(execution.root) };
|
|
441
481
|
}
|
|
482
|
+
function timingObserver(execution) {
|
|
483
|
+
const debug = execution.debug;
|
|
484
|
+
return debug ? (report) => debug({ event: "startup-timings", report }) : undefined;
|
|
485
|
+
}
|
package/dist/identity.d.ts
CHANGED
|
@@ -20,16 +20,19 @@ type ProcessIdentity = {
|
|
|
20
20
|
birth?: string;
|
|
21
21
|
};
|
|
22
22
|
/** The exit barrier records an authenticated owner without keeping its IPC token. */
|
|
23
|
-
export type UpgradeOwner = OwnerRecord & ProcessIdentity
|
|
23
|
+
export type UpgradeOwner = OwnerRecord & ProcessIdentity & {
|
|
24
|
+
purpose?: "cleanup";
|
|
25
|
+
};
|
|
24
26
|
export declare function upgradeFile(paths: RuntimePaths): string;
|
|
25
27
|
/** One private archive per upgrade instance, including across partial repair retries. */
|
|
26
28
|
export declare function upgradeArchivePath(paths: RuntimePaths, owner: Pick<UpgradeOwner, "instance">): string;
|
|
27
29
|
/** A repair must finish explicitly once it starts changing consent or moving evidence. */
|
|
28
30
|
export declare function upgradeRepairStarted(paths: RuntimePaths, owner: Pick<UpgradeOwner, "instance">): Promise<boolean>;
|
|
29
31
|
export declare function readUpgradeOwner(paths: RuntimePaths): Promise<UpgradeOwner | undefined>;
|
|
30
|
-
export declare function recordUpgradeOwner(paths: RuntimePaths, { version, root, instance, pid, birth }: UpgradeOwner): Promise<void>;
|
|
32
|
+
export declare function recordUpgradeOwner(paths: RuntimePaths, { version, root, instance, pid, birth, purpose }: UpgradeOwner): Promise<void>;
|
|
31
33
|
export declare function clearUpgradeOwner(paths: RuntimePaths): Promise<void>;
|
|
32
34
|
export declare function readIdentity(paths: RuntimePaths): Promise<Identity | undefined>;
|
|
35
|
+
export declare function matchesPublishedIdentity(paths: RuntimePaths, identity: Identity): boolean;
|
|
33
36
|
export declare function processExists(pid: number): boolean;
|
|
34
37
|
/** Linux start ticks from a procfs view that agrees with the caller's PID namespace. */
|
|
35
38
|
export declare function readProcessBirth(pid: number): Promise<string | undefined>;
|
package/dist/identity.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { lstatSync, realpathSync } from "node:fs";
|
|
2
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs";
|
|
3
3
|
import fs from "node:fs/promises";
|
|
4
4
|
import os from "node:os";
|
|
5
5
|
import path from "node:path";
|
|
@@ -84,13 +84,15 @@ export async function readUpgradeOwner(paths) {
|
|
|
84
84
|
const value = await readPrivateRecord(upgradeFile(paths));
|
|
85
85
|
if (value === undefined)
|
|
86
86
|
return;
|
|
87
|
-
if (!validOwner(value, paths.root) ||
|
|
87
|
+
if (!validOwner(value, paths.root) ||
|
|
88
|
+
(value.birth !== undefined && !validBirth(value.birth)) ||
|
|
89
|
+
(value.purpose !== undefined && value.purpose !== "cleanup"))
|
|
88
90
|
throw new Error("Invalid daemon upgrade record; state retained.");
|
|
89
|
-
const { version, root, instance, pid, birth } = value;
|
|
90
|
-
return
|
|
91
|
+
const { version, root, instance, pid, birth, purpose } = value;
|
|
92
|
+
return { version, root, instance, pid, ...(birth && { birth }), ...(purpose && { purpose }) };
|
|
91
93
|
}
|
|
92
|
-
export function recordUpgradeOwner(paths, { version, root, instance, pid, birth }) {
|
|
93
|
-
return publishPrivateRecord(paths, upgradeFile(paths), { version, root, instance, pid, birth });
|
|
94
|
+
export function recordUpgradeOwner(paths, { version, root, instance, pid, birth, purpose }) {
|
|
95
|
+
return publishPrivateRecord(paths, upgradeFile(paths), { version, root, instance, pid, birth, purpose });
|
|
94
96
|
}
|
|
95
97
|
export function clearUpgradeOwner(paths) {
|
|
96
98
|
return fs.rm(upgradeFile(paths), { force: true });
|
|
@@ -103,6 +105,34 @@ export async function readIdentity(paths) {
|
|
|
103
105
|
throw new Error("Invalid or incompatible daemon identity; state retained.");
|
|
104
106
|
return { ...value, token: value.token };
|
|
105
107
|
}
|
|
108
|
+
export function matchesPublishedIdentity(paths, identity) {
|
|
109
|
+
const expected = Buffer.from(JSON.stringify(identity));
|
|
110
|
+
if (expected.length > 8192)
|
|
111
|
+
return false;
|
|
112
|
+
const before = lstatSync(paths.identity, { bigint: true, throwIfNoEntry: false });
|
|
113
|
+
if (!before?.isFile() ||
|
|
114
|
+
before.size !== BigInt(expected.length) ||
|
|
115
|
+
(process.getuid && before.uid !== BigInt(process.getuid())) ||
|
|
116
|
+
(process.platform !== "win32" && (before.mode & 63n) !== 0n))
|
|
117
|
+
return false;
|
|
118
|
+
const sameFile = (info) => info?.dev === before.dev &&
|
|
119
|
+
info.ino === before.ino &&
|
|
120
|
+
info.size === before.size &&
|
|
121
|
+
info.ctimeNs === before.ctimeNs &&
|
|
122
|
+
info.mtimeNs === before.mtimeNs;
|
|
123
|
+
const fd = openSync(paths.identity, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
124
|
+
try {
|
|
125
|
+
if (!sameFile(fstatSync(fd, { bigint: true })))
|
|
126
|
+
return false;
|
|
127
|
+
const observed = Buffer.alloc(expected.length + 1);
|
|
128
|
+
return (readSync(fd, observed) === expected.length &&
|
|
129
|
+
observed.subarray(0, expected.length).equals(expected) &&
|
|
130
|
+
sameFile(lstatSync(paths.identity, { bigint: true, throwIfNoEntry: false })));
|
|
131
|
+
}
|
|
132
|
+
finally {
|
|
133
|
+
closeSync(fd);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
106
136
|
function validBirth(value) {
|
|
107
137
|
const fields = typeof value === "string" && birthPattern.exec(value);
|
|
108
138
|
return (!!fields &&
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
export type { ConnectionOptions, QueueReleaseDelivery } from "./client.js";
|
|
2
2
|
export { DaemonConnection, DaemonError, ensureDaemon, findDaemon, requestDaemon, stopDaemon, waitForDaemonExit, } from "./client.js";
|
|
3
|
+
export { type DaemonRecoveryTarget, inspectDaemonRecovery, stopDaemonForRecovery, } from "./daemon-recovery.js";
|
|
3
4
|
export type { DocumentView } from "./document.js";
|
|
4
5
|
export { documentFingerprint } from "./document.js";
|
|
5
6
|
export type { EngineContext, EngineHost, EngineSession, ReviewRequest } from "./engine/host.js";
|
|
6
7
|
export { modelSignature } from "./model-signature.js";
|
|
7
8
|
export type { Callback, ClientContact as ContactState, ClientEvent, ClientFacts, ClientHandoff, Identity, JobView, RemoteError, } from "./protocol.js";
|
|
8
|
-
export { MAX_SETTINGS_BYTES, PROTOCOL_VERSION } from "./protocol.js";
|
|
9
|
+
export { MAX_SETTINGS_BYTES, OWNERSHIP_CLEANUP_REQUIRED, PROTOCOL_VERSION } from "./protocol.js";
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { DaemonConnection, DaemonError, ensureDaemon, findDaemon, requestDaemon, stopDaemon, waitForDaemonExit, } from "./client.js";
|
|
2
|
+
export { inspectDaemonRecovery, stopDaemonForRecovery, } from "./daemon-recovery.js";
|
|
2
3
|
export { documentFingerprint } from "./document.js";
|
|
3
4
|
export { modelSignature } from "./model-signature.js";
|
|
4
|
-
export { MAX_SETTINGS_BYTES, PROTOCOL_VERSION } from "./protocol.js";
|
|
5
|
+
export { MAX_SETTINGS_BYTES, OWNERSHIP_CLEANUP_REQUIRED, PROTOCOL_VERSION } from "./protocol.js";
|