recursive-agent 0.8.3

A Rust coding-agent platform: kernel, tools, multi-agent orchestration, HTTP API, MCP, and TUI
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
//! Team roster persistence — `~/.claude/teams/{team_name}.json`.
//!
//! # Design
//!
//! A "team" is a flat roster of named agents (teammates) that the
//! coordinator can dispatch work to.  The roster is the *persisted* layer:
//! one JSON file per team under the user's data dir.  The in-memory
//! runtime counterparts (mailboxes, handles) live in `tasks.rs` and
//! `tools/agent.rs`.
//!
//! File format (`TeamFile`):
//! ```json
//! {
//!   "name": "alpha",
//!   "created_at": "2026-06-07T10:00:00Z",
//!   "members": [
//!     { "name": "researcher", "agent_type": "general", "status": "active", "model": "claude-opus-4-7" }
//!   ]
//! }
//! ```
//!
//! # Flat roster invariant
//!
//! Teammates are *flat* — a teammate's `manifest` cannot itself declare
//! teammates.  This is enforced in the `agent` tool (see
//! `src/tools/agent.rs`), not here.  `TeamRegistry` only stores the
//! roster shape; it does not validate what each teammate can spawn.
//!
//! # Atomicity
//!
//! All writes use a sibling-temp-file + rename pattern (see
//! `atomic_write` below) so a crash mid-write cannot leave a corrupt
//! `teams/*.json` on disk.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::RwLock;

use crate::error::{Error, Result};

// ---------------------------------------------------------------------------
// Path helpers
// ---------------------------------------------------------------------------

/// Directory under which per-team JSON files live.
///
/// Honors the `RECURSIVE_TEAMS_DIR` env var for tests; otherwise the
/// spec-mandated `~/.claude/teams/`.
pub fn teams_dir() -> PathBuf {
    if let Some(custom) = std::env::var_os("RECURSIVE_TEAMS_DIR") {
        return PathBuf::from(custom);
    }
    if let Some(home) = dirs::home_dir() {
        return home.join(".claude").join("teams");
    }
    PathBuf::from(".claude").join("teams")
}

/// Full path to a given team's roster file.
pub fn team_file_path(team_name: &str) -> PathBuf {
    teams_dir().join(format!("{team_name}.json"))
}

/// Validate a team name to ensure it can't be used for path traversal.
///
/// Team names are used as filename stems under `teams_dir()`. Without
/// validation, a name like `"../etc"` would resolve to a file outside
/// the teams directory. This is the team-registry equivalent of the
/// workspace sandbox enforced by `tools::resolve_within` for
/// workspace-bounded file operations: it rejects any name that could
/// escape `teams_dir()` when joined with it.
///
/// Returns `Err(Error::BadToolArgs)` with a descriptive message if the
/// name is invalid.
pub fn validate_team_name(name: &str) -> Result<()> {
    if name.is_empty()
        || name.contains('/')
        || name.contains('\\')
        || name.contains("..")
        || name.starts_with('.')
    {
        return Err(Error::BadToolArgs {
            name: "<team>".into(),
            message: format!("invalid team name: '{name}'"),
        });
    }
    Ok(())
}

/// Make sure the teams directory exists.  Returns the path.
pub fn ensure_teams_dir() -> std::io::Result<PathBuf> {
    let dir = teams_dir();
    std::fs::create_dir_all(&dir)?;
    Ok(dir)
}

// ---------------------------------------------------------------------------
// TeammateStatus / TeamMember
// ---------------------------------------------------------------------------

/// Runtime status of a teammate within a team.
///
/// Mirrors the spec:
/// - `Active`  — the teammate is currently running (or ready to be dispatched).
/// - `Idle`    — the teammate has been spawned but is not running anything.
/// - `Stopped` — the teammate was explicitly stopped by the coordinator.
/// - `Error`   — the teammate is in an error state (e.g. crashed during dispatch).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TeammateStatus {
    Active,
    Idle,
    Stopped,
    Error,
}

