ππΌββοΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.
Rust adeai-agentsclaudeclaude-codecodexcursorgeminigrokopencodespec-driven-developmentvibe-codingvim
feat: release notice and `agtx update` (#139)
Fynn Fluegge69def487d7c8
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 78b41e2..858c8cf 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -33,6 +33,18 @@ jobs:steps:- uses: actions/checkout@v4+ # The released binary reports env!("CARGO_PKG_VERSION"), and `agtx update`+ # compares it against the tag. A tag pushed without the manifest bump would+ # ship a binary that lies about its own version, so fail here instead.+ - name: Tag matches Cargo.toml+ shell: bash+ run: |+ MANIFEST=$(sed -n 's/^version = "\(.*\)"$/\1/p' Cargo.toml | head -1)+ if [ "v$MANIFEST" != "${{ github.ref_name }}" ]; then+ echo "tag ${{ github.ref_name }} != Cargo.toml v$MANIFEST"+ exit 1+ fi+- name: Install Rustuses: dtolnay/rust-toolchain@stablewith:@@ -56,12 +68,20 @@ jobs:cd target/${{ matrix.target }}/releasetar -czvf ../../../${{ matrix.archive }} agtxcd ../../..+ # install.sh and `agtx update` both fetch <archive>.sha256 and verify it.+ if command -v sha256sum > /dev/null; then+ sha256sum ${{ matrix.archive }} > ${{ matrix.archive }}.sha256+ else+ shasum -a 256 ${{ matrix.archive }} > ${{ matrix.archive }}.sha256+ fi- name: Upload artifactuses: actions/upload-artifact@v4with:name: ${{ matrix.archive }}- path: ${{ matrix.archive }}+ path: |+ ${{ matrix.archive }}+ ${{ matrix.archive }}.sha256release:name: Create Release@@ -85,7 +105,9 @@ jobs:- name: Create Releaseuses: softprops/action-gh-release@v2with:- files: artifacts/*.tar.gz+ files: |+ artifacts/*.tar.gz+ artifacts/*.sha256generate_release_notes: truedraft: falseprerelease: ${{ contains(github.ref_name, '-') }}diff --git a/CLAUDE.md b/CLAUDE.mdindex ed3dad3..0932dab 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -28,6 +28,10 @@ cargo build --release# Record an agent lifecycle event (invoked by agent hooks, not by hand)./target/release/agtx hook <task-id> <worktree> [agent] < payload.json++# Version, and self-update to the latest GitHub release+./target/release/agtx --version+./target/release/agtx update [--check]```Logs are written as JSON to `~/.config/agtx/logs/agtx.log` (daily rotation, `RUST_LOG` respected).@@ -70,6 +74,13 @@ src/βββ mcp/β βββ mod.rs # Re-exportsβ βββ server.rs # MCP server (JSON-RPC over stdio) β global and project-scoped modes+βββ update/+β βββ mod.rs # check_for_update() β the whole background check+β βββ version.rs # Semver-lite parse/compare + the prerelease policy (pure)+β βββ check.rs # Cache TTL, should_check, available (pure but for the file)+β βββ github.rs # releases/latest over curl+β βββ release.rs # Repo slug + archive naming, shared with install.sh/release.yml+β βββ install.rs # Download, verify sha256, atomic in-place binary swapβββ config/βββ mod.rs # GlobalConfig, ProjectConfig, MergedConfig, PhaseAgentsConfig,# WorktreeConfig, ThemeConfig, WorkflowPlugin, TrustStore@@ -115,6 +126,7 @@ tests/βββ agent_parity_tests.rs # Per-agent behaviour lock (launch/resume/skill paths/syntax)βββ hook_status_tests.rs # Agent lifecycle-hook status reportingβββ mcp_tests.rs # MCP server tests+βββ update_tests.rs # Version policy, cache TTL, artifact naming parity, binary swapβββ mock_infrastructure_tests.rs # Mock infrastructure testsβββ shell_popup_tests.rs # Shell popup logic testsβββ smoke/ # Per-agent smoke tests β real binaries, no mocks, opt-in@@ -314,6 +326,63 @@ phase transition gets to have. Same reasoning as never choosing codex's "Update- Resume from Review simply changes status back to Running (window already exists)- No special resume logic needed - the session just stays alive in tmux+### Self-Update+agtx tells the user when a newer release exists and replaces its own binary on request.++```+ startup βββΊ background thread βββΊ curl api.github.com/β¦/releases/latest+ β β+ β cache 24h β ~/.config/agtx/update.json+ βΌ+ mpsc::Receiver βββΊ event loop try_recv βββΊ header: "β¬ 0.2.8 [u]"+ β+ [u] popup βββΊ install_release()+```++- **The binary must know its own version.** `env!("CARGO_PKG_VERSION")` is the only source, and+ `release.yml`'s *Tag matches Cargo.toml* step fails the build when the pushed tag disagrees with+ the manifest. Before this existed the tags had reached `v0.2.7` while `Cargo.toml` still said+ `0.1.0` β a released binary could not answer the question every part of this feature compares+ against+- `--version` / `-V` / `version` and `update` are handled in the **early fast path** in `main.rs`,+ beside the `hook` arm, for two reasons: neither wants a daily log appender built for it, and the+ `mode` match below filters out every `--`-prefixed argument, so `--version` would otherwise fall+ through and open the current directory as a project+- **The cache is not an optimisation.** Unauthenticated GitHub allows 60 requests/hour *per IP* and+ agtx is launched dozens of times a day across project directories. 24h TTL; a stale cache is still+ served when the network is down, because a week-old "0.2.8 is out" is still true+- **Cache path gotcha:** built from `GlobalConfig::config_path()`'s parent, **not** `directories`'+ `config_dir()` β see the config-path split under *Database Storage*. The latter would put it in+ `~/Library/Application Support/` on macOS, away from the `config.toml` and `logs/` it belongs with+- **`curl`, not an HTTP crate.** One GET per day does not justify adding a TLS stack to a binary+ that has none; `curl` is already required by `install.sh`, and it honours `HTTPS_PROXY`/`NO_PROXY`+ and the system CA store, which is what corporate networks need. `src/update/github.rs` is the only+ file that would change if that stops being true+- **Failure is always a missing notice**, never an error: no network, no `curl`, a rate-limit body,+ an unparseable tag β all yield "no update". A version check must not be able to make the TUI shout+- **The swap** is `rename(target, target.old)` β `rename(new, target)` β unlink, staged inside the+ *target's own directory* so the rename is same-filesystem (`/tmp` often is not). Renaming over a+ running binary is legal on Unix β `ETXTBSY` applies to writing into the busy inode, not to+ replacing the directory entry. The `.old` step means a failure between the two renames leaves a+ recoverable file rather than no `agtx` at all+- **Replacing in place is what keeps worktrees valid.** The absolute `agtx` path is baked into every+ worktree's hook command and MCP configs (*Binary-path drift* below); an in-place swap keeps that+ path identical, so nothing needs re-deploying. Installing to a new location would invalidate every+ existing worktree+- **A package-managed binary is refused**, not overwritten: `/nix/store/β¦` and Homebrew prefixes get+ the right command for that manager instead. Silently replacing a file a manager believes it owns+ breaks the machine in a way that is hard to diagnose later+- **Never automatic.** agtx already refuses to answer codex's "Update now" dialog on the principle+ that it must not upgrade an agent binary behind the user's back; swapping its own would be+ incoherent. Two opt-outs for the *check*: `update_check = false` and `AGTX_NO_UPDATE_CHECK=1`+ (set in `docker/Dockerfile`, and what CI and the smoke runner should use)+- **Three files must agree on artifact naming** β `src/update/release.rs`, `install.sh` and+ `release.yml` β or `agtx update` 404s. `tests/update_tests.rs` greps the other two and asserts the+ match, because the alternative is finding the drift in a user's failed update+- `release.yml` publishes `<archive>.sha256` alongside each tarball. `install.sh` had fetched and+ verified them since it was written, but none were ever published, so its verification had never+ once run+### Database StorageAll databases stored centrally (not in project directories), in the platform data dir (`GlobalConfig::data_dir`, via the `directories` crate):- macOS: `~/Library/Application Support/agtx/`@@ -407,6 +476,7 @@ default_agent = "claude"fullscreen_on_enter = false # When true, Enter on a task attaches to tmux directly instead of opening the in-TUI popupagent_hooks = true # Write agent lifecycle-hook configs into worktrees (see Hook-Based Phase Status)auto_trust = false # Answer agents' trust / bypass-permission prompts by reading the pane (see First-Launch Dialogs)+update_check = true # Daily GitHub release check + header notice (see Self-Update)[agents] # Per-phase agent overrides (PhaseAgentsConfig)research = "claude"@@ -482,6 +552,7 @@ color_popup_header = "#69fae7" # Popup headers (light cyan)| `p` | Cyclic plugins only: Review β Planning (next phase) || `/` | Search tasks (jumps to and opens task) || `P` | Select workflow plugin |+| `u` | Update agtx (only bound when a newer release was found) || `O` | Toggle orchestrator agent (experimental) || `e` | Toggle project sidebar (`h`/`Left` from the Backlog column focuses it) || `q` | Quit |diff --git a/Cargo.lock b/Cargo.lockindex c7a62b4..efed45c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4,7 +4,7 @@ version = 4[[package]]name = "agtx"-version = "0.1.0"+version = "1.0.0"dependencies = ["anyhow","chrono",diff --git a/Cargo.toml b/Cargo.tomlindex 362fcc7..3916093 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,11 +1,11 @@[package]name = "agtx"-version = "0.1.0"+version = "1.0.0"edition = "2021"description = "Terminal-native kanban board for managing coding agents"authors = ["agtx contributors"]license = "MIT"-repository = "https://github.com/yourusername/agtx"+repository = "https://github.com/fynnfluegge/agtx"keywords = ["tui", "tmux", "agents", "kanban", "claude"]categories = ["command-line-utilities", "development-tools"]diff --git a/README.md b/README.mdindex 8f10795..640be3a 100644--- a/README.md+++ b/README.md@@ -100,6 +100,30 @@ cargo build --releasecp target/release/agtx ~/.local/bin/```+### Updating++agtx checks GitHub once a day for a newer release and shows `β¬ 0.2.8 [u]` in the+board header when there is one. Press **`u`** for the details and one key to+install it, or from a shell:++```bash+agtx update # download, verify and replace this binary in place+agtx update --check # report only; exits 1 when an update is available+agtx --version+```++The running agtx keeps the old binary until you restart it; open tmux sessions+and their agents are untouched.++To never check, set `update_check = false` in `~/.config/agtx/config.toml`, or+export `AGTX_NO_UPDATE_CHECK=1` for a single run (CI, containers). To pin or roll+back to a specific release, re-run the installer with `AGTX_VERSION`:++```bash+curl -fsSL https://raw.githubusercontent.com/fynnfluegge/agtx/main/install.sh \+ | AGTX_VERSION=v0.2.6 bash+```+### Requirements- **tmux** β agent sessions run in a dedicated tmux server@@ -156,6 +180,7 @@ reason, and you answer it in the agent's own pane (`β©` to open the task).| `x` | Delete task || `/` | Search tasks || `P` | Select spec-driven workflow plugin |+| `u` | Update agtx (only shown when a new release is available) || `O` | Toggle orchestrator agent (`--experimental`) || `e` | Toggle project sidebar || `q` | Quit |@@ -317,6 +342,16 @@ Register `agtx mcp-serve` as an MCP server, then copy `skills/sweep/SKILL.md` inConfig file location: `~/.config/agtx/config.toml`+### General++```toml+default_agent = "claude"+fullscreen_on_enter = false # Enter attaches to tmux directly instead of the in-TUI popup+agent_hooks = true # Let agents report their own phase status via lifecycle hooks+auto_trust = false # Answer agents' trust prompts on your behalf+update_check = true # Check GitHub daily for a new release (see Updating)+```+### Worktree Base Branchagtx creates a new git worktree for each task. By default it auto-detects the base branch in thisdiff --git a/docker/Dockerfile b/docker/Dockerfileindex 7e27922..bb45201 100644--- a/docker/Dockerfile+++ b/docker/Dockerfile@@ -18,6 +18,11 @@ RUN npm install -g @anthropic-ai/claude-codeRUN curl -fsSL https://raw.githubusercontent.com/fynnfluegge/agtx/main/install.sh \| AGTX_INSTALL_DIR=/usr/local/bin bash+# The container's agtx is baked into the image; a release-check notice inside it+# would point at an update the user cannot apply from here, and every container+# start would spend a request against the shared-IP GitHub rate limit.+ENV AGTX_NO_UPDATE_CHECK=1+# Non-root user β UID/GID match the host user so bind-mounted files stay correctly ownedARG UID=1000ARG GID=1000diff --git a/install.sh b/install.shindex 0403b3d..85e9611 100644--- a/install.sh+++ b/install.sh@@ -78,15 +78,21 @@ main() {error "curl is required but not installed"fi- # Get latest version- info "Fetching latest version..."- VERSION=$(get_latest_version)+ # Version: AGTX_VERSION pins one (e.g. AGTX_VERSION=v0.2.6), which is the+ # downgrade path when a release goes wrong. Otherwise take the latest.+ if [ -n "${AGTX_VERSION:-}" ]; then+ VERSION="${AGTX_VERSION}"+ info "Pinned version: ${VERSION}"+ else+ info "Fetching latest version..."+ VERSION=$(get_latest_version)- if [ -z "$VERSION" ]; then- error "Could not determine latest version. Check https://github.com/${REPO}/releases"- fi+ if [ -z "$VERSION" ]; then+ error "Could not determine latest version. Check https://github.com/${REPO}/releases"+ fi- info "Latest version: ${VERSION}"+ info "Latest version: ${VERSION}"+ fi# Construct download URLARCHIVE_NAME="${BINARY_NAME}-${VERSION}-${ARCH}-${OS}.tar.gz"diff --git a/src/config/mod.rs b/src/config/mod.rsindex f77f973..50f195e 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -48,6 +48,16 @@ pub struct GlobalConfig {/// user already gave the project (see `agent::trust`).#[serde(default)]pub auto_trust: bool,++ /// Check GitHub once a day for a newer agtx release and show a notice in+ /// the header. Set false to never ask; `AGTX_NO_UPDATE_CHECK=1` is the+ /// per-invocation equivalent, for CI and containers.+ #[serde(default = "default_update_check")]+ pub update_check: bool,+}++fn default_update_check() -> bool {+ true}fn default_agent_hooks() -> bool {@@ -64,6 +74,7 @@ impl Default for GlobalConfig {fullscreen_on_enter: false,agent_hooks: default_agent_hooks(),auto_trust: false,+ update_check: default_update_check(),}}}@@ -400,6 +411,9 @@ pub struct MergedConfig {pub branch_prefix: String,pub agent_hooks: bool,pub auto_trust: bool,+ /// Global-only: a project does not get to decide whether the user is told+ /// about agtx releases.+ pub update_check: bool,}impl MergedConfig {@@ -437,6 +451,7 @@ impl MergedConfig {fullscreen_on_enter: global.fullscreen_on_enter,agent_hooks: global.agent_hooks,auto_trust: global.auto_trust,+ update_check: global.update_check,branch_prefix: project.branch_prefix.clone()diff --git a/src/lib.rs b/src/lib.rsindex 827746f..cb71812 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -6,6 +6,7 @@ pub mod mcp;pub mod skills;pub mod tmux;pub mod tui;+pub mod update;use std::path::PathBuf;diff --git a/src/main.rs b/src/main.rsindex 0b830dd..5bbb5d1 100644--- a/src/main.rs+++ b/src/main.rs@@ -3,7 +3,7 @@ use agtx::{config::{self, GlobalConfig},git, tui, AppMode, FeatureFlags,};-use anyhow::Result;+use anyhow::{Context, Result};use crossterm::{cursor,event::{self, Event, KeyCode},@@ -24,6 +24,19 @@ async fn main() -> Result<()> {if raw.get(1).map(String::as_str) == Some("hook") {return agtx::agent::hook_status::run_hook_cli(&raw[2..]);}+ // Same reasoning for the version/update commands: they print a line or+ // two and exit, and neither wants a daily log file created for it. They+ // are handled here rather than in the `mode` match below because that+ // match filters out every `--`-prefixed argument, so `--version` would+ // otherwise fall through and open the current directory as a project.+ match raw.get(1).map(String::as_str) {+ Some("--version" | "-V" | "version") => {+ println!("agtx {}", env!("CARGO_PKG_VERSION"));+ return Ok(());+ }+ Some("update") => return run_update(&raw[2..]),+ _ => {}+ }}// Initialize audit logging to ~/.config/agtx/logs/@@ -263,3 +276,46 @@ fn prompt_agent_selection(agents: &[agent::Agent]) -> Result<&agent::Agent> {println!("\n Selected: {}\n", agents[idx].name);Ok(&agents[idx])}++/// `agtx update [--check]`+///+/// The dedicated command the header notice points at. `--check` only reports,+/// and exits 1 when an update is available so it can drive a script.+fn run_update(args: &[String]) -> Result<()> {+ use agtx::update;++ let check_only = args.iter().any(|a| a == "--check");+ let current = update::Version::current();++ // Ask GitHub directly rather than going through the cached path: someone+ // typing `agtx update` wants the answer now, not yesterday's answer.+ let release = update::github::fetch_latest_release(&update::release::repo())+ .context("could not reach GitHub to check for a new release")?;+ let latest = update::Version::parse(&release.tag_name)+ .with_context(|| format!("unrecognised release tag: {}", release.tag_name))?;++ if !latest.supersedes(¤t) {+ println!("agtx {current} is up to date (latest release: {latest})");+ return Ok(());+ }++ println!(" current {current} β latest {latest}");+ if check_only {+ if !release.html_url.is_empty() {+ println!(" {}", release.html_url);+ }+ println!(" run `agtx update` to install it");+ std::process::exit(1);+ }++ let installed = update::install::install_release(&release.tag_name, &mut |step| {+ println!(" {step}");+ })?;++ println!();+ println!(" agtx {latest} installed to {}", installed.path.display());+ // The running process still holds the old inode; tmux sessions and their+ // agents are untouched. Say so rather than implying the swap took effect.+ println!(" restart any running agtx to pick it up");+ Ok(())+}diff --git a/src/tui/app.rs b/src/tui/app.rsindex d1393bd..98149a5 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -321,6 +321,15 @@ struct AppState {orchestrator_last_check: Instant,// Background session refresh channel (non-blocking phase status polling)session_refresh_rx: Option<mpsc::Receiver<SessionRefreshResult>>,+ // Release check: spawned once at startup, consumed non-blocking like the+ // session refresh above. `None` in the receiver means "no newer release" β+ // every failure (offline, no curl, rate limit) arrives that way too, so a+ // missing notice is the only symptom a broken check can have.+ update_rx: Option<mpsc::Receiver<Option<crate::update::UpdateInfo>>>,+ update_available: Option<crate::update::UpdateInfo>,+ // Update popup ([u]) and the background install it can start+ update_popup: Option<UpdatePopup>,+ update_install_rx: Option<mpsc::Receiver<Result<String, String>>>,// Cache of dependency satisfaction per task ID (refreshed with tasks)deps_satisfied_cache: HashMap<String, bool>,// Full-screen dependency-graph overlay (Shift+D)@@ -546,6 +555,17 @@ struct PluginSelectPopup {options: Vec<PluginOption>,}+/// The `[u]` popup: what is available, and one key to install it.+#[derive(Debug, Clone)]+struct UpdatePopup {+ info: crate::update::UpdateInfo,+ /// The last line `install_release` reported, or the final outcome. The+ /// install runs on a background thread; this is the only thing the draw+ /// path reads.+ status: Option<String>,+ installing: bool,+}+#[derive(Debug, Clone)]struct PluginOption {name: String, // "" for none, "gsd", "spec-kit", etc.@@ -731,6 +751,10 @@ impl App {orchestrator_stable_since: None,orchestrator_last_check: Instant::now(),session_refresh_rx: None,+ update_rx: None,+ update_available: None,+ update_popup: None,+ update_install_rx: None,deps_satisfied_cache: HashMap::new(),dep_graph_popup: None,setup_queue: VecDeque::new(),@@ -823,6 +847,17 @@ impl App {});}+ // Release check, on a background thread so a slow or hung network never+ // delays the first frame. Deliberately not in `new_for_test`: the test+ // suite must not make network calls.+ if crate::update::check::checks_enabled(app.state.config.update_check) {+ let (tx, rx) = mpsc::channel();+ app.state.update_rx = Some(rx);+ std::thread::spawn(move || {+ let _ = tx.send(crate::update::check_for_update().unwrap_or(None));+ });+ }+// Display trust confirmation popup if project config was suppressedif trust_warning.is_some() {if let Some(ref path) = app.state.project_path {@@ -940,6 +975,10 @@ impl App {orchestrator_stable_since: None,orchestrator_last_check: Instant::now(),session_refresh_rx: None,+ update_rx: None,+ update_available: None,+ update_popup: None,+ update_install_rx: None,deps_satisfied_cache: HashMap::new(),dep_graph_popup: None,setup_queue: VecDeque::new(),@@ -1055,6 +1094,44 @@ impl App {Err(std::sync::mpsc::TryRecvError::Empty) => {}}}+ // Release check result (arrives once, then the channel is dropped)+ if let Some(ref rx) = self.state.update_rx {+ match rx.try_recv() {+ Ok(info) => {+ self.state.update_rx = None;+ self.state.update_available = info;+ }+ Err(std::sync::mpsc::TryRecvError::Disconnected) => {+ self.state.update_rx = None;+ }+ Err(std::sync::mpsc::TryRecvError::Empty) => {}+ }+ }++ // Result of an install started from the update popup+ if let Some(ref rx) = self.state.update_install_rx {+ match rx.try_recv() {+ Ok(result) => {+ self.state.update_install_rx = None;+ if let Some(popup) = self.state.update_popup.as_mut() {+ popup.installing = false;+ popup.status = Some(match result {+ Ok(msg) => msg,+ Err(e) => format!("failed: {e}"),+ });+ }+ }+ Err(std::sync::mpsc::TryRecvError::Disconnected) => {+ self.state.update_install_rx = None;+ if let Some(popup) = self.state.update_popup.as_mut() {+ popup.installing = false;+ popup.status = Some("failed: the update thread stopped".to_string());+ }+ }+ Err(std::sync::mpsc::TryRecvError::Empty) => {}+ }+ }+// Spawn background refresh if not already running and cache expiredself.maybe_spawn_session_refresh();@@ -1146,6 +1223,19 @@ impl App {Style::default().fg(hex_to_color(&state.config.theme.color_dimmed)),));}+ if let Some(ref update) = state.update_available {+ // color_selected, not a warning color: this is an affordance, not a+ // fault. `[u]` is the discovery point β the footer is already dense+ // enough that another hint there would be lost.+ right_spans.push(Span::styled(+ format!("β¬ {} ", update.latest),+ Style::default().fg(hex_to_color(&state.config.theme.color_selected)),+ ));+ right_spans.push(Span::styled(+ "[u] ",+ Style::default().fg(hex_to_color(&state.config.theme.color_dimmed)),+ ));+ }right_spans.extend([Span::styled(format!("{} ", plugin_label),@@ -1157,7 +1247,9 @@ impl App {),]);let left_len = state.project_name.len() + 2;- let right_len: usize = right_spans.iter().map(|s| s.content.len()).sum();+ // Character count, not byte count: the update notice's "β¬" is 3 bytes+ // and one column, and a byte-based width would over-pad the header.+ let right_len: usize = right_spans.iter().map(|s| s.content.chars().count()).sum();let padding = (chunks[0].width as usize).saturating_sub(left_len + right_len + 2); // 2 for borderslet mut spans = vec![left, Span::raw(" ".repeat(padding))];spans.extend(right_spans);@@ -2177,6 +2269,64 @@ impl App {frame.render_widget(content, inner);}+ // Update popup ([u])+ if let Some(ref popup) = state.update_popup {+ let popup_area = centered_rect(60, 30, area);+ frame.render_widget(Clear, popup_area);++ let main_block = Block::default()+ .title(" Update Available ")+ .borders(Borders::ALL)+ .border_style(+ Style::default().fg(hex_to_color(&state.config.theme.color_popup_border)),+ );+ frame.render_widget(main_block, popup_area);++ let inner = popup_area.inner(ratatui::layout::Margin {+ horizontal: 2,+ vertical: 1,+ });++ let selected = hex_to_color(&state.config.theme.color_selected);+ let dimmed = hex_to_color(&state.config.theme.color_dimmed);+ let mut lines: Vec<Line> = vec![+ Line::from(""),+ Line::from(vec![+ Span::styled(" current ", Style::default().fg(dimmed)),+ Span::styled(popup.info.current.to_string(), Style::default()),+ Span::styled(" β latest ", Style::default().fg(dimmed)),+ Span::styled(+ popup.info.latest.to_string(),+ Style::default().fg(selected).add_modifier(Modifier::BOLD),+ ),+ ]),+ ];+ if !popup.info.html_url.is_empty() {+ lines.push(Line::from(""));+ lines.push(Line::from(Span::styled(+ format!(" {}", popup.info.html_url),+ Style::default().fg(dimmed),+ )));+ }+ lines.push(Line::from(""));+ match (&popup.status, popup.installing) {+ (Some(status), _) => lines.push(Line::from(Span::styled(+ format!(" {}", status),+ Style::default().fg(selected),+ ))),+ (None, true) => lines.push(Line::from(Span::styled(+ " installingβ¦",+ Style::default().fg(selected),+ ))),+ (None, false) => lines.push(Line::from(Span::styled(+ " [Enter] install [Esc] close",+ Style::default().fg(dimmed),+ ))),+ }+ let content = Paragraph::new(lines).wrap(Wrap { trim: false });+ frame.render_widget(content, inner);+ }+// Plugin selection popupif let Some(ref popup) = state.plugin_select_popup {let popup_area = centered_rect(50, 40, area);@@ -2855,6 +3005,18 @@ impl App {Style::default().fg(dimmed_color),)),];+ // A user in dashboard mode is between projects, which is the best+ // moment there is to be told. The logo block has exactly one spare row.+ let mut logo = logo;+ if let Some(ref update) = state.update_available {+ logo.push(Line::from(vec![+ Span::styled(+ format!("β¬ agtx {} available ", update.latest),+ Style::default().fg(selected_color),+ ),+ Span::styled("[u]", Style::default().fg(dimmed_color)),+ ]));+ }let logo_widget = Paragraph::new(logo).alignment(Alignment::Center);frame.render_widget(logo_widget, chunks[0]);@@ -2896,7 +3058,12 @@ impl App {}// Footer- let footer = Paragraph::new(" [p] projects [n] new project [q] quit ")+ let footer_text = if state.update_available.is_some() {+ " [p] projects [n] new project [u] update [q] quit "+ } else {+ " [p] projects [n] new project [q] quit "+ };+ let footer = Paragraph::new(footer_text).style(Style::default().fg(dimmed_color)).block(Block::default().borders(Borders::ALL));frame.render_widget(footer, chunks[2]);@@ -2936,6 +3103,11 @@ impl App {return self.handle_review_confirm_key(key);}+ // Handle update popup if open+ if self.state.update_popup.is_some() {+ return self.handle_update_popup_key(key);+ }+// Handle trust confirmation popup if openif self.state.trust_confirm_popup.is_some() {return self.handle_trust_confirm_key(key);@@ -3076,6 +3248,61 @@ impl App {Ok(())}+ fn open_update_popup(&mut self) {+ if let Some(info) = self.state.update_available.clone() {+ self.state.update_popup = Some(UpdatePopup {+ info,+ status: None,+ installing: false,+ });+ }+ }++ /// `[u]` popup: Enter installs, Esc closes.+ ///+ /// The install runs on a background thread β it downloads and verifies a+ /// tarball, which must not block the event loop β and reports through+ /// `update_install_rx` like every other background operation here.+ fn handle_update_popup_key(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {+ let Some(popup) = self.state.update_popup.as_mut() else {+ return Ok(());+ };+ // Ignore everything while the swap is in flight: a second Enter would+ // start a competing download into the same staging directory.+ if popup.installing {+ return Ok(());+ }+ match key.code {+ KeyCode::Esc | KeyCode::Char('q') => {+ self.state.update_popup = None;+ }+ KeyCode::Enter => {+ // Already finished (success or failure) β Enter closes.+ if popup.status.is_some() {+ self.state.update_popup = None;+ return Ok(());+ }+ let tag = popup.info.tag.clone();+ let latest = popup.info.latest.to_string();+ popup.installing = true;+ let (tx, rx) = mpsc::channel();+ self.state.update_install_rx = Some(rx);+ std::thread::spawn(move || {+ let result = crate::update::install::install_release(&tag, &mut |_| {})+ .map(|_| {+ // The running process still holds the old inode;+ // tmux sessions and their agents are untouched.+ format!("agtx {latest} installed β restart agtx to apply")+ })+ .map_err(|e| e.to_string());+ let _ = tx.send(result);+ });+ }+ _ => {}+ }+ Ok(())+ }+fn handle_trust_confirm_key(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {let _ = key;if let Some(popup) = self.state.trust_confirm_popup.clone() {@@ -3744,6 +3971,9 @@ impl App {KeyCode::Char('p') => {self.state.show_project_list = true;}+ KeyCode::Char('u') if self.state.update_available.is_some() => {+ self.open_update_popup();+ }KeyCode::Char('n') => {let current_dir = std::env::current_dir()?;if crate::git::is_git_repo(¤t_dir) {@@ -3925,6 +4155,9 @@ impl App {// Open plugin selection popupself.open_plugin_select_popup();}+ KeyCode::Char('u') if self.state.update_available.is_some() => {+ self.open_update_popup();+ }KeyCode::Char('O') if self.state.flags.experimental => {// Toggle orchestrator agent (experimental)self.toggle_orchestrator()?;diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rsindex a51112f..8989f2b 100644--- a/src/tui/app_tests.rs+++ b/src/tui/app_tests.rs@@ -12428,3 +12428,125 @@ fn test_submit_message_stops_once_the_pane_changes() {let ops: Arc<dyn TmuxOperations> = Arc::new(mock);submit_message(&ops, "t:1");}++// === Update notice ===++#[cfg(feature = "test-mocks")]+fn an_update() -> crate::update::UpdateInfo {+ crate::update::UpdateInfo {+ current: crate::update::Version::parse("0.2.7").unwrap(),+ latest: crate::update::Version::parse("0.2.8").unwrap(),+ tag: "v0.2.8".to_string(),+ html_url: "https://github.com/fynnfluegge/agtx/releases/tag/v0.2.8".to_string(),+ }+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_u_does_nothing_without_an_available_update() {+ // `u` is only a binding when there is something to install. Without the+ // guard it would swallow a keystroke the board may want later.+ let mut app = make_test_app();+ assert!(app.state.update_available.is_none());+ press_key(&mut app, KeyCode::Char('u'));+ assert!(app.state.update_popup.is_none());+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_u_opens_the_update_popup() {+ let mut app = make_test_app();+ app.state.update_available = Some(an_update());+ press_key(&mut app, KeyCode::Char('u'));++ let popup = app.state.update_popup.as_ref().expect("popup should open");+ assert_eq!(popup.info.tag, "v0.2.8");+ assert!(!popup.installing);+ assert!(popup.status.is_none());+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_esc_closes_the_update_popup() {+ let mut app = make_test_app();+ app.state.update_available = Some(an_update());+ press_key(&mut app, KeyCode::Char('u'));+ press_key(&mut app, KeyCode::Esc);+ assert!(app.state.update_popup.is_none());+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_keys_are_ignored_while_the_install_is_in_flight() {+ // A second Enter would start a competing download into the same staging+ // directory, and Esc would leave a thread writing into the binary the user+ // just walked away from.+ let mut app = make_test_app();+ app.state.update_available = Some(an_update());+ press_key(&mut app, KeyCode::Char('u'));+ app.state.update_popup.as_mut().unwrap().installing = true;++ press_key(&mut app, KeyCode::Esc);+ assert!(+ app.state.update_popup.is_some(),+ "Esc must not close mid-install"+ );+ press_key(&mut app, KeyCode::Enter);+ assert!(app.state.update_install_rx.is_none(), "no second download");+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_enter_closes_a_finished_popup_rather_than_reinstalling() {+ let mut app = make_test_app();+ app.state.update_available = Some(an_update());+ press_key(&mut app, KeyCode::Char('u'));+ app.state.update_popup.as_mut().unwrap().status =+ Some("agtx 0.2.8 installed β restart agtx to apply".to_string());++ press_key(&mut app, KeyCode::Enter);+ assert!(app.state.update_popup.is_none());+ assert!(app.state.update_install_rx.is_none());+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_board_and_popup_draw_with_an_update_available() {+ // The header notice adds a multi-byte span ("β¬") to the right-aligned+ // group, whose padding is computed from the span widths.+ let mut app = make_test_app();+ app.state.update_available = Some(an_update());+ assert!(app.draw().is_ok());++ press_key(&mut app, KeyCode::Char('u'));+ assert!(app.draw().is_ok());+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_dashboard_draws_with_an_update_available() {+ let mut app = App::new_for_test(+ None,+ Arc::new(MockTmuxOperations::new()),+ Arc::new(MockGitOperations::new()),+ Arc::new(MockGitProviderOperations::new()),+ Arc::new(MockAgentRegistry::new()),+ )+ .unwrap();+ app.state.update_available = Some(an_update());+ assert!(app.draw().is_ok());++ press_key(&mut app, KeyCode::Char('u'));+ assert!(app.state.update_popup.is_some());+ assert!(app.draw().is_ok());+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_no_release_check_runs_in_tests() {+ // `new_for_test` must never spawn the network thread β the suite runs+ // offline and in CI, and a check per constructed App would be both slow and+ // a live dependency on GitHub.+ let app = make_test_app();+ assert!(app.state.update_rx.is_none());+}diff --git a/src/update/check.rs b/src/update/check.rsnew file mode 100644index 0000000..0d48844--- /dev/null+++ b/src/update/check.rs@@ -0,0 +1,109 @@+//! When to ask GitHub, and what to do with the answer.+//!+//! Pure except for the two functions that touch the cache file. `now` is always+//! an argument, never `Utc::now()`, so the TTL is testable.++use super::version::Version;+use anyhow::{Context, Result};+use chrono::{DateTime, Duration, Utc};+use serde::{Deserialize, Serialize};+use std::path::{Path, PathBuf};++/// How long a check result is trusted before agtx asks again.+///+/// Not an optimisation. Unauthenticated GitHub allows 60 requests/hour **per+/// IP**, and agtx is launched dozens of times a day across many project+/// directories β an uncached check would rate-limit a single developer, let+/// alone a shared NAT. The cache is what makes a notice on every launch+/// affordable: read every time, refreshed once a day.+pub const CACHE_TTL_HOURS: i64 = 24;++/// Persisted at `~/.config/agtx/update.json`.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct UpdateCache {+ pub last_checked: DateTime<Utc>,+ /// The tag as GitHub reported it, e.g. `v0.2.8`. Stored verbatim so the+ /// download URL can be rebuilt without guessing at the `v`.+ pub latest_tag: String,+ pub html_url: String,+}++/// What the TUI and the CLI both render.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct UpdateInfo {+ pub current: Version,+ pub latest: Version,+ pub tag: String,+ pub html_url: String,+}++/// `~/.config/agtx/update.json`.+///+/// Built from `GlobalConfig::config_path()`'s parent, **not** from+/// `directories`' `config_dir()` β see the config-path split in CLAUDE.md. The+/// latter puts this in `~/Library/Application Support/` on macOS, away from the+/// `config.toml` and `logs/` it belongs next to.+pub fn cache_path() -> Result<PathBuf> {+ let config = crate::config::GlobalConfig::config_path()?;+ Ok(config+ .parent()+ .context("config path has no parent directory")?+ .join("update.json"))+}++/// A corrupt or missing cache reads as "no cache", never as an error: the only+/// consequence is one extra API call.+pub fn load_cache(path: &Path) -> Option<UpdateCache> {+ let raw = std::fs::read_to_string(path).ok()?;+ serde_json::from_str(&raw).ok()+}++pub fn save_cache(path: &Path, cache: &UpdateCache) -> Result<()> {+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)?;+ }+ std::fs::write(path, serde_json::to_string_pretty(cache)?)?;+ Ok(())+}++/// Whether the network call is due.+pub fn should_check(cache: Option<&UpdateCache>, now: DateTime<Utc>) -> bool {+ match cache {+ None => true,+ // A `last_checked` in the future means a clock moved backwards; treat+ // it as stale rather than locking the check out until the date catches up.+ Some(c) => {+ now.signed_duration_since(c.last_checked) >= Duration::hours(CACHE_TTL_HOURS)+ || c.last_checked > now+ }+ }+}++/// Turn a cache entry into a notice, or nothing.+pub fn available(current: &Version, cache: &UpdateCache) -> Option<UpdateInfo> {+ let latest = Version::parse(&cache.latest_tag)?;+ if !latest.supersedes(current) {+ return None;+ }+ Some(UpdateInfo {+ current: current.clone(),+ latest,+ tag: cache.latest_tag.clone(),+ html_url: cache.html_url.clone(),+ })+}++/// Whether the background check should run at all.+///+/// Two opt-outs, and both are needed: the config field is for a user who never+/// wants it, the env var is for CI, the `docker/` images and the smoke runner,+/// which must not make a network call per launch.+pub fn checks_enabled(config_enabled: bool) -> bool {+ if !config_enabled {+ return false;+ }+ !matches!(+ std::env::var("AGTX_NO_UPDATE_CHECK").as_deref(),+ Ok("1") | Ok("true")+ )+}diff --git a/src/update/github.rs b/src/update/github.rsnew file mode 100644index 0000000..628b62a--- /dev/null+++ b/src/update/github.rs@@ -0,0 +1,79 @@+//! The one network call: `GET /repos/{repo}/releases/latest`.+//!+//! Uses the `curl` binary rather than an HTTP crate. `reqwest`/`ureq` would add+//! a TLS stack and a large dependency tree to a binary that has neither, for+//! one GET per day. `curl` is already a hard requirement of the only supported+//! install path (`install.sh`), ships by default on macOS and every Linux agtx+//! runs on, and β the part that matters in practice β honours `HTTPS_PROXY`,+//! `NO_PROXY` and the system CA store, which is what corporate networks need+//! and what a bundled rustls stack gets wrong. A missing `curl` is a silent+//! no-op, not an error.+//!+//! If a reason to drop the subprocess ever appears, this file is the only one+//! that changes.++use anyhow::{bail, Context, Result};+use std::process::Command;+use std::time::Duration;++/// Hard ceiling on the request. The check runs on a background thread and never+/// blocks a frame, but a hung connection should not keep a thread alive for the+/// life of the session either.+const TIMEOUT: Duration = Duration::from_secs(5);++pub struct Release {+ pub tag_name: String,+ pub html_url: String,+}++/// `None` when the network, the API or `curl` itself is unavailable β every+/// failure here is a missing notice, never a visible error.+pub fn fetch_latest_release(repo: &str) -> Result<Release> {+ let url = format!("https://api.github.com/repos/{}/releases/latest", repo);+ let output = Command::new("curl")+ .args([+ "-fsSL",+ "--max-time",+ &TIMEOUT.as_secs().to_string(),+ "-H",+ "Accept: application/vnd.github+json",+ // GitHub rejects requests without one. curl sends its own, but+ // being explicit makes agtx traffic identifiable in rate-limit logs.+ "-H",+ &format!("User-Agent: agtx/{}", env!("CARGO_PKG_VERSION")),+ &url,+ ])+ .output()+ .context("failed to run curl (is it installed?)")?;++ if !output.status.success() {+ bail!(+ "curl failed for {}: {}",+ url,+ String::from_utf8_lossy(&output.stderr).trim()+ );+ }++ parse_release(&String::from_utf8_lossy(&output.stdout))+}++/// Split out so the JSON handling is testable without a network: a rate-limit+/// body, an HTML error page and a truncated response must all be an `Err`, not+/// a panic.+pub fn parse_release(body: &str) -> Result<Release> {+ let json: serde_json::Value =+ serde_json::from_str(body).context("release response was not JSON")?;++ let tag_name = json+ .get("tag_name")+ .and_then(|v| v.as_str())+ .context("release response has no tag_name")?+ .to_string();+ let html_url = json+ .get("html_url")+ .and_then(|v| v.as_str())+ .unwrap_or_default()+ .to_string();++ Ok(Release { tag_name, html_url })+}diff --git a/src/update/install.rs b/src/update/install.rsnew file mode 100644index 0000000..c5875a6--- /dev/null+++ b/src/update/install.rs@@ -0,0 +1,258 @@+//! Download the release for this host, verify it, and replace the running+//! binary in place.++use anyhow::{bail, Context, Result};+use sha2::{Digest, Sha256};+use std::path::{Path, PathBuf};+use std::process::Command;++use super::release;++/// A package manager owns this binary, so agtx must not replace it.+///+/// Silently overwriting a file Homebrew or Nix believes it owns breaks the+/// machine in a way that is hard to diagnose later β the manager's manifest and+/// the file on disk disagree, and the next upgrade reverts the update without+/// explanation. Refuse and name the right command instead.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum ManagedBy {+ Homebrew,+ Nix,+}++impl ManagedBy {+ pub fn advice(&self) -> &'static str {+ match self {+ Self::Homebrew => "This agtx was installed by Homebrew β update it with `brew upgrade agtx`.",+ Self::Nix => "This agtx lives in the Nix store and cannot be replaced in place β update it through Nix.",+ }+ }+}++/// Pure so the path table is testable without installing anything.+pub fn managed_by(exe: &Path) -> Option<ManagedBy> {+ let p = exe.to_string_lossy();+ if p.starts_with("/nix/store/") {+ return Some(ManagedBy::Nix);+ }+ if p.starts_with("/opt/homebrew/")+ || p.contains("/Cellar/")+ || p.starts_with("/home/linuxbrew/")+ {+ return Some(ManagedBy::Homebrew);+ }+ None+}++/// Where the replacement lands.+///+/// `canonicalize` matters: the install path may be a symlink (`install.sh`+/// moves the binary directly, but a manual install or a dotfiles setup may+/// not), and replacing the symlink instead of its target would leave the real+/// binary stale and the link pointing at a different file than the user thinks.+pub fn target_path() -> Result<PathBuf> {+ let exe = std::env::current_exe().context("could not determine the running binary's path")?;+ Ok(exe.canonicalize().unwrap_or(exe))+}++/// `<hash> <filename>` β the format `sha256sum`/`shasum -a 256` write and+/// `install.sh` feeds back to `-c`.+pub fn parse_sha256_file(contents: &str) -> Option<String> {+ let hash = contents.split_whitespace().next()?;+ if hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit()) {+ Some(hash.to_ascii_lowercase())+ } else {+ None+ }+}++pub fn sha256_hex(bytes: &[u8]) -> String {+ let mut hasher = Sha256::new();+ hasher.update(bytes);+ format!("{:x}", hasher.finalize())+}++/// What `agtx update` reports back, so the CLI and the TUI can render the same+/// outcome differently.+pub struct Installed {+ pub tag: String,+ pub path: PathBuf,+}++fn curl_to_file(url: &str, dest: &Path) -> Result<()> {+ let status = Command::new("curl")+ .args(["-fsSL", "--max-time", "300", url, "-o"])+ .arg(dest)+ .status()+ .context("failed to run curl (is it installed?)")?;+ if !status.success() {+ bail!("download failed: {url}");+ }+ Ok(())+}++fn curl_to_string(url: &str) -> Result<String> {+ let out = Command::new("curl")+ .args(["-fsSL", "--max-time", "30", url])+ .output()+ .context("failed to run curl (is it installed?)")?;+ if !out.status.success() {+ bail!("download failed: {url}");+ }+ Ok(String::from_utf8_lossy(&out.stdout).into_owned())+}++/// Download `tag`'s archive for this host, verify it, and swap it into place.+///+/// `progress` is called with human-readable steps so the CLI can print them and+/// the TUI can put the last one in a popup.+pub fn install_release(tag: &str, progress: &mut dyn FnMut(&str)) -> Result<Installed> {+ let target = target_path()?;+ if let Some(managed) = managed_by(&target) {+ bail!("{}", managed.advice());+ }++ let dir = target+ .parent()+ .context("the running binary has no parent directory")?+ .to_path_buf();++ // Check writability before spending a download on it. `install.sh`'s+ // default is ~/.local/bin, which is writable; a binary moved under+ // /usr/local/bin with sudo is not, and agtx must not try to escalate.+ if !is_writable_dir(&dir) {+ bail!(+ "{} is not writable β re-run the installer with the right permissions:\n \+ curl -fsSL https://raw.githubusercontent.com/{}/main/install.sh | AGTX_INSTALL_DIR={} bash",+ dir.display(),+ release::repo(),+ dir.display()+ );+ }++ let os = release::host_os().context("no agtx release is published for this OS")?;+ let arch =+ release::host_arch().context("no agtx release is published for this architecture")?;+ let archive = release::archive_name(tag, arch, os);+ let repo = release::repo();+ let url = release::download_url(&repo, tag, &archive);++ // Everything staged inside the *target's own directory*, so the final+ // rename is same-filesystem. /tmp frequently is not, and `fs::rename`+ // across filesystems fails with EXDEV.+ let staging = dir.join(format!(".agtx-update-{}", std::process::id()));+ std::fs::create_dir_all(&staging)+ .with_context(|| format!("could not create staging dir {}", staging.display()))?;+ let _guard = DirGuard(staging.clone());++ progress(&format!("downloading {archive}"));+ let archive_path = staging.join(&archive);+ curl_to_file(&url, &archive_path)?;++ progress("verifying checksum");+ let bytes = std::fs::read(&archive_path)?;+ match curl_to_string(&format!("{url}.sha256")) {+ Ok(sums) => {+ let expected = parse_sha256_file(&sums)+ .with_context(|| format!("malformed checksum file for {archive}"))?;+ let actual = sha256_hex(&bytes);+ if actual != expected {+ bail!("checksum mismatch for {archive}: expected {expected}, got {actual}");+ }+ }+ // Releases before the workflow published checksums have none. Warn+ // rather than refuse, matching install.sh β but say so, so it is+ // visible rather than silent.+ Err(_) => progress("no checksum published for this release β skipping verification"),+ }++ progress("extracting");+ let status = Command::new("tar")+ .arg("-xzf")+ .arg(&archive_path)+ .arg("-C")+ .arg(&staging)+ .status()+ .context("failed to run tar")?;+ if !status.success() {+ bail!("could not extract {archive}");+ }+ let new_binary = staging.join("agtx");+ if !new_binary.exists() {+ bail!("{archive} did not contain an `agtx` binary");+ }+ set_executable(&new_binary)?;++ progress(&format!("installing to {}", target.display()));+ replace_binary(&new_binary, &target)?;++ Ok(Installed {+ tag: tag.to_string(),+ path: target,+ })+}++/// The swap, in the order that leaves a recoverable file at every step.+///+/// Renaming over a *running* binary is legal on Unix: `ETXTBSY` applies to+/// writing into the busy inode, not to replacing the directory entry that+/// points at it. The running process keeps its old inode until it exits, which+/// is why the caller has to say "restart agtx".+///+/// Moving the current binary aside first, rather than renaming straight over+/// it, means a failure between the two renames leaves `agtx.old` on disk+/// instead of no `agtx` at all.+pub fn replace_binary(new: &Path, target: &Path) -> Result<()> {+ let backup = target.with_extension("old");+ let had_backup = match std::fs::rename(target, &backup) {+ Ok(()) => true,+ // Nothing at the target yet is not a failure worth aborting for.+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,+ Err(e) => return Err(e).context("could not move the current binary aside"),+ };++ if let Err(e) = std::fs::rename(new, target) {+ if had_backup {+ let _ = std::fs::rename(&backup, target);+ }+ return Err(e).context("could not move the new binary into place");+ }++ if had_backup {+ let _ = std::fs::remove_file(&backup);+ }+ Ok(())+}++fn set_executable(path: &Path) -> Result<()> {+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755))?;+ }+ #[cfg(not(unix))]+ let _ = path;+ Ok(())+}++fn is_writable_dir(dir: &Path) -> bool {+ let probe = dir.join(format!(".agtx-write-probe-{}", std::process::id()));+ match std::fs::File::create(&probe) {+ Ok(_) => {+ let _ = std::fs::remove_file(&probe);+ true+ }+ Err(_) => false,+ }+}++/// Removes the staging directory however `install_release` returns β including+/// the early `?` on a failed download, which would otherwise leave a stray+/// directory next to the user's binary.+struct DirGuard(PathBuf);++impl Drop for DirGuard {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+}diff --git a/src/update/mod.rs b/src/update/mod.rsnew file mode 100644index 0000000..2941297--- /dev/null+++ b/src/update/mod.rs@@ -0,0 +1,58 @@+//! Release awareness and self-replacement.+//!+//! Split the way `agent::hook_status` and `tui::dep_graph` are: `version` and+//! `check` are pure (no network, no TUI, no clock of their own) so the decision+//! logic is unit-testable, and `github`/`install` are the only files that touch+//! the world.+//!+//! Two entry points share it: the background check that draws the header notice+//! (`tui::app`) and the `agtx update` subcommand (`main.rs`).++pub mod check;+pub mod github;+pub mod install;+pub mod release;+pub mod version;++pub use check::{UpdateCache, UpdateInfo};+pub use version::Version;++use anyhow::Result;+use chrono::Utc;++/// The whole check, as run on a background thread.+///+/// Reads the cache, refreshes it over the network when the TTL has expired,+/// and compares. Every failure path yields `Ok(None)` rather than an error the+/// caller has to decide how to render β offline is the normal case, not a+/// fault.+pub fn check_for_update() -> Result<Option<UpdateInfo>> {+ let current = Version::current();+ let path = check::cache_path()?;+ let mut cache = check::load_cache(&path);++ if check::should_check(cache.as_ref(), Utc::now()) {+ match github::fetch_latest_release(&release::repo()) {+ Ok(rel) => {+ let fresh = UpdateCache {+ last_checked: Utc::now(),+ latest_tag: rel.tag_name,+ html_url: rel.html_url,+ };+ // A failed write is not fatal; it just means the next launch+ // asks again.+ if let Err(e) = check::save_cache(&path, &fresh) {+ tracing::debug!("could not write update cache: {e}");+ }+ cache = Some(fresh);+ }+ Err(e) => {+ tracing::debug!("update check failed: {e}");+ // Fall through to the stale cache: a week-old "0.2.8 is out" is+ // still true and still useful on a plane.+ }+ }+ }++ Ok(cache.as_ref().and_then(|c| check::available(¤t, c)))+}diff --git a/src/update/release.rs b/src/update/release.rsnew file mode 100644index 0000000..9510031--- /dev/null+++ b/src/update/release.rs@@ -0,0 +1,47 @@+//! Release artifact naming β the third copy of strings that also live in+//! `install.sh` and `.github/workflows/release.yml`.+//!+//! All three must agree character for character or `agtx update` 404s.+//! `tests/update_tests.rs` greps the other two and asserts they match these,+//! because the alternative is finding the drift in a user's failed update.++/// Overridable so tests (and a fork) can point elsewhere without a rebuild.+pub const DEFAULT_REPO: &str = "fynnfluegge/agtx";++pub fn repo() -> String {+ std::env::var("AGTX_UPDATE_REPO").unwrap_or_else(|_| DEFAULT_REPO.to_string())+}++/// The OS token used in release archive names β matches `install.sh`'s+/// `detect_os`, which is `uname -s` folded to `linux` / `darwin`.+pub fn host_os() -> Option<&'static str> {+ match std::env::consts::OS {+ "linux" => Some("linux"),+ "macos" => Some("darwin"),+ _ => None,+ }+}++/// The arch token β matches `install.sh`'s `detect_arch`.+pub fn host_arch() -> Option<&'static str> {+ match std::env::consts::ARCH {+ "x86_64" => Some("x86_64"),+ "aarch64" => Some("aarch64"),+ _ => None,+ }+}++/// `agtx-v0.2.8-aarch64-darwin.tar.gz`+///+/// `tag` is passed through verbatim (with its `v`), because that is what+/// `release.yml` interpolates from `github.ref_name`.+pub fn archive_name(tag: &str, arch: &str, os: &str) -> String {+ format!("agtx-{}-{}-{}.tar.gz", tag, arch, os)+}++pub fn download_url(repo: &str, tag: &str, archive: &str) -> String {+ format!(+ "https://github.com/{}/releases/download/{}/{}",+ repo, tag, archive+ )+}diff --git a/src/update/version.rs b/src/update/version.rsnew file mode 100644index 0000000..39ec8be--- /dev/null+++ b/src/update/version.rs@@ -0,0 +1,121 @@+//! Semver-lite parsing and comparison for agtx release tags.+//!+//! Deliberately not the `semver` crate: the only versions this ever sees are+//! the ones agtx itself produces (`Cargo.toml` and its matching `vX.Y.Z` tag,+//! enforced by the release workflow), so the grammar is ours and small. Build+//! metadata (`+meta`) is accepted and ignored; prerelease identifiers are kept+//! because the update *policy* depends on them.++use std::cmp::Ordering;+use std::fmt;++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Version {+ pub major: u64,+ pub minor: u64,+ pub patch: u64,+ /// `Some("rc1")` for `0.3.0-rc1`. A prerelease sorts *before* the same+ /// numeric version without one.+ pub pre: Option<String>,+}++impl Version {+ /// Parse `0.2.7`, `v0.2.7`, `v0.3.0-rc1`, `0.2.7+build5`.+ ///+ /// Returns `None` for anything else. A remote tag agtx cannot parse is not+ /// an update β it is a log line. A version check must never be able to make+ /// the TUI shout about a tag it does not understand.+ pub fn parse(s: &str) -> Option<Self> {+ let s = s.trim();+ let s = s.strip_prefix('v').unwrap_or(s);+ // Build metadata does not participate in precedence (semver Β§10).+ let s = s.split('+').next()?;+ let (core, pre) = match s.split_once('-') {+ Some((core, pre)) if !pre.is_empty() => (core, Some(pre.to_string())),+ Some(_) => return None, // trailing '-' with nothing after it+ None => (s, None),+ };++ let mut parts = core.split('.');+ let major = parse_num(parts.next()?)?;+ let minor = parse_num(parts.next()?)?;+ let patch = parse_num(parts.next()?)?;+ if parts.next().is_some() {+ return None;+ }++ Some(Self {+ major,+ minor,+ patch,+ pre,+ })+ }++ /// The version this build reports, from `Cargo.toml`.+ ///+ /// Infallible in practice: `CARGO_PKG_VERSION` is a compile-time constant+ /// and the release workflow fails the build when it disagrees with the tag.+ pub fn current() -> Self {+ Self::parse(env!("CARGO_PKG_VERSION"))+ .expect("CARGO_PKG_VERSION is not a version agtx can parse")+ }++ pub fn is_prerelease(&self) -> bool {+ self.pre.is_some()+ }++ /// Whether `self` should be offered as an update over `current`.+ ///+ /// The one policy decision here: **a stable build is never offered a+ /// prerelease.** GitHub's `releases/latest` already excludes prereleases,+ /// so this is belt and braces for a redirected `AGTX_UPDATE_REPO` β but it+ /// is the behaviour that would be wrong to leave implicit. A prerelease+ /// build *is* offered the stable release that supersedes it, which is how a+ /// tester gets back onto the release line.+ pub fn supersedes(&self, current: &Version) -> bool {+ if self.is_prerelease() && !current.is_prerelease() {+ return false;+ }+ self > current+ }+}++fn parse_num(s: &str) -> Option<u64> {+ if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {+ return None;+ }+ s.parse().ok()+}++impl Ord for Version {+ fn cmp(&self, other: &Self) -> Ordering {+ // Numeric first, then: no prerelease outranks any prerelease, and two+ // prereleases fall back to a plain string compare (rc1 < rc2). Good+ // enough for tags we mint ourselves; nothing depends on rc2 < rc10.+ (self.major, self.minor, self.patch)+ .cmp(&(other.major, other.minor, other.patch))+ .then_with(|| match (&self.pre, &other.pre) {+ (None, None) => Ordering::Equal,+ (None, Some(_)) => Ordering::Greater,+ (Some(_), None) => Ordering::Less,+ (Some(a), Some(b)) => a.cmp(b),+ })+ }+}++impl PartialOrd for Version {+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {+ Some(self.cmp(other))+ }+}++impl fmt::Display for Version {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?;+ if let Some(pre) = &self.pre {+ write!(f, "-{}", pre)?;+ }+ Ok(())+ }+}diff --git a/tests/update_tests.rs b/tests/update_tests.rsnew file mode 100644index 0000000..5035637--- /dev/null+++ b/tests/update_tests.rs@@ -0,0 +1,425 @@+//! Release awareness and self-replacement.+//!+//! Everything here runs without a network. The one thing it cannot cover is+//! "does the published tarball install over the running binary" β that needs+//! real artifacts, and belongs in a post-release job.++use agtx::update::check::{self, UpdateCache};+use agtx::update::install::{self, ManagedBy};+use agtx::update::{github, release, Version};+use chrono::{Duration, TimeZone, Utc};++// ---------------------------------------------------------------- version++#[test]+fn parses_the_forms_agtx_produces() {+ for (input, expected) in [+ ("0.2.7", "0.2.7"),+ ("v0.2.7", "0.2.7"),+ (" v0.2.7\n", "0.2.7"),+ ("v0.3.0-rc1", "0.3.0-rc1"),+ ("0.2.7+build5", "0.2.7"),+ ("v10.20.30", "10.20.30"),+ ] {+ let v = Version::parse(input).unwrap_or_else(|| panic!("{input} should parse"));+ assert_eq!(v.to_string(), expected, "input {input}");+ }+}++#[test]+fn rejects_what_it_cannot_understand() {+ // A remote tag agtx cannot parse must be *no update*, never a panic and+ // never a notice about a version it does not understand.+ for input in [+ "", "v", "1.2", "1.2.3.4", "latest", "v1.2.x", "1.-2.3", "v1.2.3-", "nightly",+ ] {+ assert!(+ Version::parse(input).is_none(),+ "{input:?} should not parse"+ );+ }+}++#[test]+fn orders_numerically_not_lexically() {+ let older = Version::parse("v0.9.9").unwrap();+ let newer = Version::parse("v0.10.0").unwrap();+ assert!(newer > older, "0.10.0 must outrank 0.9.9");+ assert!(Version::parse("1.0.0").unwrap() > Version::parse("0.99.99").unwrap());+ assert_eq!(+ Version::parse("0.2.7").unwrap(),+ Version::parse("v0.2.7").unwrap()+ );+}++#[test]+fn a_prerelease_is_never_offered_to_a_stable_build() {+ let stable = Version::parse("0.2.7").unwrap();+ let pre = Version::parse("0.3.0-rc1").unwrap();+ assert!(pre > stable, "it is still numerically newer");+ assert!(+ !pre.supersedes(&stable),+ "but a stable build must not be pushed onto a release candidate"+ );+}++#[test]+fn a_prerelease_build_is_offered_the_stable_that_supersedes_it() {+ // How a tester gets back onto the release line.+ let pre = Version::parse("0.3.0-rc1").unwrap();+ let stable = Version::parse("0.3.0").unwrap();+ assert!(stable.supersedes(&pre));+}++#[test]+fn same_or_older_is_not_an_update() {+ let current = Version::parse("0.2.7").unwrap();+ assert!(!Version::parse("0.2.7").unwrap().supersedes(¤t));+ assert!(!Version::parse("0.2.6").unwrap().supersedes(¤t));+ assert!(Version::parse("0.2.8").unwrap().supersedes(¤t));+}++#[test]+fn current_version_is_parseable() {+ // Guards the `expect` in `Version::current()`: if Cargo.toml ever grows a+ // version shape this parser does not handle, fail here rather than at+ // startup in a user's terminal.+ let v = Version::current();+ assert_eq!(v.to_string(), env!("CARGO_PKG_VERSION"));+}++// ------------------------------------------------------------------ cache++fn cache_at(hours_ago: i64, tag: &str) -> UpdateCache {+ UpdateCache {+ last_checked: Utc::now() - Duration::hours(hours_ago),+ latest_tag: tag.to_string(),+ html_url: format!("https://github.com/fynnfluegge/agtx/releases/tag/{tag}"),+ }+}++#[test]+fn no_cache_means_check() {+ assert!(check::should_check(None, Utc::now()));+}++#[test]+fn fresh_cache_suppresses_the_call() {+ let cache = cache_at(1, "v0.2.8");+ assert!(!check::should_check(Some(&cache), Utc::now()));+}++#[test]+fn expired_cache_allows_the_call() {+ let cache = cache_at(check::CACHE_TTL_HOURS + 1, "v0.2.8");+ assert!(check::should_check(Some(&cache), Utc::now()));+}++#[test]+fn a_cache_from_the_future_is_stale_not_permanent() {+ // A clock that moved backwards (or a timezone mishap) must not lock the+ // check out until the calendar catches up.+ let mut cache = cache_at(0, "v0.2.8");+ cache.last_checked = Utc::now() + Duration::days(30);+ assert!(check::should_check(Some(&cache), Utc::now()));+}++#[test]+fn corrupt_cache_reads_as_no_cache() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("update.json");+ std::fs::write(&path, "{ this is not json").unwrap();+ assert!(check::load_cache(&path).is_none());+ assert!(check::should_check(None, Utc::now()));+}++#[test]+fn cache_round_trips() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("nested").join("update.json");+ let cache = UpdateCache {+ last_checked: Utc.with_ymd_and_hms(2026, 8, 26, 9, 0, 0).unwrap(),+ latest_tag: "v0.2.8".to_string(),+ html_url: "https://example.invalid/tag".to_string(),+ };+ check::save_cache(&path, &cache).unwrap();+ let loaded = check::load_cache(&path).unwrap();+ assert_eq!(loaded.latest_tag, "v0.2.8");+ assert_eq!(loaded.last_checked, cache.last_checked);+}++#[test]+fn cache_lives_next_to_config_toml_not_in_the_data_dir() {+ // The config-path split in CLAUDE.md: `directories`' config_dir() puts this+ // in ~/Library/Application Support on macOS, away from config.toml and+ // logs/. It must derive from GlobalConfig::config_path()'s parent instead.+ let path = check::cache_path().unwrap();+ let config = agtx::config::GlobalConfig::config_path().unwrap();+ assert_eq!(path.parent(), config.parent());+ assert_eq!(path.file_name().unwrap(), "update.json");+}++#[test]+fn available_compares_against_the_cached_tag() {+ let current = Version::parse("0.2.7").unwrap();+ assert!(check::available(¤t, &cache_at(1, "v0.2.8")).is_some());+ assert!(check::available(¤t, &cache_at(1, "v0.2.7")).is_none());+ assert!(check::available(¤t, &cache_at(1, "v0.2.6")).is_none());+ // An unparseable tag is not an update.+ assert!(check::available(¤t, &cache_at(1, "nightly")).is_none());+}++#[test]+fn config_and_env_each_suppress_the_check() {+ // Not run in parallel with anything that reads the same var: set/remove is+ // process-global, so the assertions bracket it tightly.+ std::env::remove_var("AGTX_NO_UPDATE_CHECK");+ assert!(check::checks_enabled(true));+ assert!(!check::checks_enabled(false), "config field must win");++ std::env::set_var("AGTX_NO_UPDATE_CHECK", "1");+ assert!(!check::checks_enabled(true), "env var must win");+ std::env::remove_var("AGTX_NO_UPDATE_CHECK");+}++// ----------------------------------------------------------------- github++#[test]+fn parses_a_real_releases_latest_payload() {+ let body = r#"{+ "url": "https://api.github.com/repos/fynnfluegge/agtx/releases/1",+ "html_url": "https://github.com/fynnfluegge/agtx/releases/tag/v0.2.8",+ "tag_name": "v0.2.8",+ "name": "v0.2.8",+ "draft": false,+ "prerelease": false,+ "assets": []+ }"#;+ let rel = github::parse_release(body).unwrap();+ assert_eq!(rel.tag_name, "v0.2.8");+ assert_eq!(+ rel.html_url,+ "https://github.com/fynnfluegge/agtx/releases/tag/v0.2.8"+ );+}++#[test]+fn a_non_release_body_is_an_error_not_a_panic() {+ // The three shapes GitHub actually returns when something is wrong.+ let rate_limited =+ r#"{"message":"API rate limit exceeded","documentation_url":"https://docs.github.com"}"#;+ assert!(github::parse_release(rate_limited).is_err());+ assert!(github::parse_release("<html><body>502</body></html>").is_err());+ assert!(github::parse_release(r#"{"tag_name": "v0.2."#).is_err());+ assert!(github::parse_release("").is_err());+}++// ---------------------------------------------------------------- release++#[test]+fn archive_names_match_the_four_published_targets() {+ for (arch, os, expected) in [+ ("aarch64", "darwin", "agtx-v0.2.8-aarch64-darwin.tar.gz"),+ ("x86_64", "darwin", "agtx-v0.2.8-x86_64-darwin.tar.gz"),+ ("x86_64", "linux", "agtx-v0.2.8-x86_64-linux.tar.gz"),+ ("aarch64", "linux", "agtx-v0.2.8-aarch64-linux.tar.gz"),+ ] {+ assert_eq!(release::archive_name("v0.2.8", arch, os), expected);+ }+}++#[test]+fn this_host_maps_to_a_published_target() {+ // Every platform agtx builds for must resolve; anything else must be a+ // clean "no release for this host" rather than a wrong URL.+ if cfg!(any(target_os = "linux", target_os = "macos")) {+ assert!(release::host_os().is_some());+ }+ if cfg!(any(target_arch = "x86_64", target_arch = "aarch64")) {+ assert!(release::host_arch().is_some());+ }+}++#[test]+fn download_url_points_at_the_tag() {+ assert_eq!(+ release::download_url("fynnfluegge/agtx", "v0.2.8", "agtx-v0.2.8-x86_64-linux.tar.gz"),+ "https://github.com/fynnfluegge/agtx/releases/download/v0.2.8/agtx-v0.2.8-x86_64-linux.tar.gz"+ );+}++/// The repo slug and the archive naming exist in three places: here,+/// `install.sh`, and `release.yml`. They must agree character for character or+/// `agtx update` 404s β and the drift would otherwise be found by a user whose+/// update silently fails, not by CI.+#[test]+fn naming_matches_install_sh() {+ let sh = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/install.sh")).unwrap();+ assert!(+ sh.contains(&format!("REPO=\"{}\"", release::DEFAULT_REPO)),+ "install.sh REPO does not match update::release::DEFAULT_REPO"+ );+ // install.sh builds: ${BINARY_NAME}-${VERSION}-${ARCH}-${OS}.tar.gz+ assert!(+ sh.contains(r#"ARCHIVE_NAME="${BINARY_NAME}-${VERSION}-${ARCH}-${OS}.tar.gz""#),+ "install.sh archive naming changed β update::release::archive_name must follow"+ );+ // and the os/arch tokens the name interpolates+ for token in [+ "echo \"linux\"",+ "echo \"darwin\"",+ "echo \"x86_64\"",+ "echo \"aarch64\"",+ ] {+ assert!(sh.contains(token), "install.sh no longer emits {token}");+ }+}++#[test]+fn naming_matches_release_workflow() {+ let yml = std::fs::read_to_string(concat!(+ env!("CARGO_MANIFEST_DIR"),+ "/.github/workflows/release.yml"+ ))+ .unwrap();+ for (arch, os) in [+ ("aarch64", "darwin"),+ ("x86_64", "darwin"),+ ("x86_64", "linux"),+ ("aarch64", "linux"),+ ] {+ // release.yml interpolates the tag as ${{ github.ref_name }}+ let expected = release::archive_name("${{ github.ref_name }}", arch, os);+ assert!(+ yml.contains(&expected),+ "release.yml does not publish {expected}"+ );+ }+ assert!(+ yml.contains(".sha256"),+ "release.yml must publish checksums β `agtx update` and install.sh both verify them"+ );+ assert!(+ yml.contains("Tag matches Cargo.toml"),+ "the tag/manifest guard is what keeps `agtx --version` honest"+ );+}++// ---------------------------------------------------------------- install++#[test]+fn package_managed_binaries_are_refused() {+ use std::path::Path;+ assert_eq!(+ install::managed_by(Path::new("/nix/store/abc123-agtx-0.2.7/bin/agtx")),+ Some(ManagedBy::Nix)+ );+ assert_eq!(+ install::managed_by(Path::new("/opt/homebrew/bin/agtx")),+ Some(ManagedBy::Homebrew)+ );+ assert_eq!(+ install::managed_by(Path::new("/usr/local/Cellar/agtx/0.2.7/bin/agtx")),+ Some(ManagedBy::Homebrew)+ );+ assert_eq!(+ install::managed_by(Path::new("/home/linuxbrew/.linuxbrew/bin/agtx")),+ Some(ManagedBy::Homebrew)+ );+ // The path install.sh actually uses, and a plain system path, are ours.+ assert_eq!(+ install::managed_by(Path::new("/Users/x/.local/bin/agtx")),+ None+ );+ assert_eq!(install::managed_by(Path::new("/usr/local/bin/agtx")), None);+}++#[test]+fn managed_advice_names_the_right_tool() {+ assert!(ManagedBy::Homebrew.advice().contains("brew upgrade"));+ assert!(ManagedBy::Nix.advice().contains("Nix"));+}++/// The digest of the empty input β the standard SHA-256 test vector.+const EMPTY_SHA256: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";++#[test]+fn parses_the_checksum_format_both_shasum_tools_write() {+ // sha256sum and `shasum -a 256` both write "<hash> <name>"+ assert_eq!(+ install::parse_sha256_file(&format!(+ "{EMPTY_SHA256} agtx-v0.2.8-x86_64-linux.tar.gz\n"+ )),+ Some(EMPTY_SHA256.to_string())+ );+ // Uppercase is normalised.+ assert_eq!(+ install::parse_sha256_file(&format!("{} x", EMPTY_SHA256.to_uppercase())),+ Some(EMPTY_SHA256.to_string())+ );+ // A 404 page, an empty file and a truncated hash are all "no checksum".+ assert!(install::parse_sha256_file("Not Found").is_none());+ assert!(install::parse_sha256_file("").is_none());+ assert!(install::parse_sha256_file(&format!("{} x", &EMPTY_SHA256[..63])).is_none());+}++#[test]+fn sha256_matches_a_known_digest() {+ assert_eq!(install::sha256_hex(b""), EMPTY_SHA256);+}++#[test]+fn replace_binary_swaps_and_cleans_up() {+ let dir = tempfile::tempdir().unwrap();+ let target = dir.path().join("agtx");+ let new = dir.path().join("agtx-new");+ std::fs::write(&target, b"old").unwrap();+ std::fs::write(&new, b"new").unwrap();++ install::replace_binary(&new, &target).unwrap();++ assert_eq!(std::fs::read(&target).unwrap(), b"new");+ assert!(!new.exists(), "the staged binary was moved, not copied");+ assert!(+ !target.with_extension("old").exists(),+ "the backup must be removed on success"+ );+}++#[test]+fn replace_binary_works_when_no_target_exists_yet() {+ let dir = tempfile::tempdir().unwrap();+ let target = dir.path().join("agtx");+ let new = dir.path().join("agtx-new");+ std::fs::write(&new, b"new").unwrap();++ install::replace_binary(&new, &target).unwrap();+ assert_eq!(std::fs::read(&target).unwrap(), b"new");+}++#[test]+fn a_failed_swap_leaves_the_old_binary_in_place() {+ // The reason the backup step exists: if the second rename fails, the user+ // must still have a working agtx rather than no agtx at all.+ let dir = tempfile::tempdir().unwrap();+ let target = dir.path().join("agtx");+ std::fs::write(&target, b"old").unwrap();+ let missing = dir.path().join("does-not-exist");++ assert!(install::replace_binary(&missing, &target).is_err());+ assert_eq!(+ std::fs::read(&target).unwrap(),+ b"old",+ "the original must be restored when the new binary cannot be moved in"+ );+}++#[test]+fn target_path_resolves_to_a_real_file() {+ let path = install::target_path().unwrap();+ assert!(+ path.exists(),+ "current_exe must resolve: {}",+ path.display()+ );+}