agentty 0.14.0

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
//! Version discovery and auto-update helpers.

use std::process::Command;
use std::sync::Arc;

use semver::Version;
use serde::Deserialize;
use tracing::{debug, warn};

const AGENTTY_NPM_PACKAGE: &str = "agentty";
const NPM_REGISTRY_LATEST_URL: &str = "https://registry.npmjs.org/agentty/latest";

/// Typed error returned by version infrastructure operations.
///
/// Wraps subprocess and I/O failures so callers can distinguish version
/// command errors without parsing opaque strings.
#[derive(Debug, thiserror::Error)]
pub(crate) enum VersionError {
    /// A version command subprocess failed to launch or produce output.
    #[error("Failed to run `{command}`: {message}")]
    CommandSpawn {
        /// The program that was being launched (e.g. `"npm"`, `"curl"`).
        command: String,
        /// Human-readable detail from the underlying I/O error.
        message: String,
    },

    /// A version command subprocess exited with a non-zero status.
    #[error("`{command}` exited with status {status}")]
    NonZeroExit {
        /// The program that exited unsuccessfully.
        command: String,
        /// Stringified process exit status.
        status: String,
        /// Combined stderr output from the failed process.
        stderr: String,
    },

    /// A successful command returned a response that could not be decoded.
    #[error("Failed to parse `{provider}` version response")]
    ResponseParse {
        /// Command or service whose response was invalid.
        provider: &'static str,
    },
}

/// Minimal command output needed by version-resolution logic.
#[derive(Debug)]
struct VersionCommandOutput {
    status: String,
    stderr: String,
    success: bool,
    stdout: String,
}

impl VersionCommandOutput {
    /// Returns stdout for a successful command or a contextual exit error.
    fn successful_stdout(self, command: &str) -> Result<String, VersionError> {
        if self.success {
            return Ok(self.stdout);
        }

        Err(VersionError::NonZeroExit {
            command: command.to_string(),
            status: self.status,
            stderr: self.stderr,
        })
    }
}

/// External command boundary for npm/curl version discovery commands.
#[cfg_attr(test, mockall::automock)]
trait VersionCommandRunner: Send + Sync {
    /// Runs one command and returns normalized output for parsing.
    fn run_command(
        &self,
        program: &str,
        args: Vec<String>,
    ) -> Result<VersionCommandOutput, VersionError>;
}

/// Production command runner backed by [`std::process::Command`].
struct RealVersionCommandRunner;

impl VersionCommandRunner for RealVersionCommandRunner {
    fn run_command(
        &self,
        program: &str,
        args: Vec<String>,
    ) -> Result<VersionCommandOutput, VersionError> {
        let output = Command::new(program)
            .args(&args)
            .output()
            .map_err(|error| VersionError::CommandSpawn {
                command: program.to_string(),
                message: error.to_string(),
            })?;

        Ok(VersionCommandOutput {
            status: output.status.to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            success: output.status.success(),
            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
        })
    }
}

/// External command boundary for running `npm i -g agentty@latest`.
///
/// The production implementation shells out via [`std::process::Command`]
/// inside `spawn_blocking`. Tests inject a [`MockUpdateRunner`] to verify
/// the update flow without subprocess execution.
#[cfg_attr(test, mockall::automock)]
pub(crate) trait UpdateRunner: Send + Sync {
    /// Runs the update command and returns combined stdout on success or a
    /// typed version error on failure.
    fn run_update(&self, command: &str, args: Vec<String>) -> Result<String, VersionError>;
}

/// Production update runner backed by [`std::process::Command`].
#[cfg(not(test))]
pub(crate) struct RealUpdateRunner;

#[cfg(not(test))]
impl UpdateRunner for RealUpdateRunner {
    fn run_update(&self, command: &str, args: Vec<String>) -> Result<String, VersionError> {
        let command_runner = RealVersionCommandRunner;
        let output = command_runner.run_command(command, args)?;

        output.successful_stdout(command)
    }
}

/// Runs `npm i -g agentty@latest` synchronously via the provided
/// [`UpdateRunner`].
pub(crate) fn run_npm_update_sync(
    update_runner: &dyn UpdateRunner,
) -> Result<String, VersionError> {
    update_runner.run_update(
        "npm",
        vec![
            "i".to_string(),
            "-g".to_string(),
            "agentty@latest".to_string(),
        ],
    )
}

