use std::sync::Arc;
use regex::Regex;
use serde_json::Value;
use crate::agent_loop::{FinishGate, Transcript};
use crate::llm::{ChatMessage, ToolCall};
use crate::run_task::SharedTranscript;
use crate::tools::BASH_TOOL_NAME;
const GATE_REASON_ENGINEER: &str = "finish_task rejected: the task prompt or project context \
names a runnable test command (a pytest/cargo/npm/pnpm/go test invocation), but no matching \
command has been run yet in this session. Run the named test suite via the bash tool, \
reconcile any failures, and only then call finish_task again.";
const GATE_REASON_PM: &str = "finish_task rejected: the task prompt or project context names a \
runnable test command (a pytest/cargo/npm/pnpm/go test invocation), but the delegated \
engineer's transcript shows no matching invocation yet. Delegate a follow-up task instructing \
the engineer to run the named test suite and reconcile any failures before finishing.";
fn test_command_pattern() -> Regex {
Regex::new(
r"(?:pytest\s+\S+)|(?:cargo\s+test)|(?:npm\s+test)|(?:pnpm\s+test)|(?:go\s+test)|(?:python\s+-m\s+pytest)",
)
.expect("test_command_pattern: hardcoded regex literal must compile")
}
pub fn names_test_command(text: &str) -> bool {
test_command_pattern().is_match(text)
}
pub fn is_test_command(command: &str) -> bool {
test_command_pattern().is_match(command)
}
pub fn bash_command_from_call(call: &ToolCall) -> Option<String> {
if call.function.name != BASH_TOOL_NAME {
return None;
}
let parsed: Value = serde_json::from_str(&call.function.arguments).ok()?;
parsed.get("command")?.as_str().map(str::to_string)
}
fn transcript_ran_test_command(messages: &[ChatMessage]) -> bool {
messages
.iter()
.filter_map(|m| m.tool_calls.as_ref())
.flatten()
.filter_map(bash_command_from_call)
.any(|cmd| is_test_command(&cmd))
}
fn seed_text(messages: &[ChatMessage]) -> String {
messages
.iter()
.filter(|m| m.role == "system" || m.role == "user")
.filter_map(|m| m.content.as_deref())
.collect::<Vec<_>>()
.join("\n")
}
pub fn default_finish_gate() -> FinishGate {
Arc::new(|transcript: &Transcript| {
let messages = transcript.messages();
if !names_test_command(&seed_text(&messages)) {
return None;
}
if transcript_ran_test_command(&messages) {
return None;
}
Some(GATE_REASON_ENGINEER.to_string())
})
}
pub fn pm_finish_gate(shared: SharedTranscript) -> FinishGate {
Arc::new(move |transcript: &Transcript| {
let messages = transcript.messages();
if !names_test_command(&seed_text(&messages)) {
return None;
}
let ran = shared
.lock()
.map(|turns| turns.iter().any(|t| t.ran_test_command))
.unwrap_or(false);
if ran {
return None;
}
Some(GATE_REASON_PM.to_string())
})
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use super::*;
use crate::llm::FunctionCall;
use crate::run_task::TurnRecord;
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,
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()),
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 transcript = Transcript::seed("system prompt", "run pytest tests/ -v before finishing");
let gate = default_finish_gate();
assert!(gate(&transcript).is_some());
}
#[test]
fn default_gate_inert_when_not_named() {
let transcript = Transcript::seed("system prompt", "implement a widget");
let gate = default_finish_gate();
assert!(gate(&transcript).is_none());
}
#[test]
fn default_gate_satisfied_when_run() {
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();
assert!(gate(&transcript).is_none());
}
#[test]
fn pm_gate_trips_when_engineer_never_ran_tests() {
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);
assert!(gate(&transcript).is_some());
}
#[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 transcript = Transcript::seed("pm system prompt", "run pytest tests/ -v");
let gate = pm_finish_gate(shared);
assert!(gate(&transcript).is_none());
}
#[test]
fn pm_gate_inert_when_not_named() {
let shared: SharedTranscript = Arc::new(Mutex::new(Vec::new()));
let transcript = Transcript::seed("pm system prompt", "coordinate the widget build");
let gate = pm_finish_gate(shared);
assert!(gate(&transcript).is_none());
}
}