@firstpick/pi-package-webui 0.10.7 → 0.10.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/DEVELOPMENT.md +95 -15
  2. package/README.md +1 -1
  3. package/TECHNICAL.md +6 -4
  4. package/bin/pi-webui-launcher.mjs +6 -3
  5. package/bin/pi-webui-native-update-guardian.mjs +37 -0
  6. package/bin/pi-webui-native-update-runner.mjs +148 -0
  7. package/bin/pi-webui-rpc-supervisor.mjs +85 -10
  8. package/bin/pi-webui-update-context.mjs +83 -0
  9. package/bin/pi-webui.mjs +537 -339
  10. package/lib/component-update-state.mjs +4 -4
  11. package/lib/rpc-supervisor-client.mjs +4 -0
  12. package/lib/rpc-supervisor-protocol.mjs +17 -4
  13. package/lib/update/coordination.mjs +207 -0
  14. package/lib/update/discovery.mjs +58 -0
  15. package/lib/update/migration.mjs +115 -0
  16. package/lib/update/native-jobs.mjs +215 -0
  17. package/lib/update/native-targets.mjs +81 -0
  18. package/lib/update/path-pi.mjs +76 -0
  19. package/lib/update/supervisor.mjs +50 -29
  20. package/lib/update/verification.mjs +18 -0
  21. package/lib/update-commands.mjs +17 -27
  22. package/package.json +2 -2
  23. package/public/app.js +170 -201
  24. package/public/index.html +5 -3
  25. package/public/styles.css +29 -1
  26. package/tests/browser/control-deck-component-updates.spec.mjs +90 -141
  27. package/tests/browser/update-reconnect.spec.mjs +37 -1
  28. package/tests/component-update-api-static.test.mjs +13 -11
  29. package/tests/control-deck-component-updates-static.test.mjs +25 -25
  30. package/tests/cwd-footer-reliability-static.test.mjs +4 -1
  31. package/tests/http-endpoints-harness.test.mjs +32 -9
  32. package/tests/mobile-static.test.mjs +9 -6
  33. package/tests/native-update-discovery.test.mjs +69 -0
  34. package/tests/native-update-lifecycle.test.mjs +92 -0
  35. package/tests/native-update-shell-survival.test.mjs +68 -0
  36. package/tests/native-update-verification.test.mjs +17 -0
  37. package/tests/rpc-supervisor-host.test.mjs +63 -1
  38. package/tests/rpc-supervisor-protocol.test.mjs +8 -0
  39. package/tests/run-all.mjs +6 -2
  40. package/tests/update-api-harness.test.mjs +57 -50
  41. package/tests/update-commands.test.mjs +29 -15
  42. package/tests/update-executor-process-tree-harness.test.mjs +84 -1
  43. package/tests/update-journal-harness.test.mjs +9 -1
  44. package/tests/update-lock-multiprocess-harness.test.mjs +60 -1
  45. package/tests/update-owners.test.mjs +32 -0
  46. package/tests/update-plan.test.mjs +110 -0
  47. package/tests/update-resolver.test.mjs +36 -0
  48. package/tests/update-supervisor-harness.test.mjs +74 -1
  49. package/tests/update-tab-restore-harness.test.mjs +9 -2
  50. package/bin/pi-webui-update-supervisor.mjs +0 -86
@@ -1,5 +1,8 @@
1
1
  import assert from "node:assert/strict";
2
- import { access, mkdtemp, rm } from "node:fs/promises";
2
+ import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { createHash } from "node:crypto";
4
+ import { runUpdateJob } from "../bin/pi-webui-native-update-runner.mjs";
5
+ import { frozenUpdateEnvironment, readUpdateContext } from "../bin/pi-webui-update-context.mjs";
3
6
  import { tmpdir } from "node:os";
4
7
  import path from "node:path";
5
8
  import { setTimeout as delay } from "node:timers/promises";
