use std::path::Path;
use std::sync::Mutex;
use tempfile::TempDir;
use super::*;
use crate::llm::FunctionCall;
use crate::run_task::TurnRecord;
fn cargo_project() -> TempDir {
let dir = tempfile::tempdir().expect("tempdir for a cargo project");
std::fs::write(
dir.path().join("Cargo.toml"),
"[package]\nname = \"fixture\"\n",
)
.expect("write Cargo.toml");
dir
}
fn gate_ctx(root: &Path, has_bash: bool) -> VerifyGateContext {
VerifyGateContext::new(Some(root.to_path_buf()), has_bash)
}
fn bash_call(id: &str, command: &str) -> ToolCall {
ToolCall {
id: id.into(),
kind: "function".into(),
function: FunctionCall {
name: BASH_TOOL_NAME.into(),
arguments: serde_json::json!({"command": command}).to_string(),
},
}
}
fn assistant_with_tool_calls(calls: Vec<ToolCall>) -> ChatMessage {
ChatMessage {
role: "assistant".into(),
content: None,
images: vec![],
tool_calls: Some(calls),
tool_call_id: None,
name: None,
cache_control: None,
}
}
#[test]
fn names_test_command_detects_each_pattern() {
for text in [
"please run pytest tests/test_basic.py -v before submitting",
"then run cargo test",
"run npm test after building",
"use pnpm test to check",
"run go test ./... first",
"invoke python -m pytest as the final step",
] {
assert!(names_test_command(text), "expected a match in {text:?}");
}
}
#[test]
fn names_test_command_false_on_unrelated_text() {
assert!(!names_test_command(
"implement a git log parser and make sure it builds cleanly"
));
}
#[test]
fn is_test_command_matches_each_pattern() {
for cmd in [
"pytest challenges/level-2-git-analyzer/test_suite/ -v",
"cargo test -p trusty-code",
"npm test",
"pnpm test --run",
"go test ./...",
"python -m pytest -x",
] {
assert!(is_test_command(cmd), "expected a match in {cmd:?}");
}
}
#[test]
fn is_test_command_false_on_unrelated_command() {
for cmd in ["ls -la", "git status", "cargo build --release", "echo ok"] {
assert!(!is_test_command(cmd), "unexpected match in {cmd:?}");
}
}
#[test]
fn bash_command_from_call_extracts_command() {
let call = bash_call("c1", "cargo test -p trusty-code");
assert_eq!(
bash_command_from_call(&call).as_deref(),
Some("cargo test -p trusty-code")
);
}
#[test]
fn bash_command_from_call_ignores_other_tools() {
let call = ToolCall {
id: "c1".into(),
kind: "function".into(),
function: FunctionCall {
name: "write_file".into(),
arguments: serde_json::json!({"path": "x", "content": "y"}).to_string(),
},
};
assert_eq!(bash_command_from_call(&call), None);
}
#[test]
fn seed_text_joins_system_and_user() {
let messages = vec![
ChatMessage::system("SYSTEM_TEXT"),
ChatMessage::user("USER_TEXT"),
ChatMessage {
role: "assistant".into(),
content: Some("mentions cargo test in passing".into()),
images: vec![],
tool_calls: None,
tool_call_id: None,
name: None,
cache_control: None,
},
];
let joined = seed_text(&messages);
assert!(joined.contains("SYSTEM_TEXT"));
assert!(joined.contains("USER_TEXT"));
assert!(!joined.contains("mentions cargo test"));
}
#[test]
fn transcript_ran_test_command_detects_match() {
let messages = vec![assistant_with_tool_calls(vec![bash_call(
"c1",
"pytest tests/ -v",
)])];
assert!(transcript_ran_test_command(&messages));
}
#[test]
fn transcript_ran_test_command_false_without_bash() {
assert!(!transcript_ran_test_command(&[]));
}
#[test]
fn default_gate_trips_when_named_and_unrun() {
let project = cargo_project();
let transcript = Transcript::seed("system prompt", "run pytest tests/ -v before finishing");
let gate = default_finish_gate(gate_ctx(project.path(), true));
assert!(matches!(gate(&transcript), FinishGateOutcome::Reject(_)));
}
#[test]
fn default_gate_inert_when_not_named() {
let project = cargo_project();
let transcript = Transcript::seed("system prompt", "implement a widget");
let gate = default_finish_gate(gate_ctx(project.path(), true));
assert_eq!(gate(&transcript), FinishGateOutcome::Accept);
}
#[test]
fn default_gate_satisfied_when_run() {
let project = cargo_project();
let mut transcript = Transcript::seed("system prompt", "run cargo test before finishing");
transcript.push_assistant(None, &[bash_call("c1", "cargo test -p trusty-code")]);
let gate = default_finish_gate(gate_ctx(project.path(), true));
assert_eq!(gate(&transcript), FinishGateOutcome::Accept);
}
#[test]
fn pm_gate_trips_when_engineer_never_ran_tests() {
let project = cargo_project();
let shared: SharedTranscript = Arc::new(Mutex::new(Vec::new()));
let transcript = Transcript::seed("pm system prompt", "run pytest tests/ -v");
let gate = pm_finish_gate(shared, Some(project.path().to_path_buf()));
let FinishGateOutcome::Reject(reason) = gate(&transcript) else {
panic!("a detectable, unrun suite must still refuse the PM's finish");
};
assert!(reason.contains("Cargo.toml"), "reason was: {reason}");
}
#[test]
fn pm_gate_satisfied_when_engineer_ran_tests() {
let shared: SharedTranscript = Arc::new(Mutex::new(vec![TurnRecord {
role: "python-engineer".into(),
model: "test-model".into(),
text: String::new(),
tool_calls: vec!["bash".into()],
ran_test_command: true,
usage: crate::perf::TokenUsage::default(),
}]));
let project = cargo_project();
let transcript = Transcript::seed("pm system prompt", "run pytest tests/ -v");
let gate = pm_finish_gate(shared, Some(project.path().to_path_buf()));
assert_eq!(gate(&transcript), FinishGateOutcome::Accept);
}
#[test]
fn pm_gate_poisoned_lock_warns_and_trips() {
let shared: SharedTranscript = Arc::new(Mutex::new(Vec::new()));
{
let shared = shared.clone();
let _ = std::thread::spawn(move || {
let _guard = shared.lock().expect("lock for poisoning");
panic!("intentional poison for pm_gate_poisoned_lock_warns_and_trips");
})
.join();
}
assert!(shared.is_poisoned(), "setup must actually poison the lock");
crate::test_support::begin_capture();
let project = cargo_project();
let transcript = Transcript::seed("pm system prompt", "run pytest tests/ -v");
let gate = pm_finish_gate(shared, Some(project.path().to_path_buf()));
let result = gate(&transcript);
assert!(
matches!(result, FinishGateOutcome::Reject(_)),
"a poisoned lock must still trip the gate (fail toward verify)"
);
let captured = crate::test_support::captured_at_least(tracing::Level::WARN);
assert!(
captured.iter().any(|m| m.contains("lock poisoned")),
"expected a warn-level poisoned-lock log, got: {captured:?}"
);
}
#[test]
fn pm_gate_inert_when_not_named() {
let shared: SharedTranscript = Arc::new(Mutex::new(Vec::new()));
let project = cargo_project();
let transcript = Transcript::seed("pm system prompt", "coordinate the widget build");
let gate = pm_finish_gate(shared, Some(project.path().to_path_buf()));
assert_eq!(gate(&transcript), FinishGateOutcome::Accept);
}
#[test]
fn named_test_command_returns_the_matched_text() {
assert_eq!(
named_test_command("then run cargo test before finishing").as_deref(),
Some("cargo test")
);
assert_eq!(named_test_command("implement a widget"), None);
}
#[test]
fn detect_manifest_names_each_ecosystem() {
type ManifestCase<'a> = (&'a [(&'a str, &'a str)], &'a str, &'a str);
let cases: &[ManifestCase] = &[
(&[("Cargo.toml", "[package]")], "Cargo.toml", "cargo test"),
(
&[("package.json", r#"{"scripts":{"test":"vitest"}}"#)],
"package.json",
"npm test",
),
(
&[
("package.json", r#"{"scripts":{"test":"vitest"}}"#),
("pnpm-lock.yaml", "lockfileVersion: '9.0'"),
],
"package.json",
"pnpm test",
),
(
&[("pyproject.toml", "[project]")],
"pyproject.toml",
"pytest",
),
(&[("pytest.ini", "[pytest]")], "pytest.ini", "pytest"),
(&[("go.mod", "module x")], "go.mod", "go test ./..."),
];
for (files, manifest, command) in cases {
let dir = tempfile::tempdir().expect("tempdir");
for (name, body) in *files {
std::fs::write(dir.path().join(name), body).expect("write manifest");
}
assert_eq!(
detect_test_command(Some(dir.path()), "cargo test"),
Ok(TestCommandTarget::Manifest {
manifest: (*manifest).to_string(),
command: (*command).to_string(),
}),
"unexpected detection for {files:?}"
);
}
}
#[test]
fn detect_package_json_without_test_script_is_not_a_manifest() {
let dir = tempfile::tempdir().expect("tempdir");
std::fs::write(dir.path().join("package.json"), r#"{"name":"x"}"#).expect("write package.json");
assert_eq!(
detect_test_command(Some(dir.path()), "npm test"),
Ok(TestCommandTarget::PromptNamed {
command: "npm test".to_string(),
})
);
}
#[test]
fn detect_undetectable_without_root_or_on_empty_root() {
assert_eq!(
detect_test_command(None, "cargo test"),
Err(UndetectableReason::NoProjectBound)
);
let empty = tempfile::tempdir().expect("tempdir");
assert_eq!(
detect_test_command(Some(empty.path()), "cargo test"),
Err(UndetectableReason::EmptyProjectRoot)
);
}
#[test]
fn detect_falls_back_to_prompt_named_on_non_empty_root() {
let dir = tempfile::tempdir().expect("tempdir");
std::fs::write(dir.path().join("README.md"), "# challenge").expect("write README");
assert_eq!(
detect_test_command(Some(dir.path()), "pytest tests/"),
Ok(TestCommandTarget::PromptNamed {
command: "pytest tests/".to_string(),
})
);
}
#[test]
fn default_gate_accepts_without_bash_tool() {
let empty = tempfile::tempdir().expect("tempdir");
let transcript = Transcript::seed("system prompt", "run cargo test before finishing");
let gate = default_finish_gate(gate_ctx(empty.path(), false));
let FinishGateOutcome::AcceptWithNote(note) = gate(&transcript) else {
panic!("an agent with no bash tool must not be refused");
};
assert!(note.contains("`bash`"), "note was: {note}");
}
#[test]
fn default_gate_accepts_on_empty_project_root() {
let empty = tempfile::tempdir().expect("tempdir");
let transcript = Transcript::seed("system prompt", "run cargo test before finishing");
let gate = default_finish_gate(gate_ctx(empty.path(), true));
let FinishGateOutcome::AcceptWithNote(note) = gate(&transcript) else {
panic!("an empty project root must not produce a refusal");
};
assert!(note.contains("empty"), "note was: {note}");
assert!(note.contains("no test command was run"), "note was: {note}");
}
#[test]
fn default_gate_refusal_names_the_manifest() {
let project = cargo_project();
let transcript = Transcript::seed("system prompt", "run cargo test before finishing");
let gate = default_finish_gate(gate_ctx(project.path(), true));
let FinishGateOutcome::Reject(reason) = gate(&transcript) else {
panic!("a detectable, unrun suite must still be refused");
};
assert!(reason.contains("Cargo.toml"), "reason was: {reason}");
assert!(reason.contains("cargo test"), "reason was: {reason}");
}
#[test]
fn pm_gate_accepts_on_empty_project_root() {
let empty = tempfile::tempdir().expect("tempdir");
let shared: SharedTranscript = Arc::new(Mutex::new(Vec::new()));
let transcript = Transcript::seed("pm system prompt", "run pytest tests/ -v");
let gate = pm_finish_gate(shared, Some(empty.path().to_path_buf()));
let FinishGateOutcome::AcceptWithNote(note) = gate(&transcript) else {
panic!("an empty project root must not produce a PM refusal");
};
assert!(note.contains("empty"), "note was: {note}");
}