@firstpick/pi-package-webui 0.8.6 → 0.8.8

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 (90) hide show
  1. package/README.md +18 -606
  2. package/bin/pi-webui-launcher.mjs +22 -0
  3. package/bin/pi-webui-update-supervisor.mjs +86 -0
  4. package/bin/pi-webui.mjs +562 -524
  5. package/index.ts +8 -5
  6. package/lib/component-update-state.mjs +21 -0
  7. package/lib/git-workflow-preferences.mjs +17 -2
  8. package/lib/optional-feature-catalog.mjs +1 -0
  9. package/lib/sampling-parameter-capabilities.mjs +160 -0
  10. package/lib/session-summary-preferences.mjs +16 -1
  11. package/lib/subagent-launch-slots.mjs +14 -2
  12. package/lib/trust-boundaries.mjs +3 -0
  13. package/lib/update/executor.mjs +99 -0
  14. package/lib/update/journal.mjs +175 -0
  15. package/lib/update/owners.mjs +70 -0
  16. package/lib/update/plan.mjs +134 -0
  17. package/lib/update/resolver.mjs +168 -0
  18. package/lib/update/supervisor.mjs +238 -0
  19. package/lib/update/verify.mjs +52 -0
  20. package/lib/update-commands.mjs +25 -13
  21. package/lib/webui-workspaces.mjs +17 -1
  22. package/package.json +4 -4
  23. package/public/app.js +1543 -109
  24. package/public/index.html +146 -48
  25. package/public/middle-button-drag-scroll.mjs +154 -0
  26. package/public/sampling-parameter-controls.mjs +361 -0
  27. package/public/service-worker.js +3 -1
  28. package/public/styles.css +512 -1
  29. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  30. package/tests/browser/control-deck-component-updates.spec.mjs +20 -22
  31. package/tests/browser/middle-button-drag-scroll.spec.mjs +145 -0
  32. package/tests/browser/persistent-ui-layout.spec.mjs +68 -23
  33. package/tests/browser/sampling-tooltip.spec.mjs +228 -0
  34. package/tests/browser/update-reconnect.spec.mjs +92 -0
  35. package/tests/codex-fast-mode-static.test.mjs +2 -2
  36. package/tests/common-options-submenus-interaction-static.test.mjs +172 -0
  37. package/tests/common-options-submenus-markup-static.test.mjs +152 -0
  38. package/tests/component-update-api-static.test.mjs +22 -61
  39. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  40. package/tests/control-deck-component-updates-static.test.mjs +13 -237
  41. package/tests/durable-rpc-supervisor-harness.test.mjs +3 -1
  42. package/tests/fast-mode-client-static.test.mjs +1 -1
  43. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  44. package/tests/feature-system-prompt-optional-feature-static.test.mjs +49 -0
  45. package/tests/fixtures/fake-pi.mjs +68 -1
  46. package/tests/fixtures/update/tree-timeout-descendant.mjs +6 -0
  47. package/tests/fixtures/update/tree-timeout-parent.mjs +11 -0
  48. package/tests/git-footer-context-menu-static.test.mjs +58 -0
  49. package/tests/http-endpoints-harness.test.mjs +68 -18
  50. package/tests/middle-button-drag-scroll-static.test.mjs +24 -0
  51. package/tests/middle-button-drag-scroll.test.mjs +170 -0
  52. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  53. package/tests/mobile-foundation-static.test.mjs +4 -4
  54. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  55. package/tests/mobile-static.test.mjs +217 -24
  56. package/tests/open-issue-wizard-static.test.mjs +1 -1
  57. package/tests/optional-feature-migration-frontend.test.mjs +13 -5
  58. package/tests/persistent-ui-layout-static.test.mjs +13 -2
  59. package/tests/prompt-routing-tab-status.test.mjs +8 -0
  60. package/tests/questionnaire-dialog.test.mjs +3 -3
  61. package/tests/remote-auth-settings-harness.test.mjs +34 -0
  62. package/tests/rpc-supervisor-host.test.mjs +11 -2
  63. package/tests/safety-guard-auto-review-harness.test.mjs +117 -0
  64. package/tests/safety-guard-auto-review-static.test.mjs +34 -0
  65. package/tests/sampling-native-controls-user-flow.test.mjs +752 -0
  66. package/tests/sampling-parameter-capabilities.test.mjs +167 -0
  67. package/tests/sampling-parameter-controls.test.mjs +241 -0
  68. package/tests/session-sampling-helper.test.mjs +228 -0
  69. package/tests/session-sampling-http.test.mjs +168 -0
  70. package/tests/session-sampling-ui-static.test.mjs +370 -0
  71. package/tests/session-summary-core.test.mjs +24 -11
  72. package/tests/side-panel-section-height-removal-static.test.mjs +34 -0
  73. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  74. package/tests/staged-content-hash-contract.test.mjs +52 -11
  75. package/tests/subagent-launch-slots.test.mjs +18 -1
  76. package/tests/theme-customizer-static.test.mjs +1 -1
  77. package/tests/ui-layout-settings.test.mjs +18 -1
  78. package/tests/update-api-harness.test.mjs +111 -0
  79. package/tests/update-commands.test.mjs +15 -45
  80. package/tests/update-executor-process-tree-harness.test.mjs +22 -0
  81. package/tests/update-journal-harness.test.mjs +59 -0
  82. package/tests/update-lock-multiprocess-harness.test.mjs +46 -0
  83. package/tests/update-owners.test.mjs +27 -0
  84. package/tests/update-plan.test.mjs +58 -0
  85. package/tests/update-resolver.test.mjs +56 -0
  86. package/tests/update-supervisor-harness.test.mjs +57 -0
  87. package/tests/update-tab-restore-harness.test.mjs +24 -0
  88. package/tests/update-verify.test.mjs +31 -0
  89. package/tests/workspace-files-live-updates-static.test.mjs +13 -4
  90. package/webui-rpc-helper.mjs +119 -0
