@firstpick/pi-package-webui 0.8.6 → 0.8.7
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/README.md +18 -606
- package/bin/pi-webui-launcher.mjs +22 -0
- package/bin/pi-webui-update-supervisor.mjs +86 -0
- package/bin/pi-webui.mjs +558 -524
- package/index.ts +8 -5
- package/lib/component-update-state.mjs +21 -0
- package/lib/git-workflow-preferences.mjs +17 -2
- package/lib/optional-feature-catalog.mjs +1 -0
- package/lib/sampling-parameter-capabilities.mjs +160 -0
- package/lib/session-summary-preferences.mjs +16 -1
- package/lib/subagent-launch-slots.mjs +14 -2
- package/lib/trust-boundaries.mjs +3 -0
- package/lib/update/executor.mjs +99 -0
- package/lib/update/journal.mjs +175 -0
- package/lib/update/owners.mjs +70 -0
- package/lib/update/plan.mjs +134 -0
- package/lib/update/resolver.mjs +168 -0
- package/lib/update/supervisor.mjs +238 -0
- package/lib/update/verify.mjs +52 -0
- package/lib/update-commands.mjs +25 -13
- package/lib/webui-workspaces.mjs +17 -1
- package/package.json +4 -4
- package/public/app.js +1290 -82
- package/public/index.html +124 -48
- package/public/middle-button-drag-scroll.mjs +154 -0
- package/public/sampling-parameter-controls.mjs +361 -0
- package/public/service-worker.js +3 -1
- package/public/styles.css +417 -1
- package/tests/boot-failure-diagnostics.test.mjs +3 -3
- package/tests/browser/control-deck-component-updates.spec.mjs +20 -22
- package/tests/browser/middle-button-drag-scroll.spec.mjs +145 -0
- package/tests/browser/persistent-ui-layout.spec.mjs +68 -23
- package/tests/browser/sampling-tooltip.spec.mjs +228 -0
- package/tests/browser/update-reconnect.spec.mjs +92 -0
- package/tests/codex-fast-mode-static.test.mjs +2 -2
- package/tests/common-options-submenus-interaction-static.test.mjs +172 -0
- package/tests/common-options-submenus-markup-static.test.mjs +152 -0
- package/tests/component-update-api-static.test.mjs +22 -61
- package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
- package/tests/control-deck-component-updates-static.test.mjs +13 -237
- package/tests/durable-rpc-supervisor-harness.test.mjs +3 -1
- package/tests/fast-mode-client-static.test.mjs +1 -1
- package/tests/feature-decision-output-popup-static.test.mjs +2 -2
- package/tests/feature-system-prompt-optional-feature-static.test.mjs +49 -0
- package/tests/fixtures/fake-pi.mjs +66 -0
- package/tests/fixtures/update/tree-timeout-descendant.mjs +6 -0
- package/tests/fixtures/update/tree-timeout-parent.mjs +11 -0
- package/tests/git-footer-context-menu-static.test.mjs +58 -0
- package/tests/http-endpoints-harness.test.mjs +68 -18
- package/tests/middle-button-drag-scroll-static.test.mjs +24 -0
- package/tests/middle-button-drag-scroll.test.mjs +170 -0
- package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
- package/tests/mobile-foundation-static.test.mjs +4 -4
- package/tests/mobile-phone-experience-static.test.mjs +1 -1
- package/tests/mobile-static.test.mjs +23 -21
- package/tests/open-issue-wizard-static.test.mjs +1 -1
- package/tests/optional-feature-migration-frontend.test.mjs +9 -5
- package/tests/persistent-ui-layout-static.test.mjs +13 -2
- package/tests/questionnaire-dialog.test.mjs +3 -3
- package/tests/remote-auth-settings-harness.test.mjs +34 -0
- package/tests/rpc-supervisor-host.test.mjs +11 -2
- package/tests/safety-guard-auto-review-harness.test.mjs +117 -0
- package/tests/safety-guard-auto-review-static.test.mjs +34 -0
- package/tests/sampling-native-controls-user-flow.test.mjs +752 -0
- package/tests/sampling-parameter-capabilities.test.mjs +167 -0
- package/tests/sampling-parameter-controls.test.mjs +241 -0
- package/tests/session-sampling-helper.test.mjs +228 -0
- package/tests/session-sampling-http.test.mjs +168 -0
- package/tests/session-sampling-ui-static.test.mjs +370 -0
- package/tests/session-summary-core.test.mjs +24 -11
- package/tests/side-panel-section-height-removal-static.test.mjs +34 -0
- package/tests/side-panel-section-reorder-static.test.mjs +3 -3
- package/tests/staged-content-hash-contract.test.mjs +52 -11
- package/tests/subagent-launch-slots.test.mjs +18 -1
- package/tests/theme-customizer-static.test.mjs +1 -1
- package/tests/ui-layout-settings.test.mjs +18 -1
- package/tests/update-api-harness.test.mjs +111 -0
- package/tests/update-commands.test.mjs +15 -45
- package/tests/update-executor-process-tree-harness.test.mjs +22 -0
- package/tests/update-journal-harness.test.mjs +59 -0
- package/tests/update-lock-multiprocess-harness.test.mjs +46 -0
- package/tests/update-owners.test.mjs +27 -0
- package/tests/update-plan.test.mjs +58 -0
- package/tests/update-resolver.test.mjs +56 -0
- package/tests/update-supervisor-harness.test.mjs +57 -0
- package/tests/update-tab-restore-harness.test.mjs +24 -0
- package/tests/update-verify.test.mjs +31 -0
- package/tests/workspace-files-live-updates-static.test.mjs +13 -4
- package/webui-rpc-helper.mjs +119 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
|
|
3
|
+
const REFUSALS = Object.freeze({
|
|
4
|
+
pnpm: "This package is owned by pnpm. Update it manually with the owning pnpm installation.",
|
|
5
|
+
yarn: "This package is owned by Yarn. Update it manually with the owning Yarn installation.",
|
|
6
|
+
source: "Source checkouts are never mutated automatically. Pull and rebuild this checkout manually.",
|
|
7
|
+
linked: "Linked packages are never mutated automatically. Update the link target manually.",
|
|
8
|
+
unknown: "Package ownership could not be proven. Update the package manually with its owning tool.",
|
|
9
|
+
opaque: "The installation root is opaque or outside its declared owner root; automatic update is refused.",
|
|
10
|
+
nested: "Only exact top-level packages may be updated automatically; transitive packages are refused.",
|
|
11
|
+
optional: "Optional packages require explicit Pi-owned registration before automatic update.",
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
function bounded(value, max = 320) {
|
|
15
|
+
const text = String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim();
|
|
16
|
+
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function inside(root, candidate) {
|
|
20
|
+
const relative = path.relative(path.resolve(root), path.resolve(candidate));
|
|
21
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function refusal(code, manager, detail = "") {
|
|
25
|
+
return Object.freeze({
|
|
26
|
+
accepted: false,
|
|
27
|
+
code,
|
|
28
|
+
manager: manager || "unknown",
|
|
29
|
+
guidance: bounded(detail || REFUSALS[code] || REFUSALS.unknown),
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Fail-closed package ownership classification for exact top-level targets. */
|
|
34
|
+
export function classifyPackageOwner({
|
|
35
|
+
manager = "unknown",
|
|
36
|
+
packageRoot = "",
|
|
37
|
+
ownerRoot = "",
|
|
38
|
+
topLevel = true,
|
|
39
|
+
linked = false,
|
|
40
|
+
sourceCheckout = false,
|
|
41
|
+
optional = false,
|
|
42
|
+
piOwned = false,
|
|
43
|
+
} = {}) {
|
|
44
|
+
const normalizedManager = String(manager || "unknown").trim().toLowerCase();
|
|
45
|
+
if (sourceCheckout) return refusal("source", normalizedManager);
|
|
46
|
+
if (linked) return refusal("linked", normalizedManager);
|
|
47
|
+
if (!topLevel) return refusal("nested", normalizedManager);
|
|
48
|
+
if (optional && !piOwned) return refusal("optional", normalizedManager);
|
|
49
|
+
if (normalizedManager === "pnpm" || normalizedManager === "yarn") return refusal(normalizedManager, normalizedManager);
|
|
50
|
+
if (!["npm", "bun", "pi"].includes(normalizedManager)) return refusal("unknown", normalizedManager);
|
|
51
|
+
if (!packageRoot || !ownerRoot) return refusal("opaque", normalizedManager);
|
|
52
|
+
try {
|
|
53
|
+
if (!inside(ownerRoot, packageRoot)) return refusal("opaque", normalizedManager);
|
|
54
|
+
} catch {
|
|
55
|
+
return refusal("opaque", normalizedManager);
|
|
56
|
+
}
|
|
57
|
+
return Object.freeze({
|
|
58
|
+
accepted: true,
|
|
59
|
+
code: "owned",
|
|
60
|
+
manager: normalizedManager,
|
|
61
|
+
packageRoot: path.resolve(packageRoot),
|
|
62
|
+
ownerRoot: path.resolve(ownerRoot),
|
|
63
|
+
scope: optional ? "pi-owned-optional" : "core",
|
|
64
|
+
topLevel: true,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function ownershipRefusalGuidance(code) {
|
|
69
|
+
return bounded(REFUSALS[code] || REFUSALS.unknown);
|
|
70
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { classifyPackageOwner } from "./owners.mjs";
|
|
3
|
+
|
|
4
|
+
const EXACT_VERSION = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
|
|
5
|
+
|
|
6
|
+
function clean(value) {
|
|
7
|
+
return String(value ?? "").trim();
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function canonicalValue(value) {
|
|
11
|
+
if (Array.isArray(value)) return value.map(canonicalValue);
|
|
12
|
+
if (!value || typeof value !== "object") return value;
|
|
13
|
+
return Object.fromEntries(Object.keys(value).sort().filter((key) => value[key] !== undefined).map((key) => [key, canonicalValue(value[key])]));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function canonicalPlanJson(value) {
|
|
17
|
+
return JSON.stringify(canonicalValue(value));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function digestUpdatePlan(plan) {
|
|
21
|
+
const { digest: _digest, ...unsigned } = plan || {};
|
|
22
|
+
return createHash("sha256").update(canonicalPlanJson(unsigned)).digest("hex");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function exactVersion(value, label) {
|
|
26
|
+
const normalized = clean(value).replace(/^v/i, "");
|
|
27
|
+
if (!EXACT_VERSION.test(normalized)) throw new TypeError(`${label} must resolve to an exact version`);
|
|
28
|
+
return normalized;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function registryUrl(value, label) {
|
|
32
|
+
const normalized = clean(value);
|
|
33
|
+
let parsed;
|
|
34
|
+
try { parsed = new URL(normalized); } catch { throw new TypeError(`${label} must be an absolute HTTP(S) registry URL`); }
|
|
35
|
+
if (!/^https?:$/.test(parsed.protocol) || parsed.username || parsed.password || parsed.hash) {
|
|
36
|
+
throw new TypeError(`${label} must be a credential-free HTTP(S) registry URL`);
|
|
37
|
+
}
|
|
38
|
+
return parsed.href;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function commandRecord(command) {
|
|
42
|
+
if (!command || typeof command !== "object" || Array.isArray(command)) throw new TypeError("target command must be an object");
|
|
43
|
+
const executable = clean(command.command);
|
|
44
|
+
if (!executable || !Array.isArray(command.args)) throw new TypeError("target command requires command and an argument array");
|
|
45
|
+
return Object.freeze({ command: executable, args: Object.freeze(command.args.map(String)) });
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Resolve moving tags exactly once and bind all apply inputs into one digest. */
|
|
49
|
+
export async function createUpdatePlan({
|
|
50
|
+
transactionId = randomUUID(),
|
|
51
|
+
createdAt = new Date().toISOString(),
|
|
52
|
+
registry = "",
|
|
53
|
+
identities = [],
|
|
54
|
+
candidates = [],
|
|
55
|
+
resolveExactTarget,
|
|
56
|
+
} = {}) {
|
|
57
|
+
if (typeof resolveExactTarget !== "function") throw new TypeError("resolveExactTarget is required");
|
|
58
|
+
if (!/^[A-Za-z0-9._-]{1,128}$/.test(clean(transactionId))) throw new TypeError("transactionId is invalid");
|
|
59
|
+
const createdTimestamp = new Date(createdAt);
|
|
60
|
+
if (!Number.isFinite(createdTimestamp.getTime())) throw new TypeError("createdAt is invalid");
|
|
61
|
+
const identityRecords = identities.map((identity) => Object.freeze(canonicalValue(identity)));
|
|
62
|
+
const identityIds = new Set(identityRecords.map((identity) => clean(identity.canonicalId)).filter(Boolean));
|
|
63
|
+
if (identityIds.size !== identityRecords.length) throw new TypeError("every plan identity requires a unique canonicalId");
|
|
64
|
+
const targets = [];
|
|
65
|
+
const refusals = [];
|
|
66
|
+
|
|
67
|
+
for (const candidate of candidates) {
|
|
68
|
+
const id = clean(candidate?.id);
|
|
69
|
+
if (!id) throw new TypeError("every candidate requires an id");
|
|
70
|
+
const owner = classifyPackageOwner(candidate.owner);
|
|
71
|
+
if (!owner.accepted) {
|
|
72
|
+
refusals.push(Object.freeze({ id, packageName: clean(candidate.packageName), ...owner }));
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
const resolved = await resolveExactTarget(Object.freeze({
|
|
76
|
+
id,
|
|
77
|
+
packageName: clean(candidate.packageName),
|
|
78
|
+
requested: clean(candidate.requested || "latest"),
|
|
79
|
+
registry: clean(candidate.registry || registry),
|
|
80
|
+
}));
|
|
81
|
+
const targetVersion = exactVersion(resolved?.version, `${id} target`);
|
|
82
|
+
const currentVersion = exactVersion(candidate.currentVersion, `${id} current version`);
|
|
83
|
+
const targetRegistry = registryUrl(resolved?.registry || candidate.registry || registry, `${id} registry`);
|
|
84
|
+
const packageName = clean(candidate.packageName);
|
|
85
|
+
const identityId = clean(candidate.identityId);
|
|
86
|
+
if (!packageName) throw new TypeError(`${id} packageName is required`);
|
|
87
|
+
if (!identityIds.has(identityId)) throw new TypeError(`${id} identityId must reference a canonical plan identity`);
|
|
88
|
+
if (targetVersion === currentVersion) continue;
|
|
89
|
+
targets.push(Object.freeze({
|
|
90
|
+
id,
|
|
91
|
+
kind: clean(candidate.kind || "package"),
|
|
92
|
+
packageName,
|
|
93
|
+
identityId,
|
|
94
|
+
currentVersion,
|
|
95
|
+
targetVersion,
|
|
96
|
+
registry: targetRegistry,
|
|
97
|
+
strategy: clean(candidate.strategy || owner.manager),
|
|
98
|
+
owner,
|
|
99
|
+
command: commandRecord(await candidate.commandForVersion(targetVersion, targetRegistry)),
|
|
100
|
+
metadata: Object.freeze(canonicalValue(resolved?.metadata || {})),
|
|
101
|
+
}));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const unsigned = Object.freeze({
|
|
105
|
+
schemaVersion: 1,
|
|
106
|
+
transactionId: clean(transactionId),
|
|
107
|
+
createdAt: createdTimestamp.toISOString(),
|
|
108
|
+
registry: registry ? registryUrl(registry, "plan registry") : "",
|
|
109
|
+
identities: Object.freeze(identityRecords),
|
|
110
|
+
targets: Object.freeze(targets),
|
|
111
|
+
refusals: Object.freeze(refusals),
|
|
112
|
+
});
|
|
113
|
+
const digest = digestUpdatePlan(unsigned);
|
|
114
|
+
return Object.freeze({ ...unsigned, digest });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function assertUpdatePlanDigest(plan, suppliedDigest) {
|
|
118
|
+
const expected = digestUpdatePlan(plan);
|
|
119
|
+
if (!/^[a-f0-9]{64}$/.test(clean(suppliedDigest)) || suppliedDigest !== plan?.digest || suppliedDigest !== expected) {
|
|
120
|
+
const error = new Error("Update plan digest does not match the persisted exact-target plan.");
|
|
121
|
+
error.code = "UPDATE_PLAN_DIGEST_MISMATCH";
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
return true;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function assertPlanIdentity(planTarget, activeIdentity) {
|
|
128
|
+
if (!planTarget?.identityId || planTarget.identityId !== activeIdentity?.canonicalId) {
|
|
129
|
+
const error = new Error(`Active identity changed before applying ${planTarget?.id || "update target"}.`);
|
|
130
|
+
error.code = "UPDATE_IDENTITY_CHANGED";
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { resolveCommandDirectory, resolvePiCommandInvocation } from "../npm-command.mjs";
|
|
4
|
+
|
|
5
|
+
const VERSION_PATTERN = /(?:^|\s)v?(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)(?=\s|$)/m;
|
|
6
|
+
|
|
7
|
+
function clean(value) {
|
|
8
|
+
return String(value ?? "").trim();
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function parseRuntimeVersion(value) {
|
|
12
|
+
return clean(value).match(VERSION_PATTERN)?.[1] || "";
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function pathApi(platform) {
|
|
16
|
+
return platform === "win32" ? path.win32 : path.posix;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function canonicalize(filePath, runtime) {
|
|
20
|
+
if (!filePath) return "";
|
|
21
|
+
const realpath = runtime.realpathSync ?? realpathSync;
|
|
22
|
+
try {
|
|
23
|
+
return realpath(filePath);
|
|
24
|
+
} catch {
|
|
25
|
+
return pathApi(runtime.platform ?? process.platform).resolve(filePath);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function resolvedExecutablePath(command, runtime) {
|
|
30
|
+
const api = pathApi(runtime.platform ?? process.platform);
|
|
31
|
+
const value = clean(command).replace(/^"|"$/g, "");
|
|
32
|
+
if (api.isAbsolute(value) || value.includes("/") || value.includes("\\")) return value;
|
|
33
|
+
const directory = resolveCommandDirectory(value, runtime);
|
|
34
|
+
return directory ? api.join(directory, value) : value;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function cliFromInvocation(invocation) {
|
|
38
|
+
const first = invocation.args?.[0] || "";
|
|
39
|
+
return /(?:^|[\\/])cli\.(?:c?js|mjs)$/i.test(first) ? first : "";
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function packageRootFromCli(cliPath, platform) {
|
|
43
|
+
if (!cliPath) return "";
|
|
44
|
+
const api = pathApi(platform);
|
|
45
|
+
const normalized = api.normalize(cliPath);
|
|
46
|
+
return api.basename(api.dirname(normalized)).toLowerCase() === "dist"
|
|
47
|
+
? api.dirname(api.dirname(normalized))
|
|
48
|
+
: api.dirname(normalized);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function explicitResolution(command, runtime) {
|
|
52
|
+
const platform = runtime.platform ?? process.platform;
|
|
53
|
+
const api = pathApi(platform);
|
|
54
|
+
const exists = runtime.existsSync ?? existsSync;
|
|
55
|
+
const requested = clean(command).replace(/^"|"$/g, "");
|
|
56
|
+
if (!requested) return { ok: false, reason: "No explicit Pi executable was supplied." };
|
|
57
|
+
const isPath = api.isAbsolute(requested) || requested.includes("/") || requested.includes("\\");
|
|
58
|
+
const directory = resolveCommandDirectory(requested, runtime);
|
|
59
|
+
if (!isPath && !directory) {
|
|
60
|
+
return { ok: false, reason: "The explicit Pi command is opaque or cannot be resolved to one executable." };
|
|
61
|
+
}
|
|
62
|
+
if (isPath) {
|
|
63
|
+
try {
|
|
64
|
+
if (!exists(requested) && !directory) return { ok: false, reason: "The explicit Pi executable does not exist." };
|
|
65
|
+
} catch {
|
|
66
|
+
return { ok: false, reason: "The explicit Pi executable cannot be inspected safely." };
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return { ok: true };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function probePi({ command, source, runCommand, runtime, timeoutMs, probeVersion }) {
|
|
73
|
+
const invocation = resolvePiCommandInvocation(command, [], runtime);
|
|
74
|
+
const cliPath = cliFromInvocation(invocation);
|
|
75
|
+
let version = "";
|
|
76
|
+
if (probeVersion) {
|
|
77
|
+
const result = await runCommand(invocation.command, [...invocation.args, "--version"], {
|
|
78
|
+
timeoutMs,
|
|
79
|
+
maxOutputLength: 4_000,
|
|
80
|
+
});
|
|
81
|
+
version = result?.exitCode === 0 && !result?.timedOut && !result?.error
|
|
82
|
+
? parseRuntimeVersion(`${result.stdout || ""}\n${result.stderr || ""}`)
|
|
83
|
+
: "";
|
|
84
|
+
if (!version) return null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const canonicalCli = canonicalize(cliPath, runtime);
|
|
88
|
+
const canonicalExecutable = canonicalize(resolvedExecutablePath(invocation.command, runtime), runtime);
|
|
89
|
+
const canonicalRequested = canonicalize(resolvedExecutablePath(command, runtime), runtime);
|
|
90
|
+
const identityPath = canonicalCli || (source === "explicit" ? canonicalRequested : canonicalExecutable);
|
|
91
|
+
return Object.freeze({
|
|
92
|
+
kind: "pi",
|
|
93
|
+
source,
|
|
94
|
+
version,
|
|
95
|
+
canonicalId: `pi:${identityPath}`,
|
|
96
|
+
executable: canonicalExecutable,
|
|
97
|
+
cliPath: canonicalCli,
|
|
98
|
+
packageRoot: packageRootFromCli(canonicalCli, runtime.platform ?? process.platform)
|
|
99
|
+
|| (source === "explicit" && canonicalRequested ? pathApi(runtime.platform ?? process.platform).dirname(canonicalRequested) : ""),
|
|
100
|
+
invocation: Object.freeze({ command: invocation.command, args: Object.freeze([...invocation.args]) }),
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Resolve the same Pi runtime used for tabs and updates. Bundled Pi wins over
|
|
106
|
+
* PATH unless an exact explicit executable was supplied. PATH is reported
|
|
107
|
+
* separately and is never selected merely because it is newer.
|
|
108
|
+
*/
|
|
109
|
+
export async function resolveCanonicalPiRuntime({
|
|
110
|
+
explicitCommand = "",
|
|
111
|
+
bundledCli = "",
|
|
112
|
+
pathCommand = "pi",
|
|
113
|
+
runCommand,
|
|
114
|
+
timeoutMs = 10_000,
|
|
115
|
+
probeVersion = true,
|
|
116
|
+
runtime = {},
|
|
117
|
+
} = {}) {
|
|
118
|
+
if (typeof runCommand !== "function") throw new TypeError("runCommand is required");
|
|
119
|
+
const exists = runtime.existsSync ?? existsSync;
|
|
120
|
+
const explicit = clean(explicitCommand);
|
|
121
|
+
|
|
122
|
+
if (explicit) {
|
|
123
|
+
const resolution = explicitResolution(explicit, runtime);
|
|
124
|
+
if (!resolution.ok) {
|
|
125
|
+
return Object.freeze({ active: null, path: null, refusal: Object.freeze({ code: "explicit-pi-unresolved", message: resolution.reason }) });
|
|
126
|
+
}
|
|
127
|
+
const active = await probePi({ command: explicit, source: "explicit", runCommand, runtime, timeoutMs, probeVersion }).catch(() => null);
|
|
128
|
+
return Object.freeze({
|
|
129
|
+
active,
|
|
130
|
+
path: null,
|
|
131
|
+
refusal: active ? null : Object.freeze({ code: "explicit-pi-unverifiable", message: "The exact explicit Pi executable did not report a supported version." }),
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
let bundledAvailable = false;
|
|
136
|
+
try { bundledAvailable = Boolean(bundledCli && exists(bundledCli)); } catch {}
|
|
137
|
+
const active = bundledAvailable
|
|
138
|
+
? await probePi({ command: bundledCli, source: "bundled", runCommand, runtime, timeoutMs, probeVersion }).catch(() => null)
|
|
139
|
+
: await probePi({ command: pathCommand, source: "path", runCommand, runtime, timeoutMs, probeVersion }).catch(() => null);
|
|
140
|
+
const pathIdentity = bundledAvailable
|
|
141
|
+
? await probePi({ command: pathCommand, source: "path", runCommand, runtime, timeoutMs, probeVersion }).catch(() => null)
|
|
142
|
+
: active;
|
|
143
|
+
|
|
144
|
+
return Object.freeze({
|
|
145
|
+
active,
|
|
146
|
+
path: pathIdentity,
|
|
147
|
+
refusal: active ? null : Object.freeze({ code: "pi-runtime-unverifiable", message: "No supported active Pi runtime could be verified." }),
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function resolveWebuiRuntimeIdentity({ packageRoot, packageName, version, owner } = {}, runtime = {}) {
|
|
152
|
+
const root = canonicalize(packageRoot, runtime);
|
|
153
|
+
const normalizedVersion = clean(version).replace(/^v/i, "");
|
|
154
|
+
if (!root || !packageName || !normalizedVersion) throw new TypeError("packageRoot, packageName, and version are required");
|
|
155
|
+
return Object.freeze({
|
|
156
|
+
kind: "webui",
|
|
157
|
+
source: "active-package",
|
|
158
|
+
packageName: clean(packageName),
|
|
159
|
+
version: normalizedVersion,
|
|
160
|
+
packageRoot: root,
|
|
161
|
+
owner: owner ? Object.freeze({ ...owner }) : null,
|
|
162
|
+
canonicalId: `webui:${root}`,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function sameRuntimeIdentity(left, right) {
|
|
167
|
+
return Boolean(left?.canonicalId && right?.canonicalId && left.canonicalId === right.canonicalId);
|
|
168
|
+
}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { chmod, mkdir, open, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { updateStatePaths } from "./journal.mjs";
|
|
6
|
+
|
|
7
|
+
const POINTER_SCHEMA = 1;
|
|
8
|
+
const RESTORE_SCHEMA = 1;
|
|
9
|
+
const MAX_RESTORE_TABS = 256;
|
|
10
|
+
const MAX_RESTORE_BYTES = 2 * 1024 * 1024;
|
|
11
|
+
|
|
12
|
+
function inside(root, candidate) {
|
|
13
|
+
const relative = path.relative(path.resolve(root), path.resolve(candidate));
|
|
14
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function managedRuntimePaths(agentDir) {
|
|
18
|
+
const root = updateStatePaths(agentDir).root;
|
|
19
|
+
return Object.freeze({
|
|
20
|
+
root,
|
|
21
|
+
runtimesDir: path.join(root, "runtimes"),
|
|
22
|
+
tempDir: path.join(root, "tmp"),
|
|
23
|
+
currentPointer: path.join(root, "current.json"),
|
|
24
|
+
previousPointer: path.join(root, "previous.json"),
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function privateJson(file, value) {
|
|
29
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
30
|
+
const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
|
|
31
|
+
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
|
|
32
|
+
await chmod(temporary, 0o600).catch(() => undefined);
|
|
33
|
+
try { await rename(temporary, file); } finally { await rm(temporary, { force: true }).catch(() => undefined); }
|
|
34
|
+
await chmod(file, 0o600).catch(() => undefined);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function readRuntimePointer(agentDir, name = "current") {
|
|
38
|
+
if (!new Set(["current", "previous"]).has(name)) throw new TypeError("pointer name must be current or previous");
|
|
39
|
+
const paths = managedRuntimePaths(agentDir);
|
|
40
|
+
const file = name === "current" ? paths.currentPointer : paths.previousPointer;
|
|
41
|
+
let pointer;
|
|
42
|
+
try { pointer = JSON.parse(await readFile(file, "utf8")); } catch (error) {
|
|
43
|
+
if (error?.code === "ENOENT") return null;
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
const runtimeRoot = typeof pointer?.runtimeRoot === "string" ? path.resolve(pointer.runtimeRoot) : "";
|
|
47
|
+
const serverEntry = typeof pointer?.serverEntry === "string" ? path.resolve(pointer.serverEntry) : "";
|
|
48
|
+
if (pointer?.schemaVersion !== POINTER_SCHEMA || !runtimeRoot || !serverEntry || !inside(paths.runtimesDir, runtimeRoot) || !inside(runtimeRoot, serverEntry)) return null;
|
|
49
|
+
try {
|
|
50
|
+
if (!(await stat(runtimeRoot)).isDirectory() || !(await stat(serverEntry)).isFile()) return null;
|
|
51
|
+
const [canonicalRuntimesDir, canonicalRuntimeRoot, canonicalServerEntry] = await Promise.all([
|
|
52
|
+
realpath(paths.runtimesDir),
|
|
53
|
+
realpath(runtimeRoot),
|
|
54
|
+
realpath(serverEntry),
|
|
55
|
+
]);
|
|
56
|
+
if (!inside(canonicalRuntimesDir, canonicalRuntimeRoot) || !inside(canonicalRuntimeRoot, canonicalServerEntry)) return null;
|
|
57
|
+
return Object.freeze({ ...pointer, runtimeRoot: canonicalRuntimeRoot, serverEntry: canonicalServerEntry });
|
|
58
|
+
} catch { return null; }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function writeRuntimePointer(agentDir, name, pointer) {
|
|
62
|
+
if (!new Set(["current", "previous"]).has(name)) throw new TypeError("pointer name must be current or previous");
|
|
63
|
+
const paths = managedRuntimePaths(agentDir);
|
|
64
|
+
const runtimeRoot = path.resolve(String(pointer?.runtimeRoot || ""));
|
|
65
|
+
const serverEntry = path.resolve(String(pointer?.serverEntry || ""));
|
|
66
|
+
if (!inside(paths.runtimesDir, runtimeRoot) || !inside(runtimeRoot, serverEntry)) throw Object.assign(new Error("Managed runtime pointer escapes the private runtime root."), { code: "UPDATE_POINTER_ESCAPE" });
|
|
67
|
+
let canonicalRuntimesDir;
|
|
68
|
+
let canonicalRuntimeRoot;
|
|
69
|
+
let canonicalServerEntry;
|
|
70
|
+
try {
|
|
71
|
+
[canonicalRuntimesDir, canonicalRuntimeRoot, canonicalServerEntry] = await Promise.all([
|
|
72
|
+
realpath(paths.runtimesDir),
|
|
73
|
+
realpath(runtimeRoot),
|
|
74
|
+
realpath(serverEntry),
|
|
75
|
+
]);
|
|
76
|
+
} catch {
|
|
77
|
+
throw Object.assign(new Error("Managed runtime pointer target is incomplete."), { code: "UPDATE_POINTER_INCOMPLETE" });
|
|
78
|
+
}
|
|
79
|
+
if (!inside(canonicalRuntimesDir, canonicalRuntimeRoot) || !inside(canonicalRuntimeRoot, canonicalServerEntry)) {
|
|
80
|
+
throw Object.assign(new Error("Managed runtime pointer resolves outside the private runtime root."), { code: "UPDATE_POINTER_ESCAPE" });
|
|
81
|
+
}
|
|
82
|
+
const record = { schemaVersion: POINTER_SCHEMA, runtimeRoot: canonicalRuntimeRoot, serverEntry: canonicalServerEntry, version: String(pointer.version || ""), activatedAt: pointer.activatedAt || new Date().toISOString() };
|
|
83
|
+
await privateJson(name === "current" ? paths.currentPointer : paths.previousPointer, record);
|
|
84
|
+
return Object.freeze(record);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function switchRuntimePointer(agentDir, candidate) {
|
|
88
|
+
const current = await readRuntimePointer(agentDir, "current");
|
|
89
|
+
if (current) await writeRuntimePointer(agentDir, "previous", current);
|
|
90
|
+
const next = await writeRuntimePointer(agentDir, "current", candidate);
|
|
91
|
+
return Object.freeze({ current: next, previous: current });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function rollbackRuntimePointer(agentDir) {
|
|
95
|
+
const paths = managedRuntimePaths(agentDir);
|
|
96
|
+
const previous = await readRuntimePointer(agentDir, "previous");
|
|
97
|
+
const current = await readRuntimePointer(agentDir, "current");
|
|
98
|
+
if (!previous) {
|
|
99
|
+
await rm(paths.currentPointer, { force: true });
|
|
100
|
+
if (current) await writeRuntimePointer(agentDir, "previous", current);
|
|
101
|
+
return Object.freeze({ current: null, previous: current, bootstrapFallback: true });
|
|
102
|
+
}
|
|
103
|
+
await writeRuntimePointer(agentDir, "current", previous);
|
|
104
|
+
if (current) await writeRuntimePointer(agentDir, "previous", current);
|
|
105
|
+
return Object.freeze({ current: previous, previous: current, bootstrapFallback: false });
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function normalizeRestoreTab(item, seen) {
|
|
109
|
+
if (!item || typeof item !== "object") return null;
|
|
110
|
+
const text = (value, max) => typeof value === "string" && value.trim() ? value.trim().slice(0, max) : undefined;
|
|
111
|
+
const rawId = text(item.id, 128);
|
|
112
|
+
const id = rawId && /^[A-Za-z0-9._:-]+$/.test(rawId) && !seen.has(rawId) ? rawId : undefined;
|
|
113
|
+
if (id) seen.add(id);
|
|
114
|
+
const tab = { id, title: text(item.title, 160), titleSource: text(item.titleSource, 32), cwd: text(item.cwd, 4096), sessionFile: text(item.sessionFile, 4096), conversationStarted: item.conversationStarted === true };
|
|
115
|
+
if (Number.isInteger(item.index) && item.index > 0) tab.index = item.index;
|
|
116
|
+
return tab;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export async function createRestoreFile(agentDir, tabs, { now = () => new Date() } = {}) {
|
|
120
|
+
const paths = managedRuntimePaths(agentDir);
|
|
121
|
+
const seen = new Set();
|
|
122
|
+
const normalized = (Array.isArray(tabs) ? tabs : []).map((item) => normalizeRestoreTab(item, seen)).filter(Boolean).slice(0, MAX_RESTORE_TABS);
|
|
123
|
+
const payload = { schemaVersion: RESTORE_SCHEMA, createdAt: now().toISOString(), tabs: normalized };
|
|
124
|
+
const encoded = `${JSON.stringify(payload)}\n`;
|
|
125
|
+
if (Buffer.byteLength(encoded) > MAX_RESTORE_BYTES) throw Object.assign(new Error("Restore descriptor file exceeds the private handoff limit."), { code: "RESTORE_FILE_TOO_LARGE" });
|
|
126
|
+
await mkdir(paths.tempDir, { recursive: true, mode: 0o700 });
|
|
127
|
+
const file = path.join(paths.tempDir, `restore-${randomUUID()}.json`);
|
|
128
|
+
const handle = await open(file, "wx", 0o600);
|
|
129
|
+
try { await handle.writeFile(encoded, "utf8"); await handle.sync(); } finally { await handle.close(); }
|
|
130
|
+
return Object.freeze({ file, count: normalized.length });
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function readRestoreFileOnce(file, agentDir) {
|
|
134
|
+
if (!file) return [];
|
|
135
|
+
const paths = managedRuntimePaths(agentDir);
|
|
136
|
+
const resolved = path.resolve(file);
|
|
137
|
+
if (!inside(paths.tempDir, resolved)) throw Object.assign(new Error("Restore descriptor path is outside the private temp root."), { code: "RESTORE_FILE_ESCAPE" });
|
|
138
|
+
let raw;
|
|
139
|
+
try {
|
|
140
|
+
const info = await stat(resolved);
|
|
141
|
+
if (!info.isFile() || info.size > MAX_RESTORE_BYTES) throw new Error("Restore descriptor is not a bounded file.");
|
|
142
|
+
raw = await readFile(resolved, "utf8");
|
|
143
|
+
} finally {
|
|
144
|
+
await rm(resolved, { force: true }).catch(() => undefined);
|
|
145
|
+
}
|
|
146
|
+
const parsed = JSON.parse(raw);
|
|
147
|
+
if (parsed?.schemaVersion !== RESTORE_SCHEMA || !Array.isArray(parsed.tabs) || parsed.tabs.length > MAX_RESTORE_TABS) throw new Error("Restore descriptor schema is invalid.");
|
|
148
|
+
const seen = new Set();
|
|
149
|
+
return parsed.tabs.map((item) => normalizeRestoreTab(item, seen)).filter(Boolean);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export async function sweepRestoreFiles(agentDir, { olderThanMs = 24 * 60 * 60_000, now = Date.now() } = {}) {
|
|
153
|
+
const { tempDir } = managedRuntimePaths(agentDir);
|
|
154
|
+
let entries = [];
|
|
155
|
+
try { entries = await readdir(tempDir); } catch (error) { if (error?.code === "ENOENT") return 0; throw error; }
|
|
156
|
+
let removed = 0;
|
|
157
|
+
for (const name of entries.filter((entry) => /^restore-[a-f0-9-]+\.json$/i.test(entry))) {
|
|
158
|
+
const file = path.join(tempDir, name);
|
|
159
|
+
try { if (now - (await stat(file)).mtimeMs > olderThanMs) { await rm(file, { force: true }); removed += 1; } } catch {}
|
|
160
|
+
}
|
|
161
|
+
return removed;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export async function listenWithRetry(server, { port, host, attempts = 40, initialDelayMs = 250 } = {}) {
|
|
165
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
166
|
+
try {
|
|
167
|
+
await new Promise((resolve, reject) => {
|
|
168
|
+
const onError = (error) => { server.off("listening", onListening); reject(error); };
|
|
169
|
+
const onListening = () => { server.off("error", onError); resolve(); };
|
|
170
|
+
server.once("error", onError); server.once("listening", onListening); server.listen(port, host);
|
|
171
|
+
});
|
|
172
|
+
return attempt + 1;
|
|
173
|
+
} catch (error) {
|
|
174
|
+
if (error?.code !== "EADDRINUSE" || attempt === attempts - 1) throw error;
|
|
175
|
+
await new Promise((resolve) => setTimeout(resolve, initialDelayMs));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
throw new Error("Listener retry exhausted.");
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export async function probeCandidateRuntime(serverEntry, { expectedVersion, expectedPiVersion, timeoutMs = 20_000, spawnImpl = spawn } = {}) {
|
|
182
|
+
return new Promise((resolve) => {
|
|
183
|
+
const child = spawnImpl(process.execPath, [serverEntry, "--candidate-probe"], { stdio: ["ignore", "pipe", "pipe"], windowsHide: true, env: { ...process.env, PI_WEBUI_CANDIDATE_PROBE: "1" } });
|
|
184
|
+
let stdout = "", stderr = "", settled = false;
|
|
185
|
+
const finish = (result) => { if (settled) return; settled = true; clearTimeout(timer); resolve(Object.freeze(result)); };
|
|
186
|
+
child.stdout?.on("data", (chunk) => { stdout = (stdout + chunk).slice(-16_000); });
|
|
187
|
+
child.stderr?.on("data", (chunk) => { stderr = (stderr + chunk).slice(-16_000); });
|
|
188
|
+
child.once("error", (error) => finish({ ok: false, error: String(error.message || error), stdout, stderr }));
|
|
189
|
+
child.once("close", (code) => {
|
|
190
|
+
let data = null;
|
|
191
|
+
try { data = JSON.parse(stdout.trim().split(/\r?\n/).at(-1)); } catch {}
|
|
192
|
+
const ok = code === 0
|
|
193
|
+
&& data?.ok === true
|
|
194
|
+
&& (!expectedVersion || data.version === expectedVersion)
|
|
195
|
+
&& (!expectedPiVersion || data.piVersion === expectedPiVersion);
|
|
196
|
+
finish({ ok, code, data, stdout, stderr, error: ok ? "" : "Candidate probe did not verify the expected Web UI runtime." });
|
|
197
|
+
});
|
|
198
|
+
const timer = setTimeout(() => { try { child.kill("SIGKILL"); } catch {} finish({ ok: false, timedOut: true, stdout, stderr, error: "Candidate probe timed out." }); }, timeoutMs);
|
|
199
|
+
timer.unref?.();
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export async function collectManagedRuntimes(agentDir, { protectedRoots = [], keepHealthyForMs = 7 * 24 * 60 * 60_000, now = Date.now() } = {}) {
|
|
204
|
+
const paths = managedRuntimePaths(agentDir);
|
|
205
|
+
const statePaths = updateStatePaths(agentDir);
|
|
206
|
+
const current = await readRuntimePointer(agentDir, "current");
|
|
207
|
+
const previous = await readRuntimePointer(agentDir, "previous");
|
|
208
|
+
const protectedSet = new Set([current?.runtimeRoot, previous?.runtimeRoot, ...protectedRoots].filter(Boolean).map((item) => path.resolve(item)));
|
|
209
|
+
try {
|
|
210
|
+
for (const name of await readdir(statePaths.updatesDir)) {
|
|
211
|
+
if (!name.endsWith(".json")) continue;
|
|
212
|
+
try {
|
|
213
|
+
const journal = JSON.parse(await readFile(path.join(statePaths.updatesDir, name), "utf8"));
|
|
214
|
+
for (const target of journal?.plan?.targets || []) {
|
|
215
|
+
const runtimeRoot = target?.metadata?.runtimeRoot;
|
|
216
|
+
if (runtimeRoot && inside(paths.runtimesDir, runtimeRoot)) protectedSet.add(path.resolve(runtimeRoot));
|
|
217
|
+
}
|
|
218
|
+
} catch {}
|
|
219
|
+
}
|
|
220
|
+
} catch (error) { if (error?.code !== "ENOENT") throw error; }
|
|
221
|
+
let entries = [];
|
|
222
|
+
try { entries = await readdir(paths.runtimesDir, { withFileTypes: true }); } catch (error) { if (error?.code === "ENOENT") return []; throw error; }
|
|
223
|
+
const removed = [];
|
|
224
|
+
for (const entry of entries) {
|
|
225
|
+
if (!entry.isDirectory()) continue;
|
|
226
|
+
const root = path.join(paths.runtimesDir, entry.name);
|
|
227
|
+
if (protectedSet.has(path.resolve(root))) continue;
|
|
228
|
+
try {
|
|
229
|
+
const info = await stat(root);
|
|
230
|
+
if (now - info.mtimeMs < keepHealthyForMs) continue;
|
|
231
|
+
await rm(root, { recursive: true, force: true });
|
|
232
|
+
removed.push(root);
|
|
233
|
+
} catch {}
|
|
234
|
+
}
|
|
235
|
+
return removed;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export const UPDATE_RESTORE_LIMIT = MAX_RESTORE_TABS;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
function version(value) {
|
|
2
|
+
return String(value ?? "").trim().replace(/^v/i, "");
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
function receipt(target, status, detail = {}) {
|
|
6
|
+
return Object.freeze({
|
|
7
|
+
targetId: String(target?.id || detail.targetId || ""),
|
|
8
|
+
kind: String(target?.kind || detail.kind || "package"),
|
|
9
|
+
status,
|
|
10
|
+
beforeVersion: version(detail.beforeVersion ?? target?.currentVersion),
|
|
11
|
+
expectedVersion: version(detail.expectedVersion ?? target?.targetVersion),
|
|
12
|
+
afterVersion: version(detail.afterVersion),
|
|
13
|
+
message: String(detail.message || ""),
|
|
14
|
+
command: detail.command || null,
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Exit zero is insufficient: identity, exact promised version, and a change are mandatory. */
|
|
19
|
+
export function verifyTargetResult(target, { beforeIdentity, afterIdentity, beforeVersion, afterVersion, command } = {}) {
|
|
20
|
+
const before = version(beforeVersion ?? target?.currentVersion);
|
|
21
|
+
const after = version(afterVersion);
|
|
22
|
+
const expected = version(target?.targetVersion);
|
|
23
|
+
if (beforeIdentity?.canonicalId && afterIdentity?.canonicalId && beforeIdentity.canonicalId !== afterIdentity.canonicalId) {
|
|
24
|
+
return receipt(target, "failed", { beforeVersion: before, afterVersion: after, command, message: "Runtime identity changed during verification." });
|
|
25
|
+
}
|
|
26
|
+
if (!after) return receipt(target, "failed", { beforeVersion: before, afterVersion: after, command, message: "The updated version could not be read." });
|
|
27
|
+
if (after === before) return receipt(target, "failed", { beforeVersion: before, afterVersion: after, command, message: "The command completed without changing the installed version." });
|
|
28
|
+
if (!expected || after !== expected) {
|
|
29
|
+
return receipt(target, "failed", { beforeVersion: before, afterVersion: after, command, message: `Expected exact version ${expected || "unknown"}, found ${after}.` });
|
|
30
|
+
}
|
|
31
|
+
return receipt(target, "success", { beforeVersion: before, afterVersion: after, command, message: `Verified ${after}.` });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function failedTargetReceipt(target, message, detail = {}) {
|
|
35
|
+
return receipt(target, "failed", { ...detail, message });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function rolledBackTargetReceipt(target, message, detail = {}) {
|
|
39
|
+
return receipt(target, "rolled-back", { ...detail, message });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function reduceUpdateReceipts(receipts = []) {
|
|
43
|
+
const ordered = Object.freeze(receipts.map((item) => Object.freeze({ ...item })));
|
|
44
|
+
const successes = ordered.filter((item) => item.status === "success").length;
|
|
45
|
+
const rolledBack = ordered.filter((item) => item.status === "rolled-back").length;
|
|
46
|
+
const failures = ordered.length - successes - rolledBack;
|
|
47
|
+
let outcome = "failed";
|
|
48
|
+
if (ordered.length > 0 && successes === ordered.length) outcome = "success";
|
|
49
|
+
else if (successes > 0) outcome = "partial";
|
|
50
|
+
else if (rolledBack > 0 && failures === 0) outcome = "rolled-back";
|
|
51
|
+
return Object.freeze({ outcome, receipts: ordered, counts: Object.freeze({ success: successes, failed: failures, rolledBack }) });
|
|
52
|
+
}
|