/// A single member of a team's roster.
///
/// Kept intentionally small — runtime concerns (mailboxes, task IDs,
/// in-flight handles) live in `tasks.rs`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TeamMember {
    /// Display name of the teammate (unique within the team).
    pub name: String,

    /// Logical agent type (e.g. `"general"`, `"researcher"`, `"coder"`).
    /// Free-form — the coordinator uses it to pick allowed_tools / prompts.
    #[serde(default)]
    pub agent_type: String,

    /// Current status of this teammate.
    #[serde(default = "default_status")]
    pub status: TeammateStatus,

    /// Model identifier (free-form, e.g. `"claude-opus-4-7"`).
    /// Empty string means "inherit from parent".
    #[serde(default)]
    pub model: String,
}

fn default_status() -> TeammateStatus {
    TeammateStatus::Idle
}

impl TeamMember {
    pub fn new(name: impl Into<String>, agent_type: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            agent_type: agent_type.into(),
            status: default_status(),
            model: String::new(),
        }
    }

    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = model.into();
        self
    }

    pub fn with_status(mut self, status: TeammateStatus) -> Self {
        self.status = status;
        self
    }
}

// ---------------------------------------------------------------------------
// TeamFile
// ---------------------------------------------------------------------------

/// The on-disk representation of a team.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TeamFile {
    /// Team name (matches the filename stem, e.g. `"alpha"`).
    pub name: String,

    /// When the team was first created.
    pub created_at: DateTime<Utc>,

    /// All members in the team, indexed by name for stable serialization.
    pub members: BTreeMap<String, TeamMember>,
}

impl TeamFile {
    /// Build a new, empty team file (no members yet).
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            created_at: Utc::now(),
            members: BTreeMap::new(),
        }
    }

    /// Add (or replace) a member.
    pub fn add_member(&mut self, member: TeamMember) {
        self.members.insert(member.name.clone(), member);
    }

    /// Remove a member by name.  Returns `true` if the member existed.
    pub fn remove_member(&mut self, name: &str) -> bool {
        self.members.remove(name).is_some()
    }

    /// Get a member by name.
    pub fn get_member(&self, name: &str) -> Option<&TeamMember> {
        self.members.get(name)
    }

    /// Mutable access to a member.
    pub fn get_member_mut(&mut self, name: &str) -> Option<&mut TeamMember> {
        self.members.get_mut(name)
    }

    /// Number of members in the team.
    pub fn member_count(&self) -> usize {
        self.members.len()
    }

    /// List of all member names (sorted, since backed by BTreeMap).
    pub fn member_names(&self) -> Vec<&str> {
        self.members.keys().map(|s| s.as_str()).collect()
    }
}

// ---------------------------------------------------------------------------
// TeamRegistry
// ---------------------------------------------------------------------------

/// In-memory + on-disk team registry.
///
/// The registry is cheap to clone — it's backed by an `Arc<RwLock<…>>`.
/// It is the single source of truth for *which teams exist* and *who
/// is on each team*.  Callers do not touch the filesystem directly;
/// they go through the registry methods (`load`, `save`, `create`,
/// `delete`, `add_member`, `remove_member`).
#[derive(Clone, Default)]
pub struct TeamRegistry {
    inner: Arc<RwLock<TeamRegistryInner>>,
}

#[derive(Default)]
struct TeamRegistryInner {
    /// team_name -> TeamFile (already loaded or freshly created).
    teams: BTreeMap<String, TeamFile>,
}

