A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
3. add verified updates and rollback for compiled installs (#2166)
kt011574e4111b
diff --git a/.github/workflows/standalone-binaries.yml b/.github/workflows/standalone-binaries.ymlindex 126749afe0..5a35840d31 100644--- a/.github/workflows/standalone-binaries.yml+++ b/.github/workflows/standalone-binaries.yml@@ -71,7 +71,7 @@ jobs:- name: Test extracted application without JavaScript runtimes on PATHworking-directory: ${{ runner.temp }}/standalone-source/packages/coding-agent- run: npx tsx ../../node_modules/vitest/dist/cli.js --run test/compiled-artifact.test.ts test/native-installer.test.ts+ run: npx tsx ../../node_modules/vitest/dist/cli.js --run test/compiled-artifact.test.ts test/native-installer.test.ts test/native-probe-timeout.test.ts- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7with:diff --git a/install.sh b/install.shindex 1ec8300df2..019c5b8181 100755--- a/install.sh+++ b/install.sh@@ -1,4 +1,5 @@#!/bin/sh+# prime-agent-native-recovery-v1set -eu@@ -62,6 +63,10 @@ prime_agent_native_lock=prime_agent_allow_insecure_http=0main() {+ if [ "${1:-}" = --rollback ]; then+ prime_agent_native_rollback+ return+ fiif [ "${1:-}" = --native-platform ]; thenprime_agent_native_platformreturn@@ -1729,6 +1734,14 @@ prime_agent_native_platform() {}prime_agent_native_cleanup() {+ if [ -n "${prime_agent_native_lock:-}" ] && [ "$(cat "$prime_agent_native_lock/pid" 2>/dev/null || :)" = "$$" ] &&+ [ -n "${native_root:-}" ] && { [ -e "$native_root/.activation-state" ] || [ -L "$native_root/.activation-state" ]; }; then+ if prime_agent_native_recover_activation; then+ prime_agent_native_prune_releases+ else+ printf 'Could not recover the interrupted activation; inspect %s/.activation-state before retrying.\n' "$native_root" >&2+ fi+ fiif [ -n "${prime_agent_native_activation_target:-}" ] && [ -n "${prime_agent_native_activation_previous:-}" ] &&[ "$(readlink "$native_root/bin/prime-agent" 2>/dev/null || :)" = "$prime_agent_native_activation_target" ] &&[ "$(readlink "$native_root/bin/previous" 2>/dev/null || :)" != "$prime_agent_native_activation_previous" ]; then@@ -1781,17 +1794,243 @@ prime_agent_native_prepare_root() {}fidone+ prime_agent_native_sweep_orphan_stagesprime_agent_native_stage=$(mktemp -d "$native_root/.install.XXXXXX")+ prime_agent_native_recovered=0+ prime_agent_native_recover_activation || exit 1+ if [ "$prime_agent_native_recovered" = 1 ]; then+ prime_agent_native_prune_releases+ fiif [ "${PRIME_AGENT_EXPECTED_CURRENT+x}" = x ] && [ "$(readlink "$native_root/bin/prime-agent" 2>/dev/null || :)" != "$PRIME_AGENT_EXPECTED_CURRENT" ]; thenprintf 'error: the active release changed; retry the update.\n' >&2; exit 1fi}+prime_agent_native_rollback() {+ prime_agent_install_traps+ prime_agent_native_prepare_root+ [ -L "$native_root/bin/previous" ] || { printf 'error: no previous compiled release is available.\n' >&2; exit 1; }+ native_previous=$(readlink "$native_root/bin/previous")+ native_current=$(readlink "$native_root/bin/prime-agent")+ if [ -n "${PRIME_AGENT_EXPECTED_PREVIOUS:-}" ] && [ "$native_previous" != "$PRIME_AGENT_EXPECTED_PREVIOUS" ]; then+ printf 'error: the previous release changed while planning rollback; retry.\n' >&2; exit 1+ fi+ [ "$native_previous" != "$native_current" ] || { printf 'error: no different previous release is available.\n' >&2; exit 1; }+ prime_agent_native_verify_release_target "$native_previous" previous || exit 1+ if prime_agent_native_verify_release_target "$native_current" current >/dev/null 2>&1; then+ prime_agent_native_activate "$native_previous" "$native_current"+ else+ # Repair only the active link; keep the healthy rollback target instead of retaining damage.+ prime_agent_native_atomic_link "$native_previous" "$native_root/bin/prime-agent" || exit 1+ fi+ prime_agent_native_prune_releases+ printf 'Restored the previous compiled release.\n'+ prime_agent_native_cleanup+}+prime_agent_native_valid_target() {- case "$1" in ../releases/*/prime-agent) ;; *) return 1 ;; esac- native_target_name=${1#../releases/}- native_target_name=${native_target_name%/prime-agent}- case "$native_target_name" in ''|.|..|*[!0-9A-Za-z.-]*) return 1 ;; esac+ prime_agent_native_parse_target "$1"+ return $?+}++prime_agent_native_parse_target() {+ native_parsed_target="$1"+ case "$native_parsed_target" in ../releases/*/prime-agent) ;; *) return 1 ;; esac+ native_parsed_name=${native_parsed_target#../releases/}+ native_parsed_name=${native_parsed_name%/prime-agent}+ case "$native_parsed_name" in ''|.|..|*/*|*[!0-9A-Za-z.-]*) return 1 ;; esac+ native_parsed_digest_suffix=${native_parsed_name##*-}+ native_parsed_digest=${native_parsed_digest_suffix%%.*}+ [ "${#native_parsed_digest}" -eq 64 ] || return 1+ case "$native_parsed_digest" in *[!0-9a-f]*) return 1 ;; esac+ if [ "$native_parsed_digest_suffix" != "$native_parsed_digest" ]; then+ native_parsed_unique=${native_parsed_digest_suffix#"$native_parsed_digest".}+ [ "${#native_parsed_unique}" -eq 6 ] || return 1+ case "$native_parsed_unique" in *[!0-9A-Za-z]*) return 1 ;; esac+ fi+ native_parsed_prefix=${native_parsed_name%-"$native_parsed_digest_suffix"}+ case "$native_parsed_prefix" in+ *-darwin-arm64) native_parsed_version=${native_parsed_prefix%-darwin-arm64}; native_parsed_platform=darwin-arm64 ;;+ *-darwin-x64) native_parsed_version=${native_parsed_prefix%-darwin-x64}; native_parsed_platform=darwin-x64 ;;+ *-linux-arm64) native_parsed_version=${native_parsed_prefix%-linux-arm64}; native_parsed_platform=linux-arm64 ;;+ *-linux-x64) native_parsed_version=${native_parsed_prefix%-linux-x64}; native_parsed_platform=linux-x64 ;;+ *) return 1 ;;+ esac+ printf '%s\n' "$native_parsed_version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$' || return 1+ native_parsed_dir="$native_root/releases/$native_parsed_name"+}++prime_agent_native_validate_asset() {+ native_asset_release_dir="$1"+ native_asset_relative="$2"+ native_asset_path="$native_asset_release_dir/$native_asset_relative"+ [ -f "$native_asset_path" ] && [ ! -L "$native_asset_path" ] || return 1+ case "$native_asset_relative" in+ */*) native_asset_parent_relative=${native_asset_relative%/*} ;;+ *) native_asset_parent_relative= ;;+ esac+ if [ -n "$native_asset_parent_relative" ]; then+ native_asset_expected_parent="$native_asset_release_dir/$native_asset_parent_relative"+ else+ native_asset_expected_parent="$native_asset_release_dir"+ fi+ native_asset_actual_parent=$(CDPATH= cd "$(dirname "$native_asset_path")" 2>/dev/null && pwd -P) || return 1+ [ "$native_asset_actual_parent" = "$native_asset_expected_parent" ]+}++prime_agent_native_validate_release_metadata() {+ native_metadata_target="$1"+ prime_agent_native_parse_target "$native_metadata_target" || return 1+ native_metadata_dir="$native_parsed_dir"+ native_metadata_version="$native_parsed_version"+ native_metadata_digest="$native_parsed_digest"+ [ -d "$native_metadata_dir" ] && [ ! -L "$native_metadata_dir" ] || return 1+ [ "$(CDPATH= cd "$native_metadata_dir" 2>/dev/null && pwd -P)" = "$native_metadata_dir" ] || return 1+ for native_metadata_asset in prime-agent package.json install.sh prime-agent-runtime/pyproject.toml prime-agent-runtime/src/rlm/repl.py theme/prime.json export-html/template.html photon_rs_bg.wasm .archive-sha256 .install-source; do+ prime_agent_native_validate_asset "$native_metadata_dir" "$native_metadata_asset" || return 1+ done+ [ "$(cat "$native_metadata_dir/.archive-sha256")" = "$native_metadata_digest" ] || return 1+ native_metadata_package_version=$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$native_metadata_dir/package.json")+ [ "$native_metadata_package_version" = "$native_metadata_version" ] || return 1+ native_metadata_source=$(cat "$native_metadata_dir/.install-source")+ case "$native_metadata_source" in http://*|https://*) ;; *) return 1 ;; esac+}++prime_agent_native_probe() (+ # macOS does not ship timeout; keep the deadline independent of Node and Python.+ native_probe_pid=+ trap '+ if [ -n "$native_probe_pid" ]; then+ kill -KILL "$native_probe_pid" 2>/dev/null || :+ wait "$native_probe_pid" 2>/dev/null || :+ fi+ ' EXIT+ trap 'exit 130' INT+ trap 'exit 143' TERM+ trap 'exit 129' HUP+ "$@" &+ native_probe_pid=$!+ native_probe_deadline=$(($(date +%s) + 10))+ while kill -0 "$native_probe_pid" 2>/dev/null; do+ if [ "$(date +%s)" -ge "$native_probe_deadline" ]; then+ printf 'error: executable probe timed out after 10 seconds.\n' >&2+ kill -KILL "$native_probe_pid" 2>/dev/null || :+ wait "$native_probe_pid" 2>/dev/null || :+ native_probe_pid=+ exit 124+ fi+ sleep 0.1+ done+ if wait "$native_probe_pid"; then native_probe_status=0; else native_probe_status=$?; fi+ native_probe_pid=+ exit "$native_probe_status"+)++prime_agent_native_verify_release_target() {+ native_verify_target="$1"+ native_verify_label="$2"+ if ! prime_agent_native_validate_release_metadata "$native_verify_target"; then+ printf 'error: invalid %s release metadata or assets. The active release was kept.\n' "$native_verify_label" >&2+ return 1+ fi+ native_verify_dir="$native_metadata_dir"+ native_verify_version="$native_metadata_version"+ if ! prime_agent_native_probe "$native_verify_dir/prime-agent" --version >"$prime_agent_native_stage/$native_verify_label.version" 2>"$prime_agent_native_stage/$native_verify_label.probe.log"; then+ cat "$prime_agent_native_stage/$native_verify_label.probe.log" >&2+ printf 'error: the %s release executable could not be validated. The active release was kept.\n' "$native_verify_label" >&2+ return 1+ fi+ if [ "$(cat "$prime_agent_native_stage/$native_verify_label.version")" != "$native_verify_version" ]; then+ printf 'error: the %s release executable reports a different version. The active release was kept.\n' "$native_verify_label" >&2+ return 1+ fi+ if ! prime_agent_native_probe "$native_verify_dir/prime-agent" --help >"$prime_agent_native_stage/$native_verify_label.help" 2>"$prime_agent_native_stage/$native_verify_label.help.log"; then+ cat "$prime_agent_native_stage/$native_verify_label.help.log" >&2+ printf 'error: the %s release executable failed its help probe. The active release was kept.\n' "$native_verify_label" >&2+ return 1+ fi+}++prime_agent_native_sweep_orphan_stages() {+ for native_orphan_stage in "$native_root"/.install.*; do+ [ -e "$native_orphan_stage" ] || [ -L "$native_orphan_stage" ] || continue+ native_orphan_name=${native_orphan_stage##*/}+ native_orphan_suffix=${native_orphan_name#.install.}+ [ "${#native_orphan_suffix}" -eq 6 ] || continue+ case "$native_orphan_suffix" in *[!0-9A-Za-z]*) continue ;; esac+ [ -d "$native_orphan_stage" ] && [ ! -L "$native_orphan_stage" ] || continue+ rm -rf "$native_orphan_stage"+ done+}++prime_agent_native_release_in_use() {+ native_usage_executable="$1"+ if native_lsof=$(command -v lsof 2>/dev/null); then+ :+ elif [ -x /usr/sbin/lsof ]; then+ native_lsof=/usr/sbin/lsof+ elif [ -x /usr/bin/lsof ]; then+ native_lsof=/usr/bin/lsof+ else+ return 2+ fi+ if "$native_lsof" -n -F p "$native_usage_executable" >"$prime_agent_native_stage/lsof.out" 2>"$prime_agent_native_stage/lsof.err"; then+ return 0+ else+ native_lsof_status=$?+ fi+ [ "$native_lsof_status" -eq 1 ] && [ ! -s "$prime_agent_native_stage/lsof.err" ] && return 1+ return 2+}++prime_agent_native_prune_releases() {+ native_prune_current=$(readlink "$native_root/bin/prime-agent" 2>/dev/null || :)+ native_prune_previous=$(readlink "$native_root/bin/previous" 2>/dev/null || :)+ for native_prune_dir in "$native_root"/releases/*; do+ [ -e "$native_prune_dir" ] || [ -L "$native_prune_dir" ] || continue+ [ -d "$native_prune_dir" ] && [ ! -L "$native_prune_dir" ] || continue+ native_prune_target="../releases/${native_prune_dir##*/}/prime-agent"+ [ "$native_prune_target" != "$native_prune_current" ] || continue+ [ "$native_prune_target" != "$native_prune_previous" ] || continue+ prime_agent_native_validate_release_metadata "$native_prune_target" || continue+ if prime_agent_native_release_in_use "$native_prune_dir/prime-agent"; then+ continue+ else+ native_prune_usage_status=$?+ fi+ [ "$native_prune_usage_status" -eq 1 ] || continue+ rm -rf "$native_prune_dir"+ done+}++prime_agent_native_recover_activation() {+ native_activation_state="$native_root/.activation-state"+ if [ ! -e "$native_activation_state" ] && [ ! -L "$native_activation_state" ]; then+ return 0+ fi+ if [ ! -f "$native_activation_state" ] || [ -L "$native_activation_state" ] ||+ [ "$(wc -l <"$native_activation_state" | tr -d ' ')" != 2 ]; then+ printf 'error: invalid activation recovery state at %s. Restore bin/prime-agent and bin/previous, then remove it.\n' "$native_activation_state" >&2+ return 1+ fi+ native_recovery_target=$(sed -n '1p' "$native_activation_state")+ native_recovery_previous=$(sed -n '2p' "$native_activation_state")+ prime_agent_native_verify_release_target "$native_recovery_target" recovery-target || return 1+ if [ -n "$native_recovery_previous" ]; then+ prime_agent_native_verify_release_target "$native_recovery_previous" recovery-previous || return 1+ fi+ native_recovery_current=$(readlink "$native_root/bin/prime-agent" 2>/dev/null || :)+ if [ "$native_recovery_current" = "$native_recovery_target" ]; then+ if [ -n "$native_recovery_previous" ] && [ "$native_recovery_previous" != "$native_recovery_target" ] &&+ [ "$(readlink "$native_root/bin/previous" 2>/dev/null || :)" != "$native_recovery_previous" ]; then+ prime_agent_native_atomic_link "$native_recovery_previous" "$native_root/bin/previous" || return 1+ fi+ elif [ "$native_recovery_current" != "$native_recovery_previous" ]; then+ printf 'error: activation recovery is ambiguous: bin/prime-agent matches neither recorded release. Restore the links using %s before retrying.\n' "$native_activation_state" >&2+ return 1+ fi+ rm -f "$native_activation_state" || return 1+ prime_agent_native_recovered=1}prime_agent_native_check_public_link() {@@ -1823,20 +2062,26 @@ prime_agent_native_validate_archive() {}prime_agent_native_atomic_link() {- native_link_stage=$(mktemp -d "$prime_agent_native_stage/link.XXXXXX")- ln -s "$1" "$native_link_stage/link"+ native_link_stage=$(mktemp -d "$prime_agent_native_stage/link.XXXXXX") || return 1+ ln -s "$1" "$native_link_stage/link" || return 1# The destination is an executable link, never a directory link.- mv -f "$native_link_stage/link" "$2"- rmdir "$native_link_stage"+ mv -f "$native_link_stage/link" "$2" || return 1+ rmdir "$native_link_stage" || return 1}prime_agent_native_activate() {prime_agent_native_activation_target="$1"prime_agent_native_activation_previous="$2"+ {+ printf '%s\n' "$1"+ printf '%s\n' "$2"+ } >"$prime_agent_native_stage/activation-state"+ mv -f "$prime_agent_native_stage/activation-state" "$native_root/.activation-state"prime_agent_native_atomic_link "$1" "$native_root/bin/prime-agent"if [ -n "$2" ] && [ "$1" != "$2" ]; thenprime_agent_native_atomic_link "$2" "$native_root/bin/previous"fi+ rm -f "$native_root/.activation-state"prime_agent_native_activation_target=prime_agent_native_activation_previous=}@@ -1893,6 +2138,9 @@ prime_agent_install_native() {rm -rf "$prime_agent_download_dir"prime_agent_download_dir=native_archive="$prime_agent_native_stage/$native_file"+ if [ -n "${PRIME_AGENT_EXPECTED_SHA256:-}" ] && [ "$(awk '{print $1}' "$prime_agent_native_stage/selected.sha256")" != "$PRIME_AGENT_EXPECTED_SHA256" ]; then+ printf 'error: release manifest and checksum inventory disagree.\n' >&2; exit 1+ fiprime_agent_run_quiet_with_animation "Downloading Prime Agent" "Downloading compiled Prime Agent" "$native_platform" \prime_agent_curl_download -fsSL --connect-timeout 10 --max-time 300 "$prime_agent_base_url/releases/v$native_version/$native_file" -o "$native_archive"if command -v sha256sum >/dev/null 2>&1; then native_checker=sha256sum; else native_checker=shasum; fi@@ -1905,7 +2153,7 @@ prime_agent_install_native() {for native_asset in prime-agent package.json install.sh prime-agent-runtime/pyproject.toml prime-agent-runtime/src/rlm/repl.py theme/prime.json export-html/template.html photon_rs_bg.wasm; do[ -f "$native_extracted/$native_asset" ] || { printf 'error: missing archive asset: %s\n' "$native_asset" >&2; exit 1; }done- if ! "$native_extracted/prime-agent" --version >"$prime_agent_native_stage/version" 2>"$prime_agent_native_stage/probe.log"; then+ if ! prime_agent_native_probe "$native_extracted/prime-agent" --version >"$prime_agent_native_stage/version" 2>"$prime_agent_native_stage/probe.log"; thencat "$prime_agent_native_stage/probe.log" >&2prime_agent_native_cleanupif [ "${PRIME_AGENT_INSTALL_METHOD:-auto}" = auto ]; then@@ -1916,7 +2164,7 @@ prime_agent_install_native() {printf 'error: the compiled executable cannot run on this machine.\n' >&2; exit 1fi[ "$(cat "$prime_agent_native_stage/version")" = "$native_version" ] || { printf 'error: archive version mismatch.\n' >&2; exit 1; }- "$native_extracted/prime-agent" --help >"$prime_agent_native_stage/help"+ prime_agent_native_probe "$native_extracted/prime-agent" --help >"$prime_agent_native_stage/help"prime_agent_native_check_public_linknative_digest=$(awk '{ print $1 }' "$prime_agent_native_stage/selected.sha256")native_release_name="$native_version-$native_platform-$native_digest"@@ -1954,8 +2202,13 @@ prime_agent_install_native() {fi# Keep an existing release active if creating the public command loses a race.if [ -n "$native_previous" ]; then- prime_agent_native_activate "$native_target" "$native_previous"+ if prime_agent_native_verify_release_target "$native_previous" current >/dev/null 2>&1; then+ prime_agent_native_activate "$native_target" "$native_previous"+ else+ prime_agent_native_atomic_link "$native_target" "$native_root/bin/prime-agent" || exit 1+ fifi+ prime_agent_native_prune_releasesif [ "${PRIME_AGENT_INSTALL_LINK:-1}" != 0 ]; thenprime_agent_native_configure_path || printf 'Add %s to PATH to run Prime Agent.\n' "$native_public_bin" >&2fidiff --git a/packages/coding-agent/.changes/eng-6047-native-updates.md b/packages/coding-agent/.changes/eng-6047-native-updates.mdnew file mode 100644index 0000000000..5c4a6a510e--- /dev/null+++ b/packages/coding-agent/.changes/eng-6047-native-updates.md@@ -0,0 +1,11 @@+- Added verified updates and offline rollback for compiled Prime Agent installations, preserving sessions and restarting with the activated release.+- Fixed normal interruptions during rollback losing the release needed to undo that rollback.+- Fixed malformed compiled-release metadata causing unnecessary npm reinstalls and daemon restarts.+- Fixed interrupted compiled activation recovering the exact rollback target before another lifecycle change.+- Added conservative cleanup for abandoned installer staging and inactive managed releases while retaining live or uncertain releases.+- Fixed direct and planned rollback rejecting inconsistent release metadata, assets, paths, and executable versions before activation.+- Fixed failed activation recovery discarding the state needed to retry restoring the previous release.+- Fixed damaged compiled installations blocking repair and rollback to a healthy retained release.+- Fixed rollback planning after interrupted activation and provided repair guidance for older retained installers without recovery support.+- Fixed stalled executable checks holding the installer lock indefinitely during installation, rollback, or activation recovery.+- Fixed update guidance directing repairable compiled installations to a manual download instead of the update command.diff --git a/packages/coding-agent/docs/standalone-binaries.md b/packages/coding-agent/docs/standalone-binaries.mdindex 16321a8a66..cd3e479171 100644--- a/packages/coding-agent/docs/standalone-binaries.md+++ b/packages/coding-agent/docs/standalone-binaries.md@@ -78,11 +78,11 @@ Pinning a release whose checksum inventory only advertises npm packages uses theSet `PRIME_AGENT_INSTALL_METHOD=node` to explicitly keep the Node installation, or `binary` to require the compiled application. `PRIME_AGENT_INSTALL_DIR` overrides the managed root (default `$XDG_DATA_HOME/prime-agent` or `~/.local/share/prime-agent`); `PRIME_AGENT_BIN_DIR` overrides the public command directory (default `~/.local/bin`). Both must be absolute. Existing unrelated commands are never replaced. `PRIME_AGENT_INSTALL_LINK=0` installs without a public link.-Each release keeps its executable and assets together under `releases/`. The stable `bin/prime-agent` link changes only after validation, and `bin/previous` retains the earlier release. The installer serializes changes with `.install-lock`; normal interruption cleans up the lock. After a forced kill, confirm its recorded process is no longer running before removing the stale lock. User data remains in `~/.prime/agent`.+Each release keeps its executable and assets together under `releases/`. The stable `bin/prime-agent` link changes only after validation, and `bin/previous` retains the earlier release. The installer serializes changes with `.install-lock`; normal interruption cleans up the lock. Activation also records a durable `.activation-state` intent before changing either launcher. After a forced kill, confirm the recorded installer process is no longer running before removing the stale lock; the next installer or rollback invocation then completes or clears an unambiguous interrupted activation before making another change. User data remains in `~/.prime/agent`.-Reinstalling the same archive creates a fresh release directory with a unique suffix, so it can repair missing or changed assets without modifying files used by existing processes. Old release directories are retained; there is no automatic garbage collection yet.+Reinstalling the same archive creates a fresh release directory with a unique suffix, so it can repair missing or changed assets without modifying files used by existing processes. Cleanup runs only after the replacement is healthy.-Activation replaces the current launcher before refreshing the previous launcher. Normal interruption finishes retaining the replaced release during cleanup. A forced kill between those operations keeps the earlier rollback target intact; it may therefore point to an older retained release rather than the release that was just replaced. A forced kill still requires confirming and clearing the stale installation lock.+After a healthy activation or activation recovery, the installer removes abandoned `.install.<suffix>` staging directories while holding the installation lock. It also removes obsolete managed release directories when `lsof` can inspect the release executable and reports it unused. Current, previous, live, malformed, symlinked, and otherwise uncertain directories are retained. If `lsof` is unavailable or cannot inspect a candidate, that release is kept for a later installer run or manual review; no user-data or legacy Node/npm directory is part of this maintenance.The installer still shows download and verification progress and can prepare Python. Compilation removes JavaScript dependency installation; Python and external tools still need preparation. Set `PRIME_AGENT_BOOTSTRAP_KERNEL_ON_INSTALL=0` to defer Python setup.@@ -100,4 +100,24 @@ Migration reuses an equal or newer managed release. It also checks the capturedBefore reusing a compiled release, the bridge checks the installer's OS/architecture compatibility result and probes the executable's version. Unsupported hosts quietly retain Node. A broken probe or a mismatch with installed release metadata reports a rate-limited diagnostic with reinstall and opt-out guidance. Command handoff captures the npm link and creates the native link exclusively, so a concurrent npm command wins instead of being overwritten. The public path can be briefly absent during this one-time transfer. If abrupt termination prevents restoration, the captured command remains under the adjacent `.prime-agent-link-*` directory for recovery; the versioned application and user data remain intact.-Compiled self-update and rollback are handled by the final layer of the rollout. Homebrew packaging remains separate work.+Failed automatic migrations retry after 24 hours; `PRIME_AGENT_MIGRATE_RETRY=1` retries immediately. Homebrew packaging remains separate work.++## Updates and rollback++Run `prime-agent update` or `/update` to install the latest version on the current stable or beta channel. Managed compiled installations require a matching platform entry in the release manifest and verify its SHA-256 against both the release checksums and downloaded archive. Failed downloads or validation leave the current executable and assets active. Unmanaged archives must be updated through their original installer.++Updates retain the previous release, preserve user configuration and sessions, and use the existing busy-session confirmation and daemon restart coordination. Relaunches resolve the stable launcher after activation, so the new process runs the updated application. The installer checks that the active release has not changed since the update was planned and serializes activation with its installation lock.++Run `prime-agent update --rollback` or `/update --rollback` to restore the previous local release without downloading anything. Its managed path, checksum marker, package version, install source, required assets, executable version, and help probe are validated before switching. These checks establish internal installation consistency; they do not cryptographically re-verify every installed file against the original archive. A second rollback restores the release you just left when that release remains healthy. Rollback requires a retained release and applies only to managed compiled installations. `--force` permits reinstalling the version selected by the release channel.++If the active release is damaged, rollback validates and activates the healthy previous release without retaining the damaged one as a rollback target. Update planning can use the intact previous release's installer when it declares support for damaged-release recovery. Older retained installers instead give published-installer recovery guidance. If the current executable cannot start, rerun the published installer with `PRIME_AGENT_INSTALL_DIR` set to the managed root. Repairs preserve an existing healthy previous release.++Normal interruption during rollback finishes retaining the release being left. A forced kill can leave the launcher changes incomplete and the installation lock stale, but it also leaves the activation intent needed for the next installer invocation to recover the exact pair. Recovery refuses an unexpected or invalid link state and reports the state file instead of guessing.++## Coverage and recovery limits++Native CI runs the extracted archives on macOS 15 (ARM64 and x64) and Ubuntu 24.04 (ARM64 and x64). It tests installation, forced reinstall, later update, offline rollback, daemon replacement, runtime assets, RPC, and managed Python without JavaScript runtimes on the application PATH. The installer selects macOS 13+ and compatible glibc Linux, but these selection checks do not constitute execution testing on every older OS release.++Focused regressions cover migration without lifecycle scripts, incompatible existing binaries, deferred migration during internal daemon startup, competing installs and npm command handoffs, checksum/manifest failures, rollback metadata and executable-version mismatches, interrupted activation recovery, conservative release retention, and orphan staging cleanup. Normal installer hangups release the lock. A forced kill still requires confirming and clearing its stale lock before recovery can run; complete filesystem power-loss, disk-exhaustion, ACL, and network-filesystem fault testing is outside this matrix.++Rollback restores application files, not arbitrary future user-data schema changes. SHA-256 verification detects archive/metadata disagreement; it does not introduce an independent release-signing authority. Shell aliases and earlier competing PATH entries are not rewritten. The Node fallback package remains on disk, as do compiled releases whose use cannot be ruled out safely.diff --git a/packages/coding-agent/src/cli/command-registry.ts b/packages/coding-agent/src/cli/command-registry.tsindex e1c37e126c..6b48151ad4 100644--- a/packages/coding-agent/src/cli/command-registry.ts+++ b/packages/coding-agent/src/cli/command-registry.ts@@ -148,7 +148,7 @@ export const COMMAND_SPECS: readonly CommandSpec[] = [},{path: ["update"],- usage: "update [--force]",+ usage: "update [--force] [--rollback]",summary: "Update Prime Agent",},{diff --git a/packages/coding-agent/src/cli/daemon-update-restart.ts b/packages/coding-agent/src/cli/daemon-update-restart.tsindex f02ed081f0..8172381767 100644--- a/packages/coding-agent/src/cli/daemon-update-restart.ts+++ b/packages/coding-agent/src/cli/daemon-update-restart.ts@@ -14,7 +14,7 @@ import {DAEMON_WORKER_TOKEN_ENV,} from "../modes/daemon/daemon-worker-protocol.js";import { isProcessAlive, spawnHidden } from "../utils/child-process.js";-import { createCliSubprocessLaunchSpec } from "./subprocess-launch.js";+import { createUpdatedCliSubprocessLaunchSpec } from "./subprocess-launch.js";export const DAEMON_UPDATE_RESTART_COORDINATOR_FLAG = "--internal-update-restart-coordinator";export const DAEMON_UPDATE_RESTART_STATUS_FLAG = "--internal-update-restart-status";@@ -538,7 +538,7 @@ export async function launchDaemonUpdateRestartCoordinator(const statusPath = createStatusPath(agentDir, socketPath, requestId);const inheritedOrigin = process.env[DAEMON_WORKER_ACTIVE_SESSION_ID_ENV];const originActiveSessionId = options.originActiveSessionId ?? inheritedOrigin;- const launch = createCliSubprocessLaunchSpec([+ const launch = createUpdatedCliSubprocessLaunchSpec(["update",DAEMON_UPDATE_RESTART_COORDINATOR_FLAG,"--daemon-socket",diff --git a/packages/coding-agent/src/cli/native-update.ts b/packages/coding-agent/src/cli/native-update.tsnew file mode 100644index 0000000000..1e32f6a6c7--- /dev/null+++ b/packages/coding-agent/src/cli/native-update.ts@@ -0,0 +1,102 @@+import { execFileSync } from "node:child_process";+import { accessSync, constants, readFileSync } from "node:fs";+import { join, relative } from "node:path";+import { APP_NAME, type SelfUpdateCommand } from "../config.js";+import {+ getNativeInstallationTarget,+ readNativeInstallation,+ readNativeRollbackInstallation,+} from "../utils/native-installation.js";+import { getLatestPiRelease, isNewerPackageVersion } from "../utils/version-check.js";++export interface NativeUpdatePlan {+ command?: SelfUpdateCommand;+ targetVersion: string;+}++export async function getNativeUpdatePlan(options: {+ force: boolean;+ rollback: boolean;+ executable?: string;+}): Promise<NativeUpdatePlan> {+ const current = getNativeInstallationTarget(options.executable);+ if (!current)+ throw new Error(+ "This compiled application is not owned by the Prime Agent installer. Update it using its original installer.",+ );+ const active = readNativeInstallation(current.root);+ const installation = active ?? readNativeInstallation(current.root, "previous");+ if (!installation || installation.platform !== current.platform)+ throw new Error("The compiled installation is damaged. Run the published installer again to repair it.");+ if (+ (options.rollback || !active) &&+ !/^# prime-agent-native-recovery-v1$/m.test(readFileSync(join(installation.releaseDir, "install.sh"), "utf8"))+ )+ throw new Error(+ "The retained installer does not support this recovery. Run the published installer at https://app.primeintellect.ai/prime-agent/install.sh again to repair it.",+ );+ accessSync(installation.root, constants.W_OK);+ accessSync(join(installation.root, "bin"), constants.W_OK);+ let version: string;+ let checksum: string | undefined;+ let previousTarget: string | undefined;+ const baseUrl = process.env.PRIME_AGENT_DOWNLOAD_BASE_URL?.trim() || installation.baseUrl;+ if (options.rollback) {+ const previous = readNativeRollbackInstallation(installation.root);+ if (!previous || previous.executable === current.executable)+ throw new Error("No valid previous compiled release is available.");+ let reportedVersion: string;+ try {+ reportedVersion = execFileSync(previous.executable, ["--version"], {+ encoding: "utf8",+ timeout: 10000,+ });+ } catch {+ throw new Error("The previous compiled release executable could not be validated.");+ }+ if (reportedVersion !== previous.version && reportedVersion !== `${previous.version}\n`)+ throw new Error("The previous compiled release executable reports a different version.");+ try {+ execFileSync(previous.executable, ["--help"], { stdio: "ignore", timeout: 10000 });+ } catch {+ throw new Error("The previous compiled release executable failed its help probe.");+ }+ version = previous.version;+ previousTarget = relative(join(installation.root, "bin"), previous.executable);+ } else {+ const release = await getLatestPiRelease(current.version, { baseUrl });+ if (!release || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(release.version))+ throw new Error("Could not resolve a compiled release. The installed version was kept.");+ if (active && !options.force && !isNewerPackageVersion(release.version, current.version))+ return { targetVersion: current.version };+ const artifact = release.binaries?.find((entry) => entry.platform === current.platform);+ if (!artifact) throw new Error(`No verified compiled archive is available for ${current.platform}.`);+ version = release.version;+ checksum = artifact.sha256;+ }+ const environment = {+ PRIME_AGENT_INSTALL_METHOD: "binary",+ PRIME_AGENT_INSTALL_DIR: installation.root,+ PRIME_AGENT_DOWNLOAD_BASE_URL: baseUrl,+ PRIME_AGENT_INSTALL_LINK: "0",+ PRIME_AGENT_INSTALLER_NONINTERACTIVE: "1",+ PRIME_AGENT_INSTALLER_PLAIN: "1",+ PRIME_AGENT_BOOTSTRAP_KERNEL_ON_INSTALL: "0",+ PRIME_AGENT_EXPECTED_CURRENT: relative(join(current.root, "bin"), current.executable),+ ...(previousTarget ? { PRIME_AGENT_EXPECTED_PREVIOUS: previousTarget } : {}),+ ...(checksum ? { PRIME_AGENT_EXPECTED_SHA256: checksum } : {}),+ };+ return {+ targetVersion: version,+ command: {+ command: "/usr/bin/env",+ args: [+ ...Object.entries(environment).map(([name, value]) => `${name}=${value}`),+ "sh",+ join(installation.releaseDir, "install.sh"),+ options.rollback ? "--rollback" : version,+ ],+ display: `${APP_NAME} update${options.rollback ? " --rollback" : options.force ? " --force" : ""}`,+ },+ };+}diff --git a/packages/coding-agent/src/cli/public-command.ts b/packages/coding-agent/src/cli/public-command.tsindex 6df9e5797a..9c6e53bd11 100644--- a/packages/coding-agent/src/cli/public-command.ts+++ b/packages/coding-agent/src/cli/public-command.ts@@ -133,7 +133,7 @@ async function runPublicCommand(args: string[]): Promise<PublicCommandResult> {if (hasLegacyPackageTarget) {return fail("Package updates moved to the package command.", `Use "${APP_NAME} package update [source]".`);}- const options = parseBooleanOptions(rest, new Set(["--force"]), "update");+ const options = parseBooleanOptions(rest, new Set(["--force", "--rollback"]), "update");if (!options) return HANDLED;await handlePackageCommand(["update", "--self", ...options]);return HANDLED;diff --git a/packages/coding-agent/src/cli/subprocess-launch.ts b/packages/coding-agent/src/cli/subprocess-launch.tsindex f5843b48d1..9c60f14069 100644--- a/packages/coding-agent/src/cli/subprocess-launch.ts+++ b/packages/coding-agent/src/cli/subprocess-launch.ts@@ -1,12 +1,18 @@import { existsSync } from "node:fs";import { dirname, isAbsolute, join, resolve } from "node:path";import { isBunBinary } from "../config.js";+import { getNativeInstallation } from "../utils/native-installation.js";export interface CliSubprocessLaunchSpec {command: string;args: string[];}+export function createUpdatedCliSubprocessLaunchSpec(args: readonly string[]): CliSubprocessLaunchSpec {+ const native = isBunBinary ? getNativeInstallation() : undefined;+ return native ? { command: native.launcher, args: [...args] } : createCliSubprocessLaunchSpec(args);+}+export function createCliSubprocessEnv(source: NodeJS.ProcessEnv = process.env,entrypoint = process.argv[1],diff --git a/packages/coding-agent/src/config.ts b/packages/coding-agent/src/config.tsindex 9754e432c7..942ebd454f 100644--- a/packages/coding-agent/src/config.ts+++ b/packages/coding-agent/src/config.ts@@ -16,6 +16,7 @@ import { basename, dirname, join, posix, resolve, sep, win32 } from "path";import { fileURLToPath } from "url";import { shouldUseWindowsShell, spawnSyncHidden } from "./utils/child-process.js";import { normalizeSocketPath } from "./utils/daemon-socket-path.js";+import { getNativeInstallationTarget } from "./utils/native-installation.js";// =============================================================================// Package Detection@@ -343,6 +344,7 @@ export function getSelfUpdateUnavailableInstruction(}export function getUpdateInstruction(packageName: string): string {+ if (isBunBinary && getNativeInstallationTarget()) return `Run: ${APP_NAME} update`;const method = detectInstallMethod();const command = getSelfUpdateCommandForMethod(method, packageName);if (command) {diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex 5e15d1f281..69a6a22366 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -48,7 +48,11 @@ import {launchDaemonUpdateRestartCoordinator,resolveDaemonUpdateRestartSocketPath,} from "../../cli/daemon-update-restart.js";-import { type CliSubprocessLaunchSpec, createCliSubprocessLaunchSpec } from "../../cli/subprocess-launch.js";+import {+ type CliSubprocessLaunchSpec,+ createCliSubprocessLaunchSpec,+ createUpdatedCliSubprocessLaunchSpec,+} from "../../cli/subprocess-launch.js";import {APP_NAME,APP_TITLE,@@ -8660,15 +8664,12 @@ export class InteractiveMode {this.ui.stop();const updateEnv = includesSelf ? { ...process.env, [SELF_UPDATE_INTERACTIVE_CHILD_ENV]: "1" } : process.env;- const updateResult = spawnSync(- process.execPath,- [...process.execArgv, entrypoint, "update", ...updateChildArgs],- {- stdio: "inherit",- cwd: updateCwd,- env: updateEnv,- },- );+ const updateLaunch = createCliSubprocessLaunchSpec(["update", ...updateChildArgs]);+ const updateResult = spawnSync(updateLaunch.command, updateLaunch.args, {+ stdio: "inherit",+ cwd: updateCwd,+ env: updateEnv,+ });const updateExitCode = updateResult.status ?? (updateResult.signal ? 1 : 0);const selfUpdateNotAttempted =includesSelf && !updateResult.error && updateExitCode === SELF_UPDATE_NOT_ATTEMPTED_EXIT_CODE;@@ -8714,7 +8715,7 @@ export class InteractiveMode {);}}- const relaunch = createCliSubprocessLaunchSpec(relaunchArgs);+ const relaunch = createUpdatedCliSubprocessLaunchSpec(relaunchArgs);const updateProcess = process as NodeJS.Process & { execve?: UpdateRelaunchExecve };try {if (diff --git a/packages/coding-agent/src/package-manager-cli.ts b/packages/coding-agent/src/package-manager-cli.tsindex 5d0a8eddaf..d85251aba9 100644--- a/packages/coding-agent/src/package-manager-cli.ts+++ b/packages/coding-agent/src/package-manager-cli.ts@@ -28,6 +28,7 @@ import {launchDaemonUpdateRestartCoordinator,waitForActiveDaemonUpdateRestartCoordinator,} from "./cli/daemon-update-restart.js";+import { getNativeUpdatePlan } from "./cli/native-update.js";import {APP_NAME,CONFIG_DIR_NAME,@@ -36,6 +37,7 @@ import {getLegacyDaemonUpdateRestartManifestPath,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,+ isBunBinary,PACKAGE_NAME,SELF_UPDATE_INTERACTIVE_CHILD_ENV,SELF_UPDATE_NOT_ATTEMPTED_EXIT_CODE,@@ -86,6 +88,7 @@ interface PackageCommandOptions {updateTarget?: UpdateTarget;local: boolean;force: boolean;+ rollback: boolean;help: boolean;daemonSocketPath?: string;restartCoordinator: boolean;@@ -166,6 +169,7 @@ Options:--extensions Update installed packages only--extension <source> Update one package only--force Reinstall ${APP_NAME} even if the current version is latest+ --rollback Restore the previous compiled release--daemon-socket <path> Restart the daemon listening on this exact socketCommands:@@ -199,6 +203,7 @@ function parsePackageCommand(args: string[]): PackageCommandOptions | undefinedlet local = false;let force = false;+ let rollback = false;let help = false;let invalidOption: string | undefined;let invalidArgument: string | undefined;@@ -255,6 +260,13 @@ function parsePackageCommand(args: string[]): PackageCommandOptions | undefined}continue;}+ if (arg === "--rollback") {+ if (command === "update") {+ rollback = true;+ selfFlag = true;+ } else invalidOption = invalidOption ?? arg;+ continue;+ }if (arg === "--daemon-socket") {if (command !== "update") {@@ -365,12 +377,15 @@ function parsePackageCommand(args: string[]): PackageCommandOptions | undefined}}+ if (rollback && (extensionsFlag || extensionFlagSource || (source && !isSelfUpdateSource(source))))+ conflictingOptions = "--rollback only applies to Prime Agent itself";return {command,source,updateTarget,local,force,+ rollback,help,daemonSocketPath,restartCoordinator,@@ -431,6 +446,7 @@ interface SelfUpdatePlan {packageName: string;shouldRun: boolean;targetVersion?: string;+ command?: SelfUpdateCommand;}function setSelfUpdateNoChangeExitCode(): void {@@ -438,7 +454,13 @@ function setSelfUpdateNoChangeExitCode(): void {process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV] === "1" ? SELF_UPDATE_NOT_ATTEMPTED_EXIT_CODE : undefined;}-async function getSelfUpdatePlan(force: boolean): Promise<SelfUpdatePlan> {+async function getSelfUpdatePlan(force: boolean, rollback = false): Promise<SelfUpdatePlan> {+ if (isBunBinary) {+ const plan = await getNativeUpdatePlan({ force, rollback });+ if (!plan.command) console.log(chalk.green(`${APP_NAME} is already up to date (v${plan.targetVersion})`));+ return { installSpec: PACKAGE_NAME, packageName: PACKAGE_NAME, shouldRun: !!plan.command, ...plan };+ }+ if (rollback) throw new Error("Rollback is only available for managed compiled installations.");try {const latestRelease = await getLatestPiRelease(VERSION);const packageName = latestRelease?.packageName ?? PACKAGE_NAME;@@ -1565,17 +1587,19 @@ export async function handlePackageCommand(args: string[]): Promise<boolean> {}}if (updateTargetIncludesSelf(target)) {- const selfUpdatePlan = await getSelfUpdatePlan(options.force);+ const selfUpdatePlan = await getSelfUpdatePlan(options.force, options.rollback);if (!selfUpdatePlan.shouldRun) {setSelfUpdateNoChangeExitCode();return true;}- const selfUpdateCommand = getSelfUpdateCommand(- PACKAGE_NAME,- selfUpdateNpmCommand,- selfUpdatePlan.installSpec,- selfUpdatePlan.packageName,- );+ const selfUpdateCommand =+ selfUpdatePlan.command ??+ getSelfUpdateCommand(+ PACKAGE_NAME,+ selfUpdateNpmCommand,+ selfUpdatePlan.installSpec,+ selfUpdatePlan.packageName,+ );if (!selfUpdateCommand) {printSelfUpdateUnavailable(selfUpdateNpmCommand,diff --git a/packages/coding-agent/src/utils/native-installation.ts b/packages/coding-agent/src/utils/native-installation.tsindex 49ab91c279..bffe3e352b 100644--- a/packages/coding-agent/src/utils/native-installation.ts+++ b/packages/coding-agent/src/utils/native-installation.ts@@ -1,7 +1,20 @@import { lstatSync, readFileSync, readlinkSync, realpathSync } from "node:fs";import { dirname, join, resolve } from "node:path";-export interface NativeInstallation {+export const NATIVE_RELEASE_ASSETS = [+ "prime-agent",+ "package.json",+ "install.sh",+ "prime-agent-runtime/pyproject.toml",+ "prime-agent-runtime/src/rlm/repl.py",+ "theme/prime.json",+ "export-html/template.html",+ "photon_rs_bg.wasm",+ ".archive-sha256",+ ".install-source",+] as const;++interface NativeInstallationTarget {root: string;launcher: string;executable: string;@@ -9,10 +22,13 @@ export interface NativeInstallation {version: string;platform: string;sha256: string;+}++export interface NativeInstallation extends NativeInstallationTarget {baseUrl: string;}-export function readNativeInstallation(root: string, link = "prime-agent"): NativeInstallation | undefined {+function readNativeTarget(root: string, link: string, recoveredTarget?: string): NativeInstallationTarget | undefined {try {root = realpathSync(root);for (const part of [".managed", "bin", "releases"]) {@@ -20,20 +36,14 @@ export function readNativeInstallation(root: string, link = "prime-agent"): Nati}if (readFileSync(join(root, ".managed"), "utf8").trim() !== "prime-agent-native-v1") return undefined;const launcher = join(root, "bin", link);- const target = readlinkSync(launcher);+ const target = recoveredTarget ?? readlinkSync(launcher);const match =/^\.\.\/releases\/(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)-(darwin|linux)-(arm64|x64)-([a-f0-9]{64})(?:\.[A-Za-z0-9]{6})?\/prime-agent$/.exec(target,);if (!match) return undefined;const executable = resolve(dirname(launcher), target);- if (realpathSync(executable) !== executable) return undefined;const releaseDir = dirname(executable);- if (readFileSync(join(releaseDir, ".archive-sha256"), "utf8").trim() !== match[4]) return undefined;- const metadata = JSON.parse(readFileSync(join(releaseDir, "package.json"), "utf8")) as { version?: unknown };- if (metadata.version !== match[1]) return undefined;- const baseUrl = readFileSync(join(releaseDir, ".install-source"), "utf8").trim();- if (!["https:", "http:"].includes(new URL(baseUrl).protocol)) return undefined;return {root,launcher,@@ -42,18 +52,70 @@ export function readNativeInstallation(root: string, link = "prime-agent"): Nativersion: match[1],platform: `${match[2]}-${match[3]}`,sha256: match[4],- baseUrl,};} catch {return undefined;}}+export function readNativeInstallation(root: string, link = "prime-agent"): NativeInstallation | undefined {+ return validateNativeInstallation(readNativeTarget(root, link));+}++function validateNativeInstallation(target: NativeInstallationTarget | undefined): NativeInstallation | undefined {+ try {+ if (!target) return undefined;+ const { executable, releaseDir } = target;+ if (realpathSync(executable) !== executable) return undefined;+ for (const asset of NATIVE_RELEASE_ASSETS) {+ const assetPath = join(releaseDir, asset);+ if (!lstatSync(assetPath).isFile() || lstatSync(assetPath).isSymbolicLink()) return undefined;+ if (realpathSync(dirname(assetPath)) !== dirname(assetPath)) return undefined;+ }+ if (readFileSync(join(releaseDir, ".archive-sha256"), "utf8").trim() !== target.sha256) return undefined;+ const metadata = JSON.parse(readFileSync(join(releaseDir, "package.json"), "utf8")) as { version?: unknown };+ if (metadata.version !== target.version) return undefined;+ const baseUrl = readFileSync(join(releaseDir, ".install-source"), "utf8").trim();+ if (!["https:", "http:"].includes(new URL(baseUrl).protocol)) return undefined;+ return { ...target, baseUrl };+ } catch {+ return undefined;+ }+}++export function readNativeRollbackInstallation(root: string): NativeInstallation | undefined {+ const statePath = join(root, ".activation-state");+ const state = lstatSync(statePath, { throwIfNoEntry: false });+ if (!state) return readNativeInstallation(root, "previous");+ const invalid = () =>+ new Error(+ `Invalid or ambiguous activation recovery state at ${statePath}. Restore the recorded links before retrying.`,+ );+ if (!state.isFile() || state.isSymbolicLink()) throw invalid();+ const recorded = /^([^\n]+)\n([^\n]*)\n$/.exec(readFileSync(statePath, "utf8"));+ if (!recorded) throw invalid();+ const target = validateNativeInstallation(readNativeTarget(root, "prime-agent", recorded[1]));+ const previous = recorded[2]+ ? validateNativeInstallation(readNativeTarget(root, "previous", recorded[2]))+ : undefined;+ if (!target || (recorded[2] && !previous)) throw invalid();+ const current = readNativeTarget(root, "prime-agent");+ // Planning predicts the locked installer's recovery without modifying either launcher.+ if (current?.executable === target.executable) return previous;+ if (previous && current?.executable === previous.executable) return readNativeInstallation(root, "previous");+ throw invalid();+}+export function getNativeInstallation(executable = process.execPath): NativeInstallation | undefined {+ const target = getNativeInstallationTarget(executable);+ return target ? readNativeInstallation(target.root) : undefined;+}++export function getNativeInstallationTarget(executable = process.execPath): NativeInstallationTarget | undefined {try {const actual = realpathSync(executable);const root = resolve(dirname(actual), "../..");- const installation = readNativeInstallation(root);+ const installation = readNativeTarget(root, "prime-agent");// A running process may belong to the previous release after activation.return installation && dirname(dirname(actual)) === join(root, "releases") ? installation : undefined;} catch {diff --git a/packages/coding-agent/src/utils/version-check.ts b/packages/coding-agent/src/utils/version-check.tsindex 79ec3f824e..d4bf92f842 100644--- a/packages/coding-agent/src/utils/version-check.ts+++ b/packages/coding-agent/src/utils/version-check.ts@@ -9,6 +9,13 @@ export interface LatestPiRelease {version: string;packageName?: string;installSpec?: string;+ binaries?: NativeReleaseArtifact[];+}++interface NativeReleaseArtifact {+ platform: string;+ file: string;+ sha256: string;}interface ParsedVersion {@@ -113,11 +120,11 @@ function resolveReleaseUrl(baseUrl: string, pathOrUrl: string): string | undefinexport async function getLatestPiRelease(currentVersion: string,- options: { timeoutMs?: number } = {},+ options: { timeoutMs?: number; baseUrl?: string } = {},): Promise<LatestPiRelease | undefined> {if (process.env.PI_SKIP_VERSION_CHECK || process.env.PI_OFFLINE) return undefined;- const baseUrl = getPrimeAgentDownloadBaseUrl();+ const baseUrl = options.baseUrl?.replace(/\/+$/, "") ?? getPrimeAgentDownloadBaseUrl();const response = await fetch(`${baseUrl}/${getReleaseManifestPath(currentVersion)}`, {headers: {"User-Agent": getPiUserAgent(currentVersion),@@ -132,6 +139,7 @@ export async function getLatestPiRelease(packageName?: unknown;tarball?: unknown;version?: unknown;+ binaries?: unknown;};if (typeof data.version !== "string" || !data.version.trim()) {return undefined;@@ -150,6 +158,28 @@ export async function getLatestPiRelease(if (installSpec) {release.installSpec = installSpec;}+ if (Array.isArray(data.binaries)) {+ // Invalid optional native metadata must not discard a valid npm release.+ // Publish the list only after every entry passes validation.+ const binaries: NativeReleaseArtifact[] = [];+ const platforms = new Set<string>();+ for (const candidate of data.binaries) {+ if (!candidate || typeof candidate !== "object") return release;+ const artifact = candidate as Partial<NativeReleaseArtifact>;+ if (+ typeof artifact.platform !== "string" ||+ !/^(darwin|linux)-(arm64|x64)$/.test(artifact.platform) ||+ platforms.has(artifact.platform) ||+ artifact.file !== `prime-agent-${release.version}-${artifact.platform}.tar.gz` ||+ typeof artifact.sha256 !== "string" ||+ !/^[a-f0-9]{64}$/.test(artifact.sha256)+ )+ return release;+ platforms.add(artifact.platform);+ binaries.push({ platform: artifact.platform, file: artifact.file, sha256: artifact.sha256 });+ }+ release.binaries = binaries;+ }return release;}diff --git a/packages/coding-agent/test/config-native-update.test.ts b/packages/coding-agent/test/config-native-update.test.tsnew file mode 100644index 0000000000..b37925e739--- /dev/null+++ b/packages/coding-agent/test/config-native-update.test.ts@@ -0,0 +1,77 @@+import { execFileSync } from "node:child_process";+import { copyFileSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { describe, expect, it } from "vitest";+import { NATIVE_RELEASE_ASSETS } from "../src/utils/native-installation.js";++describe("compiled update instructions", () => {+ it.each(["healthy", "missing metadata", "missing asset", "unmanaged"])(+ "uses installer ownership for a %s compiled installation",+ (state) => {+ const root = mkdtempSync(join(tmpdir(), "native-update-instruction-"));+ try {+ const virtual = join(root, "$bunfs");+ mkdirSync(join(virtual, "utils"), { recursive: true });+ for (const file of [+ "config.ts",+ "utils/child-process.ts",+ "utils/daemon-socket-path.ts",+ "utils/native-installation.ts",+ ])+ copyFileSync(resolve(__dirname, "../src", file), join(virtual, file));+ const managed = join(root, "managed");+ mkdirSync(join(managed, "bin"), { recursive: true });+ writeFileSync(join(managed, ".managed"), "prime-agent-native-v1\n");+ let executable = "";+ for (const [version, link] of [+ ["1.0.0", "previous"],+ ["1.0.1", "prime-agent"],+ ]) {+ const digest = "a".repeat(64);+ const name = `${version}-linux-x64-${digest}`;+ const release = join(managed, "releases", name);+ for (const asset of NATIVE_RELEASE_ASSETS) {+ mkdirSync(dirname(join(release, asset)), { recursive: true });+ writeFileSync(join(release, asset), "fixture\n");+ }+ writeFileSync(join(release, "package.json"), JSON.stringify({ version }));+ writeFileSync(join(release, ".archive-sha256"), digest);+ writeFileSync(join(release, ".install-source"), "https://example.invalid");+ symlinkSync(`../releases/${name}/prime-agent`, join(managed, "bin", link));+ if (link === "prime-agent") {+ executable = join(release, "prime-agent");+ if (state === "missing metadata") rmSync(join(release, ".archive-sha256"));+ if (state === "missing asset") rmSync(join(release, "theme/prime.json"));+ }+ }+ if (state === "unmanaged") rmSync(join(managed, ".managed"));+ const entrypoint = join(root, "instruction.mts");+ writeFileSync(+ entrypoint,+ `import { getUpdateInstruction, isBunBinary } from './$bunfs/config.js';+if (!isBunBinary) throw new Error('fixture must use compiled path detection');+Object.defineProperty(process, 'execPath', { value: process.argv[2] });+console.log(getUpdateInstruction('prime-agent'));+`,+ );+ const output = execFileSync(+ process.execPath,+ ["--import", resolve(__dirname, "../../../node_modules/tsx/dist/loader.mjs"), entrypoint, executable],+ {+ encoding: "utf8",+ timeout: 10000,+ env: { ...process.env, PI_PACKAGE_DIR: resolve(__dirname, "..") },+ },+ );+ expect(output.trim()).toBe(+ state === "unmanaged"+ ? "Download from: https://github.com/PrimeIntellect-ai/prime-agent/releases/latest"+ : "Run: prime-agent update",+ );+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ },+ );+});diff --git a/packages/coding-agent/test/interactive-update-relaunch.test.ts b/packages/coding-agent/test/interactive-update-relaunch.test.tsindex b13e6b216d..49871bfb8a 100644--- a/packages/coding-agent/test/interactive-update-relaunch.test.ts+++ b/packages/coding-agent/test/interactive-update-relaunch.test.ts@@ -1,10 +1,23 @@import type * as ChildProcessModule from "child_process";import { describe, expect, it, vi } from "vitest";import type * as DaemonUpdateRestartModule from "../src/cli/daemon-update-restart.js";+import type * as ConfigModule from "../src/config.js";const updateMocks = vi.hoisted(() => ({spawnSync: vi.fn(),launchCoordinator: vi.fn(),+ binary: false,+}));++vi.mock("../src/config.js", async (importOriginal) => ({+ ...(await importOriginal<typeof ConfigModule>()),+ get isBunBinary() {+ return updateMocks.binary;+ },+}));++vi.mock("../src/utils/native-installation.js", () => ({+ getNativeInstallation: () => (updateMocks.binary ? { launcher: "/tmp/managed/bin/prime-agent" } : undefined),}));vi.mock("child_process", async (importOriginal) => ({@@ -167,9 +180,10 @@ describe("tryExecUpdateRelaunch", () => {});describe("interactive self-update relaunch", () => {- it.skipIf(process.platform === "win32")(- "tears down and replaces the TUI process without waiting for a child TUI to quit",- async () => {+ it.skipIf(process.platform === "win32").each([false, true])(+ "tears down and relaunches the TUI with the activated application (compiled: %s)",+ async (binary) => {+ updateMocks.binary = binary;const events: string[] = [];updateMocks.spawnSync.mockReset();updateMocks.spawnSync.mockImplementation(() => {@@ -234,6 +248,7 @@ describe("interactive self-update relaunch", () => {try {await handleUpdateCommand.call(receiver, "");} finally {+ updateMocks.binary = false;updateProcess.execve = originalExecve;if (originalNodeVersion) {Object.defineProperty(process.versions, "node", originalNodeVersion);@@ -252,6 +267,13 @@ describe("interactive self-update relaunch", () => {"execve",]);expect(updateMocks.spawnSync).toHaveBeenCalledTimes(1);+ const updateArgs = updateMocks.spawnSync.mock.calls[0]?.[1];+ expect(updateArgs).toEqual(+ binary+ ? ["update", "--daemon-socket", "/tmp/update.sock"]+ : [...process.execArgv, process.argv[1], "update", "--daemon-socket", "/tmp/update.sock"],+ );+ expect(execve.mock.calls[0]?.[0]).toBe(binary ? "/tmp/managed/bin/prime-agent" : process.execPath);expect(execve.mock.calls[0]?.[1]).toEqual(expect.arrayContaining(["--resume", "/tmp/session.jsonl"]));},);diff --git a/packages/coding-agent/test/native-installer.test.ts b/packages/coding-agent/test/native-installer.test.tsindex 92bb421047..b817b39a4f 100644--- a/packages/coding-agent/test/native-installer.test.ts+++ b/packages/coding-agent/test/native-installer.test.ts@@ -5,6 +5,7 @@ import {lstatSync,mkdirSync,mkdtempSync,+ readdirSync,readFileSync,readlinkSync,realpathSync,@@ -16,7 +17,10 @@ import { createServer as createHttpServer, type RequestListener } from "node:httimport { createServer as createHttpsServer } from "node:https";import { tmpdir } from "node:os";import { basename, dirname, join, resolve } from "node:path";-import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";+import { Agent, getGlobalDispatcher, setGlobalDispatcher } from "undici";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { getNativeUpdatePlan } from "../src/cli/native-update.js";+import { DaemonClient } from "../src/modes/daemon/daemon-client.js";const installer = resolve(__dirname, "../../../install.sh");const assets = [@@ -46,14 +50,21 @@ let root: string;let home: string;let base: string;let certificate: string;+const originalDispatcher = getGlobalDispatcher();+let fixtureDispatcher: Agent;-function publish(version: string, options: { broken?: boolean; missing?: boolean; link?: boolean } = {}) {+function publish(+ version: string,+ options: { broken?: boolean; missing?: boolean; link?: boolean; installer?: string } = {},+) {const source = mkdtempSync(join(root, "archive-"));for (const asset of assets) {if (options.missing && asset === assets[2]) continue;mkdirSync(dirname(join(source, asset)), { recursive: true });writeFileSync(join(source, asset), "fixture\n");}+ writeFileSync(join(source, "package.json"), JSON.stringify({ version }));+ writeFileSync(join(source, "install.sh"), options.installer ?? readFileSync(installer));writeFileSync(join(source, "prime-agent"),options.broken ? "#!/bin/sh\nexit 1\n" : `#!/bin/sh\nprintf '%s\\n' '${version}'\n`,@@ -67,6 +78,15 @@ function publish(version: string, options: { broken?: boolean; missing?: booleanconst digest = createHash("sha256").update(bytes).digest("hex");feed.set(`/releases/v${version}/${filename}`, bytes);feed.set(`/releases/v${version}/SHA256SUMS`, Buffer.from(`${digest} ${filename}\n`));+ feed.set(+ version.includes("-beta") ? "/beta.json" : "/latest.json",+ Buffer.from(+ JSON.stringify({+ version,+ binaries: [{ platform, file: filename, sha256: digest }],+ }),+ ),+ );return filename;}@@ -79,10 +99,16 @@ function publishNodePackage(version: string) {}async function install(version: string, extra: NodeJS.ProcessEnv = {}, entrypoint = installer) {- const child = spawn("sh", [entrypoint, version], {+ return run("sh", [entrypoint, version], extra);+}++async function run(executable: string, args: string[], extra: NodeJS.ProcessEnv = {}) {+ const child = spawn(executable, args, {+ cwd: home,env: {...process.env,HOME: home,+ TMPDIR: root,PATH: "/usr/bin:/bin",XDG_DATA_HOME: join(home, "data"),SHELL: "/bin/sh",@@ -91,7 +117,10 @@ async function install(version: string, extra: NodeJS.ProcessEnv = {}, entrypoinPRIME_AGENT_INSTALLER_PLAIN: "1",PRIME_AGENT_BOOTSTRAP_KERNEL_ON_INSTALL: "0",PRIME_AGENT_DOWNLOAD_BASE_URL: base,+ PRIME_AGENT_CODING_AGENT_DIR: join(home, "agent"),+ DO_NOT_TRACK: "1",CURL_CA_BUNDLE: certificate,+ NODE_EXTRA_CA_CERTS: certificate,...extra,},stdio: ["ignore", "pipe", "pipe"],@@ -113,9 +142,43 @@ function command() {return join(home, "data/prime-agent/bin/prime-agent");}+function installationRoot() {+ return join(home, "data/prime-agent");+}++function releaseDirectories() {+ return readdirSync(join(installationRoot(), "releases"), { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .map((entry) => join(installationRoot(), "releases", entry.name));+}++function createLsofShim() {+ const shim = mkdtempSync(join(root, "lsof-"));+ writeFileSync(+ join(shim, "lsof"),+ '#!/bin/sh\nfor candidate in "$@"; do executable="$candidate"; done\nif [ -n "$LIVE_EXECUTABLE" ] && [ "$executable" = "$LIVE_EXECUTABLE" ]; then printf "p123\\n"; exit 0; fi\nif [ -n "$UNCERTAIN_EXECUTABLE" ] && [ "$executable" = "$UNCERTAIN_EXECUTABLE" ]; then printf "cannot inspect\\n" >&2; exit 2; fi\nexit 1\n',+ { mode: 0o755 },+ );+ return shim;+}++function daemonSocket() {+ return join(root, `prime-agent-${process.getuid?.() ?? "user"}`, "daemon.sock");+}++async function daemonExecutable() {+ const client = new DaemonClient(daemonSocket());+ try {+ await client.connect();+ return (await client.waitForHello()).runtime?.executablePath;+ } finally {+ client.close();+ }+}+describe.skipIf(process.platform === "win32")("managed compiled installer", () => {beforeAll(async () => {- root = mkdtempSync(join(tmpdir(), "native-installer-"));+ root = realpathSync(mkdtempSync(join(process.platform === "darwin" ? "/tmp" : tmpdir(), "native-installer-")));const key = join(root, "localhost.key");certificate = join(root, "localhost.crt");execFileSync(@@ -143,6 +206,8 @@ describe.skipIf(process.platform === "win32")("managed compiled installer", () =insecureRequestCount += 1;serveFeed(request, response);});+ fixtureDispatcher = new Agent({ connect: { ca: readFileSync(certificate) } });+ setGlobalDispatcher(fixtureDispatcher);await new Promise<void>((done) => insecureServer.listen(0, "127.0.0.1", done));const insecureAddress = insecureServer.address();if (!insecureAddress || typeof insecureAddress === "string") throw new Error("missing insecure server address");@@ -166,8 +231,39 @@ describe.skipIf(process.platform === "win32")("managed compiled installer", () =beforeArchiveResponse = undefined;redirectToHttp = false;insecureRequestCount = 0;+ vi.stubEnv("PI_OFFLINE", "");+ vi.stubEnv("PI_SKIP_VERSION_CHECK", "");+ vi.stubEnv("PRIME_AGENT_DOWNLOAD_BASE_URL", "");+ });+ afterEach(async () => {+ vi.unstubAllEnvs();+ if (!existsSync(daemonSocket())) return;+ const client = new DaemonClient(daemonSocket());+ try {+ await client.connect();+ const hello = await client.waitForHello();+ await client.request({ type: "shutdown", force: true });+ if (hello.supervisorPid)+ await expect+ .poll(+ () => {+ try {+ process.kill(hello.supervisorPid!, 0);+ return false;+ } catch {+ return true;+ }+ },+ { timeout: 10000 },+ )+ .toBe(true);+ } finally {+ client.close();+ }});afterAll(async () => {+ setGlobalDispatcher(originalDispatcher);+ await fixtureDispatcher.close();await new Promise<void>((done) => server.close(() => done()));await new Promise<void>((done) => insecureServer.close(() => done()));rmSync(root, { recursive: true, force: true });@@ -281,6 +377,261 @@ download_prime_agent_package "$1" "$prime_agent_base_url/releases/v$1/$prime_age},);+ it("plans verified updates and restores the previous release offline", async () => {+ publish("1.0.0");+ expect((await install("1.0.0")).code).toBe(0);+ const executable = realpathSync(command());+ const plan = (force = false, rollback = false) => getNativeUpdatePlan({ force, rollback, executable });+ expect((await plan()).command).toBeUndefined();+ expect((await plan(true)).command).toBeDefined();+ await expect(plan(false, true)).rejects.toThrow("No valid previous");+ publish("1.0.1");+ const update = await plan();+ expect(update.targetVersion).toBe("1.0.1");+ expect(update.command?.args).toContain(`PRIME_AGENT_EXPECTED_CURRENT=${readlinkSync(command())}`);+ expect(update.command?.args).toContainEqual(expect.stringMatching(/^PRIME_AGENT_EXPECTED_SHA256=[a-f0-9]{64}$/));+ const result = await install("1.0.1");+ expect(result.code, result.output).toBe(0);+ const current = readlinkSync(command());+ feed.clear();+ vi.stubEnv("PI_OFFLINE", "1");+ const rollback = await plan(false, true);+ expect(rollback.targetVersion).toBe("1.0.0");+ expect(rollback.command?.args.at(-1)).toBe("--rollback");+ const restored = await install("--rollback");+ expect(restored.code, restored.output).toBe(0);+ expect(execFileSync(command(), ["--version"], { encoding: "utf8" })).toBe("1.0.0\n");+ expect(readlinkSync(join(dirname(command()), "previous"))).toBe(current);+ });++ it.each([+ { damage: "missing asset", file: "theme/prime.json" },+ { damage: "missing installer", file: "install.sh" },+ { damage: "missing executable", file: "prime-agent" },+ { damage: "missing metadata", file: "package.json" },+ { damage: "broken executable", file: "prime-agent" },+ ])("repairs a $damage while preserving the healthy previous release", async ({ damage, file }) => {+ for (const rollback of [true, false]) {+ publish("1.0.0");+ expect((await install("1.0.0")).code).toBe(0);+ const retained = realpathSync(command());+ publish("1.0.1");+ expect((await install("1.0.1")).code).toBe(0);+ const current = realpathSync(command());+ const previous = readlinkSync(join(dirname(command()), "previous"));+ if (damage === "broken executable") writeFileSync(current, "#!/bin/sh\nexit 1\n");+ else rmSync(join(dirname(current), file));+ const plan = await getNativeUpdatePlan({+ force: damage === "broken executable",+ rollback,+ executable: retained,+ });+ expect(plan.command?.args).toContain(`PRIME_AGENT_EXPECTED_CURRENT=${readlinkSync(command())}`);+ if (rollback) feed.clear();+ const result = await run(plan.command!.command, plan.command!.args);+ expect(result.code, result.output).toBe(0);+ expect(execFileSync(command(), ["--version"], { encoding: "utf8" })).toBe(rollback ? "1.0.0\n" : "1.0.1\n");+ expect(readlinkSync(join(dirname(command()), "previous"))).toBe(previous);+ expect(existsSync(join(installationRoot(), ".activation-state"))).toBe(false);+ rmSync(installationRoot(), { recursive: true });+ }+ });++ it.each(["no rollback handler", "no damaged-release recovery"])(+ "uses published-installer repair when the retained installer has %s",+ async (capability) => {+ let oldInstaller = readFileSync(installer, "utf8").replace("# prime-agent-native-recovery-v1\n", "");+ if (capability === "no rollback handler")+ oldInstaller = oldInstaller.replace(/\tif \[ "\$\{1:-\}" = --rollback \]; then[\s\S]*?\tfi\n/, "");+ publish("1.0.0", { installer: oldInstaller });+ expect((await install("1.0.0")).code).toBe(0);+ const retained = realpathSync(command());+ publish("1.0.1");+ expect((await install("1.0.1")).code).toBe(0);+ const current = readlinkSync(command());+ const previous = readlinkSync(join(dirname(command()), "previous"));+ rmSync(join(dirname(realpathSync(command())), "install.sh"));+ for (const rollback of [true, false])+ await expect(getNativeUpdatePlan({ force: true, rollback, executable: retained })).rejects.toThrow(+ "https://app.primeintellect.ai/prime-agent/install.sh",+ );+ expect(readlinkSync(command())).toBe(current);+ expect(readlinkSync(join(dirname(command()), "previous"))).toBe(previous);+ const repaired = await install("1.0.1");+ expect(repaired.code, repaired.output).toBe(0);+ expect(readlinkSync(command())).not.toBe(current);+ expect(readlinkSync(join(dirname(command()), "previous"))).toBe(previous);+ },+ );++ it("requires the published installer when neither retained release can supply repair assets", async () => {+ publish("1.0.0");+ expect((await install("1.0.0")).code).toBe(0);+ const executable = realpathSync(command());+ rmSync(join(dirname(executable), "theme/prime.json"));+ for (const rollback of [true, false]) {+ await expect(getNativeUpdatePlan({ force: true, rollback, executable })).rejects.toThrow(+ "published installer",+ );+ }+ });++ it("does not treat an unmanaged current link as a damaged release to repair", async () => {+ publish("1.0.0");+ expect((await install("1.0.0")).code).toBe(0);+ const executable = realpathSync(command());+ rmSync(command());+ symlinkSync(executable, command());+ await expect(getNativeUpdatePlan({ force: true, rollback: false, executable })).rejects.toThrow("not owned");+ expect(readlinkSync(command())).toBe(executable);+ });++ it.each(["HUP", "TERM", "KILL"])("keeps releases recoverable when %s interrupts rollback", async (signal) => {+ publish("1.0.0");+ expect((await install("1.0.0")).code).toBe(0);+ const restored = readlinkSync(command());+ publish("1.0.1");+ expect((await install("1.0.1")).code).toBe(0);+ const replaced = readlinkSync(command());+ const previous = join(dirname(command()), "previous");+ const shim = mkdtempSync(join(root, "interrupt-rollback-"));+ writeFileSync(+ join(shim, "mv"),+ '#!/bin/sh\n/bin/mv "$@" || exit $?\nfor destination in "$@"; do :; done\ncase "$destination" in "$INTERRUPT_BIN/prime-agent"|"$INTERRUPT_BIN/previous") if [ ! -f "$0.sent" ]; then touch "$0.sent"; kill -"$INTERRUPT_SIGNAL" "$PPID"; fi ;; esac\n',+ { mode: 0o755 },+ );+ const result = await install("--rollback", {+ PATH: `${shim}:/usr/bin:/bin`,+ INTERRUPT_BIN: realpathSync(dirname(command())),+ INTERRUPT_SIGNAL: signal,+ });+ expect(result.code, result.output).not.toBe(0);+ expect(readlinkSync(command())).toBe(restored);+ expect(execFileSync(command(), ["--version"], { encoding: "utf8" })).toBe("1.0.0\n");+ if (signal === "KILL") {+ expect(readlinkSync(previous)).toBe(restored);+ expect(existsSync(resolve(dirname(command()), replaced))).toBe(true);+ expect((await install("--rollback")).code).not.toBe(0);+ rmSync(join(home, "data/prime-agent/.install-lock"), { recursive: true });+ } else {+ expect(readlinkSync(previous)).toBe(replaced);+ expect(existsSync(join(home, "data/prime-agent/.install-lock"))).toBe(false);+ }+ feed.clear();+ const plan = await getNativeUpdatePlan({ force: false, rollback: true, executable: realpathSync(command()) });+ expect(plan.targetVersion).toBe("1.0.1");+ const recovery = await run(plan.command!.command, plan.command!.args);+ expect(recovery.code, recovery.output).toBe(0);+ expect(readlinkSync(command())).toBe(replaced);+ });++ it.each(["missing", "checksum", "duplicate", "path"])(+ "rejects a %s compiled manifest without changing the installation",+ async (failure) => {+ publish("1.0.0");+ expect((await install("1.0.0")).code).toBe(0);+ const current = readlinkSync(command());+ const artifact = { platform, file: `prime-agent-1.0.1-${platform}.tar.gz`, sha256: "a".repeat(64) };+ if (failure === "checksum") artifact.sha256 = "bad";+ if (failure === "path") artifact.file = "../outside.tar.gz";+ feed.set(+ "/latest.json",+ Buffer.from(+ JSON.stringify({+ version: "1.0.1",+ binaries: failure === "missing" ? [] : failure === "duplicate" ? [artifact, artifact] : [artifact],+ }),+ ),+ );+ await expect(+ getNativeUpdatePlan({ force: false, rollback: false, executable: realpathSync(command()) }),+ ).rejects.toThrow();+ expect(readlinkSync(command())).toBe(current);+ },+ );++ it("keeps beta updates on the beta channel", async () => {+ publish("1.0.0-beta.1");+ expect((await install("1.0.0-beta.1")).code).toBe(0);+ publish("1.0.0-beta.2");+ publish("9.0.0");+ const plan = await getNativeUpdatePlan({ force: false, rollback: false, executable: realpathSync(command()) });+ expect(plan.targetVersion).toBe("1.0.0-beta.2");+ });++ it.each(["stale", "checksum", "rollback"])(+ "keeps the active release when %s update validation fails",+ async (failure) => {+ publish("1.0.0");+ expect((await install("1.0.0")).code).toBe(0);+ const current = readlinkSync(command());+ publish("1.0.1");+ const result = await install(+ failure === "rollback" ? "--rollback" : "1.0.1",+ failure === "stale"+ ? { PRIME_AGENT_EXPECTED_CURRENT: "an older release" }+ : { PRIME_AGENT_EXPECTED_SHA256: "0".repeat(64) },+ );+ expect(result.code, result.output).not.toBe(0);+ expect(readlinkSync(command())).toBe(current);+ },+ );++ it("refuses self-update of an unmanaged executable", async () => {+ await expect(getNativeUpdatePlan({ force: true, rollback: false, executable: process.execPath })).rejects.toThrow(+ "not owned",+ );+ });++ it.each([+ "changed previous",+ "missing asset",+ "checksum marker",+ "package version",+ "executable version",+ "source symlink",+ "asset parent symlink",+ ])("preserves the active release when rollback finds a %s", async (failure) => {+ publish("1.0.0");+ expect((await install("1.0.0")).code).toBe(0);+ const previousDir = dirname(realpathSync(command()));+ publish("1.0.1");+ expect((await install("1.0.1")).code).toBe(0);+ const current = readlinkSync(command());+ const previous = readlinkSync(join(dirname(command()), "previous"));+ if (failure === "missing asset") rmSync(join(previousDir, "theme/prime.json"));+ if (failure === "checksum marker") writeFileSync(join(previousDir, ".archive-sha256"), `${"b".repeat(64)}\n`);+ if (failure === "package version") writeFileSync(join(previousDir, "package.json"), '{"version":"9.9.9"}\n');+ if (failure === "executable version")+ writeFileSync(join(previousDir, "prime-agent"), "#!/bin/sh\nprintf '9.9.9\\n'\n", { mode: 0o755 });+ if (failure === "source symlink") {+ const source = join(root, "outside-install-source");+ writeFileSync(source, "https://example.com\n");+ rmSync(join(previousDir, ".install-source"));+ symlinkSync(source, join(previousDir, ".install-source"));+ }+ if (failure === "asset parent symlink") {+ const theme = join(root, "outside-theme");+ mkdirSync(theme);+ writeFileSync(join(theme, "prime.json"), "fixture\n");+ rmSync(join(previousDir, "theme"), { recursive: true });+ symlinkSync(theme, join(previousDir, "theme"), "dir");+ }+ if (failure !== "changed previous") {+ await expect(+ getNativeUpdatePlan({ force: false, rollback: true, executable: realpathSync(command()) }),+ ).rejects.toThrow();+ }+ const result = await install(+ "--rollback",+ failure === "changed previous" ? { PRIME_AGENT_EXPECTED_PREVIOUS: "an older release" } : {},+ );+ expect(result.code, result.output).not.toBe(0);+ expect(readlinkSync(command())).toBe(current);+ expect(readlinkSync(join(dirname(command()), "previous"))).toBe(previous);+ expect(execFileSync(command(), ["--version"], { encoding: "utf8" })).toBe("1.0.1\n");+ });+it.each(["1.0.0", "1.0.1"])("retries the Node fallback when reinstalling or upgrading to %s", async (version) => {publish("1.0.0", { broken: true });publish("1.0.1", { broken: true });@@ -463,10 +814,10 @@ if [ "$destination" = "$INTERRUPT_COMMAND" ] && [ "$INTERRUPT_POINT" = after ];expect(readlinkSync(command())).not.toBe(previous);expect(readFileSync(join(dirname(realpathSync(command())), "theme/prime.json"), "utf8")).toBe("fixture\n");expect(existsSync(join(oldRelease, "theme/prime.json"))).toBe(false);- expect(readlinkSync(join(dirname(command()), "previous"))).toBe(previous);+ expect(existsSync(join(dirname(command()), "previous"))).toBe(false);});- it.each(["HUP", "TERM", "KILL"])("retains a rollback target after %s interrupts activation", async (signal) => {+ it.each(["HUP", "TERM"])("retains a rollback target after %s interrupts activation", async (signal) => {for (const version of ["1.0.0", "1.0.1", "1.0.2"]) publish(version);expect((await install("1.0.0")).code).toBe(0);const retained = readlinkSync(command());@@ -484,10 +835,182 @@ if [ "$destination" = "$INTERRUPT_COMMAND" ] && [ "$INTERRUPT_POINT" = after ];INTERRUPT_SIGNAL: signal,});expect(result.code, result.output).not.toBe(0);- expect(readlinkSync(join(dirname(command()), "previous"))).toBe(signal === "KILL" ? retained : replaced);+ expect(readlinkSync(join(dirname(command()), "previous"))).toBe(replaced);expect(readlinkSync(command())).not.toBe(retained);expect(execFileSync(command(), ["--version"], { encoding: "utf8" })).toBe("1.0.2\n");- expect(existsSync(join(home, "data/prime-agent/.install-lock"))).toBe(signal === "KILL");+ expect(existsSync(join(home, "data/prime-agent/.install-lock"))).toBe(false);+ expect(existsSync(join(installationRoot(), ".activation-state"))).toBe(false);+ });++ it.each([+ ["first update", ["1.0.0"], "1.0.0"],+ ["subsequent update", ["1.0.0", "1.0.1"], "1.0.1"],+ ] as const)(+ "recovers the exact replaced release after SIGKILL during a %s",+ async (_label, installed, replacedVersion) => {+ for (const version of ["1.0.0", "1.0.1", "1.0.2"]) publish(version);+ for (const version of installed) expect((await install(version)).code).toBe(0);+ const shim = mkdtempSync(join(root, "kill-activation-"));+ writeFileSync(+ join(shim, "mv"),+ '#!/bin/sh\n/bin/mv "$@" || exit $?\nfor destination in "$@"; do :; done\nif [ "$destination" = "$INTERRUPT_BIN/prime-agent" ]; then kill -KILL "$PPID"; fi\n',+ { mode: 0o755 },+ );+ const killed = await install("1.0.2", {+ PATH: `${shim}:/usr/bin:/bin`,+ INTERRUPT_BIN: realpathSync(dirname(command())),+ });+ expect(killed.code, killed.output).not.toBe(0);+ expect(execFileSync(command(), ["--version"], { encoding: "utf8" })).toBe("1.0.2\n");+ expect(existsSync(join(installationRoot(), ".activation-state"))).toBe(true);+ expect(readdirSync(installationRoot()).some((entry) => entry.startsWith(".install."))).toBe(true);+ rmSync(join(installationRoot(), ".install-lock"), { recursive: true });+ feed.clear();+ const plan = await getNativeUpdatePlan({ force: false, rollback: true, executable: realpathSync(command()) });+ expect(plan.targetVersion).toBe(replacedVersion);+ const rollback = await run(plan.command!.command, plan.command!.args);+ expect(rollback.code, rollback.output).toBe(0);+ expect(execFileSync(command(), ["--version"], { encoding: "utf8" })).toBe(`${replacedVersion}\n`);+ expect(existsSync(join(installationRoot(), ".activation-state"))).toBe(false);+ expect(readdirSync(installationRoot()).some((entry) => entry.startsWith(".install."))).toBe(false);+ },+ );++ it.each(["ln", "mv", "rmdir", "rm"])("keeps recovery retryable when %s fails during recovery", async (operation) => {+ publish("1.0.0");+ publish("1.0.1");+ expect((await install("1.0.0")).code).toBe(0);+ const previous = readlinkSync(command());+ expect((await install("1.0.1")).code).toBe(0);+ const current = readlinkSync(command());+ rmSync(join(dirname(command()), "previous"));+ const state = join(installationRoot(), ".activation-state");+ writeFileSync(state, `${current}\n${previous}\n`);+ const shim = mkdtempSync(join(root, "fail-recovery-"));+ writeFileSync(+ join(shim, operation),+ `#!/bin/sh+for destination in "$@"; do :; done+case "$destination" in+ */link.??????/link|*/link.??????|"$FAIL_PREVIOUS"|"$FAIL_STATE") exit 73 ;;+esac+exec /bin/${operation} "$@"+`,+ { mode: 0o755 },+ );+ const failed = await install("--rollback", {+ PATH: `${shim}:/usr/bin:/bin`,+ FAIL_PREVIOUS: join(dirname(command()), "previous"),+ FAIL_STATE: state,+ });+ expect(failed.code, failed.output).not.toBe(0);+ expect(readlinkSync(command())).toBe(current);+ if (operation === "rmdir") {+ // The link already changed; exit cleanup can finish the recorded recovery.+ expect(readlinkSync(join(dirname(command()), "previous"))).toBe(previous);+ } else {+ expect(readFileSync(state, "utf8")).toBe(`${current}\n${previous}\n`);+ }+ const retry = await install("--rollback");+ expect(retry.code, retry.output).toBe(0);+ expect(readlinkSync(command())).toBe(previous);+ expect(existsSync(state)).toBe(false);+ });++ it("recovers a completed previous-link rename after SIGKILL", async () => {+ for (const version of ["1.0.0", "1.0.1", "1.0.2"]) publish(version);+ expect((await install("1.0.0")).code).toBe(0);+ expect((await install("1.0.1")).code).toBe(0);+ const shim = mkdtempSync(join(root, "kill-after-previous-"));+ writeFileSync(+ join(shim, "mv"),+ '#!/bin/sh\n/bin/mv "$@" || exit $?\nfor destination in "$@"; do :; done\nif [ "$destination" = "$INTERRUPT_BIN/previous" ]; then kill -KILL "$PPID"; fi\n',+ { mode: 0o755 },+ );+ const killed = await install("1.0.2", {+ PATH: `${shim}:/usr/bin:/bin`,+ INTERRUPT_BIN: realpathSync(dirname(command())),+ });+ expect(killed.code, killed.output).not.toBe(0);+ expect(existsSync(join(installationRoot(), ".activation-state"))).toBe(true);+ rmSync(join(installationRoot(), ".install-lock"), { recursive: true });+ feed.clear();+ const plan = await getNativeUpdatePlan({ force: false, rollback: true, executable: realpathSync(command()) });+ expect(plan.targetVersion).toBe("1.0.1");+ const rollback = await run(plan.command!.command, plan.command!.args);+ expect(rollback.code, rollback.output).toBe(0);+ expect(execFileSync(command(), ["--version"], { encoding: "utf8" })).toBe("1.0.1\n");+ });++ it("refuses ambiguous activation recovery without changing either launcher", async () => {+ for (const version of ["1.0.0", "1.0.1", "1.0.2"]) publish(version);+ const lsof = createLsofShim();+ const environment = { PATH: `${lsof}:/usr/bin:/bin` };+ expect((await install("1.0.0", environment)).code).toBe(0);+ const oldest = readlinkSync(command());+ expect((await install("1.0.1", { ...environment, LIVE_EXECUTABLE: realpathSync(command()) })).code).toBe(0);+ const middle = readlinkSync(command());+ expect(+ (await install("1.0.2", { ...environment, LIVE_EXECUTABLE: resolve(dirname(command()), oldest) })).code,+ ).toBe(0);+ const current = readlinkSync(command());+ const previous = readlinkSync(join(dirname(command()), "previous"));+ writeFileSync(join(installationRoot(), ".activation-state"), `${middle}\n${oldest}\n`);+ await expect(+ getNativeUpdatePlan({ force: false, rollback: true, executable: realpathSync(command()) }),+ ).rejects.toThrow("ambiguous activation recovery");+ const result = await install("--rollback", environment);+ expect(result.code, result.output).not.toBe(0);+ expect(result.output).toContain("activation recovery is ambiguous");+ expect(readlinkSync(command())).toBe(current);+ expect(readlinkSync(join(dirname(command()), "previous"))).toBe(previous);+ expect(readFileSync(join(installationRoot(), ".activation-state"), "utf8")).toBe(`${middle}\n${oldest}\n`);+ });++ it("prunes only inactive managed releases and safe orphan staging directories", async () => {+ for (const version of ["1.0.0", "1.0.1", "1.0.2", "1.0.3"]) publish(version);+ const lsof = createLsofShim();+ const environment = { PATH: `${lsof}:/usr/bin:/bin` };+ expect((await install("1.0.0", environment)).code).toBe(0);+ const liveRelease = dirname(realpathSync(command()));+ const orphan = join(installationRoot(), ".install.A1b2C3");+ mkdirSync(orphan);+ writeFileSync(join(orphan, "partial"), "fixture");+ const uncertainStage = join(installationRoot(), ".install.keep");+ mkdirSync(uncertainStage);+ const outside = join(root, "outside-stage");+ mkdirSync(outside);+ const stagingLink = join(installationRoot(), ".install.Z9z9Z9");+ symlinkSync(outside, stagingLink, "dir");+ expect((await install("1.0.1", environment)).code).toBe(0);+ expect(existsSync(orphan)).toBe(false);+ expect(existsSync(uncertainStage)).toBe(true);+ expect(lstatSync(stagingLink).isSymbolicLink()).toBe(true);+ const uncertainRelease = dirname(realpathSync(command()));+ const unknownRelease = join(installationRoot(), "releases/user-files");+ mkdirSync(unknownRelease);+ writeFileSync(join(unknownRelease, "keep"), "user data");+ expect((await install("1.0.2", { ...environment, LIVE_EXECUTABLE: join(liveRelease, "prime-agent") })).code).toBe(+ 0,+ );+ expect(existsSync(liveRelease)).toBe(true);+ expect(releaseDirectories()).toHaveLength(4);+ expect(+ (+ await install("1.0.3", {+ ...environment,+ LIVE_EXECUTABLE: join(liveRelease, "prime-agent"),+ UNCERTAIN_EXECUTABLE: join(uncertainRelease, "prime-agent"),+ })+ ).code,+ ).toBe(0);+ expect(existsSync(liveRelease)).toBe(true);+ expect(existsSync(uncertainRelease)).toBe(true);+ expect(readFileSync(join(unknownRelease, "keep"), "utf8")).toBe("user data");+ expect(releaseDirectories()).toHaveLength(5);+ expect((await install("1.0.3", environment)).code).toBe(0);+ expect(releaseDirectories()).toHaveLength(3);+ expect(readFileSync(join(unknownRelease, "keep"), "utf8")).toBe("user data");});it("does not steal another installation's lock", async () => {@@ -524,7 +1047,7 @@ if [ "$destination" = "$INTERRUPT_COMMAND" ] && [ "$INTERRUPT_POINT" = after ];});it.skipIf(!process.env.PRIME_AGENT_TEST_ARCHIVE)(- "installs the actual compiled release archive",+ "installs, updates, and rolls back actual compiled releases without Node",async () => {const archive = process.env.PRIME_AGENT_TEST_ARCHIVE!;const name = basename(archive);@@ -536,7 +1059,85 @@ if [ "$destination" = "$INTERRUPT_COMMAND" ] && [ "$INTERRUPT_POINT" = after ];expect(execFileSync(command(), ["--version"], { encoding: "utf8", env: { HOME: home, PATH: "/usr/bin:/bin" } }),).toBe(`${version}\n`);+ const originalTarget = readlinkSync(command());+ feed.set(+ "/latest.json",+ Buffer.from(+ JSON.stringify({+ version,+ binaries: [+ { platform, file: name, sha256: createHash("sha256").update(readFileSync(archive)).digest("hex") },+ ],+ }),+ ),+ );+ const reinstalled = await run(command(), ["update", "--force"]);+ expect(reinstalled.code, reinstalled.output).toBe(0);+ expect(reinstalled.output).not.toContain("Warning:");+ expect(readlinkSync(command())).not.toBe(originalTarget);+ expect(readlinkSync(command())).toMatch(/\.[A-Za-z0-9]{6}\/prime-agent$/);+ const repaired = await run(command(), ["update"]);+ expect(repaired.code, repaired.output).toBe(0);+ expect(repaired.output).toContain("already up to date");+ const previous = readlinkSync(command());+ const source = mkdtempSync(join(root, "real-release-"));+ execFileSync("tar", ["-xzf", archive, "-C", source]);+ const metadata = JSON.parse(readFileSync(join(source, "package.json"), "utf8")) as { version: string };+ metadata.version = "99.0.0";+ writeFileSync(join(source, "package.json"), JSON.stringify(metadata));+ const nextFile = `prime-agent-99.0.0-${platform}.tar.gz`;+ const nextArchive = join(root, nextFile);+ execFileSync("tar", ["-czf", nextArchive, "-C", source, "."]);+ const bytes = readFileSync(nextArchive);+ const sha256 = createHash("sha256").update(bytes).digest("hex");+ feed.set(`/releases/v99.0.0/${nextFile}`, bytes);+ feed.set("/releases/v99.0.0/SHA256SUMS", Buffer.from(`${sha256} ${nextFile}\n`));+ feed.set(+ "/latest.json",+ Buffer.from(JSON.stringify({ version: "v99.0.0", binaries: [{ platform, file: nextFile, sha256 }] })),+ );+ mkdirSync(join(home, "agent"), { recursive: true });+ writeFileSync(join(home, "agent/auth.json"), "{}\n");+ writeFileSync(+ join(home, "extension.ts"),+ readFileSync(resolve(__dirname, "fixtures/compiled-artifact-extension.ts")),+ );+ const session = await run(command(), [+ "--offline",+ "--no-context-files",+ "--no-extensions",+ "-e",+ join(home, "extension.ts"),+ "--provider",+ "artifact-faux",+ "--model",+ "artifact",+ "--no-tools",+ "-p",+ "test update",+ ]);+ expect(session.code, session.output).toBe(0);+ expect(session.output).toContain("artifact-ok:");+ expect(await daemonExecutable()).toBe(realpathSync(command()));+ const updated = await run(command(), ["update"]);+ expect(updated.code, updated.output).toBe(0);+ expect(updated.output).toContain("to v99.0.0");+ expect(updated.output).not.toContain("Warning:");+ expect((await run(command(), ["--version"])).output).toBe("99.0.0\n");+ expect(await daemonExecutable()).toBe(realpathSync(command()));+ expect(readlinkSync(join(dirname(command()), "previous"))).toBe(previous);+ const unchanged = await run(command(), ["update"]);+ expect(unchanged.code, unchanged.output).toBe(0);+ expect(unchanged.output).toContain("already up to date");+ feed.clear();+ const restored = await run(command(), ["update", "--rollback"], { PI_OFFLINE: "1" });+ expect(restored.code, restored.output).toBe(0);+ expect(restored.output).not.toContain("Warning:");+ expect(readlinkSync(command())).toBe(previous);+ expect(await daemonExecutable()).toBe(realpathSync(command()));+ expect((await run(command(), ["--version"])).output).toBe(`${version}\n`);+ expect(readFileSync(join(home, "agent/auth.json"), "utf8")).toBe("{}\n");},- 60000,+ 120000,);});diff --git a/packages/coding-agent/test/native-probe-timeout.test.ts b/packages/coding-agent/test/native-probe-timeout.test.tsnew file mode 100644index 0000000000..c62f3f9b1e--- /dev/null+++ b/packages/coding-agent/test/native-probe-timeout.test.ts@@ -0,0 +1,125 @@+import { type ChildProcess, spawn } from "node:child_process";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readlinkSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { describe, expect, it } from "vitest";++const installer = resolve(__dirname, "../../../install.sh");++describe.skipIf(process.platform === "win32")("native executable probe deadlines", () => {+ it.each([+ ["rollback", "--version"],+ ["rollback", "--help"],+ ["recovery", "--version"],+ ["recovery", "--help"],+ ] as const)(+ "releases the lock after a blocked %s %s probe",+ async (operation, argument) => {+ const root = mkdtempSync(join(tmpdir(), "native-probe-timeout-"));+ const managed = join(root, "managed");+ const probePids = join(root, "probe-pids");+ const bin = join(managed, "bin");+ mkdirSync(bin, { recursive: true });+ writeFileSync(join(managed, ".managed"), "prime-agent-native-v1\n");+ const targets = ["1.0.0", "1.0.1"].map((version) => {+ const digest = "a".repeat(64);+ const name = `${version}-${process.platform}-${process.arch}-${digest}`;+ const release = join(managed, "releases", name);+ for (const asset of [+ "install.sh",+ "prime-agent-runtime/pyproject.toml",+ "prime-agent-runtime/src/rlm/repl.py",+ "theme/prime.json",+ "export-html/template.html",+ "photon_rs_bg.wasm",+ ]) {+ mkdirSync(dirname(join(release, asset)), { recursive: true });+ writeFileSync(join(release, asset), "fixture\n");+ }+ writeFileSync(join(release, "package.json"), JSON.stringify({ version }));+ writeFileSync(join(release, ".archive-sha256"), `${digest}\n`);+ writeFileSync(join(release, ".install-source"), "https://example.invalid\n");+ writeFileSync(+ join(release, "prime-agent"),+ `#!/bin/sh+if [ "$1" = "$BLOCK_ARGUMENT" ] && [ "${version}" = "1.0.0" ]; then+ printf '%s\\n' "$$" >> "$PROBE_PIDS"+ trap '' TERM+ exec sleep 60+fi+printf '%s\\n' '${version}'+`,+ { mode: 0o755 },+ );+ return `../releases/${name}/prime-agent`;+ });+ symlinkSync(targets[1], join(bin, "prime-agent"));+ symlinkSync(targets[0], join(bin, "previous"));+ const journal = join(managed, ".activation-state");+ if (operation === "recovery") writeFileSync(journal, `${targets[1]}\n${targets[0]}\n`);+ let child: ChildProcess | undefined;+ let result: Promise<{ code: number | null; signal: NodeJS.Signals | null }> | undefined;+ try {+ const installerChild = spawn("sh", [installer, "--rollback"], {+ env: {+ ...process.env,+ HOME: root,+ PATH: "/usr/bin:/bin",+ PRIME_AGENT_INSTALL_DIR: managed,+ BLOCK_ARGUMENT: argument,+ PROBE_PIDS: probePids,+ },+ stdio: ["ignore", "pipe", "pipe"],+ timeout: operation === "recovery" ? 27000 : 17000,+ killSignal: "SIGKILL",+ });+ child = installerChild;+ let output = "";+ installerChild.stdout.on("data", (chunk) => {+ output += chunk.toString();+ });+ installerChild.stderr.on("data", (chunk) => {+ output += chunk.toString();+ });+ result = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((done, reject) => {+ installerChild.once("error", reject);+ installerChild.once("exit", (code, signal) => done({ code, signal }));+ });+ await expect.poll(() => existsSync(probePids), { timeout: 3000 }).toBe(true);+ expect(existsSync(join(managed, ".install-lock"))).toBe(true);+ const exited = await result;+ expect(exited.signal, output).toBeNull();+ expect(exited.code, output).not.toBe(0);+ expect(output).toContain("probe timed out after 10 seconds");+ expect(readlinkSync(join(bin, "prime-agent"))).toBe(targets[1]);+ expect(readlinkSync(join(bin, "previous"))).toBe(targets[0]);+ expect(existsSync(join(managed, ".install-lock"))).toBe(false);+ expect(existsSync(journal)).toBe(operation === "recovery");+ for (const pid of readFileSync(probePids, "utf8").trim().split("\n").map(Number))+ expect(() => process.kill(pid, 0)).toThrow();+ } finally {+ if (child && child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");+ await result;+ if (existsSync(probePids))+ for (const pid of readFileSync(probePids, "utf8").trim().split("\n").map(Number)) {+ try {+ process.kill(pid, "SIGKILL");+ } catch {+ /* Already exited. */+ }+ }+ rmSync(root, { recursive: true, force: true });+ }+ },+ 35000,+ );+});diff --git a/packages/coding-agent/test/native-update.test.ts b/packages/coding-agent/test/native-update.test.tsnew file mode 100644index 0000000000..1990ec916a--- /dev/null+++ b/packages/coding-agent/test/native-update.test.ts@@ -0,0 +1,99 @@+import { mkdirSync, mkdtempSync, readlinkSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { getNativeUpdatePlan } from "../src/cli/native-update.js";+import { NATIVE_RELEASE_ASSETS } from "../src/utils/native-installation.js";+import { getLatestPiRelease } from "../src/utils/version-check.js";++const artifact = {+ platform: "linux-x64",+ file: "prime-agent-1.2.4-linux-x64.tar.gz",+ sha256: "b".repeat(64),+};+const invalidMetadata: Array<{ name: string; binaries: unknown }> = [+ { name: "invalid checksum", binaries: [{ ...artifact, sha256: "invalid" }] },+ { name: "duplicate platform", binaries: [artifact, artifact] },+ { name: "valid entry followed by invalid entry", binaries: [artifact, null] },+ { name: "wrong archive version", binaries: [{ ...artifact, file: "prime-agent-1.2.3-linux-x64.tar.gz" }] },+ { name: "non-array metadata", binaries: { artifact } },+];++describe("native release metadata isolation", () => {+ let root: string;+ let executable: string;+ let target: string;+ const baseUrl = "https://releases.example";++ beforeEach(() => {+ vi.stubEnv("PI_SKIP_VERSION_CHECK", "");+ vi.stubEnv("PI_OFFLINE", "");+ vi.stubEnv("PRIME_AGENT_DOWNLOAD_BASE_URL", baseUrl);+ root = realpathSync(mkdtempSync(join(tmpdir(), "prime-native-metadata-")));+ const checksum = "a".repeat(64);+ const releaseName = `1.2.3-linux-x64-${checksum}`;+ const releaseDir = join(root, "releases", releaseName);+ mkdirSync(releaseDir, { recursive: true });+ mkdirSync(join(root, "bin"));+ writeFileSync(join(root, ".managed"), "prime-agent-native-v1\n");+ for (const asset of NATIVE_RELEASE_ASSETS) {+ mkdirSync(dirname(join(releaseDir, asset)), { recursive: true });+ writeFileSync(join(releaseDir, asset), "fixture\n");+ }+ writeFileSync(join(releaseDir, ".archive-sha256"), checksum);+ writeFileSync(join(releaseDir, ".install-source"), baseUrl);+ writeFileSync(join(releaseDir, "package.json"), JSON.stringify({ version: "1.2.3" }));+ executable = join(releaseDir, "prime-agent");+ writeFileSync(executable, "fixture executable");+ target = `../releases/${releaseName}/prime-agent`;+ symlinkSync(target, join(root, "bin", "prime-agent"));+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+ rmSync(root, { recursive: true, force: true });+ });++ it.each(invalidMetadata)(+ "preserves npm release details but refuses native updates for $name",+ async ({ binaries }) => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Response.json({+ version: "v1.2.4",+ package: "prime-agent",+ tarball: "releases/v1.2.4/prime-agent-1.2.4.tgz",+ binaries,+ }),+ ),+ );++ await expect(getLatestPiRelease("1.2.3")).resolves.toEqual({+ version: "1.2.4",+ packageName: "prime-agent",+ installSpec: `${baseUrl}/releases/v1.2.4/prime-agent-1.2.4.tgz`,+ });+ for (const force of [false, true]) {+ await expect(getNativeUpdatePlan({ force, rollback: false, executable })).rejects.toThrow(+ "No verified compiled archive is available for linux-x64.",+ );+ }+ expect(readlinkSync(join(root, "bin", "prime-agent"))).toBe(target);+ },+ );++ it("uses the verified platform checksum when the entire native list is valid", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => Response.json({ version: "1.2.4", binaries: [artifact] })),+ );++ const plan = await getNativeUpdatePlan({ force: false, rollback: false, executable });++ expect(plan.targetVersion).toBe("1.2.4");+ expect(plan.command?.args).toContain(`PRIME_AGENT_EXPECTED_SHA256=${artifact.sha256}`);+ expect(plan.command?.args).toContain("PRIME_AGENT_INSTALL_METHOD=binary");+ });+});diff --git a/packages/coding-agent/test/package-self-update-daemon.test.ts b/packages/coding-agent/test/package-self-update-daemon.test.tsindex af8ebf000d..ef8f780098 100644--- a/packages/coding-agent/test/package-self-update-daemon.test.ts+++ b/packages/coding-agent/test/package-self-update-daemon.test.ts@@ -578,6 +578,66 @@ describe("self-update daemon restart", () => {expect(mockState.calls.some((call) => call.startsWith("spawn:npm "))).toBe(false);});+ it.each(["bad checksum", "duplicate platform"])(+ "keeps an up-to-date npm install and daemon untouched with %s metadata",+ async (invalidKind) => {+ process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV] = "1";+ const artifact = {+ platform: "linux-x64",+ file: `prime-agent-${VERSION}-linux-x64.tar.gz`,+ sha256: "a".repeat(64),+ };+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Response.json({+ version: VERSION,+ package: PACKAGE_NAME,+ tarball: `https://releases.example/releases/v${VERSION}/prime-agent-${VERSION}.tgz`,+ binaries:+ invalidKind === "bad checksum" ? [{ ...artifact, sha256: "invalid" }] : [artifact, artifact],+ }),+ ),+ );++ await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);++ expect(process.exitCode).toBe(SELF_UPDATE_NOT_ATTEMPTED_EXIT_CODE);+ expect(mockState.calls).toEqual([]);+ },+ );++ it.each(["bad checksum", "duplicate platform"])(+ "keeps the selected npm release URL when a newer release has %s metadata",+ async (invalidKind) => {+ mockState.daemonProbe = { reachable: false };+ const tarball = "https://releases.example/releases/v999.0.0/prime-agent-999.0.0.tgz";+ const artifact = {+ platform: "linux-x64",+ file: "prime-agent-999.0.0-linux-x64.tar.gz",+ sha256: "a".repeat(64),+ };+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Response.json({+ version: "999.0.0",+ package: PACKAGE_NAME,+ tarball,+ binaries:+ invalidKind === "bad checksum" ? [{ ...artifact, sha256: "invalid" }] : [artifact, artifact],+ }),+ ),+ );++ await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);++ expect(mockState.calls.filter((call) => call.startsWith("spawn:"))).toEqual([+ `spawn:npm install -g ${tarball}`,+ ]);+ },+ );+it("does not use the no-change sentinel when interactive self-update is cancelled", async () => {process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV] = "1";mockState.daemonProbe = {diff --git a/packages/coding-agent/test/suite/regressions/4603-worker-recovery.test.ts b/packages/coding-agent/test/suite/regressions/4603-worker-recovery.test.tsindex 19ab4a7f43..ec856ec32d 100644--- a/packages/coding-agent/test/suite/regressions/4603-worker-recovery.test.ts+++ b/packages/coding-agent/test/suite/regressions/4603-worker-recovery.test.ts@@ -1047,15 +1047,35 @@ describe("ENG-4603 worker recovery convergence", () => {await waitForType(successor, "ready", 60_000);const successorStartId = getProcessStartId(successor.child.pid!);client.close();+ const unrelatedPaths = await createPaths();+ const unrelated = spawnSupervisor(unrelatedPaths);+ await waitForType(unrelated, "booted");+ unrelated.child.send({ type: "go" });+ await waitForType(unrelated, "ready", 60_000);const systemLsofPath = spawnSync("which", ["lsof"], { encoding: "utf8" }).stdout.trim();if (!systemLsofPath) throw new Error("Could not locate lsof for the shutdown regression");const lsofPath = join(paths.agentDir, "lsof");writeFileSync(lsofPath, '#!/bin/sh\nexec "$ENG_4603_SYSTEM_LSOF" -nP -F pn -U -a -p "$ENG_4603_LSOF_PIDS"\n', {mode: 0o700,});+ const systemSsPath = spawnSync("which", ["ss"], { encoding: "utf8" }).stdout.trim();+ const ssPath = join(paths.agentDir, "ss");+ writeFileSync(+ ssPath,+ `#!/bin/sh+[ -n "$ENG_4603_SYSTEM_SS" ] || exit 1+listeners=$("$ENG_4603_SYSTEM_SS" "$@") || exit $?+printf '%s\\n' "$listeners" | awk -v pids="$ENG_4603_LSOF_PIDS" '+ BEGIN { count=split(pids, allowed, ",") }+ { for (i=1; i<=count; i++) if (index($0, "pid=" allowed[i] ",")) { print; break } }+'+`,+ { mode: 0o700 },+ );const lsofEnvironment = {ENG_4603_LSOF_PIDS: `${predecessor.child.pid},${successor.child.pid},${workerPid}`,ENG_4603_SYSTEM_LSOF: systemLsofPath,+ ENG_4603_SYSTEM_SS: systemSsPath,PATH: `${paths.agentDir}:${process.env.PATH ?? ""}`,};const listenersBeforeShutdown = spawnSync(lsofPath, [], {@@ -1068,6 +1088,9 @@ describe("ENG-4603 worker recovery convergence", () => {const shutdown = await runCli(paths, ["shutdown", "--force", "--json"], 60_000, lsofEnvironment);expect(shutdown.code).toBe(0);const shutdownResult = JSON.parse(shutdown.stdout) as { stopped: unknown[]; failed: unknown[] };+ expect(exactProcessIsAlive(unrelated.child.pid!, unrelated.identity?.processStartId)).toBe(true);+ const unrelatedClient = await connectEventually(unrelatedPaths.socketPath);+ unrelatedClient.close();const survivingIdentities = [{ pid: predecessor.child.pid!, processStartId: predecessorStartId },{ pid: successor.child.pid!, processStartId: successorStartId },diff --git a/packages/coding-agent/test/suite/regressions/4606-update-restart-coordinator.test.ts b/packages/coding-agent/test/suite/regressions/4606-update-restart-coordinator.test.tsindex b940982e2e..19d5a296ab 100644--- a/packages/coding-agent/test/suite/regressions/4606-update-restart-coordinator.test.ts+++ b/packages/coding-agent/test/suite/regressions/4606-update-restart-coordinator.test.ts@@ -401,7 +401,7 @@ describe("ENG-4606 update restart coordinator", () => {`Coordinator failed: ${status.message}\npredecessor stderr:\n${predecessor.stderr}\npredecessor stdout:\n${predecessor.stdout}`,);}- expect(status).toMatchObject({+ expect(status, JSON.stringify(status, null, 2)).toMatchObject({phase: "complete",socketPath: paths.socketPath,counts: { total: 1, restored: 1, resumed: 1, failed: 0 },