@narumitw/pi-sync-daemon 0.0.0-stage → 0.3.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 +22 -0
- package/LICENSE +21 -0
- package/README.md +91 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +127 -0
- package/dist/client.d.ts +57 -0
- package/dist/client.js +534 -0
- package/dist/consent.d.ts +24 -0
- package/dist/consent.js +205 -0
- package/dist/document.d.ts +10 -0
- package/dist/document.js +6 -0
- package/dist/endpoint.d.ts +8 -0
- package/dist/endpoint.js +91 -0
- package/dist/engine/backends/backend-factory.d.ts +6 -0
- package/dist/engine/backends/backend-factory.js +16 -0
- package/dist/engine/backends/backend-identity.d.ts +3 -0
- package/dist/engine/backends/backend-identity.js +38 -0
- package/dist/engine/backends/backend-types.d.ts +70 -0
- package/dist/engine/backends/backend-types.js +1 -0
- package/dist/engine/backends/git/git-backend.d.ts +55 -0
- package/dist/engine/backends/git/git-backend.js +700 -0
- package/dist/engine/backends/git/git-config.d.ts +5 -0
- package/dist/engine/backends/git/git-config.js +118 -0
- package/dist/engine/backends/git/git-runner.d.ts +25 -0
- package/dist/engine/backends/git/git-runner.js +232 -0
- package/dist/engine/backends/git/git-storage.d.ts +39 -0
- package/dist/engine/backends/git/git-storage.js +226 -0
- package/dist/engine/backends/s3/s3-backend.d.ts +32 -0
- package/dist/engine/backends/s3/s3-backend.js +436 -0
- package/dist/engine/backends/s3/s3-client.d.ts +36 -0
- package/dist/engine/backends/s3/s3-client.js +352 -0
- package/dist/engine/backends/s3/s3-conditions.d.ts +4 -0
- package/dist/engine/backends/s3/s3-conditions.js +66 -0
- package/dist/engine/backends/snapshot-pointer.d.ts +6 -0
- package/dist/engine/backends/snapshot-pointer.js +22 -0
- package/dist/engine/backends/sync-backend.d.ts +71 -0
- package/dist/engine/backends/sync-backend.js +23 -0
- package/dist/engine/backends/webdav/webdav-backend.d.ts +34 -0
- package/dist/engine/backends/webdav/webdav-backend.js +534 -0
- package/dist/engine/backends/webdav/webdav-client.d.ts +36 -0
- package/dist/engine/backends/webdav/webdav-client.js +326 -0
- package/dist/engine/backends/webdav/webdav-config.d.ts +5 -0
- package/dist/engine/backends/webdav/webdav-config.js +73 -0
- package/dist/engine/commands/command-types.d.ts +31 -0
- package/dist/engine/commands/command-types.js +1 -0
- package/dist/engine/host.d.ts +70 -0
- package/dist/engine/host.js +16 -0
- package/dist/engine/paths.d.ts +9 -0
- package/dist/engine/paths.js +71 -0
- package/dist/engine/settings/config-errors.d.ts +1 -0
- package/dist/engine/settings/config-errors.js +4 -0
- package/dist/engine/settings/config-file.d.ts +33 -0
- package/dist/engine/settings/config-file.js +630 -0
- package/dist/engine/settings/config.d.ts +24 -0
- package/dist/engine/settings/config.js +200 -0
- package/dist/engine/settings/settings-management.d.ts +24 -0
- package/dist/engine/settings/settings-management.js +191 -0
- package/dist/engine/settings/settings-store.d.ts +8 -0
- package/dist/engine/settings/settings-store.js +41 -0
- package/dist/engine/settings/settings-types.d.ts +134 -0
- package/dist/engine/settings/settings-types.js +1 -0
- package/dist/engine/settings/settings-validation.d.ts +15 -0
- package/dist/engine/settings/settings-validation.js +356 -0
- package/dist/engine/snapshot/session-paths.d.ts +12 -0
- package/dist/engine/snapshot/session-paths.js +91 -0
- package/dist/engine/snapshot/snapshot-apply.d.ts +22 -0
- package/dist/engine/snapshot/snapshot-apply.js +262 -0
- package/dist/engine/snapshot/snapshot-case-replacement.d.ts +15 -0
- package/dist/engine/snapshot/snapshot-case-replacement.js +82 -0
- package/dist/engine/snapshot/snapshot-codec.d.ts +6 -0
- package/dist/engine/snapshot/snapshot-codec.js +53 -0
- package/dist/engine/snapshot/snapshot-exclude-safety.d.ts +7 -0
- package/dist/engine/snapshot/snapshot-exclude-safety.js +47 -0
- package/dist/engine/snapshot/snapshot-mutation-queues.d.ts +9 -0
- package/dist/engine/snapshot/snapshot-mutation-queues.js +133 -0
- package/dist/engine/snapshot/snapshot-paths.d.ts +1 -0
- package/dist/engine/snapshot/snapshot-paths.js +11 -0
- package/dist/engine/snapshot/snapshot-root-transition.d.ts +25 -0
- package/dist/engine/snapshot/snapshot-root-transition.js +122 -0
- package/dist/engine/snapshot/snapshot-transaction-directory.d.ts +2 -0
- package/dist/engine/snapshot/snapshot-transaction-directory.js +16 -0
- package/dist/engine/snapshot/snapshot-transaction-plan.d.ts +12 -0
- package/dist/engine/snapshot/snapshot-transaction-plan.js +68 -0
- package/dist/engine/snapshot/snapshot-transaction.d.ts +15 -0
- package/dist/engine/snapshot/snapshot-transaction.js +787 -0
- package/dist/engine/snapshot/snapshot-types.d.ts +48 -0
- package/dist/engine/snapshot/snapshot-types.js +1 -0
- package/dist/engine/snapshot/snapshot.d.ts +30 -0
- package/dist/engine/snapshot/snapshot.js +364 -0
- package/dist/engine/state/json-file.d.ts +6 -0
- package/dist/engine/state/json-file.js +49 -0
- package/dist/engine/state/lock-policy.d.ts +2 -0
- package/dist/engine/state/lock-policy.js +2 -0
- package/dist/engine/state/lock.d.ts +20 -0
- package/dist/engine/state/lock.js +259 -0
- package/dist/engine/state/lockfile-fs.d.ts +13 -0
- package/dist/engine/state/lockfile-fs.js +13 -0
- package/dist/engine/state/merge-baseline-store.d.ts +11 -0
- package/dist/engine/state/merge-baseline-store.js +187 -0
- package/dist/engine/state/mutation-directory-sync.d.ts +5 -0
- package/dist/engine/state/mutation-directory-sync.js +34 -0
- package/dist/engine/state/operation-availability.d.ts +49 -0
- package/dist/engine/state/operation-availability.js +40 -0
- package/dist/engine/state/state-directory.d.ts +14 -0
- package/dist/engine/state/state-directory.js +225 -0
- package/dist/engine/state/state-types.d.ts +27 -0
- package/dist/engine/state/state-types.js +1 -0
- package/dist/engine/state/sync-state-store.d.ts +11 -0
- package/dist/engine/state/sync-state-store.js +54 -0
- package/dist/engine/sync/agent-candidate.d.ts +44 -0
- package/dist/engine/sync/agent-candidate.js +207 -0
- package/dist/engine/sync/agent-plan.d.ts +8 -0
- package/dist/engine/sync/agent-plan.js +84 -0
- package/dist/engine/sync/agent-policy.d.ts +9 -0
- package/dist/engine/sync/agent-policy.js +10 -0
- package/dist/engine/sync/agent-refusal-retry.d.ts +4 -0
- package/dist/engine/sync/agent-refusal-retry.js +39 -0
- package/dist/engine/sync/agent-request.d.ts +14 -0
- package/dist/engine/sync/agent-request.js +13 -0
- package/dist/engine/sync/agent-runner.d.ts +6 -0
- package/dist/engine/sync/agent-runner.js +183 -0
- package/dist/engine/sync/agent-store.d.ts +7 -0
- package/dist/engine/sync/agent-store.js +177 -0
- package/dist/engine/sync/agent-sync.d.ts +4 -0
- package/dist/engine/sync/agent-sync.js +132 -0
- package/dist/engine/sync/apply-review.d.ts +8 -0
- package/dist/engine/sync/apply-review.js +51 -0
- package/dist/engine/sync/conflict-artifact-ownership.d.ts +4 -0
- package/dist/engine/sync/conflict-artifact-ownership.js +53 -0
- package/dist/engine/sync/conflict-artifacts.d.ts +32 -0
- package/dist/engine/sync/conflict-artifacts.js +158 -0
- package/dist/engine/sync/conflict-groups.d.ts +9 -0
- package/dist/engine/sync/conflict-groups.js +76 -0
- package/dist/engine/sync/conflict-preview.d.ts +4 -0
- package/dist/engine/sync/conflict-preview.js +53 -0
- package/dist/engine/sync/conflict-resolution.d.ts +13 -0
- package/dist/engine/sync/conflict-resolution.js +53 -0
- package/dist/engine/sync/conflict-retention.d.ts +5 -0
- package/dist/engine/sync/conflict-retention.js +61 -0
- package/dist/engine/sync/conflict-review.d.ts +4 -0
- package/dist/engine/sync/conflict-review.js +73 -0
- package/dist/engine/sync/content-conflicts.d.ts +10 -0
- package/dist/engine/sync/content-conflicts.js +70 -0
- package/dist/engine/sync/continuous-errors.d.ts +14 -0
- package/dist/engine/sync/continuous-errors.js +66 -0
- package/dist/engine/sync/continuous-lease.d.ts +9 -0
- package/dist/engine/sync/continuous-lease.js +206 -0
- package/dist/engine/sync/continuous-record.d.ts +31 -0
- package/dist/engine/sync/continuous-record.js +199 -0
- package/dist/engine/sync/continuous-storage.d.ts +14 -0
- package/dist/engine/sync/continuous-storage.js +59 -0
- package/dist/engine/sync/continuous-sync.d.ts +15 -0
- package/dist/engine/sync/continuous-sync.js +496 -0
- package/dist/engine/sync/continuous-watch.d.ts +3 -0
- package/dist/engine/sync/continuous-watch.js +65 -0
- package/dist/engine/sync/exclude-policy.d.ts +5 -0
- package/dist/engine/sync/exclude-policy.js +79 -0
- package/dist/engine/sync/field-migration.d.ts +5 -0
- package/dist/engine/sync/field-migration.js +20 -0
- package/dist/engine/sync/file-merge-planner.d.ts +36 -0
- package/dist/engine/sync/file-merge-planner.js +123 -0
- package/dist/engine/sync/initialization.d.ts +12 -0
- package/dist/engine/sync/initialization.js +75 -0
- package/dist/engine/sync/json-document.d.ts +29 -0
- package/dist/engine/sync/json-document.js +172 -0
- package/dist/engine/sync/local-field-policy.d.ts +2 -0
- package/dist/engine/sync/local-field-policy.js +26 -0
- package/dist/engine/sync/local-fields.d.ts +9 -0
- package/dist/engine/sync/local-fields.js +116 -0
- package/dist/engine/sync/merge-apply.d.ts +5 -0
- package/dist/engine/sync/merge-apply.js +386 -0
- package/dist/engine/sync/merge-journal.d.ts +31 -0
- package/dist/engine/sync/merge-journal.js +179 -0
- package/dist/engine/sync/merge-transfer-error.d.ts +3 -0
- package/dist/engine/sync/merge-transfer-error.js +64 -0
- package/dist/engine/sync/merged-sync.d.ts +6 -0
- package/dist/engine/sync/merged-sync.js +618 -0
- package/dist/engine/sync/mutation-owner.d.ts +2 -0
- package/dist/engine/sync/mutation-owner.js +18 -0
- package/dist/engine/sync/package-merge.d.ts +3 -0
- package/dist/engine/sync/package-merge.js +82 -0
- package/dist/engine/sync/partial-progress.d.ts +15 -0
- package/dist/engine/sync/partial-progress.js +39 -0
- package/dist/engine/sync/remote-snapshot.d.ts +28 -0
- package/dist/engine/sync/remote-snapshot.js +62 -0
- package/dist/engine/sync/resolver-stream.d.ts +4 -0
- package/dist/engine/sync/resolver-stream.js +34 -0
- package/dist/engine/sync/session-merge.d.ts +3 -0
- package/dist/engine/sync/session-merge.js +178 -0
- package/dist/engine/sync/session-push.d.ts +5 -0
- package/dist/engine/sync/session-push.js +32 -0
- package/dist/engine/sync/settings-conflicts.d.ts +8 -0
- package/dist/engine/sync/settings-conflicts.js +56 -0
- package/dist/engine/sync/settings-merge.d.ts +13 -0
- package/dist/engine/sync/settings-merge.js +93 -0
- package/dist/engine/sync/signals.d.ts +2 -0
- package/dist/engine/sync/signals.js +8 -0
- package/dist/engine/sync/startup-timings.d.ts +11 -0
- package/dist/engine/sync/startup-timings.js +44 -0
- package/dist/engine/sync/sync-decision.d.ts +35 -0
- package/dist/engine/sync/sync-decision.js +66 -0
- package/dist/engine/sync/sync-error-guidance.d.ts +2 -0
- package/dist/engine/sync/sync-error-guidance.js +55 -0
- package/dist/engine/sync/sync-errors.d.ts +9 -0
- package/dist/engine/sync/sync-errors.js +18 -0
- package/dist/engine/sync/sync-inspection.d.ts +26 -0
- package/dist/engine/sync/sync-inspection.js +40 -0
- package/dist/engine/sync/sync-loaders.d.ts +7 -0
- package/dist/engine/sync/sync-loaders.js +8 -0
- package/dist/engine/sync/sync-local.d.ts +5 -0
- package/dist/engine/sync/sync-local.js +40 -0
- package/dist/engine/sync/sync-mutations.d.ts +30 -0
- package/dist/engine/sync/sync-mutations.js +589 -0
- package/dist/engine/sync/sync-operations.d.ts +2 -0
- package/dist/engine/sync/sync-operations.js +3 -0
- package/dist/engine/sync/sync-policy.d.ts +85 -0
- package/dist/engine/sync/sync-policy.js +356 -0
- package/dist/engine/sync/sync-queries.d.ts +7 -0
- package/dist/engine/sync/sync-queries.js +195 -0
- package/dist/engine/sync/sync-state.d.ts +31 -0
- package/dist/engine/sync/sync-state.js +92 -0
- package/dist/engine/sync/text-merge.d.ts +19 -0
- package/dist/engine/sync/text-merge.js +124 -0
- package/dist/engine/types.d.ts +5 -0
- package/dist/engine/types.js +2 -0
- package/dist/engine/ui/merge-review.d.ts +2 -0
- package/dist/engine/ui/merge-review.js +7 -0
- package/dist/engine/ui/merged-sync-summary.d.ts +25 -0
- package/dist/engine/ui/merged-sync-summary.js +86 -0
- package/dist/engine/ui/sync-format.d.ts +13 -0
- package/dist/engine/ui/sync-format.js +150 -0
- package/dist/engine/ui/sync-status.d.ts +9 -0
- package/dist/engine/ui/sync-status.js +30 -0
- package/dist/engine/ui/terminal-text.d.ts +3 -0
- package/dist/engine/ui/terminal-text.js +9 -0
- package/dist/engine/ui/transfer-changes.d.ts +12 -0
- package/dist/engine/ui/transfer-changes.js +24 -0
- package/dist/engine/ui/transfer-review.d.ts +3 -0
- package/dist/engine/ui/transfer-review.js +19 -0
- package/dist/engine-service.d.ts +14 -0
- package/dist/engine-service.js +322 -0
- package/dist/identity.d.ts +20 -0
- package/dist/identity.js +133 -0
- package/dist/idle-exit.d.ts +17 -0
- package/dist/idle-exit.js +77 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +4 -0
- package/dist/lifecycle-log.d.ts +7 -0
- package/dist/lifecycle-log.js +53 -0
- package/dist/lifecycle.d.ts +2 -0
- package/dist/lifecycle.js +21 -0
- package/dist/model-signature.d.ts +2 -0
- package/dist/model-signature.js +7 -0
- package/dist/monitor.d.ts +14 -0
- package/dist/monitor.js +272 -0
- package/dist/participant-admission.d.ts +5 -0
- package/dist/participant-admission.js +30 -0
- package/dist/protocol.d.ts +102 -0
- package/dist/protocol.js +97 -0
- package/dist/resolver-host.d.ts +11 -0
- package/dist/resolver-host.js +78 -0
- package/dist/server.d.ts +24 -0
- package/dist/server.js +808 -0
- package/dist/service-host.d.ts +7 -0
- package/dist/service-host.js +174 -0
- package/docs/architecture.md +162 -0
- package/package.json +54 -4
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { readMergeAncestors } from "../state/merge-baseline-store.js";
|
|
3
|
+
import { mergePathIdentity } from "./file-merge-planner.js";
|
|
4
|
+
import { mergeSession } from "./session-merge.js";
|
|
5
|
+
import { isMergeTextPath, mergeText, TEXT_MERGE_WORK_LIMIT } from "./text-merge.js";
|
|
6
|
+
export function snapshotFile(filePath, bytes) {
|
|
7
|
+
return {
|
|
8
|
+
path: filePath,
|
|
9
|
+
contentBase64: bytes.toString("base64"),
|
|
10
|
+
sha256: createHash("sha256").update(bytes).digest("hex"),
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
export async function resolveContentConflicts(config, state, local, remote, plan, protectedPaths, options = {}) {
|
|
14
|
+
if (plan.kind !== "planned" || !config.mergeContent)
|
|
15
|
+
return plan;
|
|
16
|
+
options.signal?.throwIfAborted();
|
|
17
|
+
const budget = options.textBudget ?? { remaining: TEXT_MERGE_WORK_LIMIT };
|
|
18
|
+
const decisions = [...plan.decisions];
|
|
19
|
+
let ancestors = [];
|
|
20
|
+
try {
|
|
21
|
+
ancestors = (await readMergeAncestors(config, state)) ?? [];
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
options.signal?.throwIfAborted();
|
|
25
|
+
return plan;
|
|
26
|
+
}
|
|
27
|
+
options.signal?.throwIfAborted();
|
|
28
|
+
const oursByPath = new Map(local.files.map((file) => [file.path, file]));
|
|
29
|
+
const theirsByPath = new Map(remote.files.map((file) => [file.path, file]));
|
|
30
|
+
const ancestorsByPath = new Map(ancestors.map((file) => [file.path, file]));
|
|
31
|
+
const decisionIndex = new Map(decisions.map((decision, index) => [decision.path, index]));
|
|
32
|
+
const protectedKeys = new Set([...protectedPaths].map(mergePathIdentity));
|
|
33
|
+
for (const conflict of plan.conflicts) {
|
|
34
|
+
options.signal?.throwIfAborted();
|
|
35
|
+
if (conflict.reason !== "both-changed" || protectedKeys.has(mergePathIdentity(conflict.path)))
|
|
36
|
+
continue;
|
|
37
|
+
const session = conflict.path.startsWith("sessions/") && conflict.path.endsWith(".jsonl");
|
|
38
|
+
if (!session && (!isMergeTextPath(conflict.path) || budget.remaining === 0))
|
|
39
|
+
continue;
|
|
40
|
+
const ours = oursByPath.get(conflict.path);
|
|
41
|
+
const theirs = theirsByPath.get(conflict.path);
|
|
42
|
+
if (!ours || !theirs)
|
|
43
|
+
continue;
|
|
44
|
+
const ancestor = ancestorsByPath.get(conflict.path);
|
|
45
|
+
const base = ancestor ? Buffer.from(ancestor.contentBase64, "base64") : undefined;
|
|
46
|
+
if (!base)
|
|
47
|
+
continue;
|
|
48
|
+
const localBytes = Buffer.from(ours.contentBase64, "base64");
|
|
49
|
+
const remoteBytes = Buffer.from(theirs.contentBase64, "base64");
|
|
50
|
+
const bytes = session
|
|
51
|
+
? mergeSession(base, localBytes, remoteBytes)
|
|
52
|
+
: mergeText(base, localBytes, remoteBytes, { budget, signal: options.signal });
|
|
53
|
+
if (!bytes)
|
|
54
|
+
continue;
|
|
55
|
+
const index = decisionIndex.get(conflict.path);
|
|
56
|
+
if (index === undefined)
|
|
57
|
+
continue;
|
|
58
|
+
decisions[index] = {
|
|
59
|
+
kind: "accepted",
|
|
60
|
+
path: conflict.path,
|
|
61
|
+
source: "merged",
|
|
62
|
+
file: snapshotFile(conflict.path, bytes),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
kind: "planned",
|
|
67
|
+
decisions,
|
|
68
|
+
conflicts: decisions.filter((item) => item.kind === "conflict"),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export type ContinuousErrorKind = "transient" | "contention" | "stale" | "authentication" | "storage" | "unsafe" | "model" | "budget" | "unknown";
|
|
2
|
+
/** Categories are safe to persist; provider messages and causes are not. */
|
|
3
|
+
export declare class ContinuousError extends Error {
|
|
4
|
+
readonly kind: ContinuousErrorKind;
|
|
5
|
+
readonly retryAfterMs?: number | undefined;
|
|
6
|
+
constructor(kind: ContinuousErrorKind, message: string, retryAfterMs?: number | undefined);
|
|
7
|
+
}
|
|
8
|
+
export declare function continuousFailure(error: unknown): {
|
|
9
|
+
kind: ContinuousErrorKind;
|
|
10
|
+
retry: boolean;
|
|
11
|
+
delay?: number;
|
|
12
|
+
};
|
|
13
|
+
export declare function boundedRetryDelay(value: unknown): number | undefined;
|
|
14
|
+
export declare function retryAfter(response: Response): number | undefined;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { SyncBackendConflictError } from "../backends/sync-backend.js";
|
|
2
|
+
/** Categories are safe to persist; provider messages and causes are not. */
|
|
3
|
+
export class ContinuousError extends Error {
|
|
4
|
+
kind;
|
|
5
|
+
retryAfterMs;
|
|
6
|
+
constructor(kind, message, retryAfterMs) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.kind = kind;
|
|
9
|
+
this.retryAfterMs = retryAfterMs;
|
|
10
|
+
this.name = "ContinuousError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export function continuousFailure(error) {
|
|
14
|
+
const seen = new Set();
|
|
15
|
+
for (let current = error; current && !seen.has(current) && seen.size < 8;) {
|
|
16
|
+
seen.add(current);
|
|
17
|
+
if (current instanceof ContinuousError)
|
|
18
|
+
return {
|
|
19
|
+
kind: current.kind,
|
|
20
|
+
retry: ["transient", "contention", "stale", "budget"].includes(current.kind),
|
|
21
|
+
delay: current.retryAfterMs,
|
|
22
|
+
};
|
|
23
|
+
if (current instanceof SyncBackendConflictError)
|
|
24
|
+
return { kind: "stale", retry: true };
|
|
25
|
+
if (typeof current !== "object")
|
|
26
|
+
break;
|
|
27
|
+
const value = current;
|
|
28
|
+
if (value.status === 401 || value.status === 403)
|
|
29
|
+
return { kind: "authentication", retry: false };
|
|
30
|
+
if (value.status === 408 ||
|
|
31
|
+
value.status === 429 ||
|
|
32
|
+
(typeof value.status === "number" && Number.isInteger(value.status) && value.status >= 500 && value.status <= 599))
|
|
33
|
+
return { kind: "transient", retry: true, delay: boundedRetryDelay(value.retryAfterMs) };
|
|
34
|
+
if (value.code === "ELOCKED")
|
|
35
|
+
return { kind: "contention", retry: true };
|
|
36
|
+
if (value.code === "ECOMPROMISED")
|
|
37
|
+
return { kind: "stale", retry: true };
|
|
38
|
+
if (value.name === "TimeoutError" ||
|
|
39
|
+
[
|
|
40
|
+
"ECONNRESET",
|
|
41
|
+
"ECONNREFUSED",
|
|
42
|
+
"ETIMEDOUT",
|
|
43
|
+
"ENETUNREACH",
|
|
44
|
+
"EHOSTUNREACH",
|
|
45
|
+
"ENOTFOUND",
|
|
46
|
+
"EAI_AGAIN",
|
|
47
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
48
|
+
"UND_ERR_SOCKET",
|
|
49
|
+
].includes(String(value.code)))
|
|
50
|
+
return { kind: "transient", retry: true };
|
|
51
|
+
if (["EACCES", "EPERM", "ENOSPC", "EROFS", "EIO"].includes(String(value.code)))
|
|
52
|
+
return { kind: "storage", retry: false };
|
|
53
|
+
current = value.cause;
|
|
54
|
+
}
|
|
55
|
+
return { kind: "unknown", retry: false };
|
|
56
|
+
}
|
|
57
|
+
export function boundedRetryDelay(value) {
|
|
58
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.min(value, 300_000) : undefined;
|
|
59
|
+
}
|
|
60
|
+
export function retryAfter(response) {
|
|
61
|
+
const value = response.headers.get("retry-after");
|
|
62
|
+
if (!value)
|
|
63
|
+
return;
|
|
64
|
+
const seconds = Number(value);
|
|
65
|
+
return boundedRetryDelay(Number.isFinite(seconds) ? seconds * 1000 : Date.parse(value) - Date.now());
|
|
66
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface ContinuousLease {
|
|
2
|
+
signal: AbortSignal;
|
|
3
|
+
assert(): void;
|
|
4
|
+
release(): Promise<void>;
|
|
5
|
+
}
|
|
6
|
+
/** Advisory only: never authority for a transfer or lease takeover. */
|
|
7
|
+
export declare function continuousLeaseOwner(binding: string): Promise<string>;
|
|
8
|
+
/** Caller holds state-directory access during acquisition; the renewable guard prevents live migration. */
|
|
9
|
+
export declare function acquireContinuousLease(binding: string): Promise<ContinuousLease | undefined>;
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { lstatSync, readFileSync, rmdirSync, stat } from "node:fs";
|
|
3
|
+
import fs from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import lockfile from "proper-lockfile";
|
|
6
|
+
import { withLock } from "../state/lock.js";
|
|
7
|
+
import { LOCKFILE_FS_ADAPTER } from "../state/lockfile-fs.js";
|
|
8
|
+
import { continuousRoot, prepareContinuousRoot, readContinuousPrivate, writeContinuousPrivate, } from "./continuous-storage.js";
|
|
9
|
+
const STALE_MS = 30_000;
|
|
10
|
+
const localLeases = new Set();
|
|
11
|
+
const futureGuards = new Map();
|
|
12
|
+
function validOwner(value) {
|
|
13
|
+
if (!value || typeof value !== "object")
|
|
14
|
+
return false;
|
|
15
|
+
const owner = value;
|
|
16
|
+
return (Object.keys(owner).sort().join(",") === "binding,id,pid,version" &&
|
|
17
|
+
owner.version === 1 &&
|
|
18
|
+
typeof owner.id === "string" &&
|
|
19
|
+
/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/u.test(owner.id) &&
|
|
20
|
+
Number.isSafeInteger(owner.pid) &&
|
|
21
|
+
owner.pid > 0 &&
|
|
22
|
+
owner.pid <= 2147483647 &&
|
|
23
|
+
typeof owner.binding === "string" &&
|
|
24
|
+
/^[a-f0-9]{64}$/u.test(owner.binding));
|
|
25
|
+
}
|
|
26
|
+
/** Advisory only: never authority for a transfer or lease takeover. */
|
|
27
|
+
export async function continuousLeaseOwner(binding) {
|
|
28
|
+
const owner = await readContinuousPrivate("owner.json");
|
|
29
|
+
if (owner === undefined)
|
|
30
|
+
return "Local scheduler lease: not observed; waiting for an eligible session";
|
|
31
|
+
if (!validOwner(owner))
|
|
32
|
+
throw new Error("Invalid continuous sync owner");
|
|
33
|
+
try {
|
|
34
|
+
const guard = await fs.lstat(path.join(continuousRoot(), "scheduler.lock"));
|
|
35
|
+
if (guard.isDirectory() && !guard.isSymbolicLink() && Date.now() - guard.mtimeMs <= STALE_MS)
|
|
36
|
+
return `Local scheduler lease: observed for pid ${owner.pid}; ${owner.binding === binding ? "this can be another session" : "another setup; this setup is standby"}`;
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (error.code !== "ENOENT")
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
return "Local scheduler lease: not observed; waiting for an eligible session";
|
|
43
|
+
}
|
|
44
|
+
/** Caller holds state-directory access during acquisition; the renewable guard prevents live migration. */
|
|
45
|
+
export async function acquireContinuousLease(binding) {
|
|
46
|
+
await prepareContinuousRoot();
|
|
47
|
+
const file = path.join(continuousRoot(), "scheduler");
|
|
48
|
+
const guardPath = `${file}.lock`;
|
|
49
|
+
if (localLeases.has(file))
|
|
50
|
+
return undefined;
|
|
51
|
+
const previousOwner = await readContinuousPrivate("owner.json");
|
|
52
|
+
if (previousOwner !== undefined && !validOwner(previousOwner))
|
|
53
|
+
throw new Error("Invalid continuous sync owner; evidence retained.");
|
|
54
|
+
if (localLeases.has(file))
|
|
55
|
+
return undefined;
|
|
56
|
+
localLeases.add(file);
|
|
57
|
+
const acquiredAt = performance.now();
|
|
58
|
+
const ownerPath = path.join(continuousRoot(), "owner.json");
|
|
59
|
+
const controller = new AbortController();
|
|
60
|
+
const owner = { version: 1, id: randomUUID(), pid: process.pid, binding };
|
|
61
|
+
let identity;
|
|
62
|
+
let published = false;
|
|
63
|
+
// proper-lockfile also uses rmdirSync at process exit. Fence both cleanup paths.
|
|
64
|
+
const removeGuard = (target) => {
|
|
65
|
+
if (identity) {
|
|
66
|
+
const current = lstatSync(target);
|
|
67
|
+
if (current.dev !== identity.dev || current.ino !== identity.ino)
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
let current;
|
|
71
|
+
try {
|
|
72
|
+
const record = lstatSync(ownerPath);
|
|
73
|
+
if (!record.isFile() ||
|
|
74
|
+
record.isSymbolicLink() ||
|
|
75
|
+
record.nlink !== 1 ||
|
|
76
|
+
record.size > 4096 ||
|
|
77
|
+
(process.platform !== "win32" && record.mode & 0o077))
|
|
78
|
+
return;
|
|
79
|
+
current = JSON.parse(readFileSync(ownerPath, "utf8"));
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (error.code !== "ENOENT")
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
if (published && current === undefined)
|
|
86
|
+
return;
|
|
87
|
+
if (current !== undefined &&
|
|
88
|
+
(!validOwner(current) ||
|
|
89
|
+
(current.id !== owner.id && (published || current.id !== previousOwner?.id))))
|
|
90
|
+
return;
|
|
91
|
+
rmdirSync(target);
|
|
92
|
+
};
|
|
93
|
+
const adapter = {
|
|
94
|
+
...LOCKFILE_FS_ADAPTER,
|
|
95
|
+
stat: (target, callback) => stat(target, (error, value) => {
|
|
96
|
+
if (!error && value.mtimeMs > Date.now() + STALE_MS) {
|
|
97
|
+
const identity = `${value.dev}:${value.ino}:${value.mtimeMs}`;
|
|
98
|
+
const previous = futureGuards.get(target);
|
|
99
|
+
if (!previous || previous.identity !== identity)
|
|
100
|
+
futureGuards.set(target, { identity, since: performance.now() });
|
|
101
|
+
else if (performance.now() - previous.since > STALE_MS)
|
|
102
|
+
value.mtime = new Date(Date.now() - STALE_MS - 1);
|
|
103
|
+
}
|
|
104
|
+
else
|
|
105
|
+
futureGuards.delete(target);
|
|
106
|
+
callback(error, value);
|
|
107
|
+
}),
|
|
108
|
+
rmdirSync: removeGuard,
|
|
109
|
+
rmdir: (target, callback) => {
|
|
110
|
+
try {
|
|
111
|
+
removeGuard(target);
|
|
112
|
+
callback();
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
callback(error);
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
let compromised = false;
|
|
120
|
+
let unlock;
|
|
121
|
+
try {
|
|
122
|
+
unlock = await lockfile.lock(file, {
|
|
123
|
+
fs: adapter,
|
|
124
|
+
realpath: false,
|
|
125
|
+
stale: STALE_MS,
|
|
126
|
+
update: 10_000,
|
|
127
|
+
retries: 0,
|
|
128
|
+
onCompromised: () => {
|
|
129
|
+
compromised = true;
|
|
130
|
+
controller.abort(new DOMException("Continuous sync ownership lost", "AbortError"));
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
localLeases.delete(file);
|
|
136
|
+
if (error.code === "ELOCKED")
|
|
137
|
+
return undefined;
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
let released = false;
|
|
141
|
+
const release = async () => {
|
|
142
|
+
if (released)
|
|
143
|
+
return;
|
|
144
|
+
released = true;
|
|
145
|
+
controller.abort(new DOMException("Continuous sync owner released", "AbortError"));
|
|
146
|
+
try {
|
|
147
|
+
if (!compromised)
|
|
148
|
+
await unlock();
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
localLeases.delete(file);
|
|
152
|
+
futureGuards.delete(guardPath);
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
try {
|
|
156
|
+
identity = await fs.lstat(guardPath);
|
|
157
|
+
await withLock("continuous-owner", async () => {
|
|
158
|
+
const previous = await readContinuousPrivate("owner.json");
|
|
159
|
+
if (previous !== undefined && !validOwner(previous))
|
|
160
|
+
throw new Error("Invalid continuous sync owner; evidence retained.");
|
|
161
|
+
if (previous?.id !== previousOwner?.id ||
|
|
162
|
+
performance.now() - acquiredAt > STALE_MS)
|
|
163
|
+
throw new Error("Continuous lease generation changed before publication.");
|
|
164
|
+
const current = lstatSync(guardPath);
|
|
165
|
+
if (controller.signal.aborted || current.dev !== identity?.dev || current.ino !== identity.ino)
|
|
166
|
+
throw new Error("Continuous lease changed before publication.");
|
|
167
|
+
await writeContinuousPrivate("owner.json", owner);
|
|
168
|
+
published = true;
|
|
169
|
+
});
|
|
170
|
+
const assert = () => {
|
|
171
|
+
controller.signal.throwIfAborted();
|
|
172
|
+
try {
|
|
173
|
+
const root = lstatSync(continuousRoot());
|
|
174
|
+
if (!root.isDirectory() || root.isSymbolicLink() || (process.platform !== "win32" && root.mode & 0o077))
|
|
175
|
+
throw new Error("Unsafe lease root");
|
|
176
|
+
const stat = lstatSync(guardPath);
|
|
177
|
+
if (stat.isSymbolicLink() ||
|
|
178
|
+
!stat.isDirectory() ||
|
|
179
|
+
stat.dev !== identity?.dev ||
|
|
180
|
+
stat.ino !== identity.ino ||
|
|
181
|
+
Date.now() - stat.mtimeMs > STALE_MS)
|
|
182
|
+
throw new Error("Lease guard changed");
|
|
183
|
+
const record = lstatSync(ownerPath);
|
|
184
|
+
if (!record.isFile() ||
|
|
185
|
+
record.isSymbolicLink() ||
|
|
186
|
+
record.nlink !== 1 ||
|
|
187
|
+
record.size > 4096 ||
|
|
188
|
+
(process.platform !== "win32" && record.mode & 0o077))
|
|
189
|
+
throw new Error("Unsafe owner record");
|
|
190
|
+
const value = JSON.parse(readFileSync(ownerPath, "utf8"));
|
|
191
|
+
if (!validOwner(value) || value.id !== owner.id || value.binding !== binding || value.pid !== process.pid)
|
|
192
|
+
throw new Error("Lease owner changed");
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
controller.abort(new DOMException("Continuous sync ownership lost", "AbortError"));
|
|
196
|
+
controller.signal.throwIfAborted();
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
assert();
|
|
200
|
+
return { signal: controller.signal, assert, release };
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
await release();
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { AnySyncConfig } from "../settings/settings-types.js";
|
|
2
|
+
import { type ContinuousErrorKind } from "./continuous-errors.js";
|
|
3
|
+
import { type ContinuousLease } from "./continuous-lease.js";
|
|
4
|
+
export declare const REQUEST_WINDOW_MS: number;
|
|
5
|
+
export interface ContinuousRecord {
|
|
6
|
+
version: 1;
|
|
7
|
+
binding: string;
|
|
8
|
+
pending: boolean;
|
|
9
|
+
phase: "waiting" | "syncing" | "retry" | "blocked";
|
|
10
|
+
next: number;
|
|
11
|
+
failures: number;
|
|
12
|
+
evidence?: string;
|
|
13
|
+
recovery?: string;
|
|
14
|
+
notice?: string;
|
|
15
|
+
configuration?: string;
|
|
16
|
+
error?: ContinuousErrorKind;
|
|
17
|
+
checked?: number;
|
|
18
|
+
transferred?: number;
|
|
19
|
+
calls: {
|
|
20
|
+
key: string;
|
|
21
|
+
at: number;
|
|
22
|
+
}[];
|
|
23
|
+
attempts: Record<string, number>;
|
|
24
|
+
}
|
|
25
|
+
export declare function validateContinuousRecord(value: unknown, binding: string): asserts value is ContinuousRecord;
|
|
26
|
+
export declare function readContinuousRecord(binding: string): Promise<ContinuousRecord>;
|
|
27
|
+
export declare function updateContinuousRecord<T>(binding: string, lease: ContinuousLease, update: (record: ContinuousRecord) => T): Promise<T>;
|
|
28
|
+
export declare function normalizeContinuousClock(record: ContinuousRecord, now: number): void;
|
|
29
|
+
export declare function reserveContinuousRequest(binding: string, lease: ContinuousLease, key: string, clock?: () => number, signal?: AbortSignal): Promise<void>;
|
|
30
|
+
/** Read-only status: no directory creation, lease, mutation, request reservation or provider call. */
|
|
31
|
+
export declare function continuousStatusLines(config: AnySyncConfig, clock?: () => number): Promise<string[]>;
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { withLock } from "../state/lock.js";
|
|
2
|
+
import { withStateDirectoryAccess } from "../state/state-directory.js";
|
|
3
|
+
import { ContinuousError } from "./continuous-errors.js";
|
|
4
|
+
import { continuousLeaseOwner } from "./continuous-lease.js";
|
|
5
|
+
import { CONTINUOUS_RECORD_MAX_BYTES, continuousBinding, readContinuousPrivate, readContinuousPrivateDocument, writeContinuousPrivate, } from "./continuous-storage.js";
|
|
6
|
+
export const REQUEST_WINDOW_MS = 15 * 60_000;
|
|
7
|
+
const digest = (value) => typeof value === "string" && /^[a-f0-9]{64}$/u.test(value);
|
|
8
|
+
const timestamp = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 8_640_000_000_000_000;
|
|
9
|
+
export function validateContinuousRecord(value, binding) {
|
|
10
|
+
const record = value;
|
|
11
|
+
if (!record ||
|
|
12
|
+
typeof record !== "object" ||
|
|
13
|
+
record.version !== 1 ||
|
|
14
|
+
record.binding !== binding ||
|
|
15
|
+
Object.keys(record).some((key) => ![
|
|
16
|
+
"version",
|
|
17
|
+
"binding",
|
|
18
|
+
"pending",
|
|
19
|
+
"phase",
|
|
20
|
+
"next",
|
|
21
|
+
"failures",
|
|
22
|
+
"evidence",
|
|
23
|
+
"recovery",
|
|
24
|
+
"notice",
|
|
25
|
+
"configuration",
|
|
26
|
+
"error",
|
|
27
|
+
"checked",
|
|
28
|
+
"transferred",
|
|
29
|
+
"calls",
|
|
30
|
+
"attempts",
|
|
31
|
+
].includes(key)) ||
|
|
32
|
+
typeof record.pending !== "boolean" ||
|
|
33
|
+
!["waiting", "syncing", "retry", "blocked"].includes(record.phase) ||
|
|
34
|
+
!timestamp(record.next) ||
|
|
35
|
+
!timestamp(record.failures) ||
|
|
36
|
+
record.failures > 30 ||
|
|
37
|
+
(record.evidence !== undefined && !digest(record.evidence)) ||
|
|
38
|
+
(record.recovery !== undefined && !digest(record.recovery)) ||
|
|
39
|
+
(record.notice !== undefined && !digest(record.notice)) ||
|
|
40
|
+
(record.configuration !== undefined && !digest(record.configuration)) ||
|
|
41
|
+
(record.error !== undefined &&
|
|
42
|
+
![
|
|
43
|
+
"transient",
|
|
44
|
+
"contention",
|
|
45
|
+
"stale",
|
|
46
|
+
"authentication",
|
|
47
|
+
"storage",
|
|
48
|
+
"unsafe",
|
|
49
|
+
"model",
|
|
50
|
+
"budget",
|
|
51
|
+
"unknown",
|
|
52
|
+
].includes(record.error)) ||
|
|
53
|
+
(record.checked !== undefined && !timestamp(record.checked)) ||
|
|
54
|
+
(record.transferred !== undefined && !timestamp(record.transferred)) ||
|
|
55
|
+
!Array.isArray(record.calls) ||
|
|
56
|
+
record.calls.length > 2 ||
|
|
57
|
+
record.calls.some((call) => !call || Object.keys(call).sort().join(",") !== "at,key" || !digest(call.key) || !timestamp(call.at)) ||
|
|
58
|
+
!record.attempts ||
|
|
59
|
+
typeof record.attempts !== "object" ||
|
|
60
|
+
Array.isArray(record.attempts) ||
|
|
61
|
+
Object.entries(record.attempts).some(([key, count]) => !digest(key) || !Number.isInteger(count) || count < 1 || count > 2) ||
|
|
62
|
+
record.calls.some((call) => (record.attempts[call.key] ?? 0) < record.calls.filter((other) => other.key === call.key).length))
|
|
63
|
+
throw new Error("Invalid continuous sync state; evidence retained.");
|
|
64
|
+
}
|
|
65
|
+
function emptyContinuousRecord(binding) {
|
|
66
|
+
return { version: 1, binding, pending: true, phase: "waiting", next: 0, failures: 0, calls: [], attempts: {} };
|
|
67
|
+
}
|
|
68
|
+
export async function readContinuousRecord(binding) {
|
|
69
|
+
const value = await readContinuousPrivate(`${binding}.json`);
|
|
70
|
+
if (value === undefined)
|
|
71
|
+
return emptyContinuousRecord(binding);
|
|
72
|
+
validateContinuousRecord(value, binding);
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
export async function updateContinuousRecord(binding, lease, update) {
|
|
76
|
+
return withStateDirectoryAccess(() => withLock("continuous-state", async () => {
|
|
77
|
+
lease.assert();
|
|
78
|
+
const record = await readContinuousRecord(binding);
|
|
79
|
+
lease.assert();
|
|
80
|
+
const result = update(record);
|
|
81
|
+
validateContinuousRecord(record, binding);
|
|
82
|
+
lease.assert();
|
|
83
|
+
await writeContinuousPrivate(`${binding}.json`, record);
|
|
84
|
+
lease.assert();
|
|
85
|
+
return result;
|
|
86
|
+
}));
|
|
87
|
+
}
|
|
88
|
+
export function normalizeContinuousClock(record, now) {
|
|
89
|
+
// A backward wall-clock jump cannot grant more calls: retain them for a full window.
|
|
90
|
+
record.calls = record.calls
|
|
91
|
+
.map((call) => ({ ...call, at: Math.min(call.at, now) }))
|
|
92
|
+
.filter((call) => now - call.at < REQUEST_WINDOW_MS);
|
|
93
|
+
record.next = Math.min(record.next, now + (record.error === "budget" ? REQUEST_WINDOW_MS : 300_000));
|
|
94
|
+
}
|
|
95
|
+
export async function reserveContinuousRequest(binding, lease, key, clock = Date.now, signal) {
|
|
96
|
+
signal?.throwIfAborted();
|
|
97
|
+
if (!digest(key))
|
|
98
|
+
throw new Error("Invalid continuous candidate key.");
|
|
99
|
+
let failure;
|
|
100
|
+
await updateContinuousRecord(binding, lease, (record) => {
|
|
101
|
+
signal?.throwIfAborted();
|
|
102
|
+
const now = clock();
|
|
103
|
+
signal?.throwIfAborted();
|
|
104
|
+
normalizeContinuousClock(record, now);
|
|
105
|
+
if ((record.attempts[key] ?? 0) >= 2)
|
|
106
|
+
failure = new ContinuousError("model", "Automatic request limit reached for this evidence. Change the evidence or review /sync; Sync now does not reset this limit.");
|
|
107
|
+
else if (record.calls.length >= 2)
|
|
108
|
+
failure = new ContinuousError("budget", "Automatic request window is full.", Math.max(0, (record.calls[0]?.at ?? now) + REQUEST_WINDOW_MS - now));
|
|
109
|
+
else {
|
|
110
|
+
record.attempts[key] = (record.attempts[key] ?? 0) + 1;
|
|
111
|
+
record.calls.push({ key, at: now });
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
// Atomic publication is not interruptible. A reservation written before cancellation stays spent.
|
|
115
|
+
signal?.throwIfAborted();
|
|
116
|
+
if (failure)
|
|
117
|
+
throw failure;
|
|
118
|
+
}
|
|
119
|
+
const recoveryActions = {
|
|
120
|
+
transient: "Wait for the scheduled retry. Check network and service availability if failures continue.",
|
|
121
|
+
contention: "Wait for the active sync operation to finish. Do not remove a live lock.",
|
|
122
|
+
stale: "Wait for a fresh inspection after the retry delay. Local or remote evidence changed.",
|
|
123
|
+
authentication: "Repair storage or Pi model authentication, then reopen /sync. Do not share credentials.",
|
|
124
|
+
storage: "Repair private-state permissions, free space or storage access. Retain accounting and recovery evidence.",
|
|
125
|
+
unsafe: "Remove secrets or repair unsupported conflicts. Changed evidence is inspected again; review /sync if needed.",
|
|
126
|
+
model: "Review conflict evidence and Pi model access. Sync now reuses cached refusals; a refusal needs changed evidence or a separately confirmed retry.",
|
|
127
|
+
budget: "Wait for the window allowance shown above. Waiting does not restore exhausted candidates or accounting capacity.",
|
|
128
|
+
unknown: "Review /sync diagnostics and reconcile pending recovery before retrying. Do not delete private evidence or blindly republish.",
|
|
129
|
+
};
|
|
130
|
+
function serializedBytes(record) {
|
|
131
|
+
// Keep this aligned with writeJson's private-document encoding.
|
|
132
|
+
return Buffer.byteLength(`${JSON.stringify(record, null, "\t")}\n`);
|
|
133
|
+
}
|
|
134
|
+
/** Check space for one reservation without retaining or publishing the synthetic candidate. */
|
|
135
|
+
function hasReservationCapacity(record, now) {
|
|
136
|
+
const existing = Object.keys(record.attempts).find((key) => record.attempts[key] === 1);
|
|
137
|
+
let key = existing ?? "0".repeat(64);
|
|
138
|
+
if (!existing) {
|
|
139
|
+
for (let index = 1; record.attempts[key] !== undefined; index++)
|
|
140
|
+
key = index.toString(16).padStart(64, "0");
|
|
141
|
+
}
|
|
142
|
+
return (serializedBytes({
|
|
143
|
+
...record,
|
|
144
|
+
calls: [...record.calls, { key, at: now }],
|
|
145
|
+
attempts: { ...record.attempts, [key]: (record.attempts[key] ?? 0) + 1 },
|
|
146
|
+
}) <= CONTINUOUS_RECORD_MAX_BYTES);
|
|
147
|
+
}
|
|
148
|
+
/** Read-only status: no directory creation, lease, mutation, request reservation or provider call. */
|
|
149
|
+
export async function continuousStatusLines(config, clock = Date.now) {
|
|
150
|
+
if (!config.continuous)
|
|
151
|
+
return ["Continuous sync: Off"];
|
|
152
|
+
if (!config.agentMode)
|
|
153
|
+
return ["Continuous sync: paused; enable Autonomous sync first"];
|
|
154
|
+
try {
|
|
155
|
+
const binding = await continuousBinding(config);
|
|
156
|
+
const document = await readContinuousPrivateDocument(`${binding}.json`);
|
|
157
|
+
const record = document === undefined ? emptyContinuousRecord(binding) : document.value;
|
|
158
|
+
validateContinuousRecord(record, binding);
|
|
159
|
+
const bytes = serializedBytes(record);
|
|
160
|
+
// Only this detached read is normalized. A Status read never publishes clock repairs or expires durable calls.
|
|
161
|
+
const now = clock();
|
|
162
|
+
normalizeContinuousClock(record, now);
|
|
163
|
+
const spent = Object.values(record.attempts).filter((count) => count === 2).length;
|
|
164
|
+
const eligible = record.calls.length < 2 ? now : Math.min(...record.calls.map((call) => call.at)) + REQUEST_WINDOW_MS;
|
|
165
|
+
const capacityRecord = { ...record, calls: [...record.calls] };
|
|
166
|
+
normalizeContinuousClock(capacityRecord, eligible);
|
|
167
|
+
const available = hasReservationCapacity(capacityRecord, eligible);
|
|
168
|
+
const owner = await continuousLeaseOwner(binding).catch(() => "Local scheduler lease: private owner metadata unavailable; retain evidence and repair access");
|
|
169
|
+
return [
|
|
170
|
+
`Continuous sync: ${record.phase}${record.error ? ` (${record.error})` : ""}${document === undefined ? "; no accounting record yet" : ""}`,
|
|
171
|
+
owner,
|
|
172
|
+
"Scheduler owner model: unavailable; the observing session's selected model is not proof of the owner's model.",
|
|
173
|
+
`Automatic requests (rolling 15 minutes, window only): ${record.calls.length}/2 used; ${2 - record.calls.length} remaining.`,
|
|
174
|
+
`Next request eligibility: ${available ? (eligible === now ? "now (window allowance)" : `${new Date(eligible).toISOString()} (window allowance)`) : "unavailable (accounting full)"}. Candidate, capacity, ownership and safety checks still apply.`,
|
|
175
|
+
`Spent candidates: ${spent} exhausted / ${Object.keys(record.attempts).length} tracked; 2 automatic requests per candidate. Expired windows do not clear this limit.`,
|
|
176
|
+
`Accounting: ${bytes}/${CONTINUOUS_RECORD_MAX_BYTES} serialized bytes; ${Math.max(0, CONTINUOUS_RECORD_MAX_BYTES - bytes)} bytes free; ${document?.bytes ?? 0} bytes on disk${available ? "." : "; full for another reservation."}`,
|
|
177
|
+
...(!available
|
|
178
|
+
? [
|
|
179
|
+
"Accounting recovery: pause Continuous sync and seek reviewed recovery. Do not delete accounting, prune candidates or reset limits to regain requests.",
|
|
180
|
+
]
|
|
181
|
+
: []),
|
|
182
|
+
`Last successful background check: ${record.checked !== undefined ? new Date(record.checked).toISOString() : "not yet checked"}`,
|
|
183
|
+
`Last successful background transfer: ${record.transferred !== undefined ? new Date(record.transferred).toISOString() : "none"}`,
|
|
184
|
+
...(record.phase === "retry" ? [`Next background attempt: ${new Date(record.next).toISOString()}`] : []),
|
|
185
|
+
...(record.error ? [`Recovery (${record.error}): ${recoveryActions[record.error]}`] : []),
|
|
186
|
+
...(record.phase === "blocked" && !record.error
|
|
187
|
+
? ["Review /sync diagnostics and repair changed evidence. Retain private recovery state."]
|
|
188
|
+
: []),
|
|
189
|
+
"Monitoring requires an eligible open Pi session. Status does not spend model requests or clear retry limits.",
|
|
190
|
+
];
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
return [
|
|
194
|
+
"Continuous sync: private state unavailable; usage, eligibility and accounting bytes cannot be verified.",
|
|
195
|
+
`Accounting capacity: ${CONTINUOUS_RECORD_MAX_BYTES} bytes; do not treat unavailable accounting as unused allowance.`,
|
|
196
|
+
"Recovery: pause Continuous sync, retain malformed, unknown or unsafe evidence, and repair private-state access. Do not delete accounting or reset limits.",
|
|
197
|
+
];
|
|
198
|
+
}
|
|
199
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { AnySyncConfig } from "../settings/settings-types.js";
|
|
2
|
+
export declare const CONTINUOUS_RECORD_MAX_BYTES = 131072;
|
|
3
|
+
export declare function hashContinuous(value: unknown): string;
|
|
4
|
+
export declare function continuousBinding(config: AnySyncConfig): Promise<string>;
|
|
5
|
+
export declare function continuousRoot(): string;
|
|
6
|
+
export declare function prepareContinuousRoot(): Promise<void>;
|
|
7
|
+
export declare function checkContinuousRoot(): Promise<void>;
|
|
8
|
+
export declare function readContinuousPrivate(name: string): Promise<unknown>;
|
|
9
|
+
/** Read-only metadata; uses the same private-file checks as runtime reads. */
|
|
10
|
+
export declare function readContinuousPrivateDocument(name: string): Promise<{
|
|
11
|
+
value: unknown;
|
|
12
|
+
bytes: number;
|
|
13
|
+
} | undefined>;
|
|
14
|
+
export declare function writeContinuousPrivate(name: string, value: unknown): Promise<void>;
|