@@ -0,0 +1,34 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const [app, css, layout, html, serviceWorker] = await Promise.all([
8
+ readFile(join(root, "public", "app.js"), "utf8"),
9
+ readFile(join(root, "public", "styles.css"), "utf8"),
10
+ readFile(join(root, "lib", "ui-layout-settings.mjs"), "utf8"),
11
+ readFile(join(root, "public", "index.html"), "utf8"),
12
+ readFile(join(root, "public", "service-worker.js"), "utf8"),
13
+ ]);
14
+
15
+ for (const removedToken of [
16
+ "data-side-panel-section-resize",
17
+ "initializeSidePanelSectionResizing",
18
+ "persistSidePanelSectionHeight",
19
+ "beginSidePanelSectionResize",
20
+ "side-panel-section-resize-handle",
21
+ "side-panel-section-resizing",
22
+ ]) {
23
+ assert.doesNotMatch(app, new RegExp(removedToken), `${removedToken} should be absent from the browser controller`);
24
+ assert.doesNotMatch(css, new RegExp(removedToken), `${removedToken} should be absent from side-panel styles`);
25
+ }
26
+ assert.doesNotMatch(layout, /sectionHeightMin|sectionHeightMax|validateSectionHeights|sectionHeights/, "the durable layout schema should not expose section heights");
27
+ assert.match(app, /const UI_LAYOUT_SIDE_PANEL_FIELDS = \["sectionOrder", "collapsedSectionIds", "hiddenSectionIds", "collapsed"\];/, "the browser durable layout field list should omit section heights");
28
+ assert.match(app, /function clearRemovedSidePanelSectionHeightState\(\)[\s\S]*localStorage\.removeItem\(REMOVED_SIDE_PANEL_SECTION_HEIGHT_STORAGE_KEY\)[\s\S]*record\.field === "sidePanel" && record\.subfield === "sectionHeights"/, "startup should remove the retired cache and pending mutations");
29
+ assert.match(app, /clearRemovedSidePanelSectionHeightState\(\);\s*restoreDurableUiLayoutPendingJournal\(\);/, "retired height state should be cleared before pending layout restoration");
30
+ assert.match(html, /styles\.css\?v=104/, "removing section resize styles should advance the stylesheet revision");
31
+ assert.match(html, /app\.js\?v=120/, "removing section resize behavior should advance the app revision");
32
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v81"/, "removing browser assets should advance the PWA cache identity");
33
+
34
+ console.log("side-panel-section-height-removal-static.test.mjs passed");
@@ -61,8 +61,8 @@ assert.match(
61
61
  /\.side-panel-section-toggle\[data-side-panel-section-toggle\][\s\S]*cursor: grab[\s\S]*touch-action: none[\s\S]*\.side-panel-section\.dragging[\s\S]*cursor: grabbing[\s\S]*\.drag-over-before[\s\S]*\.drag-over-after/,
62
62
  "section headers should expose model-picker-style grab, dragging, and insertion-marker affordances",
63
63
  );
64
- assert.match(html, /styles\.css\?v=98/, "changed side-panel styles should advance the stylesheet revision");
65
- assert.match(html, /app\.js\?v=113/, "changed side-panel behavior should advance the app revision");
66
- assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v74"/, "changed browser assets should advance the PWA cache identity");
64
+ assert.match(html, /styles\.css\?v=104/, "changed side-panel styles should advance the stylesheet revision");
65
+ assert.match(html, /app\.js\?v=120/, "changed side-panel behavior should advance the app revision");
66
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v81"/, "changed browser assets should advance the PWA cache identity");
67
67
 
68
68
  console.log("side-panel-section-reorder-static.test.mjs passed");
@@ -5,6 +5,7 @@ import { tmpdir } from "node:os";
5
5
  import path from "node:path";
6
6
  import { dirname, join } from "node:path";
7
7
  import { fileURLToPath, pathToFileURL } from "node:url";
8
+ import { setTimeout as delay } from "node:timers/promises";
8
9
 
9
10
  const root = join(dirname(fileURLToPath(import.meta.url)), "..");
10
11
  const workspaceRoot = join(root, "..");
@@ -13,6 +14,29 @@ const fakePi = join(root, "tests", "fixtures", "fake-pi.mjs");
13
14
  const reviewModuleUrl = pathToFileURL(join(workspaceRoot, "pi-extension-aur-review", "src", "git.ts")).href;
14
15
  const port = 41000 + Math.floor(Math.random() * 10000);
15
16
 
17
+ async function waitForChildClose(child, timeoutMs = 2_000) {
18
+ if (child.exitCode !== null) return true;
19
+ return Promise.race([
20
+ new Promise((resolve) => child.once("close", () => resolve(true))),
21
+ delay(timeoutMs, false),
22
+ ]);
23
+ }
24
+
25
+ async function rmWithRetry(target) {
26
+ let lastError;
27
+ for (let attempt = 0; attempt < 20; attempt += 1) {
28
+ try {
29
+ await rm(target, { recursive: true, force: true });
30
+ return;
31
+ } catch (error) {
32
+ lastError = error;
33
+ if (!["EBUSY", "EPERM", "ENOTEMPTY"].includes(error?.code)) throw error;
34
+ await delay(Math.min(500, 150 * (attempt + 1)));
35
+ }
36
+ }
37
+ throw lastError;
38
+ }
39
+
16
40
  function git(cwd, ...args) {
17
41
  const result = spawnSync("git", args, { cwd, encoding: "utf8" });
18
42
  assert.equal(result.status, 0, `git ${args.join(" ")} failed:\n${result.stderr || result.stdout}`);
@@ -56,6 +80,7 @@ const child = spawn(process.execPath, [serverScript, "--cwd", repo, "--host", "1
56
80
  ...process.env,
57
81
  PI_CODING_AGENT_DIR: agentDir,
58
82
  PI_WEBUI_SETTINGS_FILE: path.join(agentDir, "settings.json"),
83
+ PI_WEBUI_RPC_SUPERVISOR: "0",
59
84
  },
60
85
  });
61
86
  let serverOutput = "";
