Skip to content

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

Rust

prepare the homebrew-core release: src tarball, formula, update guard (#3372)

ktf220e19a9bb7
diff --git a/.changes/update-homebrew-refusal.md b/.changes/update-homebrew-refusal.md
new file mode 100644
index 0000000000..643ad91fa5
--- /dev/null
+++ b/.changes/update-homebrew-refusal.md
@@ -0,0 +1 @@
+- `prime-agent update` on a Homebrew-managed install (Cellar formula or Caskroom cask) no longer attempts an installer self-update: it now refuses and points at `brew upgrade prime-agent` (or `brew upgrade --cask prime-agent`).
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index cd807bf92b..864e0b432b 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -215,6 +215,34 @@ jobs:
--catalog-assets "target/${{ matrix.target }}/catalog-assets" \
--out-dir "target/${{ matrix.target }}/dist"
cat "target/${{ matrix.target }}/dist/manifest.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
+ # cut per stable release: the job gate keeps this stable-only, and the
+ # step gate holds the matrix to a single leg so the artifact exists
+ # exactly once. The output goes to its own src-dist dir — the binary
+ # artifact's upload glob (dist/prime-agent-*) must not pick the src
+ # tarball up as a per-target artifact.
+ - name: Assemble the source tarball (homebrew-core candidate)
+ if: matrix.target == 'x86_64-unknown-linux-gnu' && !contains(github.ref_name, '-')
+ run: |
+ set -euo pipefail
+ python3 scripts/release/assemble_source.py \
+ --repo-root . \
+ --version "${RELEASE_VERSION#v}" \
+ --catalog-assets "target/${{ matrix.target }}/catalog-assets" \
+ --out-dir "target/${{ matrix.target }}/src-dist"
+ cat "target/${{ matrix.target }}/src-dist/manifest.json"
+ - name: Upload the source tarball artifacts
+ if: matrix.target == 'x86_64-unknown-linux-gnu' && !contains(github.ref_name, '-')
+ uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
+ with:
+ name: artifacts-source
+ path: |
+ target/${{ matrix.target }}/src-dist/prime-agent-*
+ target/${{ matrix.target }}/src-dist/SHA256SUMS
+ target/${{ matrix.target }}/src-dist/manifest.json
+ if-no-files-found: error
- name: Upload artifacts
# The glob carries the decoder alongside the payload files — it is
# a workflow artifact, never a tarball member: assemble never stages
@@ -852,7 +880,12 @@ jobs:
(cd release-out && sha256sum --check SHA256SUMS)
RELEASE_PREFIX="releases/${RELEASE_VERSION}"
+ # The R2 channel serves the installers: the platform tarballs
+ # 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
+ case "$artifact" in *-src.tar.gz) continue ;; esac
aws s3 cp "$artifact" "s3://${R2_BUCKET}/${RELEASE_PREFIX}/$(basename "$artifact")" \
--endpoint-url "$R2_ENDPOINT_URL" \
--content-type application/gzip \
diff --git a/crates/pa-cli/src/client_update.rs b/crates/pa-cli/src/client_update.rs
index d5d7bf2e1e..8c60fb59fa 100644
--- a/crates/pa-cli/src/client_update.rs
+++ b/crates/pa-cli/src/client_update.rs
@@ -2,10 +2,10 @@
//! output captured — the TUI stays mounted while the install runs, so the
//! installer's own progress never writes to the live frame, and the
//! failure tail becomes the error row's message. It follows the same
-//! update channel as `prime-agent update`. The same body
-//! `prime-agent update` runs (pa-core's installer module), so the TUI and
-//! the CLI cannot diverge.
+//! update channel as `prime-agent update`. Both surfaces consult the
+//! same pa-core Homebrew detector before entering the installer funnel.
+use pa_core::update::homebrew;
use pa_core::update::installer::{self, InstallerOutput};
#[derive(Clone, Default)]
@@ -14,6 +14,30 @@ pub struct ClientUpdate;
impl pa_tui::update_command::UpdateCommands for ClientUpdate {
fn run_update(&self) -> pa_tui::update_command::UpdateRunFuture {
Box::pin(async {
+ if let Some(kind) = std::env::current_exe()
+ .ok()
+ .as_deref()
+ .and_then(homebrew::managed_kind)
+ {
+ if let Ok(cwd) = std::env::current_dir() {
+ let agent_dir = crate::config::get_agent_dir();
+ let settings = pa_core::settings::SettingsManager::create(&cwd, &agent_dir);
+ if !crate::mode::telemetry_disabled(&settings) {
+ let client =
+ pa_core::session_engine::telemetry::build_client(&settings, &agent_dir);
+ pa_telemetry::UpdateHomebrewRefusal {
+ kind: kind.as_str(),
+ }
+ .track(&client);
+ // The TUI already owns a runtime; draining in the
+ // background cannot delay the refusal row.
+ tokio::spawn(async move {
+ let _ = client.shutdown().await;
+ });
+ }
+ }
+ return Err(homebrew::upgrade_instruction(kind));
+ }
match installer::run_installer(
Some(crate::installer_update::requested_installer_channel(None)),
InstallerOutput::Capture,
diff --git a/crates/pa-cli/src/config.rs b/crates/pa-cli/src/config.rs
index 511a997e7e..61442befa9 100644
--- a/crates/pa-cli/src/config.rs
+++ b/crates/pa-cli/src/config.rs
@@ -1,6 +1,6 @@
//! Product-wide constants and environment handling.
-use std::path::{Path, PathBuf};
+use std::path::PathBuf;
pub const APP_NAME: &str = "prime-agent";
@@ -57,7 +57,8 @@ pub fn version() -> &'static str {
}
/// The packaged package-dir (`PI_PACKAGE_DIR` wins, else the directory of
-/// the executable).
+/// the executable, launcher symlinks resolved through pa-core's
+/// `exe_dir_of`).
fn package_dir() -> PathBuf {
if let Ok(env_dir) = std::env::var("PI_PACKAGE_DIR") {
if !env_dir.is_empty() {
@@ -66,7 +67,7 @@ fn package_dir() -> PathBuf {
}
std::env::current_exe()
.ok()
- .and_then(|exe| exe.parent().map(Path::to_path_buf))
+ .and_then(|exe| pa_core::packages::exe_dir_of(&exe))
.unwrap_or_else(|| PathBuf::from("."))
}
diff --git a/crates/pa-cli/src/installer_update.rs b/crates/pa-cli/src/installer_update.rs
index 5aa67179d8..0ecbbdd22b 100644
--- a/crates/pa-cli/src/installer_update.rs
+++ b/crates/pa-cli/src/installer_update.rs
@@ -6,13 +6,18 @@
//! TypeScript version, installs the latest Rust build of the update
//! channel, and never touches `~/.prime/agent` (the sessions and
//! configuration). The TUI's `/update` runs the same core out-of-band
-//! (`client_update.rs`), so the two surfaces cannot diverge.
+//! (`client_update.rs`); both consult pa-core's Homebrew detector before
+//! entering the installer funnel.
+use pa_core::update::homebrew;
use pa_core::update::install::current_platform_alias;
use pa_core::update::installer::{self, InstallerOutput};
use pa_core::update::release::{artifact_for_platform, LatestRelease};
use pa_core::update::version::UpdateChannel;
+/// TS self-update's no-install exit code: the package manager owns this update.
+const SELF_UPDATE_NOT_ATTEMPTED_EXIT_CODE: i32 = 75;
+
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct UpdateOptions {
/// `--check`: print the latest release of the update channel vs the
@@ -79,6 +84,50 @@ pub fn requested_installer_channel(flag: Option<UpdateChannel>) -> &'static str
/// Run the update command: the funnel (the installer script owns the
/// whole move) or the `--check` report. Returns the process exit code.
pub fn run(options: &UpdateOptions) -> i32 {
+ // `--check` is read-only and remains available to Homebrew installs.
+ let homebrew_kind = if options.check {
+ None
+ } else {
+ std::env::current_exe()
+ .ok()
+ .as_deref()
+ .and_then(homebrew::managed_kind)
+ };
+ if let Some(kind) = homebrew_kind {
+ println!("{}", homebrew::upgrade_instruction(kind));
+ // The refusal must not depend on telemetry. A one-shot runtime is
+ // only needed when recording is enabled; failure to record never
+ // changes the instruction or the no-install exit code.
+ if let Ok(cwd) = std::env::current_dir() {
+ let agent_dir = crate::config::get_agent_dir();
+ let settings = pa_core::settings::SettingsManager::create(&cwd, &agent_dir);
+ let telemetry_runtime = (!crate::mode::telemetry_disabled(&settings))
+ .then(|| {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ })
+ .and_then(Result::ok);
+ if let Some(runtime) = telemetry_runtime {
+ runtime.block_on(async {
+ let client =
+ pa_core::session_engine::telemetry::build_client(&settings, &agent_dir);
+ pa_telemetry::UpdateHomebrewRefusal {
+ kind: kind.as_str(),
+ }
+ .track(&client);
+ let _ = tokio::time::timeout(
+ std::time::Duration::from_millis(
+ pa_tui::interactive::TELEMETRY_EXIT_TIMEOUT_MS,
+ ),
+ client.shutdown(),
+ )
+ .await;
+ });
+ }
+ }
+ return SELF_UPDATE_NOT_ATTEMPTED_EXIT_CODE;
+ }
let Ok(runtime) = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
diff --git a/crates/pa-core/src/kernel/bootstrap/venv/runtime_source.rs b/crates/pa-core/src/kernel/bootstrap/venv/runtime_source.rs
index d5e22d44e5..7e92a924f2 100644
--- a/crates/pa-core/src/kernel/bootstrap/venv/runtime_source.rs
+++ b/crates/pa-core/src/kernel/bootstrap/venv/runtime_source.rs
@@ -12,11 +12,10 @@ pub(in crate::kernel::bootstrap) fn package_dir() -> PathBuf {
return expand_home(&env_dir);
}
}
- let exe_dir = std::env::current_exe()
+ std::env::current_exe()
.ok()
- .and_then(|exe| exe.parent().map(Path::to_path_buf))
- .unwrap_or_else(|| PathBuf::from("."));
- exe_dir
+ .and_then(|exe| crate::packages::exe_dir_of(&exe))
+ .unwrap_or_else(|| PathBuf::from("."))
}
/// The packaged sidecar directory (the exe-adjacent layout): the TS `runtimeCandidateDirs`
diff --git a/crates/pa-core/src/packages/mod.rs b/crates/pa-core/src/packages/mod.rs
index 3a8120f613..ed74f3c82e 100644
--- a/crates/pa-core/src/packages/mod.rs
+++ b/crates/pa-core/src/packages/mod.rs
@@ -43,7 +43,8 @@ pub(crate) fn is_offline_mode_enabled() -> bool {
/// The package directory: `PI_PACKAGE_DIR` wins (matching the TS
/// `getPackageDir` override), then the directory of the executable (the
-/// packaged bun-binary layout).
+/// packaged bun-binary layout), through [`exe_dir_of`] so a launcher
+/// symlink resolves.
pub(crate) fn package_dir() -> PathBuf {
if let Ok(env_dir) = std::env::var("PI_PACKAGE_DIR") {
if !env_dir.is_empty() {
@@ -52,10 +53,27 @@ pub(crate) fn package_dir() -> PathBuf {
}
std::env::current_exe()
.ok()
- .and_then(|exe| exe.parent().map(std::path::Path::to_path_buf))
+ .and_then(|exe| exe_dir_of(&exe))
.unwrap_or_else(|| PathBuf::from("."))
}
+/// The directory beside the binary's real file: a launcher symlink (the
+/// Homebrew formula's `bin` link) must resolve, or the payload shipped
+/// beside the real binary is invisible; a plain path stays untouched.
+/// The managed installer's launcher (`update::install::install_root_of`)
+/// resolves its launch the same way.
+#[must_use]
+pub fn exe_dir_of(exe: &std::path::Path) -> Option<PathBuf> {
+ let is_symlink =
+ std::fs::symlink_metadata(exe).is_ok_and(|metadata| metadata.file_type().is_symlink());
+ let resolved = if is_symlink {
+ exe.canonicalize().ok()?
+ } else {
+ exe.to_path_buf()
+ };
+ resolved.parent().map(std::path::Path::to_path_buf)
+}
+
/// The bundled docs directory (TS `getDocsPath`): `<package dir>/docs`.
#[must_use]
pub fn docs_path() -> PathBuf {
diff --git a/crates/pa-core/src/packages/tests.rs b/crates/pa-core/src/packages/tests.rs
index 044f38298a..105fd4e9f6 100644
--- a/crates/pa-core/src/packages/tests.rs
+++ b/crates/pa-core/src/packages/tests.rs
@@ -6,6 +6,8 @@ use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::Command;
+#[cfg(unix)]
+use crate::packages::exe_dir_of;
use crate::packages::source::{GitSource, SourceScope, UserOrProject};
use crate::packages::PackageManager;
use crate::settings::SettingsManager;
@@ -327,3 +329,22 @@ fn git_ref_checkout_installs_the_pinned_revision() {
assert!(installed.join("package.json").exists());
assert!(!installed.join("skills.md").exists(), "pinned ref checkout");
}
+
+/// A launcher symlink resolves to the real binary's directory (the
+/// Homebrew formula's `bin` link): the shipped payload sits beside the
+/// real file, and a plain path stays untouched.
+#[cfg(unix)]
+#[test]
+fn exe_dir_of_resolves_a_launcher_symlink() {
+ let root = tempfile::tempdir().unwrap();
+ let libexec = root.path().join("libexec");
+ let bin = root.path().join("bin");
+ std::fs::create_dir_all(&libexec).unwrap();
+ std::fs::create_dir_all(&bin).unwrap();
+ std::fs::write(libexec.join("prime-agent"), b"binary").unwrap();
+ let launcher = bin.join("prime-agent");
+ std::os::unix::fs::symlink(libexec.join("prime-agent"), &launcher).unwrap();
+ let real = libexec.join("prime-agent");
+ assert_eq!(exe_dir_of(&launcher), Some(libexec.clone()));
+ assert_eq!(exe_dir_of(&real), Some(libexec));
+}
diff --git a/crates/pa-core/src/update/homebrew.rs b/crates/pa-core/src/update/homebrew.rs
new file mode 100644
index 0000000000..271f13bcd8
--- /dev/null
+++ b/crates/pa-core/src/update/homebrew.rs
@@ -0,0 +1,106 @@
+//! Detect Homebrew-owned Prime Agent binaries before the installer update funnel.
+//! Homebrew links `<prefix>/bin/prime-agent` into a Cellar formula or a
+//! Caskroom cask: resolving the executable symlink is load-bearing because
+//! checking only the invoked `bin` path would miss both managed installs.
+
+use std::ffi::OsStr;
+use std::path::Path;
+
+/// The Homebrew package layout that owns the running binary.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum HomebrewKind {
+ /// A formula keg under `Cellar/prime-agent`.
+ Formula,
+ /// A cask version under `Caskroom/prime-agent`.
+ Cask,
+}
+
+impl HomebrewKind {
+ /// The fixed telemetry vocabulary for this Homebrew layout.
+ #[must_use]
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Formula => "formula",
+ Self::Cask => "cask",
+ }
+ }
+}
+
+/// Resolve the executable and identify a Homebrew-managed ancestor pair.
+/// Unresolvable paths and unrelated install layouts are not Homebrew-owned.
+#[must_use]
+pub fn managed_kind(executable: &Path) -> Option<HomebrewKind> {
+ let resolved = executable.canonicalize().ok()?;
+ for ancestor in resolved.ancestors() {
+ if ancestor.file_name() != Some(OsStr::new("prime-agent")) {
+ continue;
+ }
+ let owner = ancestor.parent().and_then(Path::file_name);
+ if owner == Some(OsStr::new("Cellar")) {
+ return Some(HomebrewKind::Formula);
+ }
+ if owner == Some(OsStr::new("Caskroom")) {
+ return Some(HomebrewKind::Cask);
+ }
+ }
+ None
+}
+
+/// The package-manager command to print instead of attempting self-update.
+#[must_use]
+pub fn upgrade_instruction(kind: HomebrewKind) -> String {
+ match kind {
+ HomebrewKind::Formula => "Update with: brew upgrade prime-agent".to_string(),
+ HomebrewKind::Cask => "Update with: brew upgrade --cask prime-agent".to_string(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn detects_formula_and_cask_layouts() {
+ let root = tempfile::tempdir().unwrap();
+ let formula = root
+ .path()
+ .join("Cellar/prime-agent/1.0.0/libexec/prime-agent");
+ let cask = root.path().join("Caskroom/prime-agent/1.0.0/prime-agent");
+ std::fs::create_dir_all(formula.parent().unwrap()).unwrap();
+ std::fs::create_dir_all(cask.parent().unwrap()).unwrap();
+ std::fs::write(&formula, b"binary").unwrap();
+ std::fs::write(&cask, b"binary").unwrap();
+ assert_eq!(managed_kind(&formula), Some(HomebrewKind::Formula));
+ assert_eq!(managed_kind(&cask), Some(HomebrewKind::Cask));
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn resolves_brew_bin_symlinks_into_the_formula_keg() {
+ let root = tempfile::tempdir().unwrap();
+ let formula = root
+ .path()
+ .join("Cellar/prime-agent/1.0.0/libexec/prime-agent");
+ let launcher = root.path().join("bin/prime-agent");
+ std::fs::create_dir_all(formula.parent().unwrap()).unwrap();
+ std::fs::create_dir_all(launcher.parent().unwrap()).unwrap();
+ std::fs::write(&formula, b"binary").unwrap();
+ std::os::unix::fs::symlink(&formula, &launcher).unwrap();
+ assert_eq!(managed_kind(&launcher), Some(HomebrewKind::Formula));
+ }
+
+ #[test]
+ fn ignores_other_kegs_and_non_homebrew_installs() {
+ let root = tempfile::tempdir().unwrap();
+ for path in [
+ "Cellar/other-tool/1.0.0/libexec/prime-agent",
+ "releases/1.0.0-darwin-arm64-abc123/prime-agent",
+ "plain/prime-agent",
+ ] {
+ let executable = root.path().join(path);
+ std::fs::create_dir_all(executable.parent().unwrap()).unwrap();
+ std::fs::write(&executable, b"binary").unwrap();
+ assert_eq!(managed_kind(&executable), None);
+ }
+ }
+}
diff --git a/crates/pa-core/src/update/mod.rs b/crates/pa-core/src/update/mod.rs
index 5de44ca175..1dab002018 100644
--- a/crates/pa-core/src/update/mod.rs
+++ b/crates/pa-core/src/update/mod.rs
@@ -8,9 +8,11 @@
//! channel's installer (never a GitHub raw or workflow URL) owns the whole
//! move, exec'd through the trusted absolute `/bin/sh` (never a
//! `PATH`-resolved interpreter), kept beside the staged flow the
-//! `package update` self target still serves.
+//! `package update` self target still serves. The `homebrew` detector
+//! lets CLI and TUI refuse package-manager installs before that funnel.
pub mod download;
+pub mod homebrew;
pub mod install;
pub mod installer;
pub mod release;
diff --git a/crates/pa-models/src/bundled.rs b/crates/pa-models/src/bundled.rs
index c8ce7b2b53..1978c21a95 100644
--- a/crates/pa-models/src/bundled.rs
+++ b/crates/pa-models/src/bundled.rs
@@ -23,7 +23,8 @@ pub struct BundledAssets {
impl BundledAssets {
/// The package directory: `PI_PACKAGE_DIR` when set (the wire-internal
- /// identifier, kept for TS parity), else the executable's directory.
+ /// identifier, kept for TS parity), else the executable's directory
+ /// (launcher symlinks resolve through [`exe_dir_of`]).
pub fn package_dir() -> PathBuf {
std::env::var_os("PI_PACKAGE_DIR")
.filter(|value| !value.is_empty())
@@ -31,7 +32,7 @@ impl BundledAssets {
|| {
std::env::current_exe()
.ok()
- .and_then(|exe| exe.parent().map(Path::to_path_buf))
+ .and_then(|exe| exe_dir_of(&exe))
.unwrap_or_default()
},
PathBuf::from,
@@ -102,11 +103,43 @@ pub fn load_bundled_models(asset: &str, templates: &PinnedTemplates) -> Option<V
Some(models)
}
+/// The directory beside the binary's real file: a launcher symlink (the
+/// Homebrew formula's `bin` link) must resolve, or the assets shipped
+/// beside the real binary are invisible; a plain path stays untouched
+/// (pa-core's package-dir lookups resolve the same way).
+fn exe_dir_of(exe: &Path) -> Option<PathBuf> {
+ let is_symlink =
+ std::fs::symlink_metadata(exe).is_ok_and(|metadata| metadata.file_type().is_symlink());
+ let resolved = if is_symlink {
+ exe.canonicalize().ok()?
+ } else {
+ exe.to_path_buf()
+ };
+ resolved.parent().map(Path::to_path_buf)
+}
+
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
+ #[cfg(unix)]
+ #[test]
+ fn a_launcher_symlink_resolves_to_the_real_payload_dir() {
+ let root = tempfile::tempdir().unwrap();
+ let libexec = root.path().join("libexec");
+ let bin = root.path().join("bin");
+ std::fs::create_dir_all(&libexec).unwrap();
+ std::fs::create_dir_all(&bin).unwrap();
+ std::fs::write(libexec.join("prime-agent"), b"binary").unwrap();
+ // The Homebrew formula layout: bin/prime-agent -> Cellar libexec.
+ let launcher = bin.join("prime-agent");
+ std::os::unix::fs::symlink(libexec.join("prime-agent"), &launcher).unwrap();
+ let real = libexec.join("prime-agent");
+ assert_eq!(exe_dir_of(&launcher), Some(libexec.clone()));
+ assert_eq!(exe_dir_of(&real), Some(libexec));
+ }
+
fn asset(models: impl AsRef<[serde_json::Value]>) -> String {
serde_json::to_string_pretty(&json!({"schemaVersion": 1, "models": models.as_ref()}))
.unwrap()
diff --git a/crates/pa-telemetry/src/catalog.rs b/crates/pa-telemetry/src/catalog.rs
index 7ff2f5f203..dc77b92671 100644
--- a/crates/pa-telemetry/src/catalog.rs
+++ b/crates/pa-telemetry/src/catalog.rs
@@ -1193,6 +1193,14 @@ const UPDATE_EVENTS: &[EventRule] = &[
("sessions_failed", optional(count())),
],
},
+ // The installer funnel refuses a Homebrew-owned executable before
+ // downloading or running the installer. `kind` is the package layout,
+ // never an executable path; invalid values normalize to `formula`.
+ EventRule {
+ name: "update_homebrew_refusal",
+ since: 2,
+ properties: &[("kind", required(enum_rule(&["formula", "cask"], "formula")))],
+ },
EventRule {
name: "update_aborted",
since: 1,
diff --git a/crates/pa-telemetry/src/events.rs b/crates/pa-telemetry/src/events.rs
index 66135b8ee3..b5decee9fc 100644
--- a/crates/pa-telemetry/src/events.rs
+++ b/crates/pa-telemetry/src/events.rs
@@ -212,6 +212,23 @@ impl AgentInstallationStage {
}
}
+/// `update_homebrew_refusal`: an installer update rejected because Homebrew
+/// owns the executable. Only the fixed formula/cask layout kind is recorded.
+#[derive(Debug, Clone, Copy)]
+pub struct UpdateHomebrewRefusal {
+ /// `formula` or `cask`; never the executable path.
+ pub kind: &'static str,
+}
+
+impl UpdateHomebrewRefusal {
+ /// Record this refusal on the shared lifecycle telemetry client.
+ pub fn track(&self, client: &TelemetryClient) {
+ let mut properties = Properties::new();
+ properties.set("kind", Value::from(self.kind));
+ client.track("update_homebrew_refusal", properties);
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/pa-telemetry/src/lib.rs b/crates/pa-telemetry/src/lib.rs
index 0da55ad29e..12b30307ed 100644
--- a/crates/pa-telemetry/src/lib.rs
+++ b/crates/pa-telemetry/src/lib.rs
@@ -60,6 +60,7 @@ pub use env::parse_bool_override;
pub use event::TelemetryEvent;
pub use events::{
AgentInstallationStage, AgentStartupStage, OnboardingStage, RunTrigger, ToolCategory,
+ UpdateHomebrewRefusal,
};
pub use install_id::{existing_install_id, install_id};
pub use platform::{base_properties, SCHEMA_VERSION};
diff --git a/packaging/homebrew/Formula/prime-agent.rb b/packaging/homebrew/Formula/prime-agent.rb
index f1c6b589d8..785342ed2a 100644
--- a/packaging/homebrew/Formula/prime-agent.rb
+++ b/packaging/homebrew/Formula/prime-agent.rb
@@ -1,17 +1,44 @@
-# Homebrew formula sketch for Prime Agent (Rust rewrite).
+# Homebrew formula candidate for prime-agent v1.0.0 (the Rust port).
#
-# Alternative to the cask (packaging/homebrew/Casks/prime-agent.rb): kept per the
-# design review so `brew install` can manage the one runtime dependency (uv) if
-# the operator ever prefers a formula channel.
+# Context: this supersedes Homebrew/homebrew-core#297372, the node-based
+# formula for the TypeScript product. The Rust port is distributed as a
+# source tarball (prime-agent-<version>-src.tar.gz: the git tree at the tag
+# plus the bundled catalog assets at the archive root — see
+# scripts/release/assemble_source.py and the assemble step in
+# .github/workflows/release.yml), which this formula builds with cargo.
+# The cask sketch next door (packaging/homebrew/Casks/prime-agent.rb) is
+# the vendor-tap alternative (prebuilt binaries) and stays untouched.
+#
+# Submission note: the sha256 below is a placeholder, filled from the
+# v1.0.0 release's SHA256SUMS when the tag publishes.
class PrimeAgent < Formula
- version "0.1.0"
- desc "RLM agent harness"
- homepage "https://github.com/kevinjosethomas/prime-agent-rs"
+ desc "Coding agent harness with a persistent Python control environment"
+ homepage "https://github.com/PrimeIntellect-ai/prime-agent"
+ url "https://github.com/PrimeIntellect-ai/prime-agent/releases/download/v1.0.0/prime-agent-1.0.0-src.tar.gz"
+ # TODO: replace with the v1.0.0 src-tarball sha256 from the release SHA256SUMS
+ sha256 "0000000000000000000000000000000000000000000000000000000000000000"
+ license "MIT"
+
+ livecheck do
+ url "https://github.com/PrimeIntellect-ai/prime-agent/releases/latest"
+ # Stable releases only: the beta cuts (-beta.N) build no source tarball.
+ regex(/prime-agent-v?(\d+(?:\.\d+)+)-src\.tar\.gz/i)
+ end
- depends_on "uv" => :recommended # kernel venv bootstrapping (binary looks for uv on PATH)
+ depends_on "rust" => :build
+ # The binary bootstraps its kernel venv through uv whenever one must be
+ # created or refreshed, so it is a hard runtime dependency.
+ depends_on "uv"
def install
- libexec.install Dir["*"]
+ system "cargo", "build", "--release", "--locked"
+ # The shipped payload set (assemble_artifacts.py STAGED_ENTRIES): the
+ # binary plus the kernel runtime, skills, and the bundled catalog
+ # assets it resolves beside its executable.
+ libexec.install "target/release/prime-agent"
+ libexec.install "prime-agent-runtime", "skills"
+ libexec.install "models.bundled.json", "mcp-services.bundled.json"
+ libexec.install "LICENSE", "README.md"
bin.install_symlink libexec/"prime-agent"
end
diff --git a/scripts/release/assemble_source.py b/scripts/release/assemble_source.py
new file mode 100644
index 0000000000..b4cc5faf2b
--- /dev/null
+++ b/scripts/release/assemble_source.py
@@ -0,0 +1,283 @@
+#!/usr/bin/env python3
+"""Assemble the prime-agent source tarball (the homebrew-core build input).
+
+Homebrew-core builds formulas from source, so the homebrew-core submission
+candidate pins a release source tarball rather than a prebuilt archive:
+`prime-agent-<version>-src.tar.gz`, assembled here from the repo tree at
+HEAD (`git archive`) with the two validated bundled catalog assets copied
+into the tarball root. The content contract mirrors the binary tarballs
+(assemble_artifacts.py): the shipped binary payloads stage
+models.bundled.json + mcp-services.bundled.json at the archive root, and
+the formula installs the same assets beside the built binary, so source
+and binary distributions carry one identical payload layout.
+
+Usage:
+ python3 scripts/release/assemble_source.py \
+ --repo-root <repo> --version <x.y.z> --out-dir <dir> \
+ --catalog-assets <dir>
+
+`--catalog-assets` is the directory holding the generated bundled catalog
+assets (models.bundled.json + mcp-services.bundled.json); the packer
+hard-fails without VALIDATED assets (version gates + >= 42 transport
+tuples + >= 68 services — see scripts/release/bundle_catalog.py, the
+catalog spec §3.2 no-cold-start layer 2), exactly like assemble_artifacts.
+CI generates them from the fixture snapshot per build job; offline runs use
+`bundle_catalog.py generate --fixture`.
+
+`--version` must be a BARE semver (no prerelease/continuous suffix). The
+homebrew-core candidate pins a stable release, the betas publish the
+nightly channel, and the release workflow gates this step to stable tags,
+so anything but `x.y.z` hard-fails.
+
+Also written into --out-dir:
+ SHA256SUMS the one-row checksum for the source tarball
+ ("<sha256> prime-agent-<version>-src.tar.gz"), merging into
+ the promote job's combined SHA256SUMS like a build job's
+ rows;
+ manifest.json EXACTLY {"version": "v<x.y.z>", "binaries": []}. The
+ promote job's merge step reads every artifact dir's
+ manifest.json and extends its binaries list; the empty
+ list is a no-op there, and the src tarball must NOT appear
+ as a binaries row because the channel-manifest
+ completeness gate asserts the platform set of the update
+ channel (a source row would also fail its per-platform
+ file-name shape).
+
+Determinism: the archive is packed through Python's tarfile with member
+metadata pinned (mtime 0, uid/gid 0, uname/gname root, dirs 0755, plain
+files 0644 or 0755 by the git tree's exec bit) and gzip mtime 0, the same
+discipline as assemble_artifacts.pack_tarball, so two assemblies of the
+same commit produce byte-identical archives. The staged content is the
+committed tree (`git archive`), so a dirty worktree never leaks into the
+tarball, and the packed modes derive from the git tree's exec bits — a host
+umask (extraction or catalog-asset copy) cannot shift them.
+"""
+
+from __future__ import annotations
+
+import argparse
+import gzip
+import io
+import json
+import os
+import re
+import shutil
+import subprocess
+import tarfile
+import tempfile
+from pathlib import Path
+
+# The same release-scripts directory: the helpers this assembler reuses
+# (fail/sha256_file) and the bundled-catalog gate, exactly the way
+# assemble_artifacts.py imports bundle_catalog.
+from assemble_artifacts import (
+ BUNDLED_CATALOG_FILES,
+ fail,
+ sha256_file,
+ validate_bundled_catalog_dir,
+)
+
+# A BARE stable semver only. assemble_artifacts.VERSION_RE accepts the
+# prerelease/continuous suffixes the binary packer stamps (beta tags,
+# continuous builds); the source tarball pins a stable release, so any
+# suffix hard-fails here (the release workflow gates the assemble step to
+# stable tags; this validation keeps the script itself honest).
+BARE_VERSION_RE = re.compile(r"^\d+\.\d+\.\d+$")
+
+# The tagged tree must build the formula's install set: the workspace
+# (Cargo.toml/Cargo.lock/crates), the crossterm patch (vendor/), and the
+# shipped payload the formula installs beside the binary
+# (assemble_artifacts.STAGED_ENTRIES minus the binary itself, plus the
+# catalog assets staged below). A tree that lost any of these builds a
+# formula that cannot compile or install — fail the release, not the tap.
+REQUIRED_TREE_ENTRIES = (
+ "Cargo.toml",
+ "Cargo.lock",
+ "crates",
+ "vendor",
+ "prime-agent-runtime",
+ "skills",
+ "LICENSE",
+ "README.md",
+)
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--repo-root", required=True, type=Path)
+ parser.add_argument("--version", required=True)
+ parser.add_argument("--out-dir", required=True, type=Path)
+ parser.add_argument("--catalog-assets", required=True, type=Path,
+ help="directory with models.bundled.json + "
+ "mcp-services.bundled.json (see "
+ "scripts/release/bundle_catalog.py)")
+ return parser.parse_args()
+
+
+def validate_version(version: str) -> None:
+ if not BARE_VERSION_RE.match(version):
+ fail(
+ f"invalid version {version!r} (source tarballs are cut only for "
+ "bare stable semver like 1.0.0; prerelease, beta, and "
+ "continuous suffixes build no source artifact)"
+ )
+
+
+def export_tree(repo_root: Path, staging: Path) -> None:
+ """Extract the git tree at HEAD into `staging` (`git archive`).
+
+ The archive is the COMMITTED tree, so a dirty worktree never leaks
+ into the tarball. Extraction is member-by-member (the
+ restamp_continuous.unpack_archive discipline: plain files and
+ directories only, every member inside `staging`) because a git tree
+ with a link or a submodule would need link-aware packing this
+ assembler deliberately does not implement — fail loudly instead.
+ """
+ result = subprocess.run(
+ ["git", "-C", str(repo_root), "archive", "--format=tar", "HEAD"],
+ capture_output=True,
+ )
+ if result.returncode != 0:
+ message = result.stderr.decode(errors="replace").strip()
+ fail(f"git archive HEAD failed in {repo_root}: {message}")
+ with tarfile.open(fileobj=io.BytesIO(result.stdout), mode="r:") as archive:
+ for member in archive.getmembers():
+ if member.name.startswith("/") or ".." in Path(member.name).parts:
+ fail(f"git archive carries an escaping member {member.name!r}")
+ target = staging / member.name
+ if member.isdir():
+ target.mkdir(parents=True, exist_ok=True)
+ elif member.isfile():
+ target.parent.mkdir(parents=True, exist_ok=True)
+ source = archive.extractfile(member)
+ assert source is not None
+ with source, open(target, "wb") as sink:
+ shutil.copyfileobj(source, sink)
+ # The committed mode exactly (git stores 0755/0644), so a
+ # host umask cannot strip the tree's exec bits.
+ os.chmod(target, member.mode)
+ else:
+ fail(
+ f"git tree member {member.name!r} is not a plain file "
+ "or directory; the source payload must be a plain tree"
+ )
+
+
+def stage_catalog_assets(staging: Path, catalog_assets: Path) -> dict:
+ """Validate both bundled assets and copy them into the staging root.
+
+ The same release gate as assemble_artifacts.stage_tree: the packer
+ FAILS without VALIDATED assets (spec §3.9), and the assets sit at the
+ tarball root so the formula (and the binary payloads) resolve them
+ beside the installed package.
+ """
+ facts = validate_bundled_catalog_dir(catalog_assets)
+ for name in BUNDLED_CATALOG_FILES:
+ shutil.copyfile(catalog_assets / name, staging / name)
+ return facts
+
+
+def check_required_tree(staging: Path) -> None:
+ missing = [name for name in REQUIRED_TREE_ENTRIES
+ if not (staging / name).exists()]
+ if missing:
+ fail(
+ "the tagged tree is missing the formula build/install inputs: "
+ + ", ".join(missing)
+ )
+
+
+def _deterministic_source_member(member: tarfile.TarInfo) -> tarfile.TarInfo:
+ """tarfile `filter`: fixed mtime/owner, deterministic modes, no links.
+
+ The assemble_artifacts._deterministic_member discipline, except the
+ source tree keeps the git tree's exec bit (a source tarball must
+ round-trip the tagged tree, and stripping the bit would mutate the
+ test scripts and installers a formula patch or an auditor might run):
+ directories 0755, executables 0755, everything else 0644. Deriving
+ the mode from the exec bit (not the staged file mode) keeps the packed
+ archive umask-independent.
+ """
+ if member.issym() or member.islnk():
+ raise ValueError(
+ f"tarball payload contains a link entry {member.name!r}; "
+ "the source payload must be plain files and directories"
+ )
+ member.uid = 0
+ member.gid = 0
+ member.uname = "root"
+ member.gname = "root"
+ member.mtime = 0
+ if member.isdir():
+ member.mode = 0o755
+ else:
+ member.mode = 0o755 if member.mode & 0o111 else 0o644
+ return member
+
+
+def pack_source_tarball(staging: Path, out_path: Path) -> None:
+ """Deterministic tar.gz of the whole staging tree, files at the root.
+
+ The pack mirrors assemble_artifacts.pack_tarball over the staging
+ directory's full sorted top-level entry list (tarfile's recursive add
+ walks each directory in sorted order): pinned member metadata, PAX
+ format, gzip mtime 0, so two assemblies of the same commit are
+ byte-identical.
+ """
+ staging_abs = staging.resolve()
+ entries = sorted(path.name for path in staging_abs.iterdir())
+ try:
+ with open(out_path, "wb") as raw, \
+ gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0) as gz, \
+ tarfile.open(fileobj=gz, mode="w", format=tarfile.PAX_FORMAT) as archive:
+ for name in entries:
+ path = staging_abs / name
+ if path.is_dir():
+ archive.add(path, arcname=name, recursive=True,
+ filter=_deterministic_source_member)
+ else:
+ archive.add(path, arcname=name, recursive=False,
+ filter=_deterministic_source_member)
+ except ValueError as error:
+ out_path.unlink(missing_ok=True)
+ fail(str(error))
+
+
+def main() -> int:
+ args = parse_args()
+ validate_version(args.version)
+ out_dir = args.out_dir.resolve()
+ out_dir.mkdir(parents=True, exist_ok=True)
+ staging = Path(tempfile.mkdtemp(prefix="prime-agent-source-"))
+ try:
+ export_tree(args.repo_root, staging)
+ catalog_facts = stage_catalog_assets(staging, args.catalog_assets)
+ check_required_tree(staging)
+ archive_name = f"prime-agent-{args.version}-src.tar.gz"
+ archive_path = out_dir / archive_name
+ pack_source_tarball(staging, archive_path)
+ archive_sha256 = sha256_file(archive_path)
+ finally:
+ shutil.rmtree(staging, ignore_errors=True)
+
+ print(f"bundled catalog assets: {json.dumps(catalog_facts)}")
+
+ # The one-row checksum the promote job's merge collects alongside every
+ # build job's rows; the empty-binaries manifest keeps the src tarball
+ # out of the channel manifest's platform set (see the module docstring).
+ (out_dir / "SHA256SUMS").write_text(
+ f"{archive_sha256} {archive_name}\n", encoding="utf-8")
+ (out_dir / "manifest.json").write_text(
+ json.dumps({"version": f"v{args.version}", "binaries": []}, indent=2)
+ + "\n", encoding="utf-8")
+
+ print(json.dumps({
+ "version": f"v{args.version}",
+ "file": archive_name,
+ "sha256": archive_sha256,
+ }, indent=2))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/release/verify_decoders.py b/scripts/release/verify_decoders.py
index 5d8e75fd1a..2bde724f6c 100644
--- a/scripts/release/verify_decoders.py
+++ b/scripts/release/verify_decoders.py
@@ -39,6 +39,13 @@ def verify(incoming):
for directory in directories:
manifest = json.loads((directory / "manifest.json").read_text())
binaries = manifest["binaries"]
+ # The source-artifact dir (artifacts-source: the homebrew-core
+ # candidate's src tarball) carries an EMPTY binaries list by
+ # contract — it is a per-release set, not a per-target build, so
+ # the decoder/binary shape checks below do not apply. Its tarball
+ # still rides hash continuity and the merged SHA256SUMS.
+ if not binaries:
+ continue
check(len(binaries) == 1, f"{directory}: expected one binary per target")
binary = binaries[0]
target = binary["target"]