#[derive(Debug, Deserialize)]
struct NpmRegistryLatestResponse {
    version: String,
}

/// Returns the latest npmjs version tag (`vX.Y.Z`) for `agentty`.
pub async fn latest_npm_version_tag() -> Option<String> {
    latest_npm_version_tag_with_runner(Arc::new(RealVersionCommandRunner)).await
}

/// Runs latest-version discovery through an injected command boundary.
async fn latest_npm_version_tag_with_runner(
    command_runner: Arc<dyn VersionCommandRunner>,
) -> Option<String> {
    let result = tokio::task::spawn_blocking(move || {
        fetch_latest_npm_version_tag_sync(command_runner.as_ref())
    })
    .await;

    latest_version_from_task_result(result)
}

/// Converts the blocking lookup task result while retaining diagnostics.
fn latest_version_from_task_result(
    result: Result<Result<String, VersionError>, tokio::task::JoinError>,
) -> Option<String> {
    match result {
        Ok(Ok(version_tag)) => Some(version_tag),
        Ok(Err(error)) => {
            warn!(%error, "Failed to discover latest npm version");

            None
        }
        Err(error) => {
            warn!(%error, "Latest-version task failed to join");

            None
        }
    }
}

/// Returns `true` when `candidate_version` is newer than `current_version`.
pub(crate) fn is_newer_than_current_version(
    current_version: &str,
    candidate_version: &str,
) -> bool {
    let Some(current_version) = parse_version(current_version) else {
        return false;
    };

    let Some(candidate_version) = parse_version(candidate_version) else {
        return false;
    };

    candidate_version > current_version
}

fn fetch_latest_npm_version_tag_sync(
    command_runner: &dyn VersionCommandRunner,
) -> Result<String, VersionError> {
    match fetch_latest_version_with_npm_cli(command_runner) {
        Ok(latest_version) => return Ok(version_tag(&latest_version)),
        Err(error) => {
            debug!(%error, "npm CLI version lookup failed; trying registry fallback");
        }
    }

    let latest_version = fetch_latest_version_with_registry_curl(command_runner)?;

    Ok(version_tag(&latest_version))
}

fn fetch_latest_version_with_npm_cli(
    command_runner: &dyn VersionCommandRunner,
) -> Result<Version, VersionError> {
    let output = command_runner.run_command(
        "npm",
        vec![
            "view".to_string(),
            AGENTTY_NPM_PACKAGE.to_string(),
            "version".to_string(),
            "--json".to_string(),
        ],
    )?;
    let stdout = output.successful_stdout("npm")?;

    parse_npm_cli_version_response(&stdout).ok_or(VersionError::ResponseParse { provider: "npm" })
}

fn parse_npm_cli_version_response(response: &str) -> Option<Version> {
    let version: String = serde_json::from_str(response).ok()?;

    parse_version(&version)
}

fn fetch_latest_version_with_registry_curl(
    command_runner: &dyn VersionCommandRunner,
) -> Result<Version, VersionError> {
    let output = command_runner.run_command(
        "curl",
        vec!["-fsSL".to_string(), NPM_REGISTRY_LATEST_URL.to_string()],
    )?;
    let stdout = output.successful_stdout("curl")?;

    parse_registry_latest_response(&stdout).ok_or(VersionError::ResponseParse {
        provider: "npm registry",
    })
}

fn parse_registry_latest_response(response: &str) -> Option<Version> {
    let payload: NpmRegistryLatestResponse = serde_json::from_str(response).ok()?;

    parse_version(&payload.version)
}

fn parse_version(version: &str) -> Option<Version> {
    let normalized_version = version.strip_prefix('v').unwrap_or(version);

    Version::parse(normalized_version).ok()
}

fn version_tag(version: &Version) -> String {
    format!("v{version}")
}

#[cfg(test)]
mod tests {
    use std::os::unix::fs::PermissionsExt;

    use tempfile::tempdir;

    use super::*;

    const LATEST_VERSION_CHILD_ENV: &str = "AGENTTY_TEST_LATEST_VERSION_CHILD";

