use super::*;
#[tokio::test]
async fn runtime_prompt_budget_with_registry_catalog() {
use crate::config::ToolDocumentationMode;
use crate::config::types::CapabilityLevel;
use crate::core::agent::harness_kernel::SessionToolCatalogSnapshot;
use crate::llm::providers::OpenAIProvider;
use crate::prompts::{
RuntimePromptContract, append_fresh_runtime_tool_prompt_sections_for_model, append_runtime_mode_sections,
};
use crate::tools::handlers::{SessionSurface, SessionToolsConfig, ToolModelCapabilities};
use crate::tools::registry::ToolRegistry;
let workspace = tempfile::tempdir().expect("workspace");
let registry = ToolRegistry::new_for_schema(workspace.path().to_path_buf()).await;
let provider = OpenAIProvider::new("offline-fixture".into());
for planning in [false, true] {
let catalog_config = SessionToolsConfig::full_public(
SessionSurface::Interactive,
CapabilityLevel::CodeSearch,
ToolDocumentationMode::Progressive,
ToolModelCapabilities::default(),
)
.with_planning_active(planning);
let definitions = registry.model_tools(catalog_config).await;
assert!(!definitions.is_empty());
let snapshot =
SessionToolCatalogSnapshot::new(7, 9, planning, true, Some(std::sync::Arc::new(definitions)), false);
for mode in [
SystemPromptMode::Default,
SystemPromptMode::Minimal,
SystemPromptMode::Lightweight,
SystemPromptMode::Specialized,
] {
for shell in [ShellPromptProfile::UnixLike, ShellPromptProfile::PowerShell] {
let mut config = VTCodeConfig::default();
config.agent.system_prompt_mode = mode;
config.agent.shell_prompt_profile = shell;
config.agent.include_temporal_context = false;
config.agent.include_working_directory = false;
config.agent.max_system_prompt_tokens = 100_000;
config.context.max_context_tokens = 128_000;
let sections = build_prompt_sections_with_layers(
Some(&config),
None,
&crate::prompts::resources::SystemPromptLayers::default(),
);
let mut prompt = join_prompt_sections(§ions);
append_runtime_mode_sections(
&mut prompt,
RuntimePromptContract {
planning_active: planning,
request_user_input_enabled: true,
..Default::default()
},
);
append_fresh_runtime_tool_prompt_sections_for_model(
&mut prompt,
&snapshot,
true,
shell.resolve_for_current_platform(),
&provider,
crate::config::constants::models::openai::DEFAULT_MODEL,
Some(&config),
);
let lines = prompt.lines().count();
let tokens = estimate_tokens(&prompt);
eprintln!("{mode:?} {shell:?} planning={planning}: {lines} lines, {tokens} tokens");
assert!(lines <= BUILT_IN_COMPOSED_MAX_LINES, "{mode:?} {shell:?} planning={planning}: {lines} lines");
assert!(
tokens <= REGISTRY_RUNTIME_MAX_TOKENS_USIZE,
"{mode:?} {shell:?} planning={planning}: {tokens} tokens"
);
}
}
}
}
#[test]
fn built_in_composed_prompt_budget_without_workspace_additions() {
for mode in [
SystemPromptMode::Default,
SystemPromptMode::Minimal,
SystemPromptMode::Lightweight,
SystemPromptMode::Specialized,
] {
let mut config = VTCodeConfig::default();
config.agent.system_prompt_mode = mode;
config.agent.include_temporal_context = false;
config.agent.include_working_directory = false;
config.agent.instruction_max_bytes = 0;
config.agent.shell_prompt_profile = ShellPromptProfile::UnixLike;
let sections = build_prompt_sections_with_layers(
Some(&config),
None,
&crate::prompts::resources::SystemPromptLayers::default(),
);
let prompt = join_prompt_sections(§ions);
let lines = prompt.lines().count();
let tokens = estimate_tokens(&prompt);
eprintln!("{mode:?}: {lines} lines, {tokens} estimated tokens");
assert!(lines <= BUILT_IN_COMPOSED_MAX_LINES, "{mode:?} built-in prompt has {lines} lines");
assert!(
tokens <= BUILT_IN_COMPOSED_MAX_TOKENS_USIZE,
"{mode:?} built-in prompt has {tokens} estimated tokens"
);
}
}
#[test]
fn composed_prompt_preserves_override_and_append_layers() {
use crate::prompts::resources::SystemPromptLayers;
use crate::prompts::runtime_guidance::RUNTIME_GUIDANCE_SECTION;
let layers = SystemPromptLayers {
override_body: Some("custom override".to_string()),
append_bodies: vec!["first append".to_string(), "second append".to_string()],
};
let sections = build_prompt_sections_with_layers(None, None, &layers);
let prompt = join_prompt_sections(§ions);
assert!(prompt.starts_with("custom override\n\nfirst append\n\nsecond append\n\n"));
assert_eq!(prompt.matches(RUNTIME_GUIDANCE_SECTION).count(), 1);
assert!(!prompt.contains(PROMPT_TITLE));
}
#[test]
fn empty_tool_context_keeps_workspace_tool_heading_without_generated_guidance() {
let layers = crate::prompts::resources::SystemPromptLayers {
override_body: Some("## Active Tools\nWorkspace instructions.".to_string()),
append_bodies: Vec::new(),
};
let sections = build_prompt_sections_with_layers_option(None, Some(&PromptContext::default()), &layers, false);
assert!(sections.iter().all(|section| section.kind != SectionKind::ToolGuidelines));
let prompt = join_prompt_sections(§ions);
assert!(prompt.contains("## Active Tools\nWorkspace instructions."));
assert_eq!(prompt.matches("## Active Tools").count(), 1);
}
#[test]
fn planning_prompt_size_fixed_fixture() {
use crate::core::agent::harness_kernel::SessionToolCatalogSnapshot;
use crate::llm::provider::ToolDefinition;
use crate::llm::providers::OpenAIProvider;
use crate::prompts::{
RuntimePromptContract, append_runtime_mode_sections, append_runtime_tool_prompt_sections_for_model,
};
struct PlanningPromptSizeCase {
density: &'static str,
prompt_budget_tokens: u64,
max_prompt_bytes: usize,
max_estimated_tokens: usize,
}
let provider = OpenAIProvider::new("offline-fixture".into());
let names = [
tools::EXEC_COMMAND,
tools::CODE_SEARCH,
tools::TASK_TRACKER,
tools::REQUEST_USER_INPUT,
];
let snapshot = SessionToolCatalogSnapshot::new(
7,
9,
true,
true,
Some(std::sync::Arc::new(
names
.iter()
.map(|name| {
ToolDefinition::function(
(*name).to_string(),
"Fixture tool".to_string(),
serde_json::json!({"type": "object"}),
)
})
.collect(),
)),
false,
);
for case in [
PlanningPromptSizeCase {
density: "Default",
prompt_budget_tokens: 100_000,
max_prompt_bytes: PLANNING_FIXTURE_DEFAULT_MAX_BYTES,
max_estimated_tokens: PLANNING_FIXTURE_DEFAULT_MAX_TOKENS_USIZE,
},
PlanningPromptSizeCase {
density: "Minimal",
prompt_budget_tokens: 1,
max_prompt_bytes: PLANNING_FIXTURE_MINIMAL_MAX_BYTES,
max_estimated_tokens: PLANNING_FIXTURE_MINIMAL_MAX_TOKENS_USIZE,
},
] {
let mut config = VTCodeConfig::default();
config.agent.system_prompt_mode = SystemPromptMode::Minimal;
config.agent.include_temporal_context = false;
config.agent.include_working_directory = true;
config.agent.instruction_max_bytes = 0;
config.agent.shell_prompt_profile = ShellPromptProfile::UnixLike;
let mut context = PromptContext {
available_tools: names.iter().map(|name| (*name).to_string()).collect(),
..Default::default()
};
context.set_current_directory(PathBuf::from("/workspace"));
let sections = build_prompt_sections_with_layers(
Some(&config),
Some(&context),
&crate::prompts::resources::SystemPromptLayers::default(),
);
let (mut prompt, report) = apply_token_budget(
sections,
config.agent.max_system_prompt_tokens,
config.agent.system_prompt_budget_warning,
config.agent.trim_system_prompt,
0,
);
assert!(report.trimmed_sections.is_empty(), "fixture must include every composed section");
assert_eq!(report.layer_token_estimate, 0, "default layers contribute nothing");
append_runtime_mode_sections(
&mut prompt,
RuntimePromptContract {
planning_active: true,
request_user_input_enabled: true,
..Default::default()
},
);
config.agent.max_system_prompt_tokens = case.prompt_budget_tokens;
append_runtime_tool_prompt_sections_for_model(
&mut prompt,
&snapshot,
true,
ResolvedShellPromptProfile::UnixLike,
&provider,
crate::config::constants::models::openai::DEFAULT_MODEL,
Some(&config),
);
eprintln!(
"planning fixture {}: {} lines, {} bytes, {} estimated tokens",
case.density,
prompt.lines().count(),
prompt.len(),
estimate_tokens(&prompt)
);
assert!(prompt.contains(PLANNING_WORKFLOW_PLAN_PERSISTENCE_POLICY_LINE));
assert!(prompt.contains("Checklists do not persist plans"));
assert!(prompt.contains("Rejected plans stay blocked; repair before approval"));
assert!(
prompt.lines().count() <= BUILT_IN_COMPOSED_MAX_LINES,
"{} planning fixture exceeded line budget",
case.density
);
assert!(prompt.len() <= case.max_prompt_bytes, "{} planning fixture exceeded byte budget", case.density);
assert!(
estimate_tokens(&prompt) <= case.max_estimated_tokens,
"{} planning fixture exceeded token budget",
case.density
);
}
}
#[tokio::test]
async fn test_minimal_mode_selection() {
let mut config = VTCodeConfig::default();
config.agent.system_prompt_mode = SystemPromptMode::Minimal;
config.agent.include_temporal_context = false;
config.agent.include_working_directory = false;
config.agent.instruction_max_bytes = 0;
let result = compose_system_instruction_text(&PathBuf::from("."), Some(&config), None).await;
assert!(
result.len() < MINIMAL_COMPOSED_MAX_BYTES,
"Minimal mode should produce <{MINIMAL_COMPOSED_MAX_BYTES} chars (was {} chars)",
result.len()
);
assert!(result.contains("VT Code"), "Should contain VT Code identifier");
}
#[tokio::test]
async fn test_default_prompt_selection() {
let mut config = VTCodeConfig::default();
config.agent.system_prompt_mode = SystemPromptMode::Default;
config.agent.include_temporal_context = false;
config.agent.include_working_directory = false;
config.agent.instruction_max_bytes = 0;
let result = compose_system_instruction_text(&PathBuf::from("."), Some(&config), None).await;
assert!(
result.len() <= DEFAULT_COMPOSED_MAX_BYTES,
"Default mode should stay sparse with runtime guidance (<={DEFAULT_COMPOSED_MAX_BYTES} bytes, was {} bytes)",
result.len()
);
assert!(result.contains("`exec_command`, `write_stdin`, and `apply_patch`"));
assert!(result.contains("## Shell Profile"));
assert!(!result.contains("task_tracker"));
assert!(!result.contains("@file"));
assert!(result.contains("Planning workflow"));
}
#[tokio::test]
async fn test_lightweight_mode_selection() {
let mut config = VTCodeConfig::default();
config.agent.system_prompt_mode = SystemPromptMode::Lightweight;
config.agent.include_temporal_context = false;
config.agent.include_working_directory = false;
config.agent.instruction_max_bytes = 0;
let result = compose_system_instruction_text(&PathBuf::from("."), Some(&config), None).await;
assert!(result.len() > 100, "Lightweight should be >100 chars");
assert!(
result.len() < LIGHTWEIGHT_COMPOSED_MAX_BYTES,
"Lightweight should be compact with runtime guidance (<{LIGHTWEIGHT_COMPOSED_MAX_BYTES} chars, was {} chars)",
result.len()
);
assert!(result.contains("task_tracker"));
assert!(!result.contains("@file"));
assert!(result.contains("act directly in this thread"));
}
#[tokio::test]
async fn test_lightweight_mode_skips_structured_reasoning_by_default() {
let mut config = VTCodeConfig::default();
config.agent.system_prompt_mode = SystemPromptMode::Lightweight;
config.agent.include_temporal_context = false;
config.agent.include_working_directory = false;
config.agent.instruction_max_bytes = 0;
config.agent.include_structured_reasoning_tags = None;
let result = compose_system_instruction_text(&PathBuf::from("."), Some(&config), None).await;
assert!(
!result.contains("## Structured Reasoning"),
"Lightweight mode should omit structured reasoning by default"
);
}
#[tokio::test]
async fn test_lightweight_mode_allows_explicit_structured_reasoning() {
let mut config = VTCodeConfig::default();
config.agent.system_prompt_mode = SystemPromptMode::Lightweight;
config.agent.include_temporal_context = false;
config.agent.include_working_directory = false;
config.agent.instruction_max_bytes = 0;
config.agent.include_structured_reasoning_tags = Some(true);
let result = compose_system_instruction_text(&PathBuf::from("."), Some(&config), None).await;
assert!(
result.contains("## Structured Reasoning"),
"Lightweight mode should include structured reasoning when explicitly enabled"
);
assert!(result.contains("<reasoning_plan>"));
assert!(!result.contains("`<plan>` steps"), "<plan> is reserved for approval artifacts");
}
#[tokio::test]
async fn test_default_prompt_omits_structured_reasoning_by_default() {
let mut config = VTCodeConfig::default();
config.agent.system_prompt_mode = SystemPromptMode::Default;
config.agent.include_temporal_context = false;
config.agent.include_working_directory = false;
config.agent.instruction_max_bytes = 0;
config.agent.include_structured_reasoning_tags = None;
let result = compose_system_instruction_text(&PathBuf::from("."), Some(&config), None).await;
assert!(
!result.contains("## Structured Reasoning"),
"Default mode should omit structured reasoning by default"
);
}
#[tokio::test]
async fn test_specialized_prompt_omits_structured_reasoning_by_default() {
let mut config = VTCodeConfig::default();
config.agent.system_prompt_mode = SystemPromptMode::Specialized;
config.agent.include_temporal_context = false;
config.agent.include_working_directory = false;
config.agent.instruction_max_bytes = 0;
config.agent.include_structured_reasoning_tags = None;
let result = compose_system_instruction_text(&PathBuf::from("."), Some(&config), None).await;
assert!(
!result.contains("## Structured Reasoning"),
"Specialized mode should omit structured reasoning unless explicitly enabled"
);
}
#[tokio::test]
async fn test_specialized_mode_selection() {
let mut config = VTCodeConfig::default();
config.agent.system_prompt_mode = SystemPromptMode::Specialized;
config.agent.include_temporal_context = false;
config.agent.include_working_directory = false;
config.agent.instruction_max_bytes = 0;
let result = compose_system_instruction_text(&PathBuf::from("."), Some(&config), None).await;
assert!(
result.len() <= SPECIALIZED_COMPOSED_MAX_BYTES,
"Specialized should stay sparse with runtime guidance (<={SPECIALIZED_COMPOSED_MAX_BYTES} chars, was {} chars)",
result.len()
);
assert!(result.contains("task_tracker"));
assert!(result.contains("<proposed_plan>"));
assert!(result.contains(
"- When repo-wide invariants matter, also read the architecture documents the instruction map points to."
));
assert!(!result.contains("ARCHITECTURAL_INVARIANTS"));
}
#[test]
fn test_prompt_mode_enum_parsing() {
assert_eq!(SystemPromptMode::parse("minimal"), Some(SystemPromptMode::Minimal));
assert_eq!(SystemPromptMode::parse("LIGHTWEIGHT"), Some(SystemPromptMode::Lightweight));
assert_eq!(SystemPromptMode::parse("Default"), Some(SystemPromptMode::Default));
assert_eq!(SystemPromptMode::parse("specialized"), Some(SystemPromptMode::Specialized));
assert_eq!(SystemPromptMode::parse("invalid"), None);
}
#[test]
fn operating_profile_deltas_share_canonical_sentences() {
assert!(MINIMAL_OPERATING_PROFILE_DELTA.contains(OPERATING_TASK_TRACKER));
assert!(LIGHTWEIGHT_OPERATING_PROFILE_DELTA.contains(OPERATING_TASK_TRACKER));
assert!(OPERATING_TASK_TRACKER.contains("use `task_tracker` updates over lists"));
for delta in [
DEFAULT_OPERATING_PROFILE_DELTA,
MINIMAL_OPERATING_PROFILE_DELTA,
LIGHTWEIGHT_OPERATING_PROFILE_DELTA,
SPECIALIZED_OPERATING_PROFILE_DELTA,
] {
assert!(!delta.contains("start_planning"), "{delta}");
}
assert!(!DEFAULT_OPERATING_PROFILE_DELTA.contains("task_tracker"));
}
#[test]
fn plan_quality_line_requires_scope_section() {
let line = PLANNING_WORKFLOW_PLAN_QUALITY_LINE;
assert!(line.contains("`## Scope`"));
assert!(line.contains("never tracker steps"));
}
#[test]
fn plan_quality_line_keeps_rejected_work_blocked_until_repaired() {
assert!(PLANNING_WORKFLOW_PLAN_QUALITY_LINE.contains("Rejected plans stay blocked; repair before approval"));
}
#[test]
fn plan_quality_line_forbids_markdown_link_file_references() {
let line = PLANNING_WORKFLOW_PLAN_QUALITY_LINE;
assert!(line.contains("never as markdown links or editor/IDE URIs"));
assert!(line.contains("vscode-file://"));
assert!(line.contains("plain text or inline code"));
}
#[test]
fn plan_quality_line_shows_canonical_step_format() {
assert!(
PLANNING_WORKFLOW_PLAN_QUALITY_LINE
.contains(crate::tools::handlers::planning_workflow::artifacts::CANONICAL_STEP_FORMAT),
"quality line must embed artifacts::CANONICAL_STEP_FORMAT verbatim"
);
}
#[test]
fn plan_quality_line_requires_concrete_verify_checks() {
assert!(PLANNING_WORKFLOW_PLAN_QUALITY_LINE.contains("never as a semicolon chain"));
assert!(PLANNING_WORKFLOW_PLAN_QUALITY_LINE.contains("bun x markdownlint-cli2 README.md"));
let line = PLANNING_WORKFLOW_PLAN_QUALITY_LINE;
assert!(line.contains("must exit 0 on success"));
assert!(line.contains("grep/rg exit 1 cannot satisfy completion"));
assert!(line.contains("both present and absent inputs"));
assert!(line.contains("one concrete `verify:`/`verification:` command or observable check"));
assert!(
line.contains("Scope each `verify:` command to the step's files"),
"quality line must scope verify commands to the step's files so full-repo checks cannot fail on pre-existing out-of-scope findings"
);
assert!(line.contains("vague prose"));
assert!(line.contains("comma-separated verify entries that are not commands or observable checks"));
assert!(
line.contains("Commas inside single or double quotes stay inside one verify item"),
"quality line must state the quoted-comma bracket rule so first-attempt plans do not fragment shell patterns"
);
assert!(
line.contains("sed -n") && line.contains("grep -n"),
"quality line must name inspection commands that recovery synthesis naturally emits"
);
assert!(
line.contains("`git log`")
&& line.contains("`git show`")
&& line.contains("`git diff`")
&& line.contains("`git blame`")
);
assert!(line.contains("Reuse evidence; focus output"));
}
#[test]
fn planning_workflow_persistence_policy_assigns_plan_lifecycle_to_runtime() {
let line = PLANNING_WORKFLOW_PLAN_PERSISTENCE_POLICY_LINE;
assert!(line.contains("Emit exactly one final `<proposed_plan>` block"));
assert!(line.contains("no surrounding prose"));
assert!(line.contains("Do not use shell commands or file-writing tools to create or modify `.vtcode/plans/`"));
assert!(line.contains("runtime owns plan/tracker persistence and validation"));
assert!(line.contains("approval controls only after successful persistence"));
assert!(line.contains("Checklists do not persist plans"));
assert!(line.contains("Resume cancelled planning only on fresh input"));
assert!(PLANNING_WORKFLOW_PLAN_POLICY_LINE.contains("Exhausted plan validation or recovery waits for retry"));
assert!(PLANNING_WORKFLOW_PLAN_POLICY_LINE.contains("Explicit Plan mode requires approval even in full-auto"));
assert!(PLANNING_WORKFLOW_PLAN_POLICY_LINE.contains("User answers never approve implementation"));
}
#[test]
fn test_minimal_prompt_token_count() {
let approx_tokens = estimate_token_count(minimal_system_prompt());
assert!(
approx_tokens <= MINIMAL_STATIC_PROMPT_MAX_TOKENS_U64,
"Minimal prompt should stay compact, got ~{approx_tokens}"
);
}