@@ -130,10 +155,19 @@ try {
130
155
  await assertMatchesExtension("mode");
131
156
  reset();
132
157
 
133
- await symlink("normal.txt", path.join(repo, "normal-link"));
134
- git(repo, "add", "normal-link");
135
- await assertMatchesExtension("symlink");
136
- reset();
158
+ let symlinkSupported = true;
159
+ try {
160
+ await symlink("normal.txt", path.join(repo, "normal-link"));
161
+ } catch (error) {
162
+ if (!["EACCES", "EPERM"].includes(error?.code)) throw error;
163
+ symlinkSupported = false;
164
+ console.log(`staged-content-hash-contract: symlink unavailable (${error.code}); skipping symlink hash case`);
165
+ }
166
+ if (symlinkSupported) {
167
+ git(repo, "add", "normal-link");
168
+ await assertMatchesExtension("symlink");
169
+ reset();
170
+ }
137
171
 
138
172
  await writeFile(path.join(repo, "added.txt"), "added\n");
139
173
  git(repo, "rm", "-q", "deleted.txt");
@@ -164,11 +198,18 @@ try {
164
198
 
165
199
  console.log("staged content hash contract tests passed");
166
200
  } finally {
167
- child.kill("SIGTERM");
168
- await Promise.race([
169
- new Promise((resolve) => child.once("close", resolve)),
170
- new Promise((resolve) => setTimeout(resolve, 2_000)),
171
- ]);
172
- if (child.exitCode === null) child.kill("SIGKILL");
173
- await Promise.all([rm(repo, { recursive: true, force: true }), rm(agentDir, { recursive: true, force: true })]);
201
+ if (child.exitCode === null) {
202
+ try {
203
+ await request("/api/shutdown", { method: "POST" });
204
+ } catch {
205
+ // Fall back to direct termination below when the server is already unavailable.
206
+ }
207
+ }
208
+ if (child.exitCode === null) child.kill("SIGTERM");
209
+ if (!(await waitForChildClose(child))) {
210
+ child.kill("SIGKILL");
211
+ await waitForChildClose(child);
212
+ }
213
+ await delay(500);
214
+ await Promise.all([rmWithRetry(repo), rmWithRetry(agentDir)]);
174
215
  }
@@ -82,7 +82,24 @@ try {
82
82
  const projectKey = await resolveSubagentLaunchSlotProjectKey(nested);
83
83
  assert.equal(projectKey, projectRoot, "nested tab cwd must resolve to the nearest canonical repository root");
84
84
  const markerlessProjectKey = await resolveSubagentLaunchSlotProjectKey(settingsRoot);
85
- assert.equal(markerlessProjectKey, settingsRoot, "a markerless tab cwd must not collapse to the filesystem root");
85
+ assert.equal(markerlessProjectKey, settingsRoot, "a markerless tab cwd must not collapse to the global Pi directory");
86
+
87
+ const piProjectRoot = path.join(settingsRoot, "pi-project");
88
+ const piProjectNested = path.join(piProjectRoot, "nested");
89
+ await mkdir(path.join(piProjectRoot, ".pi"), { recursive: true });
90
+ await mkdir(piProjectNested, { recursive: true });
91
+ assert.equal(await resolveSubagentLaunchSlotProjectKey(piProjectNested), piProjectRoot, "a project-local .pi marker must still define the project root");
92
+
93
+ const simulatedHome = path.join(settingsRoot, "simulated-home");
94
+ const simulatedGlobalPiRoot = path.join(simulatedHome, ".pi");
95
+ const simulatedMarkerlessCwd = path.join(simulatedHome, "workspace");
96
+ await mkdir(simulatedGlobalPiRoot, { recursive: true });
97
+ await mkdir(simulatedMarkerlessCwd, { recursive: true });
98
+ assert.equal(
99
+ await resolveSubagentLaunchSlotProjectKey(simulatedMarkerlessCwd, { globalPiRoot: simulatedGlobalPiRoot }),
100
+ simulatedMarkerlessCwd,
101
+ "the global Pi directory must not turn its parent into a project root",
102
+ );
86
103
 
87
104
  const config = normalizeSubagentLaunchSlots({ user: { roles: validRoles } });
88
105
  const inherited = subagentLaunchSlotScopeEntry(config, "project", projectKey);
@@ -34,7 +34,7 @@ assert.match(html, /role="alert" hidden>[\s\S]*Replace this exact target\?/, "ov
34
34
 
35
35
  assert.match(app, /from "\.\/theme-contract\.mjs"/, "frontend should consume the shared browser-safe theme contract");
36
36
  assert.match(serviceWorker, /"\/theme-contract\.mjs"/, "the PWA app shell should cache the startup-critical theme contract");
37
- assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v74"/, "adding the theme contract to the startup graph should advance the PWA cache identity");
37
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v81"/, "adding the theme contract to the startup graph should advance the PWA cache identity");
38
38
  assert.match(pkg, /node --check public\/theme-contract\.mjs/, "the package check should syntax-check the startup-critical theme contract");
39
39
  assert.match(app, /function themeDraftFromCatalog\(theme, name = theme\?\.name\)[\s\S]*colors: cloneThemeDraft\(theme\?\.colors \|\| \{\}\)/, "catalog metadata should be projected into a schema-only editable draft");
40
40
  assert.match(app, /for \(const \{ name, label \} of group\.tokens\)/, "visual controls should render from the exact shared token inventory");
@@ -33,11 +33,20 @@ const valid = normalizeUiLayout({
33
33
  });
34
34
  assert.deepEqual(valid.sidePanel.sectionOrder, ["files", "controls", "git"]);
35
35
  assert.equal(valid.fileViewerWidth, 560);
36
+ const legacySectionHeights = normalizeUiLayout({
37
+ version: 1,
38
+ sidePanel: { ...valid.sidePanel, sectionHeights: { files: 360 } },
39
+ });
40
+ assert.equal("sectionHeights" in legacySectionHeights.sidePanel, false, "legacy saved section heights should be ignored during normalization");
36
41
  assert.equal(valid.terminalTabs.layout, "left");
37
42
 
38
43
  const partiallyMalformed = normalizeUiLayout({
39
44
  ...valid,
40
- sidePanel: { ...valid.sidePanel, sectionOrder: ["files", "files"], collapsed: true },
45
+ sidePanel: {
46
+ ...valid.sidePanel,
47
+ sectionOrder: ["files", "files"],
48
+ collapsed: true,
49
+ },
41
50
  composerActions: { ...valid.composerActions, grid: { version: 2, columns: 999, positions: {} } },
42
51
  terminalTabs: { layout: "bottom", customGroups: valid.terminalTabs.customGroups },
43
52
  });
@@ -58,6 +67,9 @@ assert.equal(merged.sidePanel.hiddenSectionIds, null, "explicit null must clear
58
67
  assert.deepEqual(merged.footerScopedModelOrder, [], "explicit empty arrays are valid resets");
59
68
  assert.equal(merged.fileViewerWidth, null);
60
69
 
70
+ const sidePanelReset = mergeUiLayout(valid, { sidePanel: null });
71
+ assert.deepEqual(sidePanelReset.sidePanel, defaults.sidePanel, "null sidePanel must reset all side-panel fields");
72
+
61
73
  const composerReset = mergeUiLayout(valid, { composerActions: { order: [], grid: null } });
62
74
  assert.deepEqual(composerReset.composerActions, { order: [], grid: null });
63
75
  const terminalReset = mergeUiLayout(valid, { terminalTabs: null });
@@ -68,6 +80,11 @@ assert.throws(() => validateUiLayoutPatch({ unknown: true }), /unsupported field
68
80
  assert.throws(() => validateUiLayoutPatch({ version: 2, fileViewerWidth: 500 }), /version must be 1/);
69
81
  assert.throws(() => validateUiLayoutPatch({ composerActions: { order: ["send"] } }), /order and grid together/);
70
82
  assert.throws(() => validateUiLayoutPatch({ sidePanel: { collapsed: "yes" } }), /boolean or null/);
83
+ assert.throws(
84
+ () => validateUiLayoutPatch({ sidePanel: { sectionHeights: { files: 240 } } }),
85
+ /unsupported field: sectionHeights/,
86
+ "removed section-height preferences must no longer be accepted",
87
+ );
71
88
  assert.throws(() => validateUiLayoutPatch({ fileViewerWidth: UI_LAYOUT_LIMITS.fileViewerWidthMin - 1 }), /must be between/);
72
89
  assert.throws(() => validateUiLayoutPatch({ footerScopedModelOrder: Array(UI_LAYOUT_LIMITS.listItems + 1).fill("model") }), /at most/);
73
90
  assert.throws(() => validateUiLayoutPatch({
@@ -0,0 +1,111 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { createServer as createHttpServer } from "node:http";
4
+ import { createServer as createNetServer } from "node:net";
5
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
6
+ import { tmpdir } from "node:os";
7
+ import path from "node:path";
8
+ import { setTimeout as delay } from "node:timers/promises";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
10
+ import { validateUpdateApplyRequest, validateUpdatePlanRequest } from "../lib/component-update-state.mjs";
11
+ import { exactNpmInstallArgs, exactPackageSpec, updatePlanConfirmationText } from "../lib/update-commands.mjs";
12
+
13
+ assert.deepEqual(validateUpdatePlanRequest({ targets: ["pi", "webui"] }), { ok: true, targets: ["pi", "webui"] });
14
+ for (const invalid of [{}, { targets: [] }, { targets: ["all"] }, { targets: ["pi", "pi"] }, { targets: ["pi"], registry: "https://evil.test" }]) {
15
+ assert.equal(validateUpdatePlanRequest(invalid).ok, false);
16
+ }
17
+ const digest = "a".repeat(64);
18
+ assert.deepEqual(validateUpdateApplyRequest({ transactionId: "tx-1", planDigest: digest }), { ok: true, transactionId: "tx-1", planDigest: digest });
19
+ for (const invalid of [{ transactionId: "tx-1" }, { transactionId: "../x", planDigest: digest }, { transactionId: "tx", planDigest: digest, command: "npm" }]) {
20
+ assert.equal(validateUpdateApplyRequest(invalid).ok, false);
21
+ }
22
+ assert.equal(exactPackageSpec("@firstpick/pi-package-webui", "1.2.3"), "@firstpick/pi-package-webui@1.2.3");
23
+ assert.throws(() => exactPackageSpec("pkg", "latest"), /exact version/);
24
+ const installArgs = exactNpmInstallArgs({ installRoot: "/private/runtime", packageName: "pkg", version: "1.2.3", registry: "https://registry.example.test" });
25
+ assert.deepEqual(installArgs.slice(-3), ["--registry", "https://registry.example.test/", "pkg@1.2.3"]);
26
+ assert.doesNotMatch(installArgs.join(" "), /--all|--extensions|@latest/);
27
+ assert.match(updatePlanConfirmationText({ transactionId: "tx", digest, targets: [{ id: "webui", currentVersion: "1.0.0", targetVersion: "1.1.0" }], refusals: [] }), new RegExp(digest));
28
+
29
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
30
+ const server = await readFile(path.join(root, "bin", "pi-webui.mjs"), "utf8");
31
+ assert.match(server, /\/api\/update\/plan[\s\S]*validateUpdatePlanRequest[\s\S]*createServerOwnedUpdatePlan/);
32
+ assert.match(server, /\/api\/update\/apply[\s\S]*validateUpdateApplyRequest[\s\S]*applyServerOwnedUpdate/);
33
+ assert.match(server, /Legacy update mutation is disabled/);
34
+ assert.match(server, /assertUpdatePlanDigest\(journal\.plan, planDigest\)/);
35
+ assert.match(server, /acquireInstallLock\(agentDir\)[\s\S]*assertPlanIdentity/);
36
+ assert.match(server, /bootIdentity/);
37
+ assert.doesNotMatch(server, /function resolveUpdateTasks|function projectPackageRootUpdateTasks|function npmGlobalPackageRootUpdateTask|function bunGlobalPackageRootUpdateTask/);
38
+
39
+ async function freePort() {
40
+ const listener = createNetServer();
41
+ await new Promise((resolve) => listener.listen(0, "127.0.0.1", resolve));
42
+ const port = listener.address().port;
43
+ await new Promise((resolve) => listener.close(resolve));
44
+ return port;
45
+ }
46
+ const registryPort = await freePort();
47
+ const webuiPort = await freePort();
48
+ const registry = createHttpServer((req, res) => {
49
+ res.writeHead(200, { "content-type": "application/json" });
50
+ res.end(JSON.stringify(req.url === "/pi-latest" ? { version: "9.9.9" } : { version: "9.9.9" }));
51
+ });
52
+ await new Promise((resolve) => registry.listen(registryPort, "127.0.0.1", resolve));
53
+ const temp = await mkdtemp(path.join(tmpdir(), "pi-webui-update-api-"));
54
+ const fakePi = path.join(temp, "fake-pi-with-version.mjs");
55
+ await writeFile(fakePi, `if (process.argv.includes("--version")) { console.log("0.84.0"); process.exit(0); } await import(${JSON.stringify(pathToFileURL(path.join(root, "tests", "fixtures", "fake-pi.mjs")).href)});\n`, "utf8");
56
+ const child = spawn(process.execPath, [path.join(root, "bin", "pi-webui.mjs"), "--cwd", temp, "--host", "127.0.0.1", "--port", String(webuiPort), "--pi", fakePi], {
57
+ stdio: ["ignore", "pipe", "pipe"],
58
+ env: {
59
+ ...process.env,
60
+ PI_WEBUI_RPC_SUPERVISOR: "0",
61
+ PI_CODING_AGENT_DIR: path.join(temp, "agent"),
62
+ PI_WEBUI_SETTINGS_FILE: path.join(temp, "settings.json"),
63
+ PI_WEBUI_PI_LATEST_VERSION_URL: `http://127.0.0.1:${registryPort}/pi-latest`,
64
+ PI_WEBUI_NPM_REGISTRY_URL: `http://127.0.0.1:${registryPort}`,
65
+ },
66
+ });
67
+ let output = "";
68
+ child.stdout.on("data", (chunk) => { output += chunk; });
69
+ child.stderr.on("data", (chunk) => { output += chunk; });
70
+ try {
71
+ let health;
72
+ for (let attempt = 0; attempt < 100; attempt += 1) {
73
+ try {
74
+ const response = await fetch(`http://127.0.0.1:${webuiPort}/api/health`, { signal: AbortSignal.timeout(500) });
75
+ if (response.ok) { health = await response.json(); break; }
76
+ } catch {}
77
+ await delay(100);
78
+ }
79
+ assert.ok(health?.bootIdentity, output);
80
+ const planResponse = await fetch(`http://127.0.0.1:${webuiPort}/api/update/plan`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ targets: ["pi", "webui"] }) });
81
+ const planPayload = await planResponse.json();
82
+ assert.equal(planResponse.status, 201, JSON.stringify(planPayload));
83
+ const plan = planPayload.data.plan;
84
+ assert.equal(plan.targets.length, 1, "the exact explicit Pi executable should own its delegated update while source WebUI remains refused");
85
+ assert.equal(plan.targets[0].id, "pi");
86
+ assert.equal(plan.targets[0].strategy, "delegate-exact-pi");
87
+ assert.deepEqual(plan.targets[0].command.args.slice(-2), ["update", "--self"]);
88
+ assert.doesNotMatch(plan.targets[0].command.args.join(" "), /@latest/);
89
+ assert.deepEqual(plan.refusals.map((item) => item.id), ["webui"]);
90
+
91
+ const sourcePlanResponse = await fetch(`http://127.0.0.1:${webuiPort}/api/update/plan`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ targets: ["webui"] }) });
92
+ const sourcePlanPayload = await sourcePlanResponse.json();
93
+ assert.equal(sourcePlanResponse.status, 201, JSON.stringify(sourcePlanPayload));
94
+ const sourcePlan = sourcePlanPayload.data.plan;
95
+ assert.equal(sourcePlan.targets.length, 0);
96
+ assert.deepEqual(sourcePlan.refusals.map((item) => item.id), ["webui"]);
97
+ const tampered = await fetch(`http://127.0.0.1:${webuiPort}/api/update/apply`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ transactionId: sourcePlan.transactionId, planDigest: "0".repeat(64) }) });
98
+ assert.equal(tampered.status, 500);
99
+ const apply = await fetch(`http://127.0.0.1:${webuiPort}/api/update/apply`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ transactionId: sourcePlan.transactionId, planDigest: sourcePlan.digest }) });
100
+ const applyPayload = await apply.json();
101
+ assert.equal(apply.status, 200, JSON.stringify(applyPayload));
102
+ assert.equal(applyPayload.data.outcome, "failed");
103
+ const legacy = await fetch(`http://127.0.0.1:${webuiPort}/api/update`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
104
+ assert.equal(legacy.status, 410);
105
+ } finally {
106
+ child.kill("SIGTERM");
107
+ if (child.exitCode === null) await new Promise((resolve) => child.once("exit", resolve));
108
+ await new Promise((resolve) => registry.close(resolve));
109
+ await rm(temp, { recursive: true, force: true });
110
+ }
111
+ console.log("update API harness passed");
@@ -1,48 +1,18 @@
1
1
  import assert from "node:assert/strict";
