@firstpick/pi-package-webui 0.8.5 → 0.8.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +18 -584
  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 +933 -554
  5. package/index.ts +16 -6
  6. package/lib/component-update-state.mjs +21 -0
  7. package/lib/git-workflow-preferences.mjs +20 -2
  8. package/lib/optional-feature-catalog.mjs +1 -0
  9. package/lib/sampling-parameter-capabilities.mjs +160 -0
  10. package/lib/session-summary-core.mjs +4 -3
  11. package/lib/session-summary-preferences.mjs +16 -1
  12. package/lib/subagent-launch-slots.mjs +14 -2
  13. package/lib/trust-boundaries.mjs +16 -0
  14. package/lib/update/executor.mjs +99 -0
  15. package/lib/update/journal.mjs +175 -0
  16. package/lib/update/owners.mjs +70 -0
  17. package/lib/update/plan.mjs +134 -0
  18. package/lib/update/resolver.mjs +168 -0
  19. package/lib/update/supervisor.mjs +238 -0
  20. package/lib/update/verify.mjs +52 -0
  21. package/lib/update-commands.mjs +25 -13
  22. package/lib/webui-workspaces.mjs +17 -1
  23. package/lib/workspace-session-summaries.mjs +400 -0
  24. package/package.json +4 -4
  25. package/public/app.js +2487 -349
  26. package/public/index.html +200 -51
  27. package/public/middle-button-drag-scroll.mjs +154 -0
  28. package/public/sampling-parameter-controls.mjs +361 -0
  29. package/public/service-worker.js +5 -1
  30. package/public/stream-output-controller.mjs +327 -0
  31. package/public/styles.css +666 -71
  32. package/public/theme-contract.mjs +244 -0
  33. package/session-summary.ts +164 -4
  34. package/tests/aur-review-widget-static.test.mjs +2 -1
  35. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  36. package/tests/browser/control-deck-component-updates.spec.mjs +20 -22
  37. package/tests/browser/interaction-continuity.spec.mjs +2 -2
  38. package/tests/browser/middle-button-drag-scroll.spec.mjs +145 -0
  39. package/tests/browser/persistent-ui-layout.spec.mjs +68 -23
  40. package/tests/browser/sampling-tooltip.spec.mjs +228 -0
  41. package/tests/browser/session-summary.spec.mjs +131 -3
  42. package/tests/browser/stream-output-isolation.spec.mjs +510 -0
  43. package/tests/browser/update-reconnect.spec.mjs +92 -0
  44. package/tests/codex-fast-mode-static.test.mjs +2 -2
  45. package/tests/common-options-submenus-interaction-static.test.mjs +172 -0
  46. package/tests/common-options-submenus-markup-static.test.mjs +152 -0
  47. package/tests/component-update-api-static.test.mjs +22 -61
  48. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  49. package/tests/control-deck-component-updates-static.test.mjs +13 -237
  50. package/tests/durable-rpc-supervisor-harness.test.mjs +3 -1
  51. package/tests/fast-mode-client-static.test.mjs +3 -2
  52. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  53. package/tests/feature-system-prompt-optional-feature-static.test.mjs +49 -0
  54. package/tests/fixtures/fake-pi.mjs +269 -2
  55. package/tests/fixtures/update/tree-timeout-descendant.mjs +6 -0
  56. package/tests/fixtures/update/tree-timeout-parent.mjs +11 -0
  57. package/tests/git-footer-context-menu-static.test.mjs +58 -0
  58. package/tests/git-workflow-preferences.test.mjs +7 -1
  59. package/tests/guided-git-aur-review.test.mjs +4 -3
  60. package/tests/http-endpoints-harness.test.mjs +274 -23
  61. package/tests/middle-button-drag-scroll-static.test.mjs +24 -0
  62. package/tests/middle-button-drag-scroll.test.mjs +170 -0
  63. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  64. package/tests/mobile-foundation-static.test.mjs +5 -6
  65. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  66. package/tests/mobile-static.test.mjs +85 -50
  67. package/tests/native-parity.test.mjs +1 -1
  68. package/tests/open-issue-wizard-static.test.mjs +2 -3
  69. package/tests/optional-feature-migration-frontend.test.mjs +9 -5
  70. package/tests/persistent-ui-layout-static.test.mjs +13 -2
  71. package/tests/questionnaire-dialog.test.mjs +3 -3
  72. package/tests/remote-auth-settings-harness.test.mjs +43 -0
  73. package/tests/rpc-supervisor-host.test.mjs +11 -2
  74. package/tests/safety-guard-auto-review-harness.test.mjs +117 -0
  75. package/tests/safety-guard-auto-review-static.test.mjs +34 -0
  76. package/tests/sampling-native-controls-user-flow.test.mjs +752 -0
  77. package/tests/sampling-parameter-capabilities.test.mjs +167 -0
  78. package/tests/sampling-parameter-controls.test.mjs +241 -0
  79. package/tests/session-sampling-helper.test.mjs +228 -0
  80. package/tests/session-sampling-http.test.mjs +168 -0
  81. package/tests/session-sampling-ui-static.test.mjs +370 -0
  82. package/tests/session-summary-core.test.mjs +205 -10
  83. package/tests/side-panel-section-height-removal-static.test.mjs +34 -0
  84. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  85. package/tests/staged-content-hash-contract.test.mjs +52 -11
  86. package/tests/stream-lifecycle-core.test.mjs +134 -0
  87. package/tests/stream-output-controller.test.mjs +252 -0
  88. package/tests/stream-output-isolation-static.test.mjs +89 -0
  89. package/tests/streaming-ui-coupling.test.mjs +50 -0
  90. package/tests/subagent-gate-visibility.test.mjs +1 -1
  91. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  92. package/tests/subagent-launch-slots.test.mjs +18 -1
  93. package/tests/theme-contract.test.mjs +104 -0
  94. package/tests/theme-customizer-static.test.mjs +82 -0
  95. package/tests/theme-scheme-mode.test.mjs +15 -0
  96. package/tests/ui-layout-settings.test.mjs +18 -1
  97. package/tests/update-api-harness.test.mjs +111 -0
  98. package/tests/update-commands.test.mjs +15 -45
  99. package/tests/update-executor-process-tree-harness.test.mjs +22 -0
  100. package/tests/update-journal-harness.test.mjs +59 -0
  101. package/tests/update-lock-multiprocess-harness.test.mjs +46 -0
  102. package/tests/update-owners.test.mjs +27 -0
  103. package/tests/update-plan.test.mjs +58 -0
  104. package/tests/update-resolver.test.mjs +56 -0
  105. package/tests/update-supervisor-harness.test.mjs +57 -0
  106. package/tests/update-tab-restore-harness.test.mjs +24 -0
  107. package/tests/update-verify.test.mjs +31 -0
  108. package/tests/workspace-files-live-updates-static.test.mjs +13 -4
  109. package/tests/workspace-session-summaries.test.mjs +288 -0
  110. package/webui-rpc-helper.mjs +119 -0