    #[test]
    fn test_parse_version_accepts_prefixed_version() {
        // Arrange
        let version = "v1.2.3";

        // Act
        let parsed_version = parse_version(version);

        // Assert
        assert_eq!(parsed_version, Some(Version::new(1, 2, 3)));
    }

    #[test]
    fn test_parse_version_rejects_invalid_version() {
        // Arrange
        let version = "vnext";

        // Act
        let parsed_version = parse_version(version);

        // Assert
        assert_eq!(parsed_version, None);
    }

    #[test]
    fn test_parse_npm_cli_version_response_accepts_json_string() {
        // Arrange
        let response = "\"0.1.14\"";

        // Act
        let parsed_version = parse_npm_cli_version_response(response);

        // Assert
        assert_eq!(parsed_version, Some(Version::new(0, 1, 14)));
    }

    #[test]
    fn test_parse_registry_latest_response_extracts_version() {
        // Arrange
        let response = r#"{"name":"agentty","version":"0.1.14"}"#;

        // Act
        let parsed_version = parse_registry_latest_response(response);

        // Assert
        assert_eq!(parsed_version, Some(Version::new(0, 1, 14)));
    }

    #[test]
    fn test_version_tag_prefixes_semver_with_v() {
        // Arrange
        let version = Version::new(0, 1, 14);

        // Act
        let version_tag = version_tag(&version);

        // Assert
        assert_eq!(version_tag, "v0.1.14");
    }

    #[test]
    fn test_fetch_latest_npm_version_tag_sync_prefers_npm_cli_result() {
        // Arrange
        let mut command_runner = MockVersionCommandRunner::new();
        command_runner
            .expect_run_command()
            .times(1)
            .returning(|program, args| {
                assert_eq!(program, "npm");
                assert_eq!(
                    args,
                    vec![
                        "view".to_string(),
                        AGENTTY_NPM_PACKAGE.to_string(),
                        "version".to_string(),
                        "--json".to_string(),
                    ]
                );

                Ok(VersionCommandOutput {
                    status: "exit status: 0".to_string(),
                    stderr: String::new(),
                    success: true,
                    stdout: "\"0.2.0\"".to_string(),
                })
            });

        // Act
        let latest_version_tag = fetch_latest_npm_version_tag_sync(&command_runner);

        // Assert
        assert_eq!(latest_version_tag.expect("lookup should succeed"), "v0.2.0");
    }

    #[test]
    fn test_fetch_latest_npm_version_tag_sync_falls_back_to_registry_curl() {
        // Arrange
        let mut command_runner = MockVersionCommandRunner::new();
        command_runner
            .expect_run_command()
            .times(1)
            .returning(|program, args| {
                assert_eq!(program, "npm");
                assert_eq!(
                    args,
                    vec![
                        "view".to_string(),
                        AGENTTY_NPM_PACKAGE.to_string(),
                        "version".to_string(),
                        "--json".to_string(),
                    ]
                );

                Ok(VersionCommandOutput {
                    status: "exit status: 1".to_string(),
                    stderr: "npm unavailable".to_string(),
                    success: false,
                    stdout: String::new(),
                })
            });
        command_runner
            .expect_run_command()
            .times(1)
            .returning(|program, args| {
                assert_eq!(program, "curl");
                assert_eq!(
                    args,
                    vec!["-fsSL".to_string(), NPM_REGISTRY_LATEST_URL.to_string(),]
                );

                Ok(VersionCommandOutput {
                    status: "exit status: 0".to_string(),
                    stderr: String::new(),
                    success: true,
                    stdout: r#"{"name":"agentty","version":"0.3.1"}"#.to_string(),
                })
            });

        // Act
        let latest_version_tag = fetch_latest_npm_version_tag_sync(&command_runner);

        // Assert
        assert_eq!(
            latest_version_tag.expect("fallback should succeed"),
            "v0.3.1"
        );
    }

