Skip to main content

agentmux_common/
srv_stderr.rs

1//! The stderr line protocol `agentmux-srv` uses to talk to whichever process
2//! supervises it — the launcher in packaged builds and `task dev`
3//! (`crates/launcher/src/srv_spawner.rs`), or the CEF host in
4//! `task dev:standalone` (`crates/cef/src/sidecar.rs`).
5//!
6//! srv formats these lines; both supervisors parse them. Putting the
7//! vocabulary here means one definition instead of three string literals that
8//! have to stay byte-identical by convention (the "keep in sync" pattern
9//! `docs/reports/REPORT_DRY_AND_MODULARITY_AUDIT_2026_09_06.md` §2 counts 334
10//! instances of).
11//!
12//! Every line is single-line and prefix-tagged. In startup order:
13//!
14//! - `AGENTMUXSRV-MIGRATING migrations:<n>` — in-process migrations are about
15//!   to run; supervisors extend their ESTART deadline. A new version's first
16//!   start prints `AGENTMUXSRV-MIGRATING copying-previous-version:<v>` before
17//!   copying the previous version's databases (`migrations/carry_forward.rs`);
18//!   supervisors match the prefix only ([`migrating_line`],
19//!   [`is_migrating_line`]).
20//! - `AGENTMUXSRV-MIGRATION-BEGIN id:<id> description:<text>` /
21//!   `AGENTMUXSRV-MIGRATION-END id:<id> duration_ms:<n>` — one pending
22//!   migration is starting / has finished, inside the `AGENTMUXSRV-MIGRATING`
23//!   window above. Before these existed, a slow migration was invisible
24//!   past the initial count — the splash showed a bare, silently-running
25//!   "Backend startup" clock with no indication anything unusual (a
26//!   multi-minute migration) was happening inside it. See
27//!   `docs/reports/REPORT_SPLASH_SCREEN_ARCHITECTURE_RETHINK_2026_09_14.md`
28//!   §2.1. Only the launcher supervisor turns these into splash sub-rows
29//!   (against the already-open `backend` stage — a migration is not a
30//!   separate top-level stage, it happens entirely inside that one); the
31//!   CEF-host sidecar has no splash to report to and simply logs them like
32//!   any other stderr line, same as it already did for the unparsed line
33//!   before this existed.
34//! - `AGENTMUXSRV-STEP-BEGIN id:<id> label:<text>` /
35//!   `AGENTMUXSRV-STEP-END id:<id> duration_ms:<n>[ status:error]` — one data-preparation
36//!   step besides a migration: copying the previous version's data, a
37//!   snapshot, waiting for another AgentMux's migrations, the backup. Written
38//!   by srv's startup and by `agentmux-srv migrate --prepare`; the launcher
39//!   shows each as a sub-row of `backend`, like a migration.
40//! - `AGENTMUXSRV-NEEDS-PREPARE reason:<text>` — srv was started by a
41//!   supervisor that prepares data ([`SUPERVISOR_PREPARES_ENV`]) and found data
42//!   that needs preparing (a previous version to copy forward, or pending
43//!   migrations); it exits [`NEEDS_PREPARE_EXIT`] before writing anything, and
44//!   the supervisor runs `agentmux-srv migrate --prepare`, then starts it again.
45//! - `AGENTMUXSRV-MIGRATION-FAILED error:<text>` — a migration failed and srv
46//!   is about to exit 1 **without** emitting ESTART. Added by Phase 1 of
47//!   `docs/specs/SPEC_MIGRATION_SYSTEM_HARDENING_2026_08_03.md`; before it,
48//!   a failed migration was a `warn!` and srv booted anyway against a store in
49//!   an unknown state.
50//! - `AGENTMUXSRV-ESTART ws:<addr> web:<addr> version:<v> buildtime:<t>
51//!   instance:<id> pending_migrations:<n>` — ready ([`Estart`]).
52//! - `AGENTMUXSRV-EVENT:<json>` — a startup event for the launcher to log
53//!   ([`parse_event_line`]).
54//! - `AGENTMUXSRV-UPGRADE version:<v> [approved:<how>:<id>] launcher:<path>` (a portable) or
55//!   `… installer:<path>` (a `setup.exe` install; the digest is `sha256:<hex>` before it). The optional
56//!   `approved:` token says who approved the restart; the launcher skips it. Any time after ESTART: the
57//!   user chose "Upgrade & restart" and `<path>` is the launcher, or the
58//!   installer, of a release srv downloaded and verified. The launcher checks it again, asks
59//!   the user itself, and restarts into it (`crates/launcher/src/upgrade_restart.rs`).
60
61/// Prefix of the line srv writes when it is ready to serve.
62pub const ESTART_PREFIX: &str = "AGENTMUXSRV-ESTART";
63
64/// The fields of an `ESTART_PREFIX` line. Endpoints are `host:port`.
65#[derive(Debug, Clone, Default, PartialEq, Eq)]
66pub struct Estart {
67    pub ws_endpoint: String,
68    pub web_endpoint: String,
69    pub version: String,
70    pub build_time: String,
71    pub instance_id: String,
72    /// Migrations still pending after srv's own run; non-zero only when one
73    /// could not be applied.
74    pub pending_migrations: usize,
75}
76
77pub fn estart_line(e: &Estart) -> String {
78    format!(
79        "{} ws:{} web:{} version:{} buildtime:{} instance:{} pending_migrations:{}",
80        ESTART_PREFIX, e.ws_endpoint, e.web_endpoint, e.version, e.build_time, e.instance_id, e.pending_migrations
81    )
82}
83
84/// Parse an `ESTART_PREFIX` line; `None` for any other line. A missing field
85/// reads as empty (or 0), as both supervisors always read it.
86pub fn parse_estart_line(line: &str) -> Option<Estart> {
87    let rest = line.strip_prefix(ESTART_PREFIX)?;
88    let parts: Vec<&str> = rest.split_whitespace().collect();
89    let get = |prefix: &str| parts.iter().find_map(|p| p.strip_prefix(prefix)).unwrap_or_default().to_string();
90    Some(Estart {
91        ws_endpoint: get("ws:"),
92        web_endpoint: get("web:"),
93        version: get("version:"),
94        build_time: get("buildtime:"),
95        instance_id: get("instance:"),
96        pending_migrations: get("pending_migrations:").parse().unwrap_or(0),
97    })
98}
99
100/// Prefix of the line srv writes before slow work that precedes ESTART
101/// (migrations, copying the previous version's data); supervisors extend
102/// their ESTART deadline when they see it.
103pub const MIGRATING_PREFIX: &str = "AGENTMUXSRV-MIGRATING";
104
105/// `AGENTMUXSRV-MIGRATING <what>:<detail>`, e.g. `migrations:3`.
106pub fn migrating_line(what: &str, detail: impl std::fmt::Display) -> String {
107    format!("{MIGRATING_PREFIX} {what}:{detail}")
108}
109
110pub fn is_migrating_line(line: &str) -> bool {
111    line.starts_with(MIGRATING_PREFIX)
112}
113
114/// Prefix of a startup event line; the rest of the line is its JSON.
115pub const EVENT_PREFIX: &str = "AGENTMUXSRV-EVENT:";
116
117/// The JSON of an `EVENT_PREFIX` line; `None` for any other line.
118pub fn parse_event_line(line: &str) -> Option<&str> {
119    line.strip_prefix(EVENT_PREFIX)
120}
121
122/// Prefix of the line srv writes to stderr immediately before exiting 1
123/// because `run_pending_migrations` failed. Supervisors match on this to fail
124/// fast with the real reason instead of waiting out the ESTART timeout.
125pub const MIGRATION_FAILED_PREFIX: &str = "AGENTMUXSRV-MIGRATION-FAILED";
126
127/// Format the failure line srv emits. The error text is flattened to a single
128/// line (the protocol is line-delimited; a multi-line SQLite error would
129/// otherwise split into one tagged line and several untagged ones).
130pub fn migration_failed_line(err: &str) -> String {
131    format!("{} error:{}", MIGRATION_FAILED_PREFIX, one_line(err))
132}
133
134/// Parse a stderr line. Returns the error message if this is a
135/// `MIGRATION_FAILED_PREFIX` line, `None` for any other line. Tolerates a
136/// missing `error:` field and never returns an empty message, so callers can
137/// put the result straight into a user-facing dialog.
138pub fn parse_migration_failed_line(line: &str) -> Option<String> {
139    let rest = line.strip_prefix(MIGRATION_FAILED_PREFIX)?;
140    let rest = rest.trim_start();
141    let msg = rest.strip_prefix("error:").unwrap_or(rest).trim();
142    Some(if msg.is_empty() { "unknown error".to_string() } else { msg.to_string() })
143}
144
145fn one_line(s: &str) -> String {
146    s.split(['\n', '\r'])
147        .map(str::trim)
148        .filter(|part| !part.is_empty())
149        .collect::<Vec<_>>()
150        .join(" | ")
151}
152
153/// Set to `1` by a supervisor that runs `agentmux-srv migrate --prepare`
154/// itself (the launcher). srv then never copies, snapshots or migrates at boot:
155/// it checks read-only and exits [`NEEDS_PREPARE_EXIT`] when the data needs it.
156/// Without it (headless srv, `task dev:standalone`) srv prepares in-process.
157pub const SUPERVISOR_PREPARES_ENV: &str = "AGENTMUX_SUPERVISOR_PREPARES";
158
159/// srv's exit code after an `AGENTMUXSRV-NEEDS-PREPARE` line.
160pub const NEEDS_PREPARE_EXIT: i32 = 4;
161
162/// Prefix of the line srv writes, under [`SUPERVISOR_PREPARES_ENV`], before
163/// exiting because its data needs `migrate --prepare`.
164pub const NEEDS_PREPARE_PREFIX: &str = "AGENTMUXSRV-NEEDS-PREPARE";
165
166pub fn needs_prepare_line(reason: &str) -> String {
167    format!("{NEEDS_PREPARE_PREFIX} reason:{}", one_line(reason))
168}
169
170/// The reason of a `NEEDS_PREPARE_PREFIX` line; `None` for any other line.
171pub fn parse_needs_prepare_line(line: &str) -> Option<String> {
172    let rest = line.strip_prefix(NEEDS_PREPARE_PREFIX)?.trim_start();
173    Some(rest.strip_prefix("reason:").unwrap_or(rest).trim().to_string())
174}
175
176/// srv's exit code (and `migrate`'s) when another AgentMux of a different version holds the shared folder and this
177/// version's data needs preparing first: a refusal that does not clear until that AgentMux is closed, so a
178/// supervisor must not start it again by itself.
179pub const SHARED_FOLDER_HELD_EXIT: i32 = 5;
180
181/// Prefix of the line srv writes just before exiting [`SHARED_FOLDER_HELD_EXIT`].
182pub const SHARED_FOLDER_HELD_PREFIX: &str = "AGENTMUXSRV-SHARED-FOLDER-HELD";
183
184/// `AGENTMUXSRV-SHARED-FOLDER-HELD owner:<who> reason:<why the data needs preparing>`.
185pub fn shared_folder_held_line(owner: &str, reason: &str) -> String {
186    format!("{SHARED_FOLDER_HELD_PREFIX} owner:{} reason:{}", one_line(owner), one_line(reason))
187}
188
189/// The owner and the reason of a `SHARED_FOLDER_HELD_PREFIX` line; `None` for any other line.
190pub fn parse_shared_folder_held_line(line: &str) -> Option<(String, String)> {
191    let rest = line.strip_prefix(SHARED_FOLDER_HELD_PREFIX)?.trim_start();
192    let rest = rest.strip_prefix("owner:").unwrap_or(rest);
193    let (owner, reason) = rest.split_once(" reason:").unwrap_or((rest, ""));
194    Some((owner.trim().to_string(), reason.trim().to_string()))
195}
196
197/// srv's exit code when another srv already holds this data folder's `srv.lock`: one srv per set of
198/// databases (desktop app, `agentmux start`/`run`, a service). A refusal that does not clear until that
199/// server is closed, so a supervisor must not start it again by itself; the launcher shows the person a
200/// plain sentence instead of a failed start (task #49109).
201pub const DATA_DIR_HELD_EXIT: i32 = 6;
202
203/// Prefix of the line srv writes when a data-preparation step starts.
204pub const STEP_BEGIN_PREFIX: &str = "AGENTMUXSRV-STEP-BEGIN";
205/// Prefix of the line srv writes when that step ends.
206pub const STEP_END_PREFIX: &str = "AGENTMUXSRV-STEP-END";
207
208/// A parsed `STEP_BEGIN_PREFIX` line. Ids are code-chosen, without spaces.
209#[derive(Debug, PartialEq, Eq)]
210pub struct StepBegin {
211    pub id: String,
212    pub label: String,
213}
214
215/// A parsed `STEP_END_PREFIX` line.
216#[derive(Debug, PartialEq, Eq)]
217pub struct StepEnd {
218    pub id: String,
219    pub duration_ms: u64,
220    /// `false` when the step failed (`status:error` on the line).
221    pub ok: bool,
222}
223
224pub fn step_begin_line(id: &str, label: &str) -> String {
225    format!("{STEP_BEGIN_PREFIX} id:{id} label:{}", one_line(label))
226}
227
228pub fn step_end_line(id: &str, duration_ms: u64, ok: bool) -> String {
229    let status = if ok { "" } else { " status:error" };
230    format!("{STEP_END_PREFIX} id:{id} duration_ms:{duration_ms}{status}")
231}
232
233pub fn parse_step_begin_line(line: &str) -> Option<StepBegin> {
234    let rest = line.strip_prefix(STEP_BEGIN_PREFIX)?.trim_start().strip_prefix("id:")?;
235    let (id, rest) = rest.split_once(' ')?;
236    let label = rest.strip_prefix("label:").unwrap_or(rest).trim();
237    Some(StepBegin { id: id.to_string(), label: label.to_string() })
238}
239
240pub fn parse_step_end_line(line: &str) -> Option<StepEnd> {
241    let rest = line.strip_prefix(STEP_END_PREFIX)?.trim_start().strip_prefix("id:")?;
242    let (id, rest) = rest.split_once(' ')?;
243    let mut fields = rest.split_whitespace();
244    let duration_ms = fields.next()?.strip_prefix("duration_ms:")?.parse().ok()?;
245    let ok = !fields.any(|f| f == "status:error");
246    Some(StepEnd { id: id.to_string(), duration_ms, ok })
247}
248
249/// Prefix of the line srv writes to stderr just before applying one pending
250/// migration.
251pub const MIGRATION_BEGIN_PREFIX: &str = "AGENTMUXSRV-MIGRATION-BEGIN";
252/// Prefix of the line srv writes to stderr just after one migration applies
253/// successfully. (No `-END` line is written on failure — `up()` returning
254/// `Err` goes straight to `AGENTMUXSRV-MIGRATION-FAILED` and srv exits.)
255pub const MIGRATION_END_PREFIX: &str = "AGENTMUXSRV-MIGRATION-END";
256
257/// A parsed `MIGRATION_BEGIN_PREFIX` line.
258pub struct MigrationBegin {
259    pub id: String,
260    pub description: String,
261}
262
263/// A parsed `MIGRATION_END_PREFIX` line.
264pub struct MigrationEnd {
265    pub id: String,
266    pub duration_ms: u64,
267}
268
269/// Migration ids (`m.id()`, e.g. `"0020_agent_color_backfill"`) are a fixed,
270/// engineer-chosen identifier format with no spaces — never free text — so
271/// splitting `id:<id> description:<text>` on the first space is safe and
272/// exact, unlike `description` itself which is flattened via `one_line`.
273pub fn migration_begin_line(id: &str, description: &str) -> String {
274    format!("{} id:{} description:{}", MIGRATION_BEGIN_PREFIX, id, one_line(description))
275}
276
277pub fn migration_end_line(id: &str, duration_ms: u64) -> String {
278    format!("{} id:{} duration_ms:{}", MIGRATION_END_PREFIX, id, duration_ms)
279}
280
281/// Parse a `MIGRATION_BEGIN_PREFIX` line. `None` for any other line, or a
282/// begin line missing the `id:` field it cannot be meaningfully split
283/// without.
284pub fn parse_migration_begin_line(line: &str) -> Option<MigrationBegin> {
285    let rest = line.strip_prefix(MIGRATION_BEGIN_PREFIX)?.trim_start();
286    let rest = rest.strip_prefix("id:")?;
287    let (id, rest) = rest.split_once(' ')?;
288    let description = rest.strip_prefix("description:").unwrap_or(rest).trim();
289    Some(MigrationBegin { id: id.to_string(), description: description.to_string() })
290}
291
292/// Parse a `MIGRATION_END_PREFIX` line. `None` for any other line, a
293/// malformed one, or a non-numeric/missing `duration_ms:` field.
294pub fn parse_migration_end_line(line: &str) -> Option<MigrationEnd> {
295    let rest = line.strip_prefix(MIGRATION_END_PREFIX)?.trim_start();
296    let rest = rest.strip_prefix("id:")?;
297    let (id, rest) = rest.split_once(' ')?;
298    let ms_str = rest.trim().strip_prefix("duration_ms:")?;
299    let duration_ms = ms_str.trim().parse::<u64>().ok()?;
300    Some(MigrationEnd { id: id.to_string(), duration_ms })
301}
302
303/// Prefix of the line srv writes when the user chose "Upgrade & restart".
304pub const UPGRADE_PREFIX: &str = "AGENTMUXSRV-UPGRADE";
305
306/// What the launcher leaves in `updates/` of the data folder when the user
307/// answered No to the restart question, or the question lapsed: the version it
308/// asked about. srv reads it to stop saying "Restarting" (the launcher has no
309/// other way to tell it), so the user can start the upgrade again at once.
310pub const UPGRADE_DECLINED_FILE: &str = "declined.txt";
311
312/// Why the restart question ended without a restart: the second line of [`UPGRADE_DECLINED_FILE`]
313/// (the first is the version). srv says it in words to the user and to the agents that asked.
314#[derive(Debug, Clone, Copy, PartialEq, Eq)]
315pub enum Declined {
316    /// The user answered No.
317    No,
318    /// Nobody answered within the time the question is open: it closed itself, which counts as No.
319    TimedOut,
320    /// A Yes that came after the question had lapsed, or to an older question.
321    TooLate,
322}
323
324impl Declined {
325    pub fn as_str(self) -> &'static str {
326        match self {
327            Declined::No => "no",
328            Declined::TimedOut => "timed_out",
329            Declined::TooLate => "too_late",
330        }
331    }
332
333    pub fn parse(s: &str) -> Option<Self> {
334        [Declined::No, Declined::TimedOut, Declined::TooLate].into_iter().find(|d| d.as_str() == s.trim())
335    }
336}
337
338/// The contents of [`UPGRADE_DECLINED_FILE`]: the version, then why.
339pub fn declined_text(version: &str, why: Declined) -> String {
340    format!("{version}\n{}\n", why.as_str())
341}
342
343/// The version and the reason a [`UPGRADE_DECLINED_FILE`] holds. A file with only a version (an
344/// older launcher's) has no reason.
345pub fn parse_declined(text: &str) -> (&str, Option<Declined>) {
346    let mut lines = text.lines();
347    let version = lines.next().unwrap_or("").trim();
348    (version, lines.next().and_then(Declined::parse))
349}
350
351/// Where the Linux launcher leaves why a `.deb`/`.rpm` upgrade didn't happen,
352/// in `updates/<version>/` of the data folder: JSON `{"version": "<v>", "error":
353/// "<one line>"}`. Left when the password was refused or unavailable, the file
354/// failed its checks, or the install failed (the waiter that restarts the old
355/// version writes it). srv shows it in the version panel.
356pub const INSTALL_RESULT_FILE: &str = "install-result.json";
357
358/// What an upgrade restarts into.
359#[derive(Debug, Clone, PartialEq, Eq)]
360pub enum UpgradeTarget {
361    /// A portable's new folder: start this launcher.
362    Launcher(std::path::PathBuf),
363    /// A `setup.exe` install: run this installer, then start AgentMux again.
364    /// `sha256` (lowercase hex) is the release's digest: the launcher checks
365    /// it again on the very file it runs.
366    Installer { installer: std::path::PathBuf, sha256: String },
367}
368
369/// A parsed `UPGRADE_PREFIX` line: upgrade to `version` through `target`.
370#[derive(Debug, Clone, PartialEq, Eq)]
371pub struct UpgradeRequest {
372    pub version: String,
373    pub target: UpgradeTarget,
374    /// srv says the restart is already decided (`confirmed:1`): a person's own click or turn, or an approved
375    /// request whose in-app countdown ran out with no veto. The launcher then asks nothing more.
376    pub confirmed: bool,
377}
378
379/// The path goes last: it can hold spaces. `confirmed` adds `confirmed:1` after the version: the restart is
380/// already decided, so the launcher asks nothing more ([`UpgradeRequest::confirmed`]).
381pub fn upgrade_line(version: &str, target: &UpgradeTarget, confirmed: bool) -> String {
382    let decided = if confirmed { " confirmed:1" } else { "" };
383    match target {
384        UpgradeTarget::Launcher(p) => format!("{} version:{}{} launcher:{}", UPGRADE_PREFIX, version, decided, p.display()),
385        UpgradeTarget::Installer { installer, sha256 } => {
386            format!("{} version:{}{} sha256:{} installer:{}", UPGRADE_PREFIX, version, decided, sha256, installer.display())
387        }
388    }
389}
390
391/// Parse an `UPGRADE_PREFIX` line. `None` for any other line, or one missing
392/// a field (an installer needs its 64-hex-digit `sha256:`). A `confirmed:1`
393/// token after `version:` sets [`UpgradeRequest::confirmed`] (any other value of it does not); an
394/// `approved:<how>:<id>` token is skipped.
395pub fn parse_upgrade_line(line: &str) -> Option<UpgradeRequest> {
396    let rest = line.strip_prefix(UPGRADE_PREFIX)?.trim_start();
397    let (version, rest) = rest.strip_prefix("version:")?.split_once(' ')?;
398    let mut rest = rest.trim_start();
399    let mut confirmed = false;
400    // Tokens that may come before the target, in either order: `confirmed:<1>`, and `approved:<how>:<id>` (who
401    // approved the restart; the launcher doesn't use it).
402    loop {
403        if let Some(c) = rest.strip_prefix("confirmed:") {
404            let (value, after) = c.split_once(' ')?;
405            confirmed = value == "1";
406            rest = after.trim_start();
407        } else if let Some(approved) = rest.strip_prefix("approved:") {
408            rest = approved.split_once(' ')?.1.trim_start();
409        } else {
410            break;
411        }
412    }
413    let target = if let Some(p) = rest.strip_prefix("launcher:") {
414        UpgradeTarget::Launcher(p.trim().into())
415    } else {
416        let (sha256, rest) = rest.strip_prefix("sha256:")?.split_once(' ')?;
417        if sha256.len() != 64 || !sha256.bytes().all(|b| b.is_ascii_hexdigit()) {
418            return None;
419        }
420        let installer = rest.trim_start().strip_prefix("installer:")?.trim().into();
421        UpgradeTarget::Installer { installer, sha256: sha256.to_ascii_lowercase() }
422    };
423    let empty = match &target {
424        UpgradeTarget::Launcher(p) | UpgradeTarget::Installer { installer: p, .. } => p.as_os_str().is_empty(),
425    };
426    if version.is_empty() || empty {
427        return None;
428    }
429    Some(UpgradeRequest { version: version.to_string(), target, confirmed })
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435
436    #[test]
437    fn a_decline_file_names_the_version_and_why_and_an_older_one_has_no_reason() {
438        for why in [Declined::No, Declined::TimedOut, Declined::TooLate] {
439            assert_eq!(parse_declined(&declined_text("0.60.35", why)), ("0.60.35", Some(why)));
440        }
441        assert_eq!(parse_declined("0.60.35\n"), ("0.60.35", None));
442        assert_eq!(parse_declined("0.60.35\nsomething else\n"), ("0.60.35", None));
443        assert_eq!(parse_declined(""), ("", None));
444    }
445
446    #[test]
447    fn the_shared_folder_held_line_round_trips_on_one_line() {
448        let line = shared_folder_held_line("AgentMux 0.60.27 (stable)", "29 migration(s) pending,\nstarting with 0002_block_zones_v1");
449        assert!(!line.contains('\n'), "{line}");
450        let (owner, reason) = parse_shared_folder_held_line(&line).unwrap();
451        assert_eq!(owner, "AgentMux 0.60.27 (stable)");
452        assert_eq!(reason, "29 migration(s) pending, | starting with 0002_block_zones_v1");
453        assert!(parse_shared_folder_held_line("agentmux-srv: something else").is_none());
454    }
455
456    #[test]
457    fn estart_line_round_trips() {
458        let e = Estart {
459            ws_endpoint: "127.0.0.1:61001".into(),
460            web_endpoint: "127.0.0.1:61002".into(),
461            version: "0.59.34".into(),
462            build_time: "20261020.101010".into(),
463            instance_id: "inst-1".into(),
464            pending_migrations: 2,
465        };
466        let line = estart_line(&e);
467        assert_eq!(
468            line,
469            "AGENTMUXSRV-ESTART ws:127.0.0.1:61001 web:127.0.0.1:61002 version:0.59.34 buildtime:20261020.101010 instance:inst-1 pending_migrations:2"
470        );
471        assert_eq!(parse_estart_line(&line), Some(e));
472        assert_eq!(parse_estart_line("AGENTMUXSRV-MIGRATING migrations:1"), None);
473        let bare = parse_estart_line("AGENTMUXSRV-ESTART ws:127.0.0.1:1").unwrap();
474        assert_eq!((bare.ws_endpoint.as_str(), bare.pending_migrations), ("127.0.0.1:1", 0));
475    }
476
477    #[test]
478    fn step_lines_round_trip_and_stay_apart_from_migration_lines() {
479        let begin = step_begin_line("copy_previous_version", "Copying your data\nfrom 0.59.33");
480        assert_eq!(
481            parse_step_begin_line(&begin),
482            Some(StepBegin { id: "copy_previous_version".into(), label: "Copying your data | from 0.59.33".into() })
483        );
484        let end = step_end_line("backup", 812, true);
485        assert_eq!(parse_step_end_line(&end), Some(StepEnd { id: "backup".into(), duration_ms: 812, ok: true }));
486        let failed = step_end_line("copy_previous_version", 40, false);
487        assert_eq!(failed, "AGENTMUXSRV-STEP-END id:copy_previous_version duration_ms:40 status:error");
488        assert_eq!(parse_step_end_line(&failed).map(|e| e.ok), Some(false));
489        assert_eq!(parse_step_begin_line(&migration_begin_line("0001_x", "y")), None);
490        assert!(parse_migration_begin_line(&begin).is_none());
491        assert!(!is_migrating_line(&begin));
492        assert_eq!(parse_step_end_line("AGENTMUXSRV-STEP-END id:backup duration_ms:x"), None);
493    }
494
495    #[test]
496    fn needs_prepare_line_round_trips() {
497        let line = needs_prepare_line("2 migration(s) pending,\nfirst 0038_x");
498        assert_eq!(parse_needs_prepare_line(&line).as_deref(), Some("2 migration(s) pending, | first 0038_x"));
499        assert_eq!(parse_needs_prepare_line(&migrating_line("migrations", 2)), None);
500        assert!(parse_migration_failed_line(&line).is_none());
501    }
502
503    #[test]
504    fn migrating_and_event_lines() {
505        assert_eq!(migrating_line("migrations", 3), "AGENTMUXSRV-MIGRATING migrations:3");
506        assert!(is_migrating_line(&migrating_line("copying-previous-version", "0.59.33")));
507        assert!(!is_migrating_line("AGENTMUXSRV-MIGRATION-BEGIN id:x description:y"));
508        assert_eq!(parse_event_line(r#"AGENTMUXSRV-EVENT:{"a":1}"#), Some(r#"{"a":1}"#));
509        assert_eq!(parse_event_line("AGENTMUXSRV-ESTART ws:x"), None);
510    }
511
512    #[test]
513    fn an_approved_token_before_the_target_is_skipped() {
514        let sha = "cd".repeat(32);
515        let launcher = parse_upgrade_line("AGENTMUXSRV-UPGRADE version:0.60.8 approved:agent:agenty launcher:/opt/a b/agentmux.sh").unwrap();
516        assert_eq!(launcher.target, UpgradeTarget::Launcher("/opt/a b/agentmux.sh".into()));
517        let line = format!("AGENTMUXSRV-UPGRADE version:0.60.8 approved:person:win-1 sha256:{sha} installer:/var/u s/AgentMux_0.60.8_amd64.deb");
518        let installer = parse_upgrade_line(&line).unwrap();
519        assert_eq!(installer.version, "0.60.8");
520        assert_eq!(installer.target, UpgradeTarget::Installer { installer: "/var/u s/AgentMux_0.60.8_amd64.deb".into(), sha256: sha });
521        // The token alone is not a target.
522        assert_eq!(parse_upgrade_line("AGENTMUXSRV-UPGRADE version:0.60.8 approved:agent:agenty"), None);
523        assert_eq!(parse_upgrade_line("AGENTMUXSRV-UPGRADE version:0.60.8 approved:agent:agenty "), None);
524    }
525
526    #[test]
527    fn a_confirmed_restart_says_so_on_the_line_and_only_with_the_one_value() {
528        let sha = "ab".repeat(32);
529        let setup = UpgradeTarget::Installer { installer: r"C:\Users\A User\updates\0.60.35\AgentMux-0.60.35-x64-setup.exe".into(), sha256: sha.clone() };
530        let launcher = UpgradeTarget::Launcher("/opt/a b/agentmux.sh".into());
531        for target in [setup, launcher] {
532            let line = upgrade_line("0.60.35", &target, true);
533            assert!(line.starts_with("AGENTMUXSRV-UPGRADE version:0.60.35 confirmed:1 "), "{line}");
534            assert_eq!(parse_upgrade_line(&line), Some(UpgradeRequest { version: "0.60.35".into(), target: target.clone(), confirmed: true }));
535            // Not said, not confirmed: the launcher then asks as it always did.
536            assert!(!upgrade_line("0.60.35", &target, false).contains("confirmed"));
537            assert!(!parse_upgrade_line(&upgrade_line("0.60.35", &target, false)).unwrap().confirmed);
538        }
539        // Only `confirmed:1` confirms, whatever else it says, and it may sit beside the `approved:` token in either order.
540        let line = format!("AGENTMUXSRV-UPGRADE version:0.60.35 confirmed:0 sha256:{sha} installer:/u/a.deb");
541        assert!(!parse_upgrade_line(&line).unwrap().confirmed);
542        let line = format!("AGENTMUXSRV-UPGRADE version:0.60.35 confirmed:yes sha256:{sha} installer:/u/a.deb");
543        assert!(!parse_upgrade_line(&line).unwrap().confirmed);
544        let line = format!("AGENTMUXSRV-UPGRADE version:0.60.35 approved:agent:agenty confirmed:1 sha256:{sha} installer:/u/a.deb");
545        assert!(parse_upgrade_line(&line).unwrap().confirmed);
546        let line = format!("AGENTMUXSRV-UPGRADE version:0.60.35 confirmed:1 approved:agent:agenty sha256:{sha} installer:/u/a.deb");
547        assert!(parse_upgrade_line(&line).unwrap().confirmed);
548        // The token alone is not a target.
549        assert_eq!(parse_upgrade_line("AGENTMUXSRV-UPGRADE version:0.60.35 confirmed:1 "), None);
550    }
551
552    #[test]
553    fn upgrade_line_round_trips_a_path_with_spaces() {
554        let path = std::path::Path::new(r"C:\Users\A User\Apps\agentmux-0.59.27-x64-portable\agentmux.exe");
555        let target = UpgradeTarget::Launcher(path.to_path_buf());
556        let line = upgrade_line("0.59.27", &target, false);
557        assert_eq!(parse_upgrade_line(&line), Some(UpgradeRequest { version: "0.59.27".into(), target, confirmed: false }));
558        let sha = "ab".repeat(32);
559        let setup = UpgradeTarget::Installer {
560            installer: r"C:\Users\A User\updates\0.59.27\AgentMux-0.59.27-x64-setup.exe".into(),
561            sha256: sha.clone(),
562        };
563        assert_eq!(
564            parse_upgrade_line(&upgrade_line("0.59.27", &setup, false)),
565            Some(UpgradeRequest { version: "0.59.27".into(), target: setup, confirmed: false })
566        );
567        assert_eq!(parse_upgrade_line(&format!("AGENTMUXSRV-UPGRADE version:0.59.27 sha256:{sha} installer:")), None);
568        // An installer without its digest, or with a malformed one, is refused.
569        assert_eq!(parse_upgrade_line("AGENTMUXSRV-UPGRADE version:0.59.27 installer:C:/u/setup.exe"), None);
570        assert_eq!(parse_upgrade_line("AGENTMUXSRV-UPGRADE version:0.59.27 sha256:ab installer:C:/u/setup.exe"), None);
571        assert_eq!(parse_upgrade_line("AGENTMUXSRV-UPGRADE version:0.59.27"), None);
572        assert_eq!(parse_upgrade_line("AGENTMUXSRV-UPGRADE launcher:C:/x/agentmux.exe"), None);
573        assert_eq!(parse_upgrade_line("AGENTMUXSRV-MIGRATING migrations:1"), None);
574    }
575
576    #[test]
577    fn line_is_prefixed_and_single_line() {
578        let line = migration_failed_line("migration 0007 failed:\r\n  FOREIGN KEY constraint failed\n");
579        assert_eq!(
580            line,
581            "AGENTMUXSRV-MIGRATION-FAILED error:migration 0007 failed: | FOREIGN KEY constraint failed"
582        );
583        assert!(!line.contains('\n'));
584    }
585
586    #[test]
587    fn round_trips_through_parse() {
588        let msg = "run_pending_migrations: open shared store: disk I/O error";
589        assert_eq!(parse_migration_failed_line(&migration_failed_line(msg)).as_deref(), Some(msg));
590    }
591
592    #[test]
593    fn parse_tolerates_missing_error_field() {
594        assert_eq!(
595            parse_migration_failed_line("AGENTMUXSRV-MIGRATION-FAILED something broke").as_deref(),
596            Some("something broke")
597        );
598    }
599
600    #[test]
601    fn parse_never_returns_empty_message() {
602        assert_eq!(parse_migration_failed_line("AGENTMUXSRV-MIGRATION-FAILED").as_deref(), Some("unknown error"));
603        assert_eq!(parse_migration_failed_line("AGENTMUXSRV-MIGRATION-FAILED error:").as_deref(), Some("unknown error"));
604    }
605
606    #[test]
607    fn parse_ignores_other_protocol_lines() {
608        assert_eq!(parse_migration_failed_line("AGENTMUXSRV-MIGRATING migrations:3"), None);
609        assert_eq!(parse_migration_failed_line("AGENTMUXSRV-ESTART ws:127.0.0.1:1 web:127.0.0.1:2"), None);
610        assert_eq!(parse_migration_failed_line("plain stderr noise"), None);
611    }
612
613    #[test]
614    fn migrating_prefix_is_not_a_prefix_of_failed() {
615        // Both start with "AGENTMUXSRV-MIGRATI"; the supervisors check
616        // `starts_with` for each, so neither may be a prefix of the other.
617        assert!(!MIGRATION_FAILED_PREFIX.starts_with("AGENTMUXSRV-MIGRATING"));
618        assert!(!"AGENTMUXSRV-MIGRATING".starts_with(MIGRATION_FAILED_PREFIX));
619    }
620
621    #[test]
622    fn none_of_the_four_migration_prefixes_are_a_prefix_of_another() {
623        // All four share "AGENTMUXSRV-MIGRAT"; every supervisor matches with
624        // `starts_with`/`strip_prefix`, so a false-positive prefix match
625        // would misroute a real line.
626        let all = [
627            "AGENTMUXSRV-MIGRATING",
628            MIGRATION_FAILED_PREFIX,
629            MIGRATION_BEGIN_PREFIX,
630            MIGRATION_END_PREFIX,
631        ];
632        for a in all {
633            for b in all {
634                if a == b { continue; }
635                assert!(!a.starts_with(b), "{a:?} must not start with {b:?}");
636            }
637        }
638    }
639
640    #[test]
641    fn begin_line_round_trips_through_parse() {
642        let line = migration_begin_line("0020_agent_color_backfill", "backfill default agent colors");
643        let parsed = parse_migration_begin_line(&line).expect("must parse");
644        assert_eq!(parsed.id, "0020_agent_color_backfill");
645        assert_eq!(parsed.description, "backfill default agent colors");
646    }
647
648    #[test]
649    fn begin_line_flattens_a_multiline_description() {
650        let line = migration_begin_line("0007_x", "line one\nline two");
651        assert!(!line.contains('\n'));
652        assert_eq!(parse_migration_begin_line(&line).unwrap().description, "line one | line two");
653    }
654
655    #[test]
656    fn end_line_round_trips_through_parse() {
657        let line = migration_end_line("0020_agent_color_backfill", 147);
658        let parsed = parse_migration_end_line(&line).expect("must parse");
659        assert_eq!(parsed.id, "0020_agent_color_backfill");
660        assert_eq!(parsed.duration_ms, 147);
661    }
662
663    #[test]
664    fn begin_and_end_parsers_ignore_other_protocol_lines_and_each_other() {
665        assert!(parse_migration_begin_line("AGENTMUXSRV-MIGRATING migrations:3").is_none());
666        assert!(parse_migration_begin_line("AGENTMUXSRV-ESTART ws:x web:y").is_none());
667        assert!(parse_migration_begin_line(&migration_end_line("0007_x", 5)).is_none());
668        assert!(parse_migration_end_line(&migration_begin_line("0007_x", "d")).is_none());
669    }
670
671    #[test]
672    fn malformed_begin_and_end_lines_do_not_panic() {
673        assert!(parse_migration_begin_line(MIGRATION_BEGIN_PREFIX).is_none());
674        assert!(parse_migration_begin_line(&format!("{MIGRATION_BEGIN_PREFIX} garbage")).is_none());
675        assert!(parse_migration_end_line(MIGRATION_END_PREFIX).is_none());
676        assert!(parse_migration_end_line(&format!("{MIGRATION_END_PREFIX} id:0007_x duration_ms:notanumber")).is_none());
677    }
678}