use std::sync::Arc;
use crate::agents::AgentConfig;
use crate::mode::HarnessMode;
use crate::prompt::{
BASE_PREAMBLE, BASE_PREAMBLE_VERSION, BATCH_WRITE_GUIDANCE, DISCOVERY_GUIDANCE,
FILE_DISCOVERY_GUIDANCE, GATED_SECTIONS, PromptAssembler, assemble_system_prompt,
assemble_system_prompt_for_mode,
};
use crate::tools::{
EditTool, FinishTaskTool, GlobTool, GrepTool, ListDirTool, ReadFileTool, ToolRegistry,
TrustySearchTool, WriteFileTool, WriteFilesTool,
};
fn config_with_prompt(content: &str) -> AgentConfig {
let mut cfg = AgentConfig::default();
cfg.system_prompt.content = content.to_string();
cfg
}
fn pm_like_registry() -> ToolRegistry {
let mut reg = ToolRegistry::new();
reg.register(Arc::new(FinishTaskTool::new()));
reg
}
fn engineer_like_registry() -> ToolRegistry {
let project = std::path::Path::new(".");
let mut reg = ToolRegistry::new();
reg.register(Arc::new(GlobTool::new(project)));
reg.register(Arc::new(GrepTool::new(project)));
reg.register(Arc::new(ListDirTool::new(project)));
reg.register(Arc::new(TrustySearchTool::new(project)));
reg.register(Arc::new(WriteFileTool::new(project)));
reg.register(Arc::new(WriteFilesTool::new(project)));
reg.register(Arc::new(FinishTaskTool::new()));
reg
}
fn gated_tool_names() -> Vec<&'static str> {
GATED_SECTIONS
.iter()
.flat_map(|(_, names, _)| names.iter().copied())
.collect()
}
#[test]
fn assembled_order_is_stable() {
let cfg = config_with_prompt("AGENT_PROMPT_MARKER");
let out = assemble_system_prompt(
&cfg,
Some("PROJECT_CONTEXT_MARKER"),
Some("FALLBACK_GUIDANCE_MARKER"),
);
let base = out.find(BASE_PREAMBLE).expect("base present");
let agent = out.find("AGENT_PROMPT_MARKER").expect("agent present");
let project = out.find("PROJECT_CONTEXT_MARKER").expect("project present");
let fallback = out
.find("FALLBACK_GUIDANCE_MARKER")
.expect("fallback present");
assert!(base < agent, "BASE must precede agent prompt");
assert!(agent < project, "agent prompt must precede project context");
assert!(
project < fallback,
"project context must precede fallback guidance"
);
}
#[test]
fn base_identical_across_calls() {
let cfg = config_with_prompt("You are an engineer.");
let first = assemble_system_prompt(&cfg, Some("# Project\nrules"), None);
let second = assemble_system_prompt(&cfg, Some("# Project\nrules"), None);
assert_eq!(first, second);
}
#[test]
fn omitted_sections_produce_no_double_separator() {
let cfg = config_with_prompt("Solo agent prompt.");
let out = assemble_system_prompt(&cfg, None, None);
assert!(
!out.contains("\n\n---\n\n\n\n---\n\n"),
"must not contain a doubled separator: {out:?}"
);
assert!(
!out.ends_with("\n\n---\n\n"),
"must not end with a dangling separator: {out:?}"
);
assert_eq!(out.matches("\n\n---\n\n").count(), 1);
}
#[test]
fn empty_agent_prompt_skipped() {
let cfg = config_with_prompt("");
let out = assemble_system_prompt(&cfg, None, None);
assert!(out.starts_with(BASE_PREAMBLE), "must start with BASE");
assert_eq!(out, BASE_PREAMBLE, "BASE only — no separators added");
assert!(
!out.contains("\n\n---\n\n"),
"no separator with one section"
);
}
#[test]
fn whitespace_only_sections_are_skipped() {
let cfg = config_with_prompt(" \n ");
let out = assemble_system_prompt(&cfg, Some("\n\t \n"), Some(" "));
assert_eq!(out, BASE_PREAMBLE);
}
#[test]
fn fallback_guidance_is_last() {
let cfg = config_with_prompt("Agent prompt.");
let out = assemble_system_prompt(&cfg, Some("Project context."), Some("FALLBACK_LAST"));
assert!(
out.ends_with("FALLBACK_LAST"),
"fallback must be last: {out:?}"
);
let project = out.find("Project context.").expect("project present");
let fallback = out.find("FALLBACK_LAST").expect("fallback present");
assert!(project < fallback);
}
#[test]
fn native_tier_omits_fallback_section() {
let cfg = config_with_prompt("Agent prompt.");
let out = assemble_system_prompt(&cfg, Some("PROJECT_END"), None);
assert!(out.ends_with("PROJECT_END"));
assert_eq!(out.matches("\n\n---\n\n").count(), 2);
}
#[test]
fn base_preamble_contains_required_blocks() {
assert!(
BASE_PREAMBLE.contains("tool call"),
"tool-use protocol block missing"
);
assert!(
BASE_PREAMBLE.contains("project root"),
"filesystem-safety block missing"
);
assert!(
BASE_PREAMBLE.contains("## Summary"),
"output-convention block missing"
);
assert!(
BASE_PREAMBLE.contains("contains no tool call"),
"finish-convention block missing"
);
assert!(
BASE_PREAMBLE.contains("trusty-code harness"),
"identity/role block missing"
);
}
#[test]
fn base_preamble_requires_running_project_test_suite_before_finishing() {
assert!(
BASE_PREAMBLE.contains("run it, then report the")
|| BASE_PREAMBLE.to_lowercase().contains("run it"),
"must instruct running the project's own test suite before finishing"
);
assert!(
BASE_PREAMBLE.contains("not a substitute for the"),
"must reject self-authored tests as a substitute for the project's own suite"
);
assert!(
BASE_PREAMBLE.contains("Never claim tests passed without"),
"must forbid claiming unverified test results"
);
}
#[test]
fn base_preamble_discourages_redundant_test_reruns() {
assert!(
BASE_PREAMBLE.contains(
"ONE clean run of the suite after your LAST code change is \
sufficient"
),
"must state one clean post-change run is sufficient verification"
);
assert!(
BASE_PREAMBLE.contains("do NOT re-run the same suite again"),
"must forbid repeating an identical confirmation run over unchanged code"
);
}
#[test]
fn base_preamble_nudges_testable_design() {
assert!(
BASE_PREAMBLE.contains("pure, unit-testable core functions"),
"must nudge toward pure, unit-testable core functions"
);
assert!(
BASE_PREAMBLE.contains("thin wrapper functions"),
"must instruct keeping I/O in thin wrapper functions separate from core logic"
);
}
#[test]
fn base_preamble_requires_persistent_store_init() {
assert!(
BASE_PREAMBLE.contains("persistent store"),
"must address services backed by a database or other persistent store"
);
assert!(
BASE_PREAMBLE.contains("BEFORE the service handles its first request"),
"must instruct initializing the schema before the first request"
);
assert!(
BASE_PREAMBLE.contains("as part of constructing the application object"),
"must require creating the schema as part of constructing the application object"
);
assert!(
BASE_PREAMBLE.contains("required, primary mechanism"),
"must name eager construction-time initialization as the required, primary mechanism"
);
assert!(
BASE_PREAMBLE.contains("lifecycle event hook alone is NOT sufficient"),
"must warn that a startup or lifecycle hook alone is not sufficient"
);
assert!(
BASE_PREAMBLE
.contains("in-process test client may construct the application WITHOUT triggering"),
"must warn that an in-process test client may construct the app without firing its hooks"
);
}
#[test]
fn base_preamble_requires_tracking_the_deliverable_set() {
assert!(
BASE_PREAMBLE.contains("## Deliverable completeness"),
"BASE_PREAMBLE must carry the deliverable-completeness block (#2824)"
);
assert!(
BASE_PREAMBLE.contains("enumerate that set"),
"must instruct enumerating the required-artifact set up front"
);
assert!(
BASE_PREAMBLE.contains("which items remain outstanding"),
"must instruct tracking the outstanding items as work proceeds"
);
assert!(
BASE_PREAMBLE.contains("it is not an epilogue"),
"must state required documentation is not an epilogue"
);
assert!(
BASE_PREAMBLE.contains("the design is settled: write the required documents THEN"),
"must order required docs at the point the design settles"
);
assert!(
BASE_PREAMBLE.contains("Do the REQUIRED work before any discretionary work"),
"must order required work ahead of discretionary work"
);
assert!(
BASE_PREAMBLE.contains("while a required artifact is still \nmissing from disk")
|| BASE_PREAMBLE.contains("while a required artifact is still missing from disk"),
"must forbid starting discretionary work while a required artifact is missing"
);
assert!(
BASE_PREAMBLE.contains("Scale the tests you author yourself to the requirements"),
"must scale self-authored tests to the requirements (run-2 shipped ~130)"
);
assert!(
BASE_PREAMBLE.contains("walk your checklist one final time"),
"must require a final completeness sweep before finishing"
);
}
#[test]
fn base_preamble_batches_remaining_deliverables() {
assert!(
BATCH_WRITE_GUIDANCE.contains("ONE `write_files` call"),
"the deliverable pointer must point at the batch-write tool"
);
assert!(
BATCH_WRITE_GUIDANCE.contains("rather than one per turn"),
"must contrast batching against one-file-per-turn writes"
);
assert!(
BATCH_WRITE_GUIDANCE.contains("an N-file scaffold should cost ONE turn, not N"),
"the tool-use protocol's scaffolding bullet (#2681) must survive the move"
);
}
#[test]
fn base_preamble_is_model_agnostic() {
for forbidden in ["claude", "openai", "gpt", "anthropic", "qwen", "deepseek"] {
assert!(
!BASE_PREAMBLE.to_lowercase().contains(forbidden),
"BASE_PREAMBLE must not mention provider/model token {forbidden:?}"
);
}
}
const ILLUSTRATION_MENTIONS: &[&str] = &[
"(e.g. `write_file` then a `bash` that runs or verifies it",
"e.g. you cannot `write_file` content derived from a `read_file`",
];
fn known_tool_names() -> Vec<String> {
let project = std::path::Path::new(".");
let constructible: Vec<Box<dyn crate::tools::ToolExecutor>> = vec![
Box::new(ReadFileTool::new(project)),
Box::new(WriteFileTool::new(project)),
Box::new(WriteFilesTool::new(project)),
Box::new(EditTool::new(project)),
Box::new(GlobTool::new(project)),
Box::new(GrepTool::new(project)),
Box::new(ListDirTool::new(project)),
Box::new(TrustySearchTool::new(project)),
Box::new(FinishTaskTool::new()),
];
let mut names: Vec<String> = constructible
.iter()
.map(|tool| tool.name().to_string())
.collect();
names.extend(
[
crate::tools::BASH_TOOL_NAME,
crate::tools::DELEGATE_TO_AGENT_TOOL_NAME,
crate::tools::USE_SKILL_TOOL_NAME,
crate::tools::RECALL_SESSION_TOOL_NAME,
crate::tools::SET_GOAL_TOOL_NAME,
crate::tools::CLEAR_GOAL_TOOL_NAME,
crate::tools::TODO_WRITE_TOOL_NAME,
]
.iter()
.map(|name| (*name).to_string()),
);
names
}
fn backticked_identifiers(text: &str) -> Vec<&str> {
let spans: Vec<&str> = text.split('`').collect();
assert!(spans.len() % 2 == 1, "unbalanced backticks in: {text:?}");
spans
.iter()
.skip(1)
.step_by(2)
.copied()
.filter(|token| {
!token.is_empty() && token.chars().all(|c| c.is_ascii_lowercase() || c == '_')
})
.collect()
}
#[test]
fn base_preamble_instructs_no_registry_specific_tool() {
let known = known_tool_names();
let names_a_tool = |text: &str| {
backticked_identifiers(text)
.iter()
.any(|span| known.iter().any(|name| name == span))
};
let mut remainder = BASE_PREAMBLE.to_string();
for span in ILLUSTRATION_MENTIONS {
assert!(
remainder.contains(span),
"allowlisted illustration span is no longer in BASE_PREAMBLE: {span:?}"
);
assert!(
names_a_tool(span),
"allowlisted span names no tool, so it excuses nothing: {span:?}"
);
remainder = remainder.replace(span, "");
}
for span in backticked_identifiers(&remainder) {
assert!(
!known.iter().any(|name| name == span),
"BASE_PREAMBLE names the tool `{span}` outside ILLUSTRATION_MENTIONS. \
Every agent reads BASE, so either move the sentence into a \
registry-gated section (#4602) or, if it only illustrates the \
protocol, add its exact span to ILLUSTRATION_MENTIONS"
);
}
}
#[test]
fn every_gated_section_declares_the_tools_it_names() {
for (section, declared, _) in GATED_SECTIONS {
let named = backticked_identifiers(section);
assert!(
!named.is_empty(),
"gated section names no tool: {section:?}"
);
for name in &named {
assert!(
declared.contains(name),
"section names `{name}` but its list does not declare it"
);
}
for name in *declared {
assert!(
named.contains(name),
"list declares `{name}` but the section text never names it"
);
}
}
}
#[test]
fn base_preamble_version_is_semver_shaped() {
let parts: Vec<&str> = BASE_PREAMBLE_VERSION.split('.').collect();
assert_eq!(parts.len(), 3, "expected MAJOR.MINOR.PATCH");
for part in parts {
assert!(
part.chars().all(|c| c.is_ascii_digit()),
"non-numeric version component: {part:?}"
);
}
}
const EXPECTED_PREAMBLE_HASH: u64 = 0xb1d0_41f0_a152_88ff;
#[test]
fn base_preamble_hash_tripwire() {
const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
let mut hash = FNV_OFFSET_BASIS;
for &byte in BASE_PREAMBLE.as_bytes() {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(FNV_PRIME);
}
hash ^= BASE_PREAMBLE.len() as u64;
hash = hash.wrapping_mul(FNV_PRIME);
assert_eq!(
hash, EXPECTED_PREAMBLE_HASH,
"BASE_PREAMBLE changed — update EXPECTED_PREAMBLE_HASH and bump \
BASE_PREAMBLE_VERSION in prompt/version.rs (actual hash: {hash:#018x})"
);
}
#[test]
fn assembler_struct_matches_free_function() {
let cfg = config_with_prompt("Agent prompt.");
let via_struct = PromptAssembler.assemble(&cfg, Some("ctx"), Some("fb"));
let via_fn = assemble_system_prompt(&cfg, Some("ctx"), Some("fb"));
assert_eq!(via_struct, via_fn);
}
#[test]
fn all_sections_present_when_supplied() {
let cfg = config_with_prompt("AGENT");
let out = assemble_system_prompt(&cfg, Some("PROJECT"), Some("FALLBACK"));
assert!(out.contains(BASE_PREAMBLE));
assert!(out.contains("AGENT"));
assert!(out.contains("PROJECT"));
assert!(out.contains("FALLBACK"));
}
#[test]
fn assemble_system_prompt_for_mode_identical_when_no_skills() {
let cfg = config_with_prompt("AGENT");
let baseline = assemble_system_prompt(&cfg, Some("PROJECT"), Some("FALLBACK"));
let tools = engineer_like_registry();
let parity = assemble_system_prompt_for_mode(
HarnessMode::Parity,
&cfg,
Some("PROJECT"),
Some("FALLBACK"),
None,
Some(&tools),
);
let mode_independent =
format!("{baseline}\n\n---\n\n{FILE_DISCOVERY_GUIDANCE}\n\n---\n\n{BATCH_WRITE_GUIDANCE}");
assert_eq!(
parity, mode_independent,
"Parity = baseline + the two mode-independent gated sections"
);
let daily = assemble_system_prompt_for_mode(
HarnessMode::DailyDriver,
&cfg,
Some("PROJECT"),
Some("FALLBACK"),
None,
Some(&tools),
);
assert_eq!(
daily,
format!("{mode_independent}\n\n---\n\n{DISCOVERY_GUIDANCE}"),
"DailyDriver with no skills = Parity + the code-discovery section"
);
}
#[test]
fn guidance_never_names_an_unregistered_tool() {
let cfg = config_with_prompt("AGENT");
let registries = [
("pm (harness tools only)", pm_like_registry()),
("engineer (project tools)", engineer_like_registry()),
];
let mut mentions = 0usize;
for (label, registry) in ®istries {
for mode in [HarnessMode::Parity, HarnessMode::DailyDriver] {
let out = assemble_system_prompt_for_mode(
mode,
&cfg,
Some("PROJECT"),
Some("FALLBACK"),
Some("Available skills:\n- demo-skill: Does demo things"),
Some(registry),
);
let appended = out.replace(BASE_PREAMBLE, "");
for name in gated_tool_names() {
if !appended.contains(&format!("`{name}`")) {
continue;
}
mentions += 1;
assert!(
registry.contains(name),
"{label} / {mode:?}: prompt tells the model to call `{name}`, \
but that tool is not in its registry"
);
}
}
}
assert!(
mentions > 0,
"no prompt named any gated tool — the engineer must still be told \
about the tools it does carry"
);
}
#[test]
fn file_discovery_guidance_follows_the_registry() {
let cfg = config_with_prompt("AGENT");
let engineer = engineer_like_registry();
let pm = pm_like_registry();
for mode in [HarnessMode::Parity, HarnessMode::DailyDriver] {
let with_tools =
assemble_system_prompt_for_mode(mode, &cfg, None, None, None, Some(&engineer));
let without_tools =
assemble_system_prompt_for_mode(mode, &cfg, None, None, None, Some(&pm));
for section in [FILE_DISCOVERY_GUIDANCE, BATCH_WRITE_GUIDANCE] {
assert!(
with_tools.contains(section),
"{mode:?}: an agent holding the tools must be told about them"
);
assert!(
!without_tools.contains(section),
"{mode:?}: an agent without those tools must not be told to use them"
);
}
}
}
#[test]
fn batch_write_guidance_follows_the_registry() {
let cfg = config_with_prompt("AGENT");
let pm = assemble_system_prompt_for_mode(
HarnessMode::DailyDriver,
&cfg,
None,
None,
None,
Some(&pm_like_registry()),
);
assert!(!pm.contains("## Batching file writes"));
assert!(
!pm.contains("`write_files`"),
"the delegating PM must never be told to call `write_files`"
);
let engineer = assemble_system_prompt_for_mode(
HarnessMode::DailyDriver,
&cfg,
None,
None,
None,
Some(&engineer_like_registry()),
);
assert!(engineer.contains(BATCH_WRITE_GUIDANCE));
assert!(
engineer.contains("ONE `write_files` call"),
"the bake-off-tuned deliverable-tail pointer (#2824) must survive the move"
);
}
#[test]
fn unknown_registry_omits_every_discovery_section() {
let cfg = config_with_prompt("AGENT");
let out =
assemble_system_prompt_for_mode(HarnessMode::DailyDriver, &cfg, None, None, None, None);
for (section, _, _) in GATED_SECTIONS {
assert!(!out.contains(section));
}
assert!(!out.contains("## File discovery"));
assert!(!out.contains("## Code discovery"));
}
#[test]
fn daily_driver_appends_discovery_guidance() {
let cfg = config_with_prompt("AGENT");
let catalog = "Available skills:\n- demo-skill: Does demo things";
let tools = engineer_like_registry();
let out = assemble_system_prompt_for_mode(
HarnessMode::DailyDriver,
&cfg,
Some("PROJECT"),
Some("FALLBACK"),
Some(catalog),
Some(&tools),
);
assert!(out.contains(DISCOVERY_GUIDANCE));
assert!(out.contains("search_code"));
let guidance_at = out.find("## Code discovery").expect("guidance present");
assert!(
out.find("FALLBACK").unwrap() < guidance_at,
"guidance after fallback"
);
assert!(
guidance_at < out.find(catalog).unwrap(),
"guidance before catalog"
);
}
#[test]
fn parity_omits_discovery_guidance() {
let cfg = config_with_prompt("AGENT");
let baseline = assemble_system_prompt(&cfg, Some("PROJECT"), Some("FALLBACK"));
let tools = pm_like_registry();
let out = assemble_system_prompt_for_mode(
HarnessMode::Parity,
&cfg,
Some("PROJECT"),
Some("FALLBACK"),
Some("Available skills:\n- demo"),
Some(&tools),
);
assert_eq!(out, baseline);
assert!(!out.contains("## Code discovery"));
}
#[test]
fn daily_driver_appends_skills_catalog() {
let cfg = config_with_prompt("AGENT");
let catalog = "Available skills:\n- demo-skill: Does demo things";
let out = assemble_system_prompt_for_mode(
HarnessMode::DailyDriver,
&cfg,
Some("PROJECT"),
Some("FALLBACK"),
Some(catalog),
Some(&engineer_like_registry()),
);
assert!(out.contains("AGENT"));
assert!(out.contains(catalog));
assert!(
out.find("FALLBACK").unwrap() < out.find(catalog).unwrap(),
"the skills catalog must be the trailing section"
);
}
#[test]
fn parity_ignores_skills_catalog() {
let cfg = config_with_prompt("AGENT");
let baseline = assemble_system_prompt(&cfg, Some("PROJECT"), Some("FALLBACK"));
let catalog = "Available skills:\n- demo-skill: Does demo things";
let out = assemble_system_prompt_for_mode(
HarnessMode::Parity,
&cfg,
Some("PROJECT"),
Some("FALLBACK"),
Some(catalog),
Some(&pm_like_registry()),
);
assert_eq!(out, baseline);
assert!(!out.contains("demo-skill"));
}
#[test]
fn delegate_mode_prompt_carries_the_routing_table() {
let pm = crate::agents::resolve_agent(
std::path::Path::new("/tcode-tests-no-such-agents-dir"),
"pm",
)
.expect("the embedded `pm` card must resolve");
let assembled = assemble_system_prompt_for_mode(
HarnessMode::DailyDriver,
&pm,
None,
None,
None,
None,
);
let block = crate::assets::pm_routing_block(&assembled).unwrap_or_else(|| {
panic!("the assembled delegate-mode prompt carries no routing block (#8287)")
});
let mut cursor = 0usize;
for target in crate::assets::PM_ROUTING_ORDER {
let needle = format!("`{target}`");
let at = block[cursor..].find(&needle).unwrap_or_else(|| {
panic!(
"the assembled routing block names no `{target}` target at or after \
byte {cursor} — DOC-75 §1 fixes the order research -> engineer -> qa"
)
});
cursor += at + needle.len();
}
}