    #[test]
    fn test_fetch_latest_npm_version_tag_sync_preserves_fallback_failure() {
        // Arrange
        let mut command_runner = MockVersionCommandRunner::new();
        command_runner
            .expect_run_command()
            .times(2)
            .returning(|program, _| {
                Ok(VersionCommandOutput {
                    status: "exit status: 7".to_string(),
                    stderr: format!("{program} unavailable"),
                    success: false,
                    stdout: String::new(),
                })
            });

        // Act
        let error = fetch_latest_npm_version_tag_sync(&command_runner)
            .expect_err("both lookup commands should fail");

        // Assert
        assert!(matches!(
            error,
            VersionError::NonZeroExit {
                command,
                status,
                stderr,
            } if command == "curl"
                && status == "exit status: 7"
                && stderr == "curl unavailable"
        ));
    }

    #[test]
    fn test_fetch_latest_npm_version_tag_sync_reports_invalid_fallback_response() {
        // Arrange
        let mut command_runner = MockVersionCommandRunner::new();
        command_runner
            .expect_run_command()
            .times(2)
            .returning(|_, _| {
                Ok(VersionCommandOutput {
                    status: "exit status: 0".to_string(),
                    stderr: String::new(),
                    success: true,
                    stdout: "not-json".to_string(),
                })
            });

        // Act
        let error = fetch_latest_npm_version_tag_sync(&command_runner)
            .expect_err("invalid fallback response should fail");

        // Assert
        assert!(matches!(
            error,
            VersionError::ResponseParse {
                provider: "npm registry"
            }
        ));
    }

    #[tokio::test]
    async fn test_latest_npm_version_tag_uses_injected_runner_across_blocking_boundary() {
        // Arrange
        let mut command_runner = MockVersionCommandRunner::new();
        command_runner
            .expect_run_command()
            .times(1)
            .returning(|program, _| {
                assert_eq!(program, "npm");

                Ok(VersionCommandOutput {
                    status: "exit status: 0".to_string(),
                    stderr: String::new(),
                    success: true,
                    stdout: "\"0.5.0\"".to_string(),
                })
            });

        // Act
        let version_tag = latest_npm_version_tag_with_runner(Arc::new(command_runner)).await;

        // Assert
        assert_eq!(version_tag.as_deref(), Some("v0.5.0"));
    }

