car-multi 0.55.0

Multi-agent coordination patterns for Common Agent Runtime
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
//! Per-agent filesystem workspace isolation.
//!
//! [`task_context`](crate::task_context) isolates an agent's **state** (the
//! key/value store). This module isolates its **filesystem**: when parallel
//! agents mutate files, giving each its own working directory prevents them from
//! clobbering one another — the file-level analogue of the blog's
//! `isolation: 'worktree'`.
//!
//! ## What the runtime can and can't do
//!
//! CAR doesn't own process execution — the caller's `AgentRunner` runs the tools.
//! So the runtime *provisions* an isolated directory (or git worktree) and
//! *advertises* its path to the agent via `AgentSpec.metadata["workspace"]`; the
//! runner is responsible for actually running its file tools relative to that
//! path. The runtime guarantees provisioning and cleanup (RAII); honoring the
//! path is a cooperative contract with the runner. This is the honest boundary
//! for a runtime that validates and orchestrates but does not itself exec.

use crate::types::AgentSpec;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::path::{Path, PathBuf};

/// Metadata key under which a provisioned workspace path is advertised to the
/// agent runner.
pub const WORKSPACE_METADATA_KEY: &str = "workspace";

/// How to provision a per-agent workspace.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WorkspaceMode {
    /// A plain empty directory per agent. No VCS; cheapest.
    Directory,
    /// A `git worktree` checked out at `base`'s HEAD (or at
    /// [`WorkspaceConfig::rev`] when set), so each agent edits an
    /// isolated copy of the repository. Requires `base` to be inside a git repo
    /// and a `git` binary on PATH; falls back to an error if either is missing.
    GitWorktree,
}

/// Configuration for per-agent workspace provisioning.
#[derive(Debug, Clone)]
pub struct WorkspaceConfig {
    /// Base directory under which per-agent workspaces are created. For
    /// `GitWorktree` this must be inside (or be) a git working tree, unless
    /// `repo` names the repository explicitly.
    pub base: PathBuf,
    pub mode: WorkspaceMode,
    /// For `GitWorktree`: the repository to check worktrees out of, when it
    /// differs from `base`. `None` derives the repo from `base` (the original
    /// behavior, where worktrees land inside the repo itself). Setting this
    /// lets worktrees live *outside* the repository — e.g. under a state dir —
    /// so they never show up as untracked entries in the user's checkout.
    pub repo: Option<PathBuf>,
    /// For `GitWorktree`: the commit-ish to check the worktree out at. `None`
    /// is the repository's `HEAD`, the original behavior. Setting it lets a
    /// session start from work that is not checked out — another developer's
    /// published branch, say — without touching the user's checkout.
    pub rev: Option<String>,
}

impl WorkspaceConfig {
    pub fn directory(base: impl Into<PathBuf>) -> Self {
        Self {
            base: base.into(),
            mode: WorkspaceMode::Directory,
            repo: None,
            rev: None,
        }
    }

    pub fn git_worktree(base: impl Into<PathBuf>) -> Self {
        Self {
            base: base.into(),
            mode: WorkspaceMode::GitWorktree,
            repo: None,
            rev: None,
        }
    }

    /// Git worktrees of `repo`, created under `base` (which may be anywhere on
    /// the filesystem, e.g. `~/.car/coder/worktrees`).
    pub fn git_worktree_at(repo: impl Into<PathBuf>, base: impl Into<PathBuf>) -> Self {
        Self {
            base: base.into(),
            mode: WorkspaceMode::GitWorktree,
            repo: Some(repo.into()),
            rev: None,
        }
    }

    /// Check the worktree out at `rev` instead of `HEAD`.
    pub fn with_rev(mut self, rev: impl Into<String>) -> Self {
        self.rev = Some(rev.into());
        self
    }
}

/// Sanitize an agent name into a single safe path segment. Non-`[A-Za-z0-9_-]`
/// chars (including `.` and `/`) collapse to `-`, so no traversal or separator
/// can escape `base`. Note: distinct names can collide after sanitization (e.g.
/// `a/b` and `a-b`), sharing a workspace — keep agent names distinct under this
/// mapping when isolation matters.
fn sanitize(name: &str) -> String {
    let s: String = name
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '-'
            }
        })
        .collect();
    if s.is_empty() {
        "agent".to_string()
    } else {
        s
    }
}

/// An RAII handle to a provisioned per-agent workspace. The directory (or git
/// worktree) is removed when this is dropped.
#[derive(Debug)]
pub struct AgentWorkspace {
    path: PathBuf,
    mode: WorkspaceMode,
    /// The git repo root, for `git worktree remove` on drop (GitWorktree only).
    repo_root: Option<PathBuf>,
    cleanup_on_drop: bool,
}