impl TeamRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    /// Insert a freshly created or loaded team into the in-memory
    /// registry. This is what `team_create` and `team_load` use so the
    /// registry is queryable via `get`/`list` after a tool call.
    /// Returns the previous value if a team with the same name existed.
    pub async fn register_team(&self, team: TeamFile) -> Option<TeamFile> {
        self.inner
            .write()
            .await
            .teams
            .insert(team.name.clone(), team)
    }

    /// Load a team from disk.  Errors if the team file does not exist
    /// or is malformed.
    pub async fn load(team_name: &str) -> Result<Self> {
        validate_team_name(team_name)?;
        let path = team_file_path(team_name);
        let bytes = std::fs::read(&path).map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                Error::NotFound(format!("team '{team_name}'"))
            } else {
                Error::Internal {
                    context: "team::load".to_string(),
                    message: format!("read team file: {e}"),
                }
            }
        })?;
        let team: TeamFile = serde_json::from_slice(&bytes)?;
        let mut inner = TeamRegistryInner::default();
        inner.teams.insert(team.name.clone(), team);
        Ok(Self {
            inner: Arc::new(RwLock::new(inner)),
        })
    }

    /// Create a new empty team in memory and persist it.
    pub async fn create(team_name: &str) -> Result<Self> {
        validate_team_name(team_name)?;
        let team = TeamFile::new(team_name);
        Self::save_team(&team)?;
        let mut inner = TeamRegistryInner::default();
        inner.teams.insert(team.name.clone(), team);
        Ok(Self {
            inner: Arc::new(RwLock::new(inner)),
        })
    }

    /// Persist the in-memory team to disk (atomic).
    pub async fn save(&self) -> Result<()> {
        let inner = self.inner.read().await;
        for team in inner.teams.values() {
            Self::save_team(team)?;
        }
        Ok(())
    }

    pub(crate) fn save_team(team: &TeamFile) -> Result<()> {
        ensure_teams_dir()?;
        let path = team_file_path(&team.name);
        let json = serde_json::to_string_pretty(team)?;
        crate::atomic::atomic_write(&path, json.as_bytes())?;
        Ok(())
    }

    /// Get a clone of the in-memory TeamFile.
    pub async fn get(&self, team_name: &str) -> Option<TeamFile> {
        self.inner.read().await.teams.get(team_name).cloned()
    }

    /// List all teams currently in memory.
    pub async fn list_teams(&self) -> Vec<String> {
        self.inner.read().await.teams.keys().cloned().collect()
    }

    /// List all teams that exist on disk.
    ///
    /// Reads the teams dir; useful for discovery (e.g. a `team_list`
    /// tool that wants to show all teams across the system).
    pub fn list_on_disk() -> std::io::Result<Vec<String>> {
        let dir = teams_dir();
        if !dir.exists() {
            return Ok(Vec::new());
        }
        let mut out = Vec::new();
        for entry in std::fs::read_dir(&dir)? {
            let entry = entry?;
            let path = entry.path();
            if !path.is_file() {
                continue;
            }
            if path.extension().and_then(|e| e.to_str()) != Some("json") {
                continue;
            }
            if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                // Skip temp files left behind by interrupted writes.
                if stem.starts_with(".tmp-") {
                    continue;
                }
                out.push(stem.to_string());
            }
        }
        out.sort();
        Ok(out)
    }

    /// Delete a team from memory and disk.
    pub async fn delete(team_name: &str) -> Result<bool> {
        validate_team_name(team_name)?;
        let path = team_file_path(team_name);
        match std::fs::remove_file(&path) {
            Ok(()) => Ok(true),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
            Err(e) => Err(Error::Internal {
                context: "team::delete".to_string(),
                message: format!("delete team file: {e}"),
            }),
        }
    }

    /// Add a member to a team (in-memory + persisted).
    pub async fn add_member(&self, team_name: &str, member: TeamMember) -> Result<()> {
        validate_team_name(team_name)?;
        let mut inner = self.inner.write().await;
        let team = inner
            .teams
            .get_mut(team_name)
            .ok_or_else(|| Error::NotFound(format!("team '{team_name}'")))?;
        team.add_member(member);
        Self::save_team(team)?;
        Ok(())
    }

    /// Remove a member from a team (in-memory + persisted).
    /// Returns `true` if the member existed.
    pub async fn remove_member(&self, team_name: &str, member_name: &str) -> Result<bool> {
        validate_team_name(team_name)?;
        let mut inner = self.inner.write().await;
        let team = inner
            .teams
            .get_mut(team_name)
            .ok_or_else(|| Error::NotFound(format!("team '{team_name}'")))?;
        let removed = team.remove_member(member_name);
        if removed {
            Self::save_team(team)?;
        }
        Ok(removed)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn with_temp_teams_dir() -> crate::test_util::PinnedTeamsDir {
        crate::test_util::PinnedTeamsDir::new()
    }

    #[test]
    fn team_file_new_is_empty() {
        let tf = TeamFile::new("alpha");
        assert_eq!(tf.name, "alpha");
        assert_eq!(tf.member_count(), 0);
        assert!(tf.member_names().is_empty());
        assert!(tf.created_at <= Utc::now());
    }

    #[test]
    fn add_and_remove_member() {
        let mut tf = TeamFile::new("alpha");
        let m = TeamMember::new("researcher", "general");
        tf.add_member(m.clone());
        assert_eq!(tf.member_count(), 1);
        assert_eq!(tf.get_member("researcher"), Some(&m));
        assert!(tf.remove_member("researcher"));
        assert_eq!(tf.member_count(), 0);
        assert!(
            !tf.remove_member("researcher"),
            "double-remove returns false"
        );
    }

    #[test]
    fn team_member_with_model_and_status() {
        let m = TeamMember::new("coder", "general")
            .with_model("claude-opus-4-7")
            .with_status(TeammateStatus::Active);
        assert_eq!(m.model, "claude-opus-4-7");
        assert_eq!(m.status, TeammateStatus::Active);
    }

    #[test]
    fn team_file_round_trip_json() {
        let mut tf = TeamFile::new("alpha");
        tf.add_member(TeamMember::new("researcher", "general"));
        tf.add_member(
            TeamMember::new("coder", "general")
                .with_model("claude-opus-4-7")
                .with_status(TeammateStatus::Active),
        );
        let json = serde_json::to_string(&tf).unwrap();
        let back: TeamFile = serde_json::from_str(&json).unwrap();
        assert_eq!(tf, back);
    }

    #[tokio::test]
    async fn registry_create_save_load() {
        let _g = with_temp_teams_dir();
        let reg = TeamRegistry::create("alpha").await.unwrap();
        assert_eq!(reg.list_teams().await, vec!["alpha".to_string()]);
        assert!(team_file_path("alpha").exists());

        // Re-load: should produce an equal TeamFile.
        let reg2 = TeamRegistry::load("alpha").await.unwrap();
        let tf = reg2.get("alpha").await.unwrap();
        assert_eq!(tf.name, "alpha");
        assert_eq!(tf.member_count(), 0);
    }

    #[tokio::test]
    async fn registry_add_remove_member_persists() {
        let _g = with_temp_teams_dir();
        let reg = TeamRegistry::create("beta").await.unwrap();
        reg.add_member("beta", TeamMember::new("r", "general"))
            .await
            .unwrap();
        reg.add_member(
            "beta",
            TeamMember::new("c", "general").with_model("claude-opus-4-7"),
        )
        .await
        .unwrap();

        // Reload from disk and confirm both members are present.
        let reg2 = TeamRegistry::load("beta").await.unwrap();
        let tf = reg2.get("beta").await.unwrap();
        assert_eq!(tf.member_count(), 2);
        assert!(tf.get_member("r").is_some());
        assert!(tf.get_member("c").is_some());
        assert_eq!(tf.get_member("c").unwrap().model, "claude-opus-4-7");

        // Remove one and confirm.
        assert!(reg.remove_member("beta", "r").await.unwrap());
        let reg3 = TeamRegistry::load("beta").await.unwrap();
        assert_eq!(reg3.get("beta").await.unwrap().member_count(), 1);
    }

    #[tokio::test]
    async fn registry_delete_removes_file() {
        let _g = with_temp_teams_dir();
        let _ = TeamRegistry::create("gamma").await.unwrap();
        assert!(team_file_path("gamma").exists());
        assert!(TeamRegistry::delete("gamma").await.unwrap());
        assert!(!team_file_path("gamma").exists());
        // Second delete is idempotent: returns false, no error.
        assert!(!TeamRegistry::delete("gamma").await.unwrap());
    }

    #[tokio::test]
    async fn registry_load_missing_team_errors() {
        let _g = with_temp_teams_dir();
        let res = TeamRegistry::load("nonexistent").await;
        assert!(matches!(res, Err(Error::NotFound(_))));
    }

    #[test]
    fn atomic_write_replaces_existing() {
        let g = with_temp_teams_dir();
        let dir = g.path();
        let p = dir.join("alpha.json");
        crate::atomic::atomic_write(&p, b"{\"name\":\"alpha\"}").unwrap();
        let s1 = std::fs::read_to_string(&p).unwrap();
        assert_eq!(s1, "{\"name\":\"alpha\"}");

        crate::atomic::atomic_write(&p, b"{\"name\":\"alpha\",\"v\":2}").unwrap();
        let s2 = std::fs::read_to_string(&p).unwrap();
        assert_eq!(s2, "{\"name\":\"alpha\",\"v\":2}");

        // No leftover .tmp- files.
        for entry in std::fs::read_dir(dir).unwrap() {
            let entry = entry.unwrap();
            assert!(
                !entry
                    .file_name()
                    .to_str()
                    .unwrap()
                    .starts_with(".tmp-team-"),
                "found leftover temp file: {:?}",
                entry.file_name()
            );
        }
    }

    #[test]
    fn teammate_status_default_is_idle() {
        let j = r#"{"name":"x","agent_type":"general","model":""}"#;
        let m: TeamMember = serde_json::from_str(j).unwrap();
        assert_eq!(m.status, TeammateStatus::Idle);
    }

    // ── Gap-filling tests ────────────────────────────────────────────────────

    #[test]
    fn validate_team_name_accepts_valid_names() {
        assert!(validate_team_name("alpha").is_ok());
        assert!(validate_team_name("my-team-123").is_ok());
        assert!(validate_team_name("team_v2").is_ok());
    }

    #[test]
    fn validate_team_name_rejects_empty() {
        assert!(
            validate_team_name("").is_err(),
            "empty name must be rejected"
        );
    }

    #[test]
    fn validate_team_name_rejects_slash() {
        assert!(
            validate_team_name("etc/passwd").is_err(),
            "/ must be rejected"
        );
    }

    #[test]
    fn validate_team_name_rejects_backslash() {
        assert!(
            validate_team_name("etc\\passwd").is_err(),
            r"\ must be rejected"
        );
    }

    #[test]
    fn validate_team_name_rejects_dotdot() {
        assert!(validate_team_name("..").is_err(), ".. must be rejected");
        assert!(
            validate_team_name("../escape").is_err(),
            "../escape must be rejected"
        );
    }

    #[test]
    fn validate_team_name_rejects_leading_dot() {
        assert!(
            validate_team_name(".hidden").is_err(),
            ".hidden must be rejected"
        );
    }

    #[test]
    fn team_file_get_member_mut_modifies_in_place() {
        let mut tf = TeamFile::new("test");
        tf.add_member(TeamMember::new("dev", "general"));
        {
            let m = tf.get_member_mut("dev").expect("must find 'dev'");
            m.model = "gpt-4o".to_string();
        }
        assert_eq!(tf.get_member("dev").unwrap().model, "gpt-4o");
    }

    #[test]
    fn team_file_get_member_mut_returns_none_for_unknown() {
        let mut tf = TeamFile::new("test");
        assert!(tf.get_member_mut("ghost").is_none());
    }

    #[test]
    fn team_file_path_contains_team_name() {
        let _g = with_temp_teams_dir();
        let path = team_file_path("my-team");
        assert!(
            path.to_string_lossy().contains("my-team.json"),
            "path must contain 'my-team.json', got: {path:?}"
        );
    }

    #[test]
    fn teams_dir_honors_env_var() {
        let _lock = crate::test_util::env_lock();
        let custom = "/tmp/custom-teams-dir";
        std::env::set_var("RECURSIVE_TEAMS_DIR", custom);
        let dir = teams_dir();
        std::env::remove_var("RECURSIVE_TEAMS_DIR");
        assert_eq!(dir, std::path::PathBuf::from(custom));
    }
}