Skip to content

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

Rust

ship windows support (#3196)

kt18632f7df03b
diff --git a/.github/workflows/release-prepare.yml b/.github/workflows/release-prepare.yml
index 5f07fc1611..3b424f619f 100644
--- a/.github/workflows/release-prepare.yml
+++ b/.github/workflows/release-prepare.yml
@@ -233,8 +233,9 @@ jobs:
PR's squash-merge commit via the GitHub API (the release-bot App; no
user PAT, no local tags).
2. `release.yml` (tag-triggered, unchanged) validates tag == Cargo.toml,
- builds the 4-target matrix, and `promote` waits for the protected
- `release` environment approval - **the approval is the publish**.
+ builds the 5-target matrix (the windows MSVC build included), and
+ `promote` waits for the protected `release` environment approval -
+ **the approval is the publish**.
3. On approval: assets + SHA256SUMS + SBOMs + SLSA provenance +
`latest.json` land on the `{tag}` GitHub release; the in-app updater
(`latest.json`) picks it up, and the curl install lands with the
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 1bde8b13f8..a85e8d0f6e 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1,7 +1,7 @@
# Release pipeline for Prime Agent (Rust).
#
# THE TWO BUILD ROUTES (one promote gate):
-# - a plain vX.Y.Z tag (stable) BUILDS its own 4-target matrix: the stable
+# - a plain vX.Y.Z tag (stable) BUILDS its own 5-target matrix: the stable
# cadence is rare, and its cut must not depend on a continuous run the
# staleness gate may have skipped (a superseded push builds nothing) or
# artifact retention may have evicted;
@@ -19,6 +19,8 @@
# green gates on that commit). Both routes upload the same
# artifacts-<target> set into this run, so the promote gate consumes
# one shape from either route.
+# - the Windows target (build-windows) BUILDS on both routes: continuous
+# builds no Windows target, so a beta has no win32 artifact to consume.
#
name: release
@@ -108,14 +110,16 @@ jobs:
strategy:
fail-fast: false
matrix:
+ # Windows cannot ride this matrix: the job-level `container:` pins the
+ # linux builds to the reviewed ubuntu:22.04 image (the digest-pinned
+ # glibc baseline), and a Windows runner cannot host that container.
+ # The MSVC target builds in its own `build-windows` job below (the
+ # build-darwin pattern).
include:
- target: x86_64-unknown-linux-gnu
runs-on: ubuntu-24.04
- target: aarch64-unknown-linux-gnu
runs-on: ubuntu-24.04-arm
- # Windows ships when the platform trait impls land:
- # - target: x86_64-pc-windows-msvc
- # runs-on: windows-2022
env:
# AppleDouble resource forks must not leak into the archive; the
# assembler additionally enforces plain-file payloads.
@@ -309,6 +313,89 @@ jobs:
target/${{ matrix.target }}/dist/manifest.json
if-no-files-found: error
+ # The Windows build: its own job (the build-darwin pattern), because the
+ # GNU builds pin their glibc baseline inside the digest-reviewed ubuntu:22.04
+ # container - a runner-level image a windows runner cannot host. The runner
+ # label is pinned to windows-2022 (never the mutable windows-latest) for the
+ # same reviewed-baseline reason as the container digest: a label that
+ # drifts under promote would drift the release baseline; it moves only
+ # through reviewed changes.
+ #
+ # BOTH ROUTES build it: the continuous workflow builds no Windows target,
+ # so a -beta* tag has no continuous win32 artifact to consume - this job
+ # builds the tag commit itself on either route and uploads the same
+ # artifacts-<target> shape into this run.
+ build-windows:
+ needs: tag-check
+ name: build-${{ matrix.target }}
+ runs-on: ${{ matrix.runs-on }}
+ permissions:
+ contents: read
+ timeout-minutes: 90
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - target: x86_64-pc-windows-msvc
+ runs-on: windows-2022
+ steps:
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ persist-credentials: false
+ # The pinned SHA is the toolchain pin: this action version has no
+ # `toolchain` input, and its parse step hard-codes 1.98.1. Change the
+ # compiler by changing the SHA; a `toolchain:` input is ignored.
+ - uses: dtolnay/rust-toolchain@ce678459e9fc7500d337468f904b95f1b5c10b5e
+ with:
+ targets: ${{ matrix.target }}
+ - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
+ with:
+ key: ${{ matrix.target }}
+ # The Windows runner images ship `python` (python3 is not a stable alias
+ # there); the release scripts run under whichever spelling exists.
+ - name: Resolve the Python interpreter
+ 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).
+ - name: Build (release, locked)
+ 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
+ run: |
+ set -euo pipefail
+ # Cargo's MSVC linker emits prime-agent.exe; the payload name the
+ # assembler stages and the installer extracts.
+ bin="target/${{ matrix.target }}/release/prime-agent.exe"
+ out="$("${bin}" --version)"
+ [[ "${out}" == "${RELEASE_VERSION#v}" ]] || { echo "binary reports '${out}', expected '${RELEASE_VERSION#v}'"; exit 1; }
+ - name: Generate bundled catalog assets (fixture, offline-safe)
+ shell: bash
+ run: |
+ set -euo pipefail
+ "${PY}" scripts/release/bundle_catalog.py generate --fixture \
+ --out "target/${{ matrix.target }}/catalog-assets"
+ - name: Assemble tarball + checksums + manifest
+ shell: bash
+ run: |
+ set -euo pipefail
+ "${PY}" scripts/release/assemble_artifacts.py \
+ --repo-root . \
+ --version "${RELEASE_VERSION#v}" \
+ --target "${{ matrix.target }}" \
+ --binary "target/${{ matrix.target }}/release/prime-agent.exe" \
+ --catalog-assets "target/${{ matrix.target }}/catalog-assets" \
+ --out-dir "target/${{ matrix.target }}/dist"
+ cat "target/${{ matrix.target }}/dist/manifest.json"
+ - name: Upload artifacts
+ uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ with:
+ name: artifacts-${{ matrix.target }}
+ path: |
+ target/${{ matrix.target }}/dist/prime-agent-*
+ target/${{ matrix.target }}/dist/SHA256SUMS
+ target/${{ matrix.target }}/dist/manifest.json
+ if-no-files-found: error
+
# THE BETA CHANNEL'S BUILD (the consume route): the continuous workflow
# already built the exact commit this beta names - nightly.yml waits out
# the pushed commit's continuous run (its whole build matrix green) before
@@ -431,14 +518,15 @@ jobs:
# promote on BOTH routes - each route deliberately skips the other two
# legs. The expression admits exactly the two healthy routes and nothing
# else: (stable) both build jobs succeeded, or (beta) the consume route
+ # succeeded - and on both, build-windows (it runs on either route)
# succeeded; a failed leg, a cancelled run, or a failed tag-check leaves
# promote skipped, matching the pre-consume failure semantics. The
# artifact completeness assertion inside the gate is the belt behind the
# routing: an incomplete set fails the promotion loudly either way.
- if: ${{ !cancelled() && (
+ if: ${{ !cancelled() && needs.build-windows.result == 'success' && (
(needs.build-gnu.result == 'success' && needs.build-darwin.result == 'success')
|| needs.reuse-continuous.result == 'success') }}
- needs: [build-gnu, build-darwin, reuse-continuous]
+ needs: [build-gnu, build-darwin, build-windows, reuse-continuous]
name: promotion gate -> release attach
runs-on: ubuntu-latest
# The channel gates differ: the stable channel publishes from the protected
@@ -670,6 +758,21 @@ jobs:
rows.append(
{"platform": platform, "file": file_name, "sha256": sha}
)
+ # COMPLETENESS: the channel's platform list must match the built set.
+ # The reader serves every known platform; a manifest that silently
+ # dropped one (a skipped matrix leg, a build-job regression) would
+ # strand that platform's installs on the old channel version, so a
+ # missing row fails the release here instead of publishing a
+ # shrunken channel. `promote` needs every build job, so the merged
+ # manifest carries every known platform by construction; this gate
+ # turns that invariant into an enforced contract.
+ missing = known - seen
+ if missing:
+ sys.exit(
+ f"the release is missing artifact rows for {sorted(missing)}: "
+ "the channel manifest must carry a row for every known "
+ "platform (one build job per platform)"
+ )
document = {"version": f"v{version}"}
v1_rows = [row for row in rows if row["platform"] in v1_platforms]
if v1_rows:
@@ -700,8 +803,8 @@ jobs:
# - HEADER FORM (TS parity): the version-prefixed artifacts
# (releases/v<version>/) are immutable (1y) with their content
# types; the root pointers (latest.json, stable, beta, beta.json,
- # install.sh, install-beta.sh) are no-cache — the user path is
- # always fresh.
+ # install.sh, install-beta.sh, install.ps1, install-beta.ps1) are
+ # no-cache — the user path is always fresh.
# - NO PATS, NO LEAKS: the GitHub side uses the workflow's own
# identity (github.token); the R2 keys are repo-level secrets
# read only by this job; nothing is echoed.
@@ -745,12 +848,14 @@ jobs:
--content-type text/plain \
--cache-control 'public, max-age=31536000, immutable'
- # The rendered installer pair: the repo file's defaults ARE the
+ # The rendered installer pairs: the repo files' defaults ARE the
# official domain, so the publish render only stamps the build's
- # R2 base + channel default into the served copies. Both renders
+ # R2 base + channel default into the served copies. All renders
# publish on every cut (TS parity: a changed installer ships with
# whichever channel publishes, so the served scripts never go
- # stale between releases).
+ # stale between releases) — the sh pair (install.sh /
+ # install-beta.sh) and the Windows PowerShell pair (install.ps1 /
+ # install-beta.ps1).
render_installer() {
channel="$1"
sed -e "s|^DOWNLOAD_BASE_URL_DEFAULT=.*|DOWNLOAD_BASE_URL_DEFAULT=\"${INSTALL_BASE_URL}\"|" \
@@ -760,6 +865,20 @@ jobs:
grep -q "^RELEASE_CHANNEL_DEFAULT=${channel}$" "/tmp/install-${channel}.sh"
}
+ # The Windows-native render of the same installer (install.ps1):
+ # the same base + channel stamps, the same publish-every-cut rule.
+ # The Windows-idiomatic entry is
+ # irm <base>/install.ps1 | iex
+ # while Git-Bash users run the install-rust.sh form above.
+ render_installer_ps1() {
+ channel="$1"
+ sed -e "s|^\$DownloadBaseUrlDefault = '.*'|\$DownloadBaseUrlDefault = '${INSTALL_BASE_URL}'|" \
+ -e "s|^\$ReleaseChannelDefault = '.*'|\$ReleaseChannelDefault = '${channel}'|" \
+ "verification-source/install.ps1" > "/tmp/install-${channel}.ps1"
+ grep -qF "\$DownloadBaseUrlDefault = '${INSTALL_BASE_URL}'" "/tmp/install-${channel}.ps1"
+ grep -qF "\$ReleaseChannelDefault = '${channel}'" "/tmp/install-${channel}.ps1"
+ }
+
# THE ANNOTATED-TAG PEEL: the nightly cuts create ANNOTATED tags,
# so GITHUB_SHA is the tag OBJECT, not the commit — resolve the
# commit (and its parent) through the ref chain instead of
@@ -874,10 +993,15 @@ jobs:
--endpoint-url "$R2_ENDPOINT_URL" \
--content-type text/x-shellscript \
--cache-control no-cache
- # The stable installer (install.sh) moves ONLY on a stable
- # release — a beta cut never touches the stable channel's
- # surface (the TS version serves installs until the first
- # Rust stable release replaces it).
+ render_installer_ps1 beta
+ aws s3 cp /tmp/install-beta.ps1 "s3://${R2_BUCKET}/install-beta.ps1" \
+ --endpoint-url "$R2_ENDPOINT_URL" \
+ --content-type text/plain \
+ --cache-control no-cache
+ # The stable installers (install.sh / install.ps1) move ONLY
+ # on a stable release — a beta cut never touches the stable
+ # channel's surface (the TS version serves installs until the
+ # first Rust stable release replaces it).
echo "beta channel advanced to ${RELEASE_VERSION} at ${INSTALL_BASE_URL}"
fi
fi
@@ -895,11 +1019,21 @@ jobs:
--endpoint-url "$R2_ENDPOINT_URL" \
--content-type text/x-shellscript \
--cache-control no-cache
+ render_installer_ps1 stable
+ aws s3 cp /tmp/install-stable.ps1 "s3://${R2_BUCKET}/install.ps1" \
+ --endpoint-url "$R2_ENDPOINT_URL" \
+ --content-type text/plain \
+ --cache-control no-cache
render_installer beta
aws s3 cp /tmp/install-beta.sh "s3://${R2_BUCKET}/install-beta.sh" \
--endpoint-url "$R2_ENDPOINT_URL" \
--content-type text/x-shellscript \
--cache-control no-cache
+ render_installer_ps1 beta
+ aws s3 cp /tmp/install-beta.ps1 "s3://${R2_BUCKET}/install-beta.ps1" \
+ --endpoint-url "$R2_ENDPOINT_URL" \
+ --content-type text/plain \
+ --cache-control no-cache
echo "stable channel advanced to ${RELEASE_VERSION} at ${INSTALL_BASE_URL}"
fi
fi
diff --git a/.github/workflows/windows-runtime-triage.yml b/.github/workflows/windows-runtime-triage.yml
index 7990683db3..3281e17635 100644
--- a/.github/workflows/windows-runtime-triage.yml
+++ b/.github/workflows/windows-runtime-triage.yml
@@ -31,7 +31,11 @@ jobs:
windows-battery:
name: windows battery (on-demand)
runs-on: windows-latest
- timeout-minutes: 120
+ # GitHub-hosted jobs stop at six hours whatever this says, so 360 is
+ # the real maximum. The full pa-cli e2e set alone runs past it on this
+ # runner (measured on four dispatches), which is why the install e2e
+ # runs before the pa-cli battery.
+ timeout-minutes: 360
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
@@ -80,6 +84,22 @@ jobs:
ForEach-Object { Remove-Item -Path ("Env:" + $_.Name) -ErrorAction SilentlyContinue }
cargo test --locked -p pa-tui 2>&1 | Tee-Object -FilePath pa-tui_win.log
exit $LASTEXITCODE
+ # The Windows install gates: both entry points (install.ps1 and
+ # install-rust.sh under Git Bash) install the REAL assembled
+ # win32-x64 artifact from a locally served channel and answer
+ # --version through their launchers (scripts/release/
+ # test_windows_install.ps1). This is the shipped-product proof: the
+ # build's artifact + the installers the channel serves. THE ORDER:
+ # BEFORE the pa-cli battery - the full pa-cli e2e set runs past
+ # three hours on this runner (measured twice), so the install proof
+ # must not sit behind it.
+ - name: windows install e2e (ps1 + sh routes)
+ id: install_e2e
+ continue-on-error: true
+ shell: pwsh
+ run: |
+ pwsh -NoProfile -File scripts/release/test_windows_install.ps1 2>&1 | Tee-Object -FilePath win-install-e2e.log
+ exit $LASTEXITCODE
- name: pa-cli battery (unit + the e2e set)
id: pa_cli
continue-on-error: true
@@ -92,10 +112,10 @@ jobs:
- name: Summary + the overall verdict
shell: pwsh
run: |
- $summary = "WIN_BATTERY pa-types=${{ steps.pa_types.outcome }} pa-core=${{ steps.pa_core.outcome }} pa-daemon=${{ steps.pa_daemon.outcome }} pa-tui=${{ steps.pa_tui.outcome }} pa-cli=${{ steps.pa_cli.outcome }}"
+ $summary = "WIN_BATTERY pa-types=${{ steps.pa_types.outcome }} pa-core=${{ steps.pa_core.outcome }} pa-daemon=${{ steps.pa_daemon.outcome }} pa-tui=${{ steps.pa_tui.outcome }} pa-cli=${{ steps.pa_cli.outcome }} install-e2e=${{ steps.install_e2e.outcome }}"
Add-Content -Path win_battery_summary.log -Value $summary
Write-Output $summary
- if (@("${{ steps.pa_types.outcome }}", "${{ steps.pa_core.outcome }}", "${{ steps.pa_daemon.outcome }}", "${{ steps.pa_tui.outcome }}", "${{ steps.pa_cli.outcome }}") -contains 'failure') { exit 1 }
+ if (@("${{ steps.pa_types.outcome }}", "${{ steps.pa_core.outcome }}", "${{ steps.pa_daemon.outcome }}", "${{ steps.pa_tui.outcome }}", "${{ steps.pa_cli.outcome }}", "${{ steps.install_e2e.outcome }}") -contains 'failure') { exit 1 }
- name: Upload the per-crate logs
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
@@ -107,5 +127,6 @@ jobs:
pa-daemon_win.log
pa-tui_win.log
pa-cli_win.log
+ win-install-e2e.log
win_battery_summary.log
if-no-files-found: warn
diff --git a/Makefile b/Makefile
index 0905902c96..4affa0252d 100644
--- a/Makefile
+++ b/Makefile
@@ -22,6 +22,19 @@ windows-cross:
cargo check --workspace --target x86_64-pc-windows-gnu --all-targets
cargo clippy --workspace --target x86_64-pc-windows-gnu --all-targets -- -D warnings
+# Windows MSVC cross-check: the release target's own triple (release.yml's
+# build-windows job builds x86_64-pc-windows-msvc natively on windows-2022;
+# this gate type-checks the same target from a linux host). The check form
+# needs MSVC-side C tooling for the native build scripts (ring): cargo-xwin
+# wraps the build with the MSVC CRT + clang-cl/llvm-lib, so the gate fails
+# loudly when cargo-xwin (or the llvm tools) is missing instead of silently
+# skipping. The gnu gate above stays the cheap cfg-hygiene mirror; the
+# authoritative msvc build runs on the windows runner.
+windows-msvc-cross:
+ @rustup target list --installed | grep -q x86_64-pc-windows-msvc || { echo "x86_64-pc-windows-msvc target not installed (rustup target add x86_64-pc-windows-msvc)"; exit 1; }
+ @command -v cargo-xwin >/dev/null 2>&1 || { echo "cargo-xwin not installed (cargo install cargo-xwin --locked; it provisions the MSVC CRT + expects clang-cl/llvm-lib on PATH)"; exit 1; }
+ cargo xwin check --workspace --target x86_64-pc-windows-msvc --all-targets
+
# Lints the live workflow files (.github/workflows/).
actionlint:
@command -v actionlint >/dev/null 2>&1 || { echo "actionlint not installed (see rhysd/actionlint releases)"; exit 1; }
diff --git a/README.md b/README.md
index 5add0aef23..3ce4fdfff8 100644
--- a/README.md
+++ b/README.md
@@ -46,6 +46,14 @@ Install the latest build with the one-command installer (every push to the `rust
curl -fsSL https://app.primeintellect.ai/prime-agent/install.sh | sh
```
+On Windows, install from PowerShell:
+
+```powershell
+irm https://app.primeintellect.ai/prime-agent/install.ps1 | iex
+```
+
+The sh one-liner also works under Git Bash on Windows. Both installers publish the same layout (the launcher under `$HOME\.local\bin`, the payload under `$HOME\.local\share\prime-agent`) and read the same release channel: darwin (arm64/x64), linux (arm64/x64), and windows (x86_64, `win32-x64`).
+
The served installer and everything it downloads — the version pointers, the platform tarballs, the checksums — come from the same domain: no GitHub URL is on the user path.
## Why Prime Agent
diff --git a/crates/pa-cli/src/daemon_discovery/mod.rs b/crates/pa-cli/src/daemon_discovery/mod.rs
index 6b8adc20cf..8b0400f684 100644
--- a/crates/pa-cli/src/daemon_discovery/mod.rs
+++ b/crates/pa-cli/src/daemon_discovery/mod.rs
@@ -248,7 +248,8 @@ fn scan_socket_dir(socket_dir: &Path) -> Vec<PathBuf> {
/// Windows daemon endpoints are named pipes: there is no socket directory to
/// sweep, and discovery comes from tracked worker descriptors and the
-/// default pipe (TS `scanSocketDir` returns [] on win32).
+/// default pipe (see [`discover_daemons_with`]; TS `scanSocketDir` returns
+/// [] on win32).
#[cfg(not(unix))]
fn scan_socket_dir(_socket_dir: &Path) -> Vec<PathBuf> {
Vec::new()
@@ -464,6 +465,17 @@ pub(crate) fn verify_hello_supervisor_pid(
/// current root, tests pass their own fixture dirs. A daemon outside the
/// root is never discovered, probed, or stopped.
pub(crate) fn discover_daemons(root: &DaemonStateRoot) -> Vec<DaemonInfo> {
+ discover_daemons_with(root, cfg!(windows))
+}
+
+/// [`discover_daemons`] with the endpoint model explicit. With
+/// `named_pipes` (Windows) there is no listener census and no socket dir to
+/// sweep, so the fixed daemon pipe is always probed: an idle daemon with no
+/// tracked workers is otherwise invisible and `shutdown` would report
+/// success without stopping it. A pipe exists only while its server holds
+/// it, so an unanswered one with no listener or tracked worker is simply
+/// absent - there is no orphan file to report or remove.
+fn discover_daemons_with(root: &DaemonStateRoot, named_pipes: bool) -> Vec<DaemonInfo> {
let mut process_by_socket = std::collections::HashMap::new();
for daemon in scan_listening_daemons(root) {
if is_worker_socket_path(&daemon.socket_path, &root.socket_dir) {
@@ -485,12 +497,13 @@ pub(crate) fn discover_daemons(root: &DaemonStateRoot) -> Vec<DaemonInfo> {
.filter(|path| !is_worker_socket_path(path, &root.socket_dir)),
)
.chain(worker_sockets.iter().cloned())
+ .chain(named_pipes.then(|| root.default_socket_path.clone()))
.collect();
sockets.retain(|path| state_root_matches(root, path));
let mut infos: Vec<DaemonInfo> = sockets
.into_iter()
- .map(|socket_path| {
+ .filter_map(|socket_path| {
let proc = process_by_socket.get(&socket_path);
let probe = probe_daemon(&socket_path);
let pid = proc.map(|daemon| daemon.pid).or_else(|| {
@@ -504,10 +517,12 @@ pub(crate) fn discover_daemons(root: &DaemonStateRoot) -> Vec<DaemonInfo> {
classify_reachable(&probe)
} else if proc.is_some() || has_tracked_workers {
DaemonStatus::Unreachable
+ } else if named_pipes {
+ return None;
} else {
DaemonStatus::OrphanFile
};
- DaemonInfo {
+ Some(DaemonInfo {
pid_source: pid.map(|_| {
if proc.is_some() {
PidSource::Listener
@@ -527,7 +542,7 @@ pub(crate) fn discover_daemons(root: &DaemonStateRoot) -> Vec<DaemonInfo> {
session_count: probe.session_count,
status,
has_tracked_workers: has_tracked_workers.then_some(true),
- }
+ })
})
.collect();
sort_daemons(&mut infos);
@@ -684,6 +699,41 @@ mod tests {
assert!(!infos[0].is_default);
}
+ #[cfg(unix)]
+ #[test]
+ fn named_pipe_discovery_probes_the_default_endpoint_without_tracked_workers() {
+ let tmp = tempfile::tempdir().expect("tempdir");
+ let mut root = fixture_root(tmp.path());
+ // Outside the socket dir, so the socket-dir sweep cannot find it:
+ // only the named-pipe arm's fixed endpoint does, like the Windows
+ // daemon pipe.
+ root.default_socket_path = root.agent_dir.join("daemon-pipe.sock");
+ std::fs::create_dir_all(&root.socket_dir).expect("socket dir");
+
+ // No daemon on the pipe: nothing is reported, not a fake orphan.
+ assert!(discover_daemons_with(&root, true).is_empty());
+
+ // An idle daemon with no tracked workers. Accepted connections are
+ // dropped at once, so the probe is reachable without the hello wait.
+ let listener =
+ std::os::unix::net::UnixListener::bind(&root.default_socket_path).expect("bind");
+ std::thread::spawn(move || {
+ for stream in listener.incoming() {
+ drop(stream);
+ }
+ });
+ assert!(
+ discover_daemons_with(&root, false).is_empty(),
+ "the unix arm only sees socket-dir files and listeners"
+ );
+ let infos = discover_daemons_with(&root, true);
+ assert_eq!(infos.len(), 1);
+ assert_eq!(infos[0].socket_path, root.default_socket_path);
+ assert!(infos[0].is_default);
+ assert_eq!(infos[0].has_tracked_workers, None);
+ assert_eq!(infos[0].status, DaemonStatus::Stale);
+ }
+
#[test]
fn quiet_period_completes_after_the_threshold() {
assert!(evaluate_shutdown_quiet_period(1_500, Some(500)));
diff --git a/crates/pa-cli/tests/installer_platform_map.rs b/crates/pa-cli/tests/installer_platform_map.rs
new file mode 100644
index 0000000000..dba9c1c2ce
--- /dev/null
+++ b/crates/pa-cli/tests/installer_platform_map.rs
@@ -0,0 +1,199 @@
+//! The installer's platform map, pinned against the script's own text:
+//! the uname rows install-rust.sh resolves (the MSYS/Cygwin/MINGW Windows
+//! arm included) and the Windows contract install.ps1 serves. The map is
+//! the load-bearing seam the mission names — a user on an unsupported
+//! machine must see the honest refusal, and a Windows user (Git Bash,
+//! MSYS2, Cygwin) must land on the MSVC build's win32-x64 channel row.
+//!
+//! The detection block is EXTRACTED from install-rust.sh and driven through
+//! `sh` with a stubbed uname (the release-workflow test pattern: the real
+//! step code, fixture inputs), so the pin holds the shipped text, not a
+//! copy of it.
+
+#![cfg(unix)]
+
+use std::path::{Path, PathBuf};
+use std::process::{Command, Output};
+
+/// The repo root (crates/pa-cli -> crates -> root): install-rust.sh and
+/// install.ps1 live there.
+fn repo_root() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .ancestors()
+ .nth(2)
+ .map(Path::to_path_buf)
+ .expect("worktree root")
+}
+
+/// The script's platform-detection block, verbatim: from the uname reads
+/// through the `BINARY_NAME` if/else.
+fn platform_block(script: &str) -> String {
+ let text =
+ std::fs::read_to_string(repo_root().join(script)).expect("read the installer script");
+ let start = text.find("OS=\"$(uname -s)\"").expect("the uname -s read");
+ let name_at = start
+ + text[start..]
+ .find("BINARY_NAME=")
+ .expect("the BINARY_NAME block");
+ let fi_at = name_at + text[name_at..].find("\nfi\n").expect("the block's fi");
+ text[start..fi_at + "\nfi".len()].to_string()
+}
+
+/// Drive the extracted block under `sh` with one fake uname pair; the
+/// harness stubs `die` (the full script's function) and prints the
+/// resolved map row.
+fn detect(os: &str, arch: &str) -> Output {
+ let block = platform_block("install-rust.sh");
+ let harness = format!(
+ "#!/bin/sh\n\
+ die() {{ printf '%s\n' \"$1\" >&2; exit 1; }}\n\
+ uname() {{\n\
+ \x20 case \"$1\" in\n\
+ \x20 -s) printf '%s\\n' \"$FAKE_OS\" ;;\n\
+ \x20 -m) printf '%s\\n' \"$FAKE_ARCH\" ;;\n\
+ \x20 *) printf 'stub\\n' ;;\n\
+ \x20 esac\n\
+ }}\n\
+ {block}\n\
+ printf '%s|%s|%s|%s\\n' \"$TARGET\" \"$CHANNEL_PLATFORM\" \"$WINDOWS\" \"$BINARY_NAME\"\n"
+ );
+ let dir = tempfile::tempdir().expect("scratch dir");
+ let path = dir.path().join("harness.sh");
+ std::fs::write(&path, harness).expect("write the harness");
+ Command::new("sh")
+ .arg(&path)
+ .env("FAKE_OS", os)
+ .env("FAKE_ARCH", arch)
+ .output()
+ .expect("run the detection harness")
+}
+
+fn map_row(output: &Output) -> String {
+ String::from_utf8_lossy(&output.stdout).trim().to_string()
+}
+
+/// The five published platforms resolve to their channel rows; the Windows
+/// uname family (Git Bash, MSYS2, Cygwin) lands on the MSVC build with the
+/// `.exe` binary name.
+#[test]
+fn the_uname_map_resolves_the_published_platforms() {
+ let cases = [
+ (
+ "Darwin",
+ "arm64",
+ "aarch64-apple-darwin|darwin-arm64|no|prime-agent",
+ ),
+ (
+ "Darwin",
+ "x86_64",
+ "x86_64-apple-darwin|darwin-x64|no|prime-agent",
+ ),
+ (
+ "Linux",
+ "x86_64",
+ "x86_64-unknown-linux-gnu|linux-x64|no|prime-agent",
+ ),
+ (
+ "Linux",
+ "aarch64",
+ "aarch64-unknown-linux-gnu|linux-arm64|no|prime-agent",
+ ),
+ (
+ "MINGW64_NT-10.0-19045",
+ "x86_64",
+ "x86_64-pc-windows-msvc|win32-x64|yes|prime-agent.exe",
+ ),
+ (
+ "MSYS_NT-10.0-19045",
+ "x86_64",
+ "x86_64-pc-windows-msvc|win32-x64|yes|prime-agent.exe",
+ ),
+ (
+ "CYGWIN_NT-10.0-19045",
+ "x86_64",
+ "x86_64-pc-windows-msvc|win32-x64|yes|prime-agent.exe",
+ ),
+ ];
+ for (os, arch, expected) in cases {
+ let output = detect(os, arch);
+ assert!(
+ output.status.success(),
+ "the {os}:{arch} row must resolve: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert_eq!(map_row(&output), expected, "the {os}:{arch} row");
+ }
+}
+
+/// An unsupported machine gets the honest refusal: the full matrix — the
+/// MSVC build named — plus the Windows entry points, so the die tells the
+/// user exactly what ships.
+#[test]
+fn the_uname_map_refuses_unsupported_machines_with_the_matrix() {
+ for (os, arch) in [
+ ("Windows_NT", "x86_64"),
+ ("MINGW32_NT-10.0-19045", "i686"),
+ ("FreeBSD", "amd64"),
+ ] {
+ let output = detect(os, arch);
+ assert!(!output.status.success(), "the {os}:{arch} pair must refuse");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("no rust build is published for"),
+ "the {os}:{arch} refusal names the gap: {stderr}"
+ );
+ assert!(
+ stderr.contains("x86_64-pc-windows-msvc"),
+ "the refusal names the Windows build: {stderr}"
+ );
+ assert!(
+ stderr.contains("install.ps1"),
+ "the refusal names the Windows-native installer: {stderr}"
+ );
+ }
+}
+
+/// install.ps1's Windows contract: the win32-x64 channel row (the TS
+/// `NATIVE_PLATFORMS` spelling the manifest reader keeps), the ARM64
+/// refusal, and the two render lines the release pipeline's publish step
+/// stamps (the sed + grep contract in release.yml's promote job).
+#[test]
+fn install_ps1_carries_the_windows_contract() {
+ let text = std::fs::read_to_string(repo_root().join("install.ps1")).expect("read install.ps1");
+ // The channel row.
+ assert!(
+ text.contains("$platform = 'win32-x64'"),
+ "the ps1 serves win32-x64"
+ );
+ assert!(
+ text.contains("prime-agent-$version-$platform.tar.gz"),
+ "the ps1 validates the channel-named artifact row"
+ );
+ // The arch refusal: an ARM64 Windows machine fails loudly.
+ assert!(
+ text.contains("PROCESSOR_ARCHITECTURE") && text.contains("build only"),
+ "the ps1 refuses non-x86_64 machines loudly"
+ );
+ // The publish render's stamp lines (release.yml's render_installer_ps1
+ // sed + grep targets): both must exist verbatim at line starts.
+ assert!(
+ text.contains("$DownloadBaseUrlDefault = '"),
+ "the base-URL default line the publish stamps must exist"
+ );
+ assert!(
+ text.contains("$ReleaseChannelDefault = '"),
+ "the channel-default line the publish stamps must exist"
+ );
+ // The same layout as install-rust.sh (share\prime-agent + bin):
+ // the two routes must interoperate on one install.
+ assert!(
+ text.contains("share\\prime-agent") && text.contains("prime-agent.exe"),
+ "the ps1 publishes the same payload layout with the .exe name"
+ );
+ // The marker write: the same ownership proof the sh installer writes
+ // (the update funnel's channel-stickiness read keys on its shape).
+ assert!(
+ text.contains("install-rust.sh channel"),
+ "the ps1 writes the funnel-readable install marker"
+ );
+}
diff --git a/crates/pa-cli/tests/packaged_layout_e2e.rs b/crates/pa-cli/tests/packaged_layout_e2e.rs
index 81ba173722..9862458d4d 100644
--- a/crates/pa-cli/tests/packaged_layout_e2e.rs
+++ b/crates/pa-cli/tests/packaged_layout_e2e.rs
@@ -40,6 +40,18 @@ fn repo_root() -> PathBuf {
.expect("worktree root")
}
+/// The interpreter the release scripts run under: `python3`, or `python`
+/// where only that spelling exists (the Windows runner images; the release
+/// workflow resolves it the same way).
+fn python_interpreter() -> Option<&'static str> {
+ ["python3", "python"].into_iter().find(|name| {
+ Command::new(name)
+ .arg("--version")
+ .output()
+ .is_ok_and(|output| output.status.success())
+ })
+}
+
/// These tests stage full packaged layouts and boot the kernel; they are
/// heavy and contend on a small box, so each one holds this lock for its
/// whole body.
@@ -52,13 +64,25 @@ fn serial_lock() -> std::sync::MutexGuard<'static, ()> {
}
}
+/// The staged binary name: Cargo's MSVC linker emits `prime-agent.exe` on
+/// Windows (`std::env::consts::EXE_SUFFIX`), and the packaged layout - the
+/// installer's extract target and the binary's own exe-adjacent resolution
+/// - names the platform's spelling.
+fn packaged_binary_name() -> &'static str {
+ if cfg!(windows) {
+ "prime-agent.exe"
+ } else {
+ "prime-agent"
+ }
+}
+
/// Stage the packaged layout into `dir`: the binary, the version manifest,
/// and the shipped assets. `with_runtime` controls whether the
/// prime-agent-runtime sidecar is present (the failure-UX scenario removes
/// it).
fn stage_packaged_layout(dir: &Path, with_runtime: bool) {
std::fs::create_dir_all(dir).expect("stage dir");
- let binary = dir.join("prime-agent");
+ let binary = dir.join(packaged_binary_name());
std::fs::copy(env!("CARGO_BIN_EXE_prime-agent"), &binary).expect("copy binary");
set_executable(&binary);
std::fs::write(
@@ -135,9 +159,17 @@ fn kernel_python() -> Option<PathBuf> {
);
return Some(explicit);
}
+ // The kernel venv's interpreter spelling is platform-shaped (the venv
+ // layout the product's own bootstrap creates: `bin/python` on unix,
+ // `Scripts\python.exe` on Windows).
+ let venv_python = if cfg!(windows) {
+ "kernel-venv/Scripts/python.exe"
+ } else {
+ "kernel-venv/bin/python"
+ };
let candidate = PathBuf::from(std::env::var("HOME").map_or_else(
- |_| "/home/ubuntu/.prime/agent/kernel-venv/bin/python".to_string(),
- |home| format!("{home}/.prime/agent/kernel-venv/bin/python"),
+ |_| format!("/home/ubuntu/.prime/agent/{venv_python}"),
+ |home| format!("{home}/.prime/agent/{venv_python}"),
));
if candidate.exists() {
return Some(candidate);
@@ -177,7 +209,7 @@ impl Sandbox {
/// ambient API keys. A test that wants an override sets it after this
/// call: a later `Command::env` wins over the scrub.
fn command(&self, staged: &Path) -> Command {
- let mut command = Command::new(staged.join("prime-agent"));
+ let mut command = Command::new(staged.join(packaged_binary_name()));
command
.env("HOME", self.home.path())
.env("PRIME_AGENT_CODING_AGENT_DIR", &self.agent_dir)
@@ -527,7 +559,7 @@ struct PairedFixture {
decoder: std::path::PathBuf,
}
-fn split_paired_fixture(version: &str, target: &str, alias: &str) -> PairedFixture {
+fn split_paired_fixture(python: &str, version: &str, target: &str, alias: &str) -> PairedFixture {
let dir = tempfile::TempDir::new().expect("split fixture dir");
let source = dir.path().join("prime-agent.c");
// The packer's version pin runs `--version` and compares the output:
@@ -552,7 +584,7 @@ fn split_paired_fixture(version: &str, target: &str, alias: &str) -> PairedFixtu
String::from_utf8_lossy(&compiled.stderr)
);
let shipped = dir.path().join("prime-agent");
- let split = Command::new("python3")
+ let split = Command::new(python)
.arg(
repo_root()
.join("scripts")
@@ -595,14 +627,10 @@ fn split_paired_fixture(version: &str, target: &str, alias: &str) -> PairedFixtu
#[test]
fn packaging_dry_run_produces_artifact() {
let _guard = serial_lock();
- if !Command::new("python3")
- .arg("--version")
- .output()
- .is_ok_and(|o| o.status.success())
- {
- eprintln!("python3 not available; skipping the packaging dry-run e2e");
+ let Some(python) = python_interpreter() else {
+ eprintln!("python3/python not available; skipping the packaging dry-run e2e");
return;
- }
+ };
// A synthetic tree: the packaging must ship the sidecar without its
// .venv or bytecode caches.
let tree = tempfile::TempDir::new().expect("packaging tree");
@@ -653,7 +681,7 @@ fn packaging_dry_run_produces_artifact() {
// fixture snapshot first (deterministic, stdlib-only — the same mode
// the CI build jobs use) and passes it through.
let assets = tempfile::TempDir::new().expect("catalog assets dir");
- let bundle = Command::new("python3")
+ let bundle = Command::new(python)
.arg(
repo_root()
.join("scripts")
@@ -677,13 +705,16 @@ fn packaging_dry_run_produces_artifact() {
// Linux fail-closed: the packer accepts only a paired shipped ELF +
// decoder from split_debug.py, so the dry run first splits a tiny real
// ELF fixture — the same artifact shape the CI channel ships. The
- // split fixture dir must outlive the invocation (_split_dir below).
+ // Windows arm stages the MSVC exe (the packer carries no split-debug
+ // there). The split fixture dir must outlive the invocation (_split_dir
+ // below).
let (staged_binary, staged_decoder, _split_dir): (
std::ffi::OsString,
Option<std::ffi::OsString>,
Option<tempfile::TempDir>,
) = if std::env::consts::OS == "linux" {
let fixture = split_paired_fixture(
+ python,
env!("CARGO_PKG_VERSION"),
"x86_64-unknown-linux-gnu",
"linux-x64",
@@ -696,7 +727,21 @@ fn packaging_dry_run_produces_artifact() {
} else {
(env!("CARGO_BIN_EXE_prime-agent").into(), None, None)
};
- let mut command = Command::new("python3");
+ // The platform tag the packer derives on this host: linux-x64 on the
+ // linux CI host, win32-x64 on the windows-latest battery (the channel
+ // alias, never a bare `windows-x64` — the naming the update reader's
+ // manifest contract requires).
+ let host_platform = if cfg!(windows) {
+ "win32-x64"
+ } else {
+ "linux-x64"
+ };
+ let staged_binary_name = if cfg!(windows) {
+ "prime-agent.exe"
+ } else {
+ "prime-agent"
+ };
+ let mut command = Command::new(python);
command
.arg(repo_root().join("scripts").join("package_release.py"))
.arg("--root")
@@ -719,8 +764,13 @@ fn packaging_dry_run_produces_artifact() {
);
let version = env!("CARGO_PKG_VERSION");
- let stage = out.path().join(format!("prime-agent-{version}-linux-x64"));
- assert!(stage.join("prime-agent").is_file(), "staged binary missing");
+ let stage = out
+ .path()
+ .join(format!("prime-agent-{version}-{host_platform}"));
+ assert!(
+ stage.join(staged_binary_name).is_file(),
+ "staged binary missing"
+ );
let manifest: serde_json::Value = serde_json::from_str(
&std::fs::read_to_string(stage.join("package.json")).expect("version manifest"),
)
@@ -781,7 +831,7 @@ fn packaging_dry_run_produces_artifact() {
// version and hashes, and the tarball lists the staged layout exactly.
let archive = out
.path()
- .join(format!("prime-agent-{version}-linux-x64.tar.gz"));
+ .join(format!("prime-agent-{version}-{host_platform}.tar.gz"));
assert!(archive.is_file(), "tarball missing");
let sums = std::fs::read_to_string(out.path().join("SHA256SUMS")).expect("SHA256SUMS");
let sha256 = sha256_file(&archive);
@@ -797,8 +847,8 @@ fn packaging_dry_run_produces_artifact() {
let binaries = manifest["binaries"].as_array().expect("binaries array");
assert_eq!(binaries.len(), 1);
assert_eq!(binaries[0]["sha256"], sha256.as_str());
- assert_eq!(binaries[0]["platform"], "linux-x64");
- let executable_sha = sha256_file(&stage.join("prime-agent"));
+ assert_eq!(binaries[0]["platform"], host_platform);
+ let executable_sha = sha256_file(&stage.join(staged_binary_name));
assert_eq!(binaries[0]["executableSha256"], executable_sha.as_str());
}
@@ -994,7 +1044,13 @@ fn bootstrap_kernel_venv_from_packaged_sidecar() {
stdout.contains("kernel python:"),
"bootstrap stdout: {stdout}"
);
- let venv_python = venv.join("bin").join("python");
+ // The venv layout the product's bootstrap creates: `bin/python` on
+ // unix, `Scripts\python.exe` on Windows.
+ let venv_python = if cfg!(windows) {
+ venv.join("Scripts").join("python.exe")
+ } else {
+ venv.join("bin").join("python")
+ };
assert!(venv_python.exists(), "kernel venv python missing");
// A session boots on the fresh venv: the same kernel-cell proof as the
diff --git a/crates/pa-cli/tests/release_workflow.rs b/crates/pa-cli/tests/release_workflow.rs
index 6c2bc5a910..7aef3a7909 100644
--- a/crates/pa-cli/tests/release_workflow.rs
+++ b/crates/pa-cli/tests/release_workflow.rs
@@ -35,7 +35,7 @@
//! The structural gates run everywhere. The behavior gates execute the
//! workflow's own step scripts against simulated downloads for both layout
//! modes (the port of the TS test's per-channel triad: production-only,
-//! beta-only, both - here one target, four targets, none) and skip with a
+//! beta-only, both - here one target, five targets, none) and skip with a
//! logged reason where the box's python3 is below the floor the step
//! scripts need (python 3.12: the merge step unpacks with
//! `extractall(filter=)`; the promote runner's ubuntu-24.04 provides it).
@@ -54,27 +54,40 @@ const VERSION: &str = "0.9.9";
/// The promote step that refuses archives a TS 0.9.8 updater would install.
const TS_GUARD_STEP: &str = "Refuse archives the TypeScript updater would install";
-/// The current build matrix (release.yml `build`): the four standalone
-/// targets. The single-artifact case stands in for a trimmed matrix; the
-/// four-target case is today's full release.
-const TARGETS: [&str; 4] = [
+/// The current build matrix (release.yml's `build-gnu` + `build-darwin` +
+/// `build-windows` jobs): the five standalone targets. The single-artifact
+/// case stands in for a trimmed matrix; the five-target case is today's
+/// full release.
+const TARGETS: [&str; 5] = [
"x86_64-unknown-linux-gnu",
"aarch64-unknown-linux-gnu",
"aarch64-apple-darwin",
"x86_64-apple-darwin",
+ "x86_64-pc-windows-msvc",
];
-/// The TS release-platform alias (`assemble_artifacts.py` `TARGET_ALIASES`).
+/// The release-platform alias (`assemble_artifacts.py` `TARGET_ALIASES`).
fn platform_alias(target: &str) -> &'static str {
match target {
"x86_64-unknown-linux-gnu" => "linux-x64",
"aarch64-unknown-linux-gnu" => "linux-arm64",
"aarch64-apple-darwin" => "darwin-arm64",
"x86_64-apple-darwin" => "darwin-x64",
+ "x86_64-pc-windows-msvc" => "win32-x64",
_ => panic!("no fixture alias for target {target}"),
}
}
+/// The staged payload binary name for one target
+/// (`assemble_artifacts.py` `binary_name_for_target`): the MSVC build
+/// ships `prime-agent.exe`.
+fn binary_name(target: &str) -> &'static str {
+ match target {
+ "x86_64-pc-windows-msvc" => "prime-agent.exe",
+ _ => "prime-agent",
+ }
+}
+
/// The repo root (crates/pa-cli -> crates -> root): the workflows live there.
fn repo_root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
@@ -198,15 +211,16 @@ fn sha256_file(path: &Path) -> String {
format!("{:x}", hasher.finalize())
}
-/// One real (extractable) tar.gz archive: the staged `prime-agent` payload
-/// with deterministic member metadata, the `assemble_artifacts.py` shape,
-/// plus any `extra_members`.
-fn write_fixture_tarball(out_path: &Path, extra_members: &[&str]) {
+/// One real (extractable) tar.gz archive: the staged payload binary
+/// (`prime-agent` — or `prime-agent.exe` on the MSVC target) with
+/// deterministic member metadata, the `assemble_artifacts.py` shape, plus
+/// any `extra_members`.
+fn write_fixture_tarball(out_path: &Path, payload_name: &str, extra_members: &[&str]) {
let file = fs::File::create(out_path).expect("create the fixture archive");
let encoder = flate2::write::GzEncoder::new(file, flate2::Compression::default());
let mut archive = tar::Builder::new(encoder);
let payload = VERSION.as_bytes().to_vec();
- for name in std::iter::once("prime-agent").chain(extra_members.iter().copied()) {
+ for name in std::iter::once(payload_name).chain(extra_members.iter().copied()) {
let mut header = tar::Header::new_gnu();
header.set_size(payload.len() as u64);
header.set_mode(0o755);
@@ -234,8 +248,10 @@ fn write_artifact(dir: &Path, target: &str) -> serde_json::Value {
fn write_artifact_with(dir: &Path, target: &str, extra_members: &[&str]) -> serde_json::Value {
fs::create_dir_all(dir).expect("create the artifact directory");
- let archive_name = format!("prime-agent-{VERSION}-{target}.tar.gz");
- write_fixture_tarball(&dir.join(&archive_name), extra_members);
+ // The archive name the channel contract requires: the PLATFORM ALIAS,
+ // never the target triple (the update reader drops a triple-named row).
+ let archive_name = format!("prime-agent-{VERSION}-{}.tar.gz", platform_alias(target));
+ write_fixture_tarball(&dir.join(&archive_name), binary_name(target), extra_members);
let sha256 = sha256_file(&dir.join(&archive_name));
fs::write(
dir.join("SHA256SUMS"),
@@ -317,6 +333,87 @@ fn run_promote_gates(cwd: &Path, steps: &[Step]) -> (String, serde_json::Value)
(normalize_stdout, merged)
}
+/// The Windows build job's structural contract: the MSVC target builds on
+/// its own runner (never inside build-gnu's linux container), the livecheck
+/// names the `.exe` binary, promote needs the job, and the channel
+/// completeness gate refuses a manifest that dropped a platform row.
+#[test]
+fn windows_build_job_contract() {
+ 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");
+ assert!(
+ windows.steps.iter().any(|step| {
+ step.name.as_deref() == Some("Livecheck gate: --version prints the tag version")
+ && step
+ .run
+ .as_deref()
+ .is_some_and(|run| run.contains("release/prime-agent.exe"))
+ }),
+ "the Windows livecheck must name the .exe binary Cargo's MSVC linker emits"
+ );
+ assert!(
+ windows
+ .steps
+ .iter()
+ .any(|step| step.run.as_deref().is_some_and(|run| {
+ run.contains("cargo build --release --locked --target")
+ && !run.contains("dist/prime-agent")
+ })),
+ "the Windows build compiles the MSVC target (the split-debug step is linux-only)"
+ );
+ // promote's needs list and route gate must include build-windows (it
+ // builds on both routes): the YAML schema of this test reads jobs'
+ // steps; needs/if are asserted through the raw text (the Workflow
+ // struct does not model them).
+ assert!(
+ text.contains("needs: [build-gnu, build-darwin, build-windows, reuse-continuous]")
+ && text.contains("needs.build-windows.result == 'success'"),
+ "promote must wait for the Windows build on both routes"
+ );
+ let promote = workflow
+ .jobs
+ .get("promote")
+ .expect("the promote job exists");
+ // The completeness gate: the emission refuses a missing platform row
+ // (the platform list the installer reads must match the built set).
+ let emit = promote
+ .steps
+ .iter()
+ .find(|step| {
+ step.name.as_deref()
+ == Some("Emit the channel manifest (latest.json stable / beta.json nightly)")
+ })
+ .expect("the channel-manifest emission step exists")
+ .run
+ .as_deref()
+ .expect("the emission runs a script");
+ assert!(
+ emit.contains("missing artifact rows"),
+ "the emission must refuse a manifest missing a known platform's row"
+ );
+ // The R2 publish renders + serves the PowerShell installer pair.
+ let publish = promote
+ .steps
+ .iter()
+ .find(|step| {
+ step.name.as_deref()
+ == Some("Publish the R2 channel (the user path never touches GitHub)")
+ })
+ .expect("the R2 publish step exists")
+ .run
+ .as_deref()
+ .expect("the publish runs a script");
+ assert!(
+ publish.contains("render_installer_ps1") && publish.contains("install.ps1"),
+ "the publish must render + serve the PowerShell installer pair"
+ );
+}
+
/// The structural gate: one count-independent download-all step, pinned to
/// `incoming`, followed by the normalize step before the per-artifact gates.
#[test]
@@ -421,12 +518,12 @@ fn an_archive_with_a_root_install_sh_fails_the_ts_updater_gate() {
assert!(
output.contains(&format!(
"prime-agent-{VERSION}-{}.tar.gz: contains a root-level install.sh",
- TARGETS[2]
+ platform_alias(TARGETS[2])
)),
"the gate must name the offending archive\n{output}"
);
assert!(
- !output.contains(TARGETS[1]),
+ !output.contains(platform_alias(TARGETS[1])),
"a nested install.sh must not trip the gate\n{output}"
);
}
@@ -475,11 +572,13 @@ fn single_artifact_release_finds_the_downloaded_manifest() {
.is_file());
}
-/// The full four-target release (the TS test's both-channels case): every
-/// artifact arrives in its own named directory, and the merged manifest
-/// must carry all four binaries.
+/// The full five-target release (the TS test's both-channels case): every
+/// artifact arrives in its own named directory, the merged manifest must
+/// carry all five binaries (the Windows row included), and every
+/// platform's payload unpacks under its target triple with the staged
+/// binary name (`prime-agent.exe` on the MSVC target).
#[test]
-fn four_target_release_finds_all_downloaded_manifests() {
+fn five_target_release_finds_all_downloaded_manifests() {
let Some(_python3) = python3_binary((3, 12)) else {
return;
};
@@ -507,7 +606,7 @@ fn four_target_release_finds_all_downloaded_manifests() {
assert_eq!(
merged,
expected_merged_manifest(&rows),
- "the merged manifest must carry all four targets' binaries"
+ "the merged manifest must carry all five targets' binaries"
);
assert_eq!(
fs::read_to_string(cwd.path().join("release-out/SHA256SUMS"))
@@ -516,10 +615,12 @@ fn four_target_release_finds_all_downloaded_manifests() {
"every target's checksum line must survive the merge"
);
for target in TARGETS {
- assert!(cwd
- .path()
- .join(format!("release-unpacked/{target}/prime-agent"))
- .is_file());
+ assert!(
+ cwd.path()
+ .join(format!("release-unpacked/{target}/{}", binary_name(target)))
+ .is_file(),
+ "the {target} payload unpacks with its staged binary name"
+ );
}
}
diff --git a/crates/pa-core/src/kernel/bootstrap/venv.rs b/crates/pa-core/src/kernel/bootstrap/venv.rs
index e24392c31e..1e595b5583 100644
--- a/crates/pa-core/src/kernel/bootstrap/venv.rs
+++ b/crates/pa-core/src/kernel/bootstrap/venv.rs
@@ -29,10 +29,11 @@ pub(crate) use layout::{expand_home, resolve_writable_kernel_venv_dir};
pub use layout::{kernel_venv_dir, kernel_venv_python};
pub use probe::invalidate_runtime_probe_cache;
#[cfg(test)]
-use probe::{
- clear_in_process_probe_memo_for_tests, installed_package_dir, installed_rlm_dir,
- lock_probe_memo, runtime_probe_key,
-};
+use probe::{installed_rlm_dir, lock_probe_memo, runtime_probe_key};
+// The memo-clear helper and the live-probe package-dir walk exist only behind
+// the unix tests (see their gates in probe.rs and tests.rs).
+#[cfg(all(test, unix))]
+use probe::{clear_in_process_probe_memo_for_tests, installed_package_dir};
pub(crate) use probe::{
has_prime_agent_runtime, missing_python_skill_import_labels, missing_rlm_extra_import_labels,
};
diff --git a/crates/pa-core/src/update/installer.rs b/crates/pa-core/src/update/installer.rs
index c37dba36dd..e752a6c70e 100644
--- a/crates/pa-core/src/update/installer.rs
+++ b/crates/pa-core/src/update/installer.rs
@@ -104,6 +104,7 @@ pub fn target_for(os: &str, arch: &str) -> Option<&'static str> {
("macos", "x86_64") => Some("x86_64-apple-darwin"),
("linux", "x86_64") => Some("x86_64-unknown-linux-gnu"),
("linux", "aarch64") => Some("aarch64-unknown-linux-gnu"),
+ ("windows", "x86_64") => Some("x86_64-pc-windows-msvc"),
_ => None,
}
}
@@ -117,15 +118,25 @@ pub fn target_for(os: &str, arch: &str) -> Option<&'static str> {
pub fn current_target() -> Result<&'static str> {
target_for(std::env::consts::OS, std::env::consts::ARCH).ok_or_else(|| {
anyhow!(
- "no rust build is published for {} {} (the continuous matrix \
- builds aarch64-apple-darwin, x86_64-apple-darwin, \
- aarch64-unknown-linux-gnu, and x86_64-unknown-linux-gnu)",
- std::env::consts::OS,
- std::env::consts::ARCH
+ "{}",
+ no_build_message(std::env::consts::OS, std::env::consts::ARCH)
)
})
}
+/// The refusal `--check` prints for one platform pair: the machine plus the
+/// full published matrix, so an unsupported machine sees exactly what the
+/// channel builds (the same message install-rust.sh's uname arm dies with).
+#[must_use]
+pub fn no_build_message(os: &str, arch: &str) -> String {
+ format!(
+ "no rust build is published for {os} {arch} (the release channel \
+ builds aarch64-apple-darwin, x86_64-apple-darwin, \
+ aarch64-unknown-linux-gnu, x86_64-unknown-linux-gnu, and \
+ x86_64-pc-windows-msvc)"
+ )
+}
+
/// The commit a running version's `-continuous.<sha>` stamp names — the
/// identity `--check` compares against the latest run's `head_sha`.
#[must_use]
@@ -289,7 +300,37 @@ async fn execute_script(
channel: Option<&'static str>,
output: InstallerOutput,
) -> std::result::Result<(), UpdateFailure> {
- let mut command = tokio::process::Command::new("/bin/sh");
+ // The interpreter: the trusted absolute /bin/sh on unix (never
+ // PATH-resolved, so a poisoned PATH cannot substitute the interpreter
+ // that runs the installer with the inherited credentials); on Windows
+ // the kernel shell resolver's TRUSTED Git Bash roots - hardcoded
+ // install-dir literals, never PATH and never `where bash.exe` (the
+ // get_shell_config fallback that serves the kernel shell would let a
+ // repo-controlled PATH place the interpreter that receives the
+ // inherited GITHUB_TOKEN; the funnel must not use it).
+ #[cfg(windows)]
+ let shell = {
+ match crate::platform::shell::resolve_kernel_bash_shell(None) {
+ Some(path) => path,
+ None => {
+ return Err(UpdateFailure {
+ // No shellPath guidance here: the funnel, like its unix
+ // side (the hardcoded /bin/sh), resolves only the trusted
+ // roots - the settings key serves the kernel shell, not
+ // this privileged execution (the promise would lie).
+ message: "could not run the installer: no Git Bash found at \
+ the trusted install roots \
+ (C:\\Program Files\\Git\\bin\\bash.exe); install \
+ Git for Windows (https://git-scm.com/download/win) \
+ to update from this machine"
+ .to_string(),
+ });
+ }
+ }
+ };
+ #[cfg(not(windows))]
+ let shell = "/bin/sh";
+ let mut command = tokio::process::Command::new(shell);
command.arg(script).env(ENV_PREFIX, prefix);
// The requested channel wins; otherwise the update stays on the channel
// the install marker records (the fetched script's own default is the
@@ -379,7 +420,14 @@ fn output_tail(captured: &std::process::Output) -> Option<String> {
/// `bin/prime-agent` (still present until the takeover's uninstall) never
/// matches, so the probe can never report its version.
async fn launcher_version(prefix: &Path) -> Option<String> {
- for name in ["prime-agent", "prime-agent-rust"] {
+ // The launcher names: the .cmd twin on Windows (the sh-script launcher
+ // cannot be exec'd by CreateProcess; Rust runs .cmd through cmd.exe),
+ // the sh launcher pair on unix (the pre-takeover name second).
+ #[cfg(windows)]
+ const LAUNCHER_NAMES: [&str; 2] = ["prime-agent.cmd", "prime-agent"];
+ #[cfg(not(windows))]
+ const LAUNCHER_NAMES: [&str; 2] = ["prime-agent", "prime-agent-rust"];
+ for name in LAUNCHER_NAMES {
let launcher = prefix.join("bin").join(name);
if !launcher.is_file() {
continue;
@@ -409,6 +457,36 @@ async fn launcher_version(prefix: &Path) -> Option<String> {
mod tests {
use super::*;
+ /// The platform map `prime-agent update --check` names on every
+ /// supported platform pair (the same set install-rust.sh's uname case
+ /// resolves): the Windows pair ships the MSVC target, and the refusal
+ /// covers every other pair with the full matrix in the message.
+ #[test]
+ fn target_for_covers_the_published_matrix() {
+ assert_eq!(target_for("macos", "aarch64"), Some("aarch64-apple-darwin"));
+ assert_eq!(target_for("macos", "x86_64"), Some("x86_64-apple-darwin"));
+ assert_eq!(
+ target_for("linux", "x86_64"),
+ Some("x86_64-unknown-linux-gnu")
+ );
+ assert_eq!(
+ target_for("linux", "aarch64"),
+ Some("aarch64-unknown-linux-gnu")
+ );
+ assert_eq!(
+ target_for("windows", "x86_64"),
+ Some("x86_64-pc-windows-msvc")
+ );
+ // The unsupported pairs refuse; the message names the machine and
+ // the full matrix (the Windows build included, so a refused
+ // Windows-adjacent machine sees the MSVC target it needs).
+ assert_eq!(target_for("windows", "aarch64"), None);
+ assert_eq!(target_for("freebsd", "x86_64"), None);
+ let message = no_build_message("windows", "aarch64");
+ assert!(message.contains("windows aarch64"), "{message}");
+ assert!(message.contains("x86_64-pc-windows-msvc"), "{message}");
+ }
+
/// The installed-marker channel read: a beta install's update must
/// stay on beta (the marker the installer writes at publish carries
/// the channel), a stable or pre-marker install rides the script's
@@ -615,7 +693,7 @@ echo "installed: 9.9.8-continuous.fedcba9876543210"
}
#[test]
- fn the_target_matrix_covers_the_continuous_builds() {
+ fn the_target_matrix_covers_the_published_builds() {
assert_eq!(target_for("macos", "aarch64"), Some("aarch64-apple-darwin"));
assert_eq!(target_for("macos", "x86_64"), Some("x86_64-apple-darwin"));
assert_eq!(
@@ -626,7 +704,15 @@ echo "installed: 9.9.8-continuous.fedcba9876543210"
target_for("linux", "aarch64"),
Some("aarch64-unknown-linux-gnu")
);
- assert_eq!(target_for("windows", "x86_64"), None);
+ // The Windows pair ships the MSVC build (the release channel's
+ // fifth target since the windows ship).
+ assert_eq!(
+ target_for("windows", "x86_64"),
+ Some("x86_64-pc-windows-msvc")
+ );
+ // Windows ARM64 (the only unsupported Windows shape) and every
+ // other OS refuse.
+ assert_eq!(target_for("windows", "aarch64"), None);
assert!(
current_target().is_ok(),
"the test matrix runs on a supported platform"
diff --git a/crates/pa-core/tests/release_channel_manifest.rs b/crates/pa-core/tests/release_channel_manifest.rs
index 8ed1f75f06..e4a473d533 100644
--- a/crates/pa-core/tests/release_channel_manifest.rs
+++ b/crates/pa-core/tests/release_channel_manifest.rs
@@ -491,6 +491,49 @@ fn the_producer_refuses_rows_the_reader_rejects() {
);
}
+#[test]
+fn the_producer_refuses_a_manifest_missing_a_platform_row() {
+ let (_, workflow) = load_workflow();
+ let emit_run = channel_step_run(&workflow);
+ let fixture = tempfile::tempdir().expect("fixture dir");
+ // A merged manifest missing the Windows row (the shape a skipped
+ // build leg would produce): the completeness gate must refuse — the
+ // channel's platform list must match the built set, and a shrunken
+ // manifest would strand that platform's installs.
+ let out = stage_merged_manifest(fixture.path(), "1.2.3", false);
+ let merged: serde_json::Value = serde_json::from_str(
+ &std::fs::read_to_string(out.join("manifest.json")).expect("read the merged manifest"),
+ )
+ .expect("parse the merged manifest");
+ let rows: Vec<serde_json::Value> = merged["binaries"]
+ .as_array()
+ .expect("the binaries list")
+ .iter()
+ .filter(|row| row["platform"].as_str() != Some("win32-x64"))
+ .cloned()
+ .collect();
+ std::fs::write(
+ out.join("manifest.json"),
+ serde_json::to_string_pretty(&serde_json::json!({
+ "version": merged["version"],
+ "binaries": rows,
+ }))
+ .expect("serialize"),
+ )
+ .expect("rewrite the merged manifest without the Windows row");
+
+ let result = run_step(emit_run, fixture.path(), "v1.2.3");
+ assert!(
+ !result.status.success(),
+ "the emission must fail when a known platform's row is missing"
+ );
+ let stderr = String::from_utf8_lossy(&result.stderr);
+ assert!(
+ stderr.contains("missing artifact rows") && stderr.contains("win32-x64"),
+ "the failure names the missing platform: {stderr}"
+ );
+}
+
/// Every artifact row the reader kept must name a real archive whose bytes
/// hash to the claimed digest (a manifest that lies is worse than none).
fn assert_reader_artifacts_are_truthful(release: &LatestRelease, out: &Path) {
@@ -646,17 +689,31 @@ fn assembled_archives_carry_the_platform_alias_the_reader_demands() {
let archive_bytes = std::fs::read(&archive).expect("read the archive");
assert_eq!(row["sha256"], sha256_hex(&archive_bytes));
- // The full chain: the promote emission over the assembled row, then
- // the reader over the emitted manifest.
+ // The full chain: the promote emission over the assembled row (staged
+ // into a complete five-platform merged manifest — the completeness
+ // gate refuses a manifest missing a known platform's row), then the
+ // reader over the emitted manifest.
let out = stage_merged_manifest(fixture.path(), "1.2.3", false);
std::fs::copy(&archive, out.join("prime-agent-1.2.3-linux-x64.tar.gz"))
- .expect("stage the real archive");
- let merged = serde_json::json!({"version": "v1.2.3", "binaries": [row]});
+ .expect("stage the real archive over its fixture");
+ let merged_path = out.join("manifest.json");
+ let mut merged: serde_json::Value = serde_json::from_str(
+ &std::fs::read_to_string(&merged_path).expect("read the staged merged manifest"),
+ )
+ .expect("parse the staged merged manifest");
+ merged["binaries"]
+ .as_array_mut()
+ .expect("the staged manifest's binaries")
+ .retain(|candidate| candidate["platform"] != "linux-x64");
+ merged["binaries"]
+ .as_array_mut()
+ .expect("the staged manifest's binaries")
+ .push(row.clone());
std::fs::write(
- out.join("manifest.json"),
+ &merged_path,
serde_json::to_string_pretty(&merged).expect("serialize"),
)
- .expect("write the merged manifest");
+ .expect("write the merged manifest with the assembled row");
let result = run_step(emit_run, fixture.path(), "v1.2.3");
assert!(
result.status.success(),
@@ -667,9 +724,14 @@ fn assembled_archives_carry_the_platform_alias_the_reader_demands() {
assert_eq!(json["version"], "v1.2.3");
let release = parse_channel_manifest(&bytes).expect("the reader accepts the manifest");
assert_eq!(release.version, "1.2.3");
- assert_eq!(release.artifacts.len(), 1);
- let artifact: &ReleaseArtifact = &release.artifacts[0];
- assert_eq!(artifact.platform, "linux-x64");
+ // The reader keeps every known platform's row; the assembled linux-x64
+ // row is one of the five.
+ assert_eq!(release.artifacts.len(), 5);
+ let artifact: &ReleaseArtifact = release
+ .artifacts
+ .iter()
+ .find(|artifact| artifact.platform == "linux-x64")
+ .expect("the assembled row survived the emission");
assert_eq!(artifact.file, "prime-agent-1.2.3-linux-x64.tar.gz");
assert_eq!(artifact.sha256, sha256_hex(&archive_bytes));
}
diff --git a/crates/pa-daemon/src/supervisor/signals_shutdown.rs b/crates/pa-daemon/src/supervisor/signals_shutdown.rs
index 349e33d2e9..3cac1323d7 100644
--- a/crates/pa-daemon/src/supervisor/signals_shutdown.rs
+++ b/crates/pa-daemon/src/supervisor/signals_shutdown.rs
@@ -1,9 +1,12 @@
//! Shutdown and signal handling: the drain arms, the shutdown entry, and the
//! daemon-closing shutdown event.
-use super::{
- json, Arc, ClientRouting, Ordering, PrepareState, RouteAdmission, Supervisor, Value,
- ROUTE_TIMEOUT_MS,
-};
+use super::{json, Arc, Ordering, RouteAdmission, Supervisor, Value, ROUTE_TIMEOUT_MS};
+// The only use is the broadcast inside the unix begin_signal_drain arm.
+#[cfg(unix)]
+use super::ClientRouting;
+// The only use sits behind the unix update-drain arm below.
+#[cfg(unix)]
+use super::PrepareState;
/// The non-update `daemon_closing` frame (the shutdown command's and the
/// OS-signal drain's shared spelling): every connected client learns the
diff --git a/crates/pa-tui/src/enhanced_keys.rs b/crates/pa-tui/src/enhanced_keys.rs
index 6c514ff9ce..2999c02512 100644
--- a/crates/pa-tui/src/enhanced_keys.rs
+++ b/crates/pa-tui/src/enhanced_keys.rs
@@ -83,6 +83,8 @@
use anyhow::Result;
use std::io::{IsTerminal, Stdout, Write};
use std::sync::atomic::{AtomicBool, Ordering};
+// The probe's answer channel is unix-only (see `spawn_kitty_probe`).
+#[cfg(unix)]
use std::sync::mpsc;
use std::time::Duration;
@@ -126,6 +128,7 @@ const STALE_LEVEL_DRAIN: usize = 3;
const MODIFY_OTHER_KEYS_RESET: &[u8] = b"\x1b[>4;0m";
/// TS `keyboardProtocolFallbackTimer`: the window the kitty answer gets
/// before the modifyOtherKeys fallback fires.
+#[cfg(unix)]
const KITTY_QUERY_FALLBACK: Duration = Duration::from_millis(150);
static BRACKETED_PASTE_ACTIVE: AtomicBool = AtomicBool::new(false);
@@ -535,7 +538,9 @@ fn write_all(out: &mut Stdout, sequence: &[u8]) -> Result<()> {
/// Enable the kitty protocol (TS writes `\x1b[>7u` when the query answer
/// arrives). Skipped when the surface that started the probe is already
/// gone — a stray enable would leave the flags pushed over the next
-/// surface's own setup.
+/// surface's own setup. Unix only: the kitty probe is the unix surface
+/// (see `spawn_kitty_probe`).
+#[cfg(unix)]
fn enable_kitty(out: &mut Stdout) {
// The capability is the durable truth: a later start re-applies the
// flags from it even when this push stands down for the exit.
@@ -582,6 +587,11 @@ pub(crate) fn pop_stale_levels(out: &mut Stdout) {
/// then settle. An answer within crossterm's patched 250ms query window
/// enables kitty; no answer settles with no enhanced modes (this port
/// never arms the modifyOtherKeys fallback — see the module docs).
+/// Unix only: the kitty keyboard protocol is a unix terminal surface
+/// (the vendored crossterm exposes the raw-read check unix-only); the
+/// Windows console arm settles no-kitty below — the capability stays
+/// unresolved there, never armed.
+#[cfg(unix)]
fn spawn_kitty_probe() {
let probe = std::thread::Builder::new()
.name("tui-kitty-probe".to_string())
@@ -682,6 +692,16 @@ fn spawn_kitty_probe() {
}
}
+/// Windows has no kitty keyboard protocol probe (the vendored crossterm
+/// ships the raw-read support check unix-only): the capability settles as
+/// probed-but-unsupported — the same settle the no-answer probe path takes —
+/// and the query window closes.
+#[cfg(not(unix))]
+fn spawn_kitty_probe() {
+ KITTY_PROBED.store(true, Ordering::SeqCst);
+ QUERY_IN_FLIGHT.store(false, Ordering::SeqCst);
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -845,6 +865,9 @@ mod tests {
assert!(!enhanced_keys_active());
}
+ // The late-answer standdown is the unix probe's answer path (kitty
+ // protocol + raw modes do not exist on the non-unix targets).
+ #[cfg(unix)]
#[test]
fn release_for_exit_stands_a_late_probe_answer_down() {
let _lock = lock_state();
diff --git a/install-rust.sh b/install-rust.sh
index 360090e7cc..a3601bfbe7 100755
--- a/install-rust.sh
+++ b/install-rust.sh
@@ -616,9 +616,12 @@ fetch() {
ui_progress_total="$(curl -fsSIL --connect-timeout 10 --max-time 15 "$1" 2>/dev/null \
| tr -d '\r' | awk 'tolower($1) == "content-length:" { size = $2 } END { print size }')"
case "$ui_progress_total" in ""|*[!0-9]*) ui_progress_total="" ;; esac
- # The renderer reads the size through a fixed link in its own dir.
- ln -sf "$2" "${dl}/ui-progress"
- ui_progress_path="1"
+ # The renderer reads the size through a fixed link in its own dir. Git
+ # Bash's default ln -s deep-copies and refuses a missing target, so
+ # there the step keeps its spinner without the bar.
+ if ln -sf "$2" "${dl}/ui-progress" 2>/dev/null; then
+ ui_progress_path="1"
+ fi
ui_set_active "$ui_step"
fi
while :; do
@@ -641,8 +644,15 @@ fetch() {
# uname -m maps directly to the built target: an Apple-Silicon Mac whose
# shell (and therefore binaries) run under Rosetta 2 reports x86_64 and
# gets the x86_64 build, which is the correct build for that runtime.
+# Windows runs this script only from a POSIX shell (Git Bash / MSYS2 /
+# Cygwin): uname -s reports MINGW*_NT-*, MSYS_NT-*, or CYGWIN_NT-*, and
+# the x86_64 build is the MSVC target. The Windows-native route is
+# install.ps1 (irm | iex); this arm keeps the sh one-liner working for
+# Git Bash users. Every later section reads WINDOWS / BINARY_NAME (the
+# path spellings, the payload check, the launcher, the takeover gates).
OS="$(uname -s)"
ARCH="$(uname -m)"
+WINDOWS="no"
# CHANNEL_PLATFORM is the channel manifest's platform alias (the TS
# NATIVE_PLATFORMS spelling pa-core::update::install::current_platform_alias
# reads); TARGET stays the rust triple the payload names its targets by.
@@ -651,12 +661,24 @@ case "$OS:$ARCH" in
Darwin:x86_64) TARGET=x86_64-apple-darwin; CHANNEL_PLATFORM=darwin-x64 ;;
Linux:x86_64) TARGET=x86_64-unknown-linux-gnu; CHANNEL_PLATFORM=linux-x64 ;;
Linux:aarch64) TARGET=aarch64-unknown-linux-gnu; CHANNEL_PLATFORM=linux-arm64 ;;
+ MINGW64_NT*:x86_64|MINGW_NT*:x86_64|MSYS_NT*:x86_64|CYGWIN_NT*:x86_64)
+ TARGET=x86_64-pc-windows-msvc; CHANNEL_PLATFORM=win32-x64; WINDOWS=yes ;;
*)
die "no rust build is published for ${OS} ${ARCH} (detected via uname);
the release channel builds aarch64-apple-darwin, x86_64-apple-darwin,
-aarch64-unknown-linux-gnu, and x86_64-unknown-linux-gnu"
+aarch64-unknown-linux-gnu, x86_64-unknown-linux-gnu, and
+x86_64-pc-windows-msvc (the Windows build installs through this script
+under Git Bash/MSYS2/Cygwin — uname MINGW*_NT*/MSYS_NT*/CYGWIN_NT* — or
+through install.ps1 in PowerShell)"
;;
esac
+# The staged binary name: the MSVC build ships prime-agent.exe; the
+# extraction check, the launcher, and the manifest row all name it.
+if [ "$WINDOWS" = "yes" ]; then
+ BINARY_NAME="prime-agent.exe"
+else
+ BINARY_NAME="prime-agent"
+fi
# --- glibc floor (Linux) ------------------------------------------------------
# The continuous workflow builds the GNU/Linux targets inside an
@@ -698,9 +720,20 @@ case "$CHANNEL" in
beta) CHANNEL_MANIFEST="beta.json" ;;
*) die "unknown release channel: ${CHANNEL} (stable or beta)" ;;
esac
+# THE HTTPS RULE: a plaintext download base would let a network attacker
+# swap the payload the checksum then "verifies" into place. The one escape
+# hatch is the explicitly-named knob for a local channel or e2e run
+# (install.ps1 carries the same rule + knob); it warns when it is active.
case "$BASE_URL" in
https://*) ;;
- *) die "the download base URL must be an https URL: ${BASE_URL}" ;;
+ *)
+ if [ "${PRIME_AGENT_ALLOW_HTTP:-}" = "1" ]; then
+ note "! PRIME_AGENT_ALLOW_HTTP=1: the download base ${BASE_URL} is not https,"
+ note " so the download is plaintext. Use it only for a local channel you control."
+ else
+ die "the download base URL must be an https URL: ${BASE_URL}"
+ fi
+ ;;
esac
BASE_URL="${BASE_URL%/}"
@@ -912,7 +945,15 @@ python3 required), or install python3 yourself and re-run"
# Resolved like PREFIX below: when $HOME is a symlink, a PREFIX spelled in the
# physical form must still compare equal to the store, or the guard would
# pass two different spellings of the same directory.
-PRESERVED_STORE="$("$UVPY" -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "${HOME}/.prime/agent")"
+# Windows/MSYS resolves in the POSIX (MSYS) spelling: a native python
+# round-trips the path through Windows form (realpath answers C:\...),
+# which would make every later MSYS-form comparison miss; the sh-native
+# physical_path() keeps the guard's spellings consistent end to end.
+if [ "$WINDOWS" = "yes" ]; then
+ PRESERVED_STORE="$(physical_path "${HOME}/.prime/agent")"
+else
+ PRESERVED_STORE="$("$UVPY" -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "${HOME}/.prime/agent")"
+fi
guard_preserved() {
for guarded_path in "$@"; do
case "$guarded_path" in
@@ -941,21 +982,46 @@ fresh_slot() { # base name without suffix
case "$PREFIX" in
/*) ;;
- *) die "PRIME_AGENT_RUST_PREFIX must be an absolute path: ${PREFIX}" ;;
+ *)
+ # Windows accepts the Windows drive-letter spelling too (a user passing
+ # C:\... in Git Bash): cygpath - the MSYS2/Cygwin core tool - rewrites
+ # it to the POSIX form every later step compares in.
+ if [ "$WINDOWS" = "yes" ] && command -v cygpath >/dev/null 2>&1; then
+ PREFIX="$(cygpath -u "$PREFIX" 2>/dev/null)" || die "PRIME_AGENT_RUST_PREFIX must be an absolute path: ${PRIME_AGENT_RUST_PREFIX}"
+ case "$PREFIX" in
+ /*) ;;
+ *) die "PRIME_AGENT_RUST_PREFIX must be an absolute path: ${PRIME_AGENT_RUST_PREFIX}" ;;
+ esac
+ else
+ die "PRIME_AGENT_RUST_PREFIX must be an absolute path: ${PREFIX}"
+ fi
+ ;;
esac
# Resolve PREFIX FULLY (symlinks included) BEFORE creating anything under
# it: a prefix whose spelling hides a symlink into the shared store must
-# abort before mkdir -p ever writes there, not after.
-PREFIX="$("$UVPY" -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$PREFIX")"
+# abort before mkdir -p ever writes there, not after. Windows resolves in
+# the MSYS form (the guard's ruling above).
+if [ "$WINDOWS" = "yes" ]; then
+ PREFIX="$(physical_path "$PREFIX")"
+else
+ PREFIX="$("$UVPY" -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$PREFIX")"
+fi
guard_preserved "$PREFIX" "${PREFIX}/share" "${PREFIX}/bin"
mkdir -p "${PREFIX}/share" "${PREFIX}/bin"
# The guard must also see THROUGH symlinked child roots: a ${PREFIX}/share or
# ${PREFIX}/bin that is a symlink into the shared store would otherwise let
# the publish write under it while every lexical check passes. Resolving the
# children (not refusing them) keeps legitimate out-of-store symlinked roots
-# installable while the resolved paths go through the same guard.
+# installable while the resolved paths go through the same guard. Windows
+# resolves in the MSYS form (physical_path) — a native python round-trips
+# through C:\... spelling the MSYS-form comparison can never match, which
+# would silently disarm this child-root guard (the bots' finding).
for install_root in "${PREFIX}/share" "${PREFIX}/bin"; do
- guard_preserved "$("$UVPY" -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$install_root")"
+ if [ "$WINDOWS" = "yes" ]; then
+ guard_preserved "$(physical_path "$install_root")"
+ else
+ guard_preserved "$("$UVPY" -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$install_root")"
+ fi
done
share_dir="${PREFIX}/share/prime-agent"
@@ -1111,10 +1177,19 @@ step_ok "Verified"
# socket stops answering).
# ts_stop_summary accumulates the summary line(s); the success block
# prints them with the other takeover facts.
+# WINDOWS (uname MINGW*/MSYS/CYGWIN): the TypeScript product never shipped a
+# Windows build, so no TS daemon, native install, or npm package can exist
+# here - the whole TS-takeover ladder below is a no-op by construction, and
+# this product's daemon runs a NAMED PIPE the unix-socket probe cannot see.
+# The Windows daemon stop is the product's own `shutdown` command, run in
+# the install section BEFORE the publish (a Windows process holds its
+# binary open - the payload swap needs the daemon down first; the unix
+# flow stops daemons after the publish, which a Windows file lock refuses).
ts_stop_summary=""
ts_stop_found_any=""
ts_stop_refused=""
ts_stop_rust_stopped=""
+windows_stop_summary=""
ts_socket="${TMPDIR:-/tmp}/prime-agent-$(id -u)/daemon.sock"
rust_socket="${TMPDIR:-/tmp}/prime-agent-rust-$(id -u)/daemon.sock"
env_socket="${PRIME_AGENT_DAEMON_SOCKET:-}"
@@ -1779,8 +1854,8 @@ step_start "Installing"
stage="$(mktemp -d "${PREFIX}/share/prime-agent.stage.XXXXXX")"
guard_preserved "$stage"
tar -xzf "$asset" -C "$stage"
-[ -x "${stage}/prime-agent" ] \
- || die "the tarball did not contain an executable prime-agent payload"
+[ -x "${stage}/${BINARY_NAME}" ] \
+ || die "the tarball did not contain an executable ${BINARY_NAME} payload"
# The ownership marker: the share tree this script publishes carries it, so
# later installs recognize the tree as theirs BY MARKER, not by shape — an
# unrelated directory that happens to contain a `prime-agent` entry is never
@@ -1802,15 +1877,82 @@ if [ -e "$legacy_lock" ] || [ -L "$legacy_lock" ]; then
fi
rm -f "$legacy_lock"
fi
-until ln -s $$ "$lock_link" 2>/dev/null; do
- held_by="$(readlink "$lock_link" 2>/dev/null || true)"
- if [ -n "$held_by" ] && kill -0 "$held_by" 2>/dev/null; then
- die "another install-rust.sh (pid ${held_by}) is publishing to ${PREFIX}; retry when it finishes"
+# THE WINDOWS LOCK: MSYS `ln -s` deep-copies by default (a real symlink
+# needs Developer Mode + winsymlinks), so the symlink claim is not atomic
+# on Windows - a lock DIRECTORY is: `mkdir` is the single-winner claim and
+# the holder's pid rides a file inside it. install.ps1 claims the SAME
+# directory, so the pid is always the WINDOWS pid (the MSYS/Cygwin $$ is a
+# different namespace: /proc/$$/winpid maps it) and liveness is asked of
+# Windows (tasklist), never `kill -0`. The EXIT trap sweeps the directory;
+# a lock is never auto-stolen, and when the holder does not show as live
+# the message stays conditional (the manual-recovery contract of the link).
+if [ "$WINDOWS" = "yes" ]; then
+ lock_dir="${PREFIX}/share/.prime-agent-install.lock.d"
+ pid_waits=0
+ until mkdir "$lock_dir" 2>/dev/null; do
+ # Digits only: install.ps1's Set-Content ends the pid line with CRLF.
+ held_by="$(tr -dc '0-9' 2>/dev/null < "$lock_dir/pid" || true)"
+ # The holder writes its pid just after the mkdir claim: an empty pid is
+ # (for a few seconds) a claim in progress, not a stale lock.
+ if [ -z "$held_by" ] && [ "$pid_waits" -lt 5 ]; then
+ pid_waits=$((pid_waits + 1))
+ sleep 1
+ continue
+ fi
+ if [ -n "$held_by" ] \
+ && MSYS2_ARG_CONV_EXCL='*' tasklist.exe /FI "PID eq ${held_by}" /NH 2>/dev/null \
+ | grep -qw "$held_by"; then
+ die "another prime-agent installer (Windows pid ${held_by}) is publishing to ${PREFIX}; retry when it finishes"
+ fi
+ die "a publication lock (Windows pid ${held_by:-unknown}) is held at ${lock_dir}. If no prime-agent installer (install-rust.sh or install.ps1) is running, it is stale (a crashed install); remove it and retry:
+ rm -rf \"${lock_dir}\""
+ done
+ printf '%s\n' "$(cat "/proc/$$/winpid" 2>/dev/null || echo $$)" > "$lock_dir/pid"
+else
+ until ln -s $$ "$lock_link" 2>/dev/null; do
+ held_by="$(readlink "$lock_link" 2>/dev/null || true)"
+ if [ -n "$held_by" ] && kill -0 "$held_by" 2>/dev/null; then
+ die "another install-rust.sh (pid ${held_by}) is publishing to ${PREFIX}; retry when it finishes"
+ fi
+ die "a previous install-rust.sh (pid ${held_by:-unknown}) left a stale publication lock (a crashed install; its cleanup trap cannot have run). Remove it and retry:
+ rm -f \"${lock_link}\""
+ done
+fi
+
+# THE WINDOWS DAEMON STOP, after the lock, before the publish (a Windows
+# process holds its own binary open, so the old-tree rename-aside below
+# fails while a daemon runs). THE TRUSTED STOP: the previous payload's OWN
+# BINARY (the marked share tree's prime-agent.exe), never the launcher - an
+# unowned regular file at ${launcher} is precisely the untrusted-execution
+# shape (the ownership check that later preserves it has not run yet), and
+# exec'ing it would hand a foreign command the installer's inherited
+# environment. The share tree's ownership marker gates the stop; a machine
+# with no marked payload yet (a fresh install) has no daemon the stop could
+# reach - that absence is the normal fresh-install path.
+if [ "$WINDOWS" = "yes" ] \
+ && [ -f "${share_dir}/.prime-agent-install" ] \
+ && [ -f "${share_dir}/${BINARY_NAME}" ]; then
+ say "stopping the running Rust daemon before the publish (a Windows"
+ say " process holds its binary open - the payload swap needs it down)"
+ # THE SCRIPTED FORM: the CLI's bare `shutdown` prompts for confirmation
+ # in an interactive terminal and REFUSES a non-interactive one ("Shutdown
+ # requires confirmation in an interactive terminal. Use prime-agent
+ # shutdown --force") - the installer's context is the scripted one, so
+ # --force is the documented non-interactive stop (the daemon's own forced
+ # shutdown drains its workers with its internal budgets).
+ if "${share_dir}/${BINARY_NAME}" shutdown --force >/dev/null 2>&1; then
+ windows_stop_summary="daemon: stopped cleanly for this update (the forced shutdown request, the scripted non-interactive form)"
+ say "the running daemon was shut down (the next invocation boots the new one)"
+ else
+ windows_stop_summary="daemon: WARNING no shutdown answer (if a daemon is running, stop it by hand: prime-agent shutdown --force)"
+ note "! No daemon answered the shutdown request. If one is running, stop it and re-run:"
+ todo "prime-agent shutdown --force"
fi
- die "a previous install-rust.sh (pid ${held_by:-unknown}) left a stale publication lock (a crashed install; its cleanup trap cannot have run). Remove it and retry:
- rm -f ${lock_link}"
-done
+fi
launcher_tmp=""
+cmd_tmp=""
+preserved_cmd_file=""
+windows_installed=""
displaced_ts_root=""
preserved_launcher=""
migrated_old_layout=""
@@ -1822,6 +1964,7 @@ on_exit() {
# to publish into share_dir while this one still restores state — the
# restore would delete that fresh payload (cross-installer data loss).
[ -n "$launcher_tmp" ] && rm -f "$launcher_tmp" 2>/dev/null || true
+ [ -n "${cmd_tmp:-}" ] && rm -f "$cmd_tmp" 2>/dev/null || true
# The user's unowned command file goes home if the Rust launcher never
# went live (the same restore discipline as the displaced TS tree): a
# failed launcher write must not leave the machine without ANY
@@ -1832,6 +1975,24 @@ on_exit() {
fi
preserved_launcher=""
fi
+ # The Windows .cmd twin's own preserve slot rides the same restore
+ # discipline (a failed install returns the user's unowned command).
+ if [ -n "${preserved_cmd_file:-}" ]; then
+ if mv "$preserved_cmd_file" "${bin_dir}/prime-agent.cmd" 2>/dev/null; then
+ echo "note: the existing prime-agent.cmd was restored to ${bin_dir}/prime-agent.cmd — the install did not complete" >&2
+ fi
+ preserved_cmd_file=""
+ fi
+ # THE FAILED-INSTALL DAEMON NOTE (the Windows stop-before-publish ruling):
+ # a failed install has restored every FILE it displaced, but a daemon
+ # stopped for the swap stays stopped — the sessions' state is on disk and
+ # the next prime-agent invocation boots the old payload's daemon again;
+ # the note names that recovery so the summary never leaves the user
+ # guessing (the bots' finding).
+ if [ "$WINDOWS" = "yes" ] && [ -n "$windows_stop_summary" ] && [ "${windows_installed:-}" != "yes" ]; then
+ echo "note: the daemon stopped for this failed install stays down until the next" >&2
+ echo " prime-agent invocation boots it from the restored payload" >&2
+ fi
# A migrated old-layout tree goes home the same way: the pre-takeover
# launcher (bin/prime-agent-rust) still points at the old name until this
# install's launcher section retires it, so an interrupted migration must
@@ -1844,6 +2005,11 @@ on_exit() {
fi
restore_ts_root
rm -f "$lock_link"
+ # The Windows lock arm (the mkdir lock directory): the link removal is a
+ # no-op there, the directory removal is the release.
+ if [ "$WINDOWS" = "yes" ]; then
+ rm -rf "${PREFIX}/share/.prime-agent-install.lock.d"
+ fi
}
trap on_exit EXIT
@@ -1975,6 +2141,7 @@ if ! mv "$stage" "$share_dir"; then
# (a failed migration restore is the EXIT trap's job: it holds the lock
# until the tree is back, so no second installer can slip in between)
fi
+windows_installed="yes"
# A leftover old-layout tree when a new-layout tree also existed: it is
# superseded by the fresh publish. The ownership rule is EXACTLY the
# migration's (the pre-takeover payload always shipped the binary beside
@@ -2020,7 +2187,21 @@ if [ -e "$launcher" ] || [ -L "$launcher" ]; then
fi
fi
launcher_tmp="$(mktemp "${bin_dir}/.prime-agent.XXXXXX")"
-cat > "$launcher_tmp" <<'EOF'
+if [ "$WINDOWS" = "yes" ]; then
+ # The Git Bash launcher: execs the payload's prime-agent.exe. NO daemon
+ # socket pin — this product's Windows daemon endpoint is the fixed named
+ # pipe (pa-daemon platform/paths), which is rust-only by construction:
+ # the TypeScript product never shipped a Windows build, so the unix
+ # cohabitation pin (a rust-only socket path that never collides with a
+ # TS daemon) has no TS daemon to avoid here.
+ cat > "$launcher_tmp" <<'EOF'
+#!/bin/sh
+# prime-agent — launcher written by install-rust.sh.
+export PRIME_AGENT_CODING_AGENT_DIR="${PRIME_AGENT_CODING_AGENT_DIR:-$HOME/.prime/agent}"
+exec "$(dirname "$0")/../share/prime-agent/prime-agent.exe" "$@"
+EOF
+else
+ cat > "$launcher_tmp" <<'EOF'
#!/bin/sh
# prime-agent — launcher written by install-rust.sh.
# The session store is shared with the TypeScript product BY DESIGN: both
@@ -2038,9 +2219,39 @@ export PRIME_AGENT_CODING_AGENT_DIR="${PRIME_AGENT_CODING_AGENT_DIR:-$HOME/.prim
export PRIME_AGENT_DAEMON_SOCKET="${PRIME_AGENT_DAEMON_SOCKET:-${TMPDIR:-/tmp}/prime-agent-rust-$(id -u)/daemon.sock}"
exec "$(dirname "$0")/../share/prime-agent/prime-agent" "$@"
EOF
+fi
chmod 0755 "$launcher_tmp"
mv -f "$launcher_tmp" "$launcher"
launcher_tmp=""
+# The cmd/PowerShell launcher twin (Windows only): the same
+# ../share/prime-agent payload, resolved from the .cmd's own location, so
+# `prime-agent` answers from cmd.exe and PowerShell too (the sh launcher
+# above serves Git Bash). The same unowned-file discipline as the sh
+# launcher: a foreign .cmd is preserved aside, never destroyed.
+if [ "$WINDOWS" = "yes" ]; then
+ cmd_launcher="${bin_dir}/prime-agent.cmd"
+ if [ -f "$cmd_launcher" ] \
+ && ! grep -q 'launcher written by install-rust.sh' "$cmd_launcher" 2>/dev/null; then
+ preserved_cmd_path="$(fresh_slot "${bin_dir}/prime-agent.cmd.pre-takeover")"
+ mv "$cmd_launcher" "$preserved_cmd_path" \
+ || die "could not preserve the existing file at ${cmd_launcher}; resolve it and re-run"
+ preserved_cmd_file="$preserved_cmd_path"
+ note "note: an unrelated ${cmd_launcher} existed; it was preserved at ${preserved_cmd_path}"
+ fi
+ cmd_tmp="$(mktemp "${bin_dir}/.prime-agent-cmd.XXXXXX")"
+ cat > "$cmd_tmp" <<'EOF'
+@echo off
+rem prime-agent - launcher written by install-rust.sh.
+if not defined PRIME_AGENT_CODING_AGENT_DIR set "PRIME_AGENT_CODING_AGENT_DIR=%USERPROFILE%\.prime\agent"
+"%~dp0..\share\prime-agent\prime-agent.exe" %*
+EOF
+ mv -f "$cmd_tmp" "$cmd_launcher"
+ # The takeover stands for the .cmd twin too: the preserved aside slot is
+ # NOT restored on the success path (the EXIT trap restores only what a
+ # failed install displaced - the bots' finding: the stale slot would
+ # clobber the fresh .cmd at exit).
+ preserved_cmd_file=""
+fi
# The Rust launcher is live: the takeover stands — the displaced TS tree
# stays in its legacy slot (with the printed rollback commands) and the
# preserved command file stays in its aside slot.
@@ -2077,18 +2288,24 @@ step_ok "Installed"
# invocation boots the new daemon).
last_stop_recorded=""
last_stop_was_rust=""
-stop_daemon_candidate "$ts_socket" ts
-ts_stop_stopped_ts="$last_stop_recorded"
-ts_stop_was_rust_ts="$last_stop_was_rust"
-if [ "$env_socket_probe" = "yes" ]; then
- stop_daemon_candidate "$env_socket" ts
- ts_stop_stopped_env="$last_stop_recorded"
- ts_stop_was_rust_env="$last_stop_was_rust"
-fi
-if [ "$rust_socket_probe" = "yes" ]; then
- stop_daemon_candidate "$rust_socket" ours
- ts_stop_stopped_rust="$last_stop_recorded"
- ts_stop_was_rust_rust="$last_stop_was_rust"
+# WINDOWS: no TS daemon can exist (the TS product never shipped a Windows
+# build) and this product's daemon runs a named pipe - the unix-socket
+# ladder below never applies. The Windows daemon stop already ran, before
+# the publish (the file-lock ruling).
+if [ "$WINDOWS" != "yes" ]; then
+ stop_daemon_candidate "$ts_socket" ts
+ ts_stop_stopped_ts="$last_stop_recorded"
+ ts_stop_was_rust_ts="$last_stop_was_rust"
+ if [ "$env_socket_probe" = "yes" ]; then
+ stop_daemon_candidate "$env_socket" ts
+ ts_stop_stopped_env="$last_stop_recorded"
+ ts_stop_was_rust_env="$last_stop_was_rust"
+ fi
+ if [ "$rust_socket_probe" = "yes" ]; then
+ stop_daemon_candidate "$rust_socket" ours
+ ts_stop_stopped_rust="$last_stop_recorded"
+ ts_stop_was_rust_rust="$last_stop_was_rust"
+ fi
fi
# THE VERIFY (the field contract: the TS daemon is DOWN before the install
@@ -2112,20 +2329,24 @@ verify_stopped_socket() {
"
fi
}
-if [ "${ts_stop_stopped_ts:-}" = "yes" ]; then
- verify_stopped_socket "$ts_socket" "$ts_stop_was_rust_ts"
-fi
-if [ "${ts_stop_stopped_env:-}" = "yes" ]; then
- verify_stopped_socket "$env_socket" "$ts_stop_was_rust_env"
-fi
-if [ "${ts_stop_stopped_rust:-}" = "yes" ]; then
- verify_stopped_socket "$rust_socket" "$ts_stop_was_rust_rust"
+if [ "$WINDOWS" != "yes" ]; then
+ if [ "${ts_stop_stopped_ts:-}" = "yes" ]; then
+ verify_stopped_socket "$ts_socket" "$ts_stop_was_rust_ts"
+ fi
+ if [ "${ts_stop_stopped_env:-}" = "yes" ]; then
+ verify_stopped_socket "$env_socket" "$ts_stop_was_rust_env"
+ fi
+ if [ "${ts_stop_stopped_rust:-}" = "yes" ]; then
+ verify_stopped_socket "$rust_socket" "$ts_stop_was_rust_rust"
+ fi
fi
# The TS npm package: uninstalled (operator directive — the Rust port owns the
# keyword), with the restore command printed. Exact package `prime-agent`
-# only; best-effort — an npm failure warns and moves on.
-if command -v npm >/dev/null 2>&1; then
+# only; best-effort — an npm failure warns and moves on. Windows never had
+# a TS npm install (the TS product shipped darwin/linux only), so the whole
+# step is darwin/linux.
+if [ "$WINDOWS" != "yes" ] && command -v npm >/dev/null 2>&1; then
npm_root="$(npm root -g 2>/dev/null || true)"
if [ -n "$npm_root" ] && [ -f "${npm_root}/prime-agent/package.json" ]; then
ts_version="$("$UVPY" -c 'import json, sys
@@ -2248,7 +2469,14 @@ elif [ -d "$old" ]; then
say " once you no longer need the rollback)"
fi
say "source: the ${CHANNEL} channel at ${BASE_URL} (prime-agent ${VERSION})"
-if [ -n "$ts_stop_summary" ]; then
+if [ "$WINDOWS" = "yes" ]; then
+ # The Windows stop ran before the publish (a Windows process holds its
+ # binary open); its summary rides here. A fresh install prints nothing:
+ # there was no daemon to stop.
+ if [ -n "$windows_stop_summary" ]; then
+ say "$windows_stop_summary"
+ fi
+elif [ -n "$ts_stop_summary" ]; then
printf '%s' "$ts_stop_summary" | while IFS= read -r summary_line; do say "$summary_line"; done
elif [ -z "$ts_stop_found_any" ] && [ -z "$ts_stop_refused" ]; then
# No silent skips: a machine with no daemon anywhere says so, naming
@@ -2321,6 +2549,15 @@ case ":$PATH:" in
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')"
+ fi
;;
esac
diff --git a/install.ps1 b/install.ps1
new file mode 100644
index 0000000000..1843f0ffb9
--- /dev/null
+++ b/install.ps1
@@ -0,0 +1,521 @@
+# install.ps1 — the Windows-native installer for Prime Agent (Rust build).
+#
+# THE ONE-LINER (the served copy carries the official domain + the stable
+# channel rendered in by the release pipeline's publish step):
+#
+# irm https://app.primeintellect.ai/prime-agent/install.ps1 | iex
+#
+# The Git Bash route is the same channel through install-rust.sh (the sh
+# one-liner `curl -fsSL .../install.sh | sh` under Git Bash/MSYS2/Cygwin);
+# this script is the PowerShell-native form. Both routes publish the SAME
+# layout — $PREFIX\share\prime-agent\ (the payload) and $PREFIX\bin\
+# (the launcher pair) — so either route can update the other's install.
+#
+# THE CHANNEL (install-rust.sh parity): the channel pointer (<base>/stable
+# or <base>/beta) gives the version, the channel manifest (<base>/latest.json
+# or <base>/beta.json) gives this platform's artifact row, and the versioned
+# release prefix serves the tarball plus its SHA256SUMS; the checksum is
+# verified before anything is published. NO GITHUB SURFACE anywhere in the
+# user path.
+#
+# NO TYPESCRIPT TAKEOVER STEPS: the TypeScript product never shipped a
+# Windows build, so there is no TS daemon, native install, or npm package
+# to retire here — this installer publishes the Rust payload and stops
+# this product's own daemon for the swap (a Windows process holds its
+# binary open; the payload swap needs the daemon down first).
+#
+# Configuration (environment, install-rust.sh's own knobs):
+# PRIME_AGENT_DOWNLOAD_BASE_URL the R2-backed download base
+# PRIME_AGENT_RELEASE_CHANNEL stable | beta
+# PRIME_AGENT_VERSION pin an exact version
+# PRIME_AGENT_RUST_PREFIX install prefix (default: $HOME\.local)
+#
+# Prerequisites: Windows 10+ (tar.exe and Get-FileHash ship with the OS;
+# the kernel's Python runtime bootstraps through uv on first session — the
+# pre-warm below installs the venv when uv is available).
+
+# The whole body runs in a child scope: under `irm | iex` the script shares
+# the caller's session, so the Stop preference and the installer's own
+# variables must not stay behind in it, and a refusal must return to the
+# prompt (Fail throws) instead of closing the user's PowerShell. The body
+# stays unindented so the publish render's line-anchored sed still matches.
+# Any failure reaches the catch at the bottom: run as a file it exits 1 (in
+# PowerShell 7 and Windows PowerShell 5.1 alike, never relying on how an
+# uncaught error or a trap's break maps to the exit code); under `irm | iex`
+# ($PSCommandPath is empty) it rethrows to the caller instead, so the
+# caller's session stays open.
+try {
+& {
+$ErrorActionPreference = 'Stop'
+
+# The publish-rendered defaults: the release pipeline copies this file to
+# <base>/install.ps1 with $DownloadBaseUrlDefault set to the R2 public base
+# and $ReleaseChannelDefault set to the channel; the repo-file default is
+# the same bucket-root base install-rust.sh carries, so the raw repo copy
+# installs out of the box too.
+$DownloadBaseUrlDefault = 'https://pub-728493de92a943e2a9b2d17b4719f318.r2.dev'
+$ReleaseChannelDefault = 'stable'
+
+# The installer-owned bookkeeping, initialized BEFORE any Fail can run
+# (under `irm | iex` the script scope is the caller's session: ambient
+# variables must never be read as this installer's state, so the names are
+# unique to this script and all start cleared - the bots' finding).
+$script:primeAgentInstallScratch = $null
+$script:primeAgentInstallStage = $null
+$script:primeAgentInstallLock = $null
+
+# Fail only throws: the catch at the bottom sweeps the installer's own
+# state on every failure path (a Fail and any other terminating error alike).
+function Fail($message) {
+ throw "install.ps1: $message"
+}
+
+# --- TLS floor (PowerShell 5.1 defaults can sit below TLS 1.2) ---------------
+try {
+ [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
+} catch {
+ Fail "could not enable TLS 1.2: $($_.Exception.Message)"
+}
+
+# --- the knobs ----------------------------------------------------------------
+$baseUrl = if ($env:PRIME_AGENT_DOWNLOAD_BASE_URL) { $env:PRIME_AGENT_DOWNLOAD_BASE_URL } else { $DownloadBaseUrlDefault }
+$channel = if ($env:PRIME_AGENT_RELEASE_CHANNEL) { $env:PRIME_AGENT_RELEASE_CHANNEL } else { $ReleaseChannelDefault }
+$versionPin = $env:PRIME_AGENT_VERSION
+$prefix = if ($env:PRIME_AGENT_RUST_PREFIX) { $env:PRIME_AGENT_RUST_PREFIX } else { Join-Path $HOME '.local' }
+
+# THE HTTPS RULE: the channel is served over the R2-backed domain, and a
+# plaintext download base would let a network attacker swap the payload
+# the checksum then "verifies" into place. The one escape hatch is the
+# explicitly-named knob for local-channel/e2e use (install-rust.sh carries
+# the same rule + knob); it prints a loud warning when it is active.
+$allowHttp = $env:PRIME_AGENT_ALLOW_HTTP -eq '1'
+if ($baseUrl -notmatch '^https://') {
+ if ($allowHttp) {
+ Write-Warning "PRIME_AGENT_ALLOW_HTTP=1: the download base $baseUrl is NOT https - the download is plaintext; use this only for a local channel you control"
+ } else {
+ Fail "the download base URL must be an https URL: $baseUrl"
+ }
+}
+$baseUrl = $baseUrl.TrimEnd('/')
+if (@('stable', 'beta') -notcontains $channel) { Fail "unknown release channel: $channel (stable or beta)" }
+# The prefix does not need to exist (a fresh Windows profile has no
+# $HOME\.local; the share/bin creation below makes it), but it must name
+# a directory path, not an existing FILE.
+if (Test-Path $prefix -PathType Leaf) { Fail "the install prefix names an existing file: $prefix" }
+
+# The channel files: the pointer names the version, the manifest the rows.
+$manifestName = if ($channel -eq 'beta') { 'beta.json' } else { 'latest.json' }
+$pointerName = $channel
+
+# The platform this script serves: the channel manifest's win32-x64 row
+# (the TS NATIVE_PLATFORMS spelling pa-core::update::install reads) — a
+# fixed target, checked here so an ARM64 Windows machine fails loudly
+# instead of downloading a payload it cannot start.
+$platform = 'win32-x64'
+# The OS architecture, not the process's: 32-bit PowerShell on x64 Windows
+# (WOW64) reports PROCESSOR_ARCHITECTURE=x86 and the OS arm rides
+# PROCESSOR_ARCHITEW6432 — the 64-bit OS must not be refused (Macroscope:
+# the WOW64 shape).
+$effectiveArchitecture = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }
+if ($effectiveArchitecture -ne 'AMD64') {
+ Fail "this machine reports architecture '$effectiveArchitecture'; the Windows channel ships the x86_64 (win32-x64) build only"
+}
+
+# The channel naming contract gives the artifact row's file name: the row
+# the channel manifest must carry for this platform (the reader's own rule,
+# pa-core::update::release::parse_channel_manifest).
+function ExpectedFileName($version, $platform) {
+ return "prime-agent-$version-$platform.tar.gz"
+}
+
+# --- resolve the version (the channel pointer, or the pinned version) --------
+# A PINNED version skips the channel manifest entirely (install-rust.sh
+# parity): the manifest describes the channel's CURRENT release, and a
+# historical pin must install from its own versioned prefix — the row is
+# the channel naming contract, and the release prefix's SHA256SUMS verifies
+# the artifact. An unpinned install reads the pointer + the manifest as a
+# PAIR, retrying once on a version mismatch (the publish writes the
+# manifest first and the pointer second: a read between the two writes sees
+# the old pointer with the new manifest — a transient window, not a broken
+# channel — install-rust.sh's consistency retry).
+$manifest = $null
+$manifestVersion = $null
+$row = $null
+if ($versionPin) {
+ $version = $versionPin.Trim().TrimStart('v')
+ Write-Host "installing prime-agent $version (pinned) from the $channel channel ($platform)"
+} else {
+ $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).
+ $version = (Invoke-RestMethod -Uri "$baseUrl/$pointerName").ToString().Trim().TrimStart('v')
+ if (-not $version) { Fail "could not resolve the latest $channel version from $baseUrl/$pointerName" }
+ $manifest = Invoke-RestMethod -Uri "$baseUrl/$manifestName"
+ $manifestVersion = ($manifest.version).ToString().TrimStart('v')
+ if ($manifestVersion -eq $version) { break }
+ $attempt += 1
+ if ($attempt -gt 2) {
+ Fail "the $channel manifest's version $manifestVersion does not match the channel pointer $version (re-read twice; the channel looks inconsistent)"
+ }
+ Write-Host "the $channel pointer and manifest disagree (a publish's consistency window); re-reading the pair..."
+ Start-Sleep -Seconds 1
+ }
+ Write-Host "installing prime-agent $version from the $channel channel ($platform)"
+}
+
+# --- the channel manifest row (unpinned) / the naming contract (pinned) ------
+$expectedFile = ExpectedFileName $version $platform
+if (-not $versionPin) {
+ foreach ($candidate in @($manifest.binaries_v2) + @($manifest.binaries)) {
+ if ($candidate -and $candidate.platform -eq $platform) {
+ if ($candidate.file -ne $expectedFile) {
+ Fail "the manifest's $platform row names '$($candidate.file)' instead of the channel naming '$expectedFile'"
+ }
+ $row = $candidate
+ break
+ }
+ }
+ if (-not $row) { Fail "no artifact row for platform $platform in the $channel manifest" }
+ if ($row.sha256 -notmatch '^[0-9a-f]{64}$') { Fail "the channel manifest's sha256 for $expectedFile is malformed" }
+} else {
+ Write-Host "pinned ${version}: installing from the versioned release prefix (the channel naming contract names the row)"
+}
+
+# --- the tarball + SHA256SUMS from the versioned release prefix ----------------
+$releasePrefix = "releases/v$version"
+$download = Join-Path ([IO.Path]::GetTempPath()) ("prime-agent-download-{0}" -f [Guid]::NewGuid().ToString('N'))
+New-Item -ItemType Directory -Path $download | Out-Null
+$script:primeAgentInstallScratch = $download
+# THE DOWNLOAD SWEEP: the scratch (the tarball + the sums) is removed when
+# this script exits - success below, a Fail or a terminating error in the
+# catch at the bottom (install-rust.sh's `rm -rf "$dl"` discipline; the
+# bots' finding: accumulated release tarballs in the temp folder).
+$tarball = Join-Path $download $expectedFile
+$sumsPath = Join-Path $download 'SHA256SUMS'
+try {
+ Invoke-WebRequest -Uri "$baseUrl/$releasePrefix/$expectedFile" -OutFile $tarball
+ Invoke-WebRequest -Uri "$baseUrl/$releasePrefix/SHA256SUMS" -OutFile $sumsPath
+} catch {
+ Fail "could not download $expectedFile from $baseUrl/$releasePrefix/: $($_.Exception.Message)"
+}
+
+# --- verify the checksum (the release prefix's sums, cross-checked with the
+# --- manifest's row: two independent reads of the same digest) ------------------
+$sumsLine = Get-Content -LiteralPath $sumsPath | Where-Object { $_ -match " $expectedFile$" } | Select-Object -First 1
+if (-not $sumsLine) { Fail "SHA256SUMS in $releasePrefix has no line for $expectedFile" }
+$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)"
+
+# --- extract to a staging dir inside the prefix (same volume: the final swap
+# --- is a rename, not a copy) -----------------------------------------------------
+$share = Join-Path $prefix 'share\prime-agent'
+$bin = Join-Path $prefix 'bin'
+New-Item -ItemType Directory -Path (Join-Path $prefix 'share') -Force | Out-Null
+New-Item -ItemType Directory -Path $bin -Force | Out-Null
+$stage = Join-Path (Join-Path $prefix 'share') ("prime-agent.stage-{0}" -f [Guid]::NewGuid().ToString('N'))
+New-Item -ItemType Directory -Path $stage | Out-Null
+# The stage rides every exit path once created (the failure sweep at the bottom:
+# a failed extraction/validation must not leave the extracted payload
+# behind - the bots' finding).
+$script:primeAgentInstallStage = $stage
+& tar -xzf $tarball -C $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" }
+
+# The ownership marker (install-rust.sh's exact write shape — the update
+# funnel's channel-stickiness read keys on it).
+$channelLine = "install-rust.sh channel $channel"
+$marker = "$channelLine`nversion $version"
+Set-Content -LiteralPath (Join-Path $stage '.prime-agent-install') -Value $marker -NoNewline
+
+# The launcher paths (the section below the publish writes both).
+$launcher = Join-Path $bin 'prime-agent.cmd'
+$shLauncher = Join-Path $bin 'prime-agent'
+
+# --- the publication lock (one writer): a lock DIRECTORY is the atomic
+# --- claim on Windows (mkdir wins exactly once); the holder's pid rides a
+# --- file inside, and a stale lock is never auto-stolen. THE LOCK COMES
+# --- FIRST: a failed lock claim must never have stopped a daemon (the
+# --- bots' finding - the stop-for-nothing downtime).
+$lockDir = Join-Path (Join-Path $prefix 'share') '.prime-agent-install.lock.d'
+try {
+ New-Item -ItemType Directory -Path $lockDir -ErrorAction Stop | Out-Null
+} catch {
+ $heldBy = ''
+ $pidPath = Join-Path $lockDir 'pid'
+ if (Test-Path $pidPath) { $heldBy = (Get-Content -LiteralPath $pidPath -ErrorAction SilentlyContinue) }
+ Fail "another installer (pid $heldBy) or a stale publication lock owns $lockDir; if no installer is running, remove it and re-run"
+}
+try {
+ Set-Content -LiteralPath (Join-Path $lockDir 'pid') -Value $PID
+} catch {
+ # A failed PID write releases the freshly claimed lock (the bots'
+ # finding: the leaked lock otherwise blocks every later install).
+ Remove-Item -Recurse -Force $lockDir -ErrorAction SilentlyContinue
+ Fail "could not write the publication lock PID: $($_.Exception.Message)"
+}
+# The lock rides every exit path from here: Fail releases it, and the
+# publish's finally releases + clears it.
+$script:primeAgentInstallLock = $lockDir
+
+$published = $false
+$rollback = $null
+$script:daemonStopped = $false
+
+# THE PREFLIGHT: every ownership refusal that can happen runs BEFORE the
+# daemon stop (a refused install must never have stopped a daemon - the
+# bots' finding: the stop-then-refuse order was the avoidable downtime).
+$rollback = Join-Path (Join-Path $prefix 'share') 'prime-agent.old'
+if (Test-Path $share -PathType Container) {
+ $markerPath = Join-Path $share '.prime-agent-install'
+ if (-not (Test-Path $markerPath -PathType Leaf)) {
+ Fail "refusing to take ownership of ${share}: it is not a marked prime-agent payload tree (.prime-agent-install); move it aside and re-run"
+ }
+ if (Test-Path $rollback) {
+ $rollbackMarker = Join-Path $rollback '.prime-agent-install'
+ if (-not (Test-Path $rollbackMarker -PathType Leaf)) {
+ Fail "refusing to delete the unmarked rollback directory: $rollback (move it aside and re-run)"
+ }
+ }
+}
+
+try {
+ # THE DAEMON STOP, inside the lock's try (a terminating error in the
+ # stop must still release the lock - the bots' finding: the stale lock
+ # otherwise left behind). THE TRUSTED STOP: the previous payload's own
+ # binary (the marked share tree's prime-agent.exe), never the launcher -
+ # a launcher this installer has not verified is the unowned-execution
+ # shape (an attacker-placed bin\prime-agent.cmd would otherwise run
+ # with the installer's inherited environment); the share's ownership
+ # marker gates the stop, and a fresh install (no marked payload yet)
+ # has no daemon the stop could reach.
+ $payloadStopExe = Join-Path $share 'prime-agent.exe'
+ $shareMarker = Join-Path $share '.prime-agent-install'
+ if ((Test-Path $shareMarker -PathType Leaf) -and (Test-Path $payloadStopExe -PathType Leaf)) {
+ Write-Host 'stopping the running Rust daemon before the publish (a Windows process holds its binary open)'
+ # THE SCRIPTED FORM: the CLI's bare `shutdown` prompts for
+ # confirmation in an interactive terminal and REFUSES a
+ # non-interactive one ("Shutdown requires confirmation in an
+ # interactive terminal. Use prime-agent shutdown --force") - the
+ # installer's context is the scripted one, so `--force` is the
+ # documented non-interactive stop (the daemon's own forced
+ # shutdown drains its workers with its internal budgets).
+ & $payloadStopExe shutdown --force *> $null
+ if ($LASTEXITCODE -eq 0) {
+ $script:daemonStopped = $true
+ } else {
+ Write-Warning "no daemon answered the shutdown request; if a daemon is running, stop it by hand (prime-agent shutdown --force) and re-run"
+ }
+ }
+
+ # The one-generation rollback (the ownership checks already ran in the
+ # preflight): the previous payload moves aside, the fresh stage swaps
+ # in, and the next install sweeps the rollback.
+ if (Test-Path $share -PathType Container) {
+ if (Test-Path $rollback) {
+ Remove-Item -Recurse -Force $rollback
+ }
+ [IO.Directory]::Move($share, $rollback)
+ Write-Host "rollback: $rollback (the previous payload, one generation)"
+ }
+ [IO.Directory]::Move($stage, $share)
+ $script:primeAgentInstallStage = $null
+ # The payload is live: no later launcher failure rolls it back (the new
+ # tree is valid; the restored launchers point at ../share/prime-agent/
+ # prime-agent.exe - the new payload - and keep working).
+ $published = $true
+
+ # --- the launcher pair: the cmd shim (cmd.exe + PowerShell) and the sh
+ # --- launcher (Git Bash) - the same payload, both shells, the same
+ # --- content install-rust.sh writes. THE LOCK STAYS HELD through the
+ # --- launcher transaction (the bots' finding: a second installer must
+ # --- not slip between the payload publish and the launcher write, or
+ # --- its launcher would pair with this payload and a later failure of
+ # --- EITHER installer would restore the other's .pre-takeover over
+ # --- it). The unowned-file discipline is the sh installer's own: a
+ # --- launcher this script did not write is preserved aside, never
+ # --- overwritten (an unrelated command is never destroyed) AND a
+ # --- failure after a preserve puts the user's file back. An
+ # --- INSTALLER-OWNED launcher is snapshotted first (an I/O failure at
+ # --- Set-Content can truncate a live, working launcher).
+ # Script scope, the scope the helpers below append to: the reset must
+ # hit the same arrays, or an earlier `irm | iex` run's entries in the
+ # same session would be replayed by this run's recovery.
+ $script:preservedLaunchers = @()
+ $script:ownedLauncherBackups = @()
+ function Backup-ExistingLauncher($path) {
+ if (-not (Test-Path $path -PathType Leaf)) { return }
+ $backup = "$path.install-backup"
+ while (Test-Path $backup) { $backup = "$backup.$([Guid]::NewGuid().ToString('N').Substring(0,4))" }
+ Copy-Item -LiteralPath $path -Destination $backup -Force
+ $script:ownedLauncherBackups += ,@($backup, $path)
+ }
+ function Preserve-UnownedLauncher($path) {
+ if (-not (Test-Path $path -PathType Leaf)) { return }
+ $firstLine = (Get-Content -LiteralPath $path -TotalCount 2) -join ' '
+ if ($firstLine -match 'launcher written by install-rust\.sh') {
+ Backup-ExistingLauncher $path
+ return
+ }
+ $preserved = "$path.pre-takeover"
+ while (Test-Path $preserved) { $preserved = "$preserved.$([Guid]::NewGuid().ToString('N').Substring(0,4))" }
+ [IO.File]::Move($path, $preserved)
+ $script:preservedLaunchers += ,@($preserved, $path)
+ Write-Host "note: an unrelated $(Split-Path -Leaf $path) existed at $path; it was preserved at $preserved"
+ }
+ Preserve-UnownedLauncher $launcher
+ Preserve-UnownedLauncher $shLauncher
+
+ try {
+ $cmdShim = @'
+@echo off
+rem prime-agent - launcher written by install-rust.sh.
+if not defined PRIME_AGENT_CODING_AGENT_DIR set "PRIME_AGENT_CODING_AGENT_DIR=%USERPROFILE%\.prime\agent"
+"%~dp0..\share\prime-agent\prime-agent.exe" %*
+'@
+ Set-Content -LiteralPath $launcher -Value $cmdShim
+
+ $shBody = @'
+#!/bin/sh
+# prime-agent — launcher written by install-rust.sh.
+export PRIME_AGENT_CODING_AGENT_DIR="${PRIME_AGENT_CODING_AGENT_DIR:-$HOME/.prime/agent}"
+exec "$(dirname "$0")/../share/prime-agent/prime-agent.exe" "$@"
+'@
+ # LF endings + no BOM: the sh launcher must stay a POSIX file.
+ [IO.File]::WriteAllText($shLauncher, $shBody.Replace("`r`n", "`n"))
+
+ # The launchers are live: the owned-launcher snapshots (the failure
+ # restore points) sweep away - nothing lingers after a success.
+ foreach ($pair in $script:ownedLauncherBackups) {
+ Remove-Item -Force $pair[0] -ErrorAction SilentlyContinue
+ }
+ } catch {
+ # A failed launcher write never leaves the machine without its
+ # command: every preserved file goes home, and every OWNED
+ # launcher's pre-write snapshot is restored over its truncated
+ # form, before the failure surfaces. The destination's PARTIAL
+ # file (Set-Content/WriteAllText can create or truncate before
+ # throwing) is removed first - the broken new file otherwise
+ # blocks the restore.
+ foreach ($pair in $script:preservedLaunchers) {
+ if (Test-Path $pair[1]) { Remove-Item -Force $pair[1] -ErrorAction SilentlyContinue }
+ [IO.File]::Move($pair[0], $pair[1])
+ }
+ foreach ($pair in $script:ownedLauncherBackups) {
+ Copy-Item -LiteralPath $pair[0] -Destination $pair[1] -Force
+ Remove-Item -Force $pair[0] -ErrorAction SilentlyContinue
+ }
+ throw
+ }
+} finally {
+ # A failed publish never leaves the machine without its previous payload:
+ # the old tree returns to the live name before the lock releases (the sh
+ # installer's restore-on-exit discipline). $rollback is pre-initialized:
+ # a terminating error before its assignment must not turn the finally's
+ # own check into the leaked-lock failure.
+ if (-not $published) {
+ if ($rollback -and (Test-Path $rollback -PathType Container) -and -not (Test-Path $share)) {
+ # The restore's own failure must not swallow the lock release
+ # (an error thrown here would skip the Remove-Item below - the
+ # stale-lock manual recovery class): the restore reports the
+ # manual recovery instead of throwing.
+ try {
+ [IO.Directory]::Move($rollback, $share)
+ Write-Warning "the publish failed; the previous payload was restored to $share"
+ } catch {
+ Write-Warning "the publish failed AND the previous payload could not be restored: it waits at $rollback - recover with: Move-Item '$rollback' '$share'"
+ }
+ }
+ # A failed install sweeps its stage tree (the bots' finding: the
+ # accumulated prime-agent.stage-* directories).
+ if ($stage -and (Test-Path $stage -PathType Container)) {
+ Remove-Item -Recurse -Force $stage -ErrorAction SilentlyContinue
+ }
+ # A daemon stopped for a FAILED install stays down (its sessions'
+ # state is on disk; nothing here restarts it): name the recovery so
+ # the user never guesses - the next invocation boots the old
+ # payload's daemon again.
+ if ($script:daemonStopped) {
+ Write-Warning "the daemon stopped for this failed install stays down until the next prime-agent invocation boots it from the restored payload"
+ }
+ }
+ Remove-Item -Recurse -Force $lockDir -ErrorAction SilentlyContinue
+ $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) {
+ 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)'
+ }
+} 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')"
+}
+
+# --- 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)"
+ } 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-Host "launcher: $launcher"
+Write-Host "payload: $share"
+Write-Host "source: the $channel channel at $baseUrl (prime-agent $version)"
+Write-Host 'next steps: the README''s Install section ships inside the payload:'
+Write-Host " $share\README.md"
+
+$script:primeAgentInstallScratch = $null
+$script:preservedLaunchers = @()
+$script:ownedLauncherBackups = @()
+if ($download) { Remove-Item -Recurse -Force $download -ErrorAction SilentlyContinue }
+}
+} catch {
+ # THE FAILURE SWEEP, the one cleanup path for every failure: exactly
+ # what THIS script created - the download scratch, the stage tree, and
+ # the publication lock it claimed (a refused install never leaks its
+ # lock; the publish's finally has already released it when the failure
+ # came from there). The names were cleared at the top, so an ambient
+ # caller's variables never enter the cleanup.
+ if ($script:primeAgentInstallScratch) {
+ Remove-Item -Recurse -Force $script:primeAgentInstallScratch -ErrorAction SilentlyContinue
+ }
+ if ($script:primeAgentInstallStage) {
+ Remove-Item -Recurse -Force $script:primeAgentInstallStage -ErrorAction SilentlyContinue
+ }
+ if ($script:primeAgentInstallLock) {
+ Remove-Item -Recurse -Force $script:primeAgentInstallLock -ErrorAction SilentlyContinue
+ }
+ $script:primeAgentInstallScratch = $null
+ $script:primeAgentInstallStage = $null
+ $script:primeAgentInstallLock = $null
+ if ($PSCommandPath) {
+ $Host.UI.WriteErrorLine($_.Exception.Message)
+ exit 1
+ }
+ throw
+}
diff --git a/scripts/package_release.py b/scripts/package_release.py
index 3ff83c2e17..f60a1ad4d3 100644
--- a/scripts/package_release.py
+++ b/scripts/package_release.py
@@ -12,7 +12,7 @@ packages/coding-agent/scripts/copy-binary-assets.mjs) to this repo's layout:
The staged layout is the exe-adjacent packaging the binary resolves at
runtime (PI_PACKAGE_DIR override, else the directory of the executable):
- prime-agent the binary (mode 755)
+ prime-agent the binary (mode 755; prime-agent.exe on win32-x64)
package.json version manifest ({"version": <version>, piConfig})
README.md
LICENSE
@@ -110,7 +110,8 @@ def parse_args(argv):
parser.add_argument("--binary", type=Path, help="stage this binary instead of building")
parser.add_argument("--decoder", type=Path, help="separate Linux decoder for --binary")
parser.add_argument("--skip-build", action="store_true",
- help="reuse target/release/prime-agent without building")
+ help="reuse target/release/prime-agent (prime-agent.exe on"
+ " win32-x64) without building")
parser.add_argument("--out-dir", type=Path, help="output directory (default: target/release-package)")
parser.add_argument("--platform", help="platform tag (default: derived from this machine)")
parser.add_argument("--root", type=Path, default=ROOT,
@@ -141,9 +142,24 @@ def release_platform():
system = platform.system().lower()
if system not in ("linux", "darwin", "windows"):
raise SystemExit(f"error: unsupported release platform: {system}")
+ # Windows carries the TS `NATIVE_PLATFORMS` alias (`win32-x64`, the
+ # channel manifest's platform row), not the bare `windows-x64` spelling,
+ # so the local dry-run names its artifact exactly like the release
+ # pipeline's channel tarball.
+ if system == "windows":
+ return f"win32-{arch}"
return f"{system}-{arch}"
+def binary_name_for_platform(tag):
+ """The staged binary name for one platform tag: `prime-agent.exe` on
+ win32-x64 (the name Cargo's MSVC linker emits and the installer's
+ `.exe`-aware layout expects), `prime-agent` everywhere else — the same
+ naming rule the release pipeline applies
+ (`scripts/release/assemble_artifacts.py` `binary_name_for_target`)."""
+ return "prime-agent.exe" if tag == "win32-x64" else "prime-agent"
+
+
def include_path(relative, extra_excluded_names=frozenset(), extra_excluded_suffixes=()):
parts = Path(relative).parts
return not any(
@@ -201,9 +217,9 @@ def resolve_catalog_assets(args):
return args.catalog_assets
-def stage(root, binary, version, stage_dir, catalog_assets):
+def stage(root, binary, version, stage_dir, catalog_assets, binary_name):
stage_dir.mkdir(parents=True)
- staged_binary = stage_dir / "prime-agent"
+ staged_binary = stage_dir / binary_name
shutil.copy2(binary, staged_binary)
staged_binary.chmod(0o755)
# The bundled catalog assets ride beside the executable (the runtime's
@@ -230,7 +246,7 @@ def stage(root, binary, version, stage_dir, catalog_assets):
"name": "prime-agent",
"version": version,
"description": "Prime Agent: the RLM coding agent (Rust build)",
- "bin": {"prime-agent": "prime-agent"},
+ "bin": {"prime-agent": binary_name},
"piConfig": {"name": "prime-agent", "configDir": ".prime/agent"},
},
indent=2,
@@ -239,16 +255,16 @@ def stage(root, binary, version, stage_dir, catalog_assets):
)
-def validate(stage_dir, version):
+def validate(stage_dir, version, binary_name):
for name in REQUIRED_DIRS:
if not (stage_dir / name).is_dir():
raise SystemExit(f"error: missing binary asset directory: {name}")
for name in REQUIRED_FILES:
- path = stage_dir / name
+ path = stage_dir / (binary_name if name == "prime-agent" else name)
if not path.is_file():
- raise SystemExit(f"error: missing binary asset: {name}")
- if not os.access(stage_dir / "prime-agent", os.X_OK):
- raise SystemExit("error: staged prime-agent is not executable")
+ raise SystemExit(f"error: missing binary asset: {path.name}")
+ if not os.access(stage_dir / binary_name, os.X_OK):
+ raise SystemExit(f"error: staged {binary_name} is not executable")
for path in sorted(stage_dir.rglob("*")):
if path.is_symlink():
raise SystemExit(f"error: unexpected symlink in binary assets: {path}")
@@ -256,7 +272,7 @@ def validate(stage_dir, version):
raise SystemExit(f"error: unexpected binary asset: {path}")
-def pin_version(binary, stage_dir, version):
+def pin_version(binary, stage_dir, version, binary_name):
"""Two-sided version pin: the compiled-in version (probed with the
manifest resolution pointed at an empty dir) and the staged manifest must
both equal the requested release version."""
@@ -278,13 +294,13 @@ def pin_version(binary, stage_dir, version):
# The staged copy resolves the packaged manifest (exe-adjacent
# package.json): it must report the same pinned version.
probe = subprocess.run(
- [str(stage_dir / "prime-agent"), "--version"],
+ [str(stage_dir / binary_name), "--version"],
capture_output=True,
text=True,
env={**os.environ, "PI_PACKAGE_DIR": str(stage_dir)},
)
if probe.returncode != 0:
- raise SystemExit(f"error: staged prime-agent --version failed: {probe.stderr.strip()}")
+ raise SystemExit(f"error: staged {binary_name} --version failed: {probe.stderr.strip()}")
staged = probe.stdout.strip()
if staged != version:
raise SystemExit(
@@ -326,6 +342,7 @@ def main(argv=None):
root = args.root.resolve()
version = args.version or workspace_version(root)
tag = args.platform or release_platform()
+ binary_name = binary_name_for_platform(tag)
out_dir = (args.out_dir or root / "target" / "release-package").resolve()
out_dir.mkdir(parents=True, exist_ok=True)
stage_dir = out_dir / f"prime-agent-{version}-{tag}"
@@ -335,13 +352,13 @@ def main(argv=None):
if not binary.is_file():
raise SystemExit(f"error: binary not found: {binary}")
elif args.skip_build:
- binary = root / "target" / "release" / "prime-agent"
+ binary = root / "target" / "release" / binary_name
if not binary.is_file():
raise SystemExit(f"error: no prebuilt binary at {binary}; drop --skip-build")
else:
print("building the release binary (cargo build --release -p pa-cli)…")
subprocess.run(["cargo", "build", "--release", "-p", "pa-cli"], cwd=ROOT, check=True)
- binary = root / "target" / "release" / "prime-agent"
+ binary = root / "target" / "release" / binary_name
if tag.startswith("linux-"):
if tag != release_platform():
@@ -372,10 +389,10 @@ def main(argv=None):
if stage_dir.exists():
shutil.rmtree(stage_dir)
catalog_assets = resolve_catalog_assets(args)
- stage(root, binary, version, stage_dir, catalog_assets)
- validate(stage_dir, version)
+ stage(root, binary, version, stage_dir, catalog_assets, binary_name)
+ validate(stage_dir, version, binary_name)
fail_if_decoder_in_tree(stage_dir)
- pin_version(binary, stage_dir, version)
+ pin_version(binary, stage_dir, version, binary_name)
archive = out_dir / f"{stage_dir.name}.tar.gz"
if archive.exists():
@@ -384,7 +401,7 @@ def main(argv=None):
fail_if_decoder_in_archive(archive)
archive_sha = sha256_file(archive)
- executable_sha = sha256_file(stage_dir / "prime-agent")
+ executable_sha = sha256_file(stage_dir / binary_name)
manifest = {
"version": f"v{version}",
"binaries": [
diff --git a/scripts/release/assemble_artifacts.py b/scripts/release/assemble_artifacts.py
index 850e82711b..58e91a6d4a 100755
--- a/scripts/release/assemble_artifacts.py
+++ b/scripts/release/assemble_artifacts.py
@@ -21,8 +21,10 @@ hard-fails without VALIDATED assets (version gates + >= 42 transport tuples +
no-cold-start layer 2). CI generates them from the live catalog repo; offline
builds use `bundle_catalog.py generate --fixture`.
-`--binary` defaults to `<repo>/target/<target>/release/prime-agent` (cross builds)
-and falls back to `<repo>/target/release/prime-agent` (host builds).
+`--binary` defaults to `<repo>/target/<target>/release/<binary-name>` (cross
+builds) and falls back to `<repo>/target/release/<binary-name>` (host builds),
+where the binary name is `prime-agent.exe` for the Windows MSVC target and
+`prime-agent` everywhere else (`binary_name_for_target`).
`--runtime-dir` defaults to `<repo>/prime-agent-runtime` (the vendored sidecar
from the kernel-packaging lane).
`--sha` (the continuous-build stamp): a full 40-char git commit SHA. When
@@ -60,9 +62,13 @@ from pathlib import Path
from bundle_catalog import BUNDLED_CATALOG_FILES, validate_bundled_catalog_dir
# Tarball-root payload order mirrors the TS `binaryAssets` list so the
-# installer lane can extract both distributions identically.
+# installer lane can extract both distributions identically. The binary
+# entry name is platform-dependent (`binary_name_for_target`: the MSVC
+# build ships `prime-agent.exe`), so the list names the binary slot via
+# the placeholder resolved in `main`/`stage_tree`.
+BINARY_PLACEHOLDER = "prime-agent"
STAGED_ENTRIES = [
- "prime-agent",
+ BINARY_PLACEHOLDER,
"prime-agent-runtime",
"skills",
"LICENSE",
@@ -74,6 +80,16 @@ STAGED_ENTRIES = [
"mcp-services.bundled.json",
]
+
+def binary_name_for_target(target: str) -> str:
+ """The staged binary name for `target`: `prime-agent.exe` on the MSVC
+ Windows target (the name Cargo's linker emits and the installer's
+ `.exe`-aware layout expects), `prime-agent` everywhere else.
+ """
+ if "-windows-" in target:
+ return "prime-agent.exe"
+ return "prime-agent"
+
# Shipped-content policy: what the installed tree carries beyond the binary.
#
# The runtime sidecar ships only what the kernel consumes. The venv
@@ -196,17 +212,18 @@ def parse_args() -> argparse.Namespace:
def resolve_binary(args: argparse.Namespace) -> Path:
+ name = binary_name_for_target(args.target)
candidates = []
if args.binary is not None:
candidates.append(args.binary)
else:
- candidates.append(args.repo_root / "target" / args.target / "release" / "prime-agent")
- candidates.append(args.repo_root / "target" / "release" / "prime-agent")
+ candidates.append(args.repo_root / "target" / args.target / "release" / name)
+ candidates.append(args.repo_root / "target" / "release" / name)
for candidate in candidates:
if candidate.is_file() and os.access(candidate, os.X_OK):
return candidate
listed = ", ".join(str(candidate) for candidate in candidates)
- fail(f"no executable prime-agent binary found (looked at: {listed}); build first")
+ fail(f"no executable {name} binary found (looked at: {listed}); build first")
def validate_version(version: str) -> None:
@@ -262,10 +279,11 @@ def stage_tree(staging: Path, args: argparse.Namespace, stamped_version: str | N
RUNTIME_EXCLUDED_*); every other entry is a
verbatim copy.
"""
+ binary_name = binary_name_for_target(args.target)
binary = resolve_binary(args)
runtime_dir = args.runtime_dir or (args.repo_root / "prime-agent-runtime")
sources = {
- "prime-agent": binary,
+ binary_name: binary,
"prime-agent-runtime": runtime_dir,
"skills": args.repo_root / "skills",
"LICENSE": args.repo_root / "LICENSE",
@@ -294,7 +312,10 @@ def stage_tree(staging: Path, args: argparse.Namespace, stamped_version: str | N
shutil.copytree(source, target_path)
else:
shutil.copy2(source, target_path)
- os.chmod(staging / "prime-agent", 0o755)
+ # `chmod` is a no-op beyond the read-only bit on Windows hosts (the
+ # exec bit the tar member filter re-pins below); on POSIX it makes the
+ # staged binary executable for the `--version` probes.
+ os.chmod(staging / binary_name, 0o755)
# The bundled catalog assets gate (spec §3.9): the release packer FAILS
# without validated assets — generate them first (network for CI, a local
# catalog checkout, or the offline --fixture snapshot) via
@@ -310,13 +331,14 @@ def stage_tree(staging: Path, args: argparse.Namespace, stamped_version: str | N
catalog_facts = validate_bundled_catalog_dir(catalog_assets)
for name in BUNDLED_CATALOG_FILES:
shutil.copyfile(catalog_assets / name, staging / name)
- payload = list(STAGED_ENTRIES)
+ payload = [binary_name if entry == BINARY_PLACEHOLDER else entry
+ for entry in STAGED_ENTRIES]
if stamped_version is not None:
manifest = {
"name": "prime-agent",
"version": stamped_version,
"description": "Prime Agent: the RLM coding agent (Rust build)",
- "bin": {"prime-agent": "prime-agent"},
+ "bin": {"prime-agent": binary_name},
"piConfig": {"name": "prime-agent", "configDir": ".prime/agent"},
"commit": args.sha,
}
@@ -326,7 +348,8 @@ def stage_tree(staging: Path, args: argparse.Namespace, stamped_version: str | N
# sidecar staged by a later change fails here, not in the field.
fail_if_decoder_in_tree(staging)
return {
- "executable_sha256": sha256_file(staging / "prime-agent"),
+ "binary_name": binary_name,
+ "executable_sha256": sha256_file(staging / binary_name),
"payload": payload,
"catalog_assets": catalog_facts,
}
@@ -350,7 +373,7 @@ def _deterministic_member(member: tarfile.TarInfo) -> tarfile.TarInfo:
member.mtime = 0
if member.isdir():
member.mode = 0o755
- elif member.name == "prime-agent":
+ elif member.name == "prime-agent" or member.name == "prime-agent.exe":
member.mode = 0o755
else:
member.mode = 0o644
diff --git a/scripts/release/test_windows_install.ps1 b/scripts/release/test_windows_install.ps1
new file mode 100644
index 0000000000..6064a06fbf
--- /dev/null
+++ b/scripts/release/test_windows_install.ps1
@@ -0,0 +1,115 @@
+# test_windows_install.ps1 — the Windows install e2e (the windows-runtime-triage
+# battery's install gates).
+#
+# WHAT IT PROVES: both Windows entry points install the REAL release artifact
+# from a REAL channel shape —
+# 1. assemble the win32-x64 tarball with the release pipeline's own
+# assemble_artifacts.py (the exact artifact the channel ships),
+# 2. serve a local channel (the pointer, latest.json, the versioned
+# release prefix) over localhost,
+# 3. install.ps1 (the PowerShell-native route) into a scratch prefix,
+# 4. install-rust.sh under Git Bash (the sh route) into another prefix,
+# 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).
+#
+# Usage (from the repo root, on windows-latest):
+# pwsh -File scripts/release/test_windows_install.ps1
+
+$ErrorActionPreference = 'Stop'
+
+$repo = (Get-Location).Path
+$scratch = Join-Path ([IO.Path]::GetTempPath()) ("prime-agent-install-e2e-{0}" -f [Guid]::NewGuid().ToString('N'))
+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
+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
+if ($LASTEXITCODE -ne 0) { throw 'the catalog fixture generation failed' }
+
+# 2. The channel artifact + its checksums (the assembler names the archive
+# by the platform alias the channel contract requires).
+$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" }
+$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
+if ($LASTEXITCODE -ne 0) { throw 'assemble_artifacts.py failed for the msvc target' }
+$artifact = "prime-agent-$version-win32-x64.tar.gz"
+if (-not (Test-Path (Join-Path $dist $artifact))) { throw "the assembled artifact is missing: $artifact" }
+
+# 3. The local channel: the stable pointer, the manifest with the win32-x64
+# row (the shape release.yml's emission publishes), the versioned prefix.
+$channel = Join-Path $scratch 'channel'
+$releaseDir = Join-Path $channel "releases\v$version"
+New-Item -ItemType Directory -Path $releaseDir -Force | Out-Null
+Copy-Item (Join-Path $dist $artifact) $releaseDir
+Copy-Item (Join-Path $dist 'SHA256SUMS') $releaseDir
+Set-Content -LiteralPath (Join-Path $channel 'stable') -Value $version -NoNewline
+$manifestRow = "{`"platform`": `"win32-x64`", `"file`": `"$artifact`", `"sha256`": `"$( (Get-FileHash -LiteralPath (Join-Path $releaseDir $artifact) -Algorithm SHA256).Hash.ToLower() )`"}"
+Set-Content -LiteralPath (Join-Path $channel 'latest.json') -Value "{`"version`": `"v$version`", `"binaries`": [$manifestRow], `"binaries_v2`": [$manifestRow]}"
+
+# 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
+try {
+ Start-Sleep -Seconds 2
+ $base = 'http://localhost:8123'
+
+ # 5. Route A: install.ps1 (the PowerShell-native entry point). The local
+ # channel rides the explicitly-named plaintext knob (the installers'
+ # https rule has exactly this escape hatch; a real channel is always
+ # https).
+ $prefixA = Join-Path $scratch 'prefix-a'
+ New-Item -ItemType Directory -Path $prefixA | Out-Null
+ $env:PRIME_AGENT_DOWNLOAD_BASE_URL = $base
+ $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' }
+ $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
+ if ($versionA -ne $version) { throw "the cmd launcher answered '$versionA' instead of '$version'" }
+ 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" }
+ }
+
+ # 6. Route B: install-rust.sh under Git Bash (the sh entry point).
+ $prefixB = Join-Path $scratch 'prefix-b'
+ New-Item -ItemType Directory -Path $prefixB | Out-Null
+ $bash = 'C:\Program Files\Git\bin\bash.exe'
+ if (-not (Test-Path $bash)) { throw "Git Bash is required for the sh route: $bash" }
+ $env:PRIME_AGENT_DOWNLOAD_BASE_URL = $base
+ $env:PRIME_AGENT_RELEASE_CHANNEL = 'stable'
+ $env:PRIME_AGENT_RUST_PREFIX = $prefixB
+ $env:PRIME_AGENT_ALLOW_HTTP = '1'
+ & $bash (Join-Path $repo 'install-rust.sh')
+ if ($LASTEXITCODE -ne 0) { throw 'install-rust.sh failed under Git Bash' }
+ $shLauncher = Join-Path $prefixB 'bin\prime-agent'
+ if (-not (Test-Path $shLauncher)) { throw "the sh launcher is missing: $shLauncher" }
+ $cmdLauncherB = Join-Path $prefixB 'bin\prime-agent.cmd'
+ if (-not (Test-Path $cmdLauncherB)) { throw "the sh route must also write the cmd twin: $cmdLauncherB" }
+ # The MSYS form of the prefix (bash cannot parse the drive-letter spelling
+ # inside its own quoting).
+ $prefixBMsys = (& $bash -c ("cygpath -u '" + $prefixB + "'")).Trim()
+ $versionB = (& $bash -c ('"' + $prefixBMsys + '/bin/prime-agent" --version') | Select-Object -First 1)
+ if ($versionB -ne $version) { throw "the sh launcher answered '$versionB' instead of '$version'" }
+ foreach ($entry in @('share\prime-agent\prime-agent.exe', 'share\prime-agent\prime-agent-runtime\pyproject.toml')) {
+ if (-not (Test-Path (Join-Path $prefixB $entry))) { throw "the sh route's payload is missing $entry" }
+ }
+
+ 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
+ Remove-Item -Recurse -Force $scratch -ErrorAction SilentlyContinue
+}
diff --git a/scripts/release/verify_release.py b/scripts/release/verify_release.py
index 4b69091b60..a6a866aad4 100644
--- a/scripts/release/verify_release.py
+++ b/scripts/release/verify_release.py
@@ -33,12 +33,19 @@ from pathlib import Path
from bundle_catalog import validate_bundled_catalog_dir
# The release platform alias the archive name carries (TS parity; the update
# flow's channel manifest requires alias-named archives).
-from assemble_artifacts import TARGET_ALIASES, RUNTIME_EXCLUDED_NAMES, RUNTIME_EXCLUDED_SUFFIXES
+from assemble_artifacts import (
+ TARGET_ALIASES,
+ RUNTIME_EXCLUDED_NAMES,
+ RUNTIME_EXCLUDED_SUFFIXES,
+ binary_name_for_target,
+)
# Must mirror STAGED_ENTRIES in assemble_artifacts.py and §5 of the design doc.
# Never add a root-level install.sh: it is what lets a TypeScript 0.9.8
# updater install the archive (release.yml's promote job refuses it).
# Continuous builds additionally stage the package.json version manifest.
+# The binary entry is the target's name (`prime-agent.exe` on the MSVC
+# Windows target), resolved in `main` via `binary_name_for_target`.
EXPECTED_TOP_LEVEL = {
"prime-agent",
"prime-agent-runtime",
@@ -94,7 +101,9 @@ def main() -> int:
fail("--sha (the continuous stamp) and --expect-package-json "
"(the restamped release shape) are mutually exclusive")
- expected_top_level = EXPECTED_TOP_LEVEL | (
+ binary_name = binary_name_for_target(args.target)
+ expected_top_level = (EXPECTED_TOP_LEVEL - {"prime-agent"}) | {binary_name}
+ expected_top_level |= (
CONTINUOUS_EXTRA_TOP_LEVEL if (args.sha or args.expect_package_json)
else set()
)
@@ -175,9 +184,9 @@ def main() -> int:
f"{args.expect_package_json!r}")
if not str(stamped.get("commit", "")).strip():
fail("the restamped package.json lost its commit provenance")
- binary = scratch / "prime-agent"
+ binary = scratch / binary_name
if not os.access(binary, os.X_OK):
- fail("staged prime-agent is not executable")
+ fail(f"staged {binary_name} is not executable")
if entries[archive_name]["executableSha256"] != sha256_file(binary):
fail("executableSha256 in manifest.json does not match the staged binary")
env = {k: v for k, v in os.environ.items() if k != "PI_PACKAGE_DIR"}