use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::time::Duration;
use serde_json::Value;
use tam_daemon::daemon::Daemon;
use tokio::net::UnixStream;
fn tam(root: &Path, cwd: &Path, args: &[&str]) -> Command {
let mut cmd = Command::new(env!("CARGO_BIN_EXE_tam"));
cmd.args(args)
.current_dir(cwd)
.env("XDG_RUNTIME_DIR", root.join("rt"))
.env("XDG_DATA_HOME", root.join("data"))
.env("XDG_CONFIG_HOME", root.join("config"))
.env("HOME", root.join("home"))
.env_remove("TAM_AGENT_ID")
.env_remove("TAM_SOCKET")
.stdin(Stdio::null());
tam_worktree::git::without_local_env(&mut cmd);
cmd
}
async fn output(mut cmd: Command) -> Output {
tokio::task::spawn_blocking(move || cmd.output().unwrap())
.await
.unwrap()
}
fn text(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).into_owned()
}
async fn ok(root: &Path, cwd: &Path, args: &[&str]) -> String {
let out = output(tam(root, cwd, args)).await;
assert!(out.status.success(), "tam {args:?}: {}", text(&out.stderr));
text(&out.stdout)
}
fn git(dir: &Path, args: &[&str]) {
let out = tam_worktree::git::command()
.args(["-c", "user.email=t@t", "-c", "user.name=t"])
.args(args)
.current_dir(dir)
.output()
.unwrap();
assert!(out.status.success(), "git {args:?}: {}", text(&out.stderr));
}
fn repo(path: &Path) {
std::fs::create_dir_all(path).unwrap();
git(path, &["init", "-q", "-b", "main"]);
git(path, &["commit", "-q", "--allow-empty", "-m", "init"]);
}
async fn claude_args(root: &Path, id: &str) -> Vec<String> {
let path = root.join(format!("args-{id}"));
for _ in 0..100 {
if let Ok(s) = std::fs::read_to_string(&path) {
return s.lines().map(str::to_string).collect();
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
panic!("the agent of {id} never started");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_brief_from_the_command_line() {
let tmp = tempfile::tempdir().unwrap();
let root = &tmp.path().canonicalize().unwrap();
let bin = root.join("bin");
std::fs::create_dir_all(&bin).unwrap();
std::fs::write(
bin.join("claude"),
format!(
"#!/bin/sh\nf='{}/args-'\"$TAM_AGENT_ID\"\n\
for a in \"$@\"; do printf '%s\\n' \"$a\"; done > \"$f.tmp\"\n\
mv \"$f.tmp\" \"$f\"\nexec sleep 3600\n",
root.display()
),
)
.unwrap();
std::fs::set_permissions(
bin.join("claude"),
std::os::unix::fs::PermissionsExt::from_mode(0o755),
)
.unwrap();
std::env::set_var(
"PATH",
format!("{}:{}", bin.display(), std::env::var("PATH").unwrap()),
);
let sock = root.join("rt").join("tam").join("sock");
let daemon = Daemon::new(sock.clone(), root.join("ledger.jsonl"));
tokio::spawn(async move {
let _ = daemon.run().await;
});
while UnixStream::connect(&sock).await.is_err() {
tokio::time::sleep(Duration::from_millis(50)).await;
}
let tasks_dir = root.join("tasks");
let config = root.join("config").join("tam");
std::fs::create_dir_all(&config).unwrap();
std::fs::write(
config.join("config.toml"),
r#"
[[brief.patterns]]
match = '^CS-(\d+)$'
reference = "https://tickets.example/CS-{1}"
prompt = "/implement-task {brief}"
"#,
)
.unwrap();
let src = root.join("home").join("src");
repo(&src.join("api"));
repo(&src.join("web"));
let out = ok(
root,
&src,
&[
"new", "feat", "-r", "api", "-r", "web", "--brief", "CS-42", "-d",
],
)
.await;
assert!(out.contains("Started claude in 'feat/api'"), "{out}");
let url = "https://tickets.example/CS-42";
let json: Value =
serde_json::from_str(&ok(root, &src, &["brief", "feat", "--json"]).await).unwrap();
assert_eq!(json["schema_version"], 1);
assert_eq!(json["task"], "feat");
assert_eq!(json["reference"], url);
assert_eq!(json["file"], Value::Null);
let scratch = tasks_dir.join("feat").join("scratch");
assert_eq!(json["scratch"], scratch.to_str().unwrap());
assert!(scratch.is_dir());
let ps: Value = serde_json::from_str(&ok(root, &src, &["ps", "--json"]).await).unwrap();
let members = ps["tasks"][0]["members"].as_array().unwrap();
let ids: Vec<&str> = members.iter().map(|m| m["id"].as_str().unwrap()).collect();
assert_eq!(ids.len(), 2, "{ps}");
for id in &ids {
let args = claude_args(root, id).await;
assert_eq!(args.len(), 3, "{args:?}");
assert_eq!(args[0], "--settings");
assert_eq!(args[2], format!("/implement-task {url}"));
let settings: Value = serde_json::from_str(&args[1]).unwrap();
let dirs = settings["permissions"]["additionalDirectories"].clone();
assert_eq!(dirs[0], tasks_dir.join("feat").to_str().unwrap());
assert_eq!(dirs.as_array().unwrap().len(), 2, "{settings}");
}
let api_wt = root.join("home").join("worktrees").join("api--feat");
let out = ok(root, &api_wt, &["brief"]).await;
assert_eq!(
out,
format!(
"Brief of task feat: {url}\nScratch: {}\n",
scratch.display()
)
);
std::fs::write(api_wt.join("spec.md"), "the spec").unwrap();
let out = ok(root, &api_wt, &["brief", "--set", "spec.md"]).await;
assert!(
out.starts_with(&format!(
"Brief of task feat: {}\n",
api_wt.join("spec.md").display()
)),
"{out}"
);
let out = ok(root, &src, &["brief", "feat/web", "--local"]).await;
let file = tasks_dir.join("feat").join("brief.md");
assert!(
out.starts_with(&format!("Brief of task feat: {}\n", file.display())),
"{out}"
);
let template = std::fs::read_to_string(&file).unwrap();
assert!(template.contains("\n## Shared\n"), "{template}");
for name in ["nope", "feat/nope"] {
let out = output(tam(root, &src, &["brief", name, "--set", "x"])).await;
assert_eq!(out.status.code(), Some(3), "{}", text(&out.stderr));
}
let out = output(tam(
root,
&src,
&["new", "feat", "-r", "api", "--join", "--brief", "x"],
))
.await;
assert_eq!(out.status.code(), Some(2), "{}", text(&out.stderr));
std::fs::write(&file, format!("{template}\nAgreed: POST /items\n")).unwrap();
let out = output(tam(root, &src, &["drop", "feat", "-f"])).await;
assert!(out.status.success(), "{}", text(&out.stderr));
let stderr = text(&out.stderr);
let kept: Vec<PathBuf> = std::fs::read_dir(tasks_dir.join(".dropped"))
.unwrap()
.map(|e| e.unwrap().path())
.collect();
assert_eq!(kept.len(), 1);
assert!(
stderr.contains(&format!(
"warning: the brief of task 'feat' is kept at {}",
kept[0].display()
)),
"{stderr}"
);
assert!(!tasks_dir.join("feat").exists());
}