    #[tokio::test]
    async fn test_latest_npm_version_tag_uses_isolated_real_runner() {
        if std::env::var_os(LATEST_VERSION_CHILD_ENV).is_some() {
            // Arrange
            let expected_version_tag = "v0.6.0";

            // Act
            let version_tag = latest_npm_version_tag().await;

            // Assert
            assert_eq!(version_tag.as_deref(), Some(expected_version_tag));

            return;
        }

        // Arrange
        let command_dir = tempdir().expect("failed to create fake command directory");
        let npm_path = command_dir.path().join("npm");
        std::fs::write(&npm_path, "#!/bin/sh\nprintf '\"0.6.0\"'\n")
            .expect("failed to write fake npm command");
        let mut permissions = std::fs::metadata(&npm_path)
            .expect("failed to load fake npm metadata")
            .permissions();
        permissions.set_mode(0o755);
        std::fs::set_permissions(&npm_path, permissions)
            .expect("failed to make fake npm executable");
        let current_test_binary =
            std::env::current_exe().expect("failed to resolve current test binary");

        // Act
        let output = tokio::process::Command::new(current_test_binary)
            .arg("--exact")
            .arg("infra::version::tests::test_latest_npm_version_tag_uses_isolated_real_runner")
            .arg("--nocapture")
            .env("PATH", command_dir.path())
            .env(LATEST_VERSION_CHILD_ENV, "1")
            .output()
            .await
            .expect("failed to run isolated latest-version test");

        // Assert
        assert!(
            output.status.success(),
            "isolated latest-version test failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    #[test]
    fn test_fetch_latest_npm_version_tag_sync_preserves_command_errors() {
        // Arrange
        let mut command_runner = MockVersionCommandRunner::new();
        command_runner
            .expect_run_command()
            .times(2)
            .returning(|program, _| {
                Err(VersionError::CommandSpawn {
                    command: program.to_string(),
                    message: "not installed".to_string(),
                })
            });

        // Act
        let error = fetch_latest_npm_version_tag_sync(&command_runner)
            .expect_err("fallback command error should propagate");

        // Assert
        assert!(matches!(
            error,
            VersionError::CommandSpawn { command, message }
                if command == "curl" && message == "not installed"
        ));
    }

    #[test]
    fn test_real_version_command_runner_captures_process_output() {
        // Arrange
        let command_runner = RealVersionCommandRunner;

        // Act
        let output = command_runner
            .run_command(
                "sh",
                vec![
                    "-c".to_string(),
                    "printf '0.4.0'; printf 'notice' >&2".to_string(),
                ],
            )
            .expect("command should run");

        // Assert
        assert!(output.success);
        assert_eq!(output.stdout, "0.4.0");
        assert_eq!(output.stderr, "notice");
        assert!(output.status.contains('0'));
    }

    #[test]
    fn test_real_version_command_runner_reports_spawn_failure() {
        // Arrange
        let command_runner = RealVersionCommandRunner;

        // Act
        let error = command_runner
            .run_command("agentty-command-that-does-not-exist", Vec::new())
            .expect_err("missing command should fail");

        // Assert
        assert!(matches!(
            error,
            VersionError::CommandSpawn { command, message }
                if command == "agentty-command-that-does-not-exist" && !message.is_empty()
        ));
    }

    #[tokio::test]
    async fn test_latest_version_task_result_preserves_optional_public_contract() {
        // Arrange
        let success = Ok(Ok("v1.2.3".to_string()));
        let lookup_failure = Ok(Err(VersionError::ResponseParse { provider: "npm" }));
        let join_handle = tokio::spawn(std::future::pending::<()>());
        join_handle.abort();
        let join_failure = join_handle.await;

        // Act
        let successful_version = latest_version_from_task_result(success);
        let missing_version = latest_version_from_task_result(lookup_failure);
        let joined_version =
            latest_version_from_task_result(join_failure.map(|()| Ok(String::new())));

        // Assert
        assert_eq!(successful_version.as_deref(), Some("v1.2.3"));
        assert_eq!(missing_version, None);
        assert_eq!(joined_version, None);
    }

    #[test]
    fn test_is_newer_than_current_version_returns_true_when_candidate_is_newer() {
        // Arrange
        let current_version = "0.1.11";
        let candidate_version = "v0.1.12";

        // Act
        let is_newer = is_newer_than_current_version(current_version, candidate_version);

        // Assert
        assert!(is_newer);
    }

    #[test]
    fn test_is_newer_than_current_version_returns_false_when_candidate_is_not_newer() {
        // Arrange
        let current_version = "0.1.12";
        let candidate_version = "v0.1.11";

        // Act
        let is_newer = is_newer_than_current_version(current_version, candidate_version);

        // Assert
        assert!(!is_newer);
    }

    #[test]
    fn test_is_newer_than_current_version_rejects_invalid_versions() {
        // Arrange, Act
        let invalid_current = is_newer_than_current_version("current", "v1.0.0");
        let invalid_candidate = is_newer_than_current_version("1.0.0", "candidate");

        // Assert
        assert!(!invalid_current);
        assert!(!invalid_candidate);
    }

    #[test]
    fn test_run_npm_update_sync_calls_npm_install_global() {
        // Arrange
        let mut update_runner = MockUpdateRunner::new();
        update_runner
            .expect_run_update()
            .times(1)
            .returning(|command, args| {
                assert_eq!(command, "npm");
                assert_eq!(
                    args,
                    vec![
                        "i".to_string(),
                        "-g".to_string(),
                        "agentty@latest".to_string(),
                    ]
                );

                Ok("added 1 package".to_string())
            });

        // Act
        let output = run_npm_update_sync(&update_runner).expect("update should succeed");

        // Assert
        assert_eq!(output, "added 1 package");
    }

    #[test]
    fn test_run_npm_update_sync_preserves_runner_error_without_displaying_stderr() {
        // Arrange
        let mut update_runner = MockUpdateRunner::new();
        update_runner
            .expect_run_update()
            .times(1)
            .returning(|_, _| {
                Err(VersionError::NonZeroExit {
                    command: "npm".to_string(),
                    status: "exit status: 1".to_string(),
                    stderr: "permission denied".to_string(),
                })
            });

        // Act
        let error = run_npm_update_sync(&update_runner).expect_err("should propagate runner error");

        // Assert
        assert_eq!(error.to_string(), "`npm` exited with status exit status: 1");
        assert!(matches!(
            error,
            VersionError::NonZeroExit { stderr, .. } if stderr == "permission denied"
        ));
    }
}