Skip to content

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

Rust

support TypeScript updates to Rust (#3442)

ktc174739ad3b0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8ce8ab58b8..acde36c2d1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -205,6 +205,22 @@ jobs:
components: rustfmt
- run: cargo fmt --all --check
+ migration-packaging:
+ name: historical upgrade packaging
+ needs: trust
+ runs-on: ubuntu-24.04
+ timeout-minutes: 15
+ if: needs.trust.result == 'success' && needs.trust.outputs.allowed == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)
+ steps:
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ persist-credentials: false
+ - name: Verify native and npm compatibility packaging
+ run: |
+ python3 scripts/release/test_native_compat.py
+ python3 scripts/release/test_npm_bridge.py
+ python3 scripts/release/test_restamp.py
+
clippy-test:
name: check + clippy (workspace)
needs: trust
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 864e0b432b..013237e844 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -215,6 +215,26 @@ jobs:
--catalog-assets "target/${{ matrix.target }}/catalog-assets" \
--out-dir "target/${{ matrix.target }}/dist"
cat "target/${{ matrix.target }}/dist/manifest.json"
+ - name: Verify fresh channel install and reinstall
+ # Host detection must match the packaged artifact. Intel macOS is
+ # cross-built; its existing Rosetta version probe remains separate.
+ if: matrix.target != 'x86_64-apple-darwin'
+ run: |
+ set -euo pipefail
+ archives=(target/${{ matrix.target }}/dist/prime-agent-*.tar.gz)
+ python3 scripts/release/test_channel_install.py \
+ --archive "${archives[0]}" --installer install-rust.sh \
+ --report "target/${{ matrix.target }}/dist/channel-install.json"
+ - name: Verify the shipped TypeScript update command
+ # The x64 Darwin artifact is cross-built on arm64. Its historical
+ # installer detects the host, so this gate runs on native hosts only.
+ if: matrix.target != 'x86_64-apple-darwin'
+ run: |
+ set -euo pipefail
+ archives=(target/${{ matrix.target }}/dist/prime-agent-*.tar.gz)
+ python3 scripts/release/verify_legacy_release.py \
+ --candidate "${archives[0]}" \
+ --report "target/${{ matrix.target }}/dist/legacy-upgrade.json"
# The homebrew-core submission candidate: the source tarball the
# formula pins (scripts/release/assemble_source.py — the git tree at
# the tag plus the validated catalog assets at the archive root). One
@@ -254,6 +274,8 @@ jobs:
target/${{ matrix.target }}/dist/prime-agent-*
target/${{ matrix.target }}/dist/SHA256SUMS
target/${{ matrix.target }}/dist/manifest.json
+ target/${{ matrix.target }}/dist/legacy-upgrade.json
+ target/${{ matrix.target }}/dist/channel-install.json
if-no-files-found: error
build-darwin:
@@ -331,6 +353,26 @@ jobs:
--catalog-assets "target/${{ matrix.target }}/catalog-assets" \
--out-dir "target/${{ matrix.target }}/dist"
cat "target/${{ matrix.target }}/dist/manifest.json"
+ - name: Verify fresh channel install and reinstall
+ # Host detection must match the packaged artifact. Intel macOS is
+ # cross-built; its existing Rosetta version probe remains separate.
+ if: matrix.target != 'x86_64-apple-darwin'
+ run: |
+ set -euo pipefail
+ archives=(target/${{ matrix.target }}/dist/prime-agent-*.tar.gz)
+ python3 scripts/release/test_channel_install.py \
+ --archive "${archives[0]}" --installer install-rust.sh \
+ --report "target/${{ matrix.target }}/dist/channel-install.json"
+ - name: Verify the shipped TypeScript update command
+ # The x64 Darwin artifact is cross-built on arm64. Its historical
+ # installer detects the host, so this gate runs on native hosts only.
+ if: matrix.target != 'x86_64-apple-darwin'
+ run: |
+ set -euo pipefail
+ archives=(target/${{ matrix.target }}/dist/prime-agent-*.tar.gz)
+ python3 scripts/release/verify_legacy_release.py \
+ --candidate "${archives[0]}" \
+ --report "target/${{ matrix.target }}/dist/legacy-upgrade.json"
- name: Upload artifacts
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
with:
@@ -339,6 +381,8 @@ jobs:
target/${{ matrix.target }}/dist/prime-agent-*
target/${{ matrix.target }}/dist/SHA256SUMS
target/${{ matrix.target }}/dist/manifest.json
+ target/${{ matrix.target }}/dist/legacy-upgrade.json
+ target/${{ matrix.target }}/dist/channel-install.json
if-no-files-found: error
# The Windows build: its own job (the build-darwin pattern), because the
@@ -642,31 +686,12 @@ jobs:
sys.exit("hash continuity failed:\n" + "\n".join(failures))
print(f"hash continuity verified for all archives")
PY
- # Prime Agent 0.9.8 (the TypeScript release) updates itself with its
- # bundled installer, which installs any archive that carries install.sh,
- # theme/prime.json, export-html/template.html and photon_rs_bg.wasm.
- # The Rust archive lacks all four, and that is the only thing stopping a
- # TS client from installing a Rust release into the TS layout (which
- # breaks it). TS needs all four, so refusing a root-level install.sh
- # keeps every Rust archive uninstallable by the TS updater.
- - name: Refuse archives the TypeScript updater would install
+ # Existing TS updaters execute their retained installer. Verify the
+ # archive that installer activates, not merely the new curl installer.
+ - name: Verify historical native updater compatibility
run: |
set -euo pipefail
- python3 - <<'PY'
- import pathlib, sys, tarfile
- incoming = pathlib.Path("incoming")
- failures = []
- for entry_dir in sorted(p for p in incoming.iterdir() if p.is_dir()):
- for archive in sorted(entry_dir.glob("prime-agent-*.tar.gz")):
- with tarfile.open(archive) as tar:
- names = {pathlib.PurePosixPath(m.name).parts for m in tar.getmembers()}
- if ("install.sh",) in names:
- failures.append(f"{archive.name}: contains a root-level install.sh")
- if failures:
- sys.exit("a TypeScript Prime Agent updater could install these archives:\n"
- + "\n".join(failures))
- print("no archive carries the TypeScript installer layout")
- PY
+ python3 verification-source/scripts/release/native_compat.py incoming/*/prime-agent-*.tar.gz
- name: Verify Linux decoder integrity against installed tar ELF
run: |
set -euo pipefail
@@ -729,6 +754,20 @@ jobs:
tar.extractall(unpacked, filter="data")
PY
ls -la release-out release-unpacked
+ - name: Assemble the npm migration bridge
+ run: |
+ set -euo pipefail
+ channel=stable
+ case "$RELEASE_VERSION" in *-beta*) channel=beta ;; esac
+ # Keep a working TS fallback when an existing npm installation
+ # cannot run the native target. The packer verifies its pinned hash.
+ curl --fail --location --silent --show-error --retry 3 \
+ https://pub-728493de92a943e2a9b2d17b4719f318.r2.dev/releases/v0.9.8/prime-agent-0.9.8.tgz \
+ --output /tmp/prime-agent-typescript-fallback.tgz
+ python3 verification-source/scripts/release/npm_bridge.py \
+ --repo-root verification-source --version "${RELEASE_VERSION#v}" --out-dir release-out --channel "$channel" \
+ --fallback-tarball /tmp/prime-agent-typescript-fallback.tgz
+ (cd release-out && sha256sum "prime-agent-${RELEASE_VERSION#v}.tgz" >> SHA256SUMS)
- name: Emit the channel manifest (latest.json stable / beta.json nightly)
run: |
set -euo pipefail
@@ -813,7 +852,13 @@ jobs:
"the channel manifest must carry a row for every known "
"platform (one build job per platform)"
)
- document = {"version": f"v{version}"}
+ # Prime Agent 0.6+ npm clients consume package/tarball; native
+ # clients consume binaries. Keep both routes in one manifest.
+ document = {
+ "version": f"v{version}",
+ "package": "prime-agent",
+ "tarball": f"releases/v{version}/prime-agent-{version}.tgz",
+ }
v1_rows = [row for row in rows if row["platform"] in v1_platforms]
if v1_rows:
document["binaries"] = v1_rows
@@ -884,7 +929,7 @@ jobs:
# the channel manifests reference. The homebrew-core source
# tarball rides the GitHub release only (packagers pin it
# there; the R2 pointers never name it).
- for artifact in release-out/prime-agent-*.tar.gz; do
+ for artifact in release-out/prime-agent-*.tar.gz release-out/prime-agent-*.tgz; do
case "$artifact" in *-src.tar.gz) continue ;; esac
aws s3 cp "$artifact" "s3://${R2_BUCKET}/${RELEASE_PREFIX}/$(basename "$artifact")" \
--endpoint-url "$R2_ENDPOINT_URL" \
@@ -1107,6 +1152,7 @@ jobs:
with:
subject-path: |
release-out/prime-agent-*.tar.gz
+ release-out/prime-agent-*.tgz
release-out/*.debug.gz
- name: Attach to GitHub release
uses: softprops/action-gh-release@153bb8e04406b158c6c84fc1615b65b24149a1fe # v2.6.1
@@ -1122,6 +1168,7 @@ jobs:
fail_on_unmatched_files: true
files: |
release-out/prime-agent-*.tar.gz
+ release-out/prime-agent-*.tgz
release-out/*.debug.gz
release-out/SHA256SUMS
release-out/*.json
diff --git a/Makefile b/Makefile
index 3af0bda89c..00f85e1c9f 100644
--- a/Makefile
+++ b/Makefile
@@ -188,3 +188,10 @@ shard-gates:
python3 scripts/test_ci_pr_crates.py
.PHONY: check deny windows-cross actionlint glibc-gate release-dry-run continuous-dry-run audit-build package catalog-assets catalog-assets-fixture catalog-assets-gates fold-gates restamp-gates shard-gates
+
+# Offline packaging contract tests for updaters shipped since Prime Agent 0.6.
+legacy-upgrade-gates:
+ python3 scripts/release/test_native_compat.py
+ python3 scripts/release/test_npm_bridge.py
+
+.PHONY: legacy-upgrade-gates
diff --git a/crates/pa-cli/README.md b/crates/pa-cli/README.md
index d050c35e3c..d70e9606fb 100644
--- a/crates/pa-cli/README.md
+++ b/crates/pa-cli/README.md
@@ -100,3 +100,13 @@ fetch, archive staging) lives in pa-core's `update` module; the daemon-side
prepare/commit/stop drivers and the boot restore pass are pa-daemon
(slices 2-3 and 5): the coordinator's `Restoring` phase polls the
successor's `update_restore_status` RPC for the real per-session counts.
+The legacy restart adapter accepts the fresh status path supplied by shipped
+TypeScript updaters after they activate a release. It reports the original
+`requestId`/`phase` status schema, translates their session checkpoint to a
+Rust roster, and restarts the daemon without repeating activation. Recovery
+rosters remain on disk when restoration fails. Socket-scoped checkpoints resume
+after an interrupted handoff when no daemon is running, and reject a different
+installed version. The adapter holds the shipped TypeScript shutdown-admission
+lease in both historic supervisor registries until Rust owns the replacement
+socket, preventing old clients from launching a competing daemon. Admission
+records are refreshed and removed only while their ownership token matches.
diff --git a/crates/pa-cli/src/client_update.rs b/crates/pa-cli/src/client_update.rs
index 8c60fb59fa..7c820e9896 100644
--- a/crates/pa-cli/src/client_update.rs
+++ b/crates/pa-cli/src/client_update.rs
@@ -38,6 +38,34 @@ impl pa_tui::update_command::UpdateCommands for ClientUpdate {
}
return Err(homebrew::upgrade_instruction(kind));
}
+ let executable = std::env::current_exe().map_err(|error| error.to_string())?;
+ if let Some(root) = pa_core::update::install::install_root_of(&executable) {
+ // Reuse the CLI's managed activation/restart transaction.
+ // Capturing the child keeps its progress off the live frame.
+ let output = tokio::process::Command::new(executable)
+ .arg("update")
+ .env(
+ crate::public_command::SELF_UPDATE_INTERACTIVE_CHILD_ENV,
+ "1",
+ )
+ .stdin(std::process::Stdio::null())
+ .output()
+ .await
+ .map_err(|error| format!("could not start the update: {error}"))?;
+ if !output.status.success() && output.status.code() != Some(75) {
+ return Err(format!(
+ "{}{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ ));
+ }
+ return pa_core::update::install::read_installation(
+ &root,
+ pa_core::update::install::CURRENT_LAUNCHER,
+ )
+ .map(|installed| installed.version().to_string())
+ .map_err(|error| error.to_string());
+ }
match installer::run_installer(
Some(crate::installer_update::requested_installer_channel(None)),
InstallerOutput::Capture,
diff --git a/crates/pa-cli/src/lib.rs b/crates/pa-cli/src/lib.rs
index d73e5095f8..ef17f38b6f 100644
--- a/crates/pa-cli/src/lib.rs
+++ b/crates/pa-cli/src/lib.rs
@@ -89,6 +89,8 @@ fn main_impl(args: &[String], runtime: &dyn mode::Runtime) -> Result<i32, String
// Telemetry reports the version `--version` prints: the beta channel
// restamps only the packaged manifest, never the compiled-in version.
pa_telemetry::set_version(crate::config::version());
+ pa_daemon::protocol::configure_app_version(crate::config::version())
+ .map_err(|error| error.to_string())?;
let offline_mode = args.iter().any(|arg| arg == "--offline")
|| crate::config::is_truthy_env_flag(
diff --git a/crates/pa-cli/src/package_command.rs b/crates/pa-cli/src/package_command.rs
index 562425cc3e..f1e5ba2887 100644
--- a/crates/pa-cli/src/package_command.rs
+++ b/crates/pa-cli/src/package_command.rs
@@ -460,6 +460,7 @@ pub fn handle_package_command(args: &[String]) -> PackageCommandOutcome {
let exit_code = runtime.block_on(crate::update_flow::update_command::run_coordinator_mode(
socket_path,
status_path,
+ options.restart_origin_active_session_id.as_deref(),
));
return match exit_code {
Ok(code) => PackageCommandOutcome {
diff --git a/crates/pa-cli/src/public_command.rs b/crates/pa-cli/src/public_command.rs
index b8d179cded..0f2d57bff6 100644
--- a/crates/pa-cli/src/public_command.rs
+++ b/crates/pa-cli/src/public_command.rs
@@ -128,8 +128,8 @@ pub fn handle_public_command(args: &[String]) -> PublicCommandResult {
.iter()
.any(|a| a == DAEMON_UPDATE_RESTART_COORDINATOR_FLAG)
{
- handle_package_command(&args);
- return handled();
+ let result = handle_package_command(&args);
+ return handled_with_exit(result.exit_code.unwrap_or(0));
}
let separator_index = args.iter().position(|a| a == "--");
@@ -725,10 +725,14 @@ fn run_update(args: &[String]) -> PublicCommandResult {
) {
return handled_with_exit(abort_code);
}
- // The installer funnel serves the bare update and the channel flags:
- // the channel is the flag, else the saved `updateChannel` setting
- // (`/nightly on|off`), else the installed one.
- if !options.rollback && options.archive.is_none() {
+ // A Rust archive activated by a historical TS installer still belongs
+ // to that managed root. Keep using its atomic launcher activation so a
+ // custom root/public-bin pair is not silently replaced by ~/.local.
+ let managed_install = std::env::current_exe()
+ .ok()
+ .and_then(|exe| pa_core::update::install::install_root_of(&exe))
+ .is_some();
+ if !managed_install && !options.rollback && options.archive.is_none() {
let update = crate::installer_update::UpdateOptions {
check: false,
channel: options.channel,
@@ -1022,6 +1026,17 @@ mod update_options_tests {
assert_eq!(channel(&["--check", "--rollback"]), None);
}
+ #[test]
+ fn invalid_restart_coordinator_preserves_the_failure_exit_code() {
+ let args = vec![
+ "update".to_string(),
+ DAEMON_UPDATE_RESTART_COORDINATOR_FLAG.to_string(),
+ ];
+ let result = handle_public_command(&args);
+ assert!(result.handled);
+ assert_eq!(result.exit_code, Some(1));
+ }
+
#[test]
fn parses_the_ts_booleans() {
let invocation = parse(&["--force"]).unwrap();
diff --git a/crates/pa-cli/src/update_flow/coordinator.rs b/crates/pa-cli/src/update_flow/coordinator.rs
index 111ecaabc8..dbeb00f524 100644
--- a/crates/pa-cli/src/update_flow/coordinator.rs
+++ b/crates/pa-cli/src/update_flow/coordinator.rs
@@ -163,6 +163,11 @@ async fn drive(
.await
.set_state(UpdateState::Prepared)
.map_err(PhaseFailure::after_stop)?;
+ writer
+ .lock()
+ .await
+ .set_state(UpdateState::Stopping)
+ .map_err(PhaseFailure::after_stop)?;
}
// `Stopped`: fence-free predecessor exit wait (spec §9).
if let Some(identity) = &predecessor {
diff --git a/crates/pa-cli/src/update_flow/legacy_admission.rs b/crates/pa-cli/src/update_flow/legacy_admission.rs
new file mode 100644
index 0000000000..86e881dce4
--- /dev/null
+++ b/crates/pa-cli/src/update_flow/legacy_admission.rs
@@ -0,0 +1,242 @@
+//! TS shutdown admission keeps old clients from relaunching a competing
+//! supervisor while the Rust coordinator restores their socket. The record
+//! and empty `.guard` directory follow shipped proper-lockfile clients.
+
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+use anyhow::{Context, Result};
+use serde_json::{json, Value};
+
+const REGISTRY_OVERRIDE: &str = "PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_REGISTRY_DIR";
+const LEASE_MS: u64 = 5_000;
+
+pub(super) struct Admission {
+ directories: Vec<PathBuf>,
+ record: Value,
+}
+
+impl Admission {
+ pub(super) fn directories() -> Result<Vec<PathBuf>> {
+ let mut directories = if let Some(path) = std::env::var_os(REGISTRY_OVERRIDE) {
+ vec![PathBuf::from(path)]
+ } else {
+ let home =
+ pa_types::platform::home_dir().context("resolve supervisor registry home")?;
+ vec![
+ home.join(".prime/supervisor-owners"),
+ pa_daemon::socket::default_daemon_socket_path()
+ .parent()
+ .context("resolve legacy supervisor registry")?
+ .join("supervisor-owners"),
+ ]
+ };
+ directories.sort();
+ directories.dedup();
+ Ok(directories)
+ }
+
+ pub(super) async fn acquire(directories: &[PathBuf]) -> Result<Self> {
+ for directory in directories {
+ std::fs::create_dir_all(directory)?;
+ pa_core::platform::restrict_dir(directory)?;
+ }
+ let now = crate::util_time::now_iso8601();
+ let identity = super::status::coordinator_identity();
+ let mut admission = Self {
+ directories: Vec::new(),
+ record: json!({"version":1,"token":uuid::Uuid::new_v4().to_string(),
+ "pid":identity.pid,"createdAt":now,"updatedAt":now,
+ "expiresAt":pa_daemon::util::iso_from_unix_ms(crate::util_time::now_ms()+LEASE_MS)}),
+ };
+ if let Some(start_id) = identity.process_start_id {
+ admission.record["processStartId"] = json!(start_id);
+ }
+ // Acquisition never overwrites an active foreign lease. If the second
+ // registry is busy, release the first before waiting and retry both.
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
+ loop {
+ let mut blocked = false;
+ for directory in directories {
+ let result = guarded(directory, || {
+ let path = directory.join("shutdown-admission.json");
+ if read_record(&path)?.as_ref().is_some_and(record_is_active) {
+ return Ok(false);
+ }
+ super::legacy_restart::persist(&path, &admission.record)?;
+ Ok(true)
+ })
+ .await;
+ match result {
+ Ok(true) => admission.directories.push(directory.clone()),
+ Ok(false) => {
+ blocked = true;
+ break;
+ }
+ Err(error) => {
+ admission.release().await?;
+ return Err(error);
+ }
+ }
+ }
+ if !blocked {
+ return Ok(admission);
+ }
+ admission.release().await?;
+ anyhow::ensure!(
+ tokio::time::Instant::now() < deadline,
+ "another TypeScript daemon shutdown is still running"
+ );
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ admission.record["expiresAt"] = json!(pa_daemon::util::iso_from_unix_ms(
+ crate::util_time::now_ms() + LEASE_MS
+ ));
+ }
+ }
+
+ pub(super) async fn refresh(&mut self) -> Result<()> {
+ self.record["updatedAt"] = json!(crate::util_time::now_iso8601());
+ self.record["expiresAt"] = json!(pa_daemon::util::iso_from_unix_ms(
+ crate::util_time::now_ms() + LEASE_MS
+ ));
+ for directory in &self.directories {
+ guarded(directory, || {
+ let path = directory.join("shutdown-admission.json");
+ let current =
+ read_record(&path)?.context("TypeScript shutdown admission disappeared")?;
+ anyhow::ensure!(
+ current["token"] == self.record["token"],
+ "TypeScript shutdown admission ownership changed"
+ );
+ super::legacy_restart::persist(&path, &self.record)
+ })
+ .await?;
+ }
+ Ok(())
+ }
+
+ pub(super) async fn release(&mut self) -> Result<()> {
+ for directory in &self.directories {
+ guarded(directory, || {
+ let path = directory.join("shutdown-admission.json");
+ if read_record(&path)?.is_some_and(|record| record["token"] == self.record["token"])
+ {
+ std::fs::remove_file(path)?;
+ }
+ Ok(())
+ })
+ .await?;
+ }
+ self.directories.clear();
+ Ok(())
+ }
+}
+
+fn read_record(path: &Path) -> Result<Option<Value>> {
+ match std::fs::read(path) {
+ Ok(bytes) => {
+ let value: Value = serde_json::from_slice(&bytes)?;
+ anyhow::ensure!(
+ value["version"] == 1
+ && value["token"].is_string()
+ && value["pid"].as_u64().is_some_and(|pid| pid > 0)
+ && value["expiresAt"]
+ .as_str()
+ .and_then(pa_daemon::util::iso_to_unix_ms)
+ .is_some(),
+ "invalid TypeScript shutdown admission at {}",
+ path.display()
+ );
+ Ok(Some(value))
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Err(error) => Err(error.into()),
+ }
+}
+
+fn record_is_active(record: &Value) -> bool {
+ let unexpired = record["expiresAt"]
+ .as_str()
+ .and_then(pa_daemon::util::iso_to_unix_ms)
+ .is_some_and(|expires| expires > crate::util_time::now_ms());
+ if !unexpired {
+ return false;
+ }
+ let Some(pid) = record["pid"]
+ .as_u64()
+ .and_then(|pid| u32::try_from(pid).ok())
+ else {
+ return true;
+ };
+ if matches!(pa_daemon::lease::is_process_alive(pid), Ok(false)) {
+ return false;
+ }
+ !matches!((record["processStartId"].as_str(), pa_daemon::lease::get_process_start_id(pid)),
+ (Some(expected), Some(observed)) if expected != observed)
+}
+
+/// No foreign stale guard is reclaimed here. TS owns that recovery protocol;
+/// an abandoned guard produces a bounded failure rather than an unsafe write.
+async fn guarded<T>(directory: &Path, operation: impl FnOnce() -> Result<T>) -> Result<T> {
+ let path = directory.join(".guard");
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
+ loop {
+ match std::fs::create_dir(&path) {
+ Ok(()) => break,
+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
+ anyhow::ensure!(
+ tokio::time::Instant::now() < deadline,
+ "TypeScript registry guard is busy: {}",
+ path.display()
+ );
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ Err(error) => return Err(error.into()),
+ }
+ }
+ // Keep this section synchronous and much shorter than TS's five-second
+ // stale threshold. Never remove a guard another process has replaced.
+ let modified = std::fs::metadata(&path)?.modified()?;
+ let result = operation();
+ anyhow::ensure!(
+ std::fs::metadata(&path)?.modified()? == modified,
+ "TypeScript registry guard changed during the transaction"
+ );
+ std::fs::remove_dir(path)?;
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn release_preserves_a_replacement_owners_token() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("shutdown-admission.json");
+ let successor = json!({"version":1,"token":"successor","pid":std::process::id(),
+ "expiresAt":"2099-01-01T00:00:00.000Z"});
+ super::super::legacy_restart::persist(&path, &successor).unwrap();
+ let mut admission = Admission {
+ directories: vec![directory.path().to_path_buf()],
+ record: json!({"token":"old"}),
+ };
+ admission.release().await.unwrap();
+ assert_eq!(read_record(&path).unwrap(), Some(successor));
+ }
+
+ #[tokio::test]
+ async fn refresh_refuses_a_replacement_owners_token() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("shutdown-admission.json");
+ let successor = json!({"version":1,"token":"successor","pid":std::process::id(),
+ "expiresAt":"2099-01-01T00:00:00.000Z"});
+ super::super::legacy_restart::persist(&path, &successor).unwrap();
+ let mut admission = Admission {
+ directories: vec![directory.path().to_path_buf()],
+ record: json!({"token":"old"}),
+ };
+ assert!(admission.refresh().await.is_err());
+ assert_eq!(read_record(&path).unwrap(), Some(successor));
+ }
+}
diff --git a/crates/pa-cli/src/update_flow/legacy_restart.rs b/crates/pa-cli/src/update_flow/legacy_restart.rs
new file mode 100644
index 0000000000..d0fbdc7467
--- /dev/null
+++ b/crates/pa-cli/src/update_flow/legacy_restart.rs
@@ -0,0 +1,735 @@
+//! Post-install restart handoff from shipped TypeScript updaters. Those
+//! callers have already activated the release and supply a fresh status path;
+//! they cannot enter the staged Rust activation transaction.
+
+use std::path::Path;
+use std::sync::Arc;
+use std::time::Duration;
+
+use anyhow::{Context, Result};
+use pa_types::daemon::update_flow::{
+ UpdateId, UpdateProcessIdentity, UpdateRoster, UpdateTimeoutBudget,
+};
+use pa_types::daemon::DaemonCommand;
+use serde_json::{json, Value};
+use tokio::sync::Mutex;
+
+use super::successor::{identity_from_hello, spawn_supervisor, wait_for_exit, wait_for_hello};
+
+pub(super) async fn run(
+ socket: &Path,
+ status_path: &Path,
+ agent_dir: &Path,
+ origin: Option<&str>,
+) -> Result<i32> {
+ let directories = super::legacy_admission::Admission::directories()?;
+ run_in(socket, status_path, agent_dir, origin, &directories).await
+}
+
+async fn run_in(
+ socket: &Path,
+ status_path: &Path,
+ agent_dir: &Path,
+ origin: Option<&str>,
+ directories: &[std::path::PathBuf],
+) -> Result<i32> {
+ let id = UpdateId::from(format!(
+ "legacy-{}-{}",
+ std::process::id(),
+ uuid::Uuid::new_v4()
+ ));
+ let now = crate::util_time::now_iso8601();
+ let status = Arc::new(Mutex::new(json!({
+ "version": 1, "requestId": id, "socketPath": socket,
+ "phase": "starting", "coordinator": super::status::coordinator_identity(),
+ "counts": {"total":0,"restored":0,"resumed":0,"failed":0},
+ "startedAt":now,"updatedAt":now,"heartbeatAt":now
+ })));
+ persist(status_path, &*status.lock().await)?;
+ let socket_text = socket.to_string_lossy();
+ match super::intent::acquire(agent_dir, &socket_text, &id, status_path)? {
+ super::intent::AcquireOutcome::Acquired => {}
+ super::intent::AcquireOutcome::Join { .. } => {
+ let mut value = status.lock().await;
+ value["phase"] = json!("failed");
+ value["message"] =
+ json!("Another update restart is already running; retry after it completes");
+ persist(status_path, &value)?;
+ return Ok(1);
+ }
+ }
+ let result = async {
+ let mut admission = super::legacy_admission::Admission::acquire(directories).await?;
+ let operation = restart(socket, status_path, agent_dir, &id, origin, &status);
+ tokio::pin!(operation);
+ let mut heartbeat = tokio::time::interval(Duration::from_secs(1));
+ let outcome = loop {
+ tokio::select! {
+ result = &mut operation => break result,
+ _ = heartbeat.tick() => {
+ if let Err(error) = admission.refresh().await {
+ break Err(error);
+ }
+ let mut value = status.lock().await;
+ value["heartbeatAt"] = json!(crate::util_time::now_iso8601());
+ if let Err(error) = persist(status_path, &value) {
+ break Err(error);
+ }
+ }
+ }
+ };
+ let release = admission.release().await;
+ outcome.and(release)
+ }
+ .await;
+ let mut value = status.lock().await;
+ if let Err(error) = &result {
+ value["phase"] = json!("failed");
+ value["message"] = json!(format!("{error:#}"));
+ }
+ value["updatedAt"] = json!(crate::util_time::now_iso8601());
+ let final_write = persist(status_path, &value);
+ let release = super::intent::release(agent_dir, &socket_text);
+ final_write?;
+ release?;
+ Ok(i32::from(result.is_err()))
+}
+
+async fn restart(
+ socket: &Path,
+ status_path: &Path,
+ agent_dir: &Path,
+ id: &UpdateId,
+ origin: Option<&str>,
+ status: &Arc<Mutex<Value>>,
+) -> Result<()> {
+ let budget = UpdateTimeoutBudget::from_env();
+ let recovery_dir = agent_dir.join("legacy-update-recovery");
+ let socket_key = pa_daemon::paths::hash_key(&socket.to_string_lossy(), 64);
+ let roster_path = recovery_dir.join(format!("{socket_key}.json"));
+ let attempt_path = recovery_dir.join(format!("{socket_key}.attempt.json"));
+ let source_path = agent_dir
+ .join("daemon-update-restarts")
+ .join(format!("{socket_key}.json"));
+ let connection = pa_tui::daemon_client::DaemonClient::connect(socket).await;
+ let (client, _events) = match connection {
+ Ok(connection) => connection,
+ Err(error) => {
+ // A reachable but incompatible daemon is not an absent daemon.
+ if pa_daemon::socket::can_connect(socket, Duration::from_secs(1)).await {
+ return Err(error).context("connect to the previous daemon");
+ }
+ match recover_prepared(&roster_path, &attempt_path, &source_path, socket, None)? {
+ Some(roster) => {
+ let predecessor = UpdateProcessIdentity {
+ pid: roster.supervisor.pid,
+ process_start_id: roster.supervisor.process_start_id.clone(),
+ supervisor_generation: Some(roster.supervisor.generation.clone()),
+ supervisor_owner_token: None,
+ rest: serde_json::Map::new(),
+ };
+ anyhow::ensure!(
+ wait_for_exit(&predecessor, budget.predecessor_exit_ms).await,
+ "the checkpoint predecessor has not verifiably exited"
+ );
+ return boot_roster(
+ socket,
+ status_path,
+ &roster_path,
+ &roster,
+ status,
+ &budget,
+ )
+ .await;
+ }
+ None => anyhow::ensure!(
+ !attempt_path.exists(),
+ "preparation attempt is pending; retain it until its manifest is available"
+ ),
+ }
+ status.lock().await["phase"] = json!("skipped");
+ return Ok(());
+ }
+ };
+ let hello = client.hello().clone();
+ let predecessor = identity_from_hello(&hello);
+ anyhow::ensure!(
+ predecessor.pid > 0,
+ "previous daemon supplied no process identity"
+ );
+ {
+ let mut value = status.lock().await;
+ value["phase"] = json!("preparing");
+ value["predecessor"] = json!(predecessor);
+ persist(status_path, &value)?;
+ }
+ let roster = if let Some(roster) = recover_prepared(
+ &roster_path,
+ &attempt_path,
+ &source_path,
+ socket,
+ Some(&hello),
+ )? {
+ roster
+ } else {
+ anyhow::ensure!(
+ !attempt_path.exists(),
+ "preparation attempt is pending; retry after its manifest is durable"
+ );
+ std::fs::create_dir_all(&recovery_dir)?;
+ // Write the owner binding before the RPC: TS commits and stops its
+ // workers before replying, so a disconnected caller must recover disk.
+ let previous = match std::fs::read_to_string(&source_path) {
+ Ok(text) => Some(pa_daemon::paths::hash_key(&text, 64)),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
+ Err(error) => return Err(error.into()),
+ };
+ persist(
+ &attempt_path,
+ &json!({
+ "socket": socket, "version": crate::config::version(), "hello": hello,
+ "startedAt": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis(),
+ "previousDigest": previous, "updateId": id, "origin": origin,
+ }),
+ )?;
+ let response = client
+ .request_with_timeout(
+ DaemonCommand::PrepareUpdateRestart {
+ id: None,
+ update_id: None,
+ rest: serde_json::Map::new(),
+ },
+ // The shipped TS coordinator allows 120s; its own preparation
+ // deadline is 100s, followed by worker commit and shutdown.
+ budget.prepare_ms.max(120_000),
+ )
+ .await;
+ let refused = response.as_ref().is_ok_and(|response| !response.success);
+ let manifest = match response {
+ Ok(response) if response.success => response
+ .data
+ .context("previous daemon supplied no session recovery manifest"),
+ Ok(response) => Err(anyhow::anyhow!(
+ "could not prepare TypeScript sessions: {}",
+ response.error.unwrap_or_default()
+ )),
+ Err(error) => {
+ Err(error).context("prepare TypeScript sessions before stopping the daemon")
+ }
+ };
+ match manifest {
+ Ok(manifest) => {
+ let roster = super::legacy_roster::convert(&manifest, &hello, id, socket, origin)?;
+ validate_recovery(&roster, socket, crate::config::version())?;
+ persist(&roster_path, &serde_json::to_value(&roster)?)?;
+ roster
+ }
+ Err(error) => {
+ if let Some(roster) = recover_prepared(
+ &roster_path,
+ &attempt_path,
+ &source_path,
+ socket,
+ Some(&hello),
+ )? {
+ roster
+ } else {
+ if refused {
+ std::fs::remove_file(&attempt_path)?;
+ }
+ return Err(error);
+ }
+ }
+ }
+ };
+ {
+ let mut value = status.lock().await;
+ value["phase"] = json!("stopping");
+ value["counts"]["total"] = json!(roster.sessions.len());
+ persist(status_path, &value)?;
+ }
+ // A lost prepare reply can also close the connection. Reconnect before
+ // shutdown and verify we still address the recorded predecessor.
+ drop(client);
+ let (client, _events) = pa_tui::daemon_client::DaemonClient::connect(socket).await?;
+ anyhow::ensure!(
+ identity_from_hello(client.hello()) == predecessor,
+ "predecessor changed before shutdown"
+ );
+ let shutdown = client
+ .request_ok(DaemonCommand::Shutdown {
+ id: None,
+ force: None,
+ rest: serde_json::Map::new(),
+ })
+ .await;
+ // TS shutdown waits for client sockets to close before exiting.
+ // Drop the writer here; `close()` alone leaves its channel alive.
+ drop(client);
+ anyhow::ensure!(
+ wait_for_exit(&predecessor, budget.predecessor_exit_ms).await,
+ "previous daemon did not stop: {shutdown:?}"
+ );
+ boot_roster(socket, status_path, &roster_path, &roster, status, &budget).await
+}
+
+// A source TS manifest contains no owner identity. Only adopt one written
+// during an attempt whose durable owner/socket binding we recorded ourselves.
+fn recover_prepared(
+ roster_path: &Path,
+ attempt_path: &Path,
+ source_path: &Path,
+ socket: &Path,
+ live_hello: Option<&Value>,
+) -> Result<Option<UpdateRoster>> {
+ let roster = match std::fs::read(roster_path) {
+ Ok(bytes) => Some(serde_json::from_slice::<UpdateRoster>(&bytes)?),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
+ Err(error) => return Err(error.into()),
+ };
+ if let Some(roster) = roster {
+ validate_recovery(&roster, socket, crate::config::version())?;
+ if let Some(hello) = live_hello {
+ let owner = identity_from_hello(hello);
+ anyhow::ensure!(
+ owner.pid == roster.supervisor.pid
+ && owner.process_start_id == roster.supervisor.process_start_id
+ && owner.supervisor_generation.as_deref()
+ == Some(roster.supervisor.generation.as_str()),
+ "recovery checkpoint belongs to another predecessor"
+ );
+ }
+ return Ok(Some(roster));
+ }
+ let attempt: Value = match std::fs::read(attempt_path) {
+ Ok(bytes) => serde_json::from_slice(&bytes)?,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(error) => return Err(error.into()),
+ };
+ anyhow::ensure!(
+ attempt["socket"] == socket.to_string_lossy().as_ref()
+ && attempt["version"] == crate::config::version(),
+ "prepared attempt belongs to another socket or release"
+ );
+ let recorded = identity_from_hello(&attempt["hello"]);
+ anyhow::ensure!(
+ recorded.pid > 0
+ && recorded.process_start_id.is_some()
+ && recorded.supervisor_generation.is_some(),
+ "prepared attempt has no fixed predecessor identity"
+ );
+ if let Some(hello) = live_hello {
+ anyhow::ensure!(
+ identity_from_hello(hello) == recorded,
+ "prepared attempt belongs to another predecessor"
+ );
+ }
+ let text = match std::fs::read_to_string(source_path) {
+ Ok(text) => text,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(error) => return Err(error.into()),
+ };
+ if attempt["previousDigest"] == pa_daemon::paths::hash_key(&text, 64) {
+ return Ok(None);
+ }
+ let modified = std::fs::metadata(source_path)?
+ .modified()?
+ .duration_since(std::time::UNIX_EPOCH)?
+ .as_millis();
+ let started = attempt["startedAt"]
+ .as_u64()
+ .context("prepared attempt has no start time")?;
+ anyhow::ensure!(
+ modified + 1000 >= u128::from(started),
+ "TypeScript recovery manifest is stale"
+ );
+ let manifest: Value = serde_json::from_str(&text)?;
+ let id: UpdateId = serde_json::from_value(attempt["updateId"].clone())?;
+ let roster = super::legacy_roster::convert(
+ &manifest,
+ &attempt["hello"],
+ &id,
+ socket,
+ attempt["origin"].as_str(),
+ )?;
+ validate_recovery(&roster, socket, crate::config::version())?;
+ persist(roster_path, &serde_json::to_value(&roster)?)?;
+ Ok(Some(roster))
+}
+
+fn validate_recovery(roster: &UpdateRoster, socket: &Path, version: &str) -> Result<()> {
+ anyhow::ensure!(
+ roster.socket_path == socket.to_string_lossy()
+ && roster.binary.to_version == version
+ && roster.format_version == 1
+ && roster.rest.get("legacy_ts_restart") == Some(&Value::Bool(true)),
+ "legacy recovery checkpoint does not match this socket and installed release"
+ );
+ Ok(())
+}
+
+async fn boot_roster(
+ socket: &Path,
+ status_path: &Path,
+ roster_path: &Path,
+ roster: &UpdateRoster,
+ status: &Arc<Mutex<Value>>,
+ budget: &UpdateTimeoutBudget,
+) -> Result<()> {
+ {
+ let mut value = status.lock().await;
+ value["phase"] = json!("starting_daemon");
+ persist(status_path, &value)?;
+ }
+ let spawned_pid = spawn_supervisor(
+ &std::env::current_exe()?,
+ socket,
+ Some(roster_path),
+ &std::env::current_dir()?,
+ )?;
+ let successor = wait_for_hello(socket, budget.boot_ms)
+ .await
+ .context("replacement daemon did not start")?;
+ anyhow::ensure!(
+ successor.pid == spawned_pid,
+ "a different daemon won the socket during migration"
+ );
+ let (replacement, _events) = pa_tui::daemon_client::DaemonClient::connect(socket).await?;
+ let replacement_hello = replacement.hello().clone();
+ replacement.close();
+ validate_successor(&replacement_hello, spawned_pid, crate::config::version())?;
+ {
+ let mut value = status.lock().await;
+ value["phase"] = json!("restoring");
+ value["successor"] = json!(successor);
+ persist(status_path, &value)?;
+ }
+ let (counts, failures) = super::phases::restore_report(socket, budget).await;
+ anyhow::ensure!(
+ counts.total == roster.sessions.len() as u64,
+ "replacement daemon did not finish restoring all migrated sessions"
+ );
+ {
+ let mut value = status.lock().await;
+ value["counts"] = json!(counts);
+ value["failures"] = json!(failures);
+ value["phase"] = json!("complete");
+ }
+ if counts.failed == 0 {
+ std::fs::remove_file(roster_path)?;
+ match std::fs::remove_file(roster_path.with_extension("attempt.json")) {
+ Ok(()) => {}
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
+ Err(error) => return Err(error.into()),
+ }
+ }
+ Ok(())
+}
+
+fn validate_successor(hello: &Value, pid: u64, version: &str) -> Result<()> {
+ anyhow::ensure!(
+ hello.get("appVersion").and_then(Value::as_str) == Some(version)
+ && hello.get("schemaId").and_then(Value::as_str)
+ == Some(pa_types::daemon::DAEMON_SCHEMA_ID)
+ && hello.get("supervisorPid").and_then(Value::as_u64) == Some(pid),
+ "replacement daemon does not match the spawned process and installed release"
+ );
+ Ok(())
+}
+
+pub(super) fn persist(path: &Path, value: &Value) -> Result<()> {
+ use std::io::Write;
+ let temporary = path.with_extension(format!("{}.tmp", std::process::id()));
+ let mut options = std::fs::OpenOptions::new();
+ options.write(true).create(true).truncate(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ let mut file = options.open(&temporary)?;
+ serde_json::to_writer(&mut file, value)?;
+ file.write_all(b"\n")?;
+ file.sync_all()?;
+ std::fs::rename(temporary, path)?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn lost_prepare_reply_adopts_durable_manifest_before_shutdown() {
+ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+ let directory = tempfile::tempdir().unwrap();
+ let socket = directory.path().join("old.sock");
+ let source = directory.path().join("daemon-update-restarts");
+ std::fs::create_dir(&source).unwrap();
+ let key = pa_daemon::paths::hash_key(&socket.to_string_lossy(), 64);
+ let source = source.join(format!("{key}.json"));
+ let checkpoint = directory
+ .path()
+ .join("legacy-update-recovery")
+ .join(format!("{key}.json"));
+ let listener = tokio::net::UnixListener::bind(&socket).unwrap();
+ let (sent, received) = tokio::sync::oneshot::channel();
+ let source_copy = source.clone();
+ let next_turn = json!([{"customType":"pending","content":"queued witness","display":false,"timestamp":1}]);
+ let actions = json!({"formatVersion":1,"actions":[{"payload":{"kind":"turn","message":"queued action"}}]});
+ let manifest = json!({"formatVersion":1,"createdAt":"2026-10-09T00:00:00Z","sessions":[{
+ "activeSessionId":"old-active", "sessionId":"durable-session", "sessionFile":"/sessions/test.jsonl",
+ "cwd":"/project", "config":{}, "queue":{"nextTurn":next_turn,"actions":actions}, "shouldResume":true
+ }]});
+ let hello = json!({"type":"daemon_hello", "supervisorPid":std::process::id(),
+ "supervisorProcessStartId":"fixed-start", "supervisorGeneration":"generation",
+ "appVersion":"0.6.0", "protocol":{"name":"prime-agent.daemon","version":7}});
+ let owner = hello.clone();
+ let server = tokio::spawn(async move {
+ for phase in ["prepare_update_restart", "shutdown"] {
+ let (stream, _) = listener.accept().await.unwrap();
+ let (read, mut write) = stream.into_split();
+ write
+ .write_all(format!("{hello}\n").as_bytes())
+ .await
+ .unwrap();
+ let mut lines = BufReader::new(read).lines();
+ let command: Value =
+ serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
+ assert_eq!(command["command"]["type"], phase);
+ if phase == "prepare_update_restart" {
+ persist(&source_copy, &manifest).unwrap();
+ // The durable commit succeeds but its response disappears.
+ drop(write);
+ } else {
+ sent.send(()).unwrap();
+ std::future::pending::<()>().await;
+ return;
+ }
+ }
+ });
+ let task_dir = directory.path().to_path_buf();
+ let task_socket = socket.clone();
+ let operation = tokio::spawn(async move {
+ run_in(
+ &task_socket,
+ &task_dir.join("status.json"),
+ &task_dir,
+ None,
+ &[task_dir.join("owners")],
+ )
+ .await
+ });
+ tokio::time::timeout(Duration::from_secs(5), received)
+ .await
+ .expect("lost reply must recover and reach shutdown")
+ .unwrap();
+ operation.abort();
+ server.abort();
+ let _ = operation.await;
+ let _ = server.await;
+ assert!(source.exists(), "retain the TS source until adoption");
+ let roster = recover_prepared(
+ &checkpoint,
+ &checkpoint.with_extension("attempt.json"),
+ &source,
+ &socket,
+ Some(&owner),
+ )
+ .unwrap()
+ .unwrap();
+ assert_eq!(roster.supervisor.pid, u64::from(std::process::id()));
+ assert_eq!(
+ serde_json::to_value(&roster.sessions[0].queue).unwrap(),
+ json!({"next_turn":next_turn,"actions":actions})
+ );
+ let mut other = owner;
+ other["supervisorProcessStartId"] = json!("replacement-start");
+ assert!(recover_prepared(
+ &checkpoint,
+ &checkpoint.with_extension("attempt.json"),
+ &source,
+ &socket,
+ Some(&other)
+ )
+ .is_err());
+ }
+
+ #[test]
+ fn persisted_manifest_must_be_new_for_the_recorded_attempt() {
+ let directory = tempfile::tempdir().unwrap();
+ let socket = directory.path().join("daemon.sock");
+ let source = directory.path().join("source.json");
+ let attempt = directory.path().join("attempt.json");
+ let checkpoint = directory.path().join("roster.json");
+ let manifest = json!({"formatVersion":1,"createdAt":"now","sessions":[]});
+ persist(&source, &manifest).unwrap();
+ let digest = pa_daemon::paths::hash_key(&std::fs::read_to_string(&source).unwrap(), 64);
+ persist(&attempt, &json!({"socket":socket,"version":crate::config::version(),
+ "hello":{"supervisorPid":42,"supervisorProcessStartId":"start","supervisorGeneration":"generation"},
+ "startedAt":0,"previousDigest":digest,"updateId":"old-attempt"})).unwrap();
+ assert!(
+ recover_prepared(&checkpoint, &attempt, &source, &socket, None)
+ .unwrap()
+ .is_none()
+ );
+ assert!(!checkpoint.exists());
+ }
+
+ #[test]
+ fn successor_must_be_the_spawned_process_with_the_expected_schema() {
+ let hello = json!({"appVersion":"1.0.0","schemaId":pa_types::daemon::DAEMON_SCHEMA_ID,"supervisorPid":42});
+ assert!(validate_successor(&hello, 42, "1.0.0").is_ok());
+ assert!(validate_successor(&hello, 43, "1.0.0").is_err());
+ assert!(validate_successor(&hello, 42, "1.0.1").is_err());
+ let mut wrong_schema = hello;
+ wrong_schema["schemaId"] = json!("old-typescript-schema");
+ assert!(validate_successor(&wrong_schema, 42, "1.0.0").is_err());
+ }
+
+ #[tokio::test]
+ async fn absent_daemon_does_not_skip_an_incompatible_recovery_checkpoint() {
+ let directory = tempfile::tempdir().unwrap();
+ let socket = directory.path().join("absent.sock");
+ let recovery = directory.path().join("legacy-update-recovery");
+ std::fs::create_dir(&recovery).unwrap();
+ let mut roster = super::super::legacy_roster::convert(
+ &json!({"formatVersion":1,"createdAt":"2026-10-09T00:00:00.000Z","sessions":[]}),
+ &json!({"supervisorPid":42,"appVersion":"0.9.8"}),
+ &UpdateId::from("previous-attempt".to_string()),
+ &socket,
+ None,
+ )
+ .unwrap();
+ assert!(validate_recovery(&roster, &socket, crate::config::version()).is_ok());
+ roster.binary.to_version = "a-different-release".to_string();
+ let key = pa_daemon::paths::hash_key(&socket.to_string_lossy(), 64);
+ let checkpoint = recovery.join(format!("{key}.json"));
+ persist(&checkpoint, &serde_json::to_value(&roster).unwrap()).unwrap();
+ let status_path = directory.path().join("status.json");
+ assert_eq!(
+ run_in(
+ &socket,
+ &status_path,
+ directory.path(),
+ None,
+ &[directory.path().join("registry")]
+ )
+ .await
+ .unwrap(),
+ 1
+ );
+ let status: Value = serde_json::from_slice(&std::fs::read(status_path).unwrap()).unwrap();
+ assert_eq!(status["phase"], "failed");
+ assert!(
+ checkpoint.exists(),
+ "keep the checkpoint for deliberate recovery"
+ );
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn preparation_refusal_reports_failure_without_stopping_the_old_daemon() {
+ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+ let directory = tempfile::tempdir().unwrap();
+ let socket = directory.path().join("old.sock");
+ let status_path = directory.path().join("status.json");
+ let source_dir = directory.path().join("daemon-update-restarts");
+ std::fs::create_dir(&source_dir).unwrap();
+ let key = pa_daemon::paths::hash_key(&socket.to_string_lossy(), 64);
+ persist(
+ &source_dir.join(format!("{key}.json")),
+ &json!({"formatVersion":1,"createdAt":"old","sessions":[]}),
+ )
+ .unwrap();
+ let listener = tokio::net::UnixListener::bind(&socket).unwrap();
+ let server = tokio::spawn(async move {
+ let (stream, _) = listener.accept().await.unwrap();
+ let (read, mut write) = stream.into_split();
+ let hello = json!({"type":"daemon_hello","supervisorPid":std::process::id(),
+ "supervisorProcessStartId":"start", "supervisorGeneration":"generation",
+ "protocol":{"name":"prime-agent.daemon","version":7}});
+ write
+ .write_all(format!("{hello}\n").as_bytes())
+ .await
+ .unwrap();
+ let mut lines = BufReader::new(read).lines();
+ let command: Value =
+ serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
+ assert_eq!(command["command"]["type"], "prepare_update_restart");
+ assert!(command["command"].get("updateId").is_none());
+ let response = json!({"type":"response","id":command["id"],"command":"prepare_update_restart",
+ "success":false,"error":"session checkpoint failed"});
+ write
+ .write_all(format!("{response}\n").as_bytes())
+ .await
+ .unwrap();
+ while let Some(line) = lines.next_line().await.unwrap() {
+ assert!(line.is_empty(), "no shutdown command after refusal: {line}");
+ }
+ });
+ assert_eq!(
+ run_in(
+ &socket,
+ &status_path,
+ directory.path(),
+ None,
+ &[directory.path().join("registry")]
+ )
+ .await
+ .unwrap(),
+ 1
+ );
+ tokio::time::timeout(Duration::from_secs(5), server)
+ .await
+ .expect("the refused connection closes")
+ .unwrap();
+ let status: Value = serde_json::from_slice(&std::fs::read(status_path).unwrap()).unwrap();
+ assert_eq!(status["phase"], "failed");
+ let key = pa_daemon::paths::hash_key(&socket.to_string_lossy(), 64);
+ assert!(
+ !directory
+ .path()
+ .join("legacy-update-recovery")
+ .join(format!("{key}.attempt.json"))
+ .exists(),
+ "definitive refusal must not block a fresh attempt"
+ );
+ assert!(status["message"]
+ .as_str()
+ .unwrap()
+ .contains("session checkpoint failed"));
+ }
+
+ #[tokio::test]
+ async fn legacy_caller_without_a_staged_status_receives_a_ts_terminal_record() {
+ let directory = tempfile::tempdir().unwrap();
+ let socket = directory.path().join("absent.sock");
+ let status_path = directory.path().join("status.json");
+ assert_eq!(
+ run_in(
+ &socket,
+ &status_path,
+ directory.path(),
+ None,
+ &[directory.path().join("registry")]
+ )
+ .await
+ .unwrap(),
+ 0
+ );
+ let status: Value = serde_json::from_slice(&std::fs::read(status_path).unwrap()).unwrap();
+ assert_eq!(status["phase"], "skipped");
+ assert_eq!(status["version"], 1);
+ assert!(status["requestId"].is_string());
+ assert!(status["coordinator"]["pid"].as_u64().unwrap() > 0);
+ assert_eq!(
+ status["counts"],
+ json!({"total":0,"restored":0,"resumed":0,"failed":0})
+ );
+ for field in ["startedAt", "updatedAt", "heartbeatAt"] {
+ assert!(status[field].is_string(), "{field}");
+ }
+ }
+}
diff --git a/crates/pa-cli/src/update_flow/legacy_roster.rs b/crates/pa-cli/src/update_flow/legacy_roster.rs
new file mode 100644
index 0000000000..eb8d07ee25
--- /dev/null
+++ b/crates/pa-cli/src/update_flow/legacy_roster.rs
@@ -0,0 +1,325 @@
+//! Translate the released TypeScript restart checkpoint into the Rust restore roster.
+//! The create command deliberately mirrors the TS restore call: configuration,
+//! client environment, and runtime metadata belong to the resumed session.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::Path;
+
+use anyhow::{ensure, Context, Result};
+use pa_types::daemon::{
+ UpdateId, UpdateRoster, UpdateRosterBinary, UpdateRosterInFlight, UpdateRosterQueue,
+ UpdateRosterSession, UpdateRosterSessionKind, UpdateSupervisorIdentity,
+ UPDATE_ROSTER_FORMAT_VERSION,
+};
+use serde::Deserialize;
+use serde_json::{json, Map, Value};
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct LegacyManifest {
+ format_version: u64,
+ created_at: String,
+ sessions: Vec<LegacySession>,
+ #[serde(flatten)]
+ rest: Map<String, Value>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct LegacyQueue {
+ next_turn: Vec<pa_types::session::CustomMessage>,
+ actions: Value,
+}
+
+#[allow(clippy::struct_excessive_bools)] // The released TS wire format has independent activity flags.
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct LegacySession {
+ active_session_id: String,
+ session_id: String,
+ session_file: String,
+ cwd: String,
+ config: Map<String, Value>,
+ runtime_metadata: Option<Map<String, Value>>,
+ client_env: Option<BTreeMap<String, String>>,
+ queue: LegacyQueue,
+ should_resume: bool,
+ #[serde(default)]
+ was_streaming: bool,
+ #[serde(default)]
+ was_compacting: bool,
+ #[serde(default)]
+ was_bash_running: bool,
+ #[serde(default)]
+ had_running_rlm_children: bool,
+ #[serde(default)]
+ was_retrying: bool,
+ #[serde(default)]
+ had_accepted_prompt_in_flight: bool,
+}
+
+// Keep the wire-to-roster field mapping together so omissions are reviewable.
+#[allow(clippy::too_many_lines)]
+pub(super) fn convert(
+ manifest: &Value,
+ hello: &Value,
+ update_id: &UpdateId,
+ socket_path: &Path,
+ origin: Option<&str>,
+) -> Result<UpdateRoster> {
+ let manifest: LegacyManifest =
+ serde_json::from_value(manifest.clone()).context("parse TypeScript update checkpoint")?;
+ ensure!(
+ manifest.format_version == 1,
+ "unsupported TypeScript update checkpoint version"
+ );
+ let active_ids: BTreeMap<_, _> = manifest
+ .sessions
+ .iter()
+ .map(|session| {
+ (
+ session.active_session_id.clone(),
+ session.session_id.clone(),
+ )
+ })
+ .collect();
+ let files: BTreeMap<_, _> = manifest
+ .sessions
+ .iter()
+ .map(|session| (session.session_file.clone(), session.session_id.clone()))
+ .collect();
+ let mut session_ids = BTreeSet::new();
+ let mut sessions = Vec::with_capacity(manifest.sessions.len());
+ for session in manifest.sessions {
+ ensure!(
+ !session.session_id.is_empty()
+ && !session.active_session_id.is_empty()
+ && !session.session_file.is_empty(),
+ "TypeScript checkpoint contains an empty session identity"
+ );
+ ensure!(
+ session_ids.insert(session.session_id.clone()),
+ "TypeScript checkpoint contains duplicate session ids"
+ );
+ let runtime = session.runtime_metadata.as_ref();
+ let kind = match runtime
+ .and_then(|metadata| metadata.get("kind"))
+ .and_then(Value::as_str)
+ {
+ Some("subagent") => UpdateRosterSessionKind::Subagent,
+ Some("top-level") | None => UpdateRosterSessionKind::TopLevel,
+ Some(kind) => anyhow::bail!("unsupported TypeScript session kind: {kind}"),
+ };
+ let parent_session_id = runtime.and_then(|metadata| {
+ metadata
+ .get("parentSessionId")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ .or_else(|| {
+ metadata
+ .get("parentActiveSessionId")
+ .and_then(Value::as_str)
+ .and_then(|id| active_ids.get(id))
+ .cloned()
+ })
+ .or_else(|| {
+ metadata
+ .get("parentSessionFile")
+ .and_then(Value::as_str)
+ .and_then(|file| files.get(file))
+ .cloned()
+ })
+ });
+ let mut create = json!({"sessionPath": session.session_file, "cwd": session.cwd, "config": session.config});
+ if let Some(metadata) = session.runtime_metadata {
+ create["runtimeMetadata"] = Value::Object(metadata);
+ }
+ if let Some(env) = session.client_env {
+ create["env"] = serde_json::to_value(env)?;
+ }
+ sessions.push(UpdateRosterSession {
+ session_id: session.session_id,
+ active_session_id: session.active_session_id,
+ session_file: session.session_file,
+ name: None,
+ kind,
+ parent_session_id,
+ rlm_depth: 0,
+ cwd: session.cwd,
+ runtime_config: json!({"create": create}),
+ queue: UpdateRosterQueue {
+ next_turn: session.queue.next_turn,
+ actions: session.queue.actions,
+ },
+ in_flight: UpdateRosterInFlight {
+ streaming: session.was_streaming,
+ compacting: session.was_compacting,
+ bash_running: session.was_bash_running,
+ rlm_children: session.had_running_rlm_children,
+ retrying: session.was_retrying,
+ prompt_in_flight: session.had_accepted_prompt_in_flight,
+ },
+ should_resume: session.should_resume,
+ rest: Map::new(),
+ });
+ }
+ ensure!(
+ active_ids.len() == sessions.len(),
+ "TypeScript checkpoint contains duplicate active session ids"
+ );
+ let parents: BTreeMap<_, _> = sessions
+ .iter()
+ .map(|session| {
+ (
+ session.session_id.clone(),
+ session.parent_session_id.clone(),
+ )
+ })
+ .collect();
+ for session in &mut sessions {
+ let mut visited = BTreeSet::from([session.session_id.clone()]);
+ let mut parent = session.parent_session_id.as_ref();
+ while let Some(id) = parent {
+ ensure!(
+ visited.insert(id.clone()),
+ "TypeScript checkpoint contains cyclic session parents"
+ );
+ session.rlm_depth += 1;
+ parent = parents.get(id).and_then(Option::as_ref);
+ }
+ }
+ let mut rest = manifest.rest;
+ rest.insert("legacy_ts_restart".into(), Value::Bool(true));
+ if let Some(origin) = origin {
+ rest.insert("restart_origin_active_session_id".into(), json!(origin));
+ }
+ Ok(UpdateRoster {
+ format_version: UPDATE_ROSTER_FORMAT_VERSION,
+ update_id: update_id.clone(),
+ socket_path: socket_path.to_string_lossy().into_owned(),
+ created_at: manifest.created_at,
+ supervisor: UpdateSupervisorIdentity {
+ pid: hello
+ .get("supervisorPid")
+ .and_then(Value::as_u64)
+ .unwrap_or_default(),
+ process_start_id: hello
+ .get("supervisorProcessStartId")
+ .and_then(Value::as_str)
+ .map(str::to_string),
+ generation: hello
+ .get("supervisorGeneration")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string(),
+ },
+ binary: UpdateRosterBinary {
+ from_version: hello
+ .get("appVersion")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string(),
+ to_version: crate::config::version().to_string(),
+ },
+ sessions,
+ workers: Vec::new(),
+ subagents: Vec::new(),
+ heartbeats: Vec::new(),
+ rest,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn session(id: &str, metadata: &Value) -> Value {
+ json!({
+ "activeSessionId": format!("active-{id}"), "sessionId": id,
+ "sessionFile": format!("/sessions/{id}.jsonl"), "cwd": "/project",
+ "config": {"modelId": "model", "thinkingLevel": "high"},
+ "runtimeMetadata": metadata, "clientEnv": {"TEST_VAR": "preserved"},
+ "queue": {"nextTurn": [{"customType": "note", "content": "pending", "display": false, "timestamp": 1}],
+ "actions": {"formatVersion": 1, "actions": [{"payload": {"kind": "turn", "message": "queued"}}]}},
+ "shouldResume": true, "wasStreaming": false, "wasCompacting": true,
+ "wasBashRunning": true, "hadRunningRlmChildren": true,
+ "wasRetrying": true, "hadAcceptedPromptInFlight": true
+ })
+ }
+
+ #[test]
+ fn conversion_preserves_restore_inputs_and_parent_topology() {
+ let metadata = json!({"kind": "subagent", "parentActiveSessionId": "active-parent", "rlmChildId": "child-1", "createdAt": 1});
+ let child = session("child", &metadata);
+ let parent = session("parent", &json!({"kind": "top-level", "createdAt": 1}));
+ let manifest = json!({"formatVersion": 1, "createdAt": "now", "sessions": [child, parent], "discardedActiveSessionIds": ["gone"]});
+ let actual = convert(
+ &manifest,
+ &json!({"appVersion": "0.9.8", "supervisorPid": 42, "supervisorGeneration": "old"}),
+ &UpdateId("migration".into()),
+ Path::new("/daemon.sock"),
+ Some("active-parent"),
+ )
+ .unwrap();
+ let expected: UpdateRosterSession = serde_json::from_value(json!({
+ "session_id": "child", "active_session_id": "active-child", "session_file": "/sessions/child.jsonl",
+ "kind": "subagent", "parent_session_id": "parent", "rlm_depth": 1, "cwd": "/project",
+ "runtime_config": {"create": {"sessionPath": "/sessions/child.jsonl", "cwd": "/project",
+ "config": {"modelId": "model", "thinkingLevel": "high"}, "runtimeMetadata": metadata,
+ "env": {"TEST_VAR": "preserved"}}},
+ "queue": {"next_turn": manifest["sessions"][0]["queue"]["nextTurn"], "actions": manifest["sessions"][0]["queue"]["actions"]},
+ "in_flight": {"streaming": false, "compacting": true, "bash_running": true, "rlm_children": true, "retrying": true, "prompt_in_flight": true},
+ "should_resume": true
+ })).unwrap();
+ assert_eq!(actual.sessions[0], expected);
+ assert_eq!(actual.rest, serde_json::from_value::<Map<String, Value>>(json!({"legacy_ts_restart": true, "restart_origin_active_session_id": "active-parent", "discardedActiveSessionIds": ["gone"]})).unwrap());
+ }
+
+ #[test]
+ fn earlier_checkpoints_without_newer_activity_flags_remain_restorable() {
+ let mut legacy = session("idle", &Value::Null);
+ let value = legacy.as_object_mut().unwrap();
+ for flag in [
+ "wasStreaming",
+ "wasCompacting",
+ "wasBashRunning",
+ "hadRunningRlmChildren",
+ "wasRetrying",
+ "hadAcceptedPromptInFlight",
+ ] {
+ value.remove(flag);
+ }
+ value.insert("shouldResume".into(), Value::Bool(false));
+ let manifest = json!({"formatVersion": 1, "createdAt": "now", "sessions": [legacy]});
+ let actual = convert(
+ &manifest,
+ &json!({}),
+ &UpdateId("u".into()),
+ Path::new("/s"),
+ None,
+ )
+ .unwrap();
+ assert_eq!(
+ (
+ actual.sessions[0].in_flight,
+ actual.sessions[0].should_resume
+ ),
+ (UpdateRosterInFlight::default(), false)
+ );
+ }
+
+ #[test]
+ fn conversion_rejects_cycles_instead_of_hanging_during_restore_ordering() {
+ let manifest = json!({"formatVersion": 1, "createdAt": "now", "sessions": [session("parent", &json!({"kind": "subagent", "parentSessionId": "parent"}))]});
+ assert!(convert(
+ &manifest,
+ &json!({}),
+ &UpdateId("u".into()),
+ Path::new("/s"),
+ None
+ )
+ .unwrap_err()
+ .to_string()
+ .contains("cyclic"));
+ }
+}
diff --git a/crates/pa-cli/src/update_flow/mod.rs b/crates/pa-cli/src/update_flow/mod.rs
index 6fd69d353d..7bd1b855db 100644
--- a/crates/pa-cli/src/update_flow/mod.rs
+++ b/crates/pa-cli/src/update_flow/mod.rs
@@ -5,6 +5,9 @@
pub mod coordinator;
pub mod intent;
+mod legacy_admission;
+mod legacy_restart;
+mod legacy_roster;
pub mod phases;
pub mod plan;
pub mod report;
diff --git a/crates/pa-cli/src/update_flow/plan.rs b/crates/pa-cli/src/update_flow/plan.rs
index 051c9ead1d..9856719681 100644
--- a/crates/pa-cli/src/update_flow/plan.rs
+++ b/crates/pa-cli/src/update_flow/plan.rs
@@ -194,7 +194,9 @@ pub async fn plan(
current_platform_alias()
)
})?;
- let archive_url = format!("{base_url}/{}", artifact.file);
+ // Channel manifests carry a basename; immutable assets and checksums
+ // live under releases/v<version>, just as the shipped TS installer reads.
+ let archive_url = format!("{base_url}/releases/v{}/{}", release.version, artifact.file);
let archive_sha256 = artifact.sha256.clone();
Ok(UpdatePlan::Update {
version: release.version,
diff --git a/crates/pa-cli/src/update_flow/status.rs b/crates/pa-cli/src/update_flow/status.rs
index 178bde9330..99250c85cd 100644
--- a/crates/pa-cli/src/update_flow/status.rs
+++ b/crates/pa-cli/src/update_flow/status.rs
@@ -80,11 +80,17 @@ impl StatusWriter {
/// # Errors
/// Returns an error when the adopted status record cannot be persisted.
pub fn adopt(path: &Path, update_id: &UpdateId, socket_path: &str) -> Result<Self> {
- let mut writer = Self::fresh(path, update_id, socket_path);
- if let Some(existing) = read_status(path) {
- writer.status.epoch = existing.epoch + 1;
- writer.status.started_at = existing.started_at;
- }
+ let status = read_status(path).context("read the staged coordinator status")?;
+ anyhow::ensure!(
+ status.update_id == *update_id && status.socket_path == socket_path,
+ "the staged coordinator status belongs to another update"
+ );
+ let mut writer = Self {
+ path: path.to_path_buf(),
+ status,
+ };
+ writer.status.coordinator = Some(coordinator_identity());
+ writer.touch();
writer
.persist()
.context("write the adopted coordinator status")?;
@@ -291,25 +297,32 @@ mod tests {
async fn adoption_continues_the_epoch_above_the_predecessor() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("status.json");
- let predecessor_epoch = {
+ let predecessor = {
// The predecessor drives the spec's legal path to `Staged`: the coordinator's
// `set_state` asserts the transition table.
let mut writer = StatusWriter::new(&path, &update_id(), "/tmp/s.sock").unwrap();
writer.set_state(UpdateState::Planning).unwrap();
writer.set_state(UpdateState::Downloading).unwrap();
writer.set_state(UpdateState::Staged).unwrap();
- writer.current().epoch
+ writer
+ .set_message(Some("candidate verified".to_string()))
+ .unwrap();
+ writer.current().clone()
};
- let successor = StatusWriter::adopt(&path, &update_id(), "/tmp/s.sock").unwrap();
- assert!(successor.current().epoch > predecessor_epoch);
+ let mut successor = StatusWriter::adopt(&path, &update_id(), "/tmp/s.sock").unwrap();
assert_eq!(
- successor.current().started_at,
- read_status(&path).unwrap().started_at
+ read_status(&path).unwrap(),
+ UpdateStatus {
+ epoch: predecessor.epoch + 1,
+ coordinator: Some(coordinator_identity()),
+ updated_at: successor.current().updated_at.clone(),
+ heartbeat_at: successor.current().heartbeat_at.clone(),
+ ..predecessor
+ }
);
- // The adopted status file still parses with the TS schema.
- let read = read_status(&path).unwrap();
- assert_eq!(read.state, UpdateState::Acquire);
- assert!(read.epoch > predecessor_epoch);
+ // The next real coordinator transition must remain legal after handoff.
+ successor.set_state(UpdateState::Preparing).unwrap();
+ assert_eq!(read_status(&path).unwrap(), *successor.current());
}
#[tokio::test]
diff --git a/crates/pa-cli/src/update_flow/successor.rs b/crates/pa-cli/src/update_flow/successor.rs
index 3dc4eb6474..890a0344bd 100644
--- a/crates/pa-cli/src/update_flow/successor.rs
+++ b/crates/pa-cli/src/update_flow/successor.rs
@@ -104,19 +104,14 @@ pub async fn wait_for_hello(socket_path: &Path, budget_ms: u64) -> Option<Update
pub async fn wait_for_exit(identity: &UpdateProcessIdentity, budget_ms: u64) -> bool {
let deadline = Instant::now() + Duration::from_millis(budget_ms.max(1));
loop {
- let Ok(alive) = pa_daemon::lease::is_process_alive(identity.pid as u32) else {
- return true;
- };
- let start_id_matches = match &identity.process_start_id {
- None => true,
- Some(expected) => {
- matches!(
- pa_daemon::lease::get_process_start_id(identity.pid as u32),
- Some(observed) if &observed == expected
- )
- }
+ let Ok(pid) = u32::try_from(identity.pid) else {
+ return false;
};
- if !alive || !start_id_matches {
+ if process_exit_observed(
+ pa_daemon::lease::is_process_alive(pid).ok(),
+ identity.process_start_id.as_deref(),
+ pa_daemon::lease::get_process_start_id(pid).as_deref(),
+ ) {
return true;
}
if Instant::now() + BOOT_POLL >= deadline {
@@ -126,6 +121,16 @@ pub async fn wait_for_exit(identity: &UpdateProcessIdentity, budget_ms: u64) ->
}
}
+/// Only a known-dead PID or an observed different birth identity proves exit.
+fn process_exit_observed(
+ alive: Option<bool>,
+ expected: Option<&str>,
+ observed: Option<&str>,
+) -> bool {
+ alive == Some(false)
+ || matches!((alive, expected, observed), (Some(true), Some(expected), Some(observed)) if expected != observed)
+}
+
#[cfg(test)]
mod tests {
use std::path::PathBuf;
@@ -133,6 +138,24 @@ mod tests {
use super::*;
use serde_json::json;
+ #[test]
+ fn unknown_process_probes_do_not_prove_predecessor_exit() {
+ assert!(!process_exit_observed(None, Some("birth"), None));
+ assert!(!process_exit_observed(Some(true), Some("birth"), None));
+ assert!(!process_exit_observed(Some(true), None, Some("birth")));
+ assert!(!process_exit_observed(
+ Some(true),
+ Some("birth"),
+ Some("birth")
+ ));
+ assert!(process_exit_observed(Some(false), Some("birth"), None));
+ assert!(process_exit_observed(
+ Some(true),
+ Some("birth"),
+ Some("new-birth")
+ ));
+ }
+
#[test]
fn identity_maps_the_hello_frame_fields() {
let identity = identity_from_hello(&json!({
diff --git a/crates/pa-cli/src/update_flow/update_command.rs b/crates/pa-cli/src/update_flow/update_command.rs
index 085601952a..a72ebef74e 100644
--- a/crates/pa-cli/src/update_flow/update_command.rs
+++ b/crates/pa-cli/src/update_flow/update_command.rs
@@ -202,7 +202,7 @@ pub async fn run_update_command(options: &UpdateCommandOptions) -> Result<i32> {
pa_core::platform::process::set_new_session(&mut command);
#[cfg(not(unix))]
pa_core::platform::process::set_new_process_group(&mut command);
- let child = command.spawn().with_context(|| {
+ let mut child = command.spawn().with_context(|| {
format!(
"spawn the update coordinator at {}",
coordinator_exe.display()
@@ -215,15 +215,20 @@ pub async fn run_update_command(options: &UpdateCommandOptions) -> Result<i32> {
u64::from(child.id()),
&status_path,
)?;
- drop(child);
-
- let status = tail_status_with(&status_path, &mut |observed, _fresh| {
+ let status = tail_status_with(&status_path, Some(&mut child), &mut |observed, _fresh| {
phases.phase(observed);
if let Some(line) = phase_status_line(observed.state) {
println!("{line}");
}
})
.await;
+ // Reap even when a terminal status arrives before process teardown. A
+ // plain thread does not hold the async runtime open for a detached child.
+ std::thread::spawn(move || {
+ if let Err(error) = child.wait() {
+ eprintln!("Warning: could not reap the update coordinator: {error}");
+ }
+ });
phases.finish().await;
track_update_completed(&status).await;
print_terminal(&status);
@@ -269,13 +274,14 @@ async fn plan_direct(
/// Tail the coordinator's status file to a terminal state: progress, liveness, and the holder's
/// process lifetime all bound the wait.
async fn tail_status(status_path: &std::path::Path) -> UpdateStatus {
- tail_status_with(status_path, &mut |_, _| {}).await
+ tail_status_with(status_path, /*coordinator*/ None, &mut |_, _| {}).await
}
/// The tail with per-transition observers (§11: the CLI status line and the
/// `update_<phase>` telemetry derive from the same status-file transitions).
async fn tail_status_with(
status_path: &std::path::Path,
+ mut coordinator: Option<&mut std::process::Child>,
observe: &mut dyn FnMut(&UpdateStatus, bool),
) -> UpdateStatus {
let started = std::time::Instant::now();
@@ -307,6 +313,31 @@ async fn tail_status_with(
} else if missing_since.is_none() && last_epoch.is_some() {
missing_since = Some(std::time::Instant::now());
}
+ if let Some(child) = coordinator.as_deref_mut() {
+ match child.try_wait() {
+ Ok(Some(exit)) => {
+ // A final write can race the status read immediately above.
+ if let Some(status) =
+ read_status(status_path).filter(|status| status.state.is_terminal())
+ {
+ return status;
+ }
+ return unreported(
+ status_path,
+ &format!(
+ "the update coordinator exited with {exit} before reporting completion"
+ ),
+ );
+ }
+ Ok(None) => {}
+ Err(error) => {
+ return unreported(
+ status_path,
+ &format!("could not check the update coordinator: {error}"),
+ );
+ }
+ }
+ }
let swept = missing_since
.is_some_and(|seen| (seen.elapsed().as_millis() as u64) < TAIL_SWEEP_GRACE_MS);
if !swept && last_liveness.elapsed().as_millis() as u64 >= TAIL_LIVENESS_TIMEOUT_MS {
@@ -323,7 +354,7 @@ async fn tail_status_with(
}
fn unreported(status_path: &std::path::Path, message: &str) -> UpdateStatus {
- read_status(status_path).unwrap_or_else(|| UpdateStatus {
+ let mut status = read_status(status_path).unwrap_or_else(|| UpdateStatus {
version: 1,
update_id: pa_types::daemon::update_flow::UpdateId::from(String::new()),
socket_path: String::new(),
@@ -339,7 +370,10 @@ fn unreported(status_path: &std::path::Path, message: &str) -> UpdateStatus {
updated_at: String::new(),
heartbeat_at: None,
rest: serde_json::Map::default(),
- })
+ });
+ status.state = UpdateState::Failed;
+ status.message = Some(message.to_string());
+ status
}
fn print_terminal(status: &UpdateStatus) {
@@ -589,7 +623,11 @@ async fn track_update_completed(status: &UpdateStatus) {
/// # Errors
/// Returns an error when adoption or a status write fails; an invalid
/// invocation is reported on stderr and returns `Ok(1)`.
-pub async fn run_coordinator_mode(socket_path: PathBuf, status_path: PathBuf) -> Result<i32> {
+pub async fn run_coordinator_mode(
+ socket_path: PathBuf,
+ status_path: PathBuf,
+ origin: Option<&str>,
+) -> Result<i32> {
let agent_dir = crate::config::get_agent_dir();
// TS parity: the status file belongs under the agent dir's `update-restarts/` - the coordinator
// never writes status elsewhere.
@@ -598,6 +636,21 @@ pub async fn run_coordinator_mode(socket_path: PathBuf, status_path: PathBuf) ->
eprintln!("Invalid daemon update restart coordinator invocation.");
return Ok(1);
}
+ let legacy_handoff = match std::fs::read(&status_path) {
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => true,
+ Err(error) => return Err(error.into()),
+ Ok(bytes) => {
+ let value: serde_json::Value = serde_json::from_slice(&bytes)?;
+ value.get("state").is_none()
+ && value
+ .get("requestId")
+ .is_some_and(serde_json::Value::is_string)
+ && value.get("phase").and_then(serde_json::Value::as_str) == Some("starting")
+ }
+ };
+ if legacy_handoff {
+ return super::legacy_restart::run(&socket_path, &status_path, &agent_dir, origin).await;
+ }
let options = super::coordinator::CoordinatorOptions {
agent_dir,
socket_path,
@@ -608,3 +661,36 @@ pub async fn run_coordinator_mode(socket_path: PathBuf, status_path: PathBuf) ->
print_terminal(&status);
Ok(i32::from(status.state != UpdateState::Complete))
}
+
+#[cfg(all(test, unix))]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn an_exited_coordinator_fails_without_waiting_for_the_heartbeat_timeout() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("status.json");
+ let id = pa_types::daemon::update_flow::UpdateId::from("exited-child".to_string());
+ let mut writer = StatusWriter::new(&path, &id, "/tmp/unused-update.sock").unwrap();
+ writer.set_state(UpdateState::Planning).unwrap();
+ writer.set_state(UpdateState::Downloading).unwrap();
+ writer.set_state(UpdateState::Staged).unwrap();
+ let mut child = std::process::Command::new("/bin/sh")
+ .args(["-c", "exit 7"])
+ .spawn()
+ .unwrap();
+ let observed = tokio::time::timeout(
+ std::time::Duration::from_secs(10),
+ tail_status_with(&path, Some(&mut child), &mut |_, _| {}),
+ )
+ .await
+ .expect("an exited child must not consume the 180-second liveness budget");
+ let exit = child.wait().unwrap();
+ let mut expected = writer.current().clone();
+ expected.state = UpdateState::Failed;
+ expected.message = Some(format!(
+ "the update coordinator exited with {exit} before reporting completion"
+ ));
+ assert_eq!(observed, expected);
+ }
+}
diff --git a/crates/pa-cli/tests/release_workflow.rs b/crates/pa-cli/tests/release_workflow.rs
index 4320da3423..7f49828451 100644
--- a/crates/pa-cli/tests/release_workflow.rs
+++ b/crates/pa-cli/tests/release_workflow.rs
@@ -44,8 +44,8 @@ use sha2::{Digest, Sha256};
/// The fixture version the assembled artifacts carry.
const VERSION: &str = "0.9.9";
-/// The promote step that refuses archives a TS 0.9.8 updater would install.
-const TS_GUARD_STEP: &str = "Refuse archives the TypeScript updater would install";
+/// The promote step that validates the archive contract of shipped TS updaters.
+const NATIVE_COMPAT_STEP: &str = "Verify historical native updater compatibility";
/// The current build matrix (release.yml's `build-gnu` + `build-darwin` +
/// `build-windows` jobs): the five standalone targets. The single-artifact
@@ -167,6 +167,15 @@ fn python3_binary(min_version: (u8, u8)) -> Option<PathBuf> {
/// Run one workflow step script (its committed `run:` text) in `cwd`.
fn run_step(cwd: &Path, step: &Step) -> Output {
+ if step.name.as_deref() == Some(NATIVE_COMPAT_STEP) {
+ let scripts = cwd.join("verification-source/scripts/release");
+ fs::create_dir_all(&scripts).expect("create verification source directory");
+ fs::copy(
+ repo_root().join("scripts/release/native_compat.py"),
+ scripts.join("native_compat.py"),
+ )
+ .expect("copy the compatibility verifier from the checked-out release source");
+ }
let script = step.run.as_deref().expect("the step carries a run script");
Command::new("bash")
.arg("-c")
@@ -202,16 +211,57 @@ fn sha256_file(path: &Path) -> String {
format!("{:x}", hasher.finalize())
}
-/// One real (extractable) tar.gz archive: the staged payload binary
-/// (`prime-agent` — or `prime-agent.exe` on the MSVC target) with
-/// deterministic member metadata, the `assemble_artifacts.py` shape, plus
-/// any `extra_members`.
-fn write_fixture_tarball(out_path: &Path, payload_name: &str, extra_members: &[&str]) {
+/// An extractable release archive with authentic historical installer assets.
+/// `omitted_members` allows a regression case to remove a required file.
+fn write_fixture_tarball(
+ out_path: &Path,
+ payload_name: &str,
+ version: &str,
+ omitted_members: &[&str],
+) {
let file = fs::File::create(out_path).expect("create the fixture archive");
let encoder = flate2::write::GzEncoder::new(file, flate2::Compression::default());
let mut archive = tar::Builder::new(encoder);
- let payload = VERSION.as_bytes().to_vec();
- for name in std::iter::once(payload_name).chain(extra_members.iter().copied()) {
+ let mut members = vec![
+ (payload_name, version.as_bytes().to_vec()),
+ (
+ "package.json",
+ serde_json::to_vec(&serde_json::json!({"name": "prime-agent", "version": version}))
+ .expect("serialize package metadata"),
+ ),
+ ];
+ if payload_name != "prime-agent.exe" {
+ members.extend([
+ (
+ "install.sh",
+ fs::read(repo_root().join("install-rust.sh")).expect("read the repair installer"),
+ ),
+ (
+ "prime-agent-runtime/pyproject.toml",
+ b"[project]\n".to_vec(),
+ ),
+ (
+ "prime-agent-runtime/src/rlm/repl.py",
+ b"# fixture runtime\n".to_vec(),
+ ),
+ ]);
+ for name in [
+ "theme/prime.json",
+ "export-html/template.html",
+ "photon_rs_bg.wasm",
+ "PHOTON-LICENSE.md",
+ ] {
+ members.push((
+ name,
+ fs::read(repo_root().join("scripts/release/native-compat").join(name))
+ .expect("read the historical compatibility asset"),
+ ));
+ }
+ }
+ for (name, payload) in members {
+ if omitted_members.contains(&name) {
+ continue;
+ }
let mut header = tar::Header::new_gnu();
header.set_size(payload.len() as u64);
header.set_mode(0o755);
@@ -249,12 +299,17 @@ fn run_step_with_env(cwd: &Path, step: &Step, env: &[(&str, &str)]) -> Output {
command.output().expect("bash executes the step script")
}
-fn write_artifact_with(dir: &Path, target: &str, extra_members: &[&str]) -> serde_json::Value {
+fn write_artifact_with(dir: &Path, target: &str, omitted_members: &[&str]) -> serde_json::Value {
fs::create_dir_all(dir).expect("create the artifact directory");
// The archive name the channel contract requires: the PLATFORM ALIAS,
// never the target triple (the update reader drops a triple-named row).
let archive_name = format!("prime-agent-{VERSION}-{}.tar.gz", platform_alias(target));
- write_fixture_tarball(&dir.join(&archive_name), binary_name(target), extra_members);
+ write_fixture_tarball(
+ &dir.join(&archive_name),
+ binary_name(target),
+ VERSION,
+ omitted_members,
+ );
let sha256 = sha256_file(&dir.join(&archive_name));
fs::write(
dir.join("SHA256SUMS"),
@@ -289,7 +344,7 @@ fn write_artifact_version(dir: &Path, target: &str, version: &str) -> serde_json
// The archive name the channel contract requires: the PLATFORM ALIAS,
// never the target triple (the update reader drops a triple-named row).
let archive_name = format!("prime-agent-{version}-{}.tar.gz", platform_alias(target));
- write_fixture_tarball(&dir.join(&archive_name), binary_name(target), &[]);
+ write_fixture_tarball(&dir.join(&archive_name), binary_name(target), version, &[]);
let sha256 = sha256_file(&dir.join(&archive_name));
fs::write(
dir.join("SHA256SUMS"),
@@ -351,7 +406,7 @@ fn run_promote_gates(cwd: &Path, steps: &[Step]) -> (String, serde_json::Value)
steps,
"Verify hash continuity (artifacts match build-job manifests)",
)];
- let ts_guard = &steps[step_position(steps, TS_GUARD_STEP)];
+ let ts_guard = &steps[step_position(steps, NATIVE_COMPAT_STEP)];
let merge = &steps[step_position(steps, "Merge per-target manifests + SHA256SUMS")];
let normalize_stdout = assert_success(&run_step(cwd, normalize), "normalize download layout");
@@ -360,7 +415,7 @@ fn run_promote_gates(cwd: &Path, steps: &[Step]) -> (String, serde_json::Value)
verify_stdout.contains("hash continuity verified for all archives"),
"hash continuity must report verifying the archives"
);
- assert_success(&run_step(cwd, ts_guard), TS_GUARD_STEP);
+ assert_success(&run_step(cwd, ts_guard), NATIVE_COMPAT_STEP);
assert_success(&run_step(cwd, merge), "merge per-target manifests");
let merged: serde_json::Value = serde_json::from_str(
@@ -371,6 +426,39 @@ fn run_promote_gates(cwd: &Path, steps: &[Step]) -> (String, serde_json::Value)
(normalize_stdout, merged)
}
+/// Native release jobs must exercise the current channel installer as well
+/// as the retained TypeScript updater before their artifacts reach promotion.
+#[test]
+fn native_release_jobs_gate_fresh_and_legacy_installation() {
+ let text = fs::read_to_string(repo_root().join(".github/workflows/release.yml"))
+ .expect("read release.yml");
+ let workflow: Workflow = serde_yaml::from_str(&text).expect("release.yml parses as YAML");
+ for job_name in ["build-gnu", "build-darwin"] {
+ let steps = &workflow.jobs.get(job_name).expect("native build job").steps;
+ let fresh = step_position(steps, "Verify fresh channel install and reinstall");
+ let legacy = step_position(steps, "Verify the shipped TypeScript update command");
+ let upload = steps
+ .iter()
+ .position(|step| {
+ step.uses
+ .as_deref()
+ .is_some_and(|uses| uses.starts_with("actions/upload-artifact@"))
+ })
+ .expect("artifact upload step");
+ assert!(
+ fresh < upload && legacy < upload,
+ "installation gates precede artifact upload"
+ );
+ let run = steps[fresh]
+ .run
+ .as_deref()
+ .expect("fresh installation script");
+ assert!(run.contains("scripts/release/test_channel_install.py"));
+ assert!(run.contains("--installer install-rust.sh"));
+ assert!(run.contains("--archive") && run.contains("channel-install.json"));
+ }
+}
+
/// The Windows build job's structural contract: the MSVC target builds on
/// its own runner (never inside build-gnu's linux container), the livecheck
/// names the `.exe` binary, promote needs the job, and the channel
@@ -581,55 +669,42 @@ fn promote_download_layout_contract() {
download < normalize && normalize < verify && verify < merge,
"the layout must be normalized between the download and the per-artifact gates"
);
- let ts_guard = step_position(&steps, TS_GUARD_STEP);
+ let ts_guard = step_position(&steps, NATIVE_COMPAT_STEP);
assert!(
normalize < ts_guard && ts_guard < merge,
"the TS-updater gate must check every archive before anything is merged or published"
);
}
-/// A TS 0.9.8 updater installs any archive that carries install.sh (plus
-/// three other files the Rust archive lacks) into the TS layout. The promote
-/// gate must refuse an archive with a root-level install.sh, and only that
-/// root-level file: the same name deeper in the tree is not what TS reads.
+/// The promote gate accepts a usable historical installer layout and rejects
+/// an archive missing a required asset before any release is published.
#[test]
-fn an_archive_with_a_root_install_sh_fails_the_ts_updater_gate() {
- let Some(_python3) = python3_binary((3, 0)) else {
+fn historical_native_updater_gate_requires_the_compatibility_assets() {
+ let Some(_python3) = python3_binary((3, 9)) else {
return;
};
let steps = promote_steps();
- let ts_guard = &steps[step_position(&steps, TS_GUARD_STEP)];
-
+ let compat = &steps[step_position(&steps, NATIVE_COMPAT_STEP)];
let cwd = tempfile::tempdir().expect("scratch dir");
let incoming = cwd.path().join("incoming");
- write_artifact(
- &incoming.join(format!("artifacts-{}", TARGETS[0])),
- TARGETS[0],
- );
- write_artifact_with(
- &incoming.join(format!("artifacts-{}", TARGETS[1])),
- TARGETS[1],
- &["skills/install.sh"],
+ for target in TARGETS {
+ write_artifact(&incoming.join(format!("artifacts-{target}")), target);
+ }
+ let output = assert_success(&run_step(cwd.path(), compat), NATIVE_COMPAT_STEP);
+ assert_eq!(
+ output.matches("Native compatibility verified:").count(),
+ TARGETS.len()
);
- let output = assert_success(&run_step(cwd.path(), ts_guard), TS_GUARD_STEP);
- assert!(output.contains("no archive carries the TypeScript installer layout"));
write_artifact_with(
&incoming.join(format!("artifacts-{}", TARGETS[2])),
TARGETS[2],
- &["install.sh"],
- );
- let output = assert_failure(&run_step(cwd.path(), ts_guard), TS_GUARD_STEP);
- assert!(
- output.contains(&format!(
- "prime-agent-{VERSION}-{}.tar.gz: contains a root-level install.sh",
- platform_alias(TARGETS[2])
- )),
- "the gate must name the offending archive\n{output}"
+ &["theme/prime.json"],
);
+ let output = assert_failure(&run_step(cwd.path(), compat), NATIVE_COMPAT_STEP);
assert!(
- !output.contains(platform_alias(TARGETS[1])),
- "a nested install.sh must not trip the gate\n{output}"
+ output.contains("missing regular compatibility asset: theme/prime.json"),
+ "the gate must name the missing compatibility asset\n{output}"
);
}
@@ -867,6 +942,11 @@ fn the_channel_manifest_carries_the_windows_row_on_both_channels() {
)
.expect("parse the emitted beta.json");
assert_eq!(document["version"], "v0.9.9-beta.7");
+ assert_eq!(document["package"], "prime-agent");
+ assert_eq!(
+ document["tarball"],
+ "releases/v0.9.9-beta.7/prime-agent-0.9.9-beta.7.tgz"
+ );
let v2 = document["binaries_v2"]
.as_array()
.expect("binaries_v2 rows");
@@ -936,6 +1016,11 @@ fn the_channel_manifest_carries_the_windows_row_on_both_channels() {
)
.expect("parse the emitted latest.json");
assert_eq!(document["version"], stable_tag.as_str());
+ assert_eq!(document["package"], "prime-agent");
+ assert_eq!(
+ document["tarball"],
+ format!("releases/v{VERSION}/prime-agent-{VERSION}.tgz")
+ );
assert!(
document["binaries_v2"]
.as_array()
diff --git a/crates/pa-core/README.md b/crates/pa-core/README.md
index bdca2643cb..5b3d0d8d01 100644
--- a/crates/pa-core/README.md
+++ b/crates/pa-core/README.md
@@ -79,6 +79,10 @@ No provider HTTP (pa-ai), no loop policy (pa-agent), no daemon supervision (pa-d
## Depends on
pa-types, pa-ai, pa-agent (one-way).
+The Unix platform process API exposes `current_user_id()` for the daemon
+endpoint namespace to match the TypeScript `process.getuid()` contract on
+macOS as well as Linux. This reads the OS identity without filesystem or
+subprocess work.
Automatic trace delivery (`agent_traces::ContinuousTraceUpload`) owns consent-gated
persist scheduling and startup outbox recovery alongside the existing manual uploader.
diff --git a/crates/pa-core/src/platform/process.rs b/crates/pa-core/src/platform/process.rs
index eadc6e91d7..29ef61b189 100644
--- a/crates/pa-core/src/platform/process.rs
+++ b/crates/pa-core/src/platform/process.rs
@@ -5,6 +5,13 @@
use std::process::Command;
+/// The real Unix user id, matching Node `process.getuid()` for daemon namespaces.
+#[cfg(unix)]
+#[must_use]
+pub fn current_user_id() -> u32 {
+ nix::unistd::Uid::current().as_raw()
+}
+
/// Termination signal for [`kill_pid`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Signal {
diff --git a/crates/pa-core/src/update/installer.rs b/crates/pa-core/src/update/installer.rs
index 472d18d3a6..e32f3d1163 100644
--- a/crates/pa-core/src/update/installer.rs
+++ b/crates/pa-core/src/update/installer.rs
@@ -103,6 +103,9 @@ pub fn install_prefix() -> PathBuf {
return PathBuf::from(prefix);
}
}
+ if let Some(prefix) = running_installer_prefix() {
+ return prefix;
+ }
pa_types::platform::home_dir()
.unwrap_or_default()
.join(".local")
diff --git a/crates/pa-daemon/README.md b/crates/pa-daemon/README.md
index b765102156..3000ef68d7 100644
--- a/crates/pa-daemon/README.md
+++ b/crates/pa-daemon/README.md
@@ -242,7 +242,12 @@ boot), re-arms scheduled work (a boot scan of `scheduled-jobs.json`;
due active jobs of sessionless files are woken once, never archived), and
reports the pass over `update_restore_status` while `hello.update_resume`
carries the settle state; client attaches to a not-yet-restored roster row
-queue behind the pass instead of failing. The heartbeat-catalog change
+queue behind the pass instead of failing.
+For historical TypeScript update manifests, the restore pass recreates parents
+before their children, remaps active parent IDs, and restores pending context
+and action queues explicitly because those manifests predate Rust's journals.
+Attaches remain gated until that replay completes.
+The heartbeat-catalog change
broadcast owns its surface here too (the worker's cron-store
`on_heartbeat_change` listener emits a `heartbeats_changed` outbound frame
— TS daemon-mode's `broadcastGlobal` — and the supervisor re-broadcasts it
@@ -258,3 +263,9 @@ Supervisor entrypoint, worker entrypoint, `mcp_login::{WorkerMcpLoginUi, wire_wo
## Depends on
pa-types, pa-core (one-way).
+
+The composition root initializes the packaged product version with
+`protocol::configure_app_version` before entering daemon or worker mode.
+`protocol::app_version` supplies that identity to both hello frames and update
+checkpoints; library embedders fall back to the compiled version. Release
+manifest restamping therefore remains consistent with CLI `--version`.
diff --git a/crates/pa-daemon/src/platform/paths.rs b/crates/pa-daemon/src/platform/paths.rs
index b055da4601..1a6da6ff60 100644
--- a/crates/pa-daemon/src/platform/paths.rs
+++ b/crates/pa-daemon/src/platform/paths.rs
@@ -9,7 +9,7 @@ use crate::paths::hash_key;
/// Default directory holding daemon socket files (Unix).
#[cfg(unix)]
pub fn socket_dir() -> PathBuf {
- let uid = current_uid().unwrap_or_else(|| "user".to_string());
+ let uid = pa_core::platform::process::current_user_id();
let tmp = std::env::var_os("TMPDIR").map_or_else(|| PathBuf::from("/tmp"), PathBuf::from);
tmp.join(format!("prime-agent-{uid}"))
}
@@ -22,22 +22,6 @@ pub fn socket_dir() -> PathBuf {
std::env::temp_dir().join("prime-agent-user")
}
-/// Read the effective uid without libc: `/proc/self/status` on Linux,
-/// HOME-derived uniqueness elsewhere (best-effort, same as today).
-#[cfg(unix)]
-fn current_uid() -> Option<String> {
- if let Ok(status) = std::fs::read_to_string("/proc/self/status") {
- for line in status.lines() {
- if let Some(rest) = line.strip_prefix("Uid:") {
- if let Some(first) = rest.split_whitespace().next() {
- return Some(first.to_string());
- }
- }
- }
- }
- None
-}
-
/// Default supervisor endpoint: `daemon.sock` in the socket dir (Unix) or
/// the fixed daemon pipe name (Windows).
#[cfg(unix)]
@@ -84,6 +68,22 @@ pub use pa_types::platform::socket_identity;
mod tests {
use super::*;
+ #[cfg(unix)]
+ #[test]
+ fn default_socket_uses_the_same_real_uid_as_the_typescript_daemon() {
+ let output = std::process::Command::new("id")
+ .arg("-ru")
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let uid = String::from_utf8(output.stdout).unwrap();
+ let tmp = std::env::var_os("TMPDIR").map_or_else(|| PathBuf::from("/tmp"), PathBuf::from);
+ assert_eq!(
+ socket_dir(),
+ tmp.join(format!("prime-agent-{}", uid.trim()))
+ );
+ }
+
#[test]
fn worker_socket_names_are_deterministic() {
let supervisor = Path::new("/tmp/prime-agent-1/daemon.sock");
diff --git a/crates/pa-daemon/src/protocol.rs b/crates/pa-daemon/src/protocol.rs
index 30c194ec33..a4f32c3329 100644
--- a/crates/pa-daemon/src/protocol.rs
+++ b/crates/pa-daemon/src/protocol.rs
@@ -17,12 +17,33 @@ use serde_json::Value;
/// Minimum protocol version accepted in command envelopes (TS parity).
pub const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION: u64 = DAEMON_PROTOCOL_VERSION;
-/// The product version the daemon reports in every `daemon_hello`
-/// (`appVersion`): the CLI's `doctor`/`status` "current" classification
-/// compares against the same value, so this must stay the bare product
-/// version (the build identity marker lives in `runtime.buildId`).
+/// Compiled product-version fallback for library embedders. Packaged CLI
+/// processes initialize the reported version through [`configure_app_version`].
pub const DAEMON_APP_VERSION: &str = env!("CARGO_PKG_VERSION");
+static PRODUCT_VERSION: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new();
+
+/// Set the packaged product version once in the composition root, before
+/// serving supervisor or worker connections. Repeating the same value is safe.
+///
+/// # Errors
+/// Returns an error if a process attempts to serve two product versions.
+pub fn configure_app_version(version: &'static str) -> anyhow::Result<()> {
+ let configured = PRODUCT_VERSION.get_or_init(|| version);
+ anyhow::ensure!(
+ *configured == version,
+ "daemon product version was already configured differently"
+ );
+ Ok(())
+}
+
+/// Product version shared by daemon handshakes and update checkpoints. Library
+/// embedders without package metadata retain the compiled version fallback.
+#[must_use]
+pub(crate) fn app_version() -> &'static str {
+ PRODUCT_VERSION.get().copied().unwrap_or(DAEMON_APP_VERSION)
+}
+
/// Command types the daemon recognizes (TS `DAEMON_COMMAND_TYPES` in TS
/// declared order, followed by the Rust-native supervisor/worker frames).
pub const KNOWN_COMMAND_TYPES: &[&str] = &[
diff --git a/crates/pa-daemon/src/supervisor.rs b/crates/pa-daemon/src/supervisor.rs
index d3eece283e..8f9aeb4dc1 100644
--- a/crates/pa-daemon/src/supervisor.rs
+++ b/crates/pa-daemon/src/supervisor.rs
@@ -86,10 +86,10 @@ use crate::framing::{write_frame, PrivateFrameReader, DEFAULT_PRIVATE_FRAME_LIMI
use crate::paths;
use crate::prompt_admission::input_admission_id;
use crate::protocol::{
- command_active_session_id, command_type_name, current_protocol_info,
+ app_version, command_active_session_id, command_type_name, current_protocol_info,
parse_supervisor_command_line, response_failure, response_line, response_success,
DaemonResponse, DaemonRuntimeIdentity, EnvelopeParseError, TypedCreateRejection,
- DAEMON_APP_VERSION, DAEMON_SCHEMA_ID, DAEMON_SCHEMA_REVISION,
+ DAEMON_SCHEMA_ID, DAEMON_SCHEMA_REVISION,
};
use crate::registry::{
ResidentWorker, SessionRegistry, WorkerRegistration, WorkerReply, WorkerRequest,
diff --git a/crates/pa-daemon/src/supervisor/clients.rs b/crates/pa-daemon/src/supervisor/clients.rs
index 67af9fcc62..a21a01a39c 100644
--- a/crates/pa-daemon/src/supervisor/clients.rs
+++ b/crates/pa-daemon/src/supervisor/clients.rs
@@ -1,14 +1,14 @@
//! Client connections: the per-connection task - read loop, dispatch,
//! and the parsed-command execution surface.
use super::{
- broadcast, command_type_name, current_protocol_info, daemon_closing_shutdown_event,
- input_admission_id, json, parse_supervisor_command_line, response_failure, response_line,
- response_success, salvage_command_type, salvage_id, subscribers, update_gate_refuses, util,
- Arc, AsyncBufReadExt, AsyncWriteExt, BufReader, ClientRouting, DaemonCommand, DaemonOutbound,
- DaemonRuntimeIdentity, Duration, EnvelopeParseError, Map, Ordering, Outbound, ResidentWorker,
- Result, RouteAdmission, Supervisor, TransportStream, TypedCreateRejection, Value,
- DAEMON_APP_VERSION, DAEMON_SCHEMA_ID, DAEMON_SCHEMA_REVISION, ROUTE_TIMEOUT_MS,
- UPDATE_PREPARING_MESSAGE,
+ app_version, broadcast, command_type_name, current_protocol_info,
+ daemon_closing_shutdown_event, input_admission_id, json, parse_supervisor_command_line,
+ response_failure, response_line, response_success, salvage_command_type, salvage_id,
+ subscribers, update_gate_refuses, util, Arc, AsyncBufReadExt, AsyncWriteExt, BufReader,
+ ClientRouting, DaemonCommand, DaemonOutbound, DaemonRuntimeIdentity, Duration,
+ EnvelopeParseError, Map, Ordering, Outbound, ResidentWorker, Result, RouteAdmission,
+ Supervisor, TransportStream, TypedCreateRejection, Value, DAEMON_SCHEMA_ID,
+ DAEMON_SCHEMA_REVISION, ROUTE_TIMEOUT_MS, UPDATE_PREPARING_MESSAGE,
};
/// TS `OWNED_WORKER_DISCONNECT_GRACE_MS`: how long a client-owned worker
@@ -121,7 +121,7 @@ impl Supervisor {
protocol: current_protocol_info(),
schema_id: Some(DAEMON_SCHEMA_ID.to_string()),
schema_revision: Some(DAEMON_SCHEMA_REVISION),
- app_version: Some(DAEMON_APP_VERSION.to_string()),
+ app_version: Some(app_version().to_string()),
runtime: Some(DaemonRuntimeIdentity {
build_id: concat!("pa-daemon-rs-", env!("CARGO_PKG_VERSION")).to_string(),
executable_path: std::env::current_exe()
diff --git a/crates/pa-daemon/src/supervisor/update_restart.rs b/crates/pa-daemon/src/supervisor/update_restart.rs
index abf52f55bf..5da09c02a6 100644
--- a/crates/pa-daemon/src/supervisor/update_restart.rs
+++ b/crates/pa-daemon/src/supervisor/update_restart.rs
@@ -1,12 +1,12 @@
//! The update/restart flow: prepare/commit/abort transactions, the prepared
//! dir + watchdog, exit-for-update, and the attach-stream salvage helpers.
use super::{
- anyhow, build_update_roster, join_all, json, marker_expires_at_iso, paths, response_failure,
- response_line, response_success, stop_workers_gracefully, stream_attach, supervisor_identity,
- util, write_prepared_artifacts, AbortOutcome, Arc, BeginOutcome, ClientRouting, DaemonCommand,
- DaemonErrorInfo, DaemonResponse, Duration, Map, Ordering, Path, PathBuf, PrepareOp, Result,
- RouteAdmission, SnapshotPurpose, Supervisor, UpdateId, UpdatePreparedMarker,
- UpdateRosterInputs, Value, WorkerSnapshot, WorkerStopVerdict, DAEMON_APP_VERSION,
+ anyhow, app_version, build_update_roster, join_all, json, marker_expires_at_iso, paths,
+ response_failure, response_line, response_success, stop_workers_gracefully, stream_attach,
+ supervisor_identity, util, write_prepared_artifacts, AbortOutcome, Arc, BeginOutcome,
+ ClientRouting, DaemonCommand, DaemonErrorInfo, DaemonResponse, Duration, Map, Ordering, Path,
+ PathBuf, PrepareOp, Result, RouteAdmission, SnapshotPurpose, Supervisor, UpdateId,
+ UpdatePreparedMarker, UpdateRosterInputs, Value, WorkerSnapshot, WorkerStopVerdict,
WORKER_REQUEST_TIMEOUT_MS,
};
@@ -242,8 +242,8 @@ impl Supervisor {
DaemonCommand::PrepareUpdateRestart { rest, .. } => rest
.get("toVersion")
.and_then(Value::as_str)
- .unwrap_or(DAEMON_APP_VERSION),
- _ => DAEMON_APP_VERSION,
+ .unwrap_or(app_version()),
+ _ => app_version(),
};
let ledger = self.rlm_spawn_ledger_for(None).await?;
let now = util::now_ms();
@@ -254,7 +254,7 @@ impl Supervisor {
socket_path: self.options.socket_path.to_str().unwrap_or_default(),
agent_dir: &self.options.agent_dir,
supervisor: identity.clone(),
- from_version: DAEMON_APP_VERSION,
+ from_version: app_version(),
to_version,
created_at_ms: now,
ledger: &ledger,
diff --git a/crates/pa-daemon/src/update_restore.rs b/crates/pa-daemon/src/update_restore.rs
index 2d64c3360a..1f4f6af900 100644
--- a/crates/pa-daemon/src/update_restore.rs
+++ b/crates/pa-daemon/src/update_restore.rs
@@ -105,7 +105,12 @@ impl RestoreProgress {
active_session_id: row.active_session_id.clone(),
session_file: row.session_file.clone(),
name: row.name.clone(),
- needs_continuation: row.should_resume && row.in_flight.streaming,
+ needs_continuation: roster
+ .rest
+ .get("legacy_ts_restart")
+ .and_then(serde_json::Value::as_bool)
+ == Some(true)
+ || (row.should_resume && row.in_flight.streaming),
settled: false,
failure: None,
},
@@ -289,16 +294,83 @@ fn restore_target_mut<'a>(
restore_target_key(targets, selector).and_then(|key| targets.get_mut(&key))
}
-// Spec §6 step 1: the unconditional boot sweep
+// Spec §6 step 1: the boot sweep
-/// Delete this socket's update scratch directory and the legacy TS-era
-/// names (spec §6 step 1): the roster env is consumed first. Flat TS
-/// status records remain available to callers waiting for their result,
-/// even after the coordinator exits.
+/// Delete this socket's scratch directory and stale legacy names after consuming
+/// the roster env. Keep a TS manifest while its socket-bound prepare attempt is
+/// pending: an ordinary boot after a lost reply must not destroy recovery input.
+/// Flat TS status records remain available to callers waiting for their result.
pub(crate) fn boot_sweep(agent_dir: &Path, socket_path: &Path) {
let socket_hash = crate::paths::hash_key(&socket_path.to_string_lossy(), 64);
let _ = std::fs::remove_dir_all(socket_update_dir(agent_dir, &socket_hash));
- let _ = std::fs::remove_dir_all(legacy_update_restarts_dir(agent_dir));
+ let legacy_dir = legacy_update_restarts_dir(agent_dir);
+ if legacy_dir.is_symlink() {
+ // Never walk a symlink while deleting scratch entries.
+ let _ = std::fs::remove_file(&legacy_dir);
+ } else if let Ok(entries) = std::fs::read_dir(&legacy_dir) {
+ for entry in entries {
+ let entry = match entry {
+ Ok(entry) => entry,
+ Err(error) => {
+ eprintln!("pa-daemon: could not inspect legacy update scratch: {error}");
+ continue;
+ }
+ };
+ let path = entry.path();
+ let pending = path
+ .file_stem()
+ .and_then(|stem| stem.to_str())
+ .is_some_and(|key| {
+ if path.extension().and_then(|extension| extension.to_str()) != Some("json") {
+ return false;
+ }
+ let attempt_path = agent_dir
+ .join("legacy-update-recovery")
+ .join(format!("{key}.attempt.json"));
+ let attempt = std::fs::read(attempt_path)
+ .ok()
+ .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok());
+ let Some(attempt) = attempt else {
+ return false;
+ };
+ let Some(socket) = attempt["socket"]
+ .as_str()
+ .filter(|socket| !socket.is_empty())
+ else {
+ return false;
+ };
+ // Retain attempts for every socket, including older target versions.
+ // The CLI owns full predecessor/freshness validation and removes the
+ // attempt only after confirmed restoration or a safe prepare refusal.
+ crate::paths::hash_key(socket, 64) == key
+ && attempt["version"]
+ .as_str()
+ .is_some_and(|version| !version.is_empty())
+ && attempt["updateId"]
+ .as_str()
+ .is_some_and(|id| !id.is_empty())
+ && attempt["startedAt"].as_u64().is_some()
+ && attempt["hello"]["supervisorPid"]
+ .as_u64()
+ .is_some_and(|pid| pid > 0)
+ && attempt["hello"]["supervisorProcessStartId"]
+ .as_str()
+ .is_some_and(|id| !id.is_empty())
+ && attempt["hello"]["supervisorGeneration"]
+ .as_str()
+ .is_some_and(|generation| !generation.is_empty())
+ });
+ if !pending {
+ if path.is_dir() {
+ let _ = std::fs::remove_dir_all(path);
+ } else {
+ let _ = std::fs::remove_file(path);
+ }
+ }
+ }
+ // Only remove an empty directory; pending sources keep their original paths.
+ let _ = std::fs::remove_dir(&legacy_dir);
+ }
let _ = std::fs::remove_file(legacy_update_restart_status(agent_dir));
}
@@ -347,7 +419,8 @@ fn sort_rows_bottom_up(rows: &mut [&UpdateRosterSession]) {
}
/// The boot restore driver: run after the descriptor-adoption task
-/// settles, then walk the roster rows bottom-up (spec §8). NOT-RUNNING
+/// settles, then walk Rust rows bottom-up (spec §8), or TS rows parent-first
+/// so their fresh active handles can be remapped. NOT-RUNNING
/// sessions stay down; the dormant report runs AFTER the replay.
pub(crate) async fn restore_pass(
supervisor: &std::sync::Arc<Supervisor>,
@@ -363,46 +436,94 @@ pub(crate) async fn restore_pass(
return;
};
let mut rows: Vec<&UpdateRosterSession> = roster.sessions.iter().collect();
- sort_rows_bottom_up(&mut rows);
+ let legacy = roster
+ .rest
+ .get("legacy_ts_restart")
+ .and_then(serde_json::Value::as_bool)
+ == Some(true);
+ if legacy {
+ rows.sort_by_key(|row| row.rlm_depth);
+ } else {
+ sort_rows_bottom_up(&mut rows);
+ }
+ let mut restored_ids = BTreeMap::new();
let mut counts = UpdateStatusCounts::default();
let mut failures: Vec<UpdateStatusFailure> = Vec::new();
for row in rows {
counts.total += 1;
- match supervisor
+ let restored = match supervisor
.registry
.find_by_session_file(&row.session_file)
.await
{
- // The adoption pass (or a still-alive abandoned worker) brought the session up.
- Some(resident) => {
- counts.restored += 1;
- // Settle the row before the continuation treatment: the waiters attach now.
+ Some(resident) => Ok(resident),
+ None => restore_session(supervisor, row, legacy.then_some(&restored_ids)).await,
+ };
+ let restored = match restored {
+ Ok(resident) if legacy => {
+ restored_ids.insert(
+ row.active_session_id.clone(),
+ resident
+ .descriptor
+ .lock()
+ .await
+ .root_active_session_id
+ .clone(),
+ );
+ let origin = roster
+ .rest
+ .get("restart_origin_active_session_id")
+ .and_then(serde_json::Value::as_str);
+ match restore_legacy_session(
+ row,
+ origin,
+ &roster.binary.to_version,
+ |command, payload| {
+ supervisor.route_command_typed(
+ &resident,
+ command,
+ payload,
+ crate::supervisor::ROUTE_TIMEOUT_MS,
+ RouteAdmission::SupervisorInternal,
+ )
+ },
+ )
+ .await
+ {
+ Ok(resumed) => {
+ counts.resumed += u64::from(resumed);
+ Ok(resident)
+ }
+ Err(error) => Err(error),
+ }
+ }
+ Ok(resident) => {
supervisor.restore.settle_target(&row.session_id, None);
continuation_treatment(supervisor, &resident, row, &mut counts).await;
+ Ok(resident)
+ }
+ Err(error) => Err(error),
+ };
+ match restored {
+ Ok(_) => {
+ counts.restored += 1;
+ supervisor.restore.settle_target(&row.session_id, None);
+ }
+ Err(error) => {
+ let message = format!("{error:#}");
+ supervisor.log_line(&format!(
+ "update restore: could not restore {}: {message}",
+ row.session_file
+ ));
+ supervisor
+ .restore
+ .settle_target(&row.session_id, Some(message.clone()));
+ failures.push(UpdateStatusFailure {
+ session_file: row.session_file.clone(),
+ message,
+ });
+ counts.failed += 1;
}
- None => match restore_session(supervisor, row).await {
- Ok(resident) => {
- counts.restored += 1;
- supervisor.restore.settle_target(&row.session_id, None);
- continuation_treatment(supervisor, &resident, row, &mut counts).await;
- }
- Err(error) => {
- // Restore never fails the boot: record the row, leave the session on disk.
- let message = format!("{error:#}");
- supervisor.log_line(&format!(
- "update restore: could not restore {}: {message}",
- row.session_file
- ));
- supervisor
- .restore
- .settle_target(&row.session_id, Some(message.clone()));
- failures.push(UpdateStatusFailure {
- session_file: row.session_file.clone(),
- message,
- });
- counts.failed += 1;
- }
- },
}
}
// The dormant report runs here, AFTER the replay: only the sessions that stayed down count.
@@ -410,11 +531,159 @@ pub(crate) async fn restore_pass(
supervisor.restore.settle(counts, failures);
}
+/// Replay the TS manifest, whose queues have no Rust recovery journal. The
+/// command boundary is injectable so regression tests exercise the same ordering
+/// and acknowledgement handling as the live supervisor route.
+async fn restore_legacy_session<F, Fut>(
+ row: &UpdateRosterSession,
+ origin: Option<&str>,
+ version: &str,
+ mut route: F,
+) -> Result<bool>
+where
+ F: FnMut(&'static str, serde_json::Value) -> Fut,
+ Fut: std::future::Future<Output = Result<crate::protocol::DaemonResponse>>,
+{
+ let actions = row
+ .queue
+ .actions
+ .get("actions")
+ .and_then(serde_json::Value::as_array);
+ let has_actions = actions.is_some_and(|actions| !actions.is_empty());
+ // restore_actions wakes Rust's runner immediately. Hold its existing input
+ // pause across queue replay and continuation admission, including unrelated
+ // wakeups, so a follow-up cannot overtake the interrupted turn.
+ let pause = if row.should_resume && has_actions {
+ let response = route(
+ "acquire_session_input_pause",
+ json!({
+ "leaseKey": "legacy-update-restore", "clientId": UPDATE_RESTORE_CLIENT_ID,
+ }),
+ )
+ .await?;
+ anyhow::ensure!(
+ response.success,
+ "legacy update acquire_session_input_pause: {}",
+ response.error.unwrap_or_default()
+ );
+ Some(
+ response
+ .data
+ .as_ref()
+ .and_then(|data| data.get("pauseId"))
+ .and_then(serde_json::Value::as_str)
+ .context("legacy update input pause returned no pause id")?
+ .to_string(),
+ )
+ } else {
+ None
+ };
+ let outcome: Result<bool> = async {
+ let mut commands = Vec::new();
+ if origin == Some(row.active_session_id.as_str()) {
+ commands.push(("append_custom_message", json!({ "message": {
+ "customType": "prime-agent.update_complete",
+ "content": format!("[update-complete]\n\nPrime Agent updated to v{version}. This daemon session was restored after the update."),
+ "display": true,
+ "details": { "version": version },
+ }})));
+ }
+ if !row.queue.next_turn.is_empty() {
+ commands.push((
+ "restore_next_turn",
+ json!({ "messages": row.queue.next_turn }),
+ ));
+ }
+ if row.should_resume && has_actions {
+ commands.push(("restore_actions", json!({ "snapshot": row.queue.actions })));
+ }
+ for (command, payload) in commands {
+ let response = route(command, payload)
+ .await
+ .with_context(|| format!("legacy update {command}"))?;
+ anyhow::ensure!(
+ response.success,
+ "legacy update {command}: {}",
+ response.error.unwrap_or_default()
+ );
+ }
+ if !row.should_resume {
+ return Ok(false);
+ }
+ let accepted_turn = actions.is_some_and(|actions| {
+ actions.iter().any(|action| {
+ let payload = &action["payload"];
+ payload["kind"] == "turn"
+ && payload["queueVisible"] == false
+ && payload["acceptedBeforeCompletion"] == true
+ })
+ });
+ let in_flight = row.in_flight;
+ let interrupted = in_flight.streaming
+ || in_flight.compacting
+ || in_flight.bash_running
+ || in_flight.rlm_children
+ || in_flight.retrying
+ || in_flight.prompt_in_flight;
+ let mut resumed = false;
+ if interrupted && !accepted_turn {
+ let response = route(
+ "prompt",
+ json!({
+ "message": UPDATE_RESTART_CONTINUATION_PROMPT, "expandPromptTemplates": false,
+ }),
+ )
+ .await?;
+ resumed = response.success;
+ if !resumed {
+ anyhow::bail!(
+ "legacy update continuation: {}",
+ response.error.unwrap_or_default()
+ );
+ }
+ }
+ Ok(resumed || has_actions)
+ }
+ .await;
+ if let Some(pause_id) = pause {
+ // A partial restore remains parked on failure, but release the temporary
+ // lease so the ordinary user resume action can recover the session.
+ if outcome.is_err() {
+ // Best-effort abort: its failure must not skip the release below
+ // and leave the input pause held.
+ match route("abort", json!({})).await {
+ Ok(response) if response.success => {}
+ Ok(response) => eprintln!(
+ "pa-daemon: legacy update abort after failed restore also failed: {}",
+ response.error.unwrap_or_default()
+ ),
+ Err(error) => eprintln!(
+ "pa-daemon: legacy update abort after failed restore also failed: {error:#}"
+ ),
+ }
+ }
+ let response = route(
+ "release_session_input_pause",
+ json!({
+ "pauseId": pause_id, "clientId": UPDATE_RESTORE_CLIENT_ID,
+ }),
+ )
+ .await?;
+ anyhow::ensure!(
+ response.success,
+ "legacy update release_session_input_pause: {}",
+ response.error.unwrap_or_default()
+ );
+ }
+ outcome
+}
+
/// Re-create one roster row's session from the durable create command the roster captured (spec §8
/// `runtime_config`): the supervisor's own create path, under the restore client id.
async fn restore_session(
supervisor: &std::sync::Arc<Supervisor>,
row: &UpdateRosterSession,
+ restored_ids: Option<&BTreeMap<String, String>>,
) -> Result<std::sync::Arc<ResidentWorker>> {
let durable = row
.runtime_config
@@ -423,7 +692,10 @@ async fn restore_session(
.context("the roster row carries no create command")?;
let durable: pa_types::daemon::DurableDaemonCreateCommand =
serde_json::from_value(durable).context("parse the roster row's create command")?;
- let payload = crate::descriptor::create_command_payload(&durable);
+ let mut payload = crate::descriptor::create_command_payload(&durable);
+ if let Some(restored_ids) = restored_ids {
+ remap_legacy_parent(&mut payload, restored_ids);
+ }
let command: DaemonCommand =
serde_json::from_value(payload).context("rebuild the create command")?;
let summary = supervisor
@@ -440,6 +712,26 @@ async fn restore_session(
.context("the restored session did not register")
}
+/// TS restores parent sessions first and substitutes their new active handles;
+/// omit an unavailable parent handle instead of retaining a dead TS handle.
+fn remap_legacy_parent(payload: &mut serde_json::Value, restored_ids: &BTreeMap<String, String>) {
+ let Some(metadata) = payload
+ .get_mut("runtimeMetadata")
+ .and_then(serde_json::Value::as_object_mut)
+ else {
+ return;
+ };
+ if metadata.get("kind").and_then(serde_json::Value::as_str) != Some("subagent") {
+ return;
+ }
+ let Some(old_parent) = metadata.remove("parentActiveSessionId") else {
+ return;
+ };
+ if let Some(new_parent) = old_parent.as_str().and_then(|id| restored_ids.get(id)) {
+ metadata.insert("parentActiveSessionId".into(), json!(new_parent));
+ }
+}
+
/// The TS-parity continuation treatment (spec §10.5): a row mid-turn when the snapshot was taken
/// gets the continuation prompt; a failed prompt is a resume failure, not a restore failure.
async fn continuation_treatment(
@@ -613,6 +905,372 @@ mod tests {
.unwrap()
}
+ #[tokio::test]
+ async fn legacy_restore_replays_context_and_actions_before_continuing_each_interrupted_kind() {
+ for flag in [
+ "streaming",
+ "compacting",
+ "bash_running",
+ "rlm_children",
+ "retrying",
+ "prompt_in_flight",
+ ] {
+ let mut row = two_row_roster().sessions.remove(0);
+ row.should_resume = true;
+ let mut in_flight = serde_json::to_value(row.in_flight).unwrap();
+ in_flight[flag] = json!(true);
+ row.in_flight = serde_json::from_value(in_flight).unwrap();
+ row.queue.next_turn = serde_json::from_value(json!([{
+ "customType": "saved-context", "content": "keep this", "display": false,
+ "timestamp": 1
+ }]))
+ .unwrap();
+ row.queue.actions = json!({ "formatVersion": 1, "actions": [{
+ "id": "queued", "payload": { "kind": "turn", "text": "next task", "queueVisible": true }
+ }] });
+ let mut calls = Vec::new();
+ let resumed =
+ restore_legacy_session(&row, Some("active-a"), "1.0.0", |command, payload| {
+ calls.push((command, payload));
+ std::future::ready(Ok(crate::protocol::response_success(
+ None,
+ command,
+ Some(json!({ "pauseId": "test-pause" })),
+ )))
+ })
+ .await
+ .unwrap();
+ assert!(resumed, "{flag}");
+ assert_eq!(
+ calls,
+ vec![
+ (
+ "acquire_session_input_pause",
+ json!({ "leaseKey": "legacy-update-restore", "clientId": UPDATE_RESTORE_CLIENT_ID })
+ ),
+ (
+ "append_custom_message",
+ json!({ "message": {
+ "customType": "prime-agent.update_complete",
+ "content": "[update-complete]\n\nPrime Agent updated to v1.0.0. This daemon session was restored after the update.",
+ "display": true, "details": { "version": "1.0.0" }
+ }})
+ ),
+ (
+ "restore_next_turn",
+ json!({ "messages": row.queue.next_turn })
+ ),
+ ("restore_actions", json!({ "snapshot": row.queue.actions })),
+ (
+ "prompt",
+ json!({ "message": UPDATE_RESTART_CONTINUATION_PROMPT, "expandPromptTemplates": false })
+ ),
+ (
+ "release_session_input_pause",
+ json!({ "pauseId": "test-pause", "clientId": UPDATE_RESTORE_CLIENT_ID })
+ ),
+ ],
+ "{flag}"
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn legacy_restore_resumes_an_accepted_turn_without_duplicating_its_prompt() {
+ let mut row = two_row_roster().sessions.remove(0);
+ row.should_resume = true;
+ row.in_flight.prompt_in_flight = true;
+ row.queue.actions = json!({ "formatVersion": 1, "actions": [{
+ "id": "accepted", "payload": { "kind": "turn", "text": "already admitted",
+ "queueVisible": false, "acceptedBeforeCompletion": true }
+ }] });
+ let mut calls = Vec::new();
+ assert!(
+ restore_legacy_session(&row, None, "1.0.0", |command, payload| {
+ calls.push((command, payload));
+ std::future::ready(Ok(crate::protocol::response_success(
+ None,
+ command,
+ Some(json!({ "pauseId": "test-pause" })),
+ )))
+ })
+ .await
+ .unwrap()
+ );
+ assert_eq!(
+ calls,
+ vec![
+ (
+ "acquire_session_input_pause",
+ json!({ "leaseKey": "legacy-update-restore", "clientId": UPDATE_RESTORE_CLIENT_ID })
+ ),
+ ("restore_actions", json!({ "snapshot": row.queue.actions })),
+ (
+ "release_session_input_pause",
+ json!({ "pauseId": "test-pause", "clientId": UPDATE_RESTORE_CLIENT_ID })
+ ),
+ ]
+ );
+ }
+
+ #[tokio::test]
+ async fn legacy_restore_does_not_resume_idle_sessions_and_reports_failed_queue_restore() {
+ let mut row = two_row_roster().sessions.remove(0);
+ row.queue.actions = json!({ "formatVersion": 1, "actions": [{"id": "queued"}] });
+ let mut calls = Vec::new();
+ assert!(!restore_legacy_session(&row, None, "1.0.0", |command, _| {
+ calls.push(command);
+ std::future::ready(Ok(crate::protocol::response_success(
+ None,
+ command,
+ Some(json!({ "pauseId": "test-pause" })),
+ )))
+ })
+ .await
+ .unwrap());
+ assert!(calls.is_empty());
+ row.should_resume = true;
+ let mut failed_calls = Vec::new();
+ let error = restore_legacy_session(&row, None, "1.0.0", |command, _| {
+ failed_calls.push(command);
+ let response = if command == "restore_actions" {
+ crate::protocol::response_failure(None, command, "invalid action", None)
+ } else {
+ crate::protocol::response_success(
+ None,
+ command,
+ Some(json!({ "pauseId": "test-pause" })),
+ )
+ };
+ std::future::ready(Ok(response))
+ })
+ .await
+ .unwrap_err();
+ assert_eq!(
+ failed_calls,
+ [
+ "acquire_session_input_pause",
+ "restore_actions",
+ "abort",
+ "release_session_input_pause"
+ ]
+ );
+ assert_eq!(
+ error.to_string(),
+ "legacy update restore_actions: invalid action"
+ );
+ }
+
+ #[tokio::test]
+ async fn legacy_restore_releases_input_pause_when_abort_fails() {
+ let mut row = two_row_roster().sessions.remove(0);
+ row.should_resume = true;
+ row.queue.actions = json!({ "formatVersion": 1, "actions": [{"id": "queued"}] });
+ let mut calls = Vec::new();
+ let error = restore_legacy_session(&row, None, "1.0.0", |command, _| {
+ calls.push(command);
+ let response = match command {
+ "restore_actions" => {
+ crate::protocol::response_failure(None, command, "invalid action", None)
+ }
+ "abort" => crate::protocol::response_failure(None, command, "abort refused", None),
+ _ => crate::protocol::response_success(
+ None,
+ command,
+ Some(json!({ "pauseId": "test-pause" })),
+ ),
+ };
+ std::future::ready(Ok(response))
+ })
+ .await
+ .unwrap_err();
+ // A failed abort must not skip the release: a leaked pause would leave
+ // the session unable to accept input.
+ assert_eq!(
+ calls,
+ [
+ "acquire_session_input_pause",
+ "restore_actions",
+ "abort",
+ "release_session_input_pause"
+ ]
+ );
+ assert_eq!(
+ error.to_string(),
+ "legacy update restore_actions: invalid action"
+ );
+ }
+
+ #[tokio::test]
+ async fn legacy_manifest_restores_real_worker_context_and_both_queue_lanes() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let worker = crate::worker::Worker::new(
+ crate::worker::WorkerConfig {
+ socket_path: dir.path().join("worker.sock"),
+ supervisor_socket_path: std::path::PathBuf::new(),
+ token: "token".into(),
+ worker_instance_id: String::new(),
+ active_session_id: "active-a".into(),
+ agent_dir: dir.path().join("agent"),
+ recovery_journal_path: dir.path().join("recovery.jsonl"),
+ telemetry_disabled: Some(true),
+ script: Some(json!({ "responses": ["ack"] })),
+ },
+ None,
+ );
+ assert!(
+ worker
+ .dispatch("create", &json!({ "noSession": true, "cwd": dir.path() }))
+ .await
+ .success
+ );
+ let mut row = two_row_roster().sessions.remove(0);
+ row.should_resume = true;
+ row.queue.next_turn = serde_json::from_value(json!([{
+ "customType": "saved-context", "content": "pending context", "display": false,
+ "timestamp": 1
+ }]))
+ .unwrap();
+ row.queue.actions = json!({ "formatVersion": 1, "actions": [
+ { "id": "steer", "delivery": "next_turn_boundary", "payload": { "kind": "turn", "text": "steering task" } },
+ { "id": "follow", "delivery": "when_run_idle", "payload": { "kind": "turn", "text": "follow-up task" } }
+ ] });
+ let resumed = restore_legacy_session(&row, None, "1.0.0", |command, payload| {
+ let worker = &worker;
+ async move { Ok(worker.dispatch(command, &payload).await) }
+ })
+ .await
+ .unwrap();
+ assert!(resumed);
+ let core = worker.core.lock().unwrap();
+ assert_eq!(
+ (
+ core.pending_next_turn[0]["content"].clone(),
+ core.steering
+ .iter()
+ .map(|item| item.message.clone())
+ .collect::<Vec<_>>(),
+ core.follow_up
+ .iter()
+ .map(|item| item.message.clone())
+ .collect::<Vec<_>>()
+ ),
+ (
+ json!("pending context"),
+ vec!["steering task".to_string()],
+ vec!["follow-up task".to_string()]
+ )
+ );
+ }
+
+ #[tokio::test]
+ async fn legacy_busy_restore_keeps_follow_up_behind_continuation_with_a_running_worker() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let worker = crate::worker::Worker::new(
+ crate::worker::WorkerConfig {
+ socket_path: dir.path().join("worker.sock"),
+ supervisor_socket_path: std::path::PathBuf::new(),
+ token: "token".into(),
+ worker_instance_id: String::new(),
+ active_session_id: "active-a".into(),
+ agent_dir: dir.path().join("agent"),
+ recovery_journal_path: dir.path().join("recovery.jsonl"),
+ telemetry_disabled: Some(true),
+ script: Some(json!({ "responses": ["ack", "done"] })),
+ },
+ None,
+ );
+ assert!(
+ worker
+ .dispatch("create", &json!({ "noSession": true, "cwd": dir.path() }))
+ .await
+ .success
+ );
+ let mut events = worker.events.subscribe();
+ let mut row = two_row_roster().sessions.remove(0);
+ row.should_resume = true;
+ row.in_flight.streaming = true;
+ row.queue.actions = json!({ "formatVersion": 1, "actions": [{
+ "id": "follow", "delivery": "when_run_idle", "source": "interactive",
+ "payload": { "kind": "turn", "text": "queued follow-up", "queueVisible": true }
+ }] });
+ assert!(
+ restore_legacy_session(&row, None, "1.0.0", |command, payload| {
+ let worker = &worker;
+ async move {
+ // Observe the real runner handling the restore wake before the
+ // coordinator can admit its continuation. No sleeps or retries.
+ let parked = worker.idle_notify.notified();
+ tokio::pin!(parked);
+ parked.as_mut().enable();
+ let response = worker.dispatch(command, &payload).await;
+ if command == "restore_actions" {
+ worker.work_notify.notify_one();
+ tokio::time::timeout(std::time::Duration::from_secs(5), parked)
+ .await
+ .unwrap();
+ let core = worker.core.lock().unwrap();
+ assert_eq!(
+ (core.busy, core.follow_up.len()),
+ (false, 1),
+ "restored follow-up ran before continuation admission"
+ );
+ }
+ Ok(response)
+ }
+ })
+ .await
+ .unwrap()
+ );
+ let delivered = tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ let mut delivered = Vec::new();
+ while delivered.len() < 2 {
+ let frame = events.recv().await.unwrap();
+ let frame: serde_json::Value = serde_json::from_slice(&frame.payload).unwrap();
+ let event = &frame["event"];
+ if event["type"] == "message_end" && event["message"]["role"] == "user" {
+ let content = &event["message"]["content"];
+ let text = content
+ .as_str()
+ .or_else(|| content[0]["text"].as_str())
+ .unwrap();
+ delivered.push(text.to_string());
+ }
+ }
+ delivered
+ })
+ .await
+ .unwrap();
+ assert_eq!(
+ delivered,
+ [UPDATE_RESTART_CONTINUATION_PROMPT, "queued follow-up"]
+ );
+ worker.core.lock().unwrap().shutdown_requested = true;
+ worker.work_notify.notify_one();
+ }
+
+ #[test]
+ fn legacy_child_metadata_replaces_only_the_old_parent_handle() {
+ let mut payload = json!({ "runtimeMetadata": {
+ "kind": "subagent", "parentActiveSessionId": "old-parent", "rlmChildId": "child"
+ }});
+ remap_legacy_parent(
+ &mut payload,
+ &BTreeMap::from([("old-parent".into(), "new-parent".into())]),
+ );
+ assert_eq!(
+ payload,
+ json!({ "runtimeMetadata": {
+ "kind": "subagent", "parentActiveSessionId": "new-parent", "rlmChildId": "child"
+ }})
+ );
+ remap_legacy_parent(&mut payload, &BTreeMap::new());
+ assert_eq!(
+ payload,
+ json!({ "runtimeMetadata": { "kind": "subagent", "rlmChildId": "child" }})
+ );
+ }
+
#[test]
fn hello_resume_reports_progress_before_and_after_settle() {
let progress = RestoreProgress::new();
@@ -730,6 +1388,18 @@ mod tests {
assert!(tokio::time::timeout(tick, queued_a).await.is_ok());
}
+ #[test]
+ fn legacy_adoption_waits_for_manifest_queue_replay_even_when_idle() {
+ let mut roster = two_row_roster();
+ roster.rest.insert("legacy_ts_restart".into(), json!(true));
+ let progress = RestoreProgress::new();
+ progress.begin(Some(&roster));
+ progress.settle_adopted("a-1");
+ assert!(!progress.state.lock().unwrap().targets["a-1"].settled);
+ progress.settle_target("a-1", None);
+ assert!(progress.state.lock().unwrap().targets["a-1"].settled);
+ }
+
#[tokio::test(start_paused = true)]
async fn a_continuation_skip_is_still_progress_for_the_other_waiters() {
let mut roster = two_row_roster();
@@ -902,6 +1572,79 @@ mod tests {
assert!(other_socket_dir.exists());
}
+ #[test]
+ fn boot_sweep_preserves_socket_bound_lost_reply_sources_until_attempts_finish() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let agent_dir = dir.path().join("agent");
+ let socket = dir.path().join("daemon.sock");
+ let other_socket = dir.path().join("other.sock");
+ let sources = legacy_update_restarts_dir(&agent_dir);
+ let recovery = agent_dir.join("legacy-update-recovery");
+ std::fs::create_dir_all(&sources).unwrap();
+ std::fs::create_dir_all(&recovery).unwrap();
+ let mut attempts = Vec::new();
+ let mut manifests = Vec::new();
+ for pending_socket in [&socket, &other_socket] {
+ let key = crate::paths::hash_key(&pending_socket.to_string_lossy(), 64);
+ let attempt = recovery.join(format!("{key}.attempt.json"));
+ let manifest = sources.join(format!("{key}.json"));
+ std::fs::write(&attempt, serde_json::to_vec(&json!({
+ "socket": pending_socket, "version": "older-target-version", "updateId": "pending",
+ "startedAt": 123, "previousDigest": null, "origin": null,
+ "hello": { "supervisorPid": 42, "supervisorProcessStartId": "start",
+ "supervisorGeneration": "generation" }
+ })).unwrap()).unwrap();
+ std::fs::write(&manifest, "prepared TS session and queue snapshot").unwrap();
+ attempts.push(attempt);
+ manifests.push(manifest);
+ }
+ let checkpoint = recovery.join("retained-checkpoint.json");
+ std::fs::write(&checkpoint, "converted roster").unwrap();
+ let stale = sources.join("unrelated.json");
+ std::fs::write(&stale, "stale snapshot").unwrap();
+ // A marker at the wrong key cannot preserve an unrelated source.
+ std::fs::copy(&attempts[0], recovery.join("unrelated.attempt.json")).unwrap();
+ let malformed = sources.join("malformed.json");
+ std::fs::write(&malformed, "stale snapshot").unwrap();
+ std::fs::write(recovery.join("malformed.attempt.json"), "not JSON").unwrap();
+ boot_sweep(&agent_dir, &socket);
+ assert_eq!(
+ manifests
+ .iter()
+ .map(std::fs::read_to_string)
+ .collect::<std::io::Result<Vec<_>>>()
+ .unwrap(),
+ [
+ "prepared TS session and queue snapshot",
+ "prepared TS session and queue snapshot"
+ ]
+ );
+ assert!(!stale.exists());
+ assert!(!malformed.exists());
+ assert!(attempts.iter().all(|path| path.exists()));
+ assert_eq!(
+ std::fs::read_to_string(&checkpoint).unwrap(),
+ "converted roster"
+ );
+
+ // Successful coordinator adoption removes its attempt. A later boot can
+ // sweep that source without destroying another socket's pending recovery.
+ std::fs::remove_file(&attempts[0]).unwrap();
+ boot_sweep(&agent_dir, &socket);
+ assert!(!manifests[0].exists());
+ assert_eq!(
+ std::fs::read_to_string(&manifests[1]).unwrap(),
+ "prepared TS session and queue snapshot"
+ );
+ std::fs::remove_file(&attempts[1]).unwrap();
+ boot_sweep(&agent_dir, &socket);
+ assert!(!sources.exists());
+ assert_eq!(
+ std::fs::read_to_string(checkpoint).unwrap(),
+ "converted roster"
+ );
+ }
+
#[test]
fn consume_roster_env_none_without_the_env() {
// NOTE: process env is global; this documents the None path only when no
diff --git a/crates/pa-daemon/src/worker.rs b/crates/pa-daemon/src/worker.rs
index 256606d71c..04db62b0de 100644
--- a/crates/pa-daemon/src/worker.rs
+++ b/crates/pa-daemon/src/worker.rs
@@ -85,10 +85,10 @@ use crate::peer::{
PEER_COMMAND_NOT_ALLOWED,
};
use crate::protocol::{
- create_daemon_event_meta, create_daemon_replay_info, current_protocol_info,
+ app_version, create_daemon_event_meta, create_daemon_replay_info, current_protocol_info,
default_client_capabilities, normalize_client_capabilities, response_failure, response_success,
DaemonOutbound, DaemonResponse, DaemonResumeCursor, DaemonSessionClosedReason,
- DAEMON_APP_VERSION, DAEMON_SCHEMA_ID, DAEMON_SCHEMA_REVISION,
+ DAEMON_SCHEMA_ID, DAEMON_SCHEMA_REVISION,
};
use crate::registration::RegistrationHandle;
use crate::session_store::{session_file_name, SessionFile};
diff --git a/crates/pa-daemon/src/worker/connection.rs b/crates/pa-daemon/src/worker/connection.rs
index 72ff9b66f2..c39ceefc3f 100644
--- a/crates/pa-daemon/src/worker/connection.rs
+++ b/crates/pa-daemon/src/worker/connection.rs
@@ -1,12 +1,12 @@
//! Client connections: accept, authenticate, and the frame/event plumbing
//! between the worker and its supervisor.
use super::{
- active_session_id_of, anyhow, bind_transport, broadcast, create_daemon_replay_info,
- current_protocol_info, default_client_capabilities, json, normalize_client_capabilities,
- peer_command_allowed, response_failure, response_success, worker_peer_command_allowed,
- worker_server_capabilities, write_frame, write_frame_segments, Arc, AtomicU64, ConnectionRole,
- Context, DaemonOutbound, DaemonResponse, DaemonResumeCursor, Map, Ordering, Result,
- TransportStream, Value, Worker, WorkerRecoveryJournal, DAEMON_APP_VERSION, DAEMON_SCHEMA_ID,
+ active_session_id_of, anyhow, app_version, bind_transport, broadcast,
+ create_daemon_replay_info, current_protocol_info, default_client_capabilities, json,
+ normalize_client_capabilities, peer_command_allowed, response_failure, response_success,
+ worker_peer_command_allowed, worker_server_capabilities, write_frame, write_frame_segments,
+ Arc, AtomicU64, ConnectionRole, Context, DaemonOutbound, DaemonResponse, DaemonResumeCursor,
+ Map, Ordering, Result, TransportStream, Value, Worker, WorkerRecoveryJournal, DAEMON_SCHEMA_ID,
DAEMON_SCHEMA_REVISION, DEFAULT_PRIVATE_FRAME_LIMITS, PEER_COMMAND_NOT_ALLOWED,
};
@@ -325,7 +325,7 @@ impl Worker {
protocol: current_protocol_info(),
schema_id: Some(DAEMON_SCHEMA_ID.to_string()),
schema_revision: Some(DAEMON_SCHEMA_REVISION),
- app_version: Some(DAEMON_APP_VERSION.to_string()),
+ app_version: Some(app_version().to_string()),
runtime: None,
supervisor_generation: None,
supervisor_pid: Some(u64::from(std::process::id())),
diff --git a/docs/legacy-release-inventory.json b/docs/legacy-release-inventory.json
new file mode 100644
index 0000000000..5cafea59b0
--- /dev/null
+++ b/docs/legacy-release-inventory.json
@@ -0,0 +1,354 @@
+{
+ "retrieved_at": "2026-10-09",
+ "github_release_pages": 2,
+ "github_release_count": 107,
+ "stable_count": 18,
+ "releases": [
+ {
+ "tag": "v0.9.8",
+ "target_commitish": "7d442aafa985f9342134fac16c2ef41f03fb45c1",
+ "published_at": "2026-09-29T22:06:42Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.9.8",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.9.8.tgz",
+ "digest": "sha256:d7b72785119efc28bfbca8ec4a7f47a1fcdcf47fcd8cebdb60bffaa79e3e1274",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.9.8/prime-agent-0.9.8.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "beta",
+ "target_commitish": "7d442aafa985f9342134fac16c2ef41f03fb45c1",
+ "published_at": "2026-07-17T23:04:57Z",
+ "prerelease": true,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/beta",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.9.8-beta.2286.1.7d442aa.tgz",
+ "digest": "sha256:7a311e2d7fd45c0b9f134197bb3101ebc11233c6c2bf649c4d574a0d98d3473b",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/beta/prime-agent-0.9.8-beta.2286.1.7d442aa.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.9.7",
+ "target_commitish": "08ff1b2e2794ea9e8f4a08d12bc95408a66e1074",
+ "published_at": "2026-09-28T23:13:49Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.9.7",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.9.7.tgz",
+ "digest": "sha256:d696f2636cd7780d2d67296142bc1d13d72960c8be4e5cfae0bbba82f9d8707d",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.9.7/prime-agent-0.9.7.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.9.6",
+ "target_commitish": "e260085dd8f742e0def3d871860c9a888b114851",
+ "published_at": "2026-09-24T01:01:53Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.9.6",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.9.6.tgz",
+ "digest": "sha256:e5bf0e349e55b3f75c79e66006c993b10c51ed1c9bf15863b06658fcaf0232b2",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.9.6/prime-agent-0.9.6.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "releases/v0.9.1-fhcache1",
+ "target_commitish": "da819d32f6a3f57e71f5d5fb784a4958929dbdae",
+ "published_at": "2026-09-20T03:45:42Z",
+ "prerelease": true,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/releases/v0.9.1-fhcache1",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.9.1-fhcache1.tgz",
+ "digest": "sha256:4a461bf7fc9d8e6e4e61471b66341aff05ba94e02c6c25f678851d26d1b27d2c",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/releases/v0.9.1-fhcache1/prime-agent-0.9.1-fhcache1.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "fhcache-candidate-1",
+ "target_commitish": "da819d32f6a3f57e71f5d5fb784a4958929dbdae",
+ "published_at": "2026-09-20T03:33:40Z",
+ "prerelease": true,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/fhcache-candidate-1",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.9.1-fhcache1.tgz",
+ "digest": "sha256:4a461bf7fc9d8e6e4e61471b66341aff05ba94e02c6c25f678851d26d1b27d2c",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/fhcache-candidate-1/prime-agent-0.9.1-fhcache1.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.9.5",
+ "target_commitish": "a7d791bc1be09793ed5f3ec05bf4cccbc60679ea",
+ "published_at": "2026-09-16T00:13:49Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.9.5",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.9.5.tgz",
+ "digest": "sha256:349f1682c7909550842f1b04a71ba95814341b136474ade736df93f8ec006876",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.9.5/prime-agent-0.9.5.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.9.4",
+ "target_commitish": "f771dfcedd684d1afff84ca2c6fa95c7a21efbc2",
+ "published_at": "2026-09-08T23:18:05Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.9.4",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.9.4.tgz",
+ "digest": "sha256:b8d752a53d11a8c9a7580e1fb5fc24f7ce74ccad979c7e6e6aa8880fc3ad90b0",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.9.4/prime-agent-0.9.4.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.9.3",
+ "target_commitish": "915c78f42c248b08238dd27fcd4bcab32c60beab",
+ "published_at": "2026-09-06T10:44:04Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.9.3",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.9.3.tgz",
+ "digest": "sha256:ce71049389877770aa31b9be64c473685a86159adbbd2466bd43e4a9113242f1",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.9.3/prime-agent-0.9.3.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.9.2",
+ "target_commitish": "9c54a35dac3a2ad17910074d66664859ea175666",
+ "published_at": "2026-09-05T19:14:39Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.9.2",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.9.2.tgz",
+ "digest": "sha256:d649b9f0258c77de7d02aba33d786925ce41a36b601e8e24eef0f00bdc2f1f49",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.9.2/prime-agent-0.9.2.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.9.1",
+ "target_commitish": "81ae3cb34d27d38ee37f9e205a1e73694993b344",
+ "published_at": "2026-09-01T18:54:36Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.9.1",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.9.1.tgz",
+ "digest": "sha256:573bce0cd004fc62052e9a924089941b7f39266ab71e66a94c85a1f9d35835ba",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.9.1/prime-agent-0.9.1.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.9.0",
+ "target_commitish": "c394506e2f0dd887b3f94908da9f2910b43c846b",
+ "published_at": "2026-09-01T18:18:51Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.9.0",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.9.0.tgz",
+ "digest": "sha256:fc560ec74195297999405d4fbfd0d308598cf502e0fccef7f02eb60032213108",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.9.0/prime-agent-0.9.0.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.8.1",
+ "target_commitish": "514633727bf26d74f39f3119c2b0e31a5ceb2a9d",
+ "published_at": "2026-08-26T05:14:48Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.8.1",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.8.1.tgz",
+ "digest": "sha256:46c24db1782dd31adc35d5c6cbcc75564faba6ced3bf2ccf03d836ee77134475",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.8.1/prime-agent-0.8.1.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.8.0",
+ "target_commitish": "8d7deeab5861bf9d77bde3d8511046a5c799818d",
+ "published_at": "2026-08-21T21:18:10Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.8.0",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.8.0.tgz",
+ "digest": "sha256:f5b0093c7e0fddb73f94773d74383585456adfa84f12a4082d3098f23bb8fab6",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.8.0/prime-agent-0.8.0.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.7.4",
+ "target_commitish": "af0b8e00b9f704e834787fd321065ca78281f2aa",
+ "published_at": "2026-08-19T23:44:42Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.7.4",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.7.4.tgz",
+ "digest": "sha256:dea045d7c170466a102e030e940f459cc13f2c113465f40be1c7505d80405d2e",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.7.4/prime-agent-0.7.4.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.7.3",
+ "target_commitish": "61131b2d195ba7a67a4ce8ac60bb10cecae07b67",
+ "published_at": "2026-08-17T22:38:17Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.7.3",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.7.3.tgz",
+ "digest": "sha256:2a188738318b91ff91ea77b8a0b215c41543cf0483fcb18a53475dc4e7032784",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.7.3/prime-agent-0.7.3.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.7.2",
+ "target_commitish": "83a0f9f9566219551fcb6ffaf7f519a815749a58",
+ "published_at": "2026-08-11T19:00:48Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.7.2",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.7.2.tgz",
+ "digest": "sha256:bc5471f2a626d727b88a45eb745fff93b10c554a3c4fc5912f25d8c64b987f5e",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.7.2/prime-agent-0.7.2.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.7.1",
+ "target_commitish": "95afd319a78ae017a41241d50b013d656a0685ce",
+ "published_at": "2026-08-07T18:39:08Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.7.1",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.7.1.tgz",
+ "digest": "sha256:d68612c83239caafab72cc76c55ac572bfd07a059ea8fbd2a3ddbe1f2b55dcdb",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.7.1/prime-agent-0.7.1.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.7.0",
+ "target_commitish": "be9e2fa0714e7cd1c6bd9bdb1b554d2cc6550387",
+ "published_at": "2026-08-05T18:41:37Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.7.0",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.7.0.tgz",
+ "digest": "sha256:88b6578518c72cd51a825bc80f28e0fef9a64c67de4a7d6fd7afd7ca1b34da0b",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.7.0/prime-agent-0.7.0.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.6.1",
+ "target_commitish": "8bd7c18f16bfdc356c1cd20fb9fcf01119147cda",
+ "published_at": "2026-08-05T14:55:26Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.6.1",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.6.1.tgz",
+ "digest": "sha256:4c7150dbfe5807c8480676d20c3104e63045b8ca2463abf38f021062e9fcacef",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.6.1/prime-agent-0.6.1.tgz"
+ }
+ ]
+ },
+ {
+ "tag": "v0.6.0",
+ "target_commitish": "7db7b69c60be0f7b271faf948864891813b27182",
+ "published_at": "2026-08-05T04:36:20Z",
+ "prerelease": false,
+ "url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/tag/v0.6.0",
+ "npm_assets": [
+ {
+ "name": "prime-agent-0.6.0.tgz",
+ "digest": "sha256:8ef229a0422398174ba8f0ba4f7101adfc614b023a8f819f6ef3920e5d2350c6",
+ "browser_download_url": "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v0.6.0/prime-agent-0.6.0.tgz"
+ }
+ ]
+ }
+ ],
+ "support_scope": "Prime Agent 0.6.0 onward",
+ "rust_beta_tags": [
+ "v0.9.9-beta.10",
+ "v0.9.9-beta.4",
+ "v0.9.9-beta.6",
+ "v0.9.9-beta.7",
+ "v0.9.9-beta.8",
+ "v0.9.9-beta.9",
+ "v0.9.9-beta.11",
+ "v0.9.9-beta.17",
+ "v0.9.9-beta.18",
+ "v0.9.9-beta.21",
+ "v0.9.9-beta.22",
+ "v0.9.9-beta.23",
+ "v0.9.9-beta.24",
+ "v0.9.9-beta.25",
+ "v0.9.9-beta.26",
+ "v0.9.9-beta.27",
+ "v0.9.9-beta.28",
+ "v0.9.9-beta.29",
+ "v0.9.9-beta.30",
+ "v0.9.9-beta.31",
+ "v0.9.9-beta.32",
+ "v0.9.9-beta.33",
+ "v0.9.9-beta.34",
+ "v0.9.9-beta.35",
+ "v0.9.9-beta.36",
+ "v0.9.9-beta.37",
+ "v0.9.9-beta.38",
+ "v0.9.9-beta.39",
+ "v0.9.9-beta.40",
+ "v0.9.9-beta.41",
+ "v0.9.9-beta.42",
+ "v0.9.9-beta.43",
+ "v0.9.9-beta.44",
+ "v0.9.9-beta.45",
+ "v0.9.9-beta.46",
+ "v0.9.9-beta.47",
+ "v0.9.9-beta.48",
+ "v0.9.9-beta.49",
+ "v0.9.9-beta.50",
+ "v0.9.9-beta.51",
+ "v0.9.9-beta.52",
+ "v0.9.9-beta.53",
+ "v0.9.9-beta.54",
+ "v0.9.9-beta.55",
+ "v0.9.9-beta.56",
+ "v0.9.9-beta.57",
+ "v0.9.9-beta.58",
+ "v0.9.9-beta.59",
+ "v0.9.9-beta.60"
+ ]
+}
diff --git a/docs/legacy-upgrade-contract.md b/docs/legacy-upgrade-contract.md
new file mode 100644
index 0000000000..702b665b16
--- /dev/null
+++ b/docs/legacy-upgrade-contract.md
@@ -0,0 +1,217 @@
+# Legacy TypeScript upgrade contract
+
+This audit covers published Prime Agent releases from v0.6.0 onward, including
+18 stable TypeScript releases through v0.9.8 and relevant candidate and beta
+artifacts. Earlier versions are excluded from the requested support scope.
+Inventory and source comparison are not evidence that an installed-artifact
+upgrade or every supported platform has passed testing.
+
+## Published inventory in scope
+
+A full two-page GitHub Releases API query on 2026-10-09 returned 107 releases.
+The compact [release inventory](legacy-release-inventory.json) records the 18
+stable releases in scope, independent GitHub npm-asset digests, source targets,
+and relevant TS prereleases. The stable versions are 0.6.0–0.6.1,
+0.7.0–0.7.4, 0.8.0–0.8.1, and 0.9.0–0.9.8.
+
+All 18 have genuine published `prime-agent-VERSION.tgz` assets; this inventory
+does not count inherited upstream Git tags as Prime releases. The unscoped
+public npm registry endpoint for `prime-agent` returned 404 during this audit;
+these npm packages are published as tarballs through GitHub and the release bucket.
+
+Additional published TS artifacts are `0.9.1-fhcache1` (the same digest hosted by
+both `fhcache-candidate-1` and `releases/v0.9.1-fhcache1`) and the rolling `beta`
+release, currently `0.9.8-beta.2286.1.7d442aa`. The latter has npm and native
+archives. The fhcache package digest, independently supplied by the GitHub API,
+is `4a461bf7fc9d8e6e4e61471b66341aff05ba94e02c6c25f678851d26d1b27d2c`.
+It has no published SHA256SUMS file. A locally computed digest alone is not
+independent download verification.
+
+The 49 versioned Rust `0.9.9-beta.*` releases are distinct from TS migration
+fixtures and require Rust-to-Rust update coverage. Their exact published tags
+are recorded in the inventory. The `nightly` release is a rolling Rust asset host.
+Historical rolling TS beta assets are overwritten on GitHub; this inventory
+cannot establish an exhaustive list of every beta ever distributed through the
+bucket. Do not equate an absent GitHub beta tag with an unpublished build.
+
+## Authoritative release sources
+
+Use the GitHub release `target_commitish` below for source comparisons of the
+audited versions, then verify behavior against the actual published artifacts.
+Several local version tags resolve to upstream history with different package
+names and no Prime Agent updater. Those tags are not suitable fixtures for these
+releases. A recorded source target alone does not prove the bytes shipped; release
+assets remain the authoritative end-to-end test inputs.
+
+| Release | GitHub release target commit |
+| --- | --- |
+| v0.6.0 | `7db7b69c60be0f7b271faf948864891813b27182` |
+| v0.6.1 | `8bd7c18f16bfdc356c1cd20fb9fcf01119147cda` |
+| v0.7.0 | `be9e2fa0714e7cd1c6bd9bdb1b554d2cc6550387` |
+| v0.7.1 | `95afd319a78ae017a41241d50b013d656a0685ce` |
+| v0.7.2 | `83a0f9f9566219551fcb6ffaf7f519a815749a58` |
+| v0.7.3 | `61131b2d195ba7a67a4ce8ac60bb10cecae07b67` |
+| v0.7.4 | `af0b8e00b9f704e834787fd321065ca78281f2aa` |
+| v0.8.0 | `8d7deeab5861bf9d77bde3d8511046a5c799818d` |
+| v0.8.1 | `514633727bf26d74f39f3119c2b0e31a5ceb2a9d` |
+| v0.9.0 | `c394506e2f0dd887b3f94908da9f2910b43c846b` |
+| v0.9.1 | `81ae3cb34d27d38ee37f9e205a1e73694993b344` |
+| v0.9.2 | `9c54a35dac3a2ad17910074d66664859ea175666` |
+| v0.9.3 | `915c78f42c248b08238dd27fcd4bcab32c60beab` |
+| v0.9.4 | `f771dfcedd684d1afff84ca2c6fa95c7a21efbc2` |
+| v0.9.5 | `a7d791bc1be09793ed5f3ec05bf4cccbc60679ea` |
+| v0.9.6 | `e260085dd8f742e0def3d871860c9a888b114851` |
+| v0.9.7 | `08ff1b2e2794ea9e8f4a08d12bc95408a66e1074` |
+| v0.9.8 | `7d442aafa985f9342134fac16c2ef41f03fb45c1` |
+
+## Update families
+
+- v0.6.0–v0.9.4 ship npm tarballs. Their
+ `packages/coding-agent/src/utils/version-check.ts` files are byte-identical:
+ SHA-256 `5a87851fc4f6473452607cb2816945e82f37e35f3aa2ecc846b3d41f1932aa29`.
+- v0.9.5–v0.9.8 additionally ship managed native archives. Their manifest parsers
+ are byte-identical: SHA-256
+ `2a37f5116a6d855da564bb3efe4a6b62eb0d0a35523c369796b5529379dacff0`.
+ Their `cli/native-update.ts` files are also byte-identical: SHA-256
+ `707cdc796f035f01c08647c026a1f1a5aaeafbb3b4158a22e741b367a8d10f03`.
+
+All stable clients read `latest.json` under `PRIME_AGENT_DOWNLOAD_BASE_URL`, or
+the default release bucket. Beta clients read `beta.json`. The parser accepts
+`version`, `package` (or `packageName`), and `tarball`; relative tarball URLs
+resolve against the release bucket. Keep the npm tarball in the manifest even
+when native artifacts are present.
+
+## npm bridge requirements
+
+The published package builder rewrites the source package to **`prime-agent`**
+and the command to **`prime-agent`**, with entrypoint **`dist/bundle/cli.js`**.
+Do not infer the published package identity from the source package.json.
+
+The existing updater runs the detected global package manager against the
+manifest tarball. Supported command builders include npm, pnpm, yarn, and Bun;
+that source support is not a claim that each has been integration-tested.
+
+Keep the package name and `dist/bundle/cli.js` and
+`dist/bundle/cli-node.js` paths stable. The bridge also retains a thin
+`dist/cli.js` alias; that compatibility alias does not expand the tested version
+scope. In published v0.9.5–v0.9.8 npm
+artifacts, the packer moves the TS bundle to `cli-node.js` and puts the old
+native-migration shim at `cli.js`. When that shim falls back to Node, the
+updater's original entrypoint is `cli-node.js`. After package replacement the
+old CLI and TUI execute their original Node executable with that original
+absolute JavaScript entrypoint path. Both paths must run the new Rust bridge;
+a new command shim elsewhere does not repair this relaunch. The bridge must forward arguments, signals, terminal
+I/O, and exit codes and remain usable when package-manager install scripts are
+disabled. It must not remove its own package while the old process still needs
+to relaunch through it.
+
+### Failed migration and retry
+
+The bridge includes the checksum-pinned, genuine v0.9.8 TypeScript package as
+recovery. A host that cannot execute Rust must retain a usable public command,
+daemon, worker, and saved sessions. Explicit updates report failure; ordinary
+launches use recovery without repeatedly attempting the same failed install.
+
+For bridge-driven channel installs, the native executable must pass the bounded
+staged version probe before the installer replaces the public launcher. A valid
+archive checksum alone does not establish that the host can execute its payload.
+
+An explicit retry after failure must consult the current release through the
+preserved updater, including downloading its updated bridge and installer.
+Retrying only the failed bridge's pinned version would prevent a later release
+from adding support for that host. The retry may report success only after a
+working native version and its corresponding migration receipt are verified.
+
+## Managed native requirements
+
+The v0.9.5–v0.9.8 updater executes the installer bundled in the **old** release.
+Replacing only the new archive's install.sh cannot affect that installation.
+The old installer downloads
+`releases/vVERSION/prime-agent-VERSION-PLATFORM.tar.gz`, checks its checksum,
+and requires these regular files at the archive root:
+
+- `prime-agent`
+- `package.json` with the target version
+- `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`
+
+It requires `prime-agent --version` to print the bare target version and
+`prime-agent --help` to succeed. It then installs to
+`releases/VERSION-PLATFORM-SHA256[.SUFFIX]/`, writes `.archive-sha256` and
+`.install-source`, and atomically changes `bin/prime-agent`. The managed-root
+marker is `prime-agent-native-v1`.
+
+These same legacy files are revalidated by the still-running TS client before
+it can find the new launcher for restart. They must remain present after
+activation, including the two metadata files written by the old installer.
+The next Rust update must recognize this managed installation layout.
+
+The manifest parser prefers `binariesV2` over `binaries`; each accepted entry
+must have an exact platform-specific filename and lowercase 64-digit SHA-256.
+Retain the legacy platforms in the manifest only when the corresponding
+artifacts can actually run on those hosts.
+
+## Daemon and TUI handoff
+
+All audited versions launch the newly installed entrypoint with:
+
+```text
+update --internal-update-restart-coordinator --daemon-socket SOCKET
+ --internal-update-restart-status STATUS_PATH
+ [--internal-update-restart-origin SESSION_ID]
+```
+
+The TS parent creates the status directory but **does not create a staged
+status file**. The coordinator must initialize it. TS polls a version-1 JSON
+record with `requestId`, `socketPath`, `phase`, `coordinator.pid`,
+`counts: {total, restored, resumed, failed}`, `startedAt`, and `updatedAt`.
+Terminal phases are `complete`, `skipped`, and `failed`; other phases include
+`starting`, `preparing`, `stopping`, `starting_daemon`, and `restoring`.
+`heartbeatAt`, predecessor/successor identities, failures, and message are
+optional. Keep progress live during a long restore.
+
+This differs from the newer Rust staged-update FSM and its status schema.
+Recognizing the flag alone is insufficient: a legacy adapter must initialize
+and maintain TS-compatible status and use the TS daemon's
+`prepare_update_restart` / shutdown / session restoration contract. The parent
+otherwise reports a restart warning even if installation succeeded.
+
+For `/update`, the old TUI runs the update subprocess with
+`PRIME_AGENT_INTERACTIVE_SELF_UPDATE=1`, disposes its old connection, launches
+the coordinator itself, and relaunches with its saved session file. Do not
+restart the daemon prematurely from the installer or an executable probe.
+
+The TS daemon persists its restart manifest before replying to preparation.
+A lost reply therefore does not prove that preparation failed. Record a durable
+binding to the predecessor, socket, target release, and attempt before sending
+the request; recover a fresh scoped TS manifest only through that binding.
+Retain pending source manifests through ordinary startup cleanup until their
+state has been adopted. A definitive preparation refusal with no new manifest
+must allow another attempt. Queued actions must remain paused while the resumed
+continuation is admitted, so follow-up input cannot run ahead of that turn.
+
+## Platform limits and release claims
+
+The old native distribution supports Darwin arm64/x64 and Linux arm64/x64,
+including `linux-arm64-musl`, `linux-x64-baseline`, `linux-x64-musl`, and
+`linux-x64-musl-baseline`. The Rust release matrix currently ships GNU Linux
+builds with a GLIBC 2.35 ceiling and no musl target. A GNU archive must never be
+renamed to a musl suffix: that would turn a controlled refusal into a broken
+installation. Supporting Alpine/musl requires real musl artifacts and runtime
+verification. Older glibc hosts likewise need a compatible build or a clear
+unsupported-platform result before activation.
+
+The TS `baseline` suffix selects x64 CPUs without AVX2. Rust can reuse its
+ordinary x64 artifact for that alias only after verifying its target CPU and
+all bundled native dependencies work without AVX2; the absence of a separate
+Rust baseline target is not by itself proof.
+
+“All versions since 0.6” describes the source-version range, not an exemption
+from platform support. Do not claim every prior platform migrates until those
+platform gates pass. Test all 18 published npm releases, all four native source
+releases, CLI and TUI entrypoints, session preservation, daemon handoff, and a
+second Rust update using assembled artifacts.
diff --git a/docs/legacy-upgrade-evidence.md b/docs/legacy-upgrade-evidence.md
new file mode 100644
index 0000000000..d9ebf36dcf
--- /dev/null
+++ b/docs/legacy-upgrade-evidence.md
@@ -0,0 +1,137 @@
+# Legacy update compatibility evidence
+
+This is unreleased-candidate evidence, not approval to publish v1. All builds
+and runtime tests after the remote-only instruction ran in Prime sandboxes.
+Support scope starts at 0.6.0; no earlier versions are required.
+
+## Current verification status
+
+The consolidated source includes recovery hardening and current-main integration.
+Its final full repository gate and packaged-artifact migration rerun are pending.
+Earlier successful results below identify their exact snapshot; they are not
+silently attributed to the latest source.
+
+| Check | Verified result |
+| --- | --- |
+| npm CLI and TUI migration, all 18 stable TS versions | 36/36 on optimized candidate before final recovery hardening |
+| Native CLI and TUI migration, TS 0.9.5–0.9.8 | 8/8 on that optimized candidate |
+| Subsequent Rust 1.0.0 → 1.0.1 update | Passed through the original custom public command |
+| Fresh curl installation and reinstallation | Passed with final staged-probe installer |
+| Unusable native executable | Red reproduced; fixed installer retained usable TS recovery |
+| Failed migration followed by a newer release | Original update command reached Rust 1.0.1 |
+| Lost prepare response and retained queued work | Six focused coordinator tests passed; red-first regression reproduced |
+| Startup cleanup preserves pending recovery manifests | Two focused tests passed |
+| Busy-session continuation before follow-up input | Real worker regression reproduced red; 19 focused restore tests passed |
+| npm bridge unit suite | 25 passed, including IPC, fd3, signals, retry, and prefix behavior |
+| Packaging suites | 39 passed: native compatibility, restamping, decoder, catalog |
+| Earlier full repository gate | fmt, clippy, 5,145 tests passed (19 ignored), release build passed |
+
+## Published-version matrix
+
+The npm runs use unchanged, checksum-verified published packages and their real
+public CLI/TUI entrypoints. Every version below passed both commands.
+
+| Versions | CLI cases | TUI cases |
+| --- | ---: | ---: |
+| 0.6.0, 0.6.1 | 2 | 2 |
+| 0.7.0–0.7.4 | 5 | 5 |
+| 0.8.0, 0.8.1 | 2 | 2 |
+| 0.9.0–0.9.8 | 9 | 9 |
+
+Native installs additionally cover every stable native TS release,
+0.9.5–0.9.8, using each archive's unchanged old installer.
+The TUI runs require completed restoration, the original saved session attached
+to a Rust worker, a preserved transcript prefix, responsive input, and no
+restart warnings. CLI checks include version/help, checksum refusal, state
+preservation, and paths with spaces.
+
+The optimized Linux x64 snapshot tested before final recovery hardening:
+
+- Rust 1.0.0 archive: `7a5e663b535d1755504f8315d4f13de0857ed746ac5c6fdc6c5e55db84ec11b3`.
+- Rust 1.0.1 archive: `f46a36e1456dc6d7ddfefaf85bad68b29a0b06d863cb1577ce5e3445d4cad97a`.
+- Shipped executable: `0dbfb29af17614870f613017de2c6a11b25aa80572390a61dbe4d42c36335227`.
+
+Independent source archive digests and the exact version inventory live in
+[legacy-release-inventory.json](legacy-release-inventory.json).
+[The compatibility contract](legacy-upgrade-contract.md) describes the layouts,
+wire fields, and required recovery behavior.
+
+## Failure and usability evidence
+
+**Unusable executable:** the actual TS 0.6.0 updater installed a checksum-valid
+archive whose native executable named a nonexistent interpreter. With the
+old probe condition, the npm launcher was replaced and the command exited 127.
+With the fix, the staged probe refused activation, retained the npm symlink,
+wrote no success receipt, and left a genuine TS 0.9.8 daemon/worker able to
+resume the original session and accept input. The npm/native prefixes overlapped.
+
+**Future retry:** after an unsupported architecture caused migration to fail,
+the feed advanced from 1.0.0 to 1.0.1 and host support was restored. The original
+public update command fetched the new bridge and installer, activated Rust
+1.0.1, and resumed the saved session. An explicit retry that remains unsupported
+must still fail, despite the old TS updater's warning-only success exit.
+
+**Lost response:** a Unix-socket protocol fixture writes a TS-shaped manifest
+containing queued work, then drops the prepare reply. The Rust coordinator
+recovers it through its durable predecessor/socket/attempt binding before
+shutdown. Disabling recovery makes the regression fail. Tests reject foreign
+owners and stale data and permit retry after a definitive preparation refusal.
+Startup cleanup preserves pending source manifests until adoption.
+
+**Busy queue:** a real scheduled Rust worker with a scripted engine proves that
+restored follow-up input stays parked until continuation admission. Disabling
+the input pause consumes the queue too early; restoring it passes.
+
+**Usability:** separate real TS 0.6.0 npm and TS 0.9.8 native handoffs execute
+and persist a controlled Bash command after restoration, preserving prior
+transcript bytes. No provider inference or IPython execution was tested.
+
+The genuine fallback is the complete published TS 0.9.8 package, pinned to
+SHA-256 `d7b72785119efc28bfbca8ec4a7f47a1fcdcf47fcd8cebdb60bffaa79e3e1274`.
+The final staged-probe installer tested here is
+`323328cea0ede4d60aedfef486ba383ea081457e65ccedb1782ca6a0575a7f09`.
+
+## Reproduction and retained reports
+
+Run these only in an isolated test host, with temporary homes and no real
+credentials. Harnesses accept candidate archives and report paths; use their
+`--help` for the published source archive/checksum/prefix arguments.
+
+| Harness | Purpose |
+| --- | --- |
+| `scripts/release/verify_legacy_release.py` | Download and verify a genuine native TS release, then exercise its updater |
+| `scripts/release/test_legacy_upgrade.py` | Native CLI, checksum refusal, custom paths, second Rust update |
+| `scripts/release/test_legacy_npm_upgrade.py` | Genuine npm CLI migration |
+| `scripts/release/test_legacy_tui_upgrade.py` | Actual npm/native TUI update with saved-session restoration |
+| `scripts/release/test_legacy_npm_fallback.py` | Unsupported host, unusable payload, and later-release recovery |
+| `scripts/release/test_legacy_runtime_restart.py` | Real post-migration worker command execution |
+| `scripts/release/test_channel_install.py` | Current curl installer, reinstall, and user-file preservation |
+
+Reports, hashes, TUI captures, and logs were downloaded without agent binaries
+to `/tmp/prime-legacy-artifacts/` in the maintainer workspace. Key reports:
+`native-upgrade-evidence-optimized.tar.gz`, `native-tui-optimized-0.9.{5,6,7,8}.json`,
+`channel-install-probe-final.json`, `probe-red.json`, `probe-green.json`,
+`future-release-recovery.json`, `legacy-recovery-red-green.tar.gz`, and
+`make-check-final.log`. Matrix bundles contain each case's exact archive and
+bridge hashes. Intermediate evidence remains in Git history and
+`evidence-history-before-condensing.md` beside the raw reports.
+
+## Remaining release gates and limits
+
+- Rerun the full gate and migration matrix against the consolidated final source.
+- Verify production artifacts on all supported hosts. The Linux candidate was
+ built on Debian 12 with fixture catalog data. Its highest required GLIBC
+ symbol is 2.34, but that is not an Ubuntu 22.04 runtime test.
+- Stable release CI builds and livechecks Linux x64/arm64 in pinned Ubuntu 22.04,
+ and gates fresh installation plus TS migration on Linux and macOS arm64.
+ macOS x64 currently has a Rosetta version probe, not a full migration gate.
+- Older macOS arm64 CLI runs, two Rust beta CLI runs, and retained TS prerelease
+ runs passed earlier snapshots; they do not establish final platform coverage
+ or coverage of every historical beta.
+- GNU binaries do not establish musl, older-glibc, or unsupported-CPU support.
+ A working TS fallback is not a successful Rust migration.
+- npm was integration-tested; pnpm, Yarn, and Bun were not. Beta artifact reuse
+ does not execute the new fresh-install gate.
+- No final live-catalog, public stable endpoint, release-tag, or publication
+ verification is claimed. Full rendered-frame and exhaustive wire-byte parity
+ were not measured; the unchanged TS clients exercise the actual handoff.
diff --git a/install-rust.sh b/install-rust.sh
index 34846942e0..6427f4bd92 100755
--- a/install-rust.sh
+++ b/install-rust.sh
@@ -2293,15 +2293,14 @@ if [ ! -x "${stage}/${BINARY_NAME}" ]; then
rm -rf "$stage"
die "the tarball did not contain an executable ${BINARY_NAME} payload"
fi
-# --ARCHIVE ONLY: the archive's name is the version contract (the marker
+# The archive's name is the version contract (the marker
# records it and the rollback later reports it), so the payload's own
# --version must agree — a mis-named archive would publish a marker that
-# lies about its payload. The CHANNEL install is out of scope by design:
-# its tarball already passed the manifest's sha256 gate (the row's exact
-# checksum for this exact version), so the channel's integrity needs no
-# second opinion — and a probe there would add a new failure mode (a
-# cold-start binary slower than the bound) the pre-existing flow never
-# had. The probe is BOUNDED by a portable watchdog — NOT the `timeout`
+# lies about its payload. npm bridge channel installs also need this probe:
+# a checksum-valid binary may be incompatible with the host. Reject it
+# before replacing the public npm command so the bridge can retain its
+# working TypeScript recovery path. Other channel installs retain their
+# existing checksum-only behavior. The probe is BOUNDED by a portable watchdog — NOT the `timeout`
# command: on Windows `timeout` on PATH is timeout.exe, which waits
# instead of running a command and would refuse every probe, and macOS
# ships no GNU timeout at all. A payload whose --version blocks is
@@ -2311,9 +2310,8 @@ fi
# payload-writable stage: an extracted archive could forge a done marker
# where the loop looks and hang past the bound (the trailing wait would
# block on the hanging payload forever).
-if [ "$MODE" != "archive" ]; then
- # The channel install publishes without the name probe (see the block
- # comment above); the stage continues to the marker write.
+if [ "$MODE" != "archive" ] && [ "${PRIME_AGENT_PRESERVE_NPM_BRIDGE:-0}" != 1 ]; then
+ # A non-bridge channel install continues to the marker write.
:
else
probe_out="$dl/.version-probe.out"
@@ -2827,13 +2825,23 @@ export PRIME_AGENT_CODING_AGENT_DIR="${PRIME_AGENT_CODING_AGENT_DIR:-$HOME/.prim
# (the uid suffix) and rust-only: it never collides with the TypeScript
# daemon's own ${TMPDIR}/prime-agent-$(id -u) socket, so after the
# installer's clean TS-daemon stop the two daemons cannot fight again.
-export PRIME_AGENT_DAEMON_SOCKET="${PRIME_AGENT_DAEMON_SOCKET:-${TMPDIR:-/tmp}/prime-agent-rust-$(id -u)/daemon.sock}"
+# An npm migration restores the running TS daemon into its existing namespace.
+# The durable marker survives payload replacement and later curl updates.
+if [ -f "$(dirname "$0")/../share/.prime-agent-npm-bridge/legacy-daemon-socket" ]; then
+ export PRIME_AGENT_DAEMON_SOCKET="${PRIME_AGENT_DAEMON_SOCKET:-${TMPDIR:-${TMP:-${TEMP:-/tmp}}}/prime-agent-$(id -u)/daemon.sock}"
+else
+ export PRIME_AGENT_DAEMON_SOCKET="${PRIME_AGENT_DAEMON_SOCKET:-${TMPDIR:-/tmp}/prime-agent-rust-$(id -u)/daemon.sock}"
+fi
exec "$(dirname "$0")/../share/prime-agent/prime-agent" "$@"
EOF
fi
chmod 0755 "$launcher_tmp"
mv -f "$launcher_tmp" "$launcher"
launcher_tmp=""
+if [ "${PRIME_AGENT_USE_LEGACY_DAEMON_SOCKET:-0}" = 1 ]; then
+ mkdir -p "${PREFIX}/share/.prime-agent-npm-bridge"
+ printf 'legacy\n' > "${PREFIX}/share/.prime-agent-npm-bridge/legacy-daemon-socket"
+fi
# The cmd/PowerShell launcher twin (Windows only): the same
# ../share/prime-agent payload, resolved from the .cmd's own location, so
# `prime-agent` answers from cmd.exe and PowerShell too (the sh launcher
@@ -2907,7 +2915,10 @@ last_stop_was_rust=""
# build) and this product's daemon runs a named pipe - the unix-socket
# ladder below never applies. The Windows daemon stop already ran, before
# the publish (the file-lock ruling).
-if [ "$WINDOWS" != "yes" ]; then
+# The historical npm updater launches its restart coordinator through the
+# migration bridge. That coordinator must capture the TS restart manifest
+# before stopping the old daemon; the bridge explicitly transfers that duty.
+if [ "$WINDOWS" != "yes" ] && [ "${PRIME_AGENT_DEFER_DAEMON_STOP:-0}" != 1 ]; then
stop_daemon_candidate "$ts_socket" ts
ts_stop_stopped_ts="$last_stop_recorded"
ts_stop_was_rust_ts="$last_stop_was_rust"
@@ -2960,14 +2971,16 @@ fi
# keyword), with the restore command printed. Exact package `prime-agent`
# only; best-effort — an npm failure warns and moves on. Windows never had
# a TS npm install (the TS product shipped darwin/linux only), so the whole
-# step is darwin/linux.
-if [ "$WINDOWS" != "yes" ] && command -v npm >/dev/null 2>&1; then
+# step is darwin/linux. The npm migration bridge remains the package manager's
+# command entry point: removing it during its child installer would delete the
+# running launcher's files and break later package-manager updates.
+if [ "$WINDOWS" != "yes" ] && [ "${PRIME_AGENT_PRESERVE_NPM_BRIDGE:-0}" != 1 ] && command -v npm >/dev/null 2>&1; then
npm_root="$(npm root -g 2>/dev/null || true)"
if [ -n "$npm_root" ] && [ -f "${npm_root}/prime-agent/package.json" ]; then
ts_version="$("$UVPY" -c 'import json, sys
try:
package = json.load(open(sys.argv[1]))
- if package.get("name") == "prime-agent":
+ if package.get("name") == "prime-agent" and package.get("primeAgentRustBridge") is not True:
print(package.get("version", ""))
except Exception:
print("")' "${npm_root}/prime-agent/package.json")"
diff --git a/scripts/release/assemble_artifacts.py b/scripts/release/assemble_artifacts.py
index f9f1bd112c..afdc6b3291 100755
--- a/scripts/release/assemble_artifacts.py
+++ b/scripts/release/assemble_artifacts.py
@@ -27,9 +27,10 @@ where the binary name is `prime-agent.exe` for the Windows MSVC target and
`prime-agent` everywhere else (`binary_name_for_target`).
`--runtime-dir` defaults to `<repo>/prime-agent-runtime` (the vendored sidecar
from the kernel-packaging lane).
+Every archive includes a `package.json` version manifest beside the binary
+(TS installer parity: it is one of NATIVE_RELEASE_ASSETS).
`--sha` (the continuous-build stamp): a full 40-char git commit SHA. When
-given, a `package.json` version manifest is staged beside the binary (TS
-installer parity: it is one of NATIVE_RELEASE_ASSETS) whose `version` is
+given, that manifest's `version` is
`<version>-continuous.<sha>`, so the shipped binary reports the exact commit it
was built from via `--version`; the manifest records the commit too. The
archive name keeps the bare `<version>` so rolling releases overwrite assets.
@@ -60,6 +61,7 @@ from pathlib import Path
# The bundled-catalog validation gate (same release-scripts directory).
from bundle_catalog import BUNDLED_CATALOG_FILES, validate_bundled_catalog_dir
+from native_compat import stage_native_compat
# Tarball-root payload order mirrors the TS `binaryAssets` list so the
# installer lane can extract both distributions identically. The binary
@@ -271,10 +273,9 @@ def copy_runtime_tree(source: Path, target: Path) -> None:
def stage_tree(staging: Path, args: argparse.Namespace, stamped_version: str | None) -> dict:
"""Copy the tarball payload into the staging dir; return per-entry facts.
- `stamped_version` is the continuous-build version stamp (None for plain
- releases); when set, a `package.json` manifest is staged beside the binary
- so `--version` reports it at runtime (the same exe-adjacent manifest the
- TS binaryAssets carry — the Rust binary resolves it from `current_exe()`).
+ `stamped_version` overrides the plain release version in the always-staged
+ `package.json`. The binary reports it at runtime (the same exe-adjacent
+ manifest TS binaryAssets carry; Rust resolves it from `current_exe()`).
The runtime entry ships the curated content (see
RUNTIME_EXCLUDED_*); every other entry is a
@@ -334,17 +335,19 @@ def stage_tree(staging: Path, args: argparse.Namespace, stamped_version: str | N
shutil.copyfile(catalog_assets / name, staging / name)
payload = [binary_name if entry == BINARY_PLACEHOLDER else entry
for entry in STAGED_ENTRIES]
+ manifest = {
+ "name": "prime-agent",
+ "version": stamped_version or args.version,
+ "description": "Prime Agent: the RLM coding agent (Rust build)",
+ "bin": {"prime-agent": binary_name},
+ "piConfig": {"name": "prime-agent", "configDir": ".prime/agent"},
+ }
if stamped_version is not None:
- manifest = {
- "name": "prime-agent",
- "version": stamped_version,
- "description": "Prime Agent: the RLM coding agent (Rust build)",
- "bin": {"prime-agent": binary_name},
- "piConfig": {"name": "prime-agent", "configDir": ".prime/agent"},
- "commit": args.sha,
- }
- (staging / "package.json").write_text(json.dumps(manifest, indent=2) + "\n")
- payload.append("package.json")
+ manifest["commit"] = args.sha
+ (staging / "package.json").write_text(json.dumps(manifest, indent=2) + "\n")
+ payload.append("package.json")
+ if "-windows-" not in args.target:
+ payload.extend(stage_native_compat(staging))
# The payload guard runs on the staged tree BEFORE packing: a decoder
# sidecar staged by a later change fails here, not in the field.
fail_if_decoder_in_tree(staging)
diff --git a/scripts/release/native-compat/PHOTON-LICENSE.md b/scripts/release/native-compat/PHOTON-LICENSE.md
new file mode 100644
index 0000000000..b136bbc290
--- /dev/null
+++ b/scripts/release/native-compat/PHOTON-LICENSE.md
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2023, Silvia O'Dwyer
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/scripts/release/native-compat/README.md b/scripts/release/native-compat/README.md
new file mode 100644
index 0000000000..8fae75a479
--- /dev/null
+++ b/scripts/release/native-compat/README.md
@@ -0,0 +1,24 @@
+# Native installer compatibility assets
+
+Shipped TypeScript native installers validate these paths before activating a
+release and whenever validating an installed release for rollback. Rust ships
+the real historical assets to preserve that contract. They are not loaded by
+Rust's renderer or image implementation.
+
+- `theme/prime.json` and `export-html/template.html` are unmodified from
+ Prime Agent v0.9.8, commit `7d442aafa985f9342134fac16c2ef41f03fb45c1`, paths
+ `packages/coding-agent/src/modes/interactive/theme/prime.json` and
+ `packages/coding-agent/src/core/export-html/template.html`.
+- `photon_rs_bg.wasm` and `PHOTON-LICENSE.md` are unmodified from
+ `@silvia-odwyer/photon-node` 0.3.4, the dependency used by that release.
+ Source: https://registry.npmjs.org/@silvia-odwyer/photon-node/-/photon-node-0.3.4.tgz
+ Tarball SHA-256: `5a23015c1cd2c38e3c492dd96929985247b92f52d2ff0fb948d29edca52bc50a`.
+ Wasm SHA-256: `10468181565c56004c867f3a4af96f89a0ef5a63a72f2b5fb12c1f1992a3615c`.
+
+The assembler also supplies `package.json` for every release and copies the
+maintained `install-rust.sh` to `install.sh`. The old updater keeps executing
+its existing installer; the downloaded installer is not a migration hook.
+The bundled installer is available for manual Rust installation/repair and
+uses the Rust installer's arguments and environment contract.
+
+Keep these wire-level file names unchanged while supporting those installers.
diff --git a/scripts/release/native-compat/export-html/template.html b/scripts/release/native-compat/export-html/template.html
new file mode 100644
index 0000000000..fa43ac0a5b
--- /dev/null
+++ b/scripts/release/native-compat/export-html/template.html
@@ -0,0 +1,49 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Session Export</title>
+ <style>
+{{CSS}}
+ </style>
+</head>
+<body>
+ <button id="hamburger" title="Open sidebar"><svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" stroke="none"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="12" r="2.5"/><rect x="5" y="6" width="2" height="12"/><path d="M6 12h10c1 0 2 0 2-2V8"/></svg></button>
+ <div id="sidebar-overlay"></div>
+ <div id="app">
+ <aside id="sidebar">
+ <div class="sidebar-header">
+ <div class="sidebar-controls">
+ <input type="text" class="sidebar-search" id="tree-search" placeholder="Search...">
+ </div>
+ <div class="sidebar-filters">
+ <button class="filter-btn active" data-filter="default" title="Hide settings entries">Default</button>
+ <button class="filter-btn" data-filter="no-tools" title="Default minus tool results">No-tools</button>
+ <button class="filter-btn" data-filter="user-only" title="Only user messages">User</button>
+ <button class="filter-btn" data-filter="labeled-only" title="Only labeled entries">Labeled</button>
+ <button class="filter-btn" data-filter="all" title="Show everything">All</button>
+ <button class="sidebar-close" id="sidebar-close" title="Close">✕</button>
+ </div>
+ </div>
+ <div class="tree-container" id="tree-container"></div>
+ <div class="tree-status" id="tree-status"></div>
+ </aside>
+ <div id="sidebar-resizer" role="separator" aria-orientation="vertical" aria-label="Resize session tree sidebar"></div>
+ <main id="content">
+ <div id="header-container"></div>
+ <div id="messages"></div>
+ </main>
+ <div id="image-modal" class="image-modal">
+ <img id="modal-image" src="" alt="">
+ </div>
+ </div>
+
+ <script id="session-data" type="application/json">{{SESSION_DATA}}</script>
+ <script>{{MARKED_JS}}</script>
+ <script>{{HIGHLIGHT_JS}}</script>
+ <script>
+{{JS}}
+ </script>
+</body>
+</html>
diff --git a/scripts/release/native-compat/photon_rs_bg.wasm b/scripts/release/native-compat/photon_rs_bg.wasm
new file mode 100644
index 0000000000..fa30d9232a
Binary files /dev/null and b/scripts/release/native-compat/photon_rs_bg.wasm differ
diff --git a/scripts/release/native-compat/theme/prime.json b/scripts/release/native-compat/theme/prime.json
new file mode 100644
index 0000000000..05a2145d3e
--- /dev/null
+++ b/scripts/release/native-compat/theme/prime.json
@@ -0,0 +1,95 @@
+{
+ "$schema": "./theme-schema.json",
+ "name": "prime",
+ "vars": {
+ "bg": "#050506",
+ "surface": "#0d0d10",
+ "panel": "#151518",
+ "fg": "#f4f4f5",
+ "muted": "#a1a1aa",
+ "dim": "#71717a",
+ "grid": "#52525b",
+ "primary": "#7c6faf",
+ "primarySoft": "#8d7fc0",
+ "success": "#7da876",
+ "warning": "#f59e0b",
+ "error": "#d06f82",
+ "info": "#38bdf8",
+ "infoDim": "#1f6f99",
+ "neutral": "#d4d4d8",
+ "stringMint": "#8ba888",
+ "selectedBg": "#222226",
+ "userMsgBg": "#1a1a1f",
+ "customMsgBg": "#151518",
+ "toolPendingBg": "#101015",
+ "toolSuccessBg": "#0e1510",
+ "toolErrorBg": "#1a0d12",
+ "toolDiffAddedBg": "#015f00",
+ "toolDiffRemovedBg": "#5e0000"
+ },
+ "colors": {
+ "accent": "primary",
+ "border": "primary",
+ "borderAccent": "primary",
+ "borderMuted": "grid",
+ "success": "success",
+ "error": "error",
+ "warning": "warning",
+ "muted": "muted",
+ "dim": "dim",
+ "text": "",
+ "thinkingText": "#8b8b94",
+ "selectedBg": "selectedBg",
+ "userMessageBg": "userMsgBg",
+ "userMessageText": "",
+ "customMessageBg": "customMsgBg",
+ "customMessageText": "",
+ "customMessageLabel": "warning",
+ "refinementHeader": "#9575cd",
+ "refinementSummary": "#b7a1d6",
+ "toolPendingBg": "toolPendingBg",
+ "toolSuccessBg": "toolSuccessBg",
+ "toolErrorBg": "toolErrorBg",
+ "toolDiffAddedBg": "toolDiffAddedBg",
+ "toolDiffRemovedBg": "toolDiffRemovedBg",
+ "toolPanelBg": "surface",
+ "toolTitle": "",
+ "toolOutput": "muted",
+ "mdBody": "#d8d8dc",
+ "mdHeading": "primarySoft",
+ "mdLink": "info",
+ "mdLinkUrl": "dim",
+ "mdCode": "#c8c8cd",
+ "mdCodeBlock": "stringMint",
+ "mdCodeBlockBorder": "grid",
+ "mdQuote": "muted",
+ "mdQuoteBorder": "grid",
+ "mdHr": "grid",
+ "mdListBullet": "muted",
+ "toolDiffAdded": "#3fb950",
+ "toolDiffRemoved": "#f85149",
+ "toolDiffText": "#9aa0a6",
+ "toolDiffContext": "muted",
+ "syntaxComment": "muted",
+ "syntaxKeyword": "info",
+ "syntaxFunction": "info",
+ "syntaxVariable": "neutral",
+ "syntaxString": "stringMint",
+ "syntaxNumber": "warning",
+ "syntaxType": "warning",
+ "syntaxOperator": "neutral",
+ "syntaxPunctuation": "neutral",
+ "thinkingOff": "fg",
+ "thinkingMinimal": "muted",
+ "thinkingLow": "info",
+ "thinkingMedium": "primarySoft",
+ "thinkingHigh": "primary",
+ "thinkingXhigh": "primary",
+ "bashMode": "success"
+ },
+ "export": {
+ "pageBg": "bg",
+ "cardBg": "surface",
+ "infoBg": "panel"
+ }
+}
diff --git a/scripts/release/native_compat.py b/scripts/release/native_compat.py
new file mode 100644
index 0000000000..619e5c9fce
--- /dev/null
+++ b/scripts/release/native_compat.py
@@ -0,0 +1,84 @@
+"""Preserve the archive contract enforced by shipped TypeScript installers.
+
+The old installer validates these files before invoking the executable. Keep
+authentic assets so its installed-release validation and rollback continue to
+work; the Rust executable uses its own renderer and image implementation.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import shutil
+import tarfile
+from pathlib import Path, PurePosixPath
+
+ASSET_DIR = Path(__file__).resolve().parent / "native-compat"
+PHOTON_SHA256 = "10468181565c56004c867f3a4af96f89a0ef5a63a72f2b5fb12c1f1992a3615c"
+COMPAT_ASSETS = (
+ "theme/prime.json",
+ "export-html/template.html",
+ "photon_rs_bg.wasm",
+ "PHOTON-LICENSE.md",
+)
+REQUIRED_NATIVE_FILES = (
+ "prime-agent", "package.json", "install.sh",
+ "prime-agent-runtime/pyproject.toml", "prime-agent-runtime/src/rlm/repl.py",
+ *COMPAT_ASSETS,
+)
+
+
+def stage_native_compat(staging: Path) -> list[str]:
+ """Stage authentic legacy assets and a usable Rust repair installer."""
+ photon = ASSET_DIR / "photon_rs_bg.wasm"
+ if hashlib.sha256(photon.read_bytes()).hexdigest() != PHOTON_SHA256:
+ raise ValueError("legacy Photon compatibility asset checksum mismatch")
+ for name in COMPAT_ASSETS:
+ target = staging / name
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(ASSET_DIR / name, target)
+ # This file is validated, not executed, by the already-running TS installer.
+ # Ship the maintained Rust installer so manual repair uses current code.
+ shutil.copyfile(ASSET_DIR.parents[2] / "install-rust.sh", staging / "install.sh")
+ return ["theme", "export-html", "photon_rs_bg.wasm", "PHOTON-LICENSE.md", "install.sh"]
+
+
+def validate_compatibility_archive(path: Path) -> None:
+ """Raise ValueError for an archive the historical native updater rejects.
+
+ Windows never used the POSIX native TS installer. Its archive only needs
+ the common package version metadata; platform checks live in verify_release.
+ """
+ with tarfile.open(path, "r:gz") as archive:
+ members = {}
+ for member in archive.getmembers():
+ if member.name.startswith("/") or ".." in PurePosixPath(member.name).parts or "\\" in member.name:
+ raise ValueError(f"escaping member in compatibility archive: {member.name}")
+ if not member.isfile() and not member.isdir():
+ raise ValueError(f"non-regular member in compatibility archive: {member.name}")
+ if member.name in members:
+ raise ValueError(f"duplicate member in compatibility archive: {member.name}")
+ members[member.name] = member
+ windows = "prime-agent.exe" in members
+ required = ("package.json",) if windows else REQUIRED_NATIVE_FILES
+ for name in required:
+ member = members.get(name)
+ if member is None or not member.isfile() or member.size == 0:
+ raise ValueError(f"missing regular compatibility asset: {name}")
+ package = json.load(archive.extractfile("package.json"))
+ if not isinstance(package.get("version"), str) or not package["version"]:
+ raise ValueError("compatibility package.json has no version")
+ if not windows:
+ photon = archive.extractfile("photon_rs_bg.wasm").read()
+ if hashlib.sha256(photon).hexdigest() != PHOTON_SHA256:
+ raise ValueError("legacy Photon compatibility asset checksum mismatch")
+
+
+if __name__ == "__main__":
+ import argparse
+
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("archives", nargs="+", type=Path)
+ for archive_path in parser.parse_args().archives:
+ validate_compatibility_archive(archive_path)
+ print(f"Native compatibility verified: {archive_path}")
diff --git a/scripts/release/npm_bridge.py b/scripts/release/npm_bridge.py
new file mode 100644
index 0000000000..c408d38a20
--- /dev/null
+++ b/scripts/release/npm_bridge.py
@@ -0,0 +1,106 @@
+#!/usr/bin/env python3
+"""Package the Rust migration bridge consumed by historical npm self-updaters.
+
+No npm lifecycle scripts run: migration occurs when the old CLI/TUI relaunches
+dist/bundle/cli.js or its later cli-node.js fallback. Emit JSON metadata for
+the release manifest and checksums. The earliest packages relaunch dist/cli.js.
+"""
+from __future__ import annotations
+
+import argparse
+import gzip
+import hashlib
+import io
+import json
+import re
+import tarfile
+from pathlib import Path, PurePosixPath
+
+FALLBACK_VERSION = "0.9.8"
+# Independently checked against the published GitHub release SHA256SUMS.
+FALLBACK_SHA256 = "d7b72785119efc28bfbca8ec4a7f47a1fcdcf47fcd8cebdb60bffaa79e3e1274"
+
+
+def assemble(repo_root: Path, out_dir: Path, version: str, channel: str,
+ fallback_tarball: Path) -> dict:
+ if not re.fullmatch(r"\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?", version):
+ raise ValueError(f"Invalid release version: {version}")
+ if channel not in ("stable", "beta"):
+ raise ValueError(f"Invalid release channel: {channel}")
+ fallback_bytes = fallback_tarball.read_bytes()
+ if hashlib.sha256(fallback_bytes).hexdigest() != FALLBACK_SHA256:
+ raise ValueError("TypeScript fallback does not match the pinned published v0.9.8 archive")
+ with tarfile.open(fileobj=io.BytesIO(fallback_bytes)) as fallback_archive:
+ fallback_package = json.load(fallback_archive.extractfile("package/package.json"))
+ if fallback_package.get("name") != "prime-agent" or fallback_package.get("version") != FALLBACK_VERSION:
+ raise ValueError("TypeScript fallback package identity does not match published v0.9.8")
+ metadata = {
+ "name": "prime-agent", "version": version,
+ "description": "Prime Agent Rust migration launcher",
+ "bin": {"prime-agent": "dist/bundle/cli.js"},
+ "engines": {"node": ">=18"}, "os": ["darwin", "linux"],
+ "primeAgentReleaseChannel": channel,
+ "primeAgentRustBridge": True,
+ "primeAgentTypeScriptFallback": {"directory": "legacy/prime-agent",
+ "version": FALLBACK_VERSION, "sha256": FALLBACK_SHA256},
+ }
+ # Genuine fallback modules resolve dependencies through the enclosing
+ # package's node_modules. npm resolves these BEFORE replacing the previous
+ # install, including platform-specific dependencies. Copy no lifecycle
+ # scripts: recovery works with --ignore-scripts and does not start migration
+ # inside an npm installation transaction.
+ for field in ("dependencies", "optionalDependencies", "peerDependencies", "peerDependenciesMeta", "overrides"):
+ if field in fallback_package:
+ metadata[field] = fallback_package[field]
+ launcher = (Path(__file__).parent / "npm_bridge_assets/cli.cjs").read_bytes()
+ files = {
+ "package.json": (json.dumps(metadata, indent=2) + "\n").encode(),
+ "dist/bundle/cli.js": launcher,
+ # v0.9.5+ npm shims spawn this path, which the old updater captures as
+ # its coordinator/relaunch entrypoint. Both names must survive npm's
+ # package replacement with equivalent behavior.
+ "dist/bundle/cli-node.js": launcher,
+ # The first published packages used dist/cli.js. Require the bundled
+ # launcher so its __dirname still resolves the package root correctly;
+ # process.argv retains the original path captured by the old updater.
+ "dist/cli.js": b'#!/usr/bin/env node\n"use strict";\nrequire("./bundle/cli.js");\n',
+ "install-rust.sh": (repo_root / "install-rust.sh").read_bytes(),
+ }
+ modes = {}
+ with tarfile.open(fileobj=io.BytesIO(fallback_bytes)) as fallback_archive:
+ for member in fallback_archive:
+ source = PurePosixPath(member.name)
+ if source.is_absolute() or ".." in source.parts or source.parts[0] != "package":
+ raise ValueError(f"Unsafe TypeScript fallback member: {member.name}")
+ if member.isdir():
+ continue
+ if not member.isfile():
+ raise ValueError(f"Unsupported TypeScript fallback member: {member.name}")
+ name = str(PurePosixPath("legacy/prime-agent", *source.parts[1:]))
+ files[name] = fallback_archive.extractfile(member).read()
+ modes[name] = member.mode & 0o777
+ out_dir.mkdir(parents=True, exist_ok=True)
+ archive = out_dir / f"prime-agent-{version}.tgz"
+ with archive.open("wb") as output:
+ with gzip.GzipFile(fileobj=output, mode="wb", filename="", mtime=0) as compressed:
+ with tarfile.open(fileobj=compressed, mode="w") as tar:
+ for name, content in sorted(files.items()):
+ info = tarfile.TarInfo(f"package/{name}")
+ info.size = len(content)
+ info.mode = modes.get(name, 0o755 if name.endswith((".js", ".sh")) else 0o644)
+ tar.addfile(info, io.BytesIO(content))
+ return {"version": version, "package": "prime-agent", "tarball": archive.name,
+ "sha256": hashlib.sha256(archive.read_bytes()).hexdigest()}
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--repo-root", type=Path, required=True)
+ parser.add_argument("--out-dir", type=Path, required=True)
+ parser.add_argument("--version", required=True)
+ parser.add_argument("--channel", choices=("stable", "beta"), default="stable")
+ parser.add_argument("--fallback-tarball", type=Path, required=True,
+ help="checksum-pinned published TypeScript v0.9.8 npm archive")
+ args = parser.parse_args()
+ print(json.dumps(assemble(args.repo_root, args.out_dir, args.version, args.channel,
+ args.fallback_tarball)))
diff --git a/scripts/release/npm_bridge_assets/cli.cjs b/scripts/release/npm_bridge_assets/cli.cjs
new file mode 100644
index 0000000000..f6230e8bfd
--- /dev/null
+++ b/scripts/release/npm_bridge_assets/cli.cjs
@@ -0,0 +1,346 @@
+#!/usr/bin/env node
+"use strict";
+
+// Ship this at dist/bundle/cli.js and cli-node.js: historical updaters relaunch
+// their original absolute entrypoint, including the later shim's Node fallback.
+const { spawn, spawnSync } = require("node:child_process");
+const { randomUUID } = require("node:crypto");
+const { pathToFileURL } = require("node:url");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const packageRoot = path.resolve(__dirname, "../..");
+const metadata = require(path.join(packageRoot, "package.json"));
+const prefix = path.resolve(process.env.PRIME_AGENT_RUST_PREFIX || path.join(os.homedir(), ".local"));
+// npm may recreate prefix/bin/prime-agent as this package's symlink on every
+// reinstall. Invoke the payload directly, never that mutually managed path.
+const executable = path.join(prefix, "share", "prime-agent", "prime-agent");
+const args = process.argv.slice(2);
+const coordinator = args.includes("--internal-update-restart-coordinator");
+const delegatedUpdate = process.env.PRIME_AGENT_INTERNAL_TS_UPDATE === "1";
+// A delegated TS updater may spawn the new bridge's restart coordinator. That
+// coordinator must perform migration, never delegate back into the TS updater.
+delete process.env.PRIME_AGENT_INTERNAL_TS_UPDATE;
+let updateRequested = coordinator;
+// Recognize updates after leading global options without interpreting prompt
+// text such as `--print update` as an update retry. The value options mirror
+// the genuine fallback CLI's leading-global-flags contract.
+const valueFlags = new Set(["--mode", "--daemon-socket", "--provider", "--model", "--api-key",
+ "--cwd", "--system-prompt", "--append-system-prompt", "--fork", "--session-dir", "--models",
+ "--tools", "-t", "--thinking", "--extension", "-e", "--skill", "--prompt-template", "--theme",
+ "--autonomous-gate", "--autonomous-gate-retries", "--autonomous-gate-timeout-ms",
+ "--autonomous-max-continuations", "--autonomous-max-turns", "--autonomous-max-tokens",
+ "--autonomous-timeout-ms", "--goal", "--goal-token-budget", "--print", "-p"]);
+let promptRun = false;
+for (let index = 0; !coordinator && index < args.length; index++) {
+ const arg = args[index];
+ if (arg === "--") break;
+ if (["--print", "-p", "--system-prompt", "--append-system-prompt"].includes(arg)) promptRun = true;
+ if (!arg.startsWith("-")) { updateRequested = !promptRun && arg === "update"; break; }
+ if (valueFlags.has(arg) && args[index + 1] !== undefined && args[index + 1] !== "--") index++;
+ else if ((arg === "--resume" || arg === "-r") && args[index + 1] &&
+ !args[index + 1].startsWith("-") && !args[index + 1].startsWith("@")) index++;
+}
+// Keep migration state outside the payload replaced by native updates.
+const receiptDir = path.join(prefix, "share", ".prime-agent-npm-bridge");
+const receipt = path.join(receiptDir, metadata.version);
+const failedReceipt = `${receipt}.failed`;
+const legacySocketMarker = path.join(receiptDir, "legacy-daemon-socket");
+const legacySocket = path.join(os.tmpdir(), `prime-agent-${process.getuid()}`, "daemon.sock");
+const nativeEnvironment = { ...process.env,
+ PRIME_AGENT_CODING_AGENT_DIR: process.env.PRIME_AGENT_CODING_AGENT_DIR || path.join(os.homedir(), ".prime/agent"),
+ PRIME_AGENT_DAEMON_SOCKET: process.env.PRIME_AGENT_DAEMON_SOCKET ||
+ (coordinator || fs.existsSync(legacySocketMarker) ? legacySocket :
+ path.join(process.env.TMPDIR || "/tmp", `prime-agent-rust-${process.getuid()}`, "daemon.sock")),
+};
+delete nativeEnvironment.PI_PACKAGE_DIR;
+const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
+
+function run(command, args, options = {}) {
+ return new Promise((resolve, reject) => {
+ const { timeoutMs, ...spawnOptions } = options;
+ let child;
+ let requestedSignal;
+ let forceTimer;
+ let timeout;
+ let timedOut = false;
+ const terminate = signal => {
+ if (!child?.pid) return;
+ if (options.detached) {
+ try { process.kill(-child.pid, signal); } catch { child.kill(signal); }
+ } else child.kill(signal);
+ };
+ const handlers = signals.map(signal => {
+ const handler = () => {
+ requestedSignal ||= signal;
+ terminate(signal);
+ if (options.detached) {
+ forceTimer ||= setTimeout(() => terminate("SIGKILL"), 1000);
+ forceTimer.unref();
+ }
+ };
+ process.on(signal, handler);
+ return handler;
+ });
+ const cleanup = () => {
+ if (options.detached && (requestedSignal || timedOut)) terminate("SIGKILL");
+ clearTimeout(forceTimer);
+ clearTimeout(timeout);
+ signals.forEach((signal, i) => process.removeListener(signal, handlers[i]));
+ };
+ try {
+ child = spawn(command, args, { stdio: "inherit", ...spawnOptions });
+ } catch (error) {
+ cleanup();
+ reject(error);
+ return;
+ }
+ child.once("error", error => { cleanup(); reject(error); });
+ child.once("close", (code, signal) => {
+ cleanup();
+ resolve({ code, signal: requestedSignal || signal, timedOut });
+ });
+ if (timeoutMs) timeout = setTimeout(() => {
+ timedOut = true;
+ terminate("SIGTERM");
+ forceTimer ||= setTimeout(() => terminate("SIGKILL"), 1000);
+ forceTimer.unref();
+ }, timeoutMs);
+ if (requestedSignal) terminate(requestedSignal);
+ });
+}
+
+function finish(result) {
+ if (result.signal) {
+ process.kill(process.pid, result.signal);
+ return;
+ }
+ process.exitCode = result.code ?? 1;
+}
+
+function versionAtLeast(actual, wanted) {
+ const valid = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
+ if (!valid.test(actual) || !valid.test(wanted)) return false;
+ const [haveCore, havePre] = actual.split(/-(.*)/s);
+ const [wantCore, wantPre] = wanted.split(/-(.*)/s);
+ const have = haveCore.split(".").map(Number), want = wantCore.split(".").map(Number);
+ let ordering = 0;
+ for (let i = 0; i < 3 && !ordering; i++) ordering = Math.sign(have[i] - want[i]);
+ if (!ordering && havePre !== wantPre) {
+ if (havePre === undefined) ordering = 1;
+ else if (wantPre === undefined) ordering = -1;
+ else {
+ const a = havePre.split("."), b = wantPre.split(".");
+ for (let i = 0; i < Math.max(a.length, b.length) && !ordering; i++) {
+ if (a[i] === b[i]) continue;
+ if (a[i] === undefined) ordering = -1;
+ else if (b[i] === undefined) ordering = 1;
+ else if (/^\d+$/.test(a[i]) && /^\d+$/.test(b[i])) ordering = Math.sign(Number(a[i]) - Number(b[i]));
+ else if (/^\d+$/.test(a[i]) !== /^\d+$/.test(b[i])) ordering = /^\d+$/.test(a[i]) ? -1 : 1;
+ else ordering = a[i] > b[i] ? 1 : -1;
+ }
+ }
+ }
+ return ordering >= 0;
+}
+
+async function launchFallback(reason) {
+ const fallback = metadata.primeAgentTypeScriptFallback;
+ if (!fallback) throw new Error("The TypeScript recovery payload is missing from this package");
+ const fallbackRoot = path.join(packageRoot, fallback.directory);
+ const fallbackMetadata = JSON.parse(fs.readFileSync(path.join(fallbackRoot, "package.json"), "utf8"));
+ if (fallbackMetadata.name !== "prime-agent" || fallbackMetadata.version !== fallback.version) {
+ throw new Error("The TypeScript recovery payload has an unexpected package identity");
+ }
+ if (delegatedUpdate) console.error("prime-agent: Checking the latest release with the preserved TypeScript updater.");
+ else {
+ console.error(`prime-agent: Rust ${metadata.version} migration failed: ${reason}`);
+ console.error(`prime-agent: Continuing with TypeScript ${fallback.version}. Run prime-agent update to retry the Rust upgrade.`);
+ }
+ const environment = { ...process.env, PI_PACKAGE_DIR: fallbackRoot, PRIME_AGENT_INSTALL_METHOD: "node" };
+ const modules = path.dirname(packageRoot);
+ if (path.basename(modules) === "node_modules" && path.basename(path.dirname(modules)) === "lib") {
+ // The immutable fallback is nested below the real global package. Restore
+ // the prefix inference its updater would have had at the original location.
+ delete environment.NPM_CONFIG_PREFIX;
+ delete process.env.NPM_CONFIG_PREFIX;
+ environment.npm_config_prefix = path.dirname(path.dirname(modules));
+ }
+ // TS daemon workers can arrive through Node's fork IPC channel. Import the
+ // immutable fallback in this process so process.channel and inherited file
+ // descriptors survive. A second node subprocess would sever that contract.
+ Object.assign(process.env, environment);
+ process.argv[1] = path.join(packageRoot, "dist/bundle/cli.js");
+ await import(pathToFileURL(path.join(fallbackRoot, "dist/bundle/cli-node.js")).href);
+}
+
+async function main() {
+ if (process.platform !== "darwin" && process.platform !== "linux") {
+ throw new Error("This migration package supports existing macOS and Linux installations only.");
+ }
+ if (delegatedUpdate && updateRequested && !coordinator) {
+ await launchFallback("retrying the release update");
+ return;
+ }
+ // A completed migration needs no lock or disk writes on subsequent launches.
+ // Receipts are per package version: upgrading this npm bridge still enters
+ // the native-version probe and migration path below. Coordinators retain
+ // their status/namespace handoff even when the payload already exists.
+ if (!coordinator && fs.existsSync(receipt) && fs.existsSync(executable)) {
+ finish(await run(executable, args, { env: nativeEnvironment }));
+ return;
+ }
+ if (!updateRequested && fs.existsSync(failedReceipt)) {
+ await launchFallback(fs.readFileSync(failedReceipt, "utf8").trim());
+ return;
+ }
+ if (updateRequested && !coordinator && fs.existsSync(failedReceipt)) {
+ // A pinned installer cannot acquire future platform support. Let the
+ // genuine updater fetch the current bridge package (and its installer),
+ // then verify native activation instead of trusting TS's warning-only exit.
+ const result = await run(process.execPath, [path.join(packageRoot, "dist/bundle/cli.js"), ...args], {
+ env: { ...process.env, PRIME_AGENT_INTERNAL_TS_UPDATE: "1" },
+ detached: true, timeoutMs: 600000,
+ });
+ if (result.timedOut) throw new Error("The TypeScript release updater timed out before Rust activation");
+ if (result.signal || result.code !== 0) { finish(result); return; }
+ const current = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8"));
+ const probe = spawnSync(executable, ["--version"], { env: nativeEnvironment,
+ stdio: ["ignore", "pipe", "ignore"], encoding: "utf8", timeout: 5000, maxBuffer: 65536 });
+ const found = probe.status === 0 && probe.stdout.match(/\b(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/);
+ if (!current.primeAgentRustBridge || !fs.existsSync(path.join(receiptDir, current.version)) ||
+ !found || !versionAtLeast(found[1], current.version)) {
+ throw new Error("The release updater did not activate a working Rust release; TypeScript recovery remains available");
+ }
+ finish(result);
+ return;
+ }
+ fs.mkdirSync(receiptDir, { recursive: true });
+ const statusIndex = args.indexOf("--internal-update-restart-status");
+ let statusPath = coordinator && statusIndex >= 0 ? args[statusIndex + 1] : undefined;
+ if (statusPath && fs.existsSync(statusPath)) {
+ const existing = JSON.parse(fs.readFileSync(statusPath, "utf8"));
+ // A native staged transaction owns its record; only the legacy status
+ // format can be heartbeated while the migration installer runs.
+ if (existing.state !== undefined || existing.updateId !== undefined) statusPath = undefined;
+ }
+ const socketIndex = args.indexOf("--daemon-socket");
+ const now = new Date().toISOString();
+ const status = { version: 1, requestId: randomUUID(),
+ socketPath: socketIndex >= 0 ? args[socketIndex + 1] : nativeEnvironment.PRIME_AGENT_DAEMON_SOCKET,
+ phase: "starting", coordinator: { pid: process.pid },
+ counts: { total: 0, restored: 0, resumed: 0, failed: 0 },
+ startedAt: now, updatedAt: now, heartbeatAt: now };
+ const persist = () => {
+ if (!statusPath) return;
+ status.heartbeatAt = new Date().toISOString();
+ status.updatedAt = status.heartbeatAt;
+ const temporary = `${statusPath}.npm-${process.pid}`;
+ fs.mkdirSync(path.dirname(statusPath), { recursive: true });
+ fs.writeFileSync(temporary, JSON.stringify(status));
+ fs.renameSync(temporary, statusPath);
+ };
+ persist();
+ let heartbeatError;
+ const heartbeat = statusPath ? setInterval(() => {
+ try { persist(); } catch (error) { heartbeatError = error; }
+ }, 5000) : undefined;
+ const lockPath = path.join(receiptDir, "migration.lock");
+ const lockOwner = JSON.stringify({ pid: process.pid, token: randomUUID() });
+ let ownsLock = false;
+ try {
+ const deadline = Date.now() + 600000;
+ while (!ownsLock) {
+ try {
+ const fd = fs.openSync(lockPath, "wx", 0o600);
+ fs.writeFileSync(fd, lockOwner);
+ fs.closeSync(fd);
+ ownsLock = true;
+ } catch (error) {
+ if (error.code !== "EEXIST") throw error;
+ try {
+ const previous = fs.readFileSync(lockPath, "utf8");
+ const owner = JSON.parse(previous);
+ try { process.kill(owner.pid, 0); }
+ catch (probe) {
+ if (probe.code === "ESRCH" && fs.readFileSync(lockPath, "utf8") === previous) {
+ fs.unlinkSync(lockPath);
+ continue;
+ }
+ }
+ } catch (read) {
+ if (read.code === "ENOENT") continue;
+ if (!(read instanceof SyntaxError)) throw read;
+ }
+ if (Date.now() >= deadline) throw new Error(`Timed out waiting for migration lock ${lockPath}`);
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ }
+ let installed = fs.existsSync(receipt) && fs.existsSync(executable);
+ if (!installed && fs.existsSync(executable)) {
+ const probe = spawnSync(executable, ["--version"], { env: nativeEnvironment,
+ stdio: ["ignore", "pipe", "ignore"], encoding: "utf8", timeout: 5000, maxBuffer: 65536 });
+ const found = probe.status === 0 && probe.stdout.match(/\b(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/);
+ if (found) installed = versionAtLeast(found[1], metadata.version);
+ }
+ if (!installed) {
+ // The TS restart coordinator restores sessions in the TS namespace.
+ // Persist that choice in the native installer so both entrypoints agree.
+ if (!process.env.PRIME_AGENT_DAEMON_SOCKET) nativeEnvironment.PRIME_AGENT_DAEMON_SOCKET = legacySocket;
+ const result = await run("sh", [path.join(packageRoot, "install-rust.sh")], {
+ // Never remove the npm package while its updater/restart coordinator is running.
+ env: { ...nativeEnvironment, PRIME_AGENT_VERSION: metadata.version,
+ PRIME_AGENT_RELEASE_CHANNEL: metadata.primeAgentReleaseChannel,
+ PRIME_AGENT_RUST_PREFIX: prefix, PRIME_AGENT_PRESERVE_NPM_BRIDGE: "1",
+ PRIME_AGENT_USE_LEGACY_DAEMON_SOCKET: "1",
+ PRIME_AGENT_DEFER_DAEMON_STOP: coordinator ? "1" : "0" },
+ stdio: ["ignore", process.stderr, process.stderr],
+ detached: true,
+ });
+ if (result.signal || result.code !== 0) {
+ status.phase = "failed";
+ status.message = "The Rust installer failed; retry the update.";
+ persist();
+ if (result.signal) { finish(result); return; }
+ const failure = new Error(`Rust installer exited with status ${result.code ?? 1}`);
+ failure.exitCode = result.code ?? 1;
+ throw failure;
+ }
+ }
+ if (!fs.existsSync(executable)) throw new Error(`Installer did not create ${executable}`);
+ fs.writeFileSync(receipt, "installed\n");
+ if (coordinator) fs.writeFileSync(legacySocketMarker, "legacy\n");
+ if (heartbeatError) throw heartbeatError;
+ } catch (error) {
+ status.phase = "failed";
+ status.message = error.message;
+ persist();
+ throw error;
+ } finally {
+ clearInterval(heartbeat);
+ if (ownsLock && fs.readFileSync(lockPath, "utf8") === lockOwner) fs.unlinkSync(lockPath);
+ }
+ if (!process.env.PRIME_AGENT_DAEMON_SOCKET && fs.existsSync(legacySocketMarker)) {
+ nativeEnvironment.PRIME_AGENT_DAEMON_SOCKET = legacySocket;
+ }
+ finish(await run(executable, args, { env: nativeEnvironment }));
+}
+
+main().catch(async error => {
+ try {
+ fs.mkdirSync(receiptDir, { recursive: true });
+ fs.writeFileSync(failedReceipt, `${error.message}\n`);
+ } catch (recordError) {
+ console.error(`prime-agent: Could not record the failed migration: ${recordError.message}`);
+ }
+ if (updateRequested) {
+ console.error(`prime-agent: Rust migration failed: ${error.message}. TypeScript recovery remains available on the next launch.`);
+ process.exitCode = error.exitCode || 1;
+ return;
+ }
+ try { await launchFallback(error.message); }
+ catch (fallbackError) {
+ console.error(`prime-agent: TypeScript recovery could not start: ${fallbackError.message}`);
+ process.exitCode = 1;
+ }
+});
diff --git a/scripts/release/restamp_continuous.py b/scripts/release/restamp_continuous.py
index c43f8c5c64..a72317c319 100644
--- a/scripts/release/restamp_continuous.py
+++ b/scripts/release/restamp_continuous.py
@@ -59,7 +59,8 @@ from assemble_artifacts import (
sha256_file,
)
from bundle_catalog import validate_bundled_catalog_dir
-from verify_release import CONTINUOUS_EXTRA_TOP_LEVEL, CONTINUOUS_SUFFIX, EXPECTED_TOP_LEVEL
+from native_compat import validate_compatibility_archive
+from verify_release import CONTINUOUS_EXTRA_TOP_LEVEL, CONTINUOUS_SUFFIX, EXPECTED_TOP_LEVEL, NATIVE_COMPAT_TOP_LEVEL
# The runner-host target triple -> the binary this process can execute
# (installer.rs `target_for` parity: the same four continuous targets).
@@ -187,11 +188,13 @@ def restamp_target(incoming: Path, out_dir: Path, version: str,
elif decoders or decoder_files:
fail(f"{incoming.name}: unexpected decoder artifacts on {target}")
+ validate_compatibility_archive(archive)
+
# 3. Unpack; assert the continuous payload shape.
staging = Path(tempfile.mkdtemp(prefix="prime-agent-restamp-"))
try:
entries = unpack_archive(archive, staging)
- expected = sorted(EXPECTED_TOP_LEVEL | CONTINUOUS_EXTRA_TOP_LEVEL)
+ expected = sorted(EXPECTED_TOP_LEVEL | CONTINUOUS_EXTRA_TOP_LEVEL | NATIVE_COMPAT_TOP_LEVEL)
if entries != expected:
fail(f"{incoming.name}: payload {entries} != the continuous "
f"payload {expected}; refusing to restamp a foreign archive")
diff --git a/scripts/release/test_catalog_assets.py b/scripts/release/test_catalog_assets.py
index 357b524dda..e83baa9830 100644
--- a/scripts/release/test_catalog_assets.py
+++ b/scripts/release/test_catalog_assets.py
@@ -159,7 +159,8 @@ class SyntheticRepo:
runtime = root / "runtime"
runtime.mkdir()
(runtime / "pyproject.toml").write_text("[project]\nname='rlm'\n")
- (runtime / "src").mkdir()
+ (runtime / "src" / "rlm").mkdir(parents=True)
+ (runtime / "src" / "rlm" / "repl.py").write_text("# fixture REPL\n")
# The exe-adjacent kernel runtime tree package_release.py stages.
kernel = root / "prime-agent-runtime"
(kernel / "src" / "rlm").mkdir(parents=True)
diff --git a/scripts/release/test_channel_install.py b/scripts/release/test_channel_install.py
new file mode 100644
index 0000000000..2a52ae4fdf
--- /dev/null
+++ b/scripts/release/test_channel_install.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python3
+"""Exercise the current curl installer and reinstall against a local channel.
+
+Uses the real candidate executable and installer; no provider requests are made.
+The installer's normal Python/kernel bootstrap may access package registries.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import shutil
+import tempfile
+from pathlib import Path
+
+from test_legacy_upgrade import archive_identity, digest, execute, isolated_environment, publish_archive, release_server
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--archive", required=True, type=Path)
+ parser.add_argument("--installer", required=True, type=Path)
+ parser.add_argument("--report", required=True, type=Path)
+ args = parser.parse_args()
+ version, platform = archive_identity(args.archive)
+ report = {"version": version, "platform": platform, "archive_sha256": digest(args.archive),
+ "installer_sha256": digest(args.installer), "steps": []}
+ try:
+ with tempfile.TemporaryDirectory(prefix="prime-channel-install-") as temporary:
+ root = Path(temporary)
+ feed = root / "feed"
+ publish_archive(feed, args.archive)
+ shutil.copyfile(args.installer, feed / "install.sh")
+ (feed / "stable").write_text(version + "\n")
+ (feed / "latest.json").write_text(json.dumps({"version": version, "binaries": [
+ {"platform": platform, "file": args.archive.name, "sha256": digest(args.archive)}]}))
+ with release_server(feed) as base:
+ env = isolated_environment(root / "user", base)
+ prefix = root / "user" / "prefix with spaces"
+ env.update(PRIME_AGENT_RUST_PREFIX=str(prefix), PRIME_AGENT_ALLOW_HTTP="1")
+ state = Path(env["PRIME_AGENT_CODING_AGENT_DIR"])
+ witnesses = {"settings.json": '{}\n', "auth.json": '{}\n',
+ "sessions/preserved.jsonl": '{"migrationWitness":"saved session"}\n'}
+ for name, content in witnesses.items():
+ path = state / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(content)
+ command = ["bash", "-o", "pipefail", "-c", 'curl -fsSL "$PRIME_AGENT_DOWNLOAD_BASE_URL/install.sh" | sh']
+ for _ in range(2):
+ report["steps"].append(execute(command, env))
+ probe = execute([str(prefix / "bin/prime-agent"), "--version"], env)
+ report["steps"].append(probe)
+ if probe["stdout"].strip() != version:
+ raise ValueError("Installed launcher did not report channel version")
+ report["steps"].append(execute([str(prefix / "bin/prime-agent"), "--help"], env))
+ for name, content in witnesses.items():
+ if (state / name).read_text() != content:
+ raise ValueError(f"Installer changed user state: {name}")
+ report.update(status="passed", fresh_install=True, reinstall=True, user_state_preserved=True)
+ except Exception as error:
+ report.update(status="failed", error=str(error))
+ args.report.parent.mkdir(parents=True, exist_ok=True)
+ args.report.write_text(json.dumps(report, indent=2) + "\n")
+ print(json.dumps({key: value for key, value in report.items() if key != "steps"}))
+ return 0 if report["status"] == "passed" else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/release/test_legacy_npm_fallback.py b/scripts/release/test_legacy_npm_fallback.py
new file mode 100644
index 0000000000..e172e274be
--- /dev/null
+++ b/scripts/release/test_legacy_npm_fallback.py
@@ -0,0 +1,228 @@
+#!/usr/bin/env python3
+"""Real npm updater recovery when the unchanged Rust installer rejects a host.
+
+Opt-in network integration. All installs, sockets, and sessions are temporary.
+The only simulated host capability is uname -m; no installer or TS code is mocked.
+"""
+from __future__ import annotations
+
+import argparse
+import io
+import json
+import os
+from pathlib import Path
+import shlex
+import shutil
+import signal
+import subprocess
+import tarfile
+import tempfile
+
+import npm_bridge
+from test_legacy_tui_upgrade import daemon_request, wait_for
+from test_legacy_upgrade import archive_identity, digest, execute, isolated_environment, publish_archive, release_server
+
+
+def exercise(args, root: Path) -> dict:
+ source = args.previous_archive
+ with tarfile.open(source) as tar:
+ metadata = json.load(tar.extractfile("package/package.json"))
+ original_cli = tar.extractfile("package/dist/bundle/cli.js").read()
+ checksum = next(line.split()[0] for line in args.previous_checksums.read_text().splitlines()
+ if len(line.split()) == 2 and line.split()[1].lstrip("*") == source.name)
+ assert digest(source) == checksum
+ version, platform = archive_identity(args.archive)
+ candidate = args.archive
+ if args.failure_mode == "unusable-payload":
+ # Valid archive and matching published checksum, but execution fails
+ # on every host. Keep its executable mode so the staged --version
+ # probe, rather than the presence check, must reject publication.
+ candidate = root / args.archive.name
+ with tarfile.open(args.archive) as source_archive, tarfile.open(candidate, "w:gz") as rejected:
+ for member in source_archive.getmembers():
+ if member.name == "prime-agent":
+ payload = b"#!/nonexistent-prime-agent-test-interpreter\n"
+ member.size = len(payload)
+ member.mode = 0o755
+ rejected.addfile(member, io.BytesIO(payload))
+ else:
+ rejected.addfile(member, source_archive.extractfile(member) if member.isfile() else None)
+ feed = root / "feed"
+ publish_archive(feed, candidate)
+ bridge = npm_bridge.assemble(Path(__file__).resolve().parents[2], feed / "releases" / f"v{version}",
+ version, "stable", args.fallback_tarball)
+ (feed / "latest.json").write_text(json.dumps({"version": version, "package": "prime-agent",
+ "tarball": f"releases/v{version}/{bridge['tarball']}",
+ "binaries": [{"platform": platform, "file": candidate.name, "sha256": digest(candidate)}]}))
+ evidence = {"source_version": metadata["version"], "source_sha256": checksum,
+ "candidate_sha256": digest(candidate), "failure_mode": args.failure_mode,
+ "bridge_sha256": bridge["sha256"],
+ "fallback_sha256": digest(args.fallback_tarball), "steps": []}
+ with release_server(feed) as base:
+ env = isolated_environment(root / "user", base, "standard")
+ prefix = root / "npm prefix"
+ shutil.copytree(args.previous_prefix, prefix, symlinks=True)
+ public = prefix / "bin/prime-agent"
+ cli = prefix / "lib/node_modules/prime-agent/dist/bundle/cli.js"
+ assert cli.read_bytes() == original_cli
+ wrappers = root / "host"
+ wrappers.mkdir()
+ if args.failure_mode == "unsupported-host":
+ uname = wrappers / "uname"
+ uname.write_text('#!/bin/sh\nif [ "$1" = -m ]; then echo unsupported-test-architecture; else exec /usr/bin/uname "$@"; fi\n')
+ uname.chmod(0o755)
+ native_prefix = prefix if args.failure_mode == "unusable-payload" else root / "rust"
+ socket = root / "daemon.sock"
+ env.update(PATH=str(wrappers) + os.pathsep + str(prefix / "bin") + os.pathsep + env["PATH"],
+ npm_config_prefix=str(prefix), npm_config_cache=str(root / "npm-cache"),
+ npm_config_ignore_scripts="true", npm_config_audit="false", npm_config_fund="false",
+ npm_config_update_notifier="false", PRIME_AGENT_RUST_PREFIX=str(native_prefix),
+ PRIME_AGENT_ALLOW_HTTP="1", PRIME_AGENT_DAEMON_SOCKET=str(socket),
+ TERM="xterm-256color", ANTHROPIC_API_KEY="fixture-not-a-real-key")
+ state = Path(env["PRIME_AGENT_CODING_AGENT_DIR"])
+ (state / "settings.json").write_text(json.dumps({"onboardingShown": True}))
+ stamp = "2026-10-09T00:00:00.000Z"
+ transcript = state / "sessions/recovery.jsonl"
+ transcript.parent.mkdir(exist_ok=True)
+ rows = [{"type": "session", "version": 3, "id": "11111111-2222-4333-8444-555555555555", "timestamp": stamp, "cwd": env["HOME"]},
+ {"type": "message", "id": "seed", "parentId": None, "timestamp": stamp, "message": {
+ "role": "assistant", "content": [{"type": "text", "text": "durable recovery sentinel"}],
+ "api": "anthropic-messages", "provider": "anthropic", "model": "claude-sonnet-4-5",
+ "usage": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "totalTokens": 0,
+ "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0}},
+ "stopReason": "stop", "timestamp": 1791504000000}}]
+ original = "".join(json.dumps(row) + "\n" for row in rows)
+ transcript.write_text(original)
+ evidence["steps"].append(execute([str(public), "--version"], env))
+ update = subprocess.run([str(public), "update", "--force"], env=env, cwd=env["HOME"],
+ capture_output=True, text=True, timeout=240)
+ evidence["old_update"] = {"exit_code": update.returncode, "stdout": update.stdout, "stderr": update.stderr}
+ assert json.loads((cli.parents[2] / "package.json").read_text())["primeAgentRustBridge"] is True
+ probe = execute([str(public), "--version"], env)
+ evidence["steps"].append(probe)
+ assert npm_bridge.FALLBACK_VERSION in (probe["stdout"] + probe["stderr"]).splitlines(), probe
+ assert "TypeScript" in probe["stderr"], probe
+ assert not (native_prefix / "share/prime-agent/prime-agent").exists(), "Unusable native payload was published"
+ assert public.is_symlink() and public.resolve() == cli.resolve(), "Installer overwrote the public npm recovery launcher"
+ receipts = native_prefix / "share/.prime-agent-npm-bridge"
+ assert not (receipts / version).exists(), "Failed migration recorded success"
+ assert (receipts / f"{version}.failed").exists(), "Failed migration was not recorded"
+ expected_runtime = npm_bridge.FALLBACK_VERSION
+ if args.recovery_archive:
+ if args.failure_mode != "unsupported-host":
+ raise ValueError("A recovery archive currently requires unsupported-host mode")
+ recovery_version, recovery_platform = archive_identity(args.recovery_archive)
+ assert recovery_version != version
+ publish_archive(feed, args.recovery_archive)
+ recovery_bridge = npm_bridge.assemble(Path(__file__).resolve().parents[2],
+ feed / "releases" / f"v{recovery_version}", recovery_version, "stable", args.fallback_tarball)
+ (feed / "latest.json").write_text(json.dumps({"version": recovery_version, "package": "prime-agent",
+ "tarball": f"releases/v{recovery_version}/{recovery_bridge['tarball']}",
+ "binaries": [{"platform": recovery_platform, "file": args.recovery_archive.name,
+ "sha256": digest(args.recovery_archive)}]}))
+ (wrappers / "uname").unlink()
+ expected_runtime = recovery_version
+ evidence["recovery"] = {"version": recovery_version, "candidate_sha256": digest(args.recovery_archive),
+ "bridge_sha256": recovery_bridge["sha256"]}
+ retry = subprocess.run([str(public), "update", "--force"], env=env, cwd=env["HOME"],
+ capture_output=True, text=True, timeout=90)
+ evidence["explicit_retry"] = {"exit_code": retry.returncode, "stdout": retry.stdout, "stderr": retry.stderr}
+ if args.recovery_archive:
+ assert retry.returncode == 0, evidence["explicit_retry"]
+ assert (receipts / expected_runtime).is_file(), "Newer release did not record successful migration"
+ assert (native_prefix / "share/prime-agent/prime-agent").is_file()
+ recovered = execute([str(public), "--version"], env)
+ evidence["steps"].append(recovered)
+ assert recovered["stdout"].strip() == expected_runtime, recovered
+ else:
+ assert retry.returncode != 0 and "Rust migration failed" in retry.stderr, evidence["explicit_retry"]
+ expected_error = "no rust build is published" if args.failure_mode == "unsupported-host" else "refusing an unusable launcher"
+ assert expected_error in retry.stderr, evidence["explicit_retry"]
+ tmux = ["tmux", "-S", str(root / "tmux.sock")]
+
+ def tmux_run(*parts):
+ return subprocess.run(tmux + list(parts), env=env, capture_output=True, text=True, timeout=10)
+
+ def screen():
+ result = tmux_run("capture-pane", "-p", "-t", "recovery")
+ if result.returncode:
+ raise RuntimeError(result.stderr)
+ return result.stdout
+
+ try:
+ command = [str(public), "--resume", str(transcript), "--daemon-socket", str(socket),
+ "--provider", "anthropic", "--model", "claude-sonnet-4-5"]
+ tmux_run("new-session", "-d", "-s", "recovery", "-x", "120", "-y", "36", "-c", env["HOME"], shlex.join(command)).check_returncode()
+ wait_for("genuine TS fallback session", lambda: "durable recovery sentinel" in screen())
+ hello, roster = daemon_request(socket, {"type": "list"})
+ assert hello["appVersion"] == expected_runtime, hello
+ wait_for("persisted session attachment", lambda: any(
+ session.get("sessionFile") == str(transcript) and session.get("attachedClients", 0) > 0
+ for session in daemon_request(socket, {"type": "list"})[1].get("data", {}).get("sessions", [])))
+ tmux_run("send-keys", "-t", "recovery", "-l", "recovery-input-witness").check_returncode()
+ wait_for("responsive fallback input", lambda: "recovery-input-witness" in screen())
+ assert transcript.read_text().startswith(original)
+ evidence.update(status="passed", fallback_hello=hello, fallback_roster=roster,
+ responsive_screen=screen(), transcript_preserved=True)
+ finally:
+ # Track the fixture's daemon, worker, and inherited bootstrap children
+ # before shutdown; they must stop writing before deleting their home.
+ owned = set()
+ namespace = f"PRIME_AGENT_CODING_AGENT_DIR={state}".encode()
+ for process in Path("/proc").iterdir():
+ if process.name.isdigit():
+ try:
+ if namespace in (process / "environ").read_bytes().split(b"\0"):
+ owned.add(int(process.name))
+ except (OSError, PermissionError):
+ pass
+ tmux_run("kill-server")
+ try:
+ daemon_request(socket, {"type": "shutdown", "force": True})
+ except (OSError, RuntimeError, ValueError):
+ pass
+
+ def alive():
+ running = []
+ for pid in owned:
+ try:
+ stat = Path(f"/proc/{pid}/stat").read_text()
+ if stat.rsplit(")", 1)[1].split()[0] != "Z":
+ running.append(pid)
+ except FileNotFoundError:
+ pass
+ return running
+
+ try:
+ wait_for("fixture daemon and worker shutdown", lambda: not alive(), timeout=20)
+ except RuntimeError:
+ # A failed verifier must still release only its isolated children.
+ for pid in alive():
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ wait_for("forced fixture cleanup", lambda: not alive(), timeout=10)
+ raise
+ return evidence
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--recovery-archive", type=Path)
+ parser.add_argument("--failure-mode", choices=("unsupported-host", "unusable-payload"), default="unsupported-host")
+ for name in ("previous-archive", "previous-checksums", "previous-prefix", "fallback-tarball", "archive", "report"):
+ parser.add_argument("--" + name, type=Path, required=True)
+ args = parser.parse_args()
+ with tempfile.TemporaryDirectory(prefix="pfail-", dir="/tmp") as directory:
+ try:
+ report = exercise(args, Path(directory))
+ except Exception as error:
+ report = {"status": "failed", "error": str(error)}
+ args.report.write_text(json.dumps(report, indent=2) + "\n")
+ print(json.dumps(report, indent=2))
+ return int(report["status"] != "passed")
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/release/test_legacy_npm_upgrade.py b/scripts/release/test_legacy_npm_upgrade.py
new file mode 100644
index 0000000000..2e99fcd14c
--- /dev/null
+++ b/scripts/release/test_legacy_npm_upgrade.py
@@ -0,0 +1,124 @@
+#!/usr/bin/env python3
+"""Opt-in integration test: published TS npm CLI -> Rust bridge -> real Rust.
+
+Supply a released npm tarball and its SHA256SUMS, a candidate native archive,
+and optionally a prepared npm prefix to avoid reinstalling historical deps.
+Dependency installation needs network; the actual update uses only localhost.
+No npm lifecycle scripts execute, and every installation/state path is isolated.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import tarfile
+import tempfile
+
+import npm_bridge
+from test_legacy_upgrade import archive_identity, digest, execute, isolated_environment, publish_archive, release_server
+
+
+def exercise(args, root: Path) -> dict:
+ archive = args.previous_archive.resolve()
+ checksum = next((line.split()[0] for line in args.previous_checksums.read_text().splitlines()
+ if len(line.split()) == 2 and line.split()[1].lstrip('*') == archive.name), None)
+ if checksum != digest(archive):
+ raise ValueError('Historical npm artifact checksum mismatch')
+ with tarfile.open(archive) as package:
+ source = json.load(package.extractfile('package/package.json'))
+ assert source['name'] == 'prime-agent'
+ source_entrypoint = source['bin']['prime-agent']
+ if source_entrypoint not in ('dist/cli.js', 'dist/bundle/cli.js'):
+ raise ValueError(f'Unknown historical entrypoint: {source_entrypoint}')
+ version, platform = archive_identity(args.archive)
+ feed = root / 'feed'
+ publish_archive(feed, args.archive)
+ release = feed / 'releases' / f'v{version}'
+ channel = 'beta' if '-beta' in source['version'] else 'stable'
+ bridge = npm_bridge.assemble(Path(__file__).resolve().parents[2], release, version, channel, args.fallback_tarball)
+ manifest = {'version': version, 'package': 'prime-agent',
+ 'tarball': f'releases/v{version}/{bridge["tarball"]}',
+ 'binaries': [{'platform': platform, 'file': args.archive.name, 'sha256': digest(args.archive)}]}
+ (feed / ('beta.json' if channel == 'beta' else 'latest.json')).write_text(json.dumps(manifest))
+ steps = []
+ with release_server(feed) as base:
+ env = isolated_environment(root / 'user', base)
+ prefix = root / 'npm prefix'
+ if args.previous_prefix:
+ shutil.copytree(args.previous_prefix, prefix, symlinks=True)
+ env.update({'npm_config_prefix': str(prefix), 'npm_config_cache': str(root / 'npm cache'),
+ 'npm_config_ignore_scripts': 'true', 'npm_config_audit': 'false', 'npm_config_fund': 'false',
+ 'npm_config_update_notifier': 'false',
+ 'PRIME_AGENT_RUST_PREFIX': str(root / 'rust prefix'), 'PRIME_AGENT_ALLOW_HTTP': '1',
+ 'PRIME_AGENT_DAEMON_SOCKET': str(root / 'daemon.sock')})
+ env['PATH'] = str(prefix / 'bin') + os.pathsep + env['PATH']
+ if not args.previous_prefix:
+ steps.append(execute(['npm', 'install', '-g', str(archive)], env))
+ package_dir = prefix / 'lib/node_modules/prime-agent'
+ cli = package_dir / source_entrypoint
+ with tarfile.open(archive) as package:
+ assert cli.read_bytes() == package.extractfile(f'package/{source_entrypoint}').read(), 'Prepared prefix is not the supplied released CLI'
+ old = execute(['node', str(cli), '--version'], env)
+ assert (old['stdout'] + old['stderr']).strip() == source['version'], old
+ steps.append(old)
+ state = Path(env['PRIME_AGENT_CODING_AGENT_DIR'])
+ witness = state / 'skills/upgrade-witness/SKILL.md'
+ witness.parent.mkdir(parents=True)
+ witness.write_text('# Preserve this skill\n')
+ update = execute(['node', str(cli), 'update', '--force'], env)
+ steps.append(update)
+ # The old updater launches the bridge as its coordinator. No manual
+ # curl/reinstall/bridge invocation is permitted before this assertion.
+ # Some earliest clients never relaunch; their explicit opt-in case
+ # verifies activation through the next ordinary version command.
+ native = Path(env['PRIME_AGENT_RUST_PREFIX']) / 'bin/prime-agent'
+ activated_during_update = native.is_file()
+ if not activated_during_update and not args.allow_deferred_activation:
+ diagnostic = subprocess.run(['node', str(cli), '--version'], env=env, cwd=env['HOME'], capture_output=True, text=True, timeout=180)
+ raise RuntimeError(json.dumps({'message': 'Old update did not activate the Rust installation', 'steps': steps, 'bridge_diagnostic': {'exit_code': diagnostic.returncode, 'stdout': diagnostic.stdout, 'stderr': diagnostic.stderr}}, indent=2))
+ assert 'could not coordinate' not in update['stderr'].lower(), update
+ assert 'could not restart' not in update['stderr'].lower(), update
+ probe = execute(['node', str(cli), '--version'], env)
+ assert probe['stdout'].strip() == version, probe
+ assert native.is_file(), 'Normal relaunch did not activate Rust'
+ steps.append(probe)
+ steps.append(execute(['node', str(cli), '--help'], env))
+ assert witness.read_text() == '# Preserve this skill\n'
+ assert json.loads((package_dir / 'package.json').read_text())['primeAgentRustBridge'] is True
+ return {'status': 'passed', 'source_version': source['version'], 'target_version': version,
+ 'source_sha256': checksum, 'activation': 'during update' if activated_during_update else 'first normal relaunch',
+ 'source_entrypoint': source_entrypoint, 'channel': channel, 'candidate_sha256': digest(args.archive),
+ 'bridge_sha256': bridge['sha256'], 'coverage': ['real published npm CLI update', 'bridge relaunch',
+ 'Rust activation', 'version/help', 'user skill preservation', 'paths with spaces'],
+ 'not_covered': ['TUI /update', 'running daemon handoff', 'session continuation', 'kernel bootstrap', 'second Rust update'], 'steps': steps}
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--previous-archive', type=Path, required=True)
+ parser.add_argument('--previous-checksums', type=Path, required=True)
+ parser.add_argument('--previous-prefix', type=Path)
+ parser.add_argument('--archive', type=Path, required=True)
+ parser.add_argument('--fallback-tarball', type=Path, required=True)
+ parser.add_argument('--allow-deferred-activation', action='store_true',
+ help='Older updaters without a coordinator may activate Rust on the next normal command')
+ parser.add_argument('--report', type=Path)
+ args = parser.parse_args()
+ args.archive = args.archive.resolve()
+ with tempfile.TemporaryDirectory(prefix='pa-npm-', dir='/tmp') as directory:
+ try:
+ report = exercise(args, Path(directory))
+ except (AssertionError, OSError, RuntimeError, ValueError, subprocess.SubprocessError) as error:
+ report = {'status': 'failed', 'error': str(error)}
+ rendered = json.dumps(report, indent=2)
+ if args.report:
+ args.report.write_text(rendered + '\n')
+ print(rendered)
+ return int(report['status'] != 'passed')
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/scripts/release/test_legacy_runtime_restart.py b/scripts/release/test_legacy_runtime_restart.py
new file mode 100644
index 0000000000..6bdfc1e147
--- /dev/null
+++ b/scripts/release/test_legacy_runtime_restart.py
@@ -0,0 +1,241 @@
+#!/usr/bin/env python3
+"""Exercise a shipped TS daemon's post-install coordinator against a Rust candidate.
+
+This launches no model inference. All homes, sockets, and daemon ownership
+registries are temporary. Run in a disposable Prime sandbox.
+"""
+import argparse
+import json
+import os
+from pathlib import Path
+import signal
+import shutil
+import socket
+import subprocess
+import tarfile
+import tempfile
+import threading
+import time
+
+
+def connect(path):
+ stream = socket.socket(socket.AF_UNIX)
+ stream.settimeout(30)
+ try:
+ stream.connect(str(path))
+ reader = stream.makefile("r")
+ hello = json.loads(reader.readline())
+ return stream, reader, hello
+ except BaseException:
+ stream.close()
+ raise
+
+
+def request(path, command):
+ stream, reader, hello = connect(path)
+ try:
+ stream.sendall((json.dumps({"type": "command", "id": "probe", "protocol": hello["protocol"],
+ "command": command}) + "\n").encode())
+ while line := reader.readline():
+ frame = json.loads(line)
+ if frame.get("type") == "response" and frame.get("id") == "probe":
+ if not frame.get("success"):
+ raise RuntimeError(frame)
+ return frame.get("data")
+ raise RuntimeError("daemon disconnected before response")
+ finally:
+ reader.close()
+ stream.close()
+
+
+def await_hello(path, child):
+ deadline = time.monotonic() + 30
+ while True:
+ try:
+ stream, reader, hello = connect(path)
+ reader.close()
+ stream.close()
+ return hello
+ except (OSError, ValueError):
+ if child.poll() is not None or time.monotonic() >= deadline:
+ raise RuntimeError("old daemon did not become ready")
+ time.sleep(0.05)
+
+
+def stop_fixture_processes(home):
+ """Stop only Linux processes that carry this fixture's unique HOME."""
+ if not Path("/proc").is_dir():
+ return
+ expected = f"HOME={home}".encode()
+ deadline = time.monotonic() + 10
+ while True:
+ matched = []
+ for entry in Path("/proc").iterdir():
+ if not entry.name.isdigit() or int(entry.name) == os.getpid():
+ continue
+ try:
+ if expected in (entry / "environ").read_bytes().split(b"\0"):
+ matched.append(entry)
+ except (FileNotFoundError, ProcessLookupError, PermissionError):
+ continue
+ if not matched:
+ return
+ for entry in matched:
+ try:
+ # Recheck after enumeration so a reused PID cannot be signalled.
+ if expected in (entry / "environ").read_bytes().split(b"\0"):
+ os.kill(int(entry.name), signal.SIGKILL if time.monotonic() > deadline - 5 else signal.SIGTERM)
+ except (FileNotFoundError, ProcessLookupError, PermissionError):
+ pass
+ if time.monotonic() >= deadline:
+ raise RuntimeError("fixture processes did not terminate")
+ time.sleep(0.05)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--legacy-archive", type=Path)
+ parser.add_argument("--legacy-npm-prefix", type=Path)
+ parser.add_argument("--node", default="node")
+ parser.add_argument("--candidate-archive", type=Path)
+ parser.add_argument("--candidate-binary", type=Path)
+ parser.add_argument("--with-session", action="store_true")
+ parser.add_argument("--report", type=Path, required=True)
+ options = parser.parse_args()
+ if bool(options.legacy_archive) == bool(options.legacy_npm_prefix):
+ parser.error("choose one legacy native archive or installed npm prefix")
+ if bool(options.candidate_archive) == bool(options.candidate_binary):
+ parser.error("choose one candidate archive or candidate binary")
+ evidence = {}
+ with tempfile.TemporaryDirectory(prefix="legacy-runtime-") as directory:
+ root = Path(directory)
+ old_dir, candidate_dir = root / "ts", root / "rust"
+ if options.legacy_archive:
+ old_dir.mkdir()
+ with tarfile.open(options.legacy_archive) as archive:
+ archive.extractall(old_dir, filter="data")
+ old_command = [str(old_dir / "prime-agent")]
+ else:
+ shutil.copytree(options.legacy_npm_prefix, old_dir, symlinks=True)
+ old_command = [options.node, str(old_dir / "lib/node_modules/prime-agent/dist/bundle/cli.js")]
+ if options.candidate_archive:
+ candidate_dir.mkdir()
+ with tarfile.open(options.candidate_archive) as archive:
+ archive.extractall(candidate_dir, filter="data")
+ candidate = candidate_dir / "prime-agent"
+ else:
+ candidate = options.candidate_binary.resolve()
+ home, agent, temporary = root / "home", root / "agent", root / "tmp"
+ for path in (home, agent / "update-restarts", temporary):
+ path.mkdir(parents=True)
+ endpoint = temporary / "daemon.sock"
+ env = dict(os.environ)
+ for key in list(env):
+ if key.startswith(("PI_", "PRIME_AGENT_")):
+ del env[key]
+ env.update(HOME=str(home), TMPDIR=str(temporary), DO_NOT_TRACK="1",
+ XDG_CONFIG_HOME=str(home / ".config"), XDG_DATA_HOME=str(home / ".local/share"),
+ XDG_CACHE_HOME=str(home / ".cache"),
+ PRIME_AGENT_CODING_AGENT_DIR=str(agent), PRIME_AGENT_OFFLINE="1",
+ PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_REGISTRY_DIR=str(root / "owners"))
+ with (root / "old.log").open("w") as log:
+ old = subprocess.Popen(old_command + ["--mode", "daemon", "--daemon-socket", str(endpoint)],
+ env=env, cwd=root, stdout=log, stderr=subprocess.STDOUT)
+ threading.Thread(target=old.wait, daemon=True).start()
+ successor_pid = None
+ try:
+ evidence["predecessor"] = await_hello(endpoint, old)
+ transcript = None
+ if options.with_session:
+ # Seed an existing transcript: TS deliberately buffers a brand
+ # new session until its first assistant message exists.
+ transcript = agent / "sessions" / "migration.jsonl"
+ transcript.parent.mkdir(exist_ok=True)
+ stamp = "2026-10-09T00:00:00.000Z"
+ rows = [
+ {"type":"session","version":3,"id":"11111111-2222-4333-8444-555555555555","timestamp":stamp,"cwd":str(root)},
+ {"type":"message","id":"seed-assistant","parentId":None,"timestamp":stamp,"message":{
+ "role":"assistant","content":[{"type":"text","text":"durable migration sentinel"}],
+ "api":"openai-completions","provider":"openai","model":"gpt-4o-mini",
+ "usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,
+ "cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},
+ "stopReason":"stop","timestamp":1791504000000}},
+ ]
+ transcript.write_text("".join(json.dumps(row)+"\n" for row in rows))
+ created = request(endpoint, {"type": "create", "sessionPath":str(transcript), "config": {
+ "cwd": str(root), "agentDir": str(agent), "provider": "openai", "model": "gpt-4o-mini",
+ "noExtensions": True, "noSkills": True, "noContextFiles": True, "telemetryDisabled": True}})
+ evidence["created_session"] = created
+ request(endpoint, {"type": "append_custom_message", "activeSessionId": created["activeSessionId"],
+ "message": {"customType": "migration-test", "content": "live TS checkpoint sentinel",
+ "display": True, "timestamp": int(time.time() * 1000)}})
+ transcript = Path(created["sessionFile"])
+ deadline = time.monotonic() + 10
+ while True:
+ before = transcript.read_text()
+ if "live TS checkpoint sentinel" in before:
+ break
+ if time.monotonic() >= deadline:
+ raise RuntimeError("TS session did not persist the custom message")
+ time.sleep(0.05)
+ status_path = agent / "update-restarts" / "coordinator.json"
+ result = subprocess.run([str(candidate), "update", "--internal-update-restart-coordinator", "--daemon-socket",
+ str(endpoint), "--internal-update-restart-status", str(status_path)],
+ env=env, cwd=root, capture_output=True, text=True, timeout=180)
+ evidence.update(exit_code=result.returncode, stdout=result.stdout, stderr=result.stderr,
+ status=json.loads(status_path.read_text()))
+ stream, reader, hello = connect(endpoint)
+ reader.close()
+ stream.close()
+ evidence["successor"] = hello
+ successor_pid = hello["supervisorPid"]
+ assert result.returncode == 0, evidence
+ assert evidence["status"]["phase"] == "complete", evidence
+ assert successor_pid != old.pid
+ if options.with_session:
+ assert evidence["status"]["counts"]["restored"] == 1, evidence
+ assert evidence["status"]["counts"]["failed"] == 0, evidence
+ assert transcript.read_text().startswith(before), "old transcript must remain intact"
+ evidence["transcript_preserved"] = True
+ evidence["restored_sessions"] = request(endpoint, {"type": "list"})
+ restored = evidence["restored_sessions"]["sessions"]
+ assert len(restored) == 1, restored
+ assert restored[0]["sessionId"] == created["sessionId"], restored
+ assert restored[0]["sessionFile"] == str(transcript), restored
+ witness = "restored-session-bash-witness"
+ evidence["restored_bash"] = request(endpoint, {
+ "type": "execute_bash_and_wait", "activeSessionId": restored[0]["activeSessionId"],
+ "command": f"printf '%s' '{witness}'"})
+ bash = evidence["restored_bash"]
+ assert bash["output"] == witness and bash["exitCode"] == 0, bash
+ assert not bash["cancelled"] and not bash["truncated"], bash
+ deadline = time.monotonic() + 10
+ while True:
+ after = transcript.read_text()
+ rows = [json.loads(line) for line in after.splitlines()]
+ if any(row.get("message", {}).get("role") == "bashExecution"
+ and row["message"].get("output") == witness for row in rows):
+ assert after.startswith(before), "bash execution must preserve old transcript"
+ evidence["restored_bash_persisted"] = True
+ break
+ if time.monotonic() >= deadline:
+ raise RuntimeError("restored worker did not persist the bash result")
+ time.sleep(0.05)
+ evidence["success"] = True
+ finally:
+ evidence["old_log"] = (root / "old.log").read_text()
+ options.report.parent.mkdir(parents=True, exist_ok=True)
+ options.report.write_text(json.dumps(evidence, indent=2) + "\n")
+ try:
+ request(endpoint, {"type": "shutdown", "force": True})
+ except (OSError, ValueError, RuntimeError):
+ pass
+ if old.poll() is None:
+ old.terminate()
+ old.wait(timeout=30)
+ stop_fixture_processes(home)
+ print(json.dumps(evidence, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/release/test_legacy_tui_upgrade.py b/scripts/release/test_legacy_tui_upgrade.py
new file mode 100644
index 0000000000..352ab1bc55
--- /dev/null
+++ b/scripts/release/test_legacy_tui_upgrade.py
@@ -0,0 +1,256 @@
+#!/usr/bin/env python3
+"""Exercise a released TS /update in an isolated tmux session and local feed.
+
+Uses no real provider credentials and sends no inference turns. The test checks
+activation, daemon version replacement, session identity, and a responsive
+restarted TUI. All sockets and state stay within a temporary directory.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from pathlib import Path
+import shlex
+import shutil
+import socket
+import subprocess
+import tarfile
+import tempfile
+import time
+
+from test_legacy_upgrade import (
+ archive_identity, digest, execute, isolated_environment, publish_archive, release_server,
+)
+import npm_bridge
+
+
+def daemon_request(path: Path, command: dict | None = None) -> tuple[dict, dict | None]:
+ with socket.socket(socket.AF_UNIX) as client:
+ client.settimeout(3)
+ client.connect(str(path))
+ stream = client.makefile("r")
+ hello = json.loads(stream.readline())
+ if command is None:
+ return hello, None
+ client.sendall((json.dumps({"type": "command", "id": "migration-probe", "protocol": hello["protocol"], "command": command}) + "\n").encode())
+ while line := stream.readline():
+ response = json.loads(line)
+ if response.get("id") == "migration-probe":
+ return hello, response
+ raise RuntimeError("Daemon closed before replying")
+
+
+def session_files(value) -> set[str]:
+ if isinstance(value, dict):
+ files = {value["sessionFile"]} if isinstance(value.get("sessionFile"), str) else set()
+ for child in value.values():
+ files.update(session_files(child))
+ return files
+ if isinstance(value, list):
+ return set().union(*(session_files(child) for child in value))
+ return set()
+
+
+def wait_for(description: str, probe, timeout: float = 90):
+ deadline = time.monotonic() + timeout
+ last_error = None
+ while time.monotonic() < deadline:
+ try:
+ value = probe()
+ if value:
+ return value
+ except (OSError, ValueError, KeyError, RuntimeError) as error:
+ last_error = str(error)
+ time.sleep(0.1)
+ raise RuntimeError(f"Timed out waiting for {description}: {last_error}")
+
+
+def exercise(root: Path, previous: Path, installer: Path | None, candidate: Path,
+ npm_prefix: Path | None = None, previous_checksums: Path | None = None,
+ fallback_tarball: Path | None = None) -> dict:
+ version, candidate_platform = archive_identity(candidate)
+ if npm_prefix:
+ if previous_checksums is None or fallback_tarball is None:
+ raise ValueError("Published npm checksums and fallback tarball are required")
+ expected = next((line.split()[0] for line in previous_checksums.read_text().splitlines()
+ if len(line.split()) == 2 and line.split()[1].lstrip("*") == previous.name), None)
+ if expected != digest(previous):
+ raise ValueError("Historical npm artifact checksum mismatch")
+ with tarfile.open(previous) as package:
+ metadata = json.load(package.extractfile("package/package.json"))
+ if metadata["name"] != "prime-agent" or metadata["bin"]["prime-agent"] != "dist/bundle/cli.js":
+ raise ValueError("Unexpected historical npm package entrypoint")
+ previous_version = metadata["version"]
+ old_entrypoint = package.extractfile("package/dist/bundle/cli.js").read()
+ platform = candidate_platform
+ else:
+ previous_version, platform = archive_identity(previous)
+ assert platform == candidate_platform
+ feed = root / "feed"
+ if not npm_prefix:
+ publish_archive(feed, previous)
+ publish_archive(feed, candidate)
+ manifest = {"version": version, "binaries": [{"platform": platform, "file": candidate.name, "sha256": digest(candidate)}]}
+ if npm_prefix:
+ bridge = npm_bridge.assemble(Path(__file__).resolve().parents[2], feed / "releases" / f"v{version}", version, "stable", fallback_tarball)
+ manifest.update(package="prime-agent", tarball=f"releases/v{version}/{bridge['tarball']}")
+ (feed / "latest.json").write_text(json.dumps(manifest))
+ daemon_socket = root / "daemon.sock"
+ tmux = ["tmux", "-S", str(root / "tmux.sock")]
+ evidence = {
+ "previous_version": previous_version, "candidate_version": version,
+ "previous_archive": {"path": str(previous), "sha256": digest(previous)},
+ "candidate_archive": {"path": str(candidate), "sha256": digest(candidate)},
+ "installation_method": "npm" if npm_prefix else "native",
+ "steps": [],
+ }
+ if installer:
+ evidence["installer"] = {"path": str(installer), "sha256": digest(installer)}
+ if npm_prefix:
+ evidence["npm_bridge_sha256"] = bridge["sha256"]
+ with release_server(feed) as base:
+ env = isolated_environment(root / "user", base, "standard")
+ env.update(TERM="xterm-256color", ANTHROPIC_API_KEY="fixture-not-a-real-key")
+ state = Path(env["PRIME_AGENT_CODING_AGENT_DIR"])
+ (state / "settings.json").write_text(json.dumps({"onboardingShown": True}))
+ if npm_prefix:
+ isolated_prefix = root / "npm prefix"
+ shutil.copytree(npm_prefix, isolated_prefix, symlinks=True)
+ entrypoint = isolated_prefix / "lib/node_modules/prime-agent/dist/bundle/cli.js"
+ assert entrypoint.read_bytes() == old_entrypoint, "Npm fixture entrypoint differs from published bytes"
+ env.update(npm_config_prefix=str(isolated_prefix), npm_config_cache=str(root / "npm-cache"),
+ npm_config_ignore_scripts="true", npm_config_audit="false", npm_config_fund="false",
+ npm_config_update_notifier="false", PRIME_AGENT_ALLOW_HTTP="1",
+ PRIME_AGENT_RUST_PREFIX=str(root / "rust prefix"),
+ PRIME_AGENT_DAEMON_SOCKET=str(daemon_socket))
+ env["PATH"] = str(isolated_prefix / "bin") + os.pathsep + env["PATH"]
+ public = isolated_prefix / "bin/prime-agent"
+ else:
+ public = Path(env["PRIME_AGENT_BIN_DIR"]) / "prime-agent"
+ evidence["steps"].append(execute(["sh", str(installer), previous_version], env))
+ # TS buffers unsaved drafts until an assistant message exists. Start
+ # from a valid saved transcript so the migration exercises restoration.
+ transcript = state / "sessions" / "migration.jsonl"
+ transcript.parent.mkdir(exist_ok=True)
+ stamp = "2026-10-09T00:00:00.000Z"
+ rows = [
+ {"type": "session", "version": 3, "id": "11111111-2222-4333-8444-555555555555", "timestamp": stamp, "cwd": env["HOME"]},
+ {"type": "message", "id": "seed-assistant", "parentId": None, "timestamp": stamp, "message": {
+ "role": "assistant", "content": [{"type": "text", "text": "durable migration sentinel"}],
+ "api": "anthropic-messages", "provider": "anthropic", "model": "claude-sonnet-4-5",
+ "usage": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "totalTokens": 0,
+ "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0}},
+ "stopReason": "stop", "timestamp": 1791504000000}},
+ ]
+ transcript.write_text("".join(json.dumps(row) + "\n" for row in rows))
+ original_transcript = transcript.read_text()
+ command = [str(public), "--resume", str(transcript), "--daemon-socket", str(daemon_socket), "--provider", "anthropic", "--model", "claude-sonnet-4-5"]
+
+ def tmux_run(*args):
+ return subprocess.run(tmux + list(args), env=env, capture_output=True, text=True, timeout=10)
+
+ def screen():
+ captured = tmux_run("capture-pane", "-p", "-t", "migration")
+ if captured.returncode:
+ raise RuntimeError(captured.stderr)
+ return captured.stdout
+
+ try:
+ started = tmux_run("new-session", "-d", "-s", "migration", "-x", "120", "-y", "36", "-c", env["HOME"], shlex.join(command))
+ if started.returncode:
+ raise RuntimeError(started.stderr)
+ tmux_run("pipe-pane", "-o", "-t", "migration", "cat > " + shlex.quote(str(root / "terminal.log"))).check_returncode()
+ wait_for("TS TUI ready", lambda: "durable migration sentinel" in screen() and "claude-sonnet" in screen())
+ before_hello, before_roster = daemon_request(daemon_socket, {"type": "list"})
+ evidence.update(before_hello=before_hello, before_roster=before_roster, before_screen=screen())
+ # The shipped slash-name completion consumes Enter while appending
+ # a space. End the name explicitly so this Enter submits the command.
+ tmux_run("send-keys", "-t", "migration", "-l", "/update ").check_returncode()
+ wait_for("update text rendered", lambda: "/update" in screen())
+ tmux_run("send-keys", "-t", "migration", "Enter").check_returncode()
+ wait_for("Rust daemon after /update", lambda: daemon_request(daemon_socket)[0].get("appVersion") == version, timeout=180)
+ wait_for("restarted Rust TUI", lambda: (
+ f"prime agent v{version}" in screen() or f"Prime Agent updated to v{version}" in screen()
+ ) and "durable migration sentinel" in screen())
+ wait_for("original session reattached", lambda: any(
+ session.get("sessionFile") == str(transcript) and session.get("attachedClients", 0) > 0
+ for session in daemon_request(daemon_socket, {"type": "list"})[1].get("data", {}).get("sessions", [])
+ ))
+ after_hello, after_roster = daemon_request(daemon_socket, {"type": "list"})
+ evidence.update(after_hello=after_hello, after_roster=after_roster, after_screen=screen())
+ evidence["steps"].append(execute([str(public), "--version"], env))
+ assert before_hello["appVersion"] == previous_version
+ assert after_hello.get("updateResume", {}).get("complete") is True, "Daemon did not finish update restoration"
+ terminal_output = (root / "terminal.log").read_text(errors="replace")
+ assert "could not coordinate the daemon restart" not in terminal_output.lower(), "Update coordinator could not launch"
+ assert "could not restart the daemon" not in terminal_output, "Update coordinator reported restart failure"
+ assert "daemon still runs the previous version" not in terminal_output, "Update coordinator reported a stale daemon"
+ assert before_hello["supervisorPid"] != after_hello["supervisorPid"]
+ previous_sessions = session_files(before_roster)
+ assert previous_sessions, f"TS daemon had no session files: {before_roster}"
+ assert previous_sessions <= session_files(after_roster), "Migrated daemon lost the original session"
+ assert transcript.read_text().startswith(original_transcript), "Saved transcript was rewritten"
+ evidence["transcript_preserved"] = True
+ assert evidence["steps"][-1]["stdout"].strip() == version
+ # Prove the new UI still accepts local input without provider calls.
+ tmux_run("send-keys", "-t", "migration", "-l", "migration-input-witness").check_returncode()
+ wait_for("responsive Rust input", lambda: "migration-input-witness" in screen())
+ evidence["responsive_screen"] = screen()
+ evidence["status"] = "passed"
+ except Exception as error:
+ evidence.update(status="failed", error=str(error))
+ try:
+ evidence["failure_screen"] = screen()
+ except RuntimeError as capture_error:
+ evidence["capture_error"] = str(capture_error)
+ try:
+ evidence["failure_hello"], evidence["failure_roster"] = daemon_request(daemon_socket, {"type": "list"})
+ except (OSError, ValueError, RuntimeError) as daemon_error:
+ evidence["daemon_error"] = str(daemon_error)
+ finally:
+ tmux_run("kill-server")
+ terminal_log = root / "terminal.log"
+ if terminal_log.exists():
+ evidence["terminal_stream"] = terminal_log.read_text(errors="replace")
+ try:
+ hello, _ = daemon_request(daemon_socket, {"type": "shutdown", "force": True})
+ pid = hello.get("supervisorPid")
+ if pid:
+ def stopped():
+ try:
+ os.kill(pid, 0)
+ return False
+ except ProcessLookupError:
+ return True
+ wait_for("isolated daemon cleanup", stopped, timeout=20)
+ except (OSError, ValueError, RuntimeError):
+ pass
+ return evidence
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--previous-archive", required=True, type=Path)
+ method = parser.add_mutually_exclusive_group(required=True)
+ method.add_argument("--installer-file", type=Path)
+ method.add_argument("--previous-npm-prefix", type=Path)
+ parser.add_argument("--previous-checksums", type=Path)
+ parser.add_argument("--fallback-tarball", type=Path)
+ parser.add_argument("--archive", required=True, type=Path)
+ parser.add_argument("--report", required=True, type=Path)
+ args = parser.parse_args()
+ with tempfile.TemporaryDirectory(prefix="ptui-", dir="/tmp") as temporary:
+ report = exercise(Path(temporary), args.previous_archive.resolve(),
+ args.installer_file.resolve() if args.installer_file else None,
+ args.archive.resolve(),
+ args.previous_npm_prefix.resolve() if args.previous_npm_prefix else None,
+ args.previous_checksums.resolve() if args.previous_checksums else None,
+ args.fallback_tarball.resolve() if args.fallback_tarball else None)
+ args.report.write_text(json.dumps(report, indent=2) + "\n")
+ print(json.dumps(report, indent=2))
+ return int(report["status"] != "passed")
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/release/test_legacy_upgrade.py b/scripts/release/test_legacy_upgrade.py
new file mode 100644
index 0000000000..f2e6c3063c
--- /dev/null
+++ b/scripts/release/test_legacy_upgrade.py
@@ -0,0 +1,270 @@
+#!/usr/bin/env python3
+"""Exercise an unchanged TS installer against real candidate release archives.
+
+This is an opt-in integration gate, not a mocked-binary unit test. Example:
+ python3 scripts/release/test_legacy_upgrade.py \
+ --archive /tmp/prime-agent-1.0.0-darwin-arm64.tar.gz \
+ --installer-ref v0.9.8 --previous-archive /tmp/prime-agent-0.9.8-darwin-arm64.tar.gz
+
+Supply one --installer-ref per verified Prime release, or --installer-file to
+use exact bytes extracted from a published artifact. Do not assume every old
+Git tag belongs to Prime Agent: the repository includes upstream project tags.
+The JSON report distinguishes installer execution from CLI/TUI update coverage.
+All download requests use a local HTTP server, and all installation/user paths
+live in a temporary directory. Kernel bootstrap is deliberately disabled; that
+requires its own real-runtime migration test.
+"""
+from __future__ import annotations
+
+import argparse
+import contextlib
+import hashlib
+import http.server
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import signal
+import subprocess
+import tempfile
+import threading
+import tarfile
+
+REPO = Path(__file__).resolve().parents[2]
+ARCHIVE_NAME = re.compile(r"prime-agent-(\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?)-(darwin|linux)-(arm64|x64)([^/]*)\.tar\.gz$")
+
+
+def digest(path: Path) -> str:
+ checksum = hashlib.sha256()
+ with path.open("rb") as stream:
+ for block in iter(lambda: stream.read(1024 * 1024), b""):
+ checksum.update(block)
+ return checksum.hexdigest()
+
+
+def archive_identity(path: Path) -> tuple[str, str]:
+ match = ARCHIVE_NAME.fullmatch(path.name)
+ if not match:
+ raise ValueError(f"Expected a versioned native release archive: {path.name}")
+ version, system, architecture, suffix = match.groups()
+ return version, f"{system}-{architecture}{suffix}"
+
+
+def release_server(root: Path):
+ class Handler(http.server.SimpleHTTPRequestHandler):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, directory=str(root), **kwargs)
+
+ def log_message(self, *_args):
+ pass
+
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ yield f"http://127.0.0.1:{server.server_port}"
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+
+def publish_archive(feed: Path, archive: Path) -> Path:
+ version, _ = archive_identity(archive)
+ directory = feed / "releases" / f"v{version}"
+ directory.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(archive, directory / archive.name)
+ checksums = directory / "SHA256SUMS"
+ checksums.write_text(f"{digest(archive)} {archive.name}\n")
+ return checksums
+
+
+def isolated_environment(root: Path, base_url: str, layout: str = "custom") -> dict[str, str]:
+ # An allowlist prevents inheriting credentials, daemon addresses, package
+ # roots, update overrides, or user-specific runtime paths from the host.
+ env = {name: os.environ[name] for name in ("PATH", "LANG", "LC_ALL", "SYSTEMROOT") if name in os.environ}
+ for name, relative in {
+ "HOME": "home", "TMPDIR": "tmp", "XDG_DATA_HOME": "data",
+ "XDG_CONFIG_HOME": "config", "XDG_CACHE_HOME": "cache",
+ "XDG_RUNTIME_DIR": "run", "PRIME_AGENT_CODING_AGENT_DIR": "home/.prime/agent",
+ "PRIME_AGENT_INSTALL_DIR": "install root", "PRIME_AGENT_BIN_DIR": "public bin",
+ }.items():
+ path = root / relative
+ path.mkdir(parents=True, exist_ok=True)
+ env[name] = str(path)
+ if layout == "standard":
+ for name, relative in {"XDG_DATA_HOME": "home/.local/share", "PRIME_AGENT_INSTALL_DIR": "home/.local/share/prime-agent", "PRIME_AGENT_BIN_DIR": "home/.local/bin"}.items():
+ path = root / relative
+ path.mkdir(parents=True, exist_ok=True)
+ env[name] = str(path)
+ env["npm_config_prefix"] = str(root / "npm")
+ env["npm_config_userconfig"] = str(root / "npmrc")
+ env.update({
+ "SHELL": "/bin/sh", "DO_NOT_TRACK": "1", "TERM": "dumb",
+ "PRIME_AGENT_DOWNLOAD_BASE_URL": base_url,
+ "PRIME_AGENT_ALLOW_INSECURE_HTTP_FOR_TESTS": "1",
+ "PRIME_AGENT_INSTALL_METHOD": "binary", "PRIME_AGENT_INSTALLER_NONINTERACTIVE": "1",
+ "PRIME_AGENT_INSTALLER_PLAIN": "1", "PRIME_AGENT_BOOTSTRAP_KERNEL_ON_INSTALL": "0",
+ "PRIME_AGENT_INSTALL_LINK": "1", "PRIME_AGENT_PROBE_TIMEOUT_SECONDS": "30",
+ })
+ env["PATH"] = env["PRIME_AGENT_BIN_DIR"] + os.pathsep + env.get("PATH", "/usr/bin:/bin")
+ return env
+
+
+def execute(command: list[str], env: dict[str, str], expected_success: bool = True) -> dict:
+ process = subprocess.Popen(command, env=env, cwd=env["HOME"], stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, text=True, start_new_session=True)
+ try:
+ stdout, stderr = process.communicate(timeout=180)
+ except subprocess.TimeoutExpired:
+ # Installer descendants must not outlive the temporary installation.
+ os.killpg(process.pid, signal.SIGKILL)
+ stdout, stderr = process.communicate()
+ raise RuntimeError(json.dumps({"command": command, "error": "timed out after 180s", "stdout": stdout, "stderr": stderr}))
+ evidence = {"command": command, "exit_code": process.returncode, "stdout": stdout, "stderr": stderr}
+ if (process.returncode == 0) != expected_success:
+ raise RuntimeError(json.dumps(evidence, indent=2))
+ return evidence
+
+
+def exercise(installer: Path, archive: Path, previous: Path | None, root: Path, entrypoint: str, next_archive: Path | None = None, layout: str = "custom") -> dict:
+ version, platform = archive_identity(archive)
+ feed = root / "feed"
+ checksums = publish_archive(feed, archive)
+ if previous:
+ previous_version, previous_platform = archive_identity(previous)
+ if previous_platform != platform or previous_version == version:
+ raise ValueError("Previous archive must have the same platform and a different version")
+ publish_archive(feed, previous)
+ (feed / "latest.json").write_text(json.dumps({
+ "version": version, "binaries": [{"platform": platform, "file": archive.name, "sha256": digest(archive)}],
+ }))
+ if next_archive:
+ publish_archive(feed, next_archive)
+ with tarfile.open(next_archive) as payload:
+ script = payload.extractfile("install.sh")
+ if script is None:
+ raise ValueError("Next Rust archive lacks its installer")
+ (feed / "install.sh").write_bytes(script.read())
+ steps = []
+ with release_server(feed) as base_url:
+ env = isolated_environment(root / "user", base_url, layout)
+ state = Path(env["PRIME_AGENT_CODING_AGENT_DIR"])
+ # Opaque content witnesses that installation never edits existing state.
+ witnesses = {
+ "settings.json": '{"migrationWitness":"settings"}\n',
+ "auth.json": '{"migrationWitness":"credentials"}\n',
+ "sessions/migration/session.jsonl": '{"migrationWitness":"session"}\n',
+ "skills/migration/SKILL.md": "# Migration witness\n",
+ }
+ for relative, contents in witnesses.items():
+ path = state / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(contents)
+ public = Path(env["PRIME_AGENT_BIN_DIR"]) / "prime-agent"
+ active = Path(env["PRIME_AGENT_INSTALL_DIR"]) / "bin/prime-agent"
+ if previous:
+ steps.append(execute(["sh", str(installer), previous_version], env))
+ probe = execute([str(public), "--version"], env)
+ assert probe["stdout"].strip() == previous_version, probe
+ steps.append(probe)
+ old_target = os.readlink(active)
+ old_binary_hash = digest(active.resolve())
+ # A corrupted candidate must not change the active TS installation.
+ good_checksums = checksums.read_text()
+ checksums.write_text(f"{'0' * 64} {archive.name}\n")
+ steps.append(execute(["sh", str(installer), version], env, expected_success=False))
+ assert os.readlink(active) == old_target, "Failed upgrade changed active target"
+ assert digest(active.resolve()) == old_binary_hash, "Failed upgrade changed active executable"
+ checksums.write_text(good_checksums)
+ env["PRIME_AGENT_EXPECTED_CURRENT"] = old_target
+ env["PRIME_AGENT_EXPECTED_SHA256"] = digest(archive)
+ update_command = [str(public), "update"] if entrypoint == "cli" else ["sh", str(installer), version]
+ steps.append(execute(update_command, env))
+ probe = execute([str(public), "--version"], env)
+ assert probe["stdout"].strip() == version, probe
+ steps.append(probe)
+ steps.append(execute([str(public), "--help"], env))
+ assert digest(active.resolve()) == digest(public.resolve()), "Public command does not resolve to activated executable"
+ for relative, contents in witnesses.items():
+ assert (state / relative).read_text() == contents, f"User state changed: {relative}"
+ if previous:
+ retained = active.with_name("previous")
+ assert os.readlink(retained) == old_target, "Previous release not retained for recovery"
+ if next_archive:
+ next_version, next_platform = archive_identity(next_archive)
+ assert next_platform == platform, "Second Rust archive uses another platform"
+ (feed / "latest.json").write_text(json.dumps({"version": next_version, "binaries": [{"platform": platform, "file": next_archive.name, "sha256": digest(next_archive)}]}))
+ (feed / "stable").write_text(next_version + "\n")
+ env.pop("PRIME_AGENT_EXPECTED_CURRENT", None)
+ env.pop("PRIME_AGENT_EXPECTED_SHA256", None)
+ env["PRIME_AGENT_RUST_INSTALLER_URL"] = base_url + "/install.sh"
+ env["PRIME_AGENT_ALLOW_HTTP"] = "1"
+ steps.append(execute([str(public), "update"], env))
+ probe = execute([str(public), "--version"], env)
+ steps.append(probe)
+ if probe["stdout"].strip() != next_version:
+ raise RuntimeError(json.dumps({"error": "Second update did not advance the original public command", "expected_version": next_version, "steps": steps}))
+ for relative, contents in witnesses.items():
+ assert (state / relative).read_text() == contents, f"Second update changed user state: {relative}"
+ # The managed coordinator can start a successor even when there
+ # was no prior daemon. Stop that isolated successor before cleanup.
+ steps.append(execute([str(public), "shutdown", "--force"], env))
+ return {"status": "passed", "layout": layout,
+ "platform": platform, "candidate_version": version,
+ "previous_version": archive_identity(previous)[0] if previous else None,
+ "coverage": ["real released CLI update" if entrypoint == "cli" else "unchanged shipped installer", "version/help probes", "paths with spaces", "user state bytes"]
+ + (["checksum failure preserves active release", "previous release retention"] if previous else []) + (["second Rust update through same public command"] if next_archive else []),
+ "not_covered": ([] if entrypoint == "cli" else ["CLI update command"]) + ["TUI /update", "daemon handoff", "session continuation", "kernel bootstrap"] + ([] if next_archive else ["second Rust update"]),
+ "steps": steps}
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--archive", required=True, type=Path)
+ parser.add_argument("--previous-archive", type=Path)
+ parser.add_argument("--next-archive", type=Path, help="Newer Rust artifact for a second update through the migrated command")
+ parser.add_argument("--layout", choices=("custom", "standard"), default="custom")
+ parser.add_argument("--installer-ref", action="append", default=[], help="Verified release tag/commit containing install.sh")
+ parser.add_argument("--installer-file", action="append", type=Path, default=[], help="Installer extracted unchanged from a released artifact")
+ parser.add_argument("--entrypoint", choices=("installer", "cli"), default="installer")
+ parser.add_argument("--report", type=Path, help="Write machine-readable evidence (including failures)")
+ args = parser.parse_args()
+ if not args.installer_ref and not args.installer_file:
+ parser.error("Supply at least one --installer-ref or --installer-file")
+ if args.entrypoint == "cli" and not args.previous_archive:
+ parser.error("--entrypoint cli requires --previous-archive")
+ archives = [args.archive.resolve()] + ([args.previous_archive.resolve()] if args.previous_archive else [])
+ if args.next_archive:
+ archives.append(args.next_archive.resolve())
+ report = {"archives": [{"path": str(path), "sha256": digest(path)} for path in archives], "runs": []}
+ failed = False
+ with tempfile.TemporaryDirectory(prefix="prime-legacy-upgrade-") as temporary:
+ directory = Path(temporary)
+ installers = []
+ for index, ref in enumerate(args.installer_ref):
+ content = subprocess.check_output(["git", "show", f"{ref}:install.sh"], cwd=REPO)
+ commit = subprocess.check_output(["git", "rev-parse", f"{ref}^{{commit}}"], cwd=REPO, text=True).strip()
+ installer = directory / f"installer-{index}.sh"
+ installer.write_bytes(content)
+ installers.append((installer, {"ref": ref, "commit": commit}))
+ installers.extend((path.resolve(), {"file": str(path.resolve())}) for path in args.installer_file)
+ for index, (installer, source) in enumerate(installers):
+ entry = {"installer": {**source, "sha256": digest(installer)}}
+ try:
+ entry.update(exercise(installer, archives[0], args.previous_archive.resolve() if args.previous_archive else None, directory / f"case-{index}", args.entrypoint, args.next_archive.resolve() if args.next_archive else None, args.layout))
+ except (AssertionError, OSError, RuntimeError, ValueError, subprocess.SubprocessError) as error:
+ entry.update(status="failed", error=str(error))
+ failed = True
+ report["runs"].append(entry)
+ rendered = json.dumps(report, indent=2)
+ if args.report:
+ args.report.write_text(rendered + "\n")
+ print(rendered)
+ return int(failed)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/release/test_native_compat.py b/scripts/release/test_native_compat.py
new file mode 100644
index 0000000000..7f05046834
--- /dev/null
+++ b/scripts/release/test_native_compat.py
@@ -0,0 +1,84 @@
+#!/usr/bin/env python3
+"""Packaging regressions; real old-installer execution lives in test_legacy_upgrade."""
+
+import argparse
+import json
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from assemble_artifacts import BUNDLED_CATALOG_FILES, pack_tarball, stage_tree
+from native_compat import validate_compatibility_archive
+
+
+class NativeCompatibilityTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ (self.root / "skills").mkdir()
+ for name in ("LICENSE", "README.md"):
+ (self.root / name).write_text("test fixture\n")
+ runtime = self.root / "prime-agent-runtime"
+ (runtime / "src/rlm").mkdir(parents=True)
+ (runtime / "src/rlm/repl.py").write_text("# runtime fixture\n")
+ (runtime / "pyproject.toml").write_text('[project]\nname = "fixture"\n')
+ for name in BUNDLED_CATALOG_FILES:
+ (self.root / name).write_text("{}\n")
+ self.binary = self.root / "binary"
+ self.binary.write_text("#!/bin/sh\nprintf '1.0.0\\n'\n")
+ self.binary.chmod(0o755)
+
+ def assemble(self, target="aarch64-apple-darwin", stamp=None):
+ staging = self.root / "stage"
+ staging.mkdir()
+ args = argparse.Namespace(
+ repo_root=self.root, target=target, binary=self.binary,
+ runtime_dir=None, catalog_assets=self.root, version="1.0.0", sha="a" * 40,
+ )
+ # Catalog validation has its own integration suite; this test exercises
+ # packaging with a minimal payload to isolate the migration regression.
+ with patch("assemble_artifacts.validate_bundled_catalog_dir", return_value={}):
+ facts = stage_tree(staging, args, stamp)
+ archive = self.root / "release.tar.gz"
+ pack_tarball(staging, archive, facts["payload"])
+ return staging, archive, facts
+
+ def test_stable_archive_satisfies_old_installer_contract(self):
+ staging, archive, _ = self.assemble()
+ validate_compatibility_archive(archive)
+ self.assertEqual(json.loads((staging / "package.json").read_text())["version"], "1.0.0")
+ self.assertEqual((staging / "prime-agent").read_bytes(), self.binary.read_bytes())
+ repo = Path(__file__).resolve().parents[2]
+ self.assertEqual((staging / "install.sh").read_bytes(), (repo / "install-rust.sh").read_bytes())
+
+ def test_continuous_stamp_survives_compatibility_packaging(self):
+ stamp = "1.0.0-continuous." + "a" * 40
+ staging, archive, _ = self.assemble(stamp=stamp)
+ validate_compatibility_archive(archive)
+ self.assertEqual(json.loads((staging / "package.json").read_text())["version"], stamp)
+
+ def test_missing_legacy_file_rejects_archive(self):
+ staging, archive, facts = self.assemble()
+ (staging / "theme/prime.json").unlink()
+ pack_tarball(staging, archive, facts["payload"])
+ with self.assertRaisesRegex(ValueError, "theme/prime.json"):
+ validate_compatibility_archive(archive)
+
+ def test_placeholder_wasm_rejects_archive(self):
+ staging, archive, facts = self.assemble()
+ (staging / "photon_rs_bg.wasm").write_bytes(b"placeholder")
+ pack_tarball(staging, archive, facts["payload"])
+ with self.assertRaisesRegex(ValueError, "Photon.*checksum"):
+ validate_compatibility_archive(archive)
+
+ def test_windows_retains_common_metadata_without_posix_legacy_assets(self):
+ staging, archive, _ = self.assemble(target="x86_64-pc-windows-msvc")
+ validate_compatibility_archive(archive)
+ self.assertTrue((staging / "prime-agent.exe").is_file())
+ self.assertFalse((staging / "photon_rs_bg.wasm").exists())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/release/test_npm_bridge.py b/scripts/release/test_npm_bridge.py
new file mode 100644
index 0000000000..28df876c90
--- /dev/null
+++ b/scripts/release/test_npm_bridge.py
@@ -0,0 +1,414 @@
+#!/usr/bin/env python3
+"""Exercise the packed bridge at the historical npm entrypoint.
+
+The installer fixture isolates launcher behavior; the legacy-update end-to-end
+suite separately exercises the real Rust installer and published TS clients.
+"""
+import hashlib
+import io
+import json
+import os
+from pathlib import Path
+import shutil
+import signal
+import subprocess
+import sys
+import tarfile
+import tempfile
+import unittest
+from unittest.mock import patch
+
+import npm_bridge
+from npm_bridge import assemble
+
+
[email protected](sys.platform in ("darwin", "linux") and shutil.which("node") and shutil.which("npm"),
+ "requires Node and npm on a historical TypeScript platform")
+class NpmBridgeTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ self.repo = self.root / "repo"
+ self.repo.mkdir()
+ self.fallback_tarball = self.root / "fallback.tgz"
+ fallback_files = {
+ "package/package.json": json.dumps({"name": "prime-agent", "version": "0.9.8",
+ "dependencies": {}, "scripts": {"postinstall": "exit 91"}}).encode(),
+ "package/dist/bundle/cli-node.js": b'''#!/usr/bin/env node
+if (process.argv[2] === "--version") console.log("0.9.8");
+else if (process.argv[2] === "entrypoint") console.log(process.argv[1]);
+else if (process.argv[2] === "prefix") console.log(process.env.npm_config_prefix);
+else if (process.argv[2] === "descriptor") console.log(require("node:fs").readFileSync(Number(process.env.TEST_DESCRIPTOR), "utf8"));
+else if (process.argv[2] === "ipc") { process.send({fallback:true}); process.disconnect(); }
+else if (process.argv.includes("update") && !process.argv.includes("--print")) {
+ if (process.env.PRIME_AGENT_INTERNAL_TS_UPDATE) throw new Error("delegation flag leaked into the TS updater");
+ const {spawnSync}=require("node:child_process");
+ let installed={status:0};
+ if (process.env.FUTURE_BRIDGE_TARBALL) {
+ installed=spawnSync("npm",["install","--global","--ignore-scripts","--no-audit","--no-fund",
+ "--prefix",process.env.npm_config_prefix,process.env.FUTURE_BRIDGE_TARBALL],{encoding:"utf8"});
+ }
+ if (installed.status !== 0) { console.error(installed.stderr); process.exitCode=installed.status || 1; }
+ else {
+ // Historical TS CLI warns on a failed coordinator but can still exit zero.
+ // The outer bridge must verify activation instead of trusting that status.
+ const result=spawnSync(process.execPath,[process.argv[1],"update","--internal-update-restart-coordinator"],
+ {env:{...process.env,EXPECT_DEFER:"1"},stdio:"ignore"});
+ if (result.status !== 0) console.error("TypeScript coordinator warning: native migration failed");
+ process.exitCode=0;
+ }
+}
+else console.log(JSON.stringify({fallback:true,args:process.argv.slice(2)}));
+''',
+ }
+ with tarfile.open(self.fallback_tarball, "w:gz") as archive:
+ for name, data in fallback_files.items():
+ member = tarfile.TarInfo(name)
+ member.size = len(data)
+ member.mode = 0o755
+ archive.addfile(member, io.BytesIO(data))
+ # Unit tests use an offline synthetic payload; release code has no
+ # checksum override and only accepts the immutable published archive.
+ fallback_pin = patch.object(npm_bridge, "FALLBACK_SHA256",
+ hashlib.sha256(self.fallback_tarball.read_bytes()).hexdigest())
+ fallback_pin.start()
+ self.addCleanup(fallback_pin.stop)
+ self.prefix = self.root / "native prefix"
+ self.npm_prefix = self.root / "npm prefix"
+ self.installs = self.root / "installs"
+ self.fixture = self.root / "native.js"
+ self.fixture.write_text('''#!/usr/bin/env node
+if (process.argv[2] === "wait") { console.log("ready"); setInterval(() => {}, 1000); }
+else if (process.argv[2] === "--version") console.log(require("node:fs").readFileSync(require("node:path").join(__dirname,"version"),"utf8").trim());
+else if (process.argv[2] === "socket") console.log(process.env.PRIME_AGENT_DAEMON_SOCKET);
+else if (process.argv[2] === "signal") process.kill(process.pid, "SIGTERM");
+else { console.log(JSON.stringify(process.argv.slice(2))); process.exitCode = Number(process.env.NATIVE_EXIT || 0); }
+''')
+ self.fixture.chmod(0o755)
+ (self.repo / "install-rust.sh").write_text('''#!/bin/sh
+set -eu
+test "$PRIME_AGENT_VERSION" = "${EXPECT_VERSION:-1.0.0}"
+test "$PRIME_AGENT_RELEASE_CHANNEL" = "stable"
+test "$PRIME_AGENT_PRESERVE_NPM_BRIDGE" = "1"
+echo install >> "$INSTALL_LOG"
+echo "installer output stays on stderr"
+if [ "${FAIL_INSTALL:-0}" = 1 ]; then exit 23; fi
+test "$PRIME_AGENT_DEFER_DAEMON_STOP" = "${EXPECT_DEFER:-0}"
+test "$PRIME_AGENT_USE_LEGACY_DAEMON_SOCKET" = 1
+mkdir -p "$PRIME_AGENT_RUST_PREFIX/share/prime-agent"
+cp "$FIXTURE_NATIVE" "$PRIME_AGENT_RUST_PREFIX/share/prime-agent/prime-agent"
+printf '%s\\n' "$PRIME_AGENT_VERSION" > "$PRIME_AGENT_RUST_PREFIX/share/prime-agent/version"
+mkdir -p "$PRIME_AGENT_RUST_PREFIX/share/.prime-agent-npm-bridge"
+touch "$PRIME_AGENT_RUST_PREFIX/share/.prime-agent-npm-bridge/legacy-daemon-socket"
+''')
+ self.out = self.root / "out"
+ self.metadata = assemble(self.repo, self.out, "1.0.0", "stable", self.fallback_tarball)
+ self.env = {**os.environ, "PRIME_AGENT_RUST_PREFIX": str(self.prefix),
+ "INSTALL_LOG": str(self.installs), "FIXTURE_NATIVE": str(self.fixture),
+ "npm_config_cache": str(self.root / "npm-cache")}
+ self.env.pop("NODE_OPTIONS", None)
+ installed = subprocess.run(["npm", "install", "--global", "--ignore-scripts", "--no-audit", "--no-fund",
+ "--prefix", str(self.npm_prefix), str(self.out / self.metadata["tarball"])],
+ env=self.env, capture_output=True, text=True)
+ self.assertEqual(installed.returncode, 0, installed.stderr)
+ self.entrypoint = self.npm_prefix / "lib/node_modules/prime-agent/dist/bundle/cli.js"
+
+ def launch(self, *args, **environment):
+ return subprocess.run(["node", str(self.entrypoint), *args],
+ env={**self.env, **environment}, capture_output=True, text=True, timeout=10)
+
+ def test_npm_install_does_not_migrate_until_old_entrypoint_relaunches(self):
+ self.assertFalse(self.installs.exists())
+ args = ("--internal-update-restart-coordinator", "a space", "line\nbreak", "--", "-x")
+ result = self.launch(*args, NATIVE_EXIT="37", EXPECT_DEFER="1")
+ self.assertEqual(result.returncode, 37, result.stderr)
+ self.assertEqual(json.loads(result.stdout), list(args))
+ self.assertIn("installer output stays on stderr", result.stderr)
+ self.assertTrue(self.entrypoint.exists(), "migration must preserve the active npm package")
+
+ def test_later_ts_node_fallback_entrypoint_survives_npm_replacement(self):
+ # v0.9.5+ cli.js shims spawn cli-node.js. Their update coordinator
+ # retains that absolute filename after npm replaces the package.
+ self.entrypoint = self.entrypoint.with_name("cli-node.js")
+ args = ("update", "--internal-update-restart-coordinator", "a space", "--", "-x")
+ result = self.launch(*args, NATIVE_EXIT="37", EXPECT_DEFER="1")
+ self.assertEqual(result.returncode, 37, result.stderr)
+ self.assertEqual(json.loads(result.stdout), list(args))
+ self.assertTrue(self.entrypoint.exists())
+
+ def test_earliest_ts_entrypoint_resolves_package_root_after_replacement(self):
+ # Early published packages capture dist/cli.js. Its compatibility shim
+ # must resolve the bundled installer from the actual package root.
+ self.entrypoint = self.entrypoint.parents[1] / "cli.js"
+ args = ("update", "--internal-update-restart-coordinator", "a space", "--", "-x")
+ result = self.launch(*args, NATIVE_EXIT="37", EXPECT_DEFER="1")
+ self.assertEqual(result.returncode, 37, result.stderr)
+ self.assertEqual(json.loads(result.stdout), list(args))
+ self.assertTrue(self.entrypoint.exists())
+
+ def test_native_self_update_does_not_trigger_pinned_downgrade(self):
+ self.assertEqual(self.launch("first").returncode, 0)
+ # A subsequent native update replaces its payload, but the npm shim
+ # must keep forwarding to it without reinstalling the old pinned release.
+ payload = self.prefix / "share/prime-agent"
+ shutil.rmtree(payload)
+ payload.mkdir()
+ shutil.copy2(self.fixture, payload / "prime-agent")
+ result = self.launch("after-native-update")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(self.installs.read_text(), "install\n")
+
+ def test_completed_migration_launch_does_not_wait_for_migration_lock(self):
+ self.assertEqual(self.launch("first").returncode, 0)
+ lock = self.prefix / "share/.prime-agent-npm-bridge/migration.lock"
+ lock.write_text(json.dumps({"pid": os.getpid(), "token": "another-install"}))
+ result = self.launch("already-installed")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(json.loads(result.stdout), ["already-installed"])
+ self.assertEqual(self.installs.read_text(), "install\n")
+ self.assertTrue(lock.exists(), "ordinary launch must not modify another install's lock")
+
+ def test_new_npm_package_version_does_not_reuse_previous_migration_receipt(self):
+ self.assertEqual(self.launch("first").returncode, 0)
+ package_path = self.entrypoint.parents[2] / "package.json"
+ package = json.loads(package_path.read_text())
+ package["version"] = "1.1.0"
+ package_path.write_text(json.dumps(package))
+ result = self.launch("upgraded-package", EXPECT_VERSION="1.1.0")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(json.loads(result.stdout), ["upgraded-package"])
+ self.assertEqual(self.installs.read_text(), "install\ninstall\n")
+
+ def test_failed_install_does_not_activate_or_record_success(self):
+ result = self.launch("update", FAIL_INSTALL="1")
+ self.assertEqual(result.returncode, 23, result.stderr)
+ self.assertEqual(result.stdout, "")
+ self.assertFalse((self.prefix / "share/.prime-agent-npm-bridge/1.0.0").exists())
+ self.assertEqual(self.launch("update").returncode, 0)
+ self.assertEqual(self.installs.read_text(), "install\ninstall\n")
+
+ def test_failed_native_install_keeps_working_typescript_without_repeated_attempts(self):
+ result = self.launch("a prompt", FAIL_INSTALL="1")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(json.loads(result.stdout), {"fallback": True, "args": ["a prompt"]})
+ self.assertIn("Rust 1.0.0 migration failed", result.stderr)
+ self.assertIn("Continuing with TypeScript 0.9.8", result.stderr)
+ again = self.launch("--version", FAIL_INSTALL="1")
+ self.assertEqual(again.returncode, 0, again.stderr)
+ self.assertEqual(again.stdout.strip(), "0.9.8")
+ self.assertEqual(self.installs.read_text(), "install\n")
+ retry = self.launch("update", FAIL_INSTALL="1")
+ self.assertNotEqual(retry.returncode, 0, retry.stderr)
+ self.assertEqual(retry.stdout, "", "failed update must not recurse through the TS updater")
+ self.assertEqual(self.installs.read_text(), "install\ninstall\n")
+
+ def test_explicit_update_after_fallback_fetches_new_bridge_and_installer(self):
+ self.assertEqual(self.launch("--version", FAIL_INSTALL="1").stdout.strip(), "0.9.8")
+ future = assemble(self.repo, self.root / "future", "1.1.0", "stable", self.fallback_tarball)
+ result = self.launch("--offline", "--daemon-socket", str(self.root / "socket"), "update",
+ FUTURE_BRIDGE_TARBALL=str(self.root / "future" / future["tarball"]),
+ EXPECT_VERSION="1.1.0")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ package = json.loads((self.entrypoint.parents[2] / "package.json").read_text())
+ self.assertEqual(package["version"], "1.1.0")
+ self.assertTrue((self.prefix / "share/.prime-agent-npm-bridge/1.1.0").exists())
+ self.assertEqual(self.launch("--version").stdout.strip(), "1.1.0")
+
+ def test_new_bridge_that_still_cannot_install_rust_is_not_reported_as_success(self):
+ self.assertEqual(self.launch("--version", FAIL_INSTALL="1").stdout.strip(), "0.9.8")
+ future = assemble(self.repo, self.root / "future", "1.1.0", "stable", self.fallback_tarball)
+ result = self.launch("update", FUTURE_BRIDGE_TARBALL=str(self.root / "future" / future["tarball"]),
+ EXPECT_VERSION="1.1.0", FAIL_INSTALL="1")
+ self.assertNotEqual(result.returncode, 0, result.stderr)
+ self.assertIn("did not activate a working Rust release", result.stderr)
+ self.assertEqual(self.launch("--version").stdout.strip(), "0.9.8")
+
+ def test_update_after_global_options_fails_honestly_but_update_prompt_can_fallback(self):
+ result = self.launch("--offline", "--daemon-socket", str(self.root / "socket"),
+ "update", FAIL_INSTALL="1")
+ self.assertEqual(result.returncode, 23, result.stderr)
+ self.assertEqual(result.stdout, "")
+ prompt = self.launch("--print", "update")
+ self.assertEqual(prompt.returncode, 0, prompt.stderr)
+ self.assertEqual(json.loads(prompt.stdout), {"fallback": True, "args": ["--print", "update"]})
+
+ def test_coordinator_failure_remains_failed_while_later_commands_use_typescript(self):
+ status = self.root / "agent/update-restarts/failed.json"
+ result = self.launch("update", "--internal-update-restart-coordinator",
+ "--internal-update-restart-status", str(status),
+ FAIL_INSTALL="1", EXPECT_DEFER="1")
+ self.assertEqual(result.returncode, 23, result.stderr)
+ self.assertEqual(json.loads(status.read_text())["phase"], "failed")
+ self.assertEqual(result.stdout, "")
+ self.assertEqual(self.launch("--version").stdout.strip(), "0.9.8")
+
+ def test_fallback_self_update_captures_public_bridge_entrypoint(self):
+ result = self.launch("entrypoint", FAIL_INSTALL="1")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout.strip(), str(self.entrypoint))
+ self.assertEqual(self.launch("prefix").stdout.strip(), str(self.npm_prefix))
+
+ def test_fallback_preserves_inherited_worker_descriptor(self):
+ channel = self.root / "worker-channel"
+ channel.write_text("worker ready")
+ descriptor = os.open(channel, os.O_RDONLY)
+ try:
+ result = subprocess.run(["node", str(self.entrypoint), "descriptor"],
+ env={**self.env, "FAIL_INSTALL": "1", "TEST_DESCRIPTOR": str(descriptor)},
+ pass_fds=(descriptor,), capture_output=True, text=True, timeout=10)
+ finally:
+ os.close(descriptor)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout.strip(), "worker ready")
+
+ def test_fallback_preserves_node_catalog_ipc_channel(self):
+ driver = '''
+const {fork}=require("node:child_process");
+const child=fork(process.argv[1],["ipc"],{execArgv:[],stdio:["ignore","pipe","pipe","ipc"]});
+child.stderr.pipe(process.stderr);
+child.on("message",value=>console.log(JSON.stringify(value)));
+child.on("exit",code=>{process.exitCode=code;});
+'''
+ result = subprocess.run(["node", "-e", driver, str(self.entrypoint)],
+ env={**self.env, "FAIL_INSTALL": "1"},
+ capture_output=True, text=True, timeout=10)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(json.loads(result.stdout), {"fallback": True})
+
+ def test_native_signal_status_is_preserved(self):
+ result = self.launch("signal")
+ self.assertEqual(result.returncode, -signal.SIGTERM, result.stderr)
+
+ def test_signal_to_npm_launcher_reaches_native_child(self):
+ with subprocess.Popen(["node", str(self.entrypoint), "wait"], env=self.env,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) as child:
+ self.assertEqual(child.stdout.readline(), "ready\n")
+ child.send_signal(signal.SIGTERM)
+ _, stderr = child.communicate(timeout=10)
+ self.assertEqual(child.returncode, -signal.SIGTERM, stderr)
+
+ def test_missing_native_install_is_repaired(self):
+ self.assertEqual(self.launch().returncode, 0)
+ (self.prefix / "share/prime-agent/prime-agent").unlink()
+ self.assertEqual(self.launch().returncode, 0)
+ self.assertEqual(self.installs.read_text(), "install\ninstall\n")
+
+ def test_npm_and_native_prefix_overlap_does_not_recurse(self):
+ self.prefix = self.npm_prefix
+ self.env["PRIME_AGENT_RUST_PREFIX"] = str(self.prefix)
+ self.assertEqual(self.launch("first").returncode, 0)
+ # npm owns this link and may replace it during npm install at any time.
+ command = self.prefix / "bin/prime-agent"
+ self.assertEqual(command.resolve(), self.entrypoint.resolve())
+ result = subprocess.run([str(command), "after-npm-reinstall"], env=self.env,
+ capture_output=True, text=True, timeout=10)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(json.loads(result.stdout), ["after-npm-reinstall"])
+ self.assertEqual(self.installs.read_text(), "install\n")
+
+ def test_later_launch_keeps_migrated_daemon_socket_namespace(self):
+ self.env.pop("PRIME_AGENT_DAEMON_SOCKET", None)
+ self.env["TMPDIR"] = str(self.root / "sockets")
+ self.assertEqual(self.launch("--internal-update-restart-coordinator", EXPECT_DEFER="1").returncode, 0)
+ expected = str(self.root / "sockets" / f"prime-agent-{os.getuid()}" / "daemon.sock")
+ result = self.launch("socket")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout.strip(), expected)
+ custom = self.launch("socket", PRIME_AGENT_DAEMON_SOCKET=str(self.root / "custom.sock"))
+ self.assertEqual(custom.stdout.strip(), str(self.root / "custom.sock"))
+
+ def test_stale_bridge_does_not_downgrade_newer_native_without_receipt(self):
+ payload = self.prefix / "share/prime-agent"
+ payload.mkdir(parents=True)
+ executable = payload / "prime-agent"
+ executable.write_text('''#!/usr/bin/env node
+if (process.argv[2] === "--version") console.log("prime-agent 1.2.0");
+else if (process.argv[2] === "socket") console.log(process.env.PRIME_AGENT_DAEMON_SOCKET);
+else console.log(JSON.stringify(process.argv.slice(2)));
+''')
+ executable.chmod(0o755)
+ result = self.launch("keep-newer")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertFalse(self.installs.exists())
+ self.assertEqual(json.loads(result.stdout), ["keep-newer"])
+ self.env.pop("PRIME_AGENT_DAEMON_SOCKET", None)
+ self.env["TMPDIR"] = str(self.root / "sockets")
+ expected = str(self.root / "sockets" / f"prime-agent-rust-{os.getuid()}" / "daemon.sock")
+ self.assertEqual(self.launch("socket").stdout.strip(), expected)
+
+ def test_concurrent_first_launches_install_once(self):
+ processes = [subprocess.Popen(["node", str(self.entrypoint), str(i)], env=self.env,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ for i in range(4)]
+ try:
+ for i, child in enumerate(processes):
+ stdout, stderr = child.communicate(timeout=10)
+ self.assertEqual(child.returncode, 0, stderr)
+ self.assertEqual(json.loads(stdout), [str(i)])
+ finally:
+ for child in processes:
+ if child.poll() is None:
+ child.kill()
+ child.wait()
+ self.assertEqual(self.installs.read_text(), "install\n")
+
+ def test_coordinator_status_exists_before_install_and_defers_daemon_stop(self):
+ status = self.root / "agent/update-restarts/status.json"
+ installer = self.repo / "install-rust.sh"
+ installer.write_text(installer.read_text() + '\ntest -s "$TEST_RESTART_STATUS"\n')
+ assemble(self.repo, self.out, "1.0.0", "stable", self.fallback_tarball)
+ # Replace the installed fixture, preserving the real npm entrypoint.
+ shutil.copy2(installer, self.entrypoint.parents[2] / "install-rust.sh")
+ args = ["update", "--internal-update-restart-coordinator", "--internal-update-restart-status",
+ str(status), "--daemon-socket", str(self.root / "old.sock")]
+ result = self.launch(*args, EXPECT_DEFER="1", TEST_RESTART_STATUS=str(status))
+ self.assertEqual(result.returncode, 0, result.stderr)
+ value = json.loads(status.read_text())
+ self.assertEqual(value["phase"], "starting")
+ self.assertEqual(value["socketPath"], str(self.root / "old.sock"))
+ self.assertEqual(json.loads(result.stdout), args)
+
+ def test_archive_is_deterministic_and_has_no_lifecycle_scripts(self):
+ other = assemble(self.repo, self.root / "other", "1.0.0", "stable", self.fallback_tarball)
+ self.assertEqual(other, self.metadata)
+ with tarfile.open(self.out / self.metadata["tarball"]) as archive:
+ package = json.load(archive.extractfile("package/package.json"))
+ self.assertNotIn("scripts", package)
+ self.assertTrue(package["primeAgentRustBridge"])
+
+ def test_real_installer_keeps_bridge_but_retires_ts_package(self):
+ installer = (Path(__file__).resolve().parents[2] / "install-rust.sh").read_text()
+ retirement = installer.split("# The TS npm package:", 1)[1].split(
+ "# --- the kernel pre-warm:", 1)[0]
+ retirement = "# The TS npm package:" + retirement
+ fake_bin = self.root / "fake-bin"
+ fake_bin.mkdir()
+ npm_root = self.root / "npm-root"
+ package_dir = npm_root / "prime-agent"
+ package_dir.mkdir(parents=True)
+ uninstalls = self.root / "uninstalls"
+ fake_npm = fake_bin / "npm"
+ fake_npm.write_text('''#!/bin/sh
+if [ "$1" = root ]; then echo "$TEST_NPM_ROOT"; else echo uninstall >> "$TEST_UNINSTALL_LOG"; fi
+''')
+ fake_npm.chmod(0o755)
+ for flag, bridge, expected in (("1", False, False), ("", True, False), ("", False, True)):
+ with self.subTest(flag=flag, bridge=bridge):
+ uninstalls.unlink(missing_ok=True)
+ (package_dir / "package.json").write_text(json.dumps({
+ "name": "prime-agent", "version": "1.0.0" if bridge else "0.9.8",
+ "primeAgentRustBridge": bridge}))
+ result = subprocess.run(["sh", "-eu"], input='''
+WINDOWS=no
+step_start() { :; }; step_ok() { :; }; step_fail() { :; }; note() { :; }; todo() { :; }
+''' + retirement, text=True, capture_output=True, env={**self.env,
+ "PATH": str(fake_bin) + os.pathsep + self.env["PATH"],
+ "UVPY": sys.executable, "TEST_NPM_ROOT": str(npm_root),
+ "TEST_UNINSTALL_LOG": str(uninstalls), "PRIME_AGENT_PRESERVE_NPM_BRIDGE": flag})
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(uninstalls.exists(), expected)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/release/test_restamp.py b/scripts/release/test_restamp.py
index d244760390..076401c65b 100644
--- a/scripts/release/test_restamp.py
+++ b/scripts/release/test_restamp.py
@@ -110,7 +110,8 @@ class ContinuousFixture:
runtime = root / "runtime"
runtime.mkdir()
(runtime / "pyproject.toml").write_text("[project]\nname='rlm'\n")
- (runtime / "src").mkdir()
+ (runtime / "src" / "rlm").mkdir(parents=True)
+ (runtime / "src" / "rlm" / "repl.py").write_text("# fixture REPL\n")
(root / "prime-agent-runtime").mkdir()
(root / "prime-agent-runtime" / "pyproject.toml").write_text("[project]\nname='rlm'\n")
diff --git a/scripts/release/verify_legacy_release.py b/scripts/release/verify_legacy_release.py
new file mode 100644
index 0000000000..4c5272d59d
--- /dev/null
+++ b/scripts/release/verify_legacy_release.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python3
+"""Verify a candidate with the real published native TypeScript updater.
+
+Downloads immutable previous-release artifacts and verifies their published
+checksums before running the isolated migration harness. No user install is used.
+"""
+from __future__ import annotations
+
+import argparse
+import subprocess
+import sys
+import tarfile
+import tempfile
+from pathlib import Path
+
+from test_legacy_upgrade import archive_identity, digest
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--candidate", type=Path, required=True)
+ parser.add_argument("--previous-version", default="0.9.8")
+ parser.add_argument("--report", type=Path, required=True)
+ args = parser.parse_args()
+ _, platform = archive_identity(args.candidate)
+ version = args.previous_version
+ if version not in {"0.9.5", "0.9.6", "0.9.7", "0.9.8"}:
+ parser.error("previous version must be a published native TS release (0.9.5–0.9.8)")
+ name = f"prime-agent-{version}-{platform}.tar.gz"
+ base = f"https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v{version}"
+ with tempfile.TemporaryDirectory(prefix="prime-legacy-release-") as temporary:
+ root = Path(temporary)
+ for filename in (name, "SHA256SUMS"):
+ subprocess.run(["curl", "--fail", "--location", "--silent", "--show-error",
+ "--connect-timeout", "15", "--max-time", "300",
+ f"{base}/{filename}", "--output", str(root / filename)], check=True)
+ rows = [line.split() for line in (root / "SHA256SUMS").read_text().splitlines()]
+ hashes = [row[0] for row in rows if len(row) == 2 and row[1] == name]
+ if len(hashes) != 1 or hashes[0] != digest(root / name):
+ raise ValueError("published TS artifact failed checksum verification")
+ installer = root / "install.sh"
+ with tarfile.open(root / name) as archive:
+ member = archive.getmember("install.sh")
+ if not member.isfile():
+ raise ValueError("published installer is not a regular file")
+ installer.write_bytes(archive.extractfile(member).read())
+ result = subprocess.run([
+ sys.executable, str(Path(__file__).with_name("test_legacy_upgrade.py")),
+ "--archive", str(args.candidate.resolve()),
+ "--previous-archive", str(root / name),
+ "--installer-file", str(installer), "--entrypoint", "cli",
+ "--report", str(args.report.resolve()),
+ ])
+ return result.returncode
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/release/verify_release.py b/scripts/release/verify_release.py
index a6a866aad4..64424f8395 100644
--- a/scripts/release/verify_release.py
+++ b/scripts/release/verify_release.py
@@ -31,6 +31,7 @@ from pathlib import Path
# The bundled-catalog gate (same release-scripts directory).
from bundle_catalog import validate_bundled_catalog_dir
+from native_compat import validate_compatibility_archive
# The release platform alias the archive name carries (TS parity; the update
# flow's channel manifest requires alias-named archives).
from assemble_artifacts import (
@@ -41,9 +42,8 @@ from assemble_artifacts import (
)
# Must mirror STAGED_ENTRIES in assemble_artifacts.py and §5 of the design doc.
-# Never add a root-level install.sh: it is what lets a TypeScript 0.9.8
-# updater install the archive (release.yml's promote job refuses it).
-# Continuous builds additionally stage the package.json version manifest.
+# POSIX archives preserve the native TS updater contract. Every archive
+# carries version metadata; Windows never had a native TS installation.
# The binary entry is the target's name (`prime-agent.exe` on the MSVC
# Windows target), resolved in `main` via `binary_name_for_target`.
EXPECTED_TOP_LEVEL = {
@@ -52,6 +52,7 @@ EXPECTED_TOP_LEVEL = {
"skills",
"LICENSE",
"README.md",
+ "package.json",
# The bundled catalog assets (spec §3.2): the installed artifact must
# contain both, and they must pass the same validation gates the packer
# enforced at assembly time.
@@ -59,6 +60,7 @@ EXPECTED_TOP_LEVEL = {
"mcp-services.bundled.json",
}
CONTINUOUS_EXTRA_TOP_LEVEL = {"package.json"}
+NATIVE_COMPAT_TOP_LEVEL = {"theme", "export-html", "photon_rs_bg.wasm", "PHOTON-LICENSE.md", "install.sh"}
# Same shape as `continuous_version` in assemble_artifacts.py.
CONTINUOUS_SUFFIX = "continuous"
@@ -103,6 +105,8 @@ def main() -> int:
binary_name = binary_name_for_target(args.target)
expected_top_level = (EXPECTED_TOP_LEVEL - {"prime-agent"}) | {binary_name}
+ if binary_name != "prime-agent.exe":
+ expected_top_level |= NATIVE_COMPAT_TOP_LEVEL
expected_top_level |= (
CONTINUOUS_EXTRA_TOP_LEVEL if (args.sha or args.expect_package_json)
else set()
@@ -115,6 +119,8 @@ def main() -> int:
if not archive.is_file():
fail(f"archive {archive} not found; run assemble_artifacts.py first")
+ validate_compatibility_archive(archive)
+
# 1. Deterministic tarball shape: exact top-level payload, no link entries.
with tarfile.open(archive) as tar:
members = tar.getmembers()