Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

make the windows installer static, quiet and ascii-clean (#3371)

kt19f0ea73701b
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 5582d19526..cd807bf92b 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -357,7 +357,19 @@ jobs:
shell: bash
run: echo "PY=$(command -v python3 || command -v python)" >> "$GITHUB_ENV"
# Only the shipped binary links here (the build-gnu/build-darwin rule).
+ # THE STATIC VC RUNTIME (the operator's real-machine report,
+ # 2026-10-06: the dynamically linked launcher died at process start -
+ # 0xC0000135, STATUS_DLL_NOT_FOUND, exit -1073741515 - on a stock
+ # Windows box, which carries no vcruntime140.dll; the windows-2022
+ # runner image has it, so the livecheck never sees the gap): the
+ # step-scoped RUSTFLAGS below links the shipped binary against the
+ # static CRT. The pin rides THIS STEP alone and never Cargo.toml,
+ # whose dev builds stay dynamic; cargo's unit fingerprints carry
+ # RUSTFLAGS, so a cache restored from the dynamic-link era rebuilds
+ # instead of reusing a dynamically linked tree.
- name: Build (release, locked)
+ env:
+ RUSTFLAGS: -C target-feature=+crt-static
run: cargo build --release --locked --target ${{ matrix.target }} -j 4 -p pa-cli --bin prime-agent
- name: "Livecheck gate: --version prints the tag version"
shell: bash
diff --git a/crates/pa-cli/tests/installer_platform_map.rs b/crates/pa-cli/tests/installer_platform_map.rs
index dba9c1c2ce..c401686647 100644
--- a/crates/pa-cli/tests/installer_platform_map.rs
+++ b/crates/pa-cli/tests/installer_platform_map.rs
@@ -197,3 +197,986 @@ fn install_ps1_carries_the_windows_contract() {
"the ps1 writes the funnel-readable install marker"
);
}
+
+/// install.ps1's download discipline: Invoke-WebRequest under the default
+/// Progress/Verbose preferences leaks the raw .NET transfer records onto
+/// the caller's console (the progress bar and the "Writing web request /
+/// Writing request stream..." verbose chatter), and under `irm | iex` the
+/// script shares the caller's session - the operator's real-machine report
+/// (2026-10-06). The installer pins both preferences to `SilentlyContinue`
+/// around its download calls, prints its own one-line progress instead
+/// (the file name plus the size, install-rust.sh's discipline), and
+/// restores the caller's values after: the quiet zone is the download,
+/// never the session.
+#[test]
+fn install_ps1_pins_the_download_preferences_around_the_downloads() {
+ let text = std::fs::read_to_string(repo_root().join("install.ps1")).expect("read install.ps1");
+ // The download block: the two staged file names through the checksum
+ // verify that follows it.
+ let block_start = text
+ .find("$tarball = Join-Path $download $expectedFile")
+ .expect("the download block stages the tarball");
+ let block_end = text
+ .find("$sumsLine = Get-Content")
+ .expect("the checksum verify follows the download");
+ let block = &text[block_start..block_end];
+ let markers: [(&str, &str); 8] = [
+ (
+ "save of the caller's progress preference",
+ "$callerProgressPreference = $ProgressPreference",
+ ),
+ (
+ "save of the caller's verbose preference",
+ "$callerVerbosePreference = $VerbosePreference",
+ ),
+ ("progress pin", "$ProgressPreference = 'SilentlyContinue'"),
+ ("verbose pin", "$VerbosePreference = 'SilentlyContinue'"),
+ (
+ "payload download",
+ "Save-Release -Uri \"$baseUrl/$releasePrefix/$expectedFile\" -OutFile $tarball",
+ ),
+ ("restore on the failure path too", "} finally {"),
+ (
+ "restore of the caller's progress preference",
+ "$ProgressPreference = $callerProgressPreference",
+ ),
+ (
+ "restore of the caller's verbose preference",
+ "$VerbosePreference = $callerVerbosePreference",
+ ),
+ ];
+ let mut positions: Vec<usize> = Vec::new();
+ for (what, marker) in markers {
+ positions.push(
+ block.find(marker).unwrap_or_else(|| {
+ panic!("the download block must carry its {what} line: {marker}")
+ }),
+ );
+ }
+ for pair in positions.windows(2) {
+ assert!(
+ pair[0] < pair[1],
+ "the download block's discipline is ordered save -> pin -> download -> restore"
+ );
+ }
+ // The installer's own progress: the download's name before it starts,
+ // the name plus the size after it lands (install-rust.sh's
+ // step_start/step_ok "Downloaded <MB>" discipline).
+ let download_at = positions[4];
+ let announcing = block
+ .find("Write-Host \"downloading $expectedFile\"")
+ .expect("the installer announces the download by name");
+ assert!(
+ announcing < download_at,
+ "the installer's own progress line prints before the download starts"
+ );
+ assert!(
+ block.contains("downloaded: $expectedFile") && block.contains("1MB"),
+ "the installer reports the downloaded file's name and size"
+ );
+}
+
+/// The installer's console output is ASCII-only: the Windows console's
+/// default codepage renders non-ASCII bytes as mojibake (the operator's
+/// 2026-10-06 report: an em-dash printed as an a-circumflex), so every
+/// string the installer EMITS - Write-Host, Write-Warning, and Fail's
+/// thrown message - must be plain ASCII. The script's comments and the
+/// launcher files it writes are out of scope: neither lands on the console.
+#[test]
+fn install_ps1_emits_only_ascii_output() {
+ let text = std::fs::read_to_string(repo_root().join("install.ps1")).expect("read install.ps1");
+ let mut offenders: Vec<(usize, &str)> = Vec::new();
+ for (index, line) in text.lines().enumerate() {
+ let trimmed = line.trim_start();
+ if trimmed.starts_with('#') {
+ continue;
+ }
+ let emits = line.contains("Write-Host")
+ || line.contains("Write-Warning")
+ || line.contains("Write-Error")
+ || line.contains("WriteErrorLine")
+ || trimmed.starts_with("Fail ")
+ || trimmed.starts_with("throw ");
+ if emits && !line.is_ascii() {
+ offenders.push((index + 1, trimmed));
+ }
+ }
+ assert!(
+ offenders.is_empty(),
+ "install.ps1 emits non-ASCII output (the Windows console mojibakes it): {offenders:?}"
+ );
+}
+
+/// The post-install smoke test's DLL-not-found class must not lie: a
+/// launcher that fails --version with 0xC0000135 (`STATUS_DLL_NOT_FOUND`,
+/// exit -1073741515) never started its process - a runtime DLL the binary
+/// links is missing - so the venv-bootstrap claim ("the first run
+/// bootstraps the kernel venv, re-run it") would send the user chasing a
+/// bootstrap that cannot fix a missing DLL. With the static-runtime build
+/// the class should not occur at all; if it does, the message must say
+/// what actually happened.
+#[test]
+fn install_ps1_names_the_dll_not_found_failure_honestly() {
+ let text = std::fs::read_to_string(repo_root().join("install.ps1")).expect("read install.ps1");
+ let verify_at = text
+ .find("# --- verify: the launcher must answer --version")
+ .expect("the smoke test section exists");
+ let dll_exit = text.find("-1073741515").expect(
+ "the smoke test must branch on the DLL-not-found exit code (0xC0000135, -1073741515)",
+ );
+ assert!(
+ dll_exit > verify_at,
+ "the DLL-not-found branch belongs to the smoke test"
+ );
+ let warning_at = text[dll_exit..]
+ .find("Write-Warning")
+ .expect("the DLL-not-found branch prints a warning");
+ let line_end = text[dll_exit + warning_at..]
+ .find('\n')
+ .map_or(text.len(), |at| dll_exit + warning_at + at);
+ let dll_warning = &text[dll_exit..line_end];
+ assert!(
+ dll_warning.contains("0xC0000135") && dll_warning.contains("runtime"),
+ "the DLL-not-found warning must name the missing runtime dependency:\n{dll_warning}"
+ );
+ assert!(
+ !dll_warning.contains("bootstraps the kernel venv"),
+ "the DLL-not-found class must not claim the kernel-venv bootstrap:\n{dll_warning}"
+ );
+ assert!(
+ text.contains("the first run bootstraps the kernel venv"),
+ "the non-DLL failure classes keep their honest venv-bootstrap hint"
+ );
+}
+
+/// install.ps1's PATH parity (the operator's smoothness ask, 2026-10-06):
+/// a Linux box almost always carries ~/.local/bin on PATH already, so the
+/// sh installer only prints a profile note - but a Windows box has no
+/// %USERPROFILE%\\.local\\bin, and a printed-only note leaves the fresh
+/// install unusable until the user edits their environment by hand.
+/// Windows HAS a canonical user-PATH setting (the registry's User scope,
+/// no admin needed), so the installer ADDS the launcher's bin dir there
+/// itself: idempotent (appended only when the entry is absent, never
+/// duplicated), mirrored into the CURRENT session so `prime-agent` works
+/// in the same console immediately, and the printed hint says a NEW
+/// terminal gets it automatically instead of telling the user to go edit
+/// the registry by hand.
+#[test]
+fn install_ps1_adds_bin_to_the_user_path_and_the_session_path() {
+ let text = std::fs::read_to_string(repo_root().join("install.ps1")).expect("read install.ps1");
+ let section_start = text
+ .find("# --- the PATH add")
+ .expect("the PATH-add section exists");
+ let section_end = text
+ .find("# --- verify: the launcher must answer --version")
+ .expect("the smoke test section exists");
+ let section = &text[section_start..section_end];
+ let markers: [(&str, &str); 13] = [
+ (
+ "the PATH-add targets: the launcher's bin dir, plus the custom uv target when the knob placed one (a documented install target must stay discoverable)",
+ "$pathDirs = @($bin)",
+ ),
+ (
+ "the custom uv dir joins the adds (deduped against the launcher's own bin: the packaged shape points both at the same dir)",
+ "if ($uvInstallDir -ne (Join-Path $HOME '.local\\bin') -and $uvInstallDir -ne $bin) { $pathDirs += $uvInstallDir }",
+ ),
+ (
+ "the any-append flag initialized OUTSIDE the loop (a write on any iteration must broadcast; a later no-op iteration must not suppress it)",
+ "$pathAdded = $false",
+ ),
+ ("the session PATH add", "$env:PATH = \"$env:PATH;$binDir\""),
+ (
+ "the registry key open (writable: the append needs it anyway)",
+ "[Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)",
+ ),
+ (
+ "the missing-key fallback (OpenSubKey returns null when HKCU\\Environment does not exist - a stripped profile - and the null would only print manual guidance; the key is created instead)",
+ "[Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')",
+ ),
+ (
+ "the RAW user PATH read (never [Environment]::GetEnvironmentVariable: it returns the EXPANDED value, and the flattened write-back would freeze %VAR%-style entries at this run's expansion)",
+ "[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames",
+ ),
+ (
+ "the kind read (a REG_EXPAND_SZ Path must stay REG_EXPAND_SZ: SetEnvironmentVariable flattens it to plain REG_SZ, dotnet/runtime#1442)",
+ "$envKey.GetValueKind('Path')",
+ ),
+ (
+ "the expanded copy for membership (a %USERPROFILE%\\..local\\bin-style RAW entry spells the same directory as the expanded $bin - the dedup must see it, or the idempotent add appends the directory twice)",
+ "[Environment]::ExpandEnvironmentVariables($rawUserPath)",
+ ),
+ (
+ "the idempotent absent check (a whole-entry compare on BOTH spellings, never a substring: a sibling entry like C:\\Tools\\bin-old must not mask C:\\Tools\\bin)",
+ "if (-not (Test-PathEntry $rawUserPath $binDir) -and -not (Test-PathEntry $expandedUserPath $binDir)) {",
+ ),
+ (
+ "the kind-preserving user PATH write",
+ "$envKey.SetValue('Path', $newUserPath, $rawUserKind)",
+ ),
+ ("the change broadcast", "SendMessageTimeout([IntPtr]0xffff"),
+ ("the new-terminal hint", "picks them up automatically"),
+ ];
+ let mut positions: Vec<usize> = Vec::new();
+ for (what, marker) in markers {
+ positions.push(
+ section
+ .find(marker)
+ .unwrap_or_else(|| panic!("the PATH section must carry its {what} line: {marker}")),
+ );
+ }
+ for pair in positions.windows(2) {
+ assert!(
+ pair[0] < pair[1],
+ "the PATH add's discipline is session first, then the durable user write: {markers:?}"
+ );
+ }
+ // The printed note never tells the user to edit their own PATH by hand
+ // anymore: the installer did it.
+ assert!(
+ !section.contains("add it for the prime-agent command"),
+ "the PATH note must not tell the user to edit their own PATH by hand"
+ );
+ // The flattened write route is gone: SetEnvironmentVariable turns a
+ // REG_EXPAND_SZ Path into plain REG_SZ with this run's expansion frozen
+ // in (the macroscope finding: %JAVA_HOME%-style entries stop following
+ // their variables).
+ assert!(
+ !section.contains("[Environment]::SetEnvironmentVariable('Path'"),
+ "the user PATH write must preserve the registry value's kind (never the flattening SetEnvironmentVariable route)"
+ );
+ // The durable add is best-effort (the macroscope finding): the session
+ // PATH already works and the payload is published, so a registry
+ // failure must degrade to the honest manual note - never abort the
+ // finished install.
+ assert!(
+ section.contains("could not persist the PATH entry to the user environment")
+ && section.contains("put this entry on the user PATH"),
+ "a registry failure in the PATH add must degrade to the honest manual note instead of failing the install"
+ );
+ // The broadcast reflects ANY append (the reviewer's finding): the flag
+ // initializes before the loop and never resets - a later no-op
+ // iteration must not suppress the WM_SETTINGCHANGE of an earlier one.
+ let flag_at = section
+ .find("$pathAdded = $false")
+ .expect("the any-append flag exists");
+ let loop_at = section
+ .find("foreach ($binDir in $pathDirs)")
+ .expect("the PATH-add loop");
+ assert!(
+ flag_at < loop_at,
+ "the any-append flag must initialize OUTSIDE (before) the loop"
+ );
+ assert!(
+ !section.contains("\n $pathAdded = $false"),
+ "the flag must never reset inside an iteration (an earlier append's broadcast would be lost)"
+ );
+}
+
+/// install-rust.sh's uv target honors the same knob install.ps1 does (the
+/// reviewer's finding: BOTH e2e routes must be isolatable - the sh route's
+/// Git Bash run would otherwise still write the shared ~/.local/bin): the
+/// operator-set dir wins, the Windows C:\ spelling normalizes through
+/// cygpath exactly like `PRIME_AGENT_RUST_PREFIX`, and the knob is
+/// documented in the header's Configuration block.
+#[test]
+fn install_rust_sh_honors_the_uv_bin_dir_knob() {
+ let text =
+ std::fs::read_to_string(repo_root().join("install-rust.sh")).expect("read install-rust.sh");
+ assert!(
+ text.contains("[ -n \"${PRIME_AGENT_UV_BIN_DIR:-}\" ]"),
+ "install-rust.sh must honor PRIME_AGENT_UV_BIN_DIR (both e2e routes isolate)"
+ );
+ assert!(
+ text.contains("cygpath -u \"$uv_bin_dir\""),
+ "the Windows spelling of the knob must normalize exactly like PRIME_AGENT_RUST_PREFIX"
+ );
+ assert!(
+ text.contains("# PRIME_AGENT_UV_BIN_DIR"),
+ "the knob must be documented in the header's Configuration block"
+ );
+ assert!(
+ text.contains("elif [ -x \"${HOME}/.local/bin/${uv_name}\" ] && [ \"$uv_under_store\" = \"no\" ]"),
+ "the sh's uv discovery must fall back to the canonical ~/.local/bin uv when the knob redirects the target (no duplicate install) - but NEVER in the store-alias shape (a uv inside the shared store must not carry uv's python writes back into it)"
+ );
+ assert!(
+ text.contains("uv_name=\"uv\"") && text.contains("uv_name=\"uv.exe\""),
+ "the sh's uv probes must use the platform executable name (uv.exe on Windows - the Git Bash route probes real Windows files)"
+ );
+ assert!(
+ !text.contains("[ -x \"${uv_bin_dir}/uv\" ]"),
+ "every target probe must use the platform uv name, never a bare /uv (uv.exe misses on Windows)"
+ );
+ assert!(
+ text.contains("case \"$uv_bin_dir\" in\n /*) ;;\n *) die \"PRIME_AGENT_UV_BIN_DIR must be an absolute path: ${PRIME_AGENT_UV_BIN_DIR}\" ;;\n esac"),
+ "a relative knob must be refused outright (a relative target in PATH guidance breaks every later shell)"
+ );
+ assert!(
+ text.contains("PRIME_AGENT_UV_BIN_DIR must not contain a colon"),
+ "the knob must refuse the PATH separator (a target with a colon corrupts every PATH export and prepend)"
+ );
+ assert!(
+ text.contains("uv_on_path()") && text.contains("uv_on_path_entry") && text.contains("[ -f \"${uv_on_path_entry}/${uv_on_path_name}\" ]"),
+ "the sh's uv-on-PATH check must SCAN PATH for an executable file itself: command -v also reports exported shell FUNCTIONS (and a bare-name result can hit a cwd decoy), which no child process can resolve"
+ );
+ assert!(
+ text.contains("uv_path_exts=\" .com .exe .bat .cmd\"")
+ && text.contains("uv_pathtext_rest=\"${PATHEXT:-}\"")
+ && text.contains("uv_pathtext_entry=\"${uv_pathtext_rest%%;*}\"")
+ && text.contains("tr 'A-Z' 'a-z'"),
+ "the Windows candidate list must be BUILT from the effective supported PATHEXT parsed as literal semicolon-delimited entries with END-ONLY trimming (the child's windows_executable_candidates: str::trim cuts the ends, whitespace inside an entry stays part of it), in PATHEXT order, defaults only as fallback - no word splitting or glob expansion anywhere"
+ );
+ assert!(
+ text.contains("uv_path_candidates=\"uv\""),
+ "the bare name rides first (the child tries it first)"
+ );
+ assert!(
+ text.contains("for uv_on_path_name in $uv_path_candidates"),
+ "the scan iterates the candidate names within each PATH entry, mirroring the child's search"
+ );
+ assert!(
+ !text.contains("for uv_on_path_entry in $PATH"),
+ "the PATH split must be literal: an unquoted for-loop GLOB-expands a PATH entry like /tmp/glob-* into a different directory the child never searches"
+ );
+ assert!(
+ text.contains("uv_on_path_entry=\"${uv_on_path_rest%%:*}\""),
+ "the PATH entries must be split by parameter expansion alone (never globbed)"
+ );
+ assert!(
+ text.contains("uv_on_path_rest=\"${PATH}:\"")
+ && text.contains("[ -z \"${PATH+x}\" ]"),
+ "the lookup must DISTINGUISH an UNSET PATH (the child resolves nothing: no match, no abort) from a SET-EMPTY one (the child resolves the cwd: the sentinel colon visits it), and every component including a trailing or sole empty one gets its own iteration"
+ );
+ assert!(
+ text.contains("[ -n \"$uv_on_path_entry\" ] || uv_on_path_entry=\".\""),
+ "an EMPTY PATH component means the current directory in the child's resolution semantics - the scan must search it, not skip it"
+ );
+ assert!(
+ text.contains("uv_bin=\"$uv_on_path_bin\""),
+ "the sh's discovery must use the RESOLVED executable from the PATH scan, never command -v's bare-name output"
+ );
+ assert!(
+ !text.contains("uv_bin=\"$(command -v uv)\""),
+ "no bare command -v result may become uv_bin"
+ );
+ assert!(
+ text.contains("|| { [ \"$uv_under_store\" = \"no\" ] && [ -x \"${HOME}/.local/bin/${uv_name}\" ]; }") ,
+ "the 'uv found' and pre-warm gates must see a default-location uv only outside the store-alias shape"
+ );
+ assert!(
+ text.contains("if uv_on_path \\\n || { [ -n \"$uv_bin_dir\" ] && [ -x \"${uv_bin_dir}/${uv_name}\" ]; } \\\n || { [ \"$uv_under_store\" = \"no\" ] && [ -x \"${HOME}/.local/bin/${uv_name}\" ]; }; then\n step_start \"Preparing the Python kernel\""),
+ "the kernel pre-warm gate must agree with the 'uv found' gate (a default-location uv must actually warm the kernel, not just be reported found)"
+ );
+ assert!(
+ text.contains("! uv_on_path && [ -n \"$uv_bin_dir\" ]")
+ && text.contains("PATH=\"$uv_bin_dir\"")
+ && text.contains("PATH=\"${uv_bin_dir}:${PATH}\""),
+ "the sh's pre-warm PATH prepend must run only when no uv already answers on PATH (never shadow a working system uv)"
+ );
+ assert!(
+ text.contains("path_check_note \"${bin_dir}\"")
+ && text.contains("path_check_note \"${uv_bin_dir}\""),
+ "the sh's PATH guidance must cover the custom uv target too (a documented install target must stay discoverable)"
+ );
+ assert!(
+ text.contains("incoming_path=\"${PATH:-}\"") && text.contains("case \":$incoming_path:\" in"),
+ "the incoming-PATH capture must also survive an unset PATH under set -u (the whole installer continues past the uv helper); the guidance compares against the INCOMING PATH (the pre-warm's temporary prepend must never suppress the persistent-PATH guidance)"
+ );
+}
+
+/// The install ledger + the streaming download (the operator's
+/// flow-parity ask, 2026-10-06): install-rust.sh runs a real progress UI -
+/// `step_ok` / `step_fail` lines plus a download bar fed by the fetched
+/// bytes - while the ps1's download was one silent web-cmdlet call. The
+/// ps1's mirror, as far as PowerShell sensibly allows: an ASCII step
+/// ledger around the phases, and the payload streams through a
+/// `HttpClient` copy loop that repaints one short line in place (the
+/// file's name, the landed bytes, the percent) with three attempts - the
+/// .NET transfer records stay silent the whole time (the download-block
+/// pins test covers the silencing).
+#[test]
+fn install_ps1_runs_a_step_ledger_and_its_own_download_progress() {
+ let text = std::fs::read_to_string(repo_root().join("install.ps1")).expect("read install.ps1");
+ // The ledger functions exist.
+ assert!(
+ text.contains("function Step-Ok"),
+ "the installer must define Step-Ok (install-rust.sh's step_ok)"
+ );
+ assert!(
+ text.contains("function Step-Fail"),
+ "the installer must define Step-Fail (install-rust.sh's step_fail)"
+ );
+ // The streaming helper: a `HttpClient` copy loop with the installer's
+ // own in-place progress line and the sh installer's three-attempt
+ // retry.
+ let helper_start = text
+ .find("function Save-Release")
+ .expect("the streaming download helper must exist");
+ let helper = &text[helper_start..];
+ let helper = &helper[..helper.find("\n}\n").map_or(helper.len(), |at| at + 3)];
+ assert!(
+ helper.contains("System.Net.Http.HttpClient"),
+ "the helper streams with HttpClient, which emits no cmdlet progress records"
+ );
+ assert!(
+ helper.contains("`r"),
+ "the helper repaints its progress line in place (a carriage return, never a newline)"
+ );
+ assert!(
+ helper.contains("%)"),
+ "the progress line carries the percent"
+ );
+ assert!(
+ helper.contains("-NoNewline"),
+ "the progress line does not scroll"
+ );
+ assert!(
+ helper.contains("attempt"),
+ "the helper retries like the sh installer's fetch (three attempts)"
+ );
+ // The payload download goes through the helper; the raw web cmdlet for
+ // the payload is gone.
+ let block_start = text
+ .find("$tarball = Join-Path $download $expectedFile")
+ .expect("the download block stages the tarball");
+ let block_end = text
+ .find("$sumsLine = Get-Content")
+ .expect("the checksum verify follows");
+ let block = &text[block_start..block_end];
+ assert!(
+ block.contains(
+ "Save-Release -Uri \"$baseUrl/$releasePrefix/$expectedFile\" -OutFile $tarball"
+ ),
+ "the payload download must stream through the helper"
+ );
+ assert!(
+ !block.contains("Invoke-WebRequest -Uri \"$baseUrl/$releasePrefix/$expectedFile\""),
+ "the payload download must not be the noisy web cmdlet anymore"
+ );
+ // The ledger marks the phases (install-rust.sh's step_ok lines).
+ for (phase, marker) in [
+ ("checksum", "Step-Ok 'checksum verified'"),
+ ("extract", "Step-Ok 'extracted'"),
+ ("publish", "Step-Ok 'published'"),
+ ("uv", "Step-Ok 'uv installed'"),
+ ("kernel", "Step-Ok 'kernel ready'"),
+ ] {
+ assert!(
+ text.contains(marker),
+ "the ledger must mark the {phase} phase: {marker}"
+ );
+ }
+}
+
+/// The uv parity (the operator's ask, 2026-10-06): install-rust.sh INSTALLS
+/// uv when it is missing (the astral one-liner with the destination
+/// passed explicitly via `UV_INSTALL_DIR`, the fetch and the script run
+/// checked SEPARATELY so a dead network cannot masquerade as success) and
+/// then pre-warms the kernel (`prime-agent --prime-agent-bootstrap`); the
+/// ps1 only printed a note. The ps1 mirrors the whole flow: the astral
+/// installer is FETCHED (into a file, checked non-empty), RUN with
+/// `UV_INSTALL_DIR` set explicitly, and its verdict is never trusted - the
+/// `uv.exe` FILE decides; the uv bin dir rides the session PATH
+/// (install-rust.sh's pre-warm PATH fix), and a failure degrades to the
+/// honest note plus the exact manual command (the sh installer's
+/// note/todo shape).
+#[test]
+fn install_ps1_installs_uv_like_the_linux_installer() {
+ let text = std::fs::read_to_string(repo_root().join("install.ps1")).expect("read install.ps1");
+ let section_start = text
+ .find("# --- the kernel pre-warm")
+ .expect("the pre-warm section exists");
+ let section_end = text
+ .find("# --- the PATH add")
+ .expect("the PATH-add section follows");
+ let section = &text[section_start..section_end];
+ let markers: [(&str, &str); 11] = [
+ (
+ "the uv target knob (install-rust.sh's own PRIME_AGENT_UV_BIN_DIR parity: an operator-set dir wins - a packaged install keeps uv inside its own tree, the e2e harnesses point it at their scratch so a run never touches the shared ~/.local/bin; the knob validated early with the other knobs)",
+ "if ($env:PRIME_AGENT_UV_BIN_DIR) { $uvInstallDir = $env:PRIME_AGENT_UV_BIN_DIR }",
+ ),
+ (
+ "the default-location presence check (a uv that predates the knob at ~/.local/bin is still honored: no duplicate install)",
+ "$uvDefaultExe = Join-Path (Join-Path $HOME '.local\\bin') 'uv.exe'",
+ ),
+ (
+ "the real-application PATH check (a PowerShell ALIAS or FUNCTION named uv must not count: no child process can resolve it)",
+ "$uvOnPath = [bool](Get-Command uv -CommandType Application -ErrorAction SilentlyContinue)",
+ ),
+ (
+ "the three-way usable-uv record (PATH, target, default - the reviewer's finding: a pre-existing uv at the knob target must serve the pre-warm)",
+ "$uvKnown = $uvOnPath -or $uvAtTarget -or $uvAtDefault",
+ ),
+ (
+ "the astral installer fetch",
+ "Invoke-WebRequest -Uri 'https://astral.sh/uv/install.ps1' -OutFile $uvInstallerPath",
+ ),
+ (
+ "the fetch checked before the run",
+ "(Get-Item -LiteralPath $uvInstallerPath).Length -gt 0",
+ ),
+ (
+ "the explicit destination",
+ "$env:UV_INSTALL_DIR = $uvInstallDir",
+ ),
+ (
+ "the script run (a child process, never Invoke-Expression: the astral script exits 1 on its own failures, and under Invoke-Expression that exit would leave this installer's control flow)",
+ "& $childShell -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand $childEncoded",
+ ),
+ (
+ "the binary decides (the verdict gate, in the negated-first shape)",
+ "if (-not (Test-Path $uvExe -PathType Leaf)) {",
+ ),
+ (
+ "the session PATH fix",
+ "$env:PATH = \"$uvInstallDir;$env:PATH\"",
+ ),
+ (
+ "the pre-warm gate follows the three-way record",
+ "if ($uvKnown) {",
+ ),
+ ];
+ let mut positions: Vec<usize> = Vec::new();
+ for (what, marker) in markers {
+ positions.push(
+ section
+ .find(marker)
+ .unwrap_or_else(|| panic!("the uv flow must carry its {what} line: {marker}")),
+ );
+ }
+ for pair in positions.windows(2) {
+ assert!(
+ pair[0] < pair[1],
+ "the uv flow's discipline is fetch, then run, then verify by the file: {markers:?}"
+ );
+ }
+ // The pre-warm itself and the honest fallbacks.
+ assert!(
+ section.contains("--prime-agent-bootstrap"),
+ "the pre-warm still runs the kernel bootstrap"
+ );
+ assert!(
+ section.contains("irm https://astral.sh/uv/install.ps1 | iex"),
+ "the manual fallback command is named (the astral one-liner)"
+ );
+ assert!(
+ section.contains("could not install uv; the kernel pre-warm was skipped"),
+ "the honest offline note names what was skipped"
+ );
+}
+
+/// The uv target knob validates EARLY and FULLY QUALIFIED (the reviewer's
+/// findings): the check runs with the other knobs, BEFORE the daemon stop,
+/// the payload publish, and the launcher swap (a late refusal would leave
+/// a half-applied install the catch cannot roll back), and it demands a
+/// drive-based or UNC path - a rooted-only check accepts drive-relative
+/// spellings like C:uv-bin that resolve against the CURRENT directory in
+/// later shells.
+#[test]
+fn install_ps1_validates_the_uv_knob_before_any_side_effect() {
+ let text = std::fs::read_to_string(repo_root().join("install.ps1")).expect("read install.ps1");
+ let validation_at = text
+ .find("PRIME_AGENT_UV_BIN_DIR must be a fully qualified absolute path")
+ .expect("the fully-qualified validation message exists");
+ let stage_at = text
+ .find("$stage = Join-Path (Join-Path $prefix 'share')")
+ .expect("the publish stage exists");
+ assert!(
+ validation_at < stage_at,
+ "the knob validation must fail before the publish stage (a late refusal leaves a half-applied install)"
+ );
+ assert!(
+ text.contains("PRIME_AGENT_UV_BIN_DIR -notmatch '^[a-zA-Z]:[\\\\/]'"),
+ "the validation demands a drive-based spelling (drive + separator)"
+ );
+ assert!(
+ text.contains("-notmatch '^\\\\\\\\[^\\\\\\\\]+\\\\[^\\\\\\\\]+'"),
+ "the validation demands a UNC spelling WITH its server and share (an incomplete lead-in or a server without a share must not reach publication)"
+ );
+ assert!(
+ !text.contains("[System.IO.Path]::IsPathRooted"),
+ "the rooted-only check is gone: it accepts drive-relative spellings like C:uv-bin"
+ );
+ assert!(
+ text.contains("PRIME_AGENT_UV_BIN_DIR must not contain a semicolon"),
+ "the knob must refuse the PATH separator (a target carrying a semicolon corrupts the registry PATH append)"
+ );
+}
+
+/// The Windows install e2e must exercise the SHIPPED link mode (the
+/// reviewer's pre-bar finding): the harness builds its own artifact, so a
+/// plain `cargo build --release` there produces the DYNAMIC binary the
+/// workflow stopped shipping - and the runner image carries the VC
+/// runtime, so that smoke passes even on a machine that would never run
+/// the shipped one. The e2e builds with the workflow's step-scoped
+/// `crt-static` flag, rejects any vcruntime import in the built PE (the
+/// stock-box 0xC0000135 regression guard), gates on the uv install the
+/// ps1 route promises, and restores the User PATH it dirtied.
+#[test]
+fn windows_install_e2e_builds_the_shipped_link_mode() {
+ let harness = std::fs::read_to_string(
+ repo_root()
+ .join("scripts")
+ .join("release")
+ .join("test_windows_install.ps1"),
+ )
+ .expect("read test_windows_install.ps1");
+ assert!(
+ harness.contains("target-feature=+crt-static"),
+ "the e2e must build its artifact with the workflow's step-scoped crt-static flag"
+ );
+ assert!(
+ harness.contains("vcruntime"),
+ "the e2e must reject a vcruntime import in the built release binary (the runner's own VC runtime would mask the stock-box regression)"
+ );
+ assert!(
+ harness.contains(".local\\bin\\uv.exe"),
+ "the e2e must gate on the uv executable the ps1 route promises to install"
+ );
+ assert!(
+ harness.contains(".Trim().StartsWith($scratch, [System.StringComparison]::OrdinalIgnoreCase)"),
+ "the e2e must strip exactly its own scratch-prefixed PATH entries from the CURRENT user PATH (never a stale snapshot restore)"
+ );
+}
+
+/// The harnesses' User PATH cleanup strips ONLY the entries the test itself
+/// added (the macroscope finding): restoring a whole stale snapshot would
+/// clobber any PATH change made outside the test while it ran, and the
+/// flatten-on-write [Environment] route would destroy the registry value's
+/// `REG_EXPAND_SZ` kind. Each harness reads the RAW value with its kind,
+/// drops only the entries under its own scratch dir, and writes back with
+/// the kind preserved - a Path the test created from nothing is deleted
+/// again; a Path untouched by the test is not rewritten at all.
+#[test]
+fn windows_e2e_harnesses_strip_only_their_own_path_entries() {
+ for harness_name in [
+ "test_windows_install.ps1",
+ "test_windows_channel_fallback.ps1",
+ ] {
+ let harness = std::fs::read_to_string(
+ repo_root()
+ .join("scripts")
+ .join("release")
+ .join(harness_name),
+ )
+ .unwrap_or_else(|_| panic!("read {harness_name}"));
+ for (what, marker) in [
+ (
+ "the raw read",
+ "[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames",
+ ),
+ ("the kind read", "$envKey.GetValueKind('Path')"),
+ (
+ "the own-entries filter",
+ ".Trim().StartsWith($scratch, [System.StringComparison]::OrdinalIgnoreCase)",
+ ),
+ (
+ "the kind-preserving write",
+ "$envKey.SetValue('Path', ($keptEntries -join ';'), $rawUserKind)",
+ ),
+ (
+ "the absent-Path edge (the test created the value from nothing)",
+ "$envKey.DeleteValue('Path', $false)",
+ ),
+ ] {
+ assert!(
+ harness.contains(marker),
+ "{harness_name} must carry its {what} line: {marker}"
+ );
+ }
+ assert!(
+ !harness.contains("[Environment]::SetEnvironmentVariable('Path', $userPathBefore, 'User')"),
+ "{harness_name}'s cleanup must not restore a stale whole-value snapshot (it clobbers external changes and flattens the kind)"
+ );
+ }
+}
+
+/// Save-Release's body copy must survive a stalled body (the macroscope
+/// finding): `HttpClient.Timeout` under `ResponseHeadersRead` bounds only the
+/// wait for the headers, so a server that answers the headers and then
+/// parks the tarball body would hang the synchronous `$stream.Read` loop
+/// forever - the three-attempt retry the helper promises never gets its
+/// chance. Each chunk read is a bounded task: a body that delivers nothing
+/// within the stall window throws and takes the retry path, while a
+/// slow-but-flowing body never trips it (a read returns as soon as data
+/// arrives, the window restarts per chunk).
+#[test]
+fn install_ps1_download_survives_a_stalled_body() {
+ let text = std::fs::read_to_string(repo_root().join("install.ps1")).expect("read install.ps1");
+ let helper_start = text
+ .find("function Save-Release")
+ .expect("the streaming download helper must exist");
+ let helper = &text[helper_start..];
+ let helper = &helper[..helper.find("\n}\n").map_or(helper.len(), |at| at + 3)];
+ let markers: [(&str, &str); 4] = [
+ (
+ "the per-chunk stall window",
+ "$readTimeout = [TimeSpan]::FromSeconds(60)",
+ ),
+ (
+ "the bounded chunk read",
+ "$readTask = $stream.ReadAsync($buffer, 0, $buffer.Length)",
+ ),
+ (
+ "the wait against the window",
+ "if (-not $readTask.Wait($readTimeout)) {",
+ ),
+ ("the honest stall message", "the body of $Name stalled"),
+ ];
+ let mut positions: Vec<usize> = Vec::new();
+ for (what, marker) in markers {
+ positions.push(
+ helper.find(marker).unwrap_or_else(|| {
+ panic!("the download helper must carry its {what} line: {marker}")
+ }),
+ );
+ }
+ for pair in positions.windows(2) {
+ assert!(
+ pair[0] < pair[1],
+ "the stall discipline is ordered window -> read -> wait -> throw: {markers:?}"
+ );
+ }
+}
+
+/// The pre-warm's PATH fix must not shadow a working uv (the macroscope
+/// finding) and must make the uv the installer ACTUALLY knows about
+/// findable (the reviewer's finding): the product's `ensure_uv` searches
+/// PATH and `~/.local/bin/uv(.exe)` - it does NOT know the
+/// `PRIME_AGENT_UV_BIN_DIR` target - so the prepend serves the uv THIS
+/// RUN installed or found at the target when nothing usable is on PATH,
+/// while a working PATH uv is never shadowed (a stale target file cannot
+/// displace it) and a uv at the canonical `~/.local/bin` needs no prepend
+/// (`ensure_uv` finds it by itself).
+#[test]
+fn install_ps1_does_not_shadow_a_working_uv() {
+ let text = std::fs::read_to_string(repo_root().join("install.ps1")).expect("read install.ps1");
+ let section_start = text
+ .find("# --- the kernel pre-warm")
+ .expect("the pre-warm section exists");
+ let section_end = text
+ .find("# --- the PATH add")
+ .expect("the PATH-add section follows");
+ let section = &text[section_start..section_end];
+ let guard =
+ "if (-not $uvOnPath -and $uvAtTarget -and -not (Test-PathEntry $env:PATH $uvInstallDir)) {";
+ let guard_at = section
+ .find(guard)
+ .expect("the PATH fix must be guarded: it prepends only when this run owns the local uv");
+ let prepend_at = section
+ .find("$env:PATH = \"$uvInstallDir;$env:PATH\"")
+ .expect("the PATH fix's prepend line must survive the guard");
+ assert!(
+ guard_at < prepend_at,
+ "the guard decides before the prepend runs"
+ );
+}
+
+/// The fetched uv installer's path rides the child invocation as DATA (the
+/// macroscope finding): `$download` lives under the caller's TEMP, and a
+/// user profile whose path carries an apostrophe (an O'Brien-style Windows
+/// account) breaks the single-quoted literal the child script embedded -
+/// the child exits with a parse error, the install is skipped, and the
+/// kernel pre-warm is left undone on a machine that has everything but
+/// the apostrophe. The path never rides the command line (host parsing of
+/// extra arguments after `-EncodedCommand` is version-dependent) nor the
+/// script text: the parent hands it over through the environment (the
+/// same handoff the block runs `UV_INSTALL_DIR` through, with the caller's
+/// value saved and restored) and the child reads the variable - no
+/// PowerShell parsing of the path happens at any version.
+#[test]
+fn install_ps1_passes_the_uv_installer_path_as_process_data() {
+ let text = std::fs::read_to_string(repo_root().join("install.ps1")).expect("read install.ps1");
+ let section_start = text
+ .find("# --- the kernel pre-warm")
+ .expect("the pre-warm section exists");
+ let section_end = text
+ .find("# --- the PATH add")
+ .expect("the PATH-add section follows");
+ let section = &text[section_start..section_end];
+ assert!(
+ section.contains("& `$env:PRIME_AGENT_UV_INSTALLER"),
+ "the child script must invoke the fetched installer through the handoff variable, never an embedded literal"
+ );
+ assert!(
+ section.contains(
+ "$childShell = if (Get-Command pwsh -CommandType Application -ErrorAction SilentlyContinue)"
+ ),
+ "the child-shell lookup must also be Application-restricted (a profile alias named pwsh has no Source to run)"
+ );
+ assert!(
+ section.contains("(Get-Process -Id $PID).Path"),
+ "the child-shell fallback must resolve to an ABSOLUTE executable (a bare 'powershell' can be intercepted by a caller alias or function)"
+ );
+ assert!(
+ section.contains("$env:PRIME_AGENT_UV_INSTALLER = $uvInstallerPath"),
+ "the parent must hand the installer path to the child through the environment"
+ );
+ assert!(
+ section.contains("$callerUvInstaller = $env:PRIME_AGENT_UV_INSTALLER")
+ && section.contains("$env:PRIME_AGENT_UV_INSTALLER = $callerUvInstaller"),
+ "the handoff must save and restore the caller's value like UV_INSTALL_DIR beside it"
+ );
+ assert!(
+ section.contains("-EncodedCommand $childEncoded *> $null"),
+ "the encoded child invocation carries no trailing argument (host parsing of extra args after -EncodedCommand is version-dependent)"
+ );
+ assert!(
+ !section.contains("& '$uvInstallerPath'"),
+ "the child script must not embed the path in a single-quoted literal (an apostrophe in the path parses the child dead)"
+ );
+}
+
+/// The Windows e2e harnesses ISOLATE the uv install (the macroscope and
+/// reviewer findings): ownership of a file in the SHARED ~/.local/bin can
+/// never be proven airtightly (a transcript's uv-branch line proves an
+/// attempt, not the landing; a concurrent external install races the
+/// attribution) - so the harnesses never touch the shared dir at all:
+/// both installers honor the `PRIME_AGENT_UV_BIN_DIR` knob and the
+/// harnesses point it at their own scratch dir, with the caller's value
+/// saved and restored. The cleanup has no uv work left to do, and the
+/// user's ~/.local/bin is referenced only by the read-only pre-state
+/// check.
+#[test]
+fn windows_e2e_harnesses_isolate_the_uv_install() {
+ for harness_name in [
+ "test_windows_install.ps1",
+ "test_windows_channel_fallback.ps1",
+ ] {
+ let harness = std::fs::read_to_string(
+ repo_root()
+ .join("scripts")
+ .join("release")
+ .join(harness_name),
+ )
+ .unwrap_or_else(|_| panic!("read {harness_name}"));
+ assert!(
+ harness.contains("$env:PRIME_AGENT_UV_BIN_DIR = Join-Path $scratch 'uv-bin'"),
+ "{harness_name} must steer BOTH installers' uv installs into its own scratch dir (ownership of shared-profile files is unprovable; isolation removes the class)"
+ );
+ assert!(
+ harness.contains("$callerUvBinDir = $env:PRIME_AGENT_UV_BIN_DIR")
+ && harness.contains("$env:PRIME_AGENT_UV_BIN_DIR = $callerUvBinDir"),
+ "{harness_name} must save and restore the caller's PRIME_AGENT_UV_BIN_DIR like the other override knobs"
+ );
+ // The cleanup finally must never touch the user's uv binaries at
+ // all: no snapshot, no restore, no delete, no ownership guess.
+ let finally_at = harness
+ .rfind("} finally {")
+ .expect("the cleanup finally exists");
+ assert!(
+ !harness[finally_at..].contains(".local\\bin"),
+ "{harness_name}'s cleanup must not touch ~/.local/bin (the install never lands there under the knob)"
+ );
+ assert!(
+ !harness.contains("$uvSnapshotDir") && !harness.contains("$uvRestoreFailed"),
+ "{harness_name} must not carry the snapshot/restore/ownership machinery anymore (the isolated target needs none of it)"
+ );
+ }
+}
+
+/// The uv parity gate runs against the fresh-runner contract it asserts
+/// (the cursor finding): install.ps1 skips its uv branch when the machine
+/// already answers `uv` - by design - so demanding the install on a box
+/// that had uv before the test ran fails the gate without the installer
+/// being wrong. The harness records the pre-state first, and the gate
+/// throws only for a box that had no uv in either place install.ps1
+/// looks.
+#[test]
+fn windows_install_e2e_gates_the_uv_install_on_a_fresh_runner() {
+ let harness = std::fs::read_to_string(
+ repo_root()
+ .join("scripts")
+ .join("release")
+ .join("test_windows_install.ps1"),
+ )
+ .expect("read test_windows_install.ps1");
+ assert!(
+ harness.contains(
+ "$uvWasOnPath = [bool](Get-Command uv -CommandType Application -ErrorAction SilentlyContinue) -or (Test-Path (Join-Path $HOME '.local\\bin\\uv.exe'))"
+ ),
+ "the harness must record the uv pre-state before the install runs (the PATH and the ~/.local/bin places install.ps1 looks)"
+ );
+ assert!(
+ harness.contains("$uvExePath = Join-Path (Join-Path $scratch 'uv-bin') 'uv.exe'"),
+ "the gate must check the ISOLATED uv target (the harness steers both installers at its scratch dir)"
+ );
+ // The transcript capture: the evidence for both the contract gate and
+ // the cleanup's ownership tracking.
+ assert!(
+ harness.contains(
+ "$ps1Lines = @(& pwsh -File (Join-Path $repo 'install.ps1') 2>&1 | ForEach-Object { \"$_\" })"
+ ),
+ "the harness must capture the ps1 route's transcript (the uv gate's evidence)"
+ );
+ // The gate asserts the CONTRACT, never astral.sh availability: either
+ // uv.exe landed (the online path), or the transcript carries the honest
+ // degradation note (offline is a supported state of the best-effort
+ // branch - the install.ps1 flow treats it as non-fatal by design).
+ assert!(
+ harness.contains("if (-not $uvWasOnPath -and -not $uvLanded -and -not $degradedHonestly) {"),
+ "the uv gate must demand the online install OR the honest degradation, never astral.sh luck"
+ );
+ assert!(
+ harness.contains("no uv.exe and no honest degradation note"),
+ "the uv gate's failure must name the broken contract, not a network state"
+ );
+ assert!(
+ !harness.contains("did not install uv at $uvExePath"),
+ "the uv gate must not demand astral availability (the branch is best-effort by design)"
+ );
+}
+
+/// The harnesses keep the kernel pre-warm's writes out of the real user
+/// profile (the cursor finding): the bootstrap venv, uv's cache, and uv's
+/// downloaded pythons all default into the profile, and the pre-warm runs
+/// as part of the install the harness drives. Each harness steers all
+/// three into its scratch dir through the product's own override knobs
+/// and clears them again in cleanup, so the e2e touches the real profile
+/// only through the User PATH registry value and the uv binaries (both
+/// snapshotted and restored).
+#[test]
+fn windows_e2e_harnesses_keep_the_kernel_prewarm_writes_in_scratch() {
+ for harness_name in [
+ "test_windows_install.ps1",
+ "test_windows_channel_fallback.ps1",
+ ] {
+ let harness = std::fs::read_to_string(
+ repo_root()
+ .join("scripts")
+ .join("release")
+ .join(harness_name),
+ )
+ .unwrap_or_else(|_| panic!("read {harness_name}"));
+ for (what, marker) in [
+ (
+ "the venv redirect",
+ "$env:PRIME_AGENT_KERNEL_VENV = Join-Path $scratch 'kernel-venv'",
+ ),
+ (
+ "the uv cache redirect",
+ "$env:UV_CACHE_DIR = Join-Path $scratch 'uv-cache'",
+ ),
+ (
+ "the uv python redirect",
+ "$env:UV_PYTHON_INSTALL_DIR = Join-Path $scratch 'uv-python'",
+ ),
+ (
+ "the caller's venv value saved",
+ "$callerKernelVenv = $env:PRIME_AGENT_KERNEL_VENV",
+ ),
+ (
+ "the caller's venv value restored",
+ "$env:PRIME_AGENT_KERNEL_VENV = $callerKernelVenv",
+ ),
+ ] {
+ assert!(
+ harness.contains(marker),
+ "{harness_name} must carry its {what} line: {marker}"
+ );
+ }
+ assert!(
+ !harness.contains("Remove-Item 'Env:PRIME_AGENT_KERNEL_VENV'"),
+ "{harness_name}'s cleanup must RESTORE the caller's override values, never delete the knobs (a caller with its own redirect loses it on an in-process run)"
+ );
+ }
+}
diff --git a/crates/pa-cli/tests/release_workflow.rs b/crates/pa-cli/tests/release_workflow.rs
index 47d157bc1a..4320da3423 100644
--- a/crates/pa-cli/tests/release_workflow.rs
+++ b/crates/pa-cli/tests/release_workflow.rs
@@ -108,6 +108,8 @@ struct Step {
run: Option<String>,
#[serde(default)]
with: Option<serde_yaml::Value>,
+ #[serde(default)]
+ env: Option<serde_yaml::Value>,
}
/// The promote job's steps from the committed `.github/workflows/release.yml`.
@@ -450,6 +452,73 @@ fn windows_build_job_contract() {
);
}
+/// The shipped Windows binary must link the STATIC VC runtime: the
+/// MSVC target links vcruntime dynamically by default, the windows-2022
+/// runner image carries vcruntime140.dll, and a stock Windows machine does
+/// not - the dynamically linked launcher dies at process start
+/// (0xC0000135, `STATUS_DLL_NOT_FOUND`, exit -1073741515) before main runs.
+/// The operator hit exactly that on a real box (2026-10-06), so the
+/// crt-static pin is the build step's own env: only the SHIPPED binary is
+/// static, and never through Cargo.toml, whose dev builds stay dynamic.
+#[test]
+fn the_windows_build_links_the_static_vc_runtime() {
+ let text = fs::read_to_string(repo_root().join(".github/workflows/release.yml"))
+ .expect("read release.yml");
+ let workflow: Workflow = serde_yaml::from_str(&text).expect("release.yml parses as YAML");
+ let windows = workflow
+ .jobs
+ .get("build-windows")
+ .expect("the build-windows job exists");
+ let build = windows
+ .steps
+ .iter()
+ .find(|step| {
+ step.name.as_deref() == Some("Build (release, locked)")
+ && step
+ .run
+ .as_deref()
+ .is_some_and(|run| run.contains("cargo build --release --locked"))
+ })
+ .expect("the build-windows job's Build step exists");
+ let rustflags = build
+ .env
+ .as_ref()
+ .and_then(|env| env.get("RUSTFLAGS"))
+ .and_then(serde_yaml::Value::as_str)
+ .expect("the Windows build step must set RUSTFLAGS");
+ assert!(
+ rustflags.contains("target-feature=+crt-static"),
+ "the Windows build must link the static VC runtime (RUSTFLAGS carries target-feature=+crt-static), got: {rustflags}"
+ );
+ // The pin is the Windows build step's alone: the gnu and darwin release
+ // builds stay exactly as they are (crt-static would trade their libc
+ // contract for nothing a shipped binary needs).
+ for job in ["build-gnu", "build-darwin"] {
+ for step in &workflow.jobs.get(job).expect("job exists").steps {
+ if let Some(run) = step.run.as_deref() {
+ if run.contains("cargo build --release --locked") {
+ assert!(
+ !step
+ .env
+ .as_ref()
+ .and_then(|env| env.get("RUSTFLAGS"))
+ .and_then(serde_yaml::Value::as_str)
+ .is_some_and(|flags| flags.contains("crt-static")),
+ "crt-static is the Windows launcher's fix, never a gnu/darwin flag"
+ );
+ }
+ }
+ }
+ }
+ // Dev builds stay dynamic: the pin lives in the release workflow alone,
+ // never in Cargo.toml (whose every target and profile would go static).
+ let cargo_toml = fs::read_to_string(repo_root().join("Cargo.toml")).expect("read Cargo.toml");
+ assert!(
+ !cargo_toml.contains("crt-static"),
+ "crt-static belongs to the release workflow's Windows build step, not Cargo.toml: dev builds link the runtime dynamically"
+ );
+}
+
/// The structural gate: one count-independent download-all step, pinned to
/// `incoming`, followed by the normalize step before the per-artifact gates.
#[test]
diff --git a/install-rust.sh b/install-rust.sh
index f6624aa7e4..34846942e0 100755
--- a/install-rust.sh
+++ b/install-rust.sh
@@ -122,6 +122,7 @@
# PRIME_AGENT_RUST_PREFIX install prefix (default: ~/.local; the
# launcher lands at $PREFIX/bin/prime-agent,
# the payload at $PREFIX/share/prime-agent/)
+# PRIME_AGENT_UV_BIN_DIR uv install dir (default: ~/.local/bin)
#
# THE CHANNEL (the R2 form, the TS install.sh parity): the script reads
# the channel pointer (<base>/stable or <base>/beta) for the version,
@@ -211,6 +212,7 @@ Environment:
pointer read; the manifest + SHA256SUMS
checks still run)
PRIME_AGENT_RUST_PREFIX install prefix (~/.local by default)
+ PRIME_AGENT_UV_BIN_DIR uv install dir (~/.local/bin by default)
PRIME_AGENT_RUST_VERBOSE 1 = the --verbose output mode
PRIME_AGENT_ROLLBACK_CHECK 1 = with --rollback, print the resolved
rollback source and exit without touching
@@ -991,15 +993,78 @@ physical_path() {
}
uv_store_root="$(physical_path "${HOME}/.prime/agent")"
uv_default_root="$(physical_path "${HOME}/.local")"
-uv_bin_dir="${HOME}/.local/bin"
+# The store-alias detection runs FIRST so the discovery guards below can
+# read it in every branch (a uv found INSIDE the shared store must never
+# carry uv's own python writes back into it).
uv_under_store="no"
case "${uv_default_root}/" in
"${uv_store_root}/"*) uv_under_store="yes" ;;
esac
-if [ "$uv_under_store" = "yes" ]; then
- uv_bin_dir="${PREFIX}/bin"
- say "uv target: ${HOME}/.local resolves inside the shared session store;"
- say " uv installs payload-adjacent at ${uv_bin_dir} instead"
+# THE PLATFORM EXECUTABLE NAME (the reviewer's finding): the Git Bash
+# route probes real Windows files - uv.exe, not uv.
+uv_name="uv"
+if [ "$WINDOWS" = "yes" ]; then uv_name="uv.exe"; fi
+# The PATH scan's candidate names match the child's own executable
+# search (ensure_uv): the bare name first, then on Windows the SUPPORTED
+# PATHEXT entries in PATHEXT order - the defaults only when PATHEXT
+# names none.
+uv_path_candidates="uv"
+if [ "$WINDOWS" = "yes" ]; then
+ # PATHEXT entries are parsed as literal semicolon-delimited strings with
+ # END-ONLY trimming (the child's own parse: whitespace inside an entry
+ # keeps it unsupported), lowercased, filtered to the supported set in
+ # PATHEXT order; the defaults apply only when PATHEXT names none.
+ uv_path_exts=""
+ uv_pathtext_rest="${PATHEXT:-}"
+ while [ -n "$uv_pathtext_rest" ]; do
+ uv_pathtext_entry="${uv_pathtext_rest%%;*}"
+ if [ "$uv_pathtext_entry" = "$uv_pathtext_rest" ]; then
+ uv_pathtext_rest=""
+ else
+ uv_pathtext_rest="${uv_pathtext_rest#*;}"
+ fi
+ uv_pathtext_entry="${uv_pathtext_entry#"${uv_pathtext_entry%%[![:space:]]*}"}"
+ uv_pathtext_entry="${uv_pathtext_entry%"${uv_pathtext_entry##*[![:space:]]}"}"
+ uv_pathtext_entry="$(printf '%s' "$uv_pathtext_entry" | tr 'A-Z' 'a-z')"
+ case "$uv_pathtext_entry" in
+ .com|.exe|.bat|.cmd) uv_path_exts="$uv_path_exts $uv_pathtext_entry" ;;
+ esac
+ done
+ [ -n "$uv_path_exts" ] || uv_path_exts=" .com .exe .bat .cmd"
+ for uv_path_ext in $uv_path_exts; do
+ uv_path_candidates="$uv_path_candidates uv$uv_path_ext"
+ done
+fi
+# THE UV TARGET KNOB (the ps1's own PRIME_AGENT_UV_BIN_DIR): an operator-
+# set dir wins (a packaged install keeps uv inside its own tree, the e2e
+# harnesses point it at their scratch dir so a run never touches the
+# shared ~/.local/bin). The Windows C:\ spelling reaches this script
+# through the env - it normalizes exactly like PRIME_AGENT_RUST_PREFIX
+# (cygpath); a POSIX spelling passes through untouched. A RELATIVE knob
+# is refused (the reviewer's finding): a relative target would ride PATH
+# guidance into every later shell, which resolves it from its own working
+# directory - an absolute target is the only honest contract.
+if [ -n "${PRIME_AGENT_UV_BIN_DIR:-}" ]; then
+ uv_bin_dir="${PRIME_AGENT_UV_BIN_DIR}"
+ if [ "$WINDOWS" = "yes" ] && command -v cygpath >/dev/null 2>&1; then
+ uv_bin_dir="$(cygpath -u "$uv_bin_dir")" || die "PRIME_AGENT_UV_BIN_DIR could not be resolved to a POSIX path: ${PRIME_AGENT_UV_BIN_DIR}"
+ fi
+ case "$uv_bin_dir" in
+ /*) ;;
+ *) die "PRIME_AGENT_UV_BIN_DIR must be an absolute path: ${PRIME_AGENT_UV_BIN_DIR}" ;;
+ esac
+ # THE PATH SEPARATOR (the reviewer's finding): a target containing a
+ # colon would corrupt every PATH export and prepend that carries it.
+ case "$uv_bin_dir" in
+ *:*) die "PRIME_AGENT_UV_BIN_DIR must not contain a colon: ${PRIME_AGENT_UV_BIN_DIR}" ;;
+ esac
+else
+ uv_bin_dir="${HOME}/.local/bin"
+ if [ "$uv_under_store" = "yes" ]; then
+ uv_bin_dir="${PREFIX}/bin"
+ say "uv target: ${HOME}/.local resolves inside the shared session store;"
+ say " uv installs payload-adjacent at ${uv_bin_dir} instead"
+ fi
fi
# THE FALLBACK'S OWN GUARD (the store guard cannot cover this write: the
# astral install runs BEFORE the guard does): the computed target must
@@ -1022,12 +1087,64 @@ if [ "$uv_target_unsafe" = "yes" ]; then
note " here — the store is never written by this installer"
uv_bin_dir=""
fi
+# A REAL EXECUTABLE ON PATH (the reviewer's findings): a bare command -v
+# also reports exported shell FUNCTIONS (BASH_FUNC-style imports), and its
+# bare-name output can even hit a non-executable decoy file in the cwd -
+# neither is resolvable by a child process. So the check scans the PATH
+# entries itself for an EXECUTABLE file (with the platform's uv_name) and
+# never consults the shell's own function/alias resolution.
+uv_on_path() {
+ # The PATH split is PARAMETER EXPANSION ALONE (the reviewer's finding):
+ # an unquoted for-loop word-split GLOB-expands a PATH entry like
+ # /tmp/glob-* into a different directory the child never searches - a
+ # literal split cannot glob.
+ # An UNSET PATH is distinct from a SET-EMPTY one: the child resolves
+ # NOTHING without a PATH (no match, and no set -u abort - the uv
+ # download/system-Python fallback below continues), while a set-empty
+ # PATH resolves the cwd. The trailing sentinel colon then guarantees
+ # EVERY component its own iteration - a trailing or sole EMPTY
+ # component resolves as the cwd for the child.
+ if [ -z "${PATH+x}" ]; then
+ return 1
+ fi
+ uv_on_path_rest="${PATH}:"
+ while [ -n "$uv_on_path_rest" ]; do
+ uv_on_path_entry="${uv_on_path_rest%%:*}"
+ if [ "$uv_on_path_entry" = "$uv_on_path_rest" ]; then
+ uv_on_path_rest=""
+ else
+ uv_on_path_rest="${uv_on_path_rest#*:}"
+ fi
+ # An EMPTY component means the CURRENT DIRECTORY in the child's PATH
+ # resolution semantics - the scan searches it, never skips it.
+ [ -n "$uv_on_path_entry" ] || uv_on_path_entry="."
+ # Within one PATH entry the scan iterates the candidate names in the
+ # child's own order; an executable regular FILE wins.
+ for uv_on_path_name in $uv_path_candidates; do
+ [ -f "${uv_on_path_entry}/${uv_on_path_name}" ] || continue
+ [ -x "${uv_on_path_entry}/${uv_on_path_name}" ] || continue
+ uv_on_path_bin="${uv_on_path_entry}/${uv_on_path_name}"
+ return 0
+ done
+ done
+ return 1
+}
uv_bin=""
python_step="no"
-if command -v uv >/dev/null 2>&1; then
- uv_bin="$(command -v uv)"
-elif [ -x "${uv_bin_dir}/uv" ]; then
- uv_bin="${uv_bin_dir}/uv"
+if uv_on_path; then
+ uv_bin="$uv_on_path_bin"
+elif [ -x "${uv_bin_dir}/${uv_name}" ]; then
+ uv_bin="${uv_bin_dir}/${uv_name}"
+elif [ -x "${HOME}/.local/bin/${uv_name}" ] && [ "$uv_under_store" = "no" ]; then
+ # THE CANONICAL-LOCATION FALLBACK (the reviewer's finding): the knob
+ # redirects the INSTALL target, not the discovery - a usable uv at the
+ # canonical ~/.local/bin still serves this install (no duplicate
+ # download into the knob's dir). THE STORE-ALIAS GUARD (the reviewer's
+ # finding): under the ~/.local-alias-into-the-store shape that uv IS
+ # inside the shared store - selecting it would carry uv's own python
+ # writes back into the store, so the fallback refuses it and the flow
+ # installs payload-adjacent instead.
+ uv_bin="${HOME}/.local/bin/${uv_name}"
else
# The fetch and the script run are checked SEPARATELY: a plain
# `curl | sh` pipeline reports the script's status, so a dead network
@@ -1054,8 +1171,8 @@ else
https://astral.sh/uv/install.sh)" \
&& printf '%s\n' "$uv_install_out" \
| env -u UV_UNMANAGED_INSTALL UV_INSTALL_DIR="$uv_bin_dir" sh >/dev/null 2>&1 \
- && [ -x "${uv_bin_dir}/uv" ]; then
- uv_bin="${uv_bin_dir}/uv"
+ && [ -x "${uv_bin_dir}/${uv_name}" ]; then
+ uv_bin="${uv_bin_dir}/${uv_name}"
else
say "the uv install failed; falling back to a system python3"
fi
@@ -2881,12 +2998,28 @@ fi
# store-alias fallback) is invisible to the launcher unless the prefix's
# bin dir rides PATH — the pre-warm's child inherits this PATH, and the
# profile note below tells the user to make it permanent.
-if [ -n "$uv_bin_dir" ] && [ "$uv_bin_dir" != "${HOME}/.local/bin" ]; then
- PATH="${uv_bin_dir}:${PATH}"
+# THE INCOMING PATH (the reviewer's finding): the persistent-PATH guidance
+# near the end of this script must describe the user's NEXT session, never
+# this process's temporary prepend - so the pre-warm fix below captures the
+# incoming PATH first and the guidance compares against that.
+incoming_path="${PATH:-}"
+# THE GUARD (the reviewer's finding): the prepend runs only when no uv
+# already answers on PATH - a working PATH uv is never shadowed by a stale
+# target file - and it serves the uv at the target (the product's ensure_uv
+# does not know the knob's dir).
+if ! uv_on_path && [ -n "$uv_bin_dir" ] && [ "$uv_bin_dir" != "${HOME}/.local/bin" ]; then
+ # An unset PATH must not become a trailing colon (that would expose the
+ # cwd to the child's PATH search): the prepend sets the PATH outright.
+ if [ -z "${PATH+x}" ]; then
+ PATH="$uv_bin_dir"
+ else
+ PATH="${uv_bin_dir}:${PATH}"
+ fi
export PATH
fi
-if command -v uv >/dev/null 2>&1 \
- || { [ -n "$uv_bin_dir" ] && [ -x "${uv_bin_dir}/uv" ]; }; then
+if uv_on_path \
+ || { [ -n "$uv_bin_dir" ] && [ -x "${uv_bin_dir}/${uv_name}" ]; } \
+ || { [ "$uv_under_store" = "no" ] && [ -x "${HOME}/.local/bin/${uv_name}" ]; }; then
say "uv found (the kernel venv's package manager)"
else
if [ -n "$uv_bin_dir" ]; then
@@ -2909,11 +3042,11 @@ else
https://astral.sh/uv/install.sh)" \
&& printf '%s\n' "$curl_out" \
| env -u UV_UNMANAGED_INSTALL UV_INSTALL_DIR="$uv_bin_dir" sh >&3 2>&1; then
- if [ -x "${uv_bin_dir}/uv" ]; then
+ if [ -x "${uv_bin_dir}/${uv_name}" ]; then
step_ok "uv installed"
else
step_fail "Installing uv"
- note "! The uv installer reported success but ${uv_bin_dir}/uv is missing; the"
+ note "! The uv installer reported success but ${uv_bin_dir}/${uv_name} is missing; the"
note " first session may need to install uv itself."
fi
else
@@ -2923,8 +3056,14 @@ else
todo "curl -LsSf https://astral.sh/uv/install.sh | sh"
fi
fi
-if command -v uv >/dev/null 2>&1 \
- || { [ -n "$uv_bin_dir" ] && [ -x "${uv_bin_dir}/uv" ]; }; then
+# THE PRE-WARM GATE (the reviewer's finding): it must agree with the
+# 'uv found' gate above - a default-location uv must actually WARM the
+# kernel, not only be reported found (the product's ensure_uv finds
+# ~/.local/bin/uv by itself), and never in the store-alias shape (the
+# store is never written from this installer).
+if uv_on_path \
+ || { [ -n "$uv_bin_dir" ] && [ -x "${uv_bin_dir}/${uv_name}" ]; } \
+ || { [ "$uv_under_store" = "no" ] && [ -x "${HOME}/.local/bin/${uv_name}" ]; }; then
step_start "Preparing the Python kernel"
if bootstrap_out="$("$launcher" --prime-agent-bootstrap 2>&1)"; then
step_ok "Kernel ready"
@@ -3020,47 +3159,62 @@ fi
# --- PATH check (warn, not fail) ---------------------------------------------------
# The installer never edits a shell profile: it prints the one line that
-# does it for the user's shell (from $SHELL) and reloads it.
-case ":$PATH:" in
- *":${bin_dir}:"*) ;;
- *)
- case "$bin_dir" in
- "$HOME"/*) path_expr="\$HOME${bin_dir#"$HOME"}" ;;
- *) path_expr="$bin_dir" ;;
- esac
- printf '\n' >&2
- case "${SHELL:-}" in
- */zsh)
- note "! $(tilde "$bin_dir") is not on your PATH. Add it and reload your shell:"
- todo "echo 'export PATH=\"${path_expr}:\$PATH\"' >> ~/.zshrc && source ~/.zshrc"
- ;;
- */bash)
- # The tilde is printed for the user's shell to expand.
- # shellcheck disable=SC2088
- bash_profile="~/.bashrc"
- # shellcheck disable=SC2088
- if [ "$OS" = Darwin ]; then bash_profile="~/.bash_profile"; fi
- note "! $(tilde "$bin_dir") is not on your PATH. Add it and reload your shell:"
- todo "echo 'export PATH=\"${path_expr}:\$PATH\"' >> ${bash_profile} && source ${bash_profile}"
- ;;
- */fish)
- note "! $(tilde "$bin_dir") is not on your PATH. Add it:"
- todo "fish_add_path $(tilde "$bin_dir")"
- ;;
- *)
- note "! $(tilde "$bin_dir") is not on your PATH. Add this line to your shell profile"
- note " and open a new terminal:"
- todo "export PATH=\"${path_expr}:\$PATH\""
- ;;
- esac
- if [ "$WINDOWS" = "yes" ]; then
- # The user PATH takes the Windows spelling (C:\...), not the MSYS one.
- win_bin_dir="$bin_dir"
- if command -v cygpath >/dev/null 2>&1; then
- win_bin_dir="$(cygpath -w "$bin_dir" 2>/dev/null)" || win_bin_dir="$bin_dir"
- fi
- note "! For PowerShell and cmd, add it to your user PATH and open a new terminal:"
- todo "[Environment]::SetEnvironmentVariable('Path', [Environment]::GetEnvironmentVariable('Path','User') + ';${win_bin_dir}', 'User')"
+# does it for the user's shell (from $SHELL) and reloads it. THE CUSTOM UV
+# TARGET joins the check (the reviewer's finding: a documented install
+# target must stay discoverable once the installer exits - the product's
+# own ensure_uv searches PATH and ~/.local/bin only; the store-alias
+# fallback already points at the launcher's own bin dir, which the first
+# check covers).
+path_check_note() {
+ # The guidance compares against the INCOMING PATH (a fresh session's
+ # view): this script's own temporary pre-warm prepend must never
+ # suppress the persistent-PATH guidance for a dir the user still needs.
+ case ":$incoming_path:" in
+ *":$1:"*) return 0 ;;
+ esac
+ case "$1" in
+ "$HOME"/*) path_expr="\$HOME${1#"$HOME"}" ;;
+ *) path_expr="$1" ;;
+ esac
+ printf '\n' >&2
+ case "${SHELL:-}" in
+ */zsh)
+ note "! $(tilde "$1") is not on your PATH. Add it and reload your shell:"
+ todo "echo 'export PATH=\"${path_expr}:\$PATH\"' >> ~/.zshrc && source ~/.zshrc"
+ ;;
+ */bash)
+ # The tilde is printed for the user's shell to expand.
+ # shellcheck disable=SC2088
+ bash_profile="~/.bashrc"
+ # shellcheck disable=SC2088
+ if [ "$OS" = Darwin ]; then bash_profile="~/.bash_profile"; fi
+ note "! $(tilde "$1") is not on your PATH. Add it and reload your shell:"
+ todo "echo 'export PATH=\"${path_expr}:\$PATH\"' >> ${bash_profile} && source ${bash_profile}"
+ ;;
+ */fish)
+ note "! $(tilde "$1") is not on your PATH. Add it:"
+ todo "fish_add_path $(tilde "$1")"
+ ;;
+ *)
+ note "! $(tilde "$1") is not on your PATH. Add this line to your shell profile"
+ note " and open a new terminal:"
+ todo "export PATH=\"${path_expr}:\$PATH\""
+ ;;
+ esac
+ if [ "$WINDOWS" = "yes" ]; then
+ # The user PATH takes the Windows spelling (C:\...), not the MSYS one.
+ win_bin_dir="$1"
+ if command -v cygpath >/dev/null 2>&1; then
+ win_bin_dir="$(cygpath -w "$1" 2>/dev/null)" || win_bin_dir="$1"
fi
- ;;
-esac
+ note "! For PowerShell and cmd, add it to your user PATH and open a new terminal:"
+ todo "[Environment]::SetEnvironmentVariable('Path', [Environment]::GetEnvironmentVariable('Path','User') + ';${win_bin_dir}', 'User')"
+ fi
+}
+path_check_note "${bin_dir}"
+if [ -n "${PRIME_AGENT_UV_BIN_DIR:-}" ] \
+ && [ -n "$uv_bin_dir" ] \
+ && [ "$uv_bin_dir" != "${bin_dir}" ] \
+ && [ "$uv_bin_dir" != "${HOME}/.local/bin" ]; then
+ path_check_note "${uv_bin_dir}"
+fi
diff --git a/install.ps1 b/install.ps1
index 3e455c0f77..ade134768c 100644
--- a/install.ps1
+++ b/install.ps1
@@ -42,6 +42,7 @@
# PRIME_AGENT_RELEASE_CHANNEL stable | beta
# PRIME_AGENT_VERSION pin an exact version
# PRIME_AGENT_RUST_PREFIX install prefix (default: $HOME\.local)
+# PRIME_AGENT_UV_BIN_DIR uv install dir (default: $HOME\.local\bin)
#
# Prerequisites: Windows 10+ (tar.exe and Get-FileHash ship with the OS;
# the kernel's Python runtime bootstraps through uv on first session — the
@@ -90,6 +91,102 @@ try {
Fail "could not enable TLS 1.2: $($_.Exception.Message)"
}
+# --- the install ledger (install-rust.sh's step_ok / step_fail lines, in
+# --- the ASCII the console's default codepage renders cleanly) --------------
+function Step-Ok([string]$Text, [string]$Detail = '') {
+ if ($Detail) { Write-Host "ok: $Text ($Detail)" } else { Write-Host "ok: $Text" }
+}
+function Step-Fail([string]$Text, [string]$Detail = '') {
+ if ($Detail) { Write-Warning "fail: $Text ($Detail)" } else { Write-Warning "fail: $Text" }
+}
+
+# --- the whole-entry PATH compare -------------------------------------------------
+# A substring check against the joined PATH string ("$bin*") lets a sibling
+# entry like C:\Tools\bin-old mask C:\Tools\bin: the add is skipped and
+# the command stays unavailable. Membership compares WHOLE `;`-delimited
+# entries, case-insensitively (Windows paths are case-insensitive).
+function Test-PathEntry([string]$PathValue, [string]$Entry) {
+ foreach ($candidate in ($PathValue -split ';')) {
+ if ($candidate -and ($candidate.Trim() -ieq $Entry)) { return $true }
+ }
+ return $false
+}
+
+# --- the streaming download (install-rust.sh's fetch() discipline: three
+# --- attempts, and the installer's own progress, never the web cmdlet's
+# --- transfer records - a HttpClient copy loop repaints one short line in
+# --- place with the file's name, the landed bytes, and the percent) ---------
+if (-not ('System.Net.Http.HttpClient' -as [type])) {
+ Add-Type -AssemblyName System.Net.Http
+}
+function Save-Release {
+ param([string]$Uri, [string]$OutFile, [string]$Name)
+ $attempts = 0
+ while ($true) {
+ $attempts += 1
+ $client = [System.Net.Http.HttpClient]::new()
+ $response = $null
+ try {
+ $client.Timeout = [TimeSpan]::FromMinutes(30)
+ $response = $client.GetAsync($Uri, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead).GetAwaiter().GetResult()
+ if (-not $response.IsSuccessStatusCode) {
+ throw "HTTP $([int]$response.StatusCode) for $Uri"
+ }
+ $total = $response.Content.Headers.ContentLength
+ $stream = $response.Content.ReadAsStreamAsync().GetAwaiter().GetResult()
+ $file = $null
+ $done = 0L
+ try {
+ $file = [System.IO.File]::Create($OutFile)
+ $buffer = New-Object byte[] (256 * 1024)
+ # THE STALL WATCHDOG (the reviewer's finding): the
+ # HttpClient timeout above bounds only the wait for the
+ # headers under ResponseHeadersRead - a server that answers
+ # them and then parks the body would leave the synchronous
+ # read below waiting forever, and the three attempts would
+ # never run. Each chunk read is a bounded task: a body
+ # silent for the whole window throws and takes the retry
+ # path; a slow body never trips it (a read returns as data
+ # arrives, the window restarts per chunk).
+ $readTimeout = [TimeSpan]::FromSeconds(60)
+ while ($true) {
+ $readTask = $stream.ReadAsync($buffer, 0, $buffer.Length)
+ if (-not $readTask.Wait($readTimeout)) {
+ throw "the body of $Name stalled (no data for $([int]$readTimeout.TotalSeconds) seconds)"
+ }
+ $read = $readTask.Result
+ if ($read -le 0) { break }
+ $file.Write($buffer, 0, $read)
+ $done += $read
+ if ($total) {
+ $pct = [Math]::Floor($done * 100 / $total)
+ Write-Host ("`r {0}: {1:N1} of {2:N1} MB ({3}%)" -f $Name, ($done / 1MB), ($total / 1MB), $pct) -NoNewline
+ } else {
+ Write-Host ("`r {0}: {1:N1} MB" -f $Name, ($done / 1MB)) -NoNewline
+ }
+ }
+ $file.Flush()
+ } finally {
+ if ($file) { $file.Dispose() }
+ $stream.Dispose()
+ }
+ Write-Host ''
+ return
+ } catch {
+ Write-Host ''
+ Remove-Item -LiteralPath $OutFile -Force -ErrorAction SilentlyContinue
+ if ($attempts -ge 3) {
+ throw "could not download $Uri (3 attempts): $($_.Exception.Message)"
+ }
+ Write-Host "retrying $Name (attempt $($attempts + 1) of 3): $($_.Exception.Message)"
+ Start-Sleep -Seconds 1
+ } finally {
+ if ($response) { $response.Dispose() }
+ $client.Dispose()
+ }
+ }
+}
+
# --- the knobs ----------------------------------------------------------------
$baseUrl = if ($env:PRIME_AGENT_DOWNLOAD_BASE_URL) { $env:PRIME_AGENT_DOWNLOAD_BASE_URL } else { $DownloadBaseUrlDefault }
$channelRequested = $env:PRIME_AGENT_RELEASE_CHANNEL
@@ -117,6 +214,22 @@ if (@('stable', 'beta') -notcontains $channel) { Fail "unknown release channel:
# a directory path, not an existing FILE.
if (Test-Path $prefix -PathType Leaf) { Fail "the install prefix names an existing file: $prefix" }
+# THE UV TARGET KNOB VALIDATES EARLY (the reviewer's finding): a bad value
+# must fail BEFORE any side effect - the daemon stop, the payload publish,
+# and the launcher swap all happen below, and a late refusal would leave
+# a half-applied install. The target must be FULLY QUALIFIED (a
+# drive-based or UNC path WITH its server and share): a rooted-only check
+# accepts drive-relative
+# spellings like C:uv-bin or \uv-bin, which resolve against the CURRENT
+# directory in later shells - the exact break this check exists to
+# prevent.
+if ($env:PRIME_AGENT_UV_BIN_DIR -and (($env:PRIME_AGENT_UV_BIN_DIR -notmatch '^[a-zA-Z]:[\\/]') -and ($env:PRIME_AGENT_UV_BIN_DIR -notmatch '^\\\\[^\\\\]+\\[^\\\\]+'))) {
+ Fail "PRIME_AGENT_UV_BIN_DIR must be a fully qualified absolute path (a drive-based or UNC path): $($env:PRIME_AGENT_UV_BIN_DIR)"
+}
+if ($env:PRIME_AGENT_UV_BIN_DIR -and $env:PRIME_AGENT_UV_BIN_DIR.Contains(';')) {
+ Fail "PRIME_AGENT_UV_BIN_DIR must not contain a semicolon (the Windows PATH separator): $($env:PRIME_AGENT_UV_BIN_DIR)"
+}
+
# The channel files: the pointer (<base>/stable or <base>/beta) names the
# version, the channel manifest (<base>/latest.json or <base>/beta.json)
# the rows; the version resolution below reads the pair per channel.
@@ -158,22 +271,36 @@ function Read-ChannelPair($channelName) {
$pairPointer = $channelName
$pairManifestName = if ($channelName -eq 'beta') { 'beta.json' } else { 'latest.json' }
$attempt = 0
- while ($true) {
- # The pointer is published bare ("1.2.3") but a `v`-prefixed
- # spelling is a valid historical form - normalize it (the manifest's
- # version is bare; the release prefix and the artifact names carry
- # no extra `v` - the bots' finding).
- $pairVersion = (Invoke-RestMethod -Uri "$baseUrl/$pairPointer").ToString().Trim().TrimStart('v')
- if (-not $pairVersion) { Fail "could not resolve the latest $channelName version from $baseUrl/$pairPointer" }
- $pairManifest = Invoke-RestMethod -Uri "$baseUrl/$pairManifestName"
- $pairManifestVersion = ($pairManifest.version).ToString().TrimStart('v')
- if ($pairManifestVersion -eq $pairVersion) { break }
- $attempt += 1
- if ($attempt -gt 2) {
- Fail "the $channelName manifest's version $pairManifestVersion does not match the channel pointer $pairVersion (re-read twice; the channel looks inconsistent)"
+ # The same quiet discipline as the download block: these reads are web
+ # cmdlets too (their progress records flash the console); pinned here,
+ # restored on every exit - the quiet zone is the read, never the
+ # session. -UseBasicParsing keeps a stock PowerShell 5.1 (Internet
+ # Explorer never initialized) off the parsing COM path.
+ $callerProgressPreference = $ProgressPreference
+ $callerVerbosePreference = $VerbosePreference
+ $ProgressPreference = 'SilentlyContinue'
+ $VerbosePreference = 'SilentlyContinue'
+ try {
+ while ($true) {
+ # The pointer is published bare ("1.2.3") but a `v`-prefixed
+ # spelling is a valid historical form - normalize it (the manifest's
+ # version is bare; the release prefix and the artifact names carry
+ # no extra `v` - the bots' finding).
+ $pairVersion = (Invoke-RestMethod -Uri "$baseUrl/$pairPointer" -UseBasicParsing).ToString().Trim().TrimStart('v')
+ if (-not $pairVersion) { Fail "could not resolve the latest $channelName version from $baseUrl/$pairPointer" }
+ $pairManifest = Invoke-RestMethod -Uri "$baseUrl/$pairManifestName" -UseBasicParsing
+ $pairManifestVersion = ($pairManifest.version).ToString().TrimStart('v')
+ if ($pairManifestVersion -eq $pairVersion) { break }
+ $attempt += 1
+ if ($attempt -gt 2) {
+ Fail "the $channelName manifest's version $pairManifestVersion does not match the channel pointer $pairVersion (re-read twice; the channel looks inconsistent)"
+ }
+ Write-Host "the $channelName pointer and manifest disagree (a publish's consistency window); re-reading the pair..."
+ Start-Sleep -Seconds 1
}
- Write-Host "the $channelName pointer and manifest disagree (a publish's consistency window); re-reading the pair..."
- Start-Sleep -Seconds 1
+ } finally {
+ $ProgressPreference = $callerProgressPreference
+ $VerbosePreference = $callerVerbosePreference
}
return [pscustomobject]@{ Version = $pairVersion; Manifest = $pairManifest }
}
@@ -249,11 +376,31 @@ $script:primeAgentInstallScratch = $download
# bots' finding: accumulated release tarballs in the temp folder).
$tarball = Join-Path $download $expectedFile
$sumsPath = Join-Path $download 'SHA256SUMS'
+# THE QUIET DOWNLOAD (the operator's real-machine report, 2026-10-06):
+# PowerShell's web cmdlets under the default preferences leak the .NET
+# stack's transfer records onto the caller's console - the progress bar
+# and the "Writing web request / Writing request stream..." verbose
+# chatter - and under `irm | iex` this script shares the caller's
+# session, so the caller's preferences ride along. The installer pins
+# both to SilentlyContinue for its web work only and restores the
+# caller's values after (the quiet zone is the download, never the
+# session); the payload streams through Save-Release (its own in-place
+# progress line, no transfer records at all), and the checksums file's
+# small fetch stays silent under the pin.
+$callerProgressPreference = $ProgressPreference
+$callerVerbosePreference = $VerbosePreference
+$ProgressPreference = 'SilentlyContinue'
+$VerbosePreference = 'SilentlyContinue'
+Write-Host "downloading $expectedFile"
try {
- Invoke-WebRequest -Uri "$baseUrl/$releasePrefix/$expectedFile" -OutFile $tarball
- Invoke-WebRequest -Uri "$baseUrl/$releasePrefix/SHA256SUMS" -OutFile $sumsPath
+ Save-Release -Uri "$baseUrl/$releasePrefix/$expectedFile" -OutFile $tarball -Name $expectedFile
+ Invoke-WebRequest -Uri "$baseUrl/$releasePrefix/SHA256SUMS" -OutFile $sumsPath -UseBasicParsing
+ Write-Host "downloaded: $expectedFile ($([Math]::Round((Get-Item -LiteralPath $tarball).Length / 1MB, 1)) MB)"
} catch {
Fail "could not download $expectedFile from $baseUrl/$releasePrefix/: $($_.Exception.Message)"
+} finally {
+ $ProgressPreference = $callerProgressPreference
+ $VerbosePreference = $callerVerbosePreference
}
# --- verify the checksum (the release prefix's sums, cross-checked with the
@@ -264,7 +411,7 @@ $sumsSha = ($sumsLine -split '\s+')[0]
if (-not $versionPin -and $sumsSha -ne $row.sha256) { Fail "checksum mismatch between the channel manifest and SHA256SUMS for ${expectedFile}: the channel is inconsistent" }
$actualSha = (Get-FileHash -LiteralPath $tarball -Algorithm SHA256).Hash.ToLower()
if ($actualSha -ne $sumsSha) { Fail "checksum mismatch for ${expectedFile}: the download is corrupt" }
-Write-Host "checksum verified: $expectedFile ($version, the $channel channel)"
+Step-Ok 'checksum verified' "$expectedFile ($version, the $channel channel)"
# --- extract to a staging dir inside the prefix (same volume: the final swap
# --- is a rename, not a copy) -----------------------------------------------------
@@ -282,6 +429,7 @@ $script:primeAgentInstallStage = $stage
if ($LASTEXITCODE -ne 0) { Fail "could not extract $expectedFile (tar exited $LASTEXITCODE)" }
$payloadExe = Join-Path $stage 'prime-agent.exe'
if (-not (Test-Path $payloadExe -PathType Leaf)) { Fail "the tarball did not contain a prime-agent.exe payload" }
+Step-Ok 'extracted' $expectedFile
# The ownership marker (install-rust.sh's exact write shape — the update
# funnel's channel-stickiness read keys on it).
@@ -389,6 +537,7 @@ try {
# tree is valid; the restored launchers point at ../share/prime-agent/
# prime-agent.exe - the new payload - and keep working).
$published = $true
+ Step-Ok 'published' "prime-agent $version to $prefix"
# --- the launcher pair: the cmd shim (cmd.exe + PowerShell) and the sh
# --- launcher (Git Bash) - the same payload, both shells, the same
@@ -508,38 +657,263 @@ exec "$(dirname "$0")/../share/prime-agent/prime-agent.exe" "$@"
$script:primeAgentInstallLock = $null
}
-# --- the kernel pre-warm: uv + the Python venv (best-effort, install-rust.sh
-# --- parity — an offline machine still installs; the first session retries
-# --- the bootstrap online).
-$uv = Get-Command uv -ErrorAction SilentlyContinue
-if (-not $uv -and (Test-Path (Join-Path $HOME '.local\bin\uv.exe'))) { $uv = $true }
-if ($uv) {
+# --- the kernel pre-warm: uv + the Python venv (install-rust.sh
+# --- parity — the sh installer INSTALLS uv when it is missing and then
+# --- pre-warms the kernel; the ps1 mirrors the whole flow). THE SEPARATE
+# --- CHECKS (install-rust.sh's own discipline): the fetch and the script
+# --- run are verified one after the other, so a dead network cannot
+# --- masquerade as success — the astral script's own verdict is never
+# --- trusted, the uv.exe FILE decides. The destination rides the env
+# --- EXPLICITLY (UV_INSTALL_DIR, install-rust.sh's UV_INSTALL_DIR=
+# --- "$uv_bin_dir"): the computed target wins over any inherited value,
+# --- and the caller's values come back. Offline the step degrades to the
+# --- honest note plus the exact manual command (install-rust.sh's
+# --- note/todo shape); the install itself still succeeds.
+# THE UV TARGET KNOB (install-rust.sh's own PRIME_AGENT_UV_BIN_DIR): an
+# operator-set dir wins (a packaged install keeps uv inside its own tree,
+# the e2e harnesses point it at their scratch dir so a run never touches
+# the shared ~/.local/bin); without the knob the canonical ~/.local/bin is
+# the target (where the product's ensure_uv also looks).
+$uvInstallDir = Join-Path $HOME '.local\bin'
+# The knob's fully-qualified validation ran early with the other knobs
+# (before any side effect - see the validation block in the knobs section).
+if ($env:PRIME_AGENT_UV_BIN_DIR) { $uvInstallDir = $env:PRIME_AGENT_UV_BIN_DIR }
+$uvExe = Join-Path $uvInstallDir 'uv.exe'
+$uvDefaultExe = Join-Path (Join-Path $HOME '.local\bin') 'uv.exe'
+# THE THREE-WAY LOOKUP (the reviewer's finding): a usable uv is one on
+# PATH (Get-Command), at the install target, or at the canonical
+# ~/.local/bin - the product's own ensure_uv searches PATH and
+# ~/.local/bin, so both pre-existing spellings are honored (no duplicate
+# install), and the pre-warm gate below follows the record.
+# THE REAL-APPLICATION CHECK (the reviewer's finding): a bare Get-Command
+# also finds a PowerShell ALIAS or FUNCTION named uv in the caller's
+# session - which no child process can resolve - so only an Application
+# command (a real executable on PATH) counts.
+$uvOnPath = [bool](Get-Command uv -CommandType Application -ErrorAction SilentlyContinue)
+$uvAtTarget = Test-Path $uvExe -PathType Leaf
+$uvAtDefault = Test-Path $uvDefaultExe -PathType Leaf
+$uvKnown = $uvOnPath -or $uvAtTarget -or $uvAtDefault
+if (-not $uvKnown) {
+ Write-Host "installing uv (the kernel venv's package manager)"
+ $uvInstallerPath = Join-Path $download 'uv-install.ps1'
+ $callerProgressPreference = $ProgressPreference
+ $callerVerbosePreference = $VerbosePreference
+ $ProgressPreference = 'SilentlyContinue'
+ $VerbosePreference = 'SilentlyContinue'
+ try {
+ Invoke-WebRequest -Uri 'https://astral.sh/uv/install.ps1' -OutFile $uvInstallerPath -UseBasicParsing -TimeoutSec 60
+ if ((Test-Path $uvInstallerPath -PathType Leaf) -and ((Get-Item -LiteralPath $uvInstallerPath).Length -gt 0)) {
+ $callerUvInstallDir = $env:UV_INSTALL_DIR
+ $callerUvUnmanaged = $env:UV_UNMANAGED_INSTALL
+ $callerUvInstaller = $env:PRIME_AGENT_UV_INSTALLER
+ try {
+ $env:UV_INSTALL_DIR = $uvInstallDir
+ $env:UV_UNMANAGED_INSTALL = $null
+ # THE CHILD PROCESS (the reviewer's finding): the astral
+ # script exits 1 on its own failures (a Restricted execution
+ # policy among them - a stock Windows PowerShell 5.1 setting),
+ # and under Invoke-Expression that exit would leave THIS
+ # installer's control flow before the catch could degrade it
+ # to the honest note. The fetched script runs in its own
+ # shell with a process-scoped execution policy and its own
+ # silenced progress; the parent reads the child's exit as
+ # DATA, and the uv.exe FILE decides.
+ $childShell = if (Get-Command pwsh -CommandType Application -ErrorAction SilentlyContinue) {
+ (Get-Command pwsh -CommandType Application).Source
+ } elseif (Get-Command powershell -CommandType Application -ErrorAction SilentlyContinue) {
+ (Get-Command powershell -CommandType Application).Source
+ } else {
+ # The process we are already running under is a PowerShell:
+ # its own executable is the honest absolute fallback (a
+ # bare 'powershell' could be intercepted by a caller alias
+ # or function).
+ (Get-Process -Id $PID).Path
+ }
+ # THE PATH RIDES AS DATA (the reviewers' finding): the
+ # download dir sits under the caller's TEMP, and a profile
+ # path with an apostrophe in it would break the single-
+ # quoted literal in the child script - the child parsed
+ # dead, the install skipped, the pre-warm left undone. So
+ # the path never rides the command line OR the script text:
+ # it rides the environment (the same handoff this block
+ # already runs UV_INSTALL_DIR through), and the child reads
+ # the variable - environment inheritance is OS semantics,
+ # no PowerShell parsing of the path happens at any version.
+ $env:PRIME_AGENT_UV_INSTALLER = $uvInstallerPath
+ $childScript = @"
+`$ProgressPreference = 'SilentlyContinue'
+`$VerbosePreference = 'SilentlyContinue'
+& `$env:PRIME_AGENT_UV_INSTALLER
+"@
+ $childEncoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($childScript))
+ & $childShell -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand $childEncoded *> $null
+ $uvRunExit = $LASTEXITCODE
+ } finally {
+ $env:UV_INSTALL_DIR = $callerUvInstallDir
+ $env:UV_UNMANAGED_INSTALL = $callerUvUnmanaged
+ $env:PRIME_AGENT_UV_INSTALLER = $callerUvInstaller
+ }
+ if (-not (Test-Path $uvExe -PathType Leaf)) {
+ Step-Fail 'installing uv' "the uv installer exited $uvRunExit; uv.exe is missing"
+ } elseif ($uvRunExit -ne 0) {
+ Step-Fail 'installing uv' "the uv installer exited $uvRunExit (uv.exe landed; keeping it)"
+ } else {
+ Step-Ok 'uv installed' $uvInstallDir
+ }
+ } else {
+ Step-Fail 'installing uv' 'the fetched uv installer is empty'
+ }
+ } catch {
+ Step-Fail 'installing uv' $_.Exception.Message
+ } finally {
+ $ProgressPreference = $callerProgressPreference
+ $VerbosePreference = $callerVerbosePreference
+ Remove-Item -LiteralPath $uvInstallerPath -Force -ErrorAction SilentlyContinue
+ }
+ if (-not (Test-Path $uvExe -PathType Leaf)) {
+ Write-Host 'note: could not install uv; the kernel pre-warm was skipped. The first session needs uv. Install it with:'
+ Write-Host ' irm https://astral.sh/uv/install.ps1 | iex'
+ }
+}
+# THE PRE-WARM'S PATH FIX (install-rust.sh's own): the product's ensure_uv
+# searches PATH and ~/.local/bin/uv(.exe) - it does NOT know the
+# PRIME_AGENT_UV_BIN_DIR target - so the prepend serves the uv THIS RUN
+# installed or found at the target when nothing usable answers on PATH
+# (the reviewer's finding: a pre-warm whose uv is known but unfindable
+# fails). THE GUARD (the macroscope finding): a working PATH uv is never
+# shadowed - a stale target file cannot displace it - and a uv at the
+# canonical ~/.local/bin needs no prepend (ensure_uv finds it by itself).
+# The record is recomputed first: the install above may have landed the
+# target uv.
+$uvAtTarget = Test-Path $uvExe -PathType Leaf
+$uvKnown = $uvOnPath -or $uvAtTarget -or $uvAtDefault
+if (-not $uvOnPath -and $uvAtTarget -and -not (Test-PathEntry $env:PATH $uvInstallDir)) {
+ $env:PATH = "$uvInstallDir;$env:PATH"
+}
+if ($uvKnown) {
Write-Host 'kernel pre-warm: provisioning the Python kernel runtime'
& $launcher --prime-agent-bootstrap
if ($LASTEXITCODE -ne 0) {
- Write-Warning 'the kernel pre-warm failed (the install stands; the first session will retry it online)'
+ Step-Fail 'preparing the Python kernel' 'the first session retries it online'
+ } else {
+ Step-Ok 'kernel ready'
}
} else {
Write-Host 'note: uv was not found; the first session bootstraps the kernel itself and needs the network once'
}
-# --- the PATH note (warn, not fail — install-rust.sh parity) ---------------------
-$userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
-if ($userPath -notlike "*$bin*") {
- Write-Host "note: $bin is not on your PATH; add it for the prime-agent command:"
- Write-Host " [Environment]::SetEnvironmentVariable('Path', [Environment]::GetEnvironmentVariable('Path','User') + ';$bin', 'User')"
+# --- the PATH add (the operator's smoothness ask, 2026-10-06; the
+# --- windows-native shape of the sh installer's profile note) --------------------
+# Linux boxes usually carry ~/.local/bin on PATH already, so install-rust.sh
+# only PRINTS a profile note (it never edits a shell profile); a Windows
+# box has no %USERPROFILE%\.local\bin, and a printed-only note leaves the
+# fresh install unusable until the user edits their environment by hand.
+# Windows has a canonical user-PATH setting (the registry's User scope —
+# no admin needed), so the installer ADDS the launcher's bin dir there
+# itself: idempotent (appended only when the entry is absent, never
+# duplicated), mirrored into the CURRENT session so prime-agent works in
+# this console immediately, and a new terminal picks it up (the
+# WM_SETTINGCHANGE broadcast tells the running shells the environment
+# changed, the same way setx does — best-effort; the registry write is
+# what lasts).
+# THE REGISTRY-KIND DISCIPLINE (the reviewer's finding): the user Path is
+# often REG_EXPAND_SZ (the %VAR%-carrying kind Windows template profiles
+# write), and [Environment]::GetEnvironmentVariable returns it EXPANDED
+# while SetEnvironmentVariable writes back plain REG_SZ
+# (dotnet/runtime#1442) - %JAVA_HOME%-style entries would freeze at THIS
+# run's expansion and stop following their variables. The add reads the
+# RAW value with its kind through the registry API and writes the append
+# back with the SAME kind: the %VAR% spellings survive verbatim.
+# The durable add is BEST-EFFORT (the reviewer's finding): the session
+# PATH above already works and the payload is published at this point, so
+# a registry that will not open or write must degrade to the honest
+# manual note - never abort a finished install over the nicety.
+# THE PATH-ADD TARGETS (the reviewer's finding: a documented install
+# target must stay discoverable once the installer exits - the product's
+# own ensure_uv searches PATH and ~/.local/bin only): the launcher's bin
+# dir always, and the custom uv target when the knob placed one outside
+# the canonical default (the prefix's own bin is already the launcher's
+# bin dir then; the e2e harnesses strip their scratch entries again).
+$pathDirs = @($bin)
+if ($uvInstallDir -ne (Join-Path $HOME '.local\bin') -and $uvInstallDir -ne $bin) { $pathDirs += $uvInstallDir }
+# THE ANY-APPEND FLAG (the reviewer's finding): a write on ANY iteration
+# must broadcast - a later no-op iteration must never suppress an earlier
+# append's WM_SETTINGCHANGE (Explorer would hand new terminals a stale
+# environment). The flag initializes OUTSIDE the loop and never resets.
+$pathAdded = $false
+foreach ($binDir in $pathDirs) {
+ if (-not (Test-PathEntry $env:PATH $binDir)) {
+ $env:PATH = "$env:PATH;$binDir"
+ Write-Host "PATH: added $binDir to this session - prime-agent works in this console now"
+ }
+ $envKey = $null
+ try {
+ $envKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
+ if (-not $envKey) {
+ # A stripped profile can lack HKCU\Environment entirely.
+ $envKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')
+ }
+ $rawUserPath = $envKey.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
+ $rawUserKind = [Microsoft.Win32.RegistryValueKind]::ExpandString
+ if ($envKey.GetValueNames() -contains 'Path') {
+ $rawUserKind = $envKey.GetValueKind('Path')
+ }
+ # THE DUAL-SPELLING DEDUP (the reviewer's finding): a raw entry like
+ # %USERPROFILE%\.local\bin spells the SAME directory as the expanded
+ # $binDir, and a raw-text compare alone would miss it - the add would
+ # append the directory a second time in its expanded spelling. So the
+ # membership check runs against BOTH spellings while the append and
+ # the kind-preserving write-back keep the raw text untouched.
+ $expandedUserPath = [Environment]::ExpandEnvironmentVariables($rawUserPath)
+ if (-not (Test-PathEntry $rawUserPath $binDir) -and -not (Test-PathEntry $expandedUserPath $binDir)) {
+ $newUserPath = if ($rawUserPath) { $rawUserPath.TrimEnd(';') + ";$binDir" } else { $binDir }
+ $envKey.SetValue('Path', $newUserPath, $rawUserKind)
+ $pathAdded = $true
+ }
+ } catch {
+ Write-Host "note: could not persist the PATH entry to the user environment: $($_.Exception.Message)"
+ Write-Host ' this session works; to add it by hand, put this entry on the user PATH:'
+ Write-Host " $binDir"
+ } finally {
+ if ($envKey) { $envKey.Close() }
+ }
+}
+if ($pathAdded) {
+ try {
+ if (-not ('prime_agent_install.Win32SendMessage' -as [type])) {
+ Add-Type -Namespace 'prime_agent_install' -Name 'Win32SendMessage' -MemberDefinition @'
+[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
+public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);
+'@
+ }
+ [prime_agent_install.Win32SendMessage]::SendMessageTimeout([IntPtr]0xffff, 0x001A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]([UIntPtr]::Zero))
+ } catch {
+ # The registry write stands; the broadcast is a courtesy (a re-login
+ # reloads the environment too).
+ }
+ Write-Host "PATH: added the missing entries to the user PATH (a new terminal picks them up automatically)"
}
# --- verify: the launcher must answer --version -----------------------------------
try {
$versionOut = (& $launcher --version) 2>$null | Select-Object -First 1
if ($LASTEXITCODE -ne 0) {
- Write-Warning "the installed launcher failed --version (exit code $LASTEXITCODE; the first run bootstraps the kernel venv — re-run it)"
+ if ($LASTEXITCODE -eq -1073741515) {
+ # 0xC0000135, STATUS_DLL_NOT_FOUND: the launcher's process never
+ # started - a runtime DLL the binary links is missing. The shipped
+ # build links the STATIC VC runtime, so this class should not
+ # occur; the honest message replaces the venv-bootstrap claim (a
+ # DLL failure has nothing to do with the kernel venv, and
+ # re-running cannot fix it).
+ Write-Warning "the installed launcher failed --version with exit code -1073741515 (0xC0000135: the launcher could not start - a runtime DLL it needs is missing; the shipped build links the static runtime and should not need one - please report this install)"
+ } else {
+ Write-Warning "the installed launcher failed --version (exit code $LASTEXITCODE; the first run bootstraps the kernel venv - re-run it)"
+ }
} else {
Write-Host "installed: $versionOut"
}
} catch {
- Write-Warning "the first --version run failed (the first run bootstraps the kernel venv — re-run it): $($_.Exception.Message)"
+ Write-Warning "the first --version run failed (the first run bootstraps the kernel venv - re-run it): $($_.Exception.Message)"
}
Write-Host "launcher: $launcher"
Write-Host "payload: $share"
diff --git a/scripts/release/test_windows_channel_fallback.ps1 b/scripts/release/test_windows_channel_fallback.ps1
index 2bd3ffce8f..122c4890aa 100644
--- a/scripts/release/test_windows_channel_fallback.ps1
+++ b/scripts/release/test_windows_channel_fallback.ps1
@@ -78,7 +78,27 @@ function Invoke-Installer {
# test reads it back from the log.
$serverLog = Join-Path $scratch 'channel-server.log'
$server = Start-Process -FilePath $py -ArgumentList '-u','-m','http.server','0','--bind','127.0.0.1','--directory',$channel -PassThru -WindowStyle Hidden -RedirectStandardOutput $serverLog
+# install.ps1 writes the User PATH (the PATH-parity flow) and installs uv
+# when the machine has none (the astral route); the harness strips exactly
+# its own scratch-prefixed PATH entries in the cleanup below.
+# THE UV INSTALL IS ISOLATED (the reviewers' finding): ownership of a file
+# in the shared ~/.local/bin is unprovable, so the harness never lets the
+# installer touch the shared dir - install.ps1 honors
+# PRIME_AGENT_UV_BIN_DIR and the harness points it at its scratch.
+# The kernel pre-warm's writes (the venv, uv's cache, uv's pythons) would
+# land in the real user profile too; the harness steers all of them into
+# its own scratch dir through the product's override knobs and restores
+# the caller's values in the cleanup (the discipline install.ps1 itself
+# runs).
+$callerKernelVenv = $env:PRIME_AGENT_KERNEL_VENV
+$callerUvCacheDir = $env:UV_CACHE_DIR
+$callerUvPythonDir = $env:UV_PYTHON_INSTALL_DIR
+$callerUvBinDir = $env:PRIME_AGENT_UV_BIN_DIR
try {
+ $env:PRIME_AGENT_KERNEL_VENV = Join-Path $scratch 'kernel-venv'
+ $env:UV_CACHE_DIR = Join-Path $scratch 'uv-cache'
+ $env:UV_PYTHON_INSTALL_DIR = Join-Path $scratch 'uv-python'
+ $env:PRIME_AGENT_UV_BIN_DIR = Join-Path $scratch 'uv-bin'
# The port the server itself announced, then readiness is it answering
# a request for this test's own channel (beta.json): bounded deadlines,
# and a dead child fails fast instead of hanging the installer.
@@ -144,5 +164,48 @@ try {
Write-Host "WIN_CHANNEL_FALLBACK default->beta=$betaVersion notice+marker verified; explicit-stable refused with the beta route"
} finally {
Stop-Process -Id $server.Id -Force -ErrorAction SilentlyContinue
+ # The User PATH: strip ONLY the entries this test added - the ones
+ # under its own scratch dir - from the CURRENT registry value, never
+ # a stale snapshot restore (a whole-value overwrite would clobber any
+ # external PATH change made while the test ran) and never through
+ # [Environment]::SetEnvironmentVariable (it flattens a REG_EXPAND_SZ
+ # Path to plain REG_SZ with this run's expansion frozen in). The raw
+ # value rides out with its registry kind intact; a Path this test
+ # created from nothing is deleted again; a Path it never touched is
+ # not rewritten at all. A cleanup failure is recorded and the
+ # remaining steps still run (the loud tail below reports it).
+ $pathCleanFailed = $false
+ $envKey = $null
+ try {
+ $envKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
+ $rawUserPath = $envKey.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
+ $rawUserKind = [Microsoft.Win32.RegistryValueKind]::ExpandString
+ if ($envKey.GetValueNames() -contains 'Path') {
+ $rawUserKind = $envKey.GetValueKind('Path')
+ }
+ $allEntries = @($rawUserPath -split ';')
+ $keptEntries = @($allEntries | Where-Object { -not $_.Trim().StartsWith($scratch, [System.StringComparison]::OrdinalIgnoreCase) })
+ if ($keptEntries.Count -lt $allEntries.Count) {
+ if ($keptEntries.Count -gt 0) {
+ $envKey.SetValue('Path', ($keptEntries -join ';'), $rawUserKind)
+ } else {
+ $envKey.DeleteValue('Path', $false)
+ }
+ }
+ } catch {
+ $pathCleanFailed = $true
+ } finally {
+ if ($envKey) { $envKey.Close() }
+ }
+ # The uv install needs no cleanup: it never left the scratch dir (the
+ # PRIME_AGENT_UV_BIN_DIR knob above steered the installer), and the
+ # user's ~/.local/bin was never touched at all.
+ $env:PRIME_AGENT_KERNEL_VENV = $callerKernelVenv
+ $env:UV_CACHE_DIR = $callerUvCacheDir
+ $env:UV_PYTHON_INSTALL_DIR = $callerUvPythonDir
+ $env:PRIME_AGENT_UV_BIN_DIR = $callerUvBinDir
Remove-Item -Recurse -Force $scratch -ErrorAction SilentlyContinue
+ if ($pathCleanFailed) {
+ throw 'could not clean the user PATH entries this test added'
+ }
}
diff --git a/scripts/release/test_windows_install.ps1 b/scripts/release/test_windows_install.ps1
index 6064a06fbf..e35e3cf691 100644
--- a/scripts/release/test_windows_install.ps1
+++ b/scripts/release/test_windows_install.ps1
@@ -12,8 +12,9 @@
# 5. assert each route's launcher answers --version and the payload
# layout carries the .exe binary + the runtime sidecar + skills.
#
-# The kernel pre-warm rides its no-uv note path (the runner has no uv; the
-# install must still succeed — the first session bootstraps online).
+# The kernel pre-warm installs uv when it is missing (the astral route; the
+# runner has no uv but the network is up), then bootstraps the kernel venv —
+# offline the step degrades to an honest note and the install still succeeds.
#
# Usage (from the repo root, on windows-latest):
# pwsh -File scripts/release/test_windows_install.ps1
@@ -27,8 +28,63 @@ New-Item -ItemType Directory -Path $scratch | Out-Null
# The Python interpreter (the assembler + the local http server).
$py = if (Get-Command python3 -ErrorAction SilentlyContinue) { 'python3' } else { 'python' }
-# 1. The release binary + the bundled catalog assets.
-& cargo build --release --locked -p pa-cli
+# THE PE IMPORT WALK: the release artifact's DLL imports, read straight
+# from the PE headers (no dumpbin dependency on the runner).
+function Get-PeImportDlls {
+ param([string]$Path)
+ $bytes = [System.IO.File]::ReadAllBytes($Path)
+ $peOffset = [BitConverter]::ToInt32($bytes, 0x3C)
+ $signature = [Text.Encoding]::ASCII.GetString($bytes, $peOffset, 4)
+ if ($signature -ne "PE`0`0") { throw "not a PE file: $Path" }
+ $optionalHeaderOffset = $peOffset + 24
+ $magic = [BitConverter]::ToUInt16($bytes, $optionalHeaderOffset)
+ if ($magic -ne 0x20B) { throw "not a PE32+ file (magic 0x{0:X4}): $Path" -f $magic }
+ # PE32+ optional header: the data directories start at +112; the import
+ # table is directory 1.
+ $importRva = [BitConverter]::ToUInt32($bytes, $optionalHeaderOffset + 112 + 8)
+ if ($importRva -eq 0) { return @() }
+ $numSections = [BitConverter]::ToUInt16($bytes, $peOffset + 6)
+ $sizeOfOptionalHeader = [BitConverter]::ToUInt16($bytes, $peOffset + 20)
+ $sectionTableOffset = $peOffset + 24 + $sizeOfOptionalHeader
+ function ConvertTo-FileOffset([int]$Rva) {
+ for ($i = 0; $i -lt $numSections; $i++) {
+ $section = $sectionTableOffset + ($i * 40)
+ $virtualAddress = [BitConverter]::ToUInt32($bytes, $section + 12)
+ $virtualSize = [BitConverter]::ToUInt32($bytes, $section + 8)
+ $rawPointer = [BitConverter]::ToUInt32($bytes, $section + 20)
+ if ($Rva -ge $virtualAddress -and $Rva -lt ($virtualAddress + $virtualSize)) {
+ return $Rva - $virtualAddress + $rawPointer
+ }
+ }
+ throw "rva 0x{0:X} lies outside every section" -f $Rva
+ }
+ $dlls = @()
+ $descriptor = ConvertTo-FileOffset $importRva
+ while ($true) {
+ $nameRva = [BitConverter]::ToUInt32($bytes, $descriptor + 12)
+ if ($nameRva -eq 0) { break }
+ $nameOffset = ConvertTo-FileOffset $nameRva
+ $end = $nameOffset
+ while ($bytes[$end] -ne 0) { $end++ }
+ $dlls += [Text.Encoding]::ASCII.GetString($bytes, $nameOffset, $end - $nameOffset)
+ $descriptor += 20
+ }
+ return $dlls
+}
+
+# 1. The release binary + the bundled catalog assets. THE SHIPPED LINK MODE
+# (the reviewer's finding): the release workflow builds the Windows binary
+# with the step-scoped crt-static RUSTFLAGS; this e2e must install the
+# SAME link mode - a plain dynamic build would pass the launcher smoke on
+# this runner image (which carries vcruntime140.dll) and mask the stock-box
+# 0xC0000135 regression the shipped static link exists to fix. The import
+# walk below proves the built binary really dropped the redist runtime DLL.
+$env:RUSTFLAGS = '-C target-feature=+crt-static'
+try {
+ & cargo build --release --locked -p pa-cli --bin prime-agent
+} finally {
+ $env:RUSTFLAGS = $null
+}
if ($LASTEXITCODE -ne 0) { throw 'cargo build --release -p pa-cli failed' }
$assets = Join-Path $scratch 'catalog-assets'
& $py scripts/release/bundle_catalog.py generate --fixture --out $assets
@@ -39,6 +95,14 @@ if ($LASTEXITCODE -ne 0) { throw 'the catalog fixture generation failed' }
$dist = Join-Path $scratch 'dist'
$binary = Join-Path $repo 'target\release\prime-agent.exe'
if (-not (Test-Path $binary)) { throw "the release binary is missing: $binary" }
+# The stock-box regression guard: the shipped binary must not import the
+# redist VC runtime (the runner has it, a stock machine does not).
+$importedDlls = Get-PeImportDlls -Path $binary
+$vcImports = @($importedDlls | Where-Object { $_ -match 'vcruntime' })
+if ($vcImports.Count -gt 0) {
+ throw "the release binary imports the redist VC runtime ($($vcImports -join ', ')); the crt-static build did not take"
+}
+Write-Host "link mode: no vcruntime import ($($importedDlls.Count) DLL imports)"
$version = & $binary --version
if (-not $version) { throw 'the release binary did not answer --version' }
& $py scripts/release/assemble_artifacts.py --repo-root $repo --version $version --target x86_64-pc-windows-msvc --binary $binary --catalog-assets $assets --out-dir $dist
@@ -60,7 +124,32 @@ Set-Content -LiteralPath (Join-Path $channel 'latest.json') -Value "{`"version`"
# 4. Serve the channel on localhost (the installers read everything from
# this one base URL).
$server = Start-Process -FilePath $py -ArgumentList '-m','http.server','8123','--directory',$channel -PassThru -WindowStyle Hidden
+# install.ps1 writes the User PATH (the PATH-parity flow); the e2e strips
+# exactly its own scratch-prefixed PATH entries in the cleanup below (a
+# stale whole-value snapshot would linger or clobber). THE UV INSTALL IS
+# ISOLATED (the reviewers' finding): ownership of a file in the shared
+# ~/.local/bin is unprovable (a transcript line proves an attempt, not a
+# landing; a concurrent external install races the attribution) - so the
+# harness never lets the installers touch the shared dir: both routes
+# honor PRIME_AGENT_UV_BIN_DIR and the harness points it at its scratch.
+# The uv PRE-STATE still guards the parity gate below - install.ps1 skips
+# its uv branch when the machine already answers uv, so the gate runs
+# only against the fresh-runner contract.
+$uvWasOnPath = [bool](Get-Command uv -CommandType Application -ErrorAction SilentlyContinue) -or (Test-Path (Join-Path $HOME '.local\bin\uv.exe'))
+# The kernel pre-warm's writes (the venv, uv's cache, uv's pythons) and the
+# uv install itself would land in the real user profile; the harness
+# steers all of them into its own scratch dir through the product's
+# override knobs and restores the caller's values in the cleanup (the
+# discipline install.ps1 itself runs).
+$callerKernelVenv = $env:PRIME_AGENT_KERNEL_VENV
+$callerUvCacheDir = $env:UV_CACHE_DIR
+$callerUvPythonDir = $env:UV_PYTHON_INSTALL_DIR
+$callerUvBinDir = $env:PRIME_AGENT_UV_BIN_DIR
try {
+ $env:PRIME_AGENT_KERNEL_VENV = Join-Path $scratch 'kernel-venv'
+ $env:UV_CACHE_DIR = Join-Path $scratch 'uv-cache'
+ $env:UV_PYTHON_INSTALL_DIR = Join-Path $scratch 'uv-python'
+ $env:PRIME_AGENT_UV_BIN_DIR = Join-Path $scratch 'uv-bin'
Start-Sleep -Seconds 2
$base = 'http://localhost:8123'
@@ -74,8 +163,11 @@ try {
$env:PRIME_AGENT_RELEASE_CHANNEL = 'stable'
$env:PRIME_AGENT_RUST_PREFIX = $prefixA
$env:PRIME_AGENT_ALLOW_HTTP = '1'
- & pwsh -File (Join-Path $repo 'install.ps1')
- if ($LASTEXITCODE -ne 0) { throw 'install.ps1 failed' }
+ # The transcript is captured (the fallback harness's pattern): it is the
+ # uv gate's evidence below - the branch's own verdict, not the network's.
+ $ps1Lines = @(& pwsh -File (Join-Path $repo 'install.ps1') 2>&1 | ForEach-Object { "$_" })
+ if ($LASTEXITCODE -ne 0) { $ps1Lines | Write-Host; throw 'install.ps1 failed' }
+ $ps1Transcript = $ps1Lines -join [Environment]::NewLine
$cmdLauncher = Join-Path $prefixA 'bin\prime-agent.cmd'
if (-not (Test-Path $cmdLauncher)) { throw "the cmd launcher is missing: $cmdLauncher" }
$versionA = (& $cmdLauncher --version) | Select-Object -First 1
@@ -83,6 +175,18 @@ try {
foreach ($entry in @('share\prime-agent\prime-agent.exe', 'share\prime-agent\prime-agent-runtime\pyproject.toml', 'share\prime-agent\LICENSE', 'share\prime-agent\skills')) {
if (-not (Test-Path (Join-Path $prefixA $entry))) { throw "the ps1 route's payload is missing $entry" }
}
+ # The uv parity gate asserts the CONTRACT, never astral.sh availability
+ # (the reviewer's finding): the branch is best-effort by design - offline
+ # it degrades to the honest note and the install still succeeds - so
+ # the gate demands either the landed binary (the online path) or the
+ # honest degradation in the transcript. A branch that lands NEITHER is
+ # broken; the network being down is not.
+ $uvExePath = Join-Path (Join-Path $scratch 'uv-bin') 'uv.exe'
+ $uvLanded = Test-Path $uvExePath
+ $degradedHonestly = $ps1Transcript -match [regex]::Escape('could not install uv; the kernel pre-warm was skipped')
+ if (-not $uvWasOnPath -and -not $uvLanded -and -not $degradedHonestly) {
+ throw "install.ps1's uv branch landed no uv.exe and no honest degradation note (the branch is broken, not the network)"
+ }
# 6. Route B: install-rust.sh under Git Bash (the sh entry point).
$prefixB = Join-Path $scratch 'prefix-b'
@@ -111,5 +215,48 @@ try {
Write-Host "WIN_INSTALL_E2E ps1=$versionA sh=${versionB}: both routes installed the ${version} win32-x64 payload and answered --version"
} finally {
Stop-Process -Id $server.Id -Force -ErrorAction SilentlyContinue
+ # The User PATH: strip ONLY the entries this test added - the ones
+ # under its own scratch dir - from the CURRENT registry value, never
+ # a stale snapshot restore (a whole-value overwrite would clobber any
+ # external PATH change made while the test ran) and never through
+ # [Environment]::SetEnvironmentVariable (it flattens a REG_EXPAND_SZ
+ # Path to plain REG_SZ with this run's expansion frozen in). The raw
+ # value rides out with its registry kind intact; a Path this test
+ # created from nothing is deleted again; a Path it never touched is
+ # not rewritten at all. A cleanup failure is recorded and the
+ # remaining steps still run (the loud tail below reports it).
+ $pathCleanFailed = $false
+ $envKey = $null
+ try {
+ $envKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
+ $rawUserPath = $envKey.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
+ $rawUserKind = [Microsoft.Win32.RegistryValueKind]::ExpandString
+ if ($envKey.GetValueNames() -contains 'Path') {
+ $rawUserKind = $envKey.GetValueKind('Path')
+ }
+ $allEntries = @($rawUserPath -split ';')
+ $keptEntries = @($allEntries | Where-Object { -not $_.Trim().StartsWith($scratch, [System.StringComparison]::OrdinalIgnoreCase) })
+ if ($keptEntries.Count -lt $allEntries.Count) {
+ if ($keptEntries.Count -gt 0) {
+ $envKey.SetValue('Path', ($keptEntries -join ';'), $rawUserKind)
+ } else {
+ $envKey.DeleteValue('Path', $false)
+ }
+ }
+ } catch {
+ $pathCleanFailed = $true
+ } finally {
+ if ($envKey) { $envKey.Close() }
+ }
+ # The uv install needs no cleanup: it never left the scratch dir (the
+ # PRIME_AGENT_UV_BIN_DIR knob above steered both installers), and the
+ # user's ~/.local/bin was never touched at all.
+ $env:PRIME_AGENT_KERNEL_VENV = $callerKernelVenv
+ $env:UV_CACHE_DIR = $callerUvCacheDir
+ $env:UV_PYTHON_INSTALL_DIR = $callerUvPythonDir
+ $env:PRIME_AGENT_UV_BIN_DIR = $callerUvBinDir
Remove-Item -Recurse -Force $scratch -ErrorAction SilentlyContinue
+ if ($pathCleanFailed) {
+ throw 'could not clean the user PATH entries this test added'
+ }
}