2
- import { readFile } from "node:fs/promises";
3
- import { dirname, join } from "node:path";
4
- import { fileURLToPath } from "node:url";
5
- import { piUpdateCommandSteps, piUpdateCommandText, piUpdateHelpSupportsAll } from "../lib/update-commands.mjs";
6
-
7
- const packageRoot = join(dirname(fileURLToPath(import.meta.url)), "..");
8
-
9
- assert.deepEqual(piUpdateCommandSteps(), [
10
- { label: "Pi CLI", args: ["update", "--self"] },
11
- ], "Pi-only updates should use the explicit cross-version self flag");
12
-
13
- assert.deepEqual(piUpdateCommandSteps({ all: true, supportsAll: true }), [
14
- { label: "Pi CLI and configured packages", args: ["update", "--all"] },
15
- ], "all updates should prefer --all when the selected Pi executable supports it");
16
-
17
- const fallbackSteps = piUpdateCommandSteps({ all: true });
18
- assert.deepEqual(fallbackSteps, [
19
- { label: "Pi CLI", args: ["update", "--self"] },
20
- { label: "configured Pi packages", args: ["update", "--extensions"] },
21
- ], "all updates should split self and extension updates when --all is unavailable");
22
-
23
- assert.equal(piUpdateHelpSupportsAll("Usage: pi update [--self|--extensions|--all]"), true);
24
- assert.equal(piUpdateHelpSupportsAll(" --all Update pi and installed packages"), true);
25
- assert.equal(piUpdateHelpSupportsAll("Usage: pi update [--self] [--extensions]"), false);
26
- assert.equal(piUpdateHelpSupportsAll(" --allow-project-files"), false, "similar option names must not count as --all");
27
-
28
- assert.equal(piUpdateCommandText(), "pi update --self");
29
- assert.equal(piUpdateCommandText({ all: true, supportsAll: true }), "pi update --all");
30
- assert.equal(piUpdateCommandText({ all: true }), "pi update --self && pi update --extensions");
31
-
32
- const [server, app, readme] = await Promise.all([
33
- readFile(join(packageRoot, "bin", "pi-webui.mjs"), "utf8"),
34
- readFile(join(packageRoot, "public", "app.js"), "utf8"),
35
- readFile(join(packageRoot, "README.md"), "utf8"),
2
+ import { exactNpmInstallArgs, exactPackageSpec, updatePlanConfirmationText } from "../lib/update-commands.mjs";
3
+
4
+ assert.equal(exactPackageSpec("@firstpick/pi-package-webui", "v1.2.3"), "@firstpick/pi-package-webui@1.2.3");
5
+ for (const version of ["latest", "next", "1", "1.2", "", "1.2.x"]) assert.throws(() => exactPackageSpec("pkg", version), /exact version/);
6
+ const args = exactNpmInstallArgs({ installRoot: "/agent/webui/runtimes/1.2.3", packageName: "@firstpick/pi-package-webui", version: "1.2.3", registry: "https://registry.npmjs.org" });
7
+ assert.deepEqual(args, [
8
+ "install", "--prefix", "/agent/webui/runtimes/1.2.3", "--ignore-scripts", "--no-save", "--package-lock=false",
9
+ "--registry", "https://registry.npmjs.org/", "@firstpick/pi-package-webui@1.2.3",
36
10
  ]);
37
- assert.match(server, /async function piUpdateCommandSupportsAll\(command\)[\s\S]*piUpdateHelpSupportsAll/, "server should inspect update help from the selected Pi command");
38
- assert.match(server, /resolveCommand\(\["update", "--help"\]\)[\s\S]*piUpdateCommandSteps\(\{ all, supportsAll \}\)/, "server should plan commands from the capability result");
39
- assert.match(server, /const piTasks = await resolvePiUpdateCommands\(\{ all \}\)/, "all-mode task resolution should preserve the selected Pi update plan");
40
- assert.match(server, /function resolveSelectedPiCommand\(piArgs\)[\s\S]*resolvePiCommandInvocation\(options\.piBin, piArgs\)/, "selected Windows Pi shims should be normalized to an executable Node and CLI invocation");
41
- assert.match(server, /resolveCommandDirectory\(options\.piBin\)[\s\S]*piInstallDirectory[\s\S]*env: piInstallDirectory \? prependedPathEnvironment\(piInstallDirectory\)/, "Pi update tasks should put the selected Pi installation first on PATH");
42
- assert.match(server, /preferredDirectories: \[\.\.\.new Set\(piTasks\.map\(\(task\) => task\.piInstallDirectory\)/, "package-root updates should prefer npm from the selected Pi installation");
43
- assert.match(server, /async function runUpdateTask\(task\)[\s\S]*env: task\.env/, "update task execution should apply its install-aware environment");
44
- assert.match(server, /allCommand: piUpdateCommandText\(\{ all: true, supportsAll: true \}\)[\s\S]*allFallbackCommand: piUpdateCommandText\(\{ all: true \}\)/, "update status should expose preferred and fallback command text");
45
- assert.match(app, /"pi update --all" when supported, otherwise "pi update --self" followed by "pi update --extensions"/, "update confirmation should describe capability selection and fallback");
46
- assert.match(readme, /first checks the selected Pi executable's `pi update --help`[\s\S]*uses `pi update --all` when advertised[\s\S]*otherwise falls back/, "documentation should explain the checked fallback behavior");
47
-
11
+ assert.doesNotMatch(args.join(" "), /@latest|--all|--extensions|min-release-age/);
12
+ assert.throws(() => exactNpmInstallArgs({ installRoot: "/tmp", packageName: "pkg", version: "1.2.3", registry: "https://user:secret@example.test" }), /credential-free/);
13
+ const digest = "f".repeat(64);
14
+ const confirmation = updatePlanConfirmationText({ transactionId: "tx", digest, targets: [{ id: "pi", currentVersion: "1.0.0", targetVersion: "1.1.0" }], refusals: [{ id: "webui", guidance: "Source checkouts are never mutated automatically." }] });
15
+ assert.match(confirmation, /pi 1\.0\.0 → 1\.1\.0/);
16
+ assert.match(confirmation, /Source checkouts/);
17
+ assert.match(confirmation, new RegExp(digest));
48
18
  console.log("update command planning tests passed");
@@ -0,0 +1,22 @@
1
+ import assert from "node:assert/strict";
2
+ import { access, mkdtemp, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { fileURLToPath } from "node:url";
7
+ import { executeCommand } from "../lib/update/executor.mjs";
8
+
9
+ const root = await mkdtemp(path.join(tmpdir(), "pi-webui-update-tree-"));
10
+ const sentinel = path.join(root, "descendant-sentinel.txt");
11
+ const fixture = fileURLToPath(new URL("./fixtures/update/tree-timeout-parent.mjs", import.meta.url));
12
+ try {
13
+ const result = await executeCommand(process.execPath, [fixture, sentinel], { timeoutMs: 300, closeTimeoutMs: 5_000 });
14
+ assert.equal(result.timedOut, true);
15
+ assert.equal(result.closureTimedOut, false, `timed-out command should close after tree termination: ${JSON.stringify(result)}`);
16
+ assert.deepEqual(result.args, [fixture, sentinel], "executor preserves argument arrays");
17
+ await delay(1_100);
18
+ await assert.rejects(access(sentinel), { code: "ENOENT" }, "a timed-out descendant must not survive to write its delayed sentinel");
19
+ console.log("update-executor-process-tree-harness.test.mjs passed");
20
+ } finally {
21
+ await rm(root, { recursive: true, force: true });
22
+ }
@@ -0,0 +1,59 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import {
6
+ acquireInstallLock, createUpdateJournal, readUpdateJournal, reconcileInterruptedUpdates,
7
+ releaseInstallLock, transferInstallLock, transitionUpdateJournal, updateStatePaths,
8
+ } from "../lib/update/journal.mjs";
9
+
10
+ const agentDir = await mkdtemp(path.join(tmpdir(), "pi-webui-update-journal-"));
11
+ const plan = (transactionId) => ({ schemaVersion: 1, transactionId, digest: "a".repeat(64), targets: [] });
12
+ try {
13
+ let journal = await createUpdateJournal(agentDir, plan("tx-transition"));
14
+ assert.equal(journal.state, "planned");
15
+ journal = await transitionUpdateJournal(agentDir, "tx-transition", "applying");
16
+ journal = await transitionUpdateJournal(agentDir, "tx-transition", "verifying", { receipts: [{ targetId: "pi", status: "success" }] });
17
+ journal = await transitionUpdateJournal(agentDir, "tx-transition", "success");
18
+ assert.deepEqual(journal.history.map((item) => item.state), ["planned", "applying", "verifying", "success"]);
19
+ assert.equal((await readUpdateJournal(agentDir, "tx-transition")).state, "success");
20
+ await assert.rejects(transitionUpdateJournal(agentDir, "tx-transition", "applying"), { code: "UPDATE_JOURNAL_TRANSITION" });
21
+
22
+ if (process.platform !== "win32") {
23
+ const mode = (await stat(path.join(updateStatePaths(agentDir).updatesDir, "tx-transition.json"))).mode & 0o777;
24
+ assert.equal(mode, 0o600, "journal files should be private");
25
+ }
26
+
27
+ const first = await acquireInstallLock(agentDir);
28
+ await assert.rejects(acquireInstallLock(agentDir), { code: "UPDATE_LOCKED" });
29
+ assert.equal(await releaseInstallLock({ ...first, token: "wrong-owner" }), false);
30
+ const transferred = await transferInstallLock(first, 424240);
31
+ assert.equal(transferred.pid, 424240, "activation helpers should become the persisted lock owner before the parent exits");
32
+ assert.equal(JSON.parse(await readFile(first.path, "utf8")).pid, 424240);
33
+ assert.equal(await releaseInstallLock(transferred), true);
34
+
35
+ const paths = updateStatePaths(agentDir);
36
+ const old = new Date(Date.now() - 60_000).toISOString();
37
+ await writeFile(paths.installLock, `${JSON.stringify({ schemaVersion: 1, token: "stale", pid: 424242, acquiredAt: old })}\n`, { mode: 0o600 });
38
+ const recoveredLock = await acquireInstallLock(agentDir, { staleAfterMs: 1_000, isProcessAlive: () => false });
39
+ assert.notEqual(recoveredLock.token, "stale", "definitely dead stale lock should be replaced");
40
+ await releaseInstallLock(recoveredLock);
41
+
42
+ await writeFile(paths.installLock, `${JSON.stringify({ schemaVersion: 1, token: "uncertain", pid: 424243, acquiredAt: old })}\n`, { mode: 0o600 });
43
+ await assert.rejects(acquireInstallLock(agentDir, { staleAfterMs: 1_000, isProcessAlive: () => true }), { code: "UPDATE_LOCKED" }, "an old but live/uncertain lock must fail closed");
44
+ await rm(paths.installLock, { force: true });
45
+
46
+ await createUpdateJournal(agentDir, plan("tx-interrupted"));
47
+ await transitionUpdateJournal(agentDir, "tx-interrupted", "applying");
48
+ await transitionUpdateJournal(agentDir, "tx-interrupted", "verifying");
49
+ await transitionUpdateJournal(agentDir, "tx-interrupted", "activating");
50
+ const reconciled = await reconcileInterruptedUpdates(agentDir, { recover: async (entry) => ({ state: "rolled-back", error: `Recovered ${entry.transactionId}` }) });
51
+ assert.equal(reconciled.length, 1);
52
+ assert.equal(reconciled[0].state, "rolled-back");
53
+ assert.equal(reconciled[0].reconciled, true);
54
+ assert.match(reconciled[0].error, /Recovered tx-interrupted/);
55
+ assert.doesNotMatch(await readFile(path.join(paths.updatesDir, "tx-interrupted.json"), "utf8"), /\.tmp/);
56
+ console.log("update-journal-harness.test.mjs passed");
57
+ } finally {
58
+ await rm(agentDir, { recursive: true, force: true });
59
+ }
@@ -0,0 +1,46 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { mkdtemp, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { acquireInstallLock, releaseInstallLock } from "../lib/update/journal.mjs";
8
+
9
+ if (process.argv[2] === "--contender") {
10
+ const root = process.argv[3];
11
+ const holdMs = Number.parseInt(process.argv[4], 10);
12
+ try {
13
+ const lock = await acquireInstallLock(root);
14
+ process.stdout.write("acquired\n");
15
+ await new Promise((resolve) => setTimeout(resolve, holdMs));
16
+ await releaseInstallLock(lock);
17
+ process.exit(0);
18
+ } catch (error) {
19
+ process.stdout.write(`${error.code || "error"}\n`);
20
+ process.exit(error.code === "UPDATE_LOCKED" ? 2 : 3);
21
+ }
22
+ }
23
+
24
+ function contender(root, holdMs) {
25
+ return new Promise((resolve) => {
26
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), "--contender", root, String(holdMs)], { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
27
+ let output = "";
28
+ child.stdout.on("data", (chunk) => { output += chunk; });
29
+ child.stderr.on("data", (chunk) => { output += chunk; });
30
+ child.on("exit", (code) => resolve({ code, output }));
31
+ });
32
+ }
33
+
34
+ const root = await mkdtemp(path.join(tmpdir(), "pi-webui-lock-process-"));
35
+ try {
36
+ const firstPromise = contender(root, 700);
37
+ await new Promise((resolve) => setTimeout(resolve, 150));
38
+ const second = await contender(root, 0);
39
+ const first = await firstPromise;
40
+ assert.equal(first.code, 0, first.output);
41
+ assert.equal(second.code, 2, second.output);
42
+ assert.match(second.output, /UPDATE_LOCKED/);
43
+ } finally {
44
+ await rm(root, { recursive: true, force: true });
45
+ }
46
+ console.log("update lock multiprocess harness passed");
@@ -0,0 +1,27 @@
1
+ import assert from "node:assert/strict";
2
+ import path from "node:path";
3
+ import { classifyPackageOwner, ownershipRefusalGuidance } from "../lib/update/owners.mjs";
4
+
5
+ const ownerRoot = path.resolve("tmp", "agent", "npm", "node_modules");
6
+ const packageRoot = path.join(ownerRoot, "@firstpick", "pi-package-webui");
7
+ for (const manager of ["npm", "bun"]) {
8
+ const owner = classifyPackageOwner({ manager, ownerRoot, packageRoot, topLevel: true });
9
+ assert.equal(owner.accepted, true, `${manager} exact top-level ownership should be accepted`);
10
+ assert.equal(owner.manager, manager);
11
+ }
12
+ const delegatedPi = classifyPackageOwner({ manager: "pi", ownerRoot: packageRoot, packageRoot, topLevel: true });
13
+ assert.equal(delegatedPi.accepted, true, "an exact verified Pi executable may own its delegated self-update");
14
+ assert.equal(delegatedPi.manager, "pi");
15
+ for (const manager of ["pnpm", "yarn", "unknown"]) {
16
+ const owner = classifyPackageOwner({ manager, ownerRoot, packageRoot });
17
+ assert.equal(owner.accepted, false);
18
+ assert.equal(owner.code, manager === "unknown" ? "unknown" : manager);
19
+ assert.ok(owner.guidance.length > 10 && owner.guidance.length <= 320);
20
+ }
21
+ assert.equal(classifyPackageOwner({ manager: "npm", ownerRoot, packageRoot, linked: true }).code, "linked");
22
+ assert.equal(classifyPackageOwner({ manager: "npm", ownerRoot, packageRoot, sourceCheckout: true }).code, "source");
23
+ assert.equal(classifyPackageOwner({ manager: "npm", ownerRoot, packageRoot, topLevel: false }).code, "nested");
24
+ assert.equal(classifyPackageOwner({ manager: "npm", ownerRoot, packageRoot, optional: true, piOwned: false }).code, "optional");
25
+ assert.equal(classifyPackageOwner({ manager: "npm", ownerRoot, packageRoot: path.resolve("tmp", "other") }).code, "opaque");
26
+ assert.match(ownershipRefusalGuidance("source"), /never mutated automatically/i);
27
+ console.log("update-owners.test.mjs passed");
@@ -0,0 +1,58 @@
1
+ import assert from "node:assert/strict";
2
+ import path from "node:path";
3
+ import { assertPlanIdentity, assertUpdatePlanDigest, createUpdatePlan, digestUpdatePlan } from "../lib/update/plan.mjs";
4
+
5
+ const ownerRoot = path.resolve("tmp", "agent", "npm", "node_modules");
6
+ let movingLatest = "2.0.0";
7
+ let resolutions = 0;
8
+ const identity = { canonicalId: "pi:/agent/pi-cli.js", version: "1.0.0" };
9
+ const plan = await createUpdatePlan({
10
+ transactionId: "moving-latest",
11
+ createdAt: "2026-08-07T00:00:00.000Z",
12
+ registry: "https://registry.example.invalid/",
13
+ identities: [identity],
14
+ candidates: [{
15
+ id: "pi",
16
+ kind: "pi",
17
+ packageName: "@earendil-works/pi-coding-agent",
18
+ identityId: identity.canonicalId,
19
+ currentVersion: "1.0.0",
20
+ requested: "latest",
21
+ owner: { manager: "npm", ownerRoot, packageRoot: path.join(ownerRoot, "@earendil-works", "pi-coding-agent") },
22
+ commandForVersion: async (exact, registry) => ({ command: "npm", args: ["install", `@earendil-works/pi-coding-agent@${exact}`, "--registry", registry] }),
23
+ }, {
24
+ id: "optional:statsCommand",
25
+ kind: "optional",
26
+ packageName: "@firstpick/pi-extension-stats",
27
+ identityId: identity.canonicalId,
28
+ currentVersion: "1.0.0",
29
+ requested: "latest",
30
+ owner: { manager: "pi", ownerRoot, packageRoot: path.join(ownerRoot, "@firstpick", "pi-extension-stats"), optional: true, piOwned: true },
31
+ commandForVersion: async (exact) => ({ command: "pi", args: ["install", `npm:@firstpick/pi-extension-stats@${exact}`] }),
32
+ }, {
33
+ id: "source-addon",
34
+ packageName: "example-source-addon",
35
+ currentVersion: "1.0.0",
36
+ owner: { manager: "npm", ownerRoot, packageRoot: path.resolve("source"), sourceCheckout: true },
37
+ commandForVersion: () => assert.fail("refused targets must not get commands"),
38
+ }],
39
+ resolveExactTarget: async ({ requested }) => {
40
+ resolutions += 1;
41
+ assert.equal(requested, "latest");
42
+ return { version: movingLatest, metadata: { integrity: "sha512-fixture" } };
43
+ },
44
+ });
45
+ assert.equal(resolutions, 2);
46
+ assert.equal(plan.targets[0].targetVersion, "2.0.0");
47
+ assert.deepEqual(plan.targets[0].command.args, ["install", "@earendil-works/pi-coding-agent@2.0.0", "--registry", "https://registry.example.invalid/"]);
48
+ assert.deepEqual(plan.targets[1].command.args, ["install", "npm:@firstpick/pi-extension-stats@2.0.0"], "Pi-owned optional packages should retain exact targets inside the same digest-bound plan");
49
+ assert.equal(plan.refusals[0].code, "source");
50
+ assertUpdatePlanDigest(plan, plan.digest);
51
+ assert.equal(plan.digest, digestUpdatePlan(plan));
52
+ assertPlanIdentity(plan.targets[0], identity);
53
+
54
+ movingLatest = "3.0.0";
55
+ assert.equal(plan.targets[0].targetVersion, "2.0.0", "confirmation remains bound to the originally resolved exact target");
56
+ assert.throws(() => assertUpdatePlanDigest({ ...plan, targets: [{ ...plan.targets[0], targetVersion: movingLatest }] }, plan.digest), { code: "UPDATE_PLAN_DIGEST_MISMATCH" });
57
+ assert.throws(() => assertPlanIdentity(plan.targets[0], { canonicalId: "pi:/different/cli.js" }), { code: "UPDATE_IDENTITY_CHANGED" });
58
+ console.log("update-plan.test.mjs passed");