impl AgentWorkspace {
    /// Reopen an existing linked worktree without resetting or deleting it.
    /// Retained data survives an early error or dropped handle; the caller may
    /// enable cleanup only after successful delivery.
    pub fn reopen_git_worktree(repo: &Path, path: &Path) -> Result<Self, String> {
        let repo = repo.canonicalize().map_err(|e| e.to_string())?;
        let path = path.canonicalize().map_err(|e| e.to_string())?;
        let root = git_repo_root(&path)
            .ok_or("retained directory is not a git worktree")?
            .canonicalize()
            .map_err(|e| e.to_string())?;
        if root != path || repo == path || !path.join(".git").is_file() {
            return Err(
                "retained path must be a linked worktree root, not the user's checkout".into(),
            );
        }
        let common = |dir: &Path| -> Result<PathBuf, String> {
            let out = std::process::Command::new("git")
                .arg("-C")
                .arg(dir)
                .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
                .output()
                .map_err(|e| e.to_string())?;
            if !out.status.success() {
                return Err("cannot identify retained worktree repository".into());
            }
            PathBuf::from(
                String::from_utf8(out.stdout)
                    .map_err(|e| e.to_string())?
                    .trim(),
            )
            .canonicalize()
            .map_err(|e| e.to_string())
        };
        if common(&repo)? != common(&path)? {
            return Err("retained worktree belongs to another repository".into());
        }
        Ok(Self {
            path,
            mode: WorkspaceMode::GitWorktree,
            repo_root: Some(repo),
            cleanup_on_drop: false,
        })
    }

    /// Allow a successfully delivered retained workspace to be removed.
    pub fn enable_cleanup(&mut self) {
        self.cleanup_on_drop = true;
    }

    /// Provision an isolated workspace for `agent_name` under `config.base`.
    pub fn provision(config: &WorkspaceConfig, agent_name: &str) -> Result<Self, String> {
        let path = config.base.join(sanitize(agent_name));
        match config.mode {
            WorkspaceMode::Directory => {
                std::fs::create_dir_all(&path)
                    .map_err(|e| format!("create workspace dir {}: {e}", path.display()))?;
                Ok(Self {
                    path,
                    mode: WorkspaceMode::Directory,
                    repo_root: None,
                    cleanup_on_drop: true,
                })
            }
            WorkspaceMode::GitWorktree => {
                use std::ffi::OsStr;
                let rev = config.rev.as_deref().unwrap_or("HEAD");
                // git parses options after positionals, so a rev beginning with
                // `-` would be read as a flag to `worktree add`, not a commit.
                if rev.is_empty() || rev.starts_with('-') {
                    return Err(format!("invalid worktree revision {rev:?}"));
                }
                let repo_hint = config.repo.as_ref().unwrap_or(&config.base);
                let repo_root = git_repo_root(repo_hint).ok_or_else(|| {
                    format!(
                        "git_worktree workspace requires {} to be inside a git repo",
                        repo_hint.display()
                    )
                })?;
                std::fs::create_dir_all(&config.base)
                    .map_err(|e| format!("create workspace base {}: {e}", config.base.display()))?;
                // Self-heal against a worktree leaked by a prior run that didn't
                // get to clean up (process/runtime teardown): drop any stale
                // registration for this exact path, prune dangling entries, and
                // clear the directory before adding.
                let _ = run_git(
                    &repo_root,
                    &[
                        OsStr::new("worktree"),
                        OsStr::new("remove"),
                        OsStr::new("--force"),
                        path.as_os_str(),
                    ],
                );
                let _ = run_git(&repo_root, &[OsStr::new("worktree"), OsStr::new("prune")]);
                if path.exists() {
                    let _ = std::fs::remove_dir_all(&path);
                }
                run_git(
                    &repo_root,
                    &[
                        OsStr::new("worktree"),
                        OsStr::new("add"),
                        OsStr::new("--detach"),
                        path.as_os_str(),
                        OsStr::new(rev),
                    ],
                )?;
                Ok(Self {
                    path,
                    mode: WorkspaceMode::GitWorktree,
                    repo_root: Some(repo_root),
                    cleanup_on_drop: true,
                })
            }
        }
    }

    /// The provisioned workspace path.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Return `spec` with this workspace's path advertised in its metadata.
    pub fn inject(&self, mut spec: AgentSpec) -> AgentSpec {
        spec.metadata.insert(
            WORKSPACE_METADATA_KEY.to_string(),
            Value::String(self.path.to_string_lossy().into_owned()),
        );
        spec
    }
}