@@ -0,0 +1,82 @@
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 { REQUIRED_THEME_TOKENS, THEME_TOKEN_GROUPS } from "../public/theme-contract.mjs";
6
+
7
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
8
+ const [app, html, css, serviceWorker, pkg, readme] = await Promise.all([
9
+ readFile(join(root, "public", "app.js"), "utf8"),
10
+ readFile(join(root, "public", "index.html"), "utf8"),
11
+ readFile(join(root, "public", "styles.css"), "utf8"),
12
+ readFile(join(root, "public", "service-worker.js"), "utf8"),
13
+ readFile(join(root, "package.json"), "utf8"),
14
+ readFile(join(root, "README.md"), "utf8"),
15
+ ]);
16
+
17
+ assert.equal(THEME_TOKEN_GROUPS.length, 7, "customizer contract should expose seven labelled groups");
18
+ assert.equal(REQUIRED_THEME_TOKENS.length, 51, "customizer contract should expose exactly 51 required tokens");
19
+ assert.equal(new Set(REQUIRED_THEME_TOKENS).size, 51, "required customizer tokens should be unique");
20
+
21
+ assert.match(html, /id="themeCustomizeButton"[^>]*aria-haspopup="dialog"[^>]*aria-controls="themeCustomizerDialog"/, "theme controls should expose an accessible Customize dialog launcher");
22
+ assert.match(html, /<dialog id="themeCustomizerDialog"[^>]*aria-labelledby="themeCustomizerTitle"[^>]*aria-describedby="themeCustomizerDescription"/, "customizer should use a labelled native dialog");
23
+ for (const id of [
24
+ "themeCustomizerName", "themeCustomizerScope", "themeCustomizerVisualFields", "themeCustomizerThinkingMax",
25
+ "themeCustomizerVars", "themeCustomizerExportFields", "themeCustomizerJson", "themeCustomizerPreview",
26
+ "themeCustomizerStatus", "themeCustomizerCancelButton", "themeCustomizerResetButton", "themeCustomizerSaveButton",
27
+ "themeCustomizerOverwrite", "themeCustomizerOverwriteButton",
28
+ ]) {
29
+ assert.match(html, new RegExp(`id="${id}"`), `customizer should expose #${id}`);
30
+ }
31
+ assert.match(html, /<option id="themeCustomizerProjectOption" value="project">This project<\/option>[\s\S]*<option value="global">Global themes<\/option>/, "save destination should offer project and global scopes");
32
+ assert.match(html, /role="status" aria-live="polite" aria-atomic="true"/, "customizer should expose an atomic polite validation surface");
33
+ assert.match(html, /role="alert" hidden>[\s\S]*Replace this exact target\?/, "overwrite should use a hidden-until-needed alert naming the target");
34
+
35
+ assert.match(app, /from "\.\/theme-contract\.mjs"/, "frontend should consume the shared browser-safe theme contract");
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-v81"/, "adding the theme contract to the startup graph should advance the PWA cache identity");
38
+ assert.match(pkg, /node --check public\/theme-contract\.mjs/, "the package check should syntax-check the startup-critical theme contract");
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
+ assert.match(app, /for \(const \{ name, label \} of group\.tokens\)/, "visual controls should render from the exact shared token inventory");
41
+ assert.match(app, /row\.dataset\.themeToken = name/, "every required token should receive a stable visual row");
42
+ assert.match(app, /swatch\.type = "color"[\s\S]*value\.type = "text"/, "each visual row should pair a color picker with a raw Pi value control");
43
+ assert.match(app, /const direct = \/\^#\[0-9a-f\]\{6\}\$\/i\.test\(raw\)[\s\S]*swatch\.disabled = !direct[\s\S]*Terminal default; edit the value to replace it/, "variable and terminal-default values should not be silently flattened by the color picker");
44
+ assert.match(app, /validateTheme\(candidate, \{ allowWebuiExport: true \}\)/, "client feedback should validate through the shared contract");
45
+ assert.match(app, /Advanced JSON is invalid:[\s\S]*last valid preview remains active/, "invalid JSON should stay editable without replacing the valid preview");
46
+ assert.match(app, /acceptThemeCustomizerDraft\(candidate, \{ syncJson: false, syncControls: true \}\)/, "valid JSON should synchronize back to visual and optional controls");
47
+ assert.match(app, /elements\.themeCustomizerJson\.value = serializeTheme\(canonical/, "valid visual changes should synchronize canonical advanced JSON");
48
+ assert.match(app, /applyTheme\(canonical, \{ persist: false \}\)/, "live preview must use the non-persisting apply path");
49
+ assert.match(app, /themeColorToRgb\(value, theme\?\.vars \|\| \{\}, fallback\)/, "WebUI preview should convert integer xterm colors through the shared contract");
50
+
51
+ assert.match(app, /function restoreThemeCustomizerOpeningState\(generation\)[\s\S]*state\.generation !== generation[\s\S]*applyTheme\(state\.opening\.theme, \{ persist: false \}\)[\s\S]*setCustomBackgroundRecord\(state\.opening\.background\)[\s\S]*applyCustomBackgroundOverride\(\)/, "cancel should generation-guard restoration of theme, meta/scheme presentation, and custom background");
52
+ assert.match(app, /themeCustomizerDialog\?\.addEventListener\("cancel"[\s\S]*closeThemeCustomizer\(\{ restore: true \}\)/, "Escape should restore and close through the same cancel path");
53
+ assert.match(app, /async function switchTab\(tabId\)[\s\S]*if \(themeCustomizerState\) closeThemeCustomizer\(\{ restore: true \}\)[\s\S]*refreshThemeCatalog\(tabContext\)/, "tab switches should restore an open preview and refresh project-bound catalog metadata");
54
+ assert.doesNotMatch(app.slice(app.indexOf("function themeScopeLabel("), app.indexOf("function renderThemeSelect(")), /localStorage\.(?:setItem|removeItem)/, "customizer preview/save workflow must not mutate browser theme storage directly");
55
+
56
+ assert.match(app, /api\("\/api\/themes\/custom", \{[\s\S]*tabId: state\.tabContext\.tabId[\s\S]*scope,[\s\S]*fileName: `\$\{name\}\.json`[\s\S]*overwrite,[\s\S]*expectedMtimeMs:/, "save should bind the server-derived target to the opening active tab and explicit scope");
57
+ assert.match(app, /state\.overwrite = \{ signature: themeCustomizerDraftSignature\(state\), scope, fileName, mtimeMs: details\.mtimeMs \}/, "overwrite confirmation should bind target, draft signature, and server mtime");
58
+ assert.match(app, /invalidateThemeCustomizerOverwrite\(\);[\s\S]*Any draft, name, or destination change cancels this confirmation/, "editing should invalidate overwrite confirmation");
59
+ assert.match(app, /code === "THEME_CHANGED"[\s\S]*was not overwritten[\s\S]*fresh target-bound confirmation/, "stale overwrite should stop and require fresh confirmation");
60
+ assert.match(app, /themeCustomizerCancelButton\.disabled = !!state\?\.saving[\s\S]*themeCustomizerResetButton\.disabled = !!state\?\.saving/, "cancel and reset should be disabled while a theme save is in flight");
61
+ assert.match(app, /function closeThemeCustomizer[\s\S]*if \(state\.saving\)[\s\S]*Wait for the theme save to finish/, "closing should not imply an in-flight filesystem save was cancelled");
62
+ assert.match(app, /function setThemeCustomizerStatus[\s\S]*urgent \? "alert" : "status"[\s\S]*urgent \? "assertive" : "polite"/, "blocking customizer errors should use assertive alert semantics");
63
+ assert.match(app, /code === "THEME_EXISTS"\) showThemeCustomizerOverwrite/, "same-target conflicts should enter explicit overwrite UI");
64
+ assert.match(app, /theme\.custom[\s\S]*theme-scope-badge/, "custom search results should receive scope badges");
65
+ assert.match(app, /Saved \$\{response\.data\?\.fileName[\s\S]*run \/reload or restart[\s\S]*No Pi or browser theme setting was changed/, "save guidance should truthfully describe manual TUI reload and non-mutation");
66
+
67
+ assert.match(css, /\.theme-customizer-dialog \{[\s\S]*height: min\(92dvh, 58rem\)[\s\S]*overflow: hidden/, "desktop customizer should be viewport-bounded and internally scrollable");
68
+ assert.match(css, /\.theme-customizer-scroll \{[\s\S]*overflow-y: auto[\s\S]*overscroll-behavior: contain/, "long token controls should scroll inside the dialog");
69
+ assert.match(css, /\.theme-token-grid \{[\s\S]*grid-template-columns: repeat\(auto-fit, minmax\(min\(100%, 25rem\), 1fr\)\)/, "token columns should collapse based on their container before labels and inputs overlap");
70
+ assert.match(css, /\.theme-token-swatch-note \{[^}]*min-width: 0[^}]*overflow-wrap: anywhere/, "token helper text should wrap inside narrow rows");
71
+ assert.match(css, /\.theme-customizer-optional-fields fieldset \{[^}]*min-width: 0/, "optional field cards should be allowed to shrink inside the dialog");
72
+ assert.match(css, /\.theme-customizer-export-fields \{[\s\S]*grid-template-columns: repeat\(auto-fit, minmax\(min\(100%, 12rem\), 1fr\)\)/, "export color fields should wrap before their cards overflow");
73
+ assert.match(css, /\.theme-customizer-export-fields input \{[^}]*width: 100%[^}]*min-width: 0/, "export color inputs should stay within their grid tracks");
74
+ assert.match(css, /@media \(max-width: 720px\), \(pointer: coarse\) and \(hover: none\)[\s\S]*\.theme-customizer-dialog[\s\S]*width: 100vw[\s\S]*\.theme-token-grid,[\s\S]*grid-template-columns: minmax\(0, 1fr\)/, "phone/coarse layouts should become a safe one-column full-height editor");
75
+ assert.match(css, /\.extension-dialog\.theme-customizer-dialog \{[\s\S]*inset: 0;[\s\S]*height: var\(--visual-viewport-height, 100dvh\);[\s\S]*max-height: var\(--visual-viewport-height, 100dvh\);[\s\S]*overflow: hidden;[\s\S]*border-radius: 0;/, "the later generic mobile dialog rule must not override full-height customizer geometry");
76
+ assert.match(css, /\.theme-token-swatch \{[^}]*width: 44px[^}]*height: 44px/, "visual color targets should remain at least 44px");
77
+ assert.match(css, /env\(safe-area-inset-bottom\)/, "dialog actions should honor mobile safe-area insets");
78
+
79
+ assert.match(readme, /### Custom themes[\s\S]*exact 51 required theme tokens[\s\S]*last valid preview[\s\S]*This project[\s\S]*Global themes/, "README should document controls, validation, and both scopes");
80
+ assert.match(readme, /does not select the theme or mutate Pi\/browser settings[\s\S]*run `\/reload` or restart Pi/, "README should document non-persistence and truthful TUI activation");
81
+
82
+ console.log("theme-customizer-static: all assertions passed");
@@ -96,6 +96,21 @@ assert.match(
96
96
  /async function applySchemeTheme\(options = \{\}\) \{\s*await setThemeByName\(effectiveThemeName\(\), \{ \.\.\.options, persist: false \}\);\s*\}/,
97
97
  "applySchemeTheme must never persist",
98
98
  );
99
+ assert.match(
100
+ app,
101
+ /function acceptThemeCustomizerDraft\([\s\S]*?applyTheme\(canonical, \{ persist: false \}\)/,
102
+ "custom theme live preview must use a non-persisting apply path",
103
+ );
104
+ assert.match(
105
+ app,
106
+ /function restoreThemeCustomizerOpeningState\(generation\)[\s\S]*?applyTheme\(state\.opening\.theme, \{ persist: false \}\)/,
107
+ "customizer cancel must restore presentation without persisting a selection",
108
+ );
109
+ assert.doesNotMatch(
110
+ app.slice(app.indexOf("function themeScopeLabel("), app.indexOf("function renderThemeSelect(")),
111
+ /storeTheme(?:Name|Mode)|storeSchemeTheme|setThemeByName\([^;]*persist: true/,
112
+ "customizer internals must not bypass chooseTheme or mutate Light/Dark/Auto persistence",
113
+ );
99
114
 
100
115
  // Auto mode also works on MediaQueryList implementations without addEventListener
101
116
  // (legacy addListener API), matching the mobileViewMedia wiring.
@@ -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");
@@ -0,0 +1,56 @@
1
+ import assert from "node:assert/strict";
2
+ import path from "node:path";
3
+ import { resolveCanonicalPiRuntime, resolveWebuiRuntimeIdentity, sameRuntimeIdentity } from "../lib/update/resolver.mjs";
4
+
5
+ const bundledCli = "C:\\Agent\\npm\\node_modules\\@earendil-works\\pi-coding-agent\\dist\\cli.js";
6
+ const pathDir = "C:\\PathPi";
7
+ const pathCli = `${pathDir}\\node_modules\\@earendil-works\\pi-coding-agent\\dist\\cli.js`;
8
+ const explicitDir = "C:\\ExplicitPi";
9
+ const explicitShim = `${explicitDir}\\pi.cmd`;
10
+ const explicitCli = `${explicitDir}\\node_modules\\@earendil-works\\pi-coding-agent\\dist\\cli.js`;
11
+ const existing = new Set([bundledCli, `${pathDir}\\pi.CMD`, pathCli, explicitShim, explicitCli, `${pathDir}\\node.exe`, `${explicitDir}\\node.exe`, "C:\\Node\\node.exe"]);
12
+ const runtime = {
13
+ platform: "win32",
14
+ execPath: "C:\\Node\\node.exe",
15
+ env: { PATH: pathDir, PATHEXT: ".EXE;.CMD" },
16
+ existsSync: (candidate) => existing.has(path.win32.normalize(candidate)),
17
+ realpathSync: (candidate) => path.win32.normalize(candidate),
18
+ };
19
+ const calls = [];
20
+ async function runCommand(command, args, options) {
21
+ calls.push({ command, args, options });
22
+ const cli = args[0];
23
+ if (cli === bundledCli) return { exitCode: 0, stdout: "pi 1.2.3", stderr: "" };
24
+ if (path.win32.normalize(cli || "") === path.win32.normalize(pathCli)) return { exitCode: 0, stdout: "9.9.9", stderr: "" };
25
+ if (path.win32.normalize(cli || "") === path.win32.normalize(explicitCli)) return { exitCode: 0, stdout: "v2.4.6", stderr: "" };
26
+ return { exitCode: 1, stdout: "", stderr: "missing" };
27
+ }
28
+
29
+ const selected = await resolveCanonicalPiRuntime({ bundledCli, runCommand, runtime });
30
+ assert.equal(selected.active.source, "bundled");
31
+ assert.equal(selected.active.version, "1.2.3");
32
+ assert.equal(selected.path.source, "path");
33
+ assert.equal(selected.path.version, "9.9.9");
34
+ assert.notEqual(selected.active.canonicalId, selected.path.canonicalId, "a newer PATH Pi must remain separately reported and untouched");
35
+ assert.deepEqual(selected.active.invocation.args, [bundledCli], "JavaScript launchers preserve argument arrays through Node normalization");
36
+
37
+ const explicit = await resolveCanonicalPiRuntime({ explicitCommand: explicitShim, bundledCli, runCommand, runtime });
38
+ assert.equal(explicit.active.source, "explicit");
39
+ assert.equal(explicit.active.cliPath, explicitCli);
40
+ assert.deepEqual(explicit.active.invocation.args, [explicitCli], "Windows explicit shims normalize to their exact installation CLI");
41
+ assert.equal(explicit.path, null, "explicit identity does not silently consult PATH");
42
+
43
+ const opaque = await resolveCanonicalPiRuntime({ explicitCommand: "opaque-custom-pi", runCommand, runtime });
44
+ assert.equal(opaque.active, null);
45
+ assert.equal(opaque.refusal.code, "explicit-pi-unresolved");
46
+
47
+ const unsupported = await resolveCanonicalPiRuntime({ bundledCli: "C:\\Missing\\cli.js", pathCommand: "missing-pi", runCommand, runtime });
48
+ assert.equal(unsupported.active, null);
49
+ assert.equal(unsupported.refusal.code, "pi-runtime-unverifiable");
50
+
51
+ const webui = resolveWebuiRuntimeIdentity({ packageRoot: "C:\\Agent\\npm\\node_modules\\@firstpick\\pi-package-webui", packageName: "@firstpick/pi-package-webui", version: "v0.8.6" }, runtime);
52
+ assert.equal(webui.version, "0.8.6");
53
+ assert.equal(sameRuntimeIdentity(webui, { canonicalId: webui.canonicalId }), true);
54
+ assert.ok(calls.every((call) => Array.isArray(call.args)));
55
+ assert.ok(calls.every((call) => call.options?.timeoutMs === 10_000), "runtime probes should use the fail-closed ten-second budget by default");
56
+ console.log("update-resolver.test.mjs passed");