@@ -16,6 +19,86 @@ try {
16
19
  assert.deepEqual(result.args, [fixture, sentinel], "executor preserves argument arrays");
17
20
  await delay(1_100);
18
21
  await assert.rejects(access(sentinel), { code: "ENOENT" }, "a timed-out descendant must not survive to write its delayed sentinel");
22
+ const manifestPath = path.join(root, "installed.json");
23
+ const driver = path.join(root, "stub-update.mjs");
24
+ await writeFile(manifestPath, JSON.stringify({ name: "fixture-package", version: "1.0.0" }));
25
+ await writeFile(driver, `import {writeFileSync} from "node:fs"; writeFileSync(${JSON.stringify(manifestPath)}, JSON.stringify({name:"fixture-package",version:"1.1.0"})); console.log(process.env.PI_TEST_SECRET_TOKEN || "fixture only");`);
26
+ const oldSecret = process.env.PI_TEST_SECRET_TOKEN;
27
+ process.env.PI_TEST_SECRET_TOKEN = "fixture-secret-value-not-for-disk";
28
+ const digest = createHash("sha256").update(await readFile(driver)).digest("hex");
29
+ const bindings = await readUpdateContext({ env: process.env });
30
+ await writeFile(path.join(root, "intent.json"), JSON.stringify({
31
+ transactionId: "stub-job", cwd: root, ...bindings, npmConfigFiles: [],
32
+ nodeDigest: createHash("sha256").update(await readFile(process.execPath)).digest("hex"),
33
+ targets: [{ id: "fixture", packageName: "fixture-package", beforeVersion: "1.0.0", manifestPath,
34
+ driver, driverDigest: digest, command: { command: process.execPath, args: [driver] } }],
35
+ }));
36
+ assert.equal((await readFile(path.join(root, "intent.json"), "utf8")).includes('"env"'), false, "secret-bearing environment is never stored in a job intent");
37
+ const receipts = await runUpdateJob(root);
38
+ assert.equal(receipts[0].stdout.trim(), "[redacted]", "a secret emitted by a native command must not enter a receipt");
39
+ assert.equal((await readFile(path.join(root, "intent.json"), "utf8")).includes(process.env.PI_TEST_SECRET_TOKEN), false);
40
+ assert.equal(receipts[0].status, "changed", "a changed manifest is not yet a healthy restart approval");
41
+ assert.equal((await readFile(path.join(root, "complete.json"), "utf8")).includes("changed"), true);
42
+ await assert.rejects(runUpdateJob(root), /replay is prohibited/);
43
+ const secondJob = path.join(root, "second");
44
+ await mkdir(secondJob);
45
+ await writeFile(path.join(secondJob, "intent.json"), (await readFile(path.join(root, "intent.json"), "utf8")).replace("stub-job", "stub-job-2"));
46
+ await writeFile(manifestPath, JSON.stringify({ name: "fixture-package", version: "1.0.0" }));
47
+ await writeFile(driver, "throw new Error('changed driver')");
48
+ const changed = await runUpdateJob(secondJob);
49
+ assert.match(changed[0].error, /driver changed/);
50
+ assert.equal(changed[0].status, "failed");
51
+ const npmrc = path.join(root, "user.npmrc");
52
+ await writeFile(npmrc, "registry=https://registry.example.invalid/\n//registry.example.invalid/:_authToken=fixture-npm-secret\n");
53
+ const frozen = frozenUpdateEnvironment({ ...process.env, BASH_ENV: path.join(root, "startup.sh") }, root);
54
+ assert.equal(frozen.BASH_ENV, undefined, "Bash startup must not rebind the confirmed commands");
55
+ const config = await readUpdateContext({ env: frozen, npmConfigFiles: [npmrc] });
56
+ assert.equal(JSON.stringify(config).includes("fixture-npm-secret"), false, "the npm routing digest must not store credentials");
57
+ await writeFile(npmrc, "registry=https://other-registry.example.invalid/\n//registry.example.invalid/:_authToken=fixture-npm-secret\n");
58
+ const drift = await readUpdateContext({ env: frozen, npmConfigFiles: [npmrc] });
59
+ assert.notEqual(config.npmConfigDigest, drift.npmConfigDigest, "routing drift must invalidate confirmation");
60
+ await writeFile(npmrc, "@firstpick:registry=https://scoped-a.example.invalid/\n");
61
+ const scopedA = await readUpdateContext({ env: frozen, npmConfigFiles: [npmrc] });
62
+ await writeFile(npmrc, "@firstpick:registry=https://scoped-b.example.invalid/\n");
63
+ const scopedB = await readUpdateContext({ env: frozen, npmConfigFiles: [npmrc] });
64
+ assert.notEqual(scopedA.npmConfigDigest, scopedB.npmConfigDigest, "scoped registry routing drift must invalidate confirmation");
65
+ const redirected = path.join(root, "redirected-global.npmrc");
66
+ await writeFile(redirected, "@firstpick:registry=https://redirected.example.invalid/\n");
67
+ const redirectedContext = await readUpdateContext({ env: frozen, npmConfigFiles: [npmrc, redirected] });
68
+ await writeFile(redirected, "@firstpick:registry=https://changed.example.invalid/\n");
69
+ assert.notEqual(redirectedContext.npmConfigDigest, (await readUpdateContext({ env: frozen, npmConfigFiles: [npmrc, redirected] })).npmConfigDigest);
70
+ const configJob = path.join(root, "config-drift-job");
71
+ await mkdir(configJob);
72
+ await writeFile(manifestPath, JSON.stringify({ name: "fixture-package", version: "1.0.0" }));
73
+ const originalIntent = JSON.parse(await readFile(path.join(root, "intent.json"), "utf8"));
74
+ await writeFile(path.join(configJob, "intent.json"), JSON.stringify({ ...originalIntent, transactionId: "config-drift-job",
75
+ npmConfigFiles: [npmrc], npmConfigDigest: config.npmConfigDigest }));
76
+ const blocked = await runUpdateJob(configJob);
77
+ assert.equal(blocked[0].status, "failed");
78
+ assert.match(blocked[0].error, /configuration changed/);
79
+ assert.equal(JSON.parse(await readFile(manifestPath, "utf8")).version, "1.0.0", "drift must stop mutation");
80
+ const partialJob = path.join(root, "partial-job");
81
+ await mkdir(partialJob);
82
+ const secondManifest = path.join(root, "independent.json");
83
+ const failedDriver = path.join(root, "failed-driver.mjs");
84
+ const workingDriver = path.join(root, "working-driver.mjs");
85
+ await writeFile(failedDriver, "process.exitCode = 17;\n");
86
+ await writeFile(workingDriver, `import {writeFileSync} from "node:fs"; writeFileSync(${JSON.stringify(secondManifest)}, JSON.stringify({name:"independent-package",version:"1.1.0"}));`);
87
+ await writeFile(secondManifest, JSON.stringify({ name: "independent-package", version: "1.0.0" }));
88
+ const partialIntent = { ...originalIntent, transactionId: "partial-job", targets: [
89
+ { id: "first", packageName: "fixture-package", beforeVersion: "1.0.0", manifestPath,
90
+ driver: failedDriver, driverDigest: createHash("sha256").update(await readFile(failedDriver)).digest("hex"),
91
+ command: { command: process.execPath, args: [failedDriver] } },
92
+ { id: "second", packageName: "independent-package", beforeVersion: "1.0.0", manifestPath: secondManifest,
93
+ driver: workingDriver, driverDigest: createHash("sha256").update(await readFile(workingDriver)).digest("hex"),
94
+ command: { command: process.execPath, args: [workingDriver] } },
95
+ ] };
96
+ await writeFile(path.join(partialJob, "intent.json"), JSON.stringify(partialIntent));
97
+ const partial = await runUpdateJob(partialJob);
98
+ assert.deepEqual(partial.map(({ status }) => status), ["failed", "changed"], "a failed native command must not suppress an independent proven target");
99
+ assert.equal(JSON.parse(await readFile(path.join(partialJob, "complete.json"), "utf8")).receipts.length, 2);
100
+ if (oldSecret === undefined) delete process.env.PI_TEST_SECRET_TOKEN;
101
+ else process.env.PI_TEST_SECRET_TOKEN = oldSecret;
19
102
  console.log("update-executor-process-tree-harness.test.mjs passed");
20
103
  } finally {
21
104
  await rm(root, { recursive: true, force: true });
@@ -1,6 +1,8 @@
1
1
  import assert from "node:assert/strict";
2
- import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
2
+ import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
+ import { inspectNativeJob } from "../lib/update/native-jobs.mjs";
5
+ import { persistSharedJob } from "../lib/update/coordination.mjs";
4
6
  import path from "node:path";
5
7
  import {
6
8
  acquireInstallLock, createUpdateJournal, readUpdateJournal, reconcileInterruptedUpdates,
@@ -53,6 +55,12 @@ try {
53
55
  assert.equal(reconciled[0].reconciled, true);
54
56
  assert.match(reconciled[0].error, /Recovered tx-interrupted/);
55
57
  assert.doesNotMatch(await readFile(path.join(paths.updatesDir, "tx-interrupted.json"), "utf8"), /\.tmp/);
58
+ const privateJobDir = path.join(agentDir, "private-job");
59
+ await mkdir(privateJobDir);
60
+ await persistSharedJob(agentDir, { transactionId: "lost-receipt", phase: "running", jobDir: privateJobDir,
61
+ plan: { targets: [{ id: "pi" }] }, launchedAt: new Date(Date.now() - 30_000).toISOString() });
62
+ const interrupted = await inspectNativeJob(agentDir, "lost-receipt");
63
+ assert.equal(interrupted.phase, "unknown", "lost runner/receipt evidence must never become completion or unlock exclusion");
56
64
  console.log("update-journal-harness.test.mjs passed");
57
65
  } finally {
58
66
  await rm(agentDir, { recursive: true, force: true });
@@ -1,6 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
+ import { acquireEffectLocks, acknowledgeUpdateFence, affectedParticipants, assertEffectAdmission, createUpdateAdmissionCounter, releaseEffectLocks, registerUpdateParticipant, sharedUpdateRoot, unregisterUpdateParticipant } from "../lib/update/coordination.mjs";
2
3
  import { spawn } from "node:child_process";
3
- import { mkdtemp, rm } from "node:fs/promises";
4
+ import { mkdir, mkdtemp, rm } from "node:fs/promises";
4
5
  import { tmpdir } from "node:os";
5
6
  import path from "node:path";
6
7
  import { fileURLToPath } from "node:url";
@@ -40,6 +41,64 @@ try {
40
41
  assert.equal(first.code, 0, first.output);
41
42
  assert.equal(second.code, 2, second.output);
42
43
  assert.match(second.output, /UPDATE_LOCKED/);
44
+
45
+ const stateRoot = await sharedUpdateRoot({ home: root });
46
+ const effect = path.join(root, "global", "node_modules");
47
+ await mkdir(effect, { recursive: true });
48
+ const server = await registerUpdateParticipant(stateRoot, { kind: "server", roots: [effect] });
49
+ const supervisor = await registerUpdateParticipant(stateRoot, { kind: "rpc-supervisor", roots: [effect] });
50
+ const admitted = createUpdateAdmissionCounter();
51
+ const finishUnpublishedTab = admitted.begin();
52
+ const job = await acquireEffectLocks(stateRoot, [effect, effect], "one");
53
+ assert.equal((await affectedParticipants(stateRoot, job)).length, 2);
54
+ await acknowledgeUpdateFence(server, job, admitted.idle);
55
+ assert.equal((await affectedParticipants(stateRoot, job)).find((owner) => owner.token === server.token).ack.idle, false,
56
+ "a lock cannot admit the update while an admitted tab is still unpublished");
57
+ await assert.rejects(assertEffectAdmission(stateRoot, [effect]), { code: "UPDATE_FENCED" },
58
+ "the tab must recheck the fence before publishing its Pi child");
59
+ finishUnpublishedTab();
60
+ await acknowledgeUpdateFence(server, job, admitted.idle);
61
+ await acknowledgeUpdateFence(supervisor, job, false);
62
+ assert.equal((await affectedParticipants(stateRoot, job)).every((owner) => owner.ack.idle), false);
63
+ assert.equal(job.files.length, 1, "aliased declarations must not duplicate physical mutation");
64
+ await assert.rejects(acquireEffectLocks(stateRoot, [effect], "two"), { code: "UPDATE_FENCED" });
65
+ await assert.rejects(assertEffectAdmission(stateRoot, [effect]), { code: "UPDATE_FENCED" });
66
+ await assert.rejects(releaseEffectLocks(job), /completion/);
67
+ await releaseEffectLocks(job, { completionVerified: true });
68
+ await assertEffectAdmission(stateRoot, [effect]);
69
+ const nested = path.join(effect, "@firstpick", "pi-package-webui");
70
+ await mkdir(nested, { recursive: true });
71
+ const descendant = await registerUpdateParticipant(stateRoot, { kind: "server", roots: [nested] });
72
+ const parentLock = await acquireEffectLocks(stateRoot, [effect], "parent");
73
+ assert.equal((await affectedParticipants(stateRoot, parentLock)).length, 3, "nested consumers must acknowledge their ancestor effect");
74
+ await assert.rejects(assertEffectAdmission(stateRoot, [nested]), { code: "UPDATE_FENCED" });
75
+ await assert.rejects(acquireEffectLocks(stateRoot, [nested], "child"), { code: "UPDATE_FENCED" });
76
+ await releaseEffectLocks(parentLock, { completionVerified: true });
77
+ const childLock = await acquireEffectLocks(stateRoot, [nested], "child");
78
+ await assert.rejects(assertEffectAdmission(stateRoot, [effect]), { code: "UPDATE_FENCED" });
79
+ await assert.rejects(acquireEffectLocks(stateRoot, [effect], "parent-again"), { code: "UPDATE_FENCED" });
80
+ await releaseEffectLocks(childLock, { completionVerified: true });
81
+ const activePi = path.join(root, "explicit-active-pi");
82
+ const pathPi = path.join(root, "separate-path-pi");
83
+ await Promise.all([mkdir(activePi), mkdir(pathPi)]);
84
+ const explicitOwner = await registerUpdateParticipant(stateRoot, { kind: "server", roots: [activePi, pathPi] });
85
+ const pathOwner = await registerUpdateParticipant(stateRoot, { kind: "server", roots: [pathPi] });
86
+ const releaseRestart = admitted.begin();
87
+ const explicitLock = await acquireEffectLocks(stateRoot, [activePi], "explicit-pi-update");
88
+ assert.deepEqual((await affectedParticipants(stateRoot, explicitLock)).map(({ token }) => token), [explicitOwner.token],
89
+ "a different PATH Pi cannot stand in for an explicitly active installation");
90
+ await acknowledgeUpdateFence(explicitOwner, explicitLock, admitted.idle);
91
+ assert.equal((await affectedParticipants(stateRoot, explicitLock))[0].ack.idle, false,
92
+ "restart lease acquired before handoff must block idle acknowledgment during its await");
93
+ await assert.rejects(assertEffectAdmission(stateRoot, [activePi]), { code: "UPDATE_FENCED" },
94
+ "ordinary restart must recheck admission before launching the successor");
95
+ releaseRestart();
96
+ await releaseEffectLocks(explicitLock, { completionVerified: true });
97
+ await unregisterUpdateParticipant(explicitOwner);
98
+ await unregisterUpdateParticipant(pathOwner);
99
+ await unregisterUpdateParticipant(descendant);
100
+ await unregisterUpdateParticipant(server);
101
+ await unregisterUpdateParticipant(supervisor);
43
102
  } finally {
44
103
  await rm(root, { recursive: true, force: true });
45
104
  }
@@ -1,5 +1,8 @@
1
1
  import assert from "node:assert/strict";
2
+ import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
2
4
  import path from "node:path";
5
+ import { npmGlobalWebuiTarget, piUserWebuiTarget, selfUpdateCommand, userWebuiNpmSource } from "../lib/update/native-targets.mjs";
3
6
  import { classifyPackageOwner, ownershipRefusalGuidance } from "../lib/update/owners.mjs";
4
7
 
5
8
  const ownerRoot = path.resolve("tmp", "agent", "npm", "node_modules");
@@ -24,4 +27,33 @@ assert.equal(classifyPackageOwner({ manager: "npm", ownerRoot, packageRoot, topL
24
27
  assert.equal(classifyPackageOwner({ manager: "npm", ownerRoot, packageRoot, optional: true, piOwned: false }).code, "optional");
25
28
  assert.equal(classifyPackageOwner({ manager: "npm", ownerRoot, packageRoot: path.resolve("tmp", "other") }).code, "opaque");
26
29
  assert.match(ownershipRefusalGuidance("source"), /never mutated automatically/i);
30
+ const testRoot = await mkdtemp(path.join(tmpdir(), "pi-webui-native-owners-"));
31
+ try {
32
+ const agentDir = path.join(testRoot, "agent");
33
+ const globalPrefix = path.join(testRoot, "global");
34
+ const packageParts = ["@firstpick", "pi-package-webui"];
35
+ const globalModules = path.join(globalPrefix, ...(process.platform === "win32" ? ["node_modules"] : ["lib", "node_modules"]));
36
+ const globalRoot = path.join(globalModules, ...packageParts);
37
+ const userRoot = path.join(agentDir, "npm", "node_modules", ...packageParts);
38
+ await mkdir(globalRoot, { recursive: true });
39
+ await mkdir(userRoot, { recursive: true });
40
+ const manifest = JSON.stringify({ name: "@firstpick/pi-package-webui", version: "0.10.6" });
41
+ await writeFile(path.join(globalRoot, "package.json"), manifest);
42
+ await writeFile(path.join(userRoot, "package.json"), manifest);
43
+ const npm = { command: path.join(testRoot, "node"), args: [path.join(testRoot, "npm-cli.js")] };
44
+ const global = await npmGlobalWebuiTarget({ nodeModulesRoot: globalModules, prefix: globalPrefix, npmInvocation: npm });
45
+ assert.equal(global.eligible, true);
46
+ assert.deepEqual(global.command.args.slice(-3), ["-g", "update", "@firstpick/pi-package-webui"]);
47
+ const pi = { eligible: true, invocation: { command: npm.command, args: [path.join(testRoot, "pi-cli.js")] }, packageRoot: testRoot, prefix: globalPrefix, version: "0.87.1" };
48
+ const selected = await piUserWebuiTarget({ agentDir, pathPi: pi, settings: { packages: ["npm:@firstpick/pi-package-webui@^0.10.0"] } });
49
+ assert.equal(selected.eligible, true);
50
+ assert.deepEqual(selected.command.args.slice(-4), ["update", "--extension", "npm:@firstpick/pi-package-webui@^0.10.0", "--no-approve"]);
51
+ assert.deepEqual(selfUpdateCommand(pi).command.args.slice(-1), ["update"]);
52
+ assert.equal(userWebuiNpmSource({ packages: ["npm:@firstpick/pi-package-webui@0.10.6"] }).eligible, false);
53
+ assert.equal(userWebuiNpmSource({ packages: ["git:example", "npm:@firstpick/pi-package-webui@next"] }).eligible, true);
54
+ assert.equal(userWebuiNpmSource({ packages: ["npm:@firstpick/pi-package-webui", "npm:@firstpick/pi-package-webui@next"] }).eligible, false);
55
+ await rm(globalRoot, { recursive: true });
56
+ await symlink(userRoot, globalRoot, process.platform === "win32" ? "junction" : "dir");
57
+ assert.equal((await npmGlobalWebuiTarget({ nodeModulesRoot: globalModules, prefix: globalPrefix, npmInvocation: npm })).eligible, false);
58
+ } finally { await rm(testRoot, { recursive: true, force: true }); }
27
59
  console.log("update-owners.test.mjs passed");
@@ -1,5 +1,14 @@
1
1
  import assert from "node:assert/strict";
2
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { EventEmitter } from "node:events";
4
+ import { createHash } from "node:crypto";
5
+ import { readUpdateContext } from "../bin/pi-webui-update-context.mjs";
6
+ import { tmpdir } from "node:os";
2
7
  import path from "node:path";
8
+ import { affectedActivePiDependency, createNativeUpdatePlan, inspectNativeJob, launchNativeUpdate, validateNativePlan } from "../lib/update/native-jobs.mjs";
9
+ import { discoverNativeJobs } from "../lib/update/discovery.mjs";
10
+ import { acknowledgeUpdateFence, effectLockForRoot, persistSharedJob, readSharedJob, registerUpdateParticipant,
11
+ releaseEffectLocks, sharedUpdateRoot, unregisterUpdateParticipant } from "../lib/update/coordination.mjs";
3
12
  import { assertActionableUpdatePlan, assertPlanIdentity, assertUpdatePlanDigest, createUpdatePlan, digestUpdatePlan } from "../lib/update/plan.mjs";
4
13
 
5
14
  const ownerRoot = path.resolve("tmp", "agent", "npm", "node_modules");
@@ -65,4 +74,105 @@ movingLatest = "3.0.0";
65
74
  assert.equal(plan.targets[0].targetVersion, "2.0.0", "confirmation remains bound to the originally resolved exact target");
66
75
  assert.throws(() => assertUpdatePlanDigest({ ...plan, targets: [{ ...plan.targets[0], targetVersion: movingLatest }] }, plan.digest), { code: "UPDATE_PLAN_DIGEST_MISMATCH" });
67
76
  assert.throws(() => assertPlanIdentity(plan.targets[0], { canonicalId: "pi:/different/cli.js" }), { code: "UPDATE_IDENTITY_CHANGED" });
77
+ const fixture = await mkdtemp(path.join(tmpdir(), "pi-webui-native-plan-"));
78
+ try {
79
+ const driver = path.join(fixture, "stub-cli.js");
80
+ await writeFile(driver, "// read-only stub driver; never invoke a real updater\n");
81
+ const confirmed = await readUpdateContext({ env: process.env });
82
+ const nodeDigest = createHash("sha256").update(await readFile(process.execPath)).digest("hex");
83
+ const native = await createNativeUpdatePlan({ requested: "pi", context: {
84
+ cwd: fixture, agentDir: fixture, shell: process.execPath, shellDigest: nodeDigest, nodeDigest,
85
+ settingsPath: path.join(fixture, "settings.json"), npmConfigFiles: [], ...confirmed,
86
+ },
87
+ targets: [{ eligible: true, id: "pi", driver, installed: { root: fixture, version: "0.87.1" }, effectRoot: fixture,
88
+ command: { command: process.execPath, args: [driver, "update"] } }], });
89
+ validateNativePlan(native, native.digest);
90
+ assert.deepEqual(native.targets[0].command.args.slice(-1), ["update"]);
91
+ await persistSharedJob(fixture, { transactionId: native.transactionId, plan: native, phase: "planned" });
92
+ assert.equal((await inspectNativeJob(fixture, native.transactionId)).phase, "planned");
93
+ assert.throws(() => validateNativePlan({ ...native, requested: "webui" }, native.digest), /changed/);
94
+ await assert.rejects(createNativeUpdatePlan({ requested: "webui", context: { cwd: fixture, agentDir: fixture }, targets: [{ eligible: true, id: "pi" }] }), /Combined/);
95
+
96
+ const globalEffect = path.join(fixture, "global");
97
+ const bundledRoot = path.join(globalEffect, "node_modules", "@earendil-works", "pi-coding-agent");
98
+ const webuiEffect = [{ id: "webui:npm-global", effectRoot: globalEffect, status: "unchanged" }];
99
+ assert.equal(affectedActivePiDependency({ active: { piRoot: bundledRoot } }, webuiEffect), webuiEffect[0],
100
+ "a WebUI command may change its hoisted active Pi dependency even with an unchanged WebUI version");
101
+ assert.equal(affectedActivePiDependency({ active: { piRoot: path.join(fixture, "separate-path-pi") } }, webuiEffect), null,
102
+ "distinct PATH Pi must not be reloaded after unrelated WebUI mutation");
103
+ assert.equal(affectedActivePiDependency({ active: { piRoot: path.join(fixture, "explicit-pi") } }, webuiEffect), null,
104
+ "distinct explicitly selected Pi must not be reloaded after unrelated WebUI mutation");
105
+ assert.equal(affectedActivePiDependency({ active: { piRoot: bundledRoot } }, [{ ...webuiEffect[0], status: "failed" }]), null,
106
+ "failed WebUI effects cannot authorize an active Pi reload");
107
+ const stateRoot = await sharedUpdateRoot({ home: fixture });
108
+ const effectRoot = path.join(fixture, "separate-installation");
109
+ await mkdir(effectRoot);
110
+ const participant = await registerUpdateParticipant(stateRoot, { kind: "server", roots: [effectRoot] });
111
+ const launchPlan = await createNativeUpdatePlan({ requested: "pi", context: { ...native.context,
112
+ cwd: stateRoot, shell: process.execPath, ownerPackageRoot: fixture },
113
+ targets: [{ eligible: true, id: "pi", driver, installed: { root: effectRoot, version: "0.87.1" }, effectRoot,
114
+ command: { command: process.execPath, args: [driver, "update"] } }], });
115
+ await persistSharedJob(stateRoot, { transactionId: launchPlan.transactionId, plan: launchPlan, phase: "planned" });
116
+ let spawned = null;
117
+ const mockSpawn = (shell, args, options) => {
118
+ spawned = { shell, args, options };
119
+ const child = new EventEmitter();
120
+ child.pid = 12345;
121
+ child.unref = () => {};
122
+ queueMicrotask(() => child.emit("spawn"));
123
+ return child;
124
+ };
125
+ const acknowledge = setInterval(async () => {
126
+ const lock = await effectLockForRoot(stateRoot, effectRoot);
127
+ if (lock) await acknowledgeUpdateFence(participant, { token: lock.token, effects: [effectRoot] }, true);
128
+ }, 20);
129
+ try {
130
+ const launched = await launchNativeUpdate(launchPlan, launchPlan.digest, { stateRoot, spawnImpl: mockSpawn,
131
+ env: { ...process.env, PI_FIXTURE_API_TOKEN: "private-secret-only-in-memory" },
132
+ requiredParticipants: [{ kind: "server", token: participant.token }] });
133
+ assert.equal(launched.phase, "running");
134
+ assert.equal(spawned.shell, process.execPath, "the confirmed executable must be used, not a PATH lookup");
135
+ assert.equal(spawned.options.detached, true, "the guardian or Bash must survive the server");
136
+ assert.equal(spawned.options.stdio, "ignore", "the background job must not depend on server streams");
137
+ if (process.platform === "win32") {
138
+ assert.equal(spawned.args[0], path.join(stateRoot, "jobs", launchPlan.transactionId, "guardian.mjs"));
139
+ assert.equal(spawned.options.env.PI_WEBUI_UPDATE_SHELL, process.execPath);
140
+ } else assert.deepEqual(spawned.args.slice(0, 2), ["--noprofile", "--norc"]);
141
+ assert.equal(spawned.options.env.PI_FIXTURE_API_TOKEN, "private-secret-only-in-memory");
142
+ const job = await readSharedJob(stateRoot, launchPlan.transactionId);
143
+ const intentText = await readFile(path.join(job.jobDir, "intent.json"), "utf8");
144
+ assert.equal(intentText.includes("private-secret-only-in-memory"), false, "intent must not durably copy the launch environment");
145
+ assert.equal(JSON.parse(intentText).env, undefined);
146
+ await readFile(path.join(job.jobDir, "pi-webui-update-context.mjs"));
147
+ if (process.platform === "win32") {
148
+ await readFile(path.join(job.jobDir, "guardian.mjs"));
149
+ await writeFile(path.join(job.jobDir, "guardian-launch-failed.json"), JSON.stringify({
150
+ transactionId: launchPlan.transactionId, guardianPid: launched.launcherPid, noShellStarted: true,
151
+ }));
152
+ assert.equal((await inspectNativeJob(stateRoot, launchPlan.transactionId)).phase, "launch-failed",
153
+ "a guardian's proven pre-shell failure can be finalized without claiming command completion");
154
+ }
155
+ await releaseEffectLocks(job.lock, { completionVerified: true }); // The fixture spawn never launched a native command.
156
+ await persistSharedJob(stateRoot, { ...job, phase: "failed", outcome: "failed" });
157
+ const failedPlan = await createNativeUpdatePlan({ requested: "pi", context: { ...native.context,
158
+ cwd: stateRoot, shell: process.execPath, ownerPackageRoot: fixture },
159
+ targets: [{ eligible: true, id: "pi", driver, installed: { root: effectRoot, version: "0.87.1" }, effectRoot,
160
+ command: { command: process.execPath, args: [driver, "update"] } }] });
161
+ const refusedSpawn = () => {
162
+ const child = new EventEmitter();
163
+ queueMicrotask(() => child.emit("error", Object.assign(new Error("fixture shell refusal"), { code: "EACCES" })));
164
+ return child;
165
+ };
166
+ await assert.rejects(launchNativeUpdate(failedPlan, failedPlan.digest, { stateRoot,
167
+ spawnImpl: refusedSpawn, env: process.env, requiredParticipants: [{ kind: "server", token: participant.token }] }),
168
+ /fixture shell refusal/);
169
+ assert.equal((await inspectNativeJob(stateRoot, failedPlan.transactionId)).phase, "failed");
170
+ assert.equal((await discoverNativeJobs(stateRoot, { agentDir: failedPlan.context.agentDir,
171
+ ownerPackageRoot: fixture })).pi.phase, "failed", "a proven pre-spawn failure permits a fresh confirmation");
172
+ assert.equal(await effectLockForRoot(stateRoot, effectRoot), null);
173
+ } finally {
174
+ clearInterval(acknowledge);
175
+ await unregisterUpdateParticipant(participant);
176
+ }
177
+ } finally { await rm(fixture, { recursive: true, force: true }); }
68
178
  console.log("update-plan.test.mjs passed");
@@ -1,5 +1,8 @@
1
1
  import assert from "node:assert/strict";
2
+ import { mkdtemp, mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
2
4
  import path from "node:path";
5
+ import { resolveUpdatePathPi } from "../lib/update/path-pi.mjs";
3
6
  import { resolveCanonicalPiRuntime, resolveWebuiRuntimeIdentity, sameRuntimeIdentity } from "../lib/update/resolver.mjs";
4
7
 
5
8
  const bundledCli = "C:\\Agent\\npm\\node_modules\\@earendil-works\\pi-coding-agent\\dist\\cli.js";
@@ -53,4 +56,37 @@ assert.equal(webui.version, "0.8.6");
53
56
  assert.equal(sameRuntimeIdentity(webui, { canonicalId: webui.canonicalId }), true);
54
57
  assert.ok(calls.every((call) => Array.isArray(call.args)));
55
58
  assert.ok(calls.every((call) => call.options?.timeoutMs === 10_000), "runtime probes should use the fail-closed ten-second budget by default");
59
+ const fixture = await mkdtemp(path.join(tmpdir(), "pi-update-path-"));
60
+ try {
61
+ const bin = path.join(fixture, "bin");
62
+ const platform = process.platform;
63
+ const piRoot = path.join(platform === "win32" ? bin : path.join(fixture, "lib"), "node_modules", "@earendil-works", "pi-coding-agent");
64
+ const cli = path.join(piRoot, "dist", "bundle", "cli.js");
65
+ const node = path.join(bin, "node");
66
+ await mkdir(path.dirname(cli), { recursive: true });
67
+ await mkdir(bin, { recursive: true });
68
+ await writeFile(node, "test executable");
69
+ await writeFile(cli, "test cli");
70
+ if (platform === "win32") {
71
+ await writeFile(path.join(bin, "pi.cmd"), '@echo off\n"%dp0%\\node.exe" "%dp0%\\node_modules\\@earendil-works\\pi-coding-agent\\dist\\bundle\\cli.js" %*\n');
72
+ } else await symlink(path.relative(bin, cli), path.join(bin, "pi"));
73
+ const manifest = path.join(piRoot, "package.json");
74
+ await writeFile(manifest, JSON.stringify({ name: "@earendil-works/pi-coding-agent", version: "0.87.1", bin: { pi: "dist/bundle/cli.js" } }));
75
+ const version = async (command, args) => {
76
+ assert.equal(command, node);
77
+ assert.deepEqual(args, [cli, "--version"]);
78
+ return { exitCode: 0, stdout: "0.87.1" };
79
+ };
80
+ const updateRuntime = { env: { PATH: bin, PATHEXT: ".CMD" }, platform, node, runVersion: version };
81
+ const resolved = await resolveUpdatePathPi(updateRuntime);
82
+ assert.equal(resolved.eligible, true);
83
+ assert.deepEqual(resolved.invocation, { command: node, args: [cli] });
84
+ assert.equal(resolved.packageRoot, piRoot);
85
+ assert.equal((await resolveUpdatePathPi({ ...updateRuntime, env: { PATH: "" } })).eligible, false);
86
+ await writeFile(manifest, (await readFile(manifest, "utf8")).replace("0.87.1", "0.80.10"));
87
+ const older = await resolveUpdatePathPi(updateRuntime);
88
+ assert.equal(older.eligible, false, "an unproven Pi version must never be updated via PATH fallback");
89
+ } finally {
90
+ await rm(fixture, { recursive: true, force: true });
91
+ }
56
92
  console.log("update-resolver.test.mjs passed");
@@ -1,12 +1,16 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { createServer } from "node:http";
3
- import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
3
+ import { cp, mkdtemp, mkdir, readFile, readdir, rm, symlink, writeFile } from "node:fs/promises";
4
+ import { fileURLToPath } from "node:url";
5
+ import { compareWebuiVersions, migrateLegacyBootstrap } from "../lib/update/migration.mjs";
6
+ import { acquireEffectLocks, releaseEffectLocks, sharedUpdateRoot } from "../lib/update/coordination.mjs";
4
7
  import { tmpdir } from "node:os";
5
8
  import path from "node:path";
6
9
  import {
7
10
  listenWithRetry,
8
11
  managedRuntimePaths,
9
12
  probeCandidateRuntime,
13
+ probeStartupRestore,
10
14
  readRuntimePointer,
11
15
  rollbackRuntimePointer,
12
16
  switchRuntimePointer,
@@ -21,6 +25,7 @@ try {
21
25
  const serverEntry = path.join(runtimeRoot, "bin", "pi-webui.mjs");
22
26
  await mkdir(path.dirname(serverEntry), { recursive: true });
23
27
  await writeFile(serverEntry, `if (process.argv[2] === "--candidate-probe") console.log(JSON.stringify({ok:true,version:${JSON.stringify(version)},piVersion:"9.9.9"}));\n`, "utf8");
28
+ await writeFile(path.join(runtimeRoot, "package.json"), JSON.stringify({ name: "@firstpick/pi-package-webui", version }));
24
29
  return { runtimeRoot, serverEntry, version };
25
30
  };
26
31
  const first = await makeRuntime("first", "1.0.0");
@@ -42,6 +47,74 @@ try {
42
47
  assert.equal((await probeCandidateRuntime(second.serverEntry, { expectedVersion: "2.0.0", expectedPiVersion: "8.8.8" })).ok, false);
43
48
  const wrongProbe = await probeCandidateRuntime(second.serverEntry, { expectedVersion: "9.0.0" });
44
49
  assert.equal(wrongProbe.ok, false);
50
+ const metadataOnly = await probeStartupRestore(second.serverEntry, { expectedVersion: "2.0.0", timeoutMs: 1_000 });
51
+ assert.equal(metadataOnly.ok, false, "metadata-only candidates must fail isolated startup/restoration validation");
52
+
53
+ assert.equal(compareWebuiVersions("1.0.0", "1.0.0-rc.2"), 1);
54
+ assert.equal(compareWebuiVersions("1.0.0-rc.10", "1.0.0-rc.2"), 1);
55
+ assert.equal(compareWebuiVersions("0.9.9", "1.0.0"), -1);
56
+ await writeRuntimePointer(root, "current", first);
57
+ const bootstrap = path.join(root, "node_modules", "@firstpick", "pi-package-webui");
58
+ await mkdir(path.join(bootstrap, "bin"), { recursive: true });
59
+ await writeFile(path.join(bootstrap, "bin", "pi-webui.mjs"), "// candidate stub, never executes real updates\n");
60
+ const candidateManifest = path.join(bootstrap, "package.json");
61
+ await writeFile(candidateManifest, JSON.stringify({ name: "@firstpick/pi-package-webui", version: "2.0.0" }));
62
+ const rejected = await migrateLegacyBootstrap(root, bootstrap, { probe: async () => ({ ok: false }) });
63
+ assert.equal(rejected.migrated, false);
64
+ assert.equal(rejected.serverEntry, first.serverEntry);
65
+ const migrated = await migrateLegacyBootstrap(root, bootstrap, { probe: async () => ({ ok: true }) });
66
+ assert.equal(migrated.migrated, true);
67
+ assert.equal((await readRuntimePointer(root, "current")).serverEntry, first.serverEntry, "never destroy the legacy pointer");
68
+ const backups = await readdir(path.join(paths.root, "pointer-backups"));
69
+ assert.equal(backups.length, 1);
70
+ await writeFile(candidateManifest, JSON.stringify({ name: "@firstpick/pi-package-webui", version: "2.1.0" }));
71
+ const upgraded = await migrateLegacyBootstrap(root, bootstrap, { probe: async (_, { expectedVersion }) => ({ ok: expectedVersion === "2.1.0" }) });
72
+ assert.equal(upgraded.migrated, true, "a subsequent native upgrade remains on the validated bootstrap");
73
+ assert.equal(JSON.parse(await readFile(path.join(paths.root, "native-migration.json"), "utf8")).version, "2.1.0");
74
+ assert.equal((await readdir(path.join(paths.root, "pointer-backups"))).length, 1, "upgrades retain the original pointer backup");
75
+ assert.deepEqual(JSON.parse(await readFile(path.join(paths.root, "pointer-backups", backups[0], "current.json"), "utf8")).version, "1.0.0");
76
+ await writeFile(candidateManifest, JSON.stringify({ name: "@firstpick/pi-package-webui", version: "0.9.0" }));
77
+ const downgrade = await migrateLegacyBootstrap(root, bootstrap, { probe: () => assert.fail("downgrade must not probe") });
78
+ assert.equal(downgrade.migrated, false);
79
+ assert.equal(downgrade.serverEntry, first.serverEntry);
80
+
81
+ // The migration gate must run the candidate's real server and restore path,
82
+ // not merely accept a version field from a stubbed metadata probe.
83
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
84
+ const installedVersion = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8")).version;
85
+ const functionalAgent = path.join(root, "functional-agent");
86
+ const functionalPaths = managedRuntimePaths(functionalAgent);
87
+ const oldRoot = path.join(functionalPaths.runtimesDir, "old");
88
+ await mkdir(path.join(oldRoot, "bin"), { recursive: true });
89
+ await writeFile(path.join(oldRoot, "package.json"), JSON.stringify({ name: "@firstpick/pi-package-webui", version: "0.0.1" }));
90
+ await writeFile(path.join(oldRoot, "bin", "pi-webui.mjs"), "// old runtime retained by the fixture\n");
91
+ await writeRuntimePointer(functionalAgent, "current", { runtimeRoot: oldRoot, serverEntry: path.join(oldRoot, "bin", "pi-webui.mjs"), version: "0.0.1" });
92
+ const functionalCandidate = path.join(root, "functional", "node_modules", "@firstpick", "pi-package-webui");
93
+ await mkdir(functionalCandidate, { recursive: true });
94
+ for (const directory of ["bin", "lib", "public"]) {
95
+ await cp(path.join(packageRoot, directory), path.join(functionalCandidate, directory), { recursive: true });
96
+ }
97
+ await writeFile(path.join(functionalCandidate, "package.json"), await readFile(path.join(packageRoot, "package.json")));
98
+ const dependencies = path.join(functionalCandidate, "node_modules");
99
+ await symlink(path.join(packageRoot, "node_modules"), dependencies, process.platform === "win32" ? "junction" : "dir");
100
+ const actualProbe = (entry, options) => probeStartupRestore(entry, { ...options, timeoutMs: 20_000,
101
+ piCommand: path.join(packageRoot, "tests", "fixtures", "fake-pi.mjs") });
102
+ const functionalMigration = await migrateLegacyBootstrap(functionalAgent, functionalCandidate, { probe: actualProbe });
103
+ assert.equal(functionalMigration.migrated, true, JSON.stringify(functionalMigration));
104
+ assert.equal(functionalMigration.serverEntry, path.join(functionalCandidate, "bin", "pi-webui.mjs"));
105
+ assert.equal((await readRuntimePointer(functionalAgent, "current")).version, "0.0.1", "successful migration must retain the legacy pointer");
106
+ const isolatedCoordination = await sharedUpdateRoot({ home: root });
107
+ const realEquivalentEffect = path.join(root, "functional");
108
+ const verificationFence = await acquireEffectLocks(isolatedCoordination, [realEquivalentEffect], "probe-under-fence");
109
+ try {
110
+ const underFence = await actualProbe(path.join(functionalCandidate, "bin", "pi-webui.mjs"), { expectedVersion: installedVersion });
111
+ assert.equal(underFence.ok, true, "probe must start and restore while the real-equivalent installed root is fenced");
112
+ } finally { await releaseEffectLocks(verificationFence, { completionVerified: true }); } // Fixture only: no native command ran.
113
+ await rm(dependencies);
114
+ const missingDependencies = await migrateLegacyBootstrap(functionalAgent, functionalCandidate, { probe: actualProbe });
115
+ assert.equal(missingDependencies.migrated, false, "candidate without its bundled dependencies cannot be selected");
116
+ assert.equal(missingDependencies.serverEntry, path.join(oldRoot, "bin", "pi-webui.mjs"));
117
+ assert.ok(compareWebuiVersions(installedVersion, "0.0.1") > 0);
45
118
 
46
119
  const occupied = createServer();
47
120
  await new Promise((resolve) => occupied.listen(0, "127.0.0.1", resolve));
@@ -1,8 +1,9 @@
1
1
  import assert from "node:assert/strict";
2
- import { access, mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import path from "node:path";
5
- import { createRestoreFile, readRestoreFileOnce } from "../lib/update/supervisor.mjs";
5
+ import { fileURLToPath } from "node:url";
6
+ import { createRestoreFile, probeStartupRestore, readRestoreFileOnce } from "../lib/update/supervisor.mjs";
6
7
 
7
8
  const root = await mkdtemp(path.join(tmpdir(), "pi-webui-restore-"));
8
9
  try {
@@ -18,6 +19,12 @@ try {
18
19
  await writeFile(outside, JSON.stringify({ schemaVersion: 1, tabs: [] }));
19
20
  await assert.rejects(() => readRestoreFileOnce(outside, root), /outside the private temp root/);
20
21
  await access(outside);
22
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
23
+ const version = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8")).version;
24
+ const probe = await probeStartupRestore(path.join(packageRoot, "bin", "pi-webui.mjs"), {
25
+ expectedVersion: version, timeoutMs: 20_000, piCommand: path.join(packageRoot, "tests", "fixtures", "fake-pi.mjs"),
26
+ });
27
+ assert.equal(probe.ok, true, JSON.stringify(probe));
21
28
  } finally {
22
29
  await rm(root, { recursive: true, force: true });
23
30
  }
@@ -1,86 +0,0 @@
1
- #!/usr/bin/env node
2
- import { spawn } from "node:child_process";
3
- import path from "node:path";
4
- import { fileURLToPath } from "node:url";
5
- import { rollbackRuntimePointer, switchRuntimePointer } from "../lib/update/supervisor.mjs";
6
- import { releaseInstallLock, transitionUpdateJournal, updateStatePaths } from "../lib/update/journal.mjs";
7
-
8
- function args(argv) {
9
- const result = {};
10
- for (let i = 0; i < argv.length; i += 2) {
11
- const key = argv[i], value = argv[i + 1];
12
- if (!key?.startsWith("--") || !value) throw new Error("Activation helper requires paired --key value arguments.");
13
- result[key.slice(2)] = value;
14
- }
15
- return result;
16
- }
17
- function integer(value, name) {
18
- const parsed = Number.parseInt(value, 10);
19
- if (!Number.isInteger(parsed) || parsed <= 0) throw new Error(`${name} is invalid`);
20
- return parsed;
21
- }
22
- async function health(url, expectedVersion, expectedPiVersion, oldBootIdentity) {
23
- try {
24
- const response = await fetch(`${url.replace(/\/$/, "")}/api/health`, { signal: AbortSignal.timeout(1_500) });
25
- const body = await response.json();
26
- return response.ok
27
- && body?.ok === true
28
- && (!expectedVersion || body.webuiVersion === expectedVersion)
29
- && (!expectedPiVersion || body.piVersion === expectedPiVersion)
30
- && body.bootIdentity
31
- && body.bootIdentity !== oldBootIdentity ? body : null;
32
- } catch { return null; }
33
- }
34
- async function waitForHealth(url, expectedVersion, expectedPiVersion, oldBootIdentity, timeoutMs) {
35
- const deadline = Date.now() + timeoutMs;
36
- while (Date.now() < deadline) {
37
- const body = await health(url, expectedVersion, expectedPiVersion, oldBootIdentity);
38
- if (body) return body;
39
- await new Promise((resolve) => setTimeout(resolve, 300));
40
- }
41
- return null;
42
- }
43
- function launch(launcher, serverArgs, env) {
44
- const child = spawn(process.execPath, [launcher, ...serverArgs], { cwd: process.cwd(), env, detached: true, stdio: "ignore", windowsHide: true });
45
- child.unref();
46
- return child.pid;
47
- }
48
-
49
- const options = args(process.argv.slice(2));
50
- const agentDir = path.resolve(options["agent-dir"] || "");
51
- const runtimeRoot = path.resolve(options["runtime-root"] || "");
52
- const serverEntry = path.resolve(options["server-entry"] || "");
53
- const version = String(options.version || "");
54
- const piVersion = String(options["pi-version"] || "");
55
- const outcome = String(options.outcome || "success");
56
- const transactionId = String(options.transaction || "");
57
- const url = String(options.url || "");
58
- const oldBootIdentity = String(options["old-boot"] || "");
59
- const timeoutMs = integer(options["timeout-ms"] || "90000", "timeout");
60
- const serverArgs = JSON.parse(Buffer.from(options["server-args"] || "", "base64url").toString("utf8"));
61
- if (!Array.isArray(serverArgs) || !agentDir || !runtimeRoot || !serverEntry || !version || !piVersion || !url || !transactionId || !new Set(["success", "partial"]).has(outcome)) throw new Error("Activation helper arguments are incomplete.");
62
- const launcher = path.join(path.dirname(fileURLToPath(import.meta.url)), "pi-webui-launcher.mjs");
63
-
64
- const lockToken = String(process.env.PI_WEBUI_UPDATE_LOCK_TOKEN || "");
65
- delete process.env.PI_WEBUI_UPDATE_LOCK_TOKEN;
66
- const transferredLock = lockToken ? { path: updateStatePaths(agentDir).installLock, token: lockToken } : null;
67
- let exitCode = 1;
68
- try {
69
- await transitionUpdateJournal(agentDir, transactionId, "activating", { activation: { runtimeRoot, serverEntry, expectedVersion: version } });
70
- await switchRuntimePointer(agentDir, { runtimeRoot, serverEntry, version });
71
- launch(launcher, serverArgs, { ...process.env, PI_WEBUI_ACTIVATION_TRANSACTION: transactionId });
72
- const activated = await waitForHealth(url, version, piVersion, oldBootIdentity, timeoutMs);
73
- if (activated) {
74
- await transitionUpdateJournal(agentDir, transactionId, outcome, { outcome, activated: { version, piVersion, bootIdentity: activated.bootIdentity, at: new Date().toISOString() } });
75
- exitCode = 0;
76
- } else {
77
- await rollbackRuntimePointer(agentDir);
78
- launch(launcher, serverArgs, { ...process.env, PI_WEBUI_ACTIVATION_TRANSACTION: transactionId, PI_WEBUI_ROLLBACK_TRANSACTION: transactionId });
79
- const rolledBack = await waitForHealth(url, "", "", oldBootIdentity, Math.min(timeoutMs, 30_000));
80
- await transitionUpdateJournal(agentDir, transactionId, "rolled-back", { outcome: "rolled-back", rollback: { reachable: Boolean(rolledBack), at: new Date().toISOString(), reason: "Candidate failed the changed-identity health gate." } });
81
- exitCode = rolledBack ? 2 : 3;
82
- }
83
- } finally {
84
- if (transferredLock) await releaseInstallLock(transferredLock).catch(() => false);
85
- }
86
- process.exit(exitCode);