impl Drop for AgentWorkspace {
    fn drop(&mut self) {
        if !self.cleanup_on_drop {
            return;
        }
        match self.mode {
            WorkspaceMode::Directory => {
                let _ = std::fs::remove_dir_all(&self.path);
            }
            WorkspaceMode::GitWorktree => {
                if let Some(root) = &self.repo_root {
                    use std::ffi::OsStr;
                    // Best-effort: detach the worktree, then remove the dir.
                    let _ = run_git(
                        root,
                        &[
                            OsStr::new("worktree"),
                            OsStr::new("remove"),
                            OsStr::new("--force"),
                            self.path.as_os_str(),
                        ],
                    );
                    let _ = std::fs::remove_dir_all(&self.path);
                }
            }
        }
    }
}

/// Find the git working-tree root containing `dir`, if any.
fn git_repo_root(dir: &Path) -> Option<PathBuf> {
    let out = std::process::Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["rev-parse", "--show-toplevel"])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let root = String::from_utf8(out.stdout).ok()?.trim().to_string();
    if root.is_empty() {
        None
    } else {
        Some(PathBuf::from(root))
    }
}

fn run_git(repo_root: &Path, args: &[&std::ffi::OsStr]) -> Result<(), String> {
    let out = std::process::Command::new("git")
        .arg("-C")
        .arg(repo_root)
        .args(args)
        .output()
        .map_err(|e| format!("git {:?}: {e}", args))?;
    if out.status.success() {
        Ok(())
    } else {
        Err(format!(
            "git {:?} failed: {}",
            args,
            String::from_utf8_lossy(&out.stderr).trim()
        ))
    }
}

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

    fn unique_base(tag: &str) -> PathBuf {
        // Avoid Math.random/Date in tests; use pid + a static counter.
        use std::sync::atomic::{AtomicU64, Ordering};
        static N: AtomicU64 = AtomicU64::new(0);
        let n = N.fetch_add(1, Ordering::Relaxed);
        std::env::temp_dir().join(format!("car-ws-{tag}-{}-{n}", std::process::id()))
    }

    #[test]
    fn directory_workspace_is_created_injected_and_cleaned() {
        let base = unique_base("dir");
        let cfg = WorkspaceConfig::directory(&base);
        let path;
        {
            let ws = AgentWorkspace::provision(&cfg, "alice/../x").unwrap();
            path = ws.path().to_path_buf();
            assert!(path.exists() && path.is_dir());
            // Sanitized: no path traversal segments survive.
            assert_eq!(path.parent().unwrap(), base);
            assert!(!path.to_string_lossy().contains(".."));

            let spec = ws.inject(AgentSpec::new("alice", "sys"));
            assert_eq!(
                spec.metadata.get(WORKSPACE_METADATA_KEY).unwrap(),
                &Value::String(path.to_string_lossy().into_owned())
            );
        }
        // Dropped → cleaned up.
        assert!(!path.exists(), "workspace should be removed on drop");
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn git_worktree_at_provisions_outside_the_repo() {
        // Skip silently when git is unavailable (mirrors CI environments
        // without a git binary; the mode itself errors clearly there).
        if std::process::Command::new("git")
            .arg("--version")
            .output()
            .is_err()
        {
            return;
        }
        let repo = unique_base("repo");
        std::fs::create_dir_all(&repo).unwrap();
        for args in [
            vec!["init", "-q"],
            vec![
                "-c",
                "user.name=t",
                "-c",
                "user.email=t@t",
                "commit",
                "-q",
                "--allow-empty",
                "-m",
                "init",
            ],
        ] {
            let out = std::process::Command::new("git")
                .arg("-C")
                .arg(&repo)
                .args(&args)
                .output()
                .unwrap();
            assert!(
                out.status.success(),
                "git {args:?}: {}",
                String::from_utf8_lossy(&out.stderr)
            );
        }

        let base = unique_base("wt-base");
        let cfg = WorkspaceConfig::git_worktree_at(&repo, &base);
        let path;
        {
            let ws = AgentWorkspace::provision(&cfg, "session-1").unwrap();
            path = ws.path().to_path_buf();
            assert!(
                path.starts_with(&base),
                "worktree must live under base, not the repo"
            );
            assert!(path.join(".git").exists(), "worktree checkout expected");
            // The repo's status stays clean — the worktree is elsewhere.
            let out = std::process::Command::new("git")
                .arg("-C")
                .arg(&repo)
                .args(["status", "--porcelain"])
                .output()
                .unwrap();
            assert!(out.stdout.is_empty(), "repo status must stay clean");
        }
        assert!(!path.exists(), "worktree removed on drop");
        let _ = std::fs::remove_dir_all(&base);
        let _ = std::fs::remove_dir_all(&repo);
    }

    fn git_out(dir: &Path, args: &[&str]) -> String {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(args)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git {args:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        String::from_utf8(out.stdout).unwrap().trim().to_string()
    }

    #[test]
    fn reopening_retained_work_is_nondestructive_and_repository_bound() {
        let repo = unique_base("reopen-repo");
        let other = unique_base("reopen-other");
        let base = unique_base("reopen-worktrees");
        for root in [&repo, &other] {
            std::fs::create_dir_all(root).unwrap();
            git_out(root, &["init", "-q"]);
            git_out(
                root,
                &[
                    "-c",
                    "user.name=t",
                    "-c",
                    "user.email=t@t",
                    "commit",
                    "--allow-empty",
                    "-qm",
                    "initial",
                ],
            );
        }
        let workspace =
            AgentWorkspace::provision(&WorkspaceConfig::git_worktree_at(&repo, &base), "retained")
                .unwrap();
        let path = workspace.path().to_path_buf();
        std::fs::write(path.join("partial.txt"), "unfinished").unwrap();
        std::mem::forget(workspace);
        assert!(AgentWorkspace::reopen_git_worktree(&other, &path).is_err());
        assert!(AgentWorkspace::reopen_git_worktree(&repo, &repo).is_err());
        let reopened = AgentWorkspace::reopen_git_worktree(&repo, &path).unwrap();
        drop(reopened);
        assert_eq!(
            std::fs::read_to_string(path.join("partial.txt")).unwrap(),
            "unfinished"
        );
        let mut delivered = AgentWorkspace::reopen_git_worktree(&repo, &path).unwrap();
        delivered.enable_cleanup();
        drop(delivered);
        assert!(!path.exists());
        assert!(repo.is_dir());
        for root in [repo, other, base] {
            let _ = std::fs::remove_dir_all(root);
        }
    }

    #[test]
    fn git_worktree_checks_out_the_requested_rev_not_head() {
        if std::process::Command::new("git")
            .arg("--version")
            .output()
            .is_err()
        {
            return;
        }
        let repo = unique_base("rev-repo");
        std::fs::create_dir_all(&repo).unwrap();
        let commit = ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q"];
        git_out(&repo, &["init", "-q"]);
        git_out(
            &repo,
            &[&commit[..], &["--allow-empty", "-m", "one"]].concat(),
        );
        let first = git_out(&repo, &["rev-parse", "HEAD"]);
        git_out(
            &repo,
            &[&commit[..], &["--allow-empty", "-m", "two"]].concat(),
        );
        let head = git_out(&repo, &["rev-parse", "HEAD"]);
        assert_ne!(first, head);

        let base = unique_base("rev-wt");
        // Positive control: without a rev the worktree is at HEAD, so the
        // assertion below distinguishes the two.
        let at_head =
            AgentWorkspace::provision(&WorkspaceConfig::git_worktree_at(&repo, &base), "h")
                .unwrap();
        assert_eq!(git_out(at_head.path(), &["rev-parse", "HEAD"]), head);
        drop(at_head);

        let cfg = WorkspaceConfig::git_worktree_at(&repo, &base).with_rev(first.clone());
        let ws = AgentWorkspace::provision(&cfg, "r").unwrap();
        assert_eq!(git_out(ws.path(), &["rev-parse", "HEAD"]), first);
        drop(ws);
        let _ = std::fs::remove_dir_all(&base);
        let _ = std::fs::remove_dir_all(&repo);
    }

    #[test]
    fn git_worktree_refuses_a_rev_that_git_would_parse_as_a_flag() {
        let base = unique_base("rev-flag");
        for rev in ["", "-b", "--orphan=x"] {
            let cfg = WorkspaceConfig::git_worktree_at(&base, &base).with_rev(rev);
            let err = AgentWorkspace::provision(&cfg, "x").unwrap_err();
            assert!(err.contains("invalid worktree revision"), "{rev:?}: {err}");
        }
    }

    #[test]
    fn distinct_agents_get_distinct_dirs() {
        let base = unique_base("distinct");
        let cfg = WorkspaceConfig::directory(&base);
        let a = AgentWorkspace::provision(&cfg, "a").unwrap();
        let b = AgentWorkspace::provision(&cfg, "b").unwrap();
        assert_ne!(a.path(), b.path());
        drop(a);
        drop(b);
        let _ = std::fs::remove_dir_all(&base);
    }
}