Skip to main content

vtcode_core/prompts/
guidelines.rs

1use crate::config::constants::tools;
2use crate::config::types::{CapabilityLevel, ResolvedShellPromptProfile};
3use crate::core::agent::harness_kernel::SessionToolCatalogSnapshot;
4use crate::llm::provider::ToolDefinition;
5use crate::prompts::sections::{
6    SectionBoundaryMode, append_prompt_block, remove_prompt_section, trim_trailing_newlines,
7};
8use crate::tools::registry::tool_groups;
9
10const TOOL_EXEC_COMMAND: &str = tools::EXEC_COMMAND;
11const TOOL_WRITE_STDIN: &str = tools::WRITE_STDIN;
12const TOOL_CODE_SEARCH: &str = tools::CODE_SEARCH;
13const TOOL_READ_FILE: &str = tools::READ_FILE;
14const TOOL_LIST_FILES: &str = tools::LIST_FILES;
15const TOOL_GREP_FILE: &str = tools::GREP_FILE;
16const TOOL_APPLY_PATCH: &str = tools::APPLY_PATCH;
17const TOOL_REQUEST_USER_INPUT: &str = tools::REQUEST_USER_INPUT;
18const TOOL_TASK_TRACKER: &str = tools::TASK_TRACKER;
19const SOURCE_INSPECTION_GUIDANCE: &str =
20    "- Inspect relevant source, edit a bounded region, refresh after mismatch, then verify.";
21const PUBLIC_DECISION_GUIDANCE: &str = "- Use optional `record_decision` for consequential choices, rejected approaches, or recovery changes. Give concise public rationale; ordinary reads and commands need no record.";
22const MATRIX_GUIDANCE: &str = "- `matrix`: create persists explicit tasks, checks, resources, and timeouts; start freezes the spec. The coordinator delegates execution and verification to scheduler-owned workers; discovery is idle-only. Replay restores admission before discovery; resume reconciles owned cleanup. status is a projection; pause stops dispatch; user cancel is terminal. Internal failures require reconciliation, not cancellation. Workers retain effective permissions and sandbox gates. Read leases require read-only workers. Report identity is runtime-owned; final success needs durable declared checks for the current generation, never summaries or child completion. Source and declared input changes, including submodule state, invalidate checks. Automatic retry requires replay_safe, confirmed cleanup, and at most one interrupted/timeout retry; other failures need a coordinator decision.";
23const WEB_SEARCH_GUIDANCE: &str = "- web_search uses keyless DuckDuckGo; web_fetch needs separate approval. For `antiban_blocked` or `retryable: false`, do not retry; wait `retry_after_ms` for `cooldown`; retry `network_error`/`upstream_error` once.";
24const TOOL_START_PLANNING: &str = tools::START_PLANNING;
25
26const OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE: &str = "- `verify: [skip Markdown lint if unavailable]`: report skipped; review diff/links without installing tools. Lint errors remain failures.";
27
28/// Shared cross-turn resume pointer (invariant #22). The hint body itself stays
29/// transient via `append_transient_turn_notes`; tool guidance only advertises
30/// that a turn-start `Exec session resume:` note carries the live ids so a
31/// resumed or compacted session needs zero identity reconstruction.
32const CROSS_TURN_RESUME_HINT_CLAUSE: &str =
33    "; a turn-start `Exec session resume:` hint carries the live ids when a prior turn ended mid-run.";
34
35/// The single home of `start_planning` guidance, shared by the Minimal and
36/// Default Active Tools. The tool itself asks the user before entering
37/// planning (`require_confirmation`), except under full-auto or
38/// skip-confirmations, so the model calls it rather than proposing it in prose.
39const START_PLANNING_GUIDANCE_LINE: &str = "- For demanding, ambiguous, or multi-phase tasks, call `start_planning`; it asks the user before entering the read-only Planning workflow unless the session runs in full-auto or skips confirmations. Skip it for straightforward changes.";
40
41/// Planning-workflow `task_tracker` index rules. While planning, the tracker
42/// routes to the plan sidecar, which rejects index 0 (`index_path components
43/// must be >= 1`); checklist-level `index: 0` completion exists only outside
44/// planning, so neither line advertises it.
45const PLANNING_TASK_TRACKER_COMPACT_LINE: &str = "- `task_tracker`: list {\"action\":\"list\"}; updates use positive index/index_path or items, never conflicting fields; index 0 is invalid while planning. Keep blockers and verification open. `scope_review` checks cannot satisfy functional `verify` checks.";
46const PLANNING_TASK_TRACKER_INDEX_LINE: &str = "- `task_tracker`: list {\"action\":\"list\"}; update {\"action\":\"update\",\"index\":1,\"status\":\"in_progress\"}; bulk {\"action\":\"update\",\"items\":[\"[x] Done\",\"[ ] Remaining\"]}. Use positive flat indices or hierarchical index_path (index 0 is invalid while planning), or items for full checklist replacement. Omit unused fields; never combine index, index_path, and items. `scope_review` checks cannot satisfy functional `verify` checks.";
47
48/// Context-token ceiling at or below which Active Tools documentation
49/// resolves to the Minimal density.
50const MINIMAL_CONTEXT_TOKEN_CEILING: usize = 32_000;
51
52/// The single home of the parallel-call hint, shared by the Minimal and
53/// Default Active Tools; emitted only when the provider keeps parallel tool
54/// configuration enabled.
55const PARALLEL_TOOLS_LINE: &str = "- Run independent tools in parallel when inputs do not depend on each other.";
56
57/// The single home of the `code_search` filter hygiene rule, shared by the
58/// Minimal, Default, and planning Active Tools variants.
59const CODE_SEARCH_FILTER_LINE: &str = "- `code_search`: omit unused filters; no empty values (`path: \"\"`).";
60
61/// The single home of the `request_user_input` threshold rule, shared by the
62/// Minimal planning addendum and the planning Active Tools.
63const REQUEST_USER_INPUT_LINE: &str =
64    "- Use `request_user_input` only for material blockers remaining after repository exploration.";
65
66/// Read-only capability line shared by the capability-level and
67/// tool-fallback arms of `capability_mode_line`.
68const CAPABILITY_READ_ONLY_LINE: &str =
69    "- Capabilities: read-only. Analyze and search, but do not modify files or run shell commands.";
70
71/// Shared `write_stdin` recovery clause; each profile adds its own
72/// rerun/wait policy around it.
73const WRITE_STDIN_RECOVERY_CLAUSE: &str = "; if missing, recover prior output";
74
75/// Policy lines shared by both shell profiles: the profile governs syntax
76/// examples only, and VT Code never translates flags across shells.
77const SHELL_PROFILE_POLICY_SUFFIX: &str = "- The shell profile controls prompt examples and expected command syntax only; command policy, sandboxing, and approvals remain separate runtime checks.\n- VT Code does not translate GNU-to-BSD, BSD-to-GNU, Unix-to-PowerShell, or PowerShell-to-Unix command flags.";
78
79/// Documentation density is independent of the tools a session may execute.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub(crate) enum ToolGuidanceProfile {
82    Minimal,
83    Default,
84}
85
86impl ToolGuidanceProfile {
87    #[must_use]
88    pub(crate) fn resolve(
89        context_tokens: usize,
90        default_prompt_tokens: usize,
91        max_prompt_tokens: usize,
92        input_usd_per_token: Option<f64>,
93        max_budget_usd: Option<f64>,
94    ) -> Self {
95        let exceeds_cost = input_usd_per_token.zip(max_budget_usd).is_some_and(|(price, budget)| {
96            price.is_finite() && price >= 0.0 && budget.is_finite() && default_prompt_tokens as f64 * price > budget
97        });
98        if (context_tokens > 0 && context_tokens <= MINIMAL_CONTEXT_TOKEN_CEILING)
99            || (max_prompt_tokens > 0 && default_prompt_tokens > max_prompt_tokens)
100            || exceeds_cost
101        {
102            Self::Minimal
103        } else {
104            Self::Default
105        }
106    }
107}
108
109/// Which guidance-gating tools a session exposes, computed once per build so
110/// every Active Tools variant branches on the same membership policy.
111struct ToolPresence {
112    exec: bool,
113    write_stdin: bool,
114    code_search: bool,
115    web_search: bool,
116    read_file: bool,
117    grep_file: bool,
118    list_files: bool,
119    apply_patch: bool,
120    request_user_input: bool,
121    task_tracker: bool,
122    start_planning: bool,
123    matrix: bool,
124    record_decision: bool,
125}
126
127impl ToolPresence {
128    fn of(available_tools: &[String]) -> Self {
129        // Single pass over the tool list: the old form ran one linear
130        // `any()` scan per flag (10 scans per call, up to 4 calls per
131        // model-aware prompt build). Same membership policy, one walk.
132        let mut presence = Self {
133            exec: false,
134            write_stdin: false,
135            code_search: false,
136            web_search: false,
137            read_file: false,
138            grep_file: false,
139            list_files: false,
140            apply_patch: false,
141            request_user_input: false,
142            task_tracker: false,
143            start_planning: false,
144            matrix: false,
145            record_decision: false,
146        };
147        for tool in available_tools {
148            match tool.as_str() {
149                TOOL_EXEC_COMMAND => presence.exec = true,
150                TOOL_WRITE_STDIN => presence.write_stdin = true,
151                TOOL_CODE_SEARCH => presence.code_search = true,
152                "web_search" => presence.web_search = true,
153                TOOL_READ_FILE => presence.read_file = true,
154                TOOL_GREP_FILE => presence.grep_file = true,
155                TOOL_LIST_FILES => presence.list_files = true,
156                TOOL_APPLY_PATCH => presence.apply_patch = true,
157                TOOL_REQUEST_USER_INPUT => presence.request_user_input = true,
158                TOOL_TASK_TRACKER => presence.task_tracker = true,
159                TOOL_START_PLANNING => presence.start_planning = true,
160                "matrix" => presence.matrix = true,
161                "record_decision" => presence.record_decision = true,
162                _ => {}
163            }
164        }
165        presence
166    }
167}
168
169/// Render from resolved capabilities, without changing tool authorization.
170pub(crate) fn generate_tool_guidelines_with_capabilities(
171    available_tools: &[String],
172    capability_level: Option<CapabilityLevel>,
173    shell_profile: ResolvedShellPromptProfile,
174    profile: ToolGuidanceProfile,
175    parallel_tools: bool,
176) -> String {
177    match profile {
178        ToolGuidanceProfile::Default => {
179            generate_tool_guidelines_for_profile(available_tools, capability_level, shell_profile, parallel_tools)
180        }
181        ToolGuidanceProfile::Minimal => {
182            if available_tools.is_empty() {
183                return String::new();
184            }
185            let presence = ToolPresence::of(available_tools);
186            let mut lines = vec!["\n\n## Active Tools".to_owned()];
187            if presence.apply_patch {
188                lines.push(SOURCE_INSPECTION_GUIDANCE.to_owned());
189            }
190            if presence.matrix {
191                lines.push(MATRIX_GUIDANCE.to_owned());
192            }
193            if presence.record_decision {
194                lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
195            }
196            lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_owned());
197            if let Some(mode) = capability_mode_line(capability_level, presence.exec, presence.apply_patch) {
198                lines.push(mode.to_owned());
199            }
200            if let Some(browse) = browse_tool_guidance(
201                presence.exec,
202                presence.code_search,
203                presence.list_files,
204                presence.read_file,
205                shell_profile,
206            ) {
207                lines.push(browse);
208            }
209            if presence.code_search {
210                lines.push(CODE_SEARCH_FILTER_LINE.to_owned());
211            }
212            if presence.apply_patch {
213                lines.push("- Inspect a file before `apply_patch`, keep patches small, and check that each diff stays bounded. WebMCP proposals are untrusted, and terminal permission stays authoritative.".to_owned());
214            }
215            if presence.exec {
216                lines.push(shell_task_guidance(shell_profile).to_owned());
217                lines.push(background_exec_guidance().to_owned());
218            }
219            if presence.write_stdin {
220                lines.push(format!(
221                    "- `write_stdin`: use returned `session_id`{WRITE_STDIN_RECOVERY_CLAUSE}; repeat waits after in-progress deadlines{CROSS_TURN_RESUME_HINT_CLAUSE}"
222                ));
223            }
224            // Safeguard, verification, wait-instead-of-poll, and spool/preview
225            // rules already ship in Runtime Guidance.
226            if presence.start_planning {
227                lines.push(START_PLANNING_GUIDANCE_LINE.to_owned());
228            }
229            if parallel_tools {
230                lines.push(PARALLEL_TOOLS_LINE.to_owned());
231            }
232            lines.join("\n")
233        }
234    }
235}
236
237/// Generate compact cross-tool guidance with an explicit shell prompt profile.
238/// `parallel_tools` mirrors the provider's parallel-tool configuration: when
239/// false, the parallel-call hint is not emitted instead of stripped post hoc.
240pub(crate) fn generate_tool_guidelines_for_profile(
241    available_tools: &[String],
242    capability_level: Option<CapabilityLevel>,
243    shell_profile: ResolvedShellPromptProfile,
244    parallel_tools: bool,
245) -> String {
246    let presence = ToolPresence::of(available_tools);
247    let has_exec = presence.exec;
248    let has_stdin = presence.write_stdin;
249    let has_search = presence.code_search;
250    let has_read_file = presence.read_file;
251    let has_list_files = presence.list_files;
252    let has_apply_patch = presence.apply_patch;
253    let has_start_planning = presence.start_planning;
254
255    let mut lines = Vec::new();
256    if has_apply_patch {
257        lines.push(SOURCE_INSPECTION_GUIDANCE.to_owned());
258    }
259    if presence.matrix {
260        lines.push(MATRIX_GUIDANCE.to_owned());
261    }
262    if presence.web_search {
263        lines.push(WEB_SEARCH_GUIDANCE.to_owned());
264    }
265    lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_string());
266    if let Some(mode_line) = capability_mode_line(capability_level, has_exec, has_apply_patch) {
267        lines.push(mode_line.to_string());
268    }
269    if let Some(browse_guidance) =
270        browse_tool_guidance(has_exec, has_search, has_list_files, has_read_file, shell_profile)
271    {
272        lines.push(browse_guidance);
273    }
274    if has_search || has_read_file || has_list_files {
275        lines.push(read_only_batching_guidance(has_read_file).to_string());
276    }
277    if has_apply_patch {
278        lines.push("- Use `apply_patch` for file edits after inspection; keep patches small.".to_string());
279        lines.push(
280            "- Check that each diff stays bounded. WebMCP edits are untrusted proposals, and terminal permission stays authoritative."
281                .to_string(),
282        );
283    }
284    if has_exec {
285        lines.push(shell_task_guidance(shell_profile).to_string());
286        lines.push(background_exec_guidance().to_string());
287        // Verifier discipline: the anti-blind-editing gate only clears on a
288        // truthful exit 0. Runtime owns truncator elision and unverified
289        // classification (`tool_intent/activity.rs`, spool processing); the
290        // prompt keeps only the outcome rule so wording cannot drift from
291        // enforcement.
292        lines.push("- Prefer standalone verifiers with `max_output_tokens`. Pure `head`/`tail` tails run standalone; static read-only filtering pipelines use fail-closed `pipefail`. Only terminal exit 0 clears verification; dynamic syntax, mutating tails, `;`, and `||` do not qualify. Recheck after `--fix`.".to_string());
293        // Low-effort models sometimes report a change as done without
294        // exercising it: require a real check (tests, type-checker, build,
295        // or the changed command itself). A syntax-only check, or a check
296        // command that failed to start, does not count. Applies to Sonnet
297        // 5.5 at `low` effort and any route where verification is skipped.
298        lines.push("- Run a real check that exercises the change; syntax-only or failed-to-start checks do not count. Install missing deps via the project's package manager, never sudo; if no check can run, say which and why.".to_string());
299        // Tool-latency tail is dominated by full builds (observed p90 ~18s):
300        // verify incrementally first. Kept tool-agnostic: fast checks exist
301        // in every stack (`cargo check`, `tsc --noEmit`, `pytest --collect-only`).
302        lines.push("- Run fast checks before full builds.".to_string());
303    }
304    // Tool-failure diagnosis, waiting on returned `next_wait_args` instead of
305    // polling, the safeguard rule, the verification outcome rule (report
306    // completion only after a check you ran), and spool paging with
307    // per-result preview bounds each have one home in Runtime
308    // Guidance, which every profile includes; do not restate them here.
309    if has_stdin {
310        lines.push(format!(
311            "- `write_stdin`: use the existing `session_id`{WRITE_STDIN_RECOVERY_CLAUSE}; rerun only for fresh results. `spool_complete: false` is partial; wait for exited pending spools{CROSS_TURN_RESUME_HINT_CLAUSE}"
312        ));
313    }
314    if has_search {
315        lines.push(CODE_SEARCH_FILTER_LINE.to_string());
316        lines.push(code_search_guidance(has_exec));
317    }
318    if has_apply_patch || has_exec {
319        lines.push(
320            "- Build and Auto share tools and safety gates; Auto changes confirmation behavior only after explicit approval or full-auto policy."
321                .to_string(),
322        );
323    }
324    if (has_search || has_exec) && parallel_tools {
325        lines.push(PARALLEL_TOOLS_LINE.to_string());
326    }
327    if has_start_planning {
328        lines.push(START_PLANNING_GUIDANCE_LINE.to_string());
329    }
330
331    if lines.is_empty() {
332        return String::new();
333    }
334
335    if presence.record_decision {
336        lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
337    }
338    format!("\n\n## Active Tools\n{}", lines.join("\n"))
339}
340
341pub fn append_runtime_tool_prompt_sections_for_profile(
342    prompt: &mut String,
343    tool_snapshot: &SessionToolCatalogSnapshot,
344    include_catalog_metadata: bool,
345    shell_profile: ResolvedShellPromptProfile,
346) {
347    let names = snapshot_tool_names(tool_snapshot);
348    append_runtime_tool_sections_with_names(prompt, tool_snapshot, names, include_catalog_metadata, shell_profile);
349}
350
351/// Select documentation density using the active route and session budgets.
352pub fn append_runtime_tool_prompt_sections_for_model(
353    prompt: &mut String,
354    tool_snapshot: &SessionToolCatalogSnapshot,
355    include_catalog_metadata: bool,
356    shell_profile: ResolvedShellPromptProfile,
357    provider: &dyn crate::llm::provider::LLMProvider,
358    model: &str,
359    config: Option<&crate::config::VTCodeConfig>,
360) {
361    let names = snapshot_tool_names(tool_snapshot);
362    let default_guidance =
363        append_runtime_tool_sections_with_names(prompt, tool_snapshot, names, include_catalog_metadata, shell_profile);
364    let pricing = crate::config::models::model_catalog_entry(provider.name(), model).map(|entry| entry.pricing);
365    let profile = ToolGuidanceProfile::resolve(
366        crate::compaction::effective_context_budget(config, provider, model),
367        vtcode_commons::estimate_tokens(prompt),
368        config.map_or(0, |cfg| cfg.agent.max_system_prompt_tokens as usize),
369        pricing.and_then(|price| price.input),
370        config.and_then(|cfg| cfg.agent.harness.max_budget_usd),
371    );
372    let parallel_tools = provider.supports_parallel_tool_config(model);
373    // The planning mode section owns the output contract at every density.
374    // Default planning tool guidance contains no parallel-call hint.
375    if tool_snapshot.planning_active && profile == ToolGuidanceProfile::Default {
376        return;
377    }
378    remove_prompt_section(prompt, "## Active Tools", SectionBoundaryMode::BracketOrMarkdown);
379    let presence = ToolPresence::of(names);
380    let capability_level = Some(infer_capability_level_from_presence(&presence));
381    let mut guidance = match profile {
382        ToolGuidanceProfile::Default => {
383            let mut guidance = default_guidance;
384            if let (Some(original), Some(effective)) = (
385                capability_mode_line(None, presence.exec, presence.apply_patch),
386                capability_mode_line(capability_level, presence.exec, presence.apply_patch),
387            ) && original != effective
388                && let Some(start) = guidance.find(original)
389            {
390                guidance.replace_range(start..start + original.len(), effective);
391            }
392            if !parallel_tools && let Some(start) = guidance.find(PARALLEL_TOOLS_LINE) {
393                guidance.replace_range(start.saturating_sub(1)..start + PARALLEL_TOOLS_LINE.len(), "");
394            }
395            guidance
396        }
397        ToolGuidanceProfile::Minimal => {
398            generate_tool_guidelines_with_capabilities(names, capability_level, shell_profile, profile, parallel_tools)
399        }
400    };
401    if tool_snapshot.planning_active {
402        append_minimal_planning_addendum(&mut guidance, &presence);
403    }
404    append_prompt_block(prompt, guidance.trim_start_matches('\n'));
405}
406
407/// Replace the runtime tool sections with guidance built from `names`, plus
408/// optional catalog metadata. Return the Default guidance so model-aware
409/// callers can reuse it after measuring the assembled prompt.
410fn append_runtime_tool_sections_with_names(
411    prompt: &mut String,
412    tool_snapshot: &SessionToolCatalogSnapshot,
413    names: &[String],
414    include_catalog_metadata: bool,
415    shell_profile: ResolvedShellPromptProfile,
416) -> String {
417    remove_prompt_section(prompt, "## Active Tools", SectionBoundaryMode::BracketOrMarkdown);
418    remove_prompt_section(prompt, "[Runtime Tool Catalog]", SectionBoundaryMode::BracketOrMarkdown);
419    trim_trailing_newlines(prompt);
420
421    let guidelines = generate_runtime_tool_guidelines_for_profile(names, tool_snapshot.planning_active, shell_profile);
422    if !guidelines.is_empty() {
423        append_prompt_block(prompt, guidelines.trim_start_matches('\n'));
424    }
425
426    if include_catalog_metadata && tool_snapshot.snapshot.is_some() {
427        let active_tools = if tool_snapshot.active_tool_names.is_empty() {
428            "none".to_string()
429        } else {
430            tool_snapshot.active_tool_names.join(", ")
431        };
432        let catalog_metadata = format!(
433            "[Runtime Tool Catalog]\n- version: {}\n- epoch: {}\n- catalog_tools: {}\n- available_tools: {}\n- currently_available_tools: {}\n- request_user_input_enabled: {}",
434            tool_snapshot.version,
435            tool_snapshot.epoch,
436            tool_snapshot.catalog_tools(),
437            tool_snapshot.available_tools(),
438            active_tools,
439            tool_snapshot.request_user_input_enabled,
440        );
441        append_prompt_block(prompt, &catalog_metadata);
442    }
443    guidelines
444}
445
446/// Compact tool reminders; the planning mode section retains the canonical
447/// research, step-quality, output, and persistence contract at every density.
448fn append_minimal_planning_addendum(guidance: &mut String, presence: &ToolPresence) {
449    guidance.push_str("\n- Planning is read-only.");
450    let mut read_tools = Vec::with_capacity(4);
451    if presence.read_file {
452        read_tools.push(TOOL_READ_FILE);
453    }
454    if presence.grep_file {
455        read_tools.push(TOOL_GREP_FILE);
456    }
457    if presence.code_search {
458        read_tools.push(TOOL_CODE_SEARCH);
459    }
460    if presence.list_files {
461        read_tools.push(TOOL_LIST_FILES);
462    }
463    guidance.push_str("\n- Keep inspections small: ");
464    if !read_tools.is_empty() {
465        guidance.push_str(&format!("prefer `{}` over `exec_command` shell reads; ", read_tools.join("`/`")));
466    }
467    guidance.push_str("keep `max_output_tokens` small, avoid batching multiple large inspections in parallel; start git history with `git log --oneline` before targeted `git show --stat`.");
468    if presence.task_tracker {
469        guidance.push('\n');
470        guidance.push_str(PLANNING_TASK_TRACKER_COMPACT_LINE);
471    }
472    if presence.request_user_input {
473        guidance.push('\n');
474        guidance.push_str(REQUEST_USER_INPUT_LINE);
475    }
476}
477
478/// Append a compact summary of tools omitted from a client-local wire payload.
479///
480/// The listing is bounded like the `## Skills` routing section: at most
481/// `DEFERRED_TOOLS_MAX_GROUPS` groups are named and the rest collapse into one
482/// overflow line, so MCP-heavy sessions cannot bloat every request. Group
483/// descriptions are server-provided and unbounded, so each line is truncated
484/// to `DEFERRED_TOOLS_MAX_DESC_CHARS` characters.
485pub fn append_deferred_tools_prompt_section(prompt: &mut String, tools: &[ToolDefinition]) {
486    remove_prompt_section(prompt, "[Deferred Tools]", SectionBoundaryMode::BracketOrMarkdown);
487
488    let mut groups: Vec<_> = tool_groups(tools)
489        .into_iter()
490        .filter(|group| group.deferred_count > 0)
491        .collect();
492    let overflow = groups.len().saturating_sub(DEFERRED_TOOLS_MAX_GROUPS);
493    groups.truncate(DEFERRED_TOOLS_MAX_GROUPS);
494
495    let mut lines: Vec<String> = groups
496        .into_iter()
497        .map(|group| {
498            let description = truncate_deferred_description(group.description.as_deref().unwrap_or_default());
499            format!("- {} ({} tools): {}", group.name, group.deferred_count, description)
500        })
501        .collect();
502    if overflow > 0 {
503        lines.push(format!("(+{overflow} more deferred groups available — use `search_tools` to find them)"));
504    }
505
506    let unnamespaced_deferred = tools
507        .iter()
508        .filter(|tool| tool.namespace.is_none() && tool.defer_loading == Some(true))
509        .count();
510    if unnamespaced_deferred > 0 {
511        lines.push(format!("- {unnamespaced_deferred} additional deferred tools"));
512    }
513
514    if lines.is_empty() {
515        return;
516    }
517
518    let section = format!(
519        "[Deferred Tools]\n{}\nUse `search_tools` to find a deferred capability. Selected definitions become available in the next request segment.",
520        lines.join("\n")
521    );
522    append_prompt_block(prompt, &section);
523}
524
525/// Maximum deferred-tool groups named in the `[Deferred Tools]` prompt
526/// section before the rest collapse into one overflow line.
527const DEFERRED_TOOLS_MAX_GROUPS: usize = 8;
528/// Maximum characters of a group description in the section. Mirrors the
529/// `## Skills` line truncation: server-provided text must not bloat the prompt.
530const DEFERRED_TOOLS_MAX_DESC_CHARS: usize = 120;
531
532fn truncate_deferred_description(description: &str) -> String {
533    // Single pass: visit at most `MAX + 1` chars. The old form ran
534    // `chars().count()` over the whole string, then `chars().take()` again.
535    let mut chars = description.chars();
536    let truncated: String = chars.by_ref().take(DEFERRED_TOOLS_MAX_DESC_CHARS).collect();
537    if chars.next().is_none() {
538        return description.to_string();
539    }
540    format!("{}...", truncated.trim_end())
541}
542
543fn generate_runtime_tool_guidelines_for_profile(
544    available_tools: &[String],
545    planning_active: bool,
546    shell_profile: ResolvedShellPromptProfile,
547) -> String {
548    if !planning_active {
549        // Measurement parity: this Default-density build feeds the prompt size
550        // that `ToolGuidanceProfile::resolve` reads, so it keeps shipping the
551        // parallel-call hint unconditionally like the static composition path.
552        return generate_tool_guidelines_for_profile(available_tools, None, shell_profile, true);
553    }
554
555    let presence = ToolPresence::of(available_tools);
556    let has_exec = presence.exec;
557    let has_search = presence.code_search;
558    let has_read_file = presence.read_file;
559    let has_list_files = presence.list_files;
560    let has_request_user_input = presence.request_user_input;
561    let has_task_tracker = presence.task_tracker;
562
563    let mut lines = vec!["- Planning workflow active: stay within the read-safe tool list.".to_string()];
564    if presence.web_search {
565        lines.push(WEB_SEARCH_GUIDANCE.to_owned());
566    }
567    lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_string());
568    if let Some(browse_guidance) =
569        browse_tool_guidance(has_exec, has_search, has_list_files, has_read_file, shell_profile)
570    {
571        lines.push(browse_guidance);
572    }
573    if has_exec {
574        lines.push("- In Planning workflow, use `exec_command` only for read-only verification.".to_string());
575    }
576    if has_search {
577        lines.push(CODE_SEARCH_FILTER_LINE.to_string());
578    }
579    if has_task_tracker {
580        lines.push("- Keep `task_tracker` updated as you refine the plan. Indexed updates return totals and the changed item; use action=list for the full checklist.".to_string());
581        lines.push("- Keep blockers and verification open in `task_tracker` until resolved.".to_string());
582        lines.push(PLANNING_TASK_TRACKER_INDEX_LINE.to_string());
583    }
584    if has_request_user_input {
585        lines.push(REQUEST_USER_INPUT_LINE.to_string());
586    }
587    if has_search || has_exec {
588        lines.push("- If calls repeat without progress, tighten the plan instead of retrying identically.".to_string());
589    }
590    if presence.record_decision {
591        lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
592    }
593
594    format!("\n\n## Active Tools\n{}", lines.join("\n"))
595}
596
597fn snapshot_tool_names(tool_snapshot: &SessionToolCatalogSnapshot) -> &[String] {
598    &tool_snapshot.active_tool_names
599}
600
601fn browse_tool_guidance(
602    has_exec: bool,
603    has_search: bool,
604    has_list_files: bool,
605    has_read_file: bool,
606    shell_profile: ResolvedShellPromptProfile,
607) -> Option<String> {
608    if has_exec {
609        return Some(shell_browse_guidance(shell_profile, has_search));
610    }
611
612    if !(has_search || has_list_files || has_read_file) {
613        return None;
614    }
615
616    Some("- Use available read-only repository tools for browsing; do not modify files.".to_string())
617}
618
619pub(crate) fn render_shell_profile_guidance(shell_profile: ResolvedShellPromptProfile) -> String {
620    let profile_lines = match shell_profile {
621        ResolvedShellPromptProfile::UnixLike => {
622            "- Active shell profile: `unix_like`. Use Unix-like command syntax in `exec_command.cmd`, for example `ls`, `rg`, `find`, `cat`, `sed`, and `awk`.\n- On macOS, write BSD-compatible flags for BSD tools. VT Code does not rewrite GNU flags for macOS BSD tools."
623        }
624        ResolvedShellPromptProfile::PowerShell => {
625            "- Active shell profile: `powershell`. Use native PowerShell syntax in `exec_command.cmd`, for example `Get-ChildItem`, `Select-String`, `Get-Content`, and `Where-Object`.\n- On native Windows, use WSL when you need Unix-like workflows or Unix command examples."
626        }
627    };
628    format!("## Shell Profile\n{profile_lines}\n{SHELL_PROFILE_POLICY_SUFFIX}")
629}
630
631fn shell_browse_guidance(shell_profile: ResolvedShellPromptProfile, has_search: bool) -> String {
632    // Sessions show `exec_command` + `rg` crowding out `code_search`
633    // (observed 654 exec vs 15 code_search in one run): `rg` scans text
634    // while `code_search` resolves definitions and exact usages, so route
635    // code search to the dedicated tool whenever it is available.
636    const SEARCH_PREFERENCE_UNIX: &str = " Prefer `code_search` over `rg`/`grep` for code.";
637    const SEARCH_PREFERENCE_POWERSHELL: &str = " Prefer `code_search` over `Select-String` for code.";
638    match shell_profile {
639        ResolvedShellPromptProfile::UnixLike => {
640            let mut line = String::from("- Use `exec_command.cmd` with `ls`, ");
641            if !has_search {
642                line.push_str("`rg`, ");
643            }
644            line.push_str("`find`, `cat`, `sed`, and `awk` for repository browsing.");
645            if has_search {
646                line.push_str(SEARCH_PREFERENCE_UNIX);
647            }
648            line
649        }
650        ResolvedShellPromptProfile::PowerShell => {
651            let mut line = "- Use `exec_command.cmd` with native PowerShell commands such as `Get-ChildItem`, `Select-String`, `Get-Content`, and `Where-Object` for repository browsing.".to_string();
652            if has_search {
653                line.push_str(SEARCH_PREFERENCE_POWERSHELL);
654            }
655            line
656        }
657    }
658}
659
660fn shell_task_guidance(shell_profile: ResolvedShellPromptProfile) -> &'static str {
661    match shell_profile {
662        ResolvedShellPromptProfile::UnixLike => {
663            "- Use `exec_command.cmd` for build tools, test tools, `git diff -- <path>`, and shell-only tasks. In one-shot `exec_command` calls, do not use `!!`, `!$`, `!ssh`, or `fc`; write full command arguments explicitly from conversation or tool results. Interactive shells: review-safe history expansion (Bash `histverify`, zsh `HIST_VERIFY`)."
664        }
665        ResolvedShellPromptProfile::PowerShell => {
666            "- Use `exec_command.cmd` for build tools, test tools, `git diff -- <path>`, and shell-only tasks using native PowerShell syntax."
667        }
668    }
669}
670
671fn background_exec_guidance() -> &'static str {
672    "- For long-lived commands, set `background: true` on `exec_command`; it returns a bounded preview plus a stable `session_id` and wait arguments. At most three live background processes are retained per runtime, with no automatic eviction; `write_stdin` drives the session lifecycle."
673}
674
675fn read_only_batching_guidance(has_read_file: bool) -> &'static str {
676    if has_read_file {
677        "- Batch independent read-only calls; use bounded `read_file` ranges, order dependencies, serialize mutations; narrow the range on `line_truncated`; prefer wider windows and reuse evidence over overlapping slices."
678    } else {
679        "- Batch independent read-only calls; order dependent reads, and serialize mutations."
680    }
681}
682
683fn code_search_guidance(has_exec: bool) -> String {
684    const BASE: &str = "- Advanced `code_search` takes `query`; filters `path`, `file_types`, `result_types`, `max_results`; results: definitions, exact syntactic usages. Queries use literal smart-case and `|`-separated literals; truncated: narrow; unavailable: do not retry identical, drop `file_types`/broaden `path`. Example: `{\"query\":\"TurnLoop\",\"path\":\"src\",\"result_types\":[\"definition\"]}`. Do not JSON-encode arrays or integers as strings. Prefer `code_search` over `rg` on `.vtcode/context/tool_outputs/`.";
685    if has_exec {
686        format!("{BASE} Use `exec_command` or a skill for syntax patterns.")
687    } else {
688        BASE.to_string()
689    }
690}
691
692fn capability_mode_line(
693    capability_level: Option<CapabilityLevel>,
694    has_exec: bool,
695    has_file: bool,
696) -> Option<&'static str> {
697    match capability_level {
698        Some(CapabilityLevel::Basic) => {
699            Some("- Capabilities: limited. Ask the user to enable more capabilities if file work is required.")
700        }
701        Some(CapabilityLevel::FileReading | CapabilityLevel::FileListing) => Some(CAPABILITY_READ_ONLY_LINE),
702        _ if !has_exec && !has_file => Some(CAPABILITY_READ_ONLY_LINE),
703        _ => None,
704    }
705}
706
707/// Infer capability level from available tools.
708pub(crate) fn infer_capability_level(available_tools: &[String]) -> CapabilityLevel {
709    infer_capability_level_from_presence(&ToolPresence::of(available_tools))
710}
711
712fn infer_capability_level_from_presence(presence: &ToolPresence) -> CapabilityLevel {
713    if presence.code_search {
714        CapabilityLevel::CodeSearch
715    } else if presence.apply_patch {
716        CapabilityLevel::Editing
717    } else if presence.exec {
718        CapabilityLevel::Bash
719    } else if presence.list_files {
720        CapabilityLevel::FileListing
721    } else if presence.read_file {
722        CapabilityLevel::FileReading
723    } else {
724        CapabilityLevel::Basic
725    }
726}
727
728#[cfg(test)]
729mod tests {
730    use super::*;
731    use crate::config::types::ShellPromptProfile;
732
733    /// Default-density guidance with the platform shell profile and the
734    /// parallel-call hint, matching what static composition ships.
735    fn guidelines_for(tools: &[String], capability_level: Option<CapabilityLevel>) -> String {
736        generate_tool_guidelines_for_profile(
737            tools,
738            capability_level,
739            ShellPromptProfile::Auto.resolve_for_current_platform(),
740            true,
741        )
742    }
743
744    /// Reference the previous model-aware assembly: measure Default guidance,
745    /// then regenerate it with resolved density and capabilities.
746    fn rebuilt_model_tool_prompt(
747        mut prompt: String,
748        snapshot: &SessionToolCatalogSnapshot,
749        metadata: bool,
750        shell: ResolvedShellPromptProfile,
751        provider: &dyn crate::llm::provider::LLMProvider,
752        model: &str,
753        config: &crate::config::VTCodeConfig,
754    ) -> String {
755        append_runtime_tool_prompt_sections_for_profile(&mut prompt, snapshot, metadata, shell);
756        let names = snapshot_tool_names(snapshot);
757        let pricing = crate::config::models::model_catalog_entry(provider.name(), model).map(|entry| entry.pricing);
758        let profile = ToolGuidanceProfile::resolve(
759            crate::compaction::effective_context_budget(Some(config), provider, model),
760            vtcode_commons::estimate_tokens(&prompt),
761            config.agent.max_system_prompt_tokens as usize,
762            pricing.and_then(|price| price.input),
763            config.agent.harness.max_budget_usd,
764        );
765        if snapshot.planning_active && profile == ToolGuidanceProfile::Default {
766            return prompt;
767        }
768        remove_prompt_section(&mut prompt, "## Active Tools", SectionBoundaryMode::BracketOrMarkdown);
769        let presence = ToolPresence::of(names);
770        let mut guidance = generate_tool_guidelines_with_capabilities(
771            names,
772            Some(infer_capability_level_from_presence(&presence)),
773            shell,
774            profile,
775            provider.supports_parallel_tool_config(model),
776        );
777        if snapshot.planning_active {
778            append_minimal_planning_addendum(&mut guidance, &presence);
779        }
780        append_prompt_block(&mut prompt, guidance.trim_start_matches('\n'));
781        prompt
782    }
783
784    #[test]
785    fn duckduckgo_guidance_is_present_only_with_search_and_stays_bounded() {
786        let enabled = guidelines_for(&["web_search".to_owned()], None);
787        let disabled = guidelines_for(&[], None);
788        assert!(enabled.contains("keyless DuckDuckGo"));
789        assert!(enabled.contains("separate approval"));
790        assert!(enabled.contains("antiban_blocked"));
791        assert!(enabled.contains("retryable: false"));
792        assert!(enabled.contains("retry_after_ms"));
793        assert!(!disabled.contains("DuckDuckGo results"));
794        assert!(enabled.len().saturating_sub(disabled.len()) < 250);
795    }
796
797    #[test]
798    fn model_tool_prompt_reuse_matches_rebuild_across_density_and_capabilities() {
799        use crate::config::constants::models;
800        use crate::llm::provider::LLMProvider;
801        use crate::llm::providers::{AnthropicProvider, HuggingFaceProvider};
802
803        struct ProviderCase {
804            provider: Box<dyn LLMProvider>,
805            model: &'static str,
806            parallel: bool,
807        }
808        let providers = [
809            ProviderCase {
810                provider: Box::new(AnthropicProvider::new("offline-fixture".into())),
811                model: models::anthropic::DEFAULT_MODEL,
812                parallel: true,
813            },
814            ProviderCase {
815                provider: Box::new(HuggingFaceProvider::new("offline-fixture".into())),
816                model: "offline-fixture",
817                parallel: false,
818            },
819        ];
820        let initial = "Base prompt\n\n## Active Tools\nold guidance\n\n# PLANNING WORKFLOW (READ-ONLY)\nKeep the canonical contract.\n\n[Runtime Tool Catalog]\nold metadata\n\n## Tail\nKeep this section.\n\n";
821        for case in providers {
822            assert_eq!(case.provider.supports_parallel_tool_config(case.model), case.parallel);
823            for names in [
824                None,
825                Some(&[][..]),
826                Some(&[TOOL_TASK_TRACKER, TOOL_REQUEST_USER_INPUT][..]),
827                Some(&[TOOL_READ_FILE][..]),
828                Some(&[TOOL_WRITE_STDIN][..]),
829                Some(&[TOOL_EXEC_COMMAND, TOOL_APPLY_PATCH, TOOL_CODE_SEARCH, "record_decision"][..]),
830            ] {
831                for planning in [false, true] {
832                    let snapshot = SessionToolCatalogSnapshot::new(
833                        7,
834                        9,
835                        planning,
836                        true,
837                        names.map(|names| {
838                            std::sync::Arc::new(
839                                names
840                                    .iter()
841                                    .map(|name| {
842                                        ToolDefinition::function(
843                                            (*name).to_string(),
844                                            "fixture".to_string(),
845                                            serde_json::json!({"type": "object"}),
846                                        )
847                                    })
848                                    .collect(),
849                            )
850                        }),
851                        false,
852                    );
853                    for shell in [
854                        ResolvedShellPromptProfile::UnixLike,
855                        ResolvedShellPromptProfile::PowerShell,
856                    ] {
857                        for metadata in [false, true] {
858                            let mut measured = initial.to_string();
859                            append_runtime_tool_prompt_sections_for_profile(&mut measured, &snapshot, metadata, shell);
860                            let measured_tokens = vtcode_commons::estimate_tokens(&measured) as u64;
861                            for budget in [1, measured_tokens - 1, measured_tokens, 100_000] {
862                                let mut config = crate::config::VTCodeConfig::default();
863                                config.context.max_context_tokens = 128_000;
864                                config.agent.max_system_prompt_tokens = budget;
865                                let expected = rebuilt_model_tool_prompt(
866                                    initial.to_string(),
867                                    &snapshot,
868                                    metadata,
869                                    shell,
870                                    case.provider.as_ref(),
871                                    case.model,
872                                    &config,
873                                );
874                                let mut actual = initial.to_string();
875                                append_runtime_tool_prompt_sections_for_model(
876                                    &mut actual,
877                                    &snapshot,
878                                    metadata,
879                                    shell,
880                                    case.provider.as_ref(),
881                                    case.model,
882                                    Some(&config),
883                                );
884
885                                assert_eq!(
886                                    actual,
887                                    expected,
888                                    "provider={}, names={names:?}, planning={planning}, shell={shell:?}, metadata={metadata}, budget={budget}",
889                                    case.provider.name()
890                                );
891                                assert_eq!(
892                                    actual.matches("## Active Tools").count(),
893                                    usize::from(
894                                        budget >= measured_tokens || names.is_some_and(|names| !names.is_empty())
895                                    )
896                                );
897                                assert!(
898                                    actual.contains("# PLANNING WORKFLOW (READ-ONLY)\nKeep the canonical contract.")
899                                );
900                                assert!(actual.contains("## Tail\nKeep this section."));
901                            }
902                        }
903                    }
904                }
905            }
906        }
907    }
908
909    #[test]
910    fn matrix_guidance_has_presence_and_budget_in_both_densities() {
911        for profile in [ToolGuidanceProfile::Default, ToolGuidanceProfile::Minimal] {
912            let enabled = generate_tool_guidelines_with_capabilities(
913                &["matrix".to_string(), "request_user_input".to_string()],
914                None,
915                ResolvedShellPromptProfile::UnixLike,
916                profile,
917                false,
918            );
919            let disabled = generate_tool_guidelines_with_capabilities(
920                &["request_user_input".to_string()],
921                None,
922                ResolvedShellPromptProfile::UnixLike,
923                profile,
924                false,
925            );
926            assert_eq!(enabled.matches(MATRIX_GUIDANCE).count(), 1);
927            assert!(enabled.contains("declared input changes"));
928            assert!(enabled.contains("effective permissions and sandbox gates"));
929            assert!(enabled.contains("Replay restores admission before discovery"));
930            assert!(enabled.contains("user cancel is terminal"));
931            assert!(!disabled.contains("scheduler-owned"));
932            assert!(vtcode_commons::estimate_tokens(&enabled) <= 220, "{profile:?}: {enabled}");
933        }
934    }
935
936    /// Universal rules have one home in Runtime Guidance (or the shared
937    /// contract). Compose every static profile with each tool-guidance variant
938    /// and the Harness Limits section, and check each rule marker lands once.
939    #[test]
940    fn universal_rules_have_one_home_across_composed_prompt_sections() {
941        use crate::config::types::SystemPromptMode;
942        use crate::prompts::harness_limits::upsert_harness_limits_section;
943        use crate::prompts::static_prompts::static_profile_prompt;
944        use crate::prompts::system::PLANNING_WORKFLOW_READ_ONLY_NOTICE_LINE;
945
946        let shell = ResolvedShellPromptProfile::UnixLike;
947        let execution_tools = [
948            TOOL_EXEC_COMMAND,
949            TOOL_WRITE_STDIN,
950            TOOL_APPLY_PATCH,
951            TOOL_CODE_SEARCH,
952            TOOL_TASK_TRACKER,
953            TOOL_START_PLANNING,
954            TOOL_REQUEST_USER_INPUT,
955        ]
956        .map(str::to_owned)
957        .to_vec();
958        let planning_tools = [
959            TOOL_EXEC_COMMAND,
960            TOOL_WRITE_STDIN,
961            TOOL_CODE_SEARCH,
962            TOOL_GREP_FILE,
963            TOOL_TASK_TRACKER,
964            TOOL_REQUEST_USER_INPUT,
965        ]
966        .map(str::to_owned)
967        .to_vec();
968        let mut minimal_planning = generate_tool_guidelines_with_capabilities(
969            &planning_tools,
970            None,
971            shell,
972            ToolGuidanceProfile::Minimal,
973            false,
974        );
975        append_minimal_planning_addendum(&mut minimal_planning, &ToolPresence::of(&planning_tools));
976        let variants = [
977            ("default", generate_tool_guidelines_for_profile(&execution_tools, None, shell, true), false),
978            (
979                "minimal",
980                generate_tool_guidelines_with_capabilities(
981                    &execution_tools,
982                    None,
983                    shell,
984                    ToolGuidanceProfile::Minimal,
985                    true,
986                ),
987                false,
988            ),
989            ("default planning", generate_runtime_tool_guidelines_for_profile(&planning_tools, true, shell), true),
990            ("minimal planning", minimal_planning, true),
991        ];
992        // Each marker names one universal rule that lives in Runtime Guidance
993        // or the shared contract and must not be restated by tool sections.
994        let markers = [
995            "never claim a check passed",
996            "Diagnose failures; change approach",
997            "Use returned `next_wait_args`",
998            "Treat empty searches as evidence",
999            "Check optional tools once",
1000            "small non-overlapping ranges",
1001            "accumulated output never exhausts tool access",
1002            "additional_permissions",
1003            "bypass safeguards",
1004            "Delegate only sizeable",
1005            "Across compaction",
1006        ];
1007
1008        for mode in [
1009            SystemPromptMode::Default,
1010            SystemPromptMode::Minimal,
1011            SystemPromptMode::Lightweight,
1012            SystemPromptMode::Specialized,
1013        ] {
1014            for (variant, guidance, planning) in &variants {
1015                let mut prompt = static_profile_prompt(mode).to_owned();
1016                if *planning {
1017                    prompt.push_str("\n\n");
1018                    prompt.push_str(PLANNING_WORKFLOW_READ_ONLY_NOTICE_LINE);
1019                }
1020                prompt.push_str(guidance);
1021                upsert_harness_limits_section(&mut prompt, 32, 600, 2);
1022                for marker in markers {
1023                    assert_eq!(
1024                        prompt.matches(marker).count(),
1025                        1,
1026                        "{mode:?} with {variant} tool guidance should state {marker:?} exactly once"
1027                    );
1028                }
1029                let start_planning_mentions = prompt.matches("start_planning").count();
1030                assert_eq!(start_planning_mentions, usize::from(!*planning), "{mode:?} with {variant} tool guidance");
1031            }
1032        }
1033    }
1034
1035    #[test]
1036    fn documentation_profile_respects_context_tokens_and_known_cost() {
1037        assert_eq!(ToolGuidanceProfile::resolve(32_000, 100, 1000, None, None), ToolGuidanceProfile::Minimal);
1038        assert_eq!(ToolGuidanceProfile::resolve(1_000_000, 100, 1000, None, Some(0.0)), ToolGuidanceProfile::Default);
1039        assert_eq!(ToolGuidanceProfile::resolve(1_000_000, 1001, 1000, None, None), ToolGuidanceProfile::Minimal);
1040        assert_eq!(
1041            ToolGuidanceProfile::resolve(1_000_000, 1000, 2000, Some(0.00001), Some(0.001)),
1042            ToolGuidanceProfile::Minimal
1043        );
1044    }
1045
1046    #[test]
1047    fn minimal_and_default_tool_guidance_snapshots() {
1048        let tools = vec![TOOL_READ_FILE.to_owned()];
1049        let minimal = generate_tool_guidelines_with_capabilities(
1050            &tools,
1051            None,
1052            ResolvedShellPromptProfile::UnixLike,
1053            ToolGuidanceProfile::Minimal,
1054            false,
1055        );
1056        assert_eq!(
1057            minimal,
1058            "\n\n## Active Tools\n- `verify: [skip Markdown lint if unavailable]`: report skipped; review diff/links without installing tools. Lint errors remain failures.\n- Capabilities: read-only. Analyze and search, but do not modify files or run shell commands.\n- Use available read-only repository tools for browsing; do not modify files."
1059        );
1060        let default = generate_tool_guidelines_with_capabilities(
1061            &tools,
1062            None,
1063            ResolvedShellPromptProfile::UnixLike,
1064            ToolGuidanceProfile::Default,
1065            false,
1066        );
1067        assert_eq!(
1068            default,
1069            "\n\n## Active Tools\n- `verify: [skip Markdown lint if unavailable]`: report skipped; review diff/links without installing tools. Lint errors remain failures.\n- Capabilities: read-only. Analyze and search, but do not modify files or run shell commands.\n- Use available read-only repository tools for browsing; do not modify files.\n- Batch independent read-only calls; use bounded `read_file` ranges, order dependencies, serialize mutations; narrow the range on `line_truncated`; prefer wider windows and reuse evidence over overlapping slices."
1070        );
1071    }
1072
1073    #[test]
1074    fn tool_presence_flags_record_decision_in_the_single_pass() {
1075        let with = ToolPresence::of(&["matrix".to_string(), "record_decision".to_string()]);
1076        assert!(with.matrix);
1077        assert!(with.record_decision);
1078        let without = ToolPresence::of(&["matrix".to_string()]);
1079        assert!(without.matrix);
1080        assert!(!without.record_decision);
1081    }
1082
1083    #[test]
1084    fn public_decision_guidance_is_optional_and_bounded() {
1085        for profile in [ToolGuidanceProfile::Minimal, ToolGuidanceProfile::Default] {
1086            let enabled = generate_tool_guidelines_with_capabilities(
1087                &[TOOL_READ_FILE.into(), "record_decision".into()],
1088                None,
1089                ResolvedShellPromptProfile::UnixLike,
1090                profile,
1091                false,
1092            );
1093            let disabled = generate_tool_guidelines_with_capabilities(
1094                &[TOOL_READ_FILE.into()],
1095                None,
1096                ResolvedShellPromptProfile::UnixLike,
1097                profile,
1098                false,
1099            );
1100            assert!(enabled.contains(PUBLIC_DECISION_GUIDANCE));
1101            assert!(!disabled.contains("record_decision"));
1102            assert!(enabled.len().saturating_sub(disabled.len()) < 300);
1103            assert!(!enabled.contains("chain of thought"));
1104        }
1105    }
1106
1107    #[test]
1108    fn tool_guidance_uses_actual_parallel_capabilities_for_three_families() {
1109        use crate::config::constants::models;
1110        use crate::llm::provider::LLMProvider;
1111        use crate::llm::providers::{AnthropicProvider, GeminiProvider, OpenAIProvider};
1112        let providers: [(Box<dyn LLMProvider>, &str); 3] = [
1113            (Box::new(OpenAIProvider::new("offline-fixture".into())), models::openai::DEFAULT_MODEL),
1114            (Box::new(AnthropicProvider::new("offline-fixture".into())), models::anthropic::DEFAULT_MODEL),
1115            (Box::new(GeminiProvider::new("offline-fixture".into())), models::google::DEFAULT_MODEL),
1116        ];
1117        for (provider, model) in providers {
1118            for profile in [ToolGuidanceProfile::Minimal, ToolGuidanceProfile::Default] {
1119                let parallel = provider.supports_parallel_tool_config(model);
1120                let text = generate_tool_guidelines_with_capabilities(
1121                    &[TOOL_EXEC_COMMAND.to_owned()],
1122                    None,
1123                    ResolvedShellPromptProfile::UnixLike,
1124                    profile,
1125                    parallel,
1126                );
1127                assert_eq!(text.contains("tools in parallel"), parallel);
1128                let serial = generate_tool_guidelines_with_capabilities(
1129                    &[TOOL_EXEC_COMMAND.to_owned()],
1130                    None,
1131                    ResolvedShellPromptProfile::UnixLike,
1132                    profile,
1133                    false,
1134                );
1135                assert!(!serial.contains("tools in parallel"));
1136            }
1137        }
1138    }
1139
1140    #[test]
1141    fn test_read_only_capability_detection() {
1142        let tools = vec![TOOL_CODE_SEARCH.to_string()];
1143        let guidelines = guidelines_for(&tools, None);
1144        assert!(guidelines.contains("Capabilities: read-only"));
1145        assert!(guidelines.contains("do not modify files"));
1146    }
1147
1148    #[test]
1149    fn test_tool_preference_guidance() {
1150        let tools = vec![TOOL_EXEC_COMMAND.to_string(), TOOL_CODE_SEARCH.to_string()];
1151        let guidelines = generate_tool_guidelines_for_profile(&tools, None, ResolvedShellPromptProfile::UnixLike, true);
1152        assert!(guidelines.contains("Advanced `code_search` takes `query`"));
1153        assert!(guidelines.contains("literal smart-case"));
1154        assert!(guidelines.contains("exact syntactic usages"));
1155        assert!(guidelines.contains("\"result_types\":[\"definition\"]"));
1156        assert!(guidelines.contains("Do not JSON-encode arrays or integers as strings"));
1157        assert!(guidelines.contains("omit unused filters"));
1158        assert!(guidelines.contains("path: \"\""));
1159        assert!(guidelines.contains("git diff -- <path>"));
1160        assert!(guidelines.contains("build tools"));
1161        assert!(guidelines.contains("test tools"));
1162        // Search steering: with both tools present the browse line must
1163        // prefer `code_search` over `rg` for code (session evidence showed
1164        // `rg`-via-exec crowding out `code_search` 654:15).
1165        assert!(guidelines.contains("Prefer `code_search` over `rg`/`grep` for code"));
1166        // Latency steering: fast checks before full builds (tool-agnostic).
1167        assert!(guidelines.contains("Run fast checks before full builds"));
1168        // Completion-as-checkpoint guidance lives in the operating profiles;
1169        // the guidelines section no longer repeats it.
1170        assert!(!guidelines.contains("Completion is a checkpoint"));
1171    }
1172
1173    #[test]
1174    fn test_edit_workflow_guidance() {
1175        let tools = vec![TOOL_APPLY_PATCH.to_string()];
1176        let guidelines = guidelines_for(&tools, None);
1177        assert!(guidelines.contains("Use `apply_patch`"));
1178        assert!(guidelines.contains("patches small"));
1179        // Completion-as-checkpoint guidance lives in the operating profiles;
1180        // the guidelines section no longer repeats it.
1181        assert!(!guidelines.contains("verification resolved"));
1182    }
1183
1184    #[test]
1185    fn test_vt_code_guidance_omits_task_tracker() {
1186        let tools = vec![
1187            TOOL_EXEC_COMMAND.to_string(),
1188            TOOL_WRITE_STDIN.to_string(),
1189            TOOL_APPLY_PATCH.to_string(),
1190        ];
1191        let guidelines = generate_tool_guidelines_for_profile(&tools, None, ResolvedShellPromptProfile::UnixLike, true);
1192
1193        assert!(guidelines.contains("exec_command.cmd"));
1194        for command in ["ls", "rg", "find", "cat", "sed", "awk"] {
1195            assert!(
1196                guidelines.contains(&format!("`{command}`")),
1197                "{command} should be shown as an exec_command.cmd example"
1198            );
1199        }
1200        assert!(guidelines.contains("`write_stdin`"));
1201        assert!(guidelines.contains("At most three live background processes"));
1202        assert!(guidelines.contains("`apply_patch`"));
1203        assert!(!guidelines.contains("task_tracker"));
1204        assert!(!guidelines.contains("list_files"));
1205        assert!(!guidelines.contains("read_file"));
1206    }
1207
1208    #[test]
1209    fn task_tracker_guidance_explains_action_aware_indices() {
1210        let guidelines = generate_runtime_tool_guidelines_for_profile(
1211            &[TOOL_TASK_TRACKER.to_string()],
1212            true,
1213            ResolvedShellPromptProfile::UnixLike,
1214        );
1215
1216        assert!(guidelines.contains(&format!("\n{PLANNING_TASK_TRACKER_INDEX_LINE}")));
1217        assert!(PLANNING_TASK_TRACKER_INDEX_LINE.contains("positive flat indices"));
1218        assert!(PLANNING_TASK_TRACKER_INDEX_LINE.contains("(index 0 is invalid while planning)"));
1219        assert!(PLANNING_TASK_TRACKER_INDEX_LINE.contains("full checklist replacement"));
1220        assert!(PLANNING_TASK_TRACKER_INDEX_LINE.contains(r#"{"action":"list"}"#));
1221        assert!(PLANNING_TASK_TRACKER_INDEX_LINE.contains(r#"{"action":"update","index":1,"status":"in_progress"}"#));
1222        assert!(
1223            PLANNING_TASK_TRACKER_INDEX_LINE.contains(r#"{"action":"update","items":["[x] Done","[ ] Remaining"]}"#)
1224        );
1225        assert!(PLANNING_TASK_TRACKER_COMPACT_LINE.contains("never conflicting fields"));
1226        // The planning sidecar rejects index 0, so no planning line may present
1227        // it as a valid checklist-completion index.
1228        for line in [PLANNING_TASK_TRACKER_INDEX_LINE, PLANNING_TASK_TRACKER_COMPACT_LINE] {
1229            assert!(line.contains("`scope_review` checks cannot satisfy functional `verify` checks"));
1230            assert!(line.len() <= 570, "keep tracker guidance bounded");
1231            assert!(line.contains("index 0 is invalid while planning"), "{line}");
1232            assert!(!line.contains("reserved"), "{line}");
1233            assert!(!line.contains("index: 0"), "{line}");
1234        }
1235    }
1236
1237    #[test]
1238    fn unix_like_guidance_makes_command_reuse_explicit() {
1239        let tools = vec![TOOL_EXEC_COMMAND.to_string(), TOOL_WRITE_STDIN.to_string()];
1240        let guidelines = generate_tool_guidelines_for_profile(&tools, None, ResolvedShellPromptProfile::UnixLike, true);
1241
1242        assert!(guidelines.contains("one-shot `exec_command` calls"));
1243        assert!(guidelines.contains("`!!`, `!$`, `!ssh`, or `fc`"));
1244        assert!(guidelines.contains("write full command arguments explicitly"));
1245        assert!(guidelines.contains("conversation or tool results"));
1246        assert!(guidelines.contains("existing `session_id`"));
1247        assert!(guidelines.contains("background: true"));
1248        assert!(guidelines.contains("Bash `histverify`"));
1249        assert!(guidelines.contains("zsh `HIST_VERIFY`"));
1250        // Cross-turn resume (invariant #22): the live id arrives via a
1251        // turn-start `Exec session resume:` hint when a prior turn ended mid-run.
1252        assert!(guidelines.contains("`Exec session resume:`"));
1253        assert!(guidelines.contains("prior turn ended mid-run"));
1254        // No `code_search` in this profile: the search-preference clause
1255        // must not spend budget naming an unavailable tool.
1256        assert!(!guidelines.contains("Prefer `code_search` over `rg`"));
1257    }
1258
1259    #[test]
1260    fn write_stdin_guidance_advertises_cross_turn_resume_hint() {
1261        let tools = vec![TOOL_WRITE_STDIN.to_string()];
1262        let default_guidance =
1263            generate_tool_guidelines_for_profile(&tools, None, ResolvedShellPromptProfile::UnixLike, true);
1264        assert!(default_guidance.contains("`Exec session resume:`"));
1265        assert!(default_guidance.contains("prior turn ended mid-run"));
1266        assert!(default_guidance.contains("if missing, recover prior output"));
1267        assert!(default_guidance.contains("rerun only for fresh results"));
1268
1269        let minimal = generate_tool_guidelines_with_capabilities(
1270            &tools,
1271            None,
1272            ResolvedShellPromptProfile::UnixLike,
1273            ToolGuidanceProfile::Minimal,
1274            false,
1275        );
1276        assert!(minimal.contains("`Exec session resume:`"));
1277        assert!(minimal.contains("prior turn ended mid-run"));
1278        assert!(minimal.contains("if missing, recover prior output"));
1279    }
1280
1281    #[test]
1282    fn powershell_guidance_uses_native_command_examples() {
1283        let tools = vec![
1284            TOOL_EXEC_COMMAND.to_string(),
1285            TOOL_CODE_SEARCH.to_string(),
1286            TOOL_APPLY_PATCH.to_string(),
1287        ];
1288        let guidelines =
1289            generate_tool_guidelines_for_profile(&tools, None, ResolvedShellPromptProfile::PowerShell, true);
1290
1291        assert!(guidelines.contains("native PowerShell commands"));
1292        assert!(guidelines.contains("`Get-ChildItem`"));
1293        assert!(guidelines.contains("`Select-String`"));
1294        assert!(guidelines.contains("native PowerShell syntax"));
1295        assert!(guidelines.contains("Prefer `code_search` over `Select-String` for code"));
1296        assert!(guidelines.contains("Advanced `code_search` takes `query`"));
1297        assert!(guidelines.contains("literal smart-case"));
1298        assert!(guidelines.contains("omit unused filters"));
1299        assert!(!guidelines.contains("`ls`, `rg`, `find`, `cat`, `sed`, and `awk`"));
1300        assert!(!guidelines.contains("shell history expansion"));
1301        assert!(!guidelines.contains("histverify"));
1302        assert!(!guidelines.contains("HIST_VERIFY"));
1303    }
1304
1305    #[test]
1306    fn shell_profile_prompt_keeps_policy_and_syntax_separate() {
1307        let unix = render_shell_profile_guidance(ResolvedShellPromptProfile::UnixLike);
1308        assert!(unix.contains("Active shell profile: `unix_like`"));
1309        assert!(unix.contains("does not rewrite GNU flags for macOS BSD tools"));
1310        assert!(unix.contains("controls prompt examples and expected command syntax only"));
1311        assert!(unix.contains("does not translate GNU-to-BSD"));
1312
1313        let powershell = render_shell_profile_guidance(ResolvedShellPromptProfile::PowerShell);
1314        assert!(powershell.contains("Active shell profile: `powershell`"));
1315        assert!(powershell.contains("WSL"));
1316        assert!(powershell.contains("Unix-like workflows"));
1317        assert!(powershell.contains("PowerShell-to-Unix"));
1318    }
1319
1320    #[test]
1321    fn test_harness_browse_tool_guidance() {
1322        let tools = vec![TOOL_LIST_FILES.to_string(), TOOL_READ_FILE.to_string()];
1323        let guidelines = guidelines_for(&tools, None);
1324        assert!(guidelines.contains("available read-only repository tools"));
1325        assert!(guidelines.contains("bounded `read_file` ranges"));
1326        assert!(!guidelines.contains("list_files"));
1327        assert!(!guidelines.contains("offset"));
1328        assert!(!guidelines.contains("per_page"));
1329    }
1330
1331    #[test]
1332    fn test_canonical_browse_tool_guidance_prefers_public_tools() {
1333        let tools = vec![
1334            TOOL_CODE_SEARCH.to_string(),
1335            TOOL_LIST_FILES.to_string(),
1336            "read_file".to_string(),
1337        ];
1338        let guidelines = guidelines_for(&tools, None);
1339        assert!(guidelines.contains("available read-only repository tools"));
1340        assert!(guidelines.contains("code_search"));
1341        assert!(guidelines.contains("bounded `read_file` ranges"));
1342    }
1343
1344    #[test]
1345    fn test_capability_basic_guidance() {
1346        let tools = vec![];
1347        let guidelines = guidelines_for(&tools, Some(CapabilityLevel::Basic));
1348        assert!(guidelines.contains("Capabilities: limited"));
1349        assert!(guidelines.contains("enable more capabilities"));
1350    }
1351
1352    #[test]
1353    fn test_capability_file_reading_guidance() {
1354        let tools = vec![TOOL_APPLY_PATCH.to_string()];
1355        let guidelines = guidelines_for(&tools, Some(CapabilityLevel::FileReading));
1356        assert!(guidelines.contains("Capabilities: read-only"));
1357        assert!(guidelines.contains("do not modify"));
1358    }
1359
1360    #[test]
1361    fn test_full_capabilities_no_special_guidance() {
1362        let tools = vec![
1363            TOOL_APPLY_PATCH.to_string(),
1364            TOOL_EXEC_COMMAND.to_string(),
1365            TOOL_CODE_SEARCH.to_string(),
1366        ];
1367        let guidelines = generate_tool_guidelines_for_profile(
1368            &tools,
1369            Some(CapabilityLevel::Editing),
1370            ResolvedShellPromptProfile::UnixLike,
1371            true,
1372        );
1373
1374        assert!(!guidelines.contains("Capabilities: limited"));
1375        assert!(!guidelines.contains("Capabilities: read-only"));
1376    }
1377
1378    #[test]
1379    fn test_empty_tools_shows_read_only_capabilities() {
1380        let tools = vec![];
1381        let guidelines = guidelines_for(&tools, None);
1382        assert!(guidelines.contains("Capabilities: read-only"));
1383    }
1384
1385    #[test]
1386    fn test_planning_workflow_guidance_keeps_verification_open() {
1387        let tools = vec![
1388            TOOL_EXEC_COMMAND.to_string(),
1389            TOOL_TASK_TRACKER.to_string(),
1390            TOOL_CODE_SEARCH.to_string(),
1391        ];
1392        let guidelines =
1393            generate_runtime_tool_guidelines_for_profile(&tools, true, ResolvedShellPromptProfile::UnixLike);
1394        assert!(guidelines.contains("Keep `task_tracker` updated"));
1395        assert!(guidelines.contains("blockers and verification open"));
1396    }
1397
1398    #[test]
1399    fn tool_presence_of_sets_each_flag_in_one_pass() {
1400        let tools = vec![
1401            TOOL_EXEC_COMMAND.to_string(),
1402            TOOL_WRITE_STDIN.to_string(),
1403            TOOL_CODE_SEARCH.to_string(),
1404            TOOL_READ_FILE.to_string(),
1405            TOOL_LIST_FILES.to_string(),
1406            TOOL_APPLY_PATCH.to_string(),
1407            TOOL_REQUEST_USER_INPUT.to_string(),
1408            TOOL_TASK_TRACKER.to_string(),
1409            TOOL_START_PLANNING.to_string(),
1410            "matrix".to_string(),
1411            "unknown_tool".to_string(),
1412        ];
1413        let presence = ToolPresence::of(&tools);
1414        assert!(presence.exec);
1415        assert!(presence.write_stdin);
1416        assert!(presence.code_search);
1417        assert!(presence.read_file);
1418        assert!(presence.list_files);
1419        assert!(presence.apply_patch);
1420        assert!(presence.request_user_input);
1421        assert!(presence.task_tracker);
1422        assert!(presence.start_planning);
1423        assert!(presence.matrix);
1424
1425        let empty = ToolPresence::of(&[]);
1426        assert!(!empty.exec);
1427        assert!(!empty.write_stdin);
1428        assert!(!empty.code_search);
1429        assert!(!empty.read_file);
1430        assert!(!empty.list_files);
1431        assert!(!empty.apply_patch);
1432        assert!(!empty.request_user_input);
1433        assert!(!empty.task_tracker);
1434        assert!(!empty.start_planning);
1435        assert!(!empty.matrix);
1436    }
1437
1438    #[test]
1439    fn test_capability_inference_precedence() {
1440        let tools = vec![TOOL_APPLY_PATCH.to_string(), TOOL_CODE_SEARCH.to_string()];
1441        assert_eq!(infer_capability_level(&tools), CapabilityLevel::CodeSearch);
1442
1443        let tools = vec![TOOL_EXEC_COMMAND.to_string(), TOOL_APPLY_PATCH.to_string()];
1444        assert_eq!(infer_capability_level(&tools), CapabilityLevel::Editing);
1445    }
1446
1447    #[test]
1448    fn test_capability_inference_variants() {
1449        let tools = vec![TOOL_APPLY_PATCH.to_string()];
1450        assert_eq!(infer_capability_level(&tools), CapabilityLevel::Editing);
1451
1452        let tools = vec![TOOL_EXEC_COMMAND.to_string()];
1453        assert_eq!(infer_capability_level(&tools), CapabilityLevel::Bash);
1454
1455        let tools = vec![TOOL_CODE_SEARCH.to_string()];
1456        assert_eq!(infer_capability_level(&tools), CapabilityLevel::CodeSearch);
1457
1458        let tools = vec![TOOL_LIST_FILES.to_string()];
1459        assert_eq!(infer_capability_level(&tools), CapabilityLevel::FileListing);
1460
1461        let tools = vec!["read_file".to_string()];
1462        assert_eq!(infer_capability_level(&tools), CapabilityLevel::FileReading);
1463
1464        let tools = vec!["unknown_tool".to_string()];
1465        assert_eq!(infer_capability_level(&tools), CapabilityLevel::Basic);
1466    }
1467
1468    #[test]
1469    fn test_guidelines_stay_compact() {
1470        let tools = vec![
1471            TOOL_EXEC_COMMAND.to_string(),
1472            TOOL_CODE_SEARCH.to_string(),
1473            "read_file".to_string(),
1474            TOOL_LIST_FILES.to_string(),
1475            "apply_patch".to_string(),
1476        ];
1477        let guidelines = generate_tool_guidelines_for_profile(&tools, None, ResolvedShellPromptProfile::UnixLike, true);
1478        assert!(guidelines.contains("Batch independent read-only calls"));
1479        assert!(guidelines.contains("code_search"));
1480        // Exec-capable profiles describe the fail-closed verifier pipeline
1481        // contract, including the terminal outcome and rejected shell forms.
1482        assert!(guidelines.contains("static read-only filtering pipelines use fail-closed `pipefail`"));
1483        assert!(guidelines.contains("Only terminal exit 0 clears verification"));
1484        assert!(guidelines.contains("Recheck after `--fix`"));
1485        assert!(guidelines.contains("dynamic syntax, mutating tails, `;`, and `||` do not qualify"));
1486        assert!(!guidelines.contains("elided"));
1487        assert!(guidelines.contains("max_output_tokens"));
1488        assert!(guidelines.contains("Build and Auto share tools and safety gates"));
1489        let approx_tokens = vtcode_commons::estimate_tokens(&guidelines);
1490        // The batching, bounded-diff, and verifier-discipline guardrails are
1491        // intentionally part of the compact shared prompt. Raised from 500 so
1492        // the verifier rule can state its reason (a visible exit status).
1493        // Raised to 580 for the Sonnet 5.5 low-effort real-check rule
1494        // (syntax-only/failed-to-start do not count; project package manager,
1495        // never sudo; state which check was skipped and why).
1496        // Raised to 640 for wider-window reuse and code_search unavailable
1497        // no-retry guardrails (session-20261015 overlapping reads + identical
1498        // retries).
1499        // Source inspection is separate from verification and retained in both densities.
1500        assert!(approx_tokens < 640, "got ~{approx_tokens} tokens");
1501    }
1502
1503    #[test]
1504    fn deferred_tools_section_caps_groups_and_truncates_descriptions() {
1505        use crate::llm::provider::ToolNamespace;
1506
1507        fn deferred_mcp_tool(server: &str, tool: &str, description: &str) -> ToolDefinition {
1508            let mut definition = ToolDefinition::function(
1509                format!("mcp__{server}__{tool}"),
1510                "deferred".to_string(),
1511                serde_json::json!({"type": "object"}),
1512            );
1513            definition.namespace = Some(ToolNamespace {
1514                name: server.to_string(),
1515                description: description.to_string(),
1516            });
1517            definition.defer_loading = Some(true);
1518            definition
1519        }
1520
1521        let mut tools = Vec::new();
1522        for index in 0..10 {
1523            tools.push(deferred_mcp_tool(&format!("server-{index:02}"), "search", "Tools provided by MCP server"));
1524        }
1525        // One group with an unbounded server-provided description.
1526        tools.push(deferred_mcp_tool("server-long", "search", &"d".repeat(500)));
1527
1528        let mut prompt = "Base prompt".to_string();
1529        append_deferred_tools_prompt_section(&mut prompt, &tools);
1530
1531        assert!(prompt.contains("[Deferred Tools]"));
1532        assert!(prompt.contains("server-00 (1 tools)"));
1533        assert!(prompt.contains("server-07 (1 tools)"));
1534        assert!(!prompt.contains("server-08 (1 tools)"), "groups past the cap must collapse into overflow");
1535        assert!(!prompt.contains("server-09 (1 tools)"));
1536        assert!(
1537            prompt.contains("(+3 more deferred groups available"),
1538            "10 named groups + 1 long group over the 8-group cap overflows by 3"
1539        );
1540        assert!(!prompt.contains(&"d".repeat(121)), "group descriptions must stay truncated");
1541        assert!(prompt.contains("Use `search_tools` to find a deferred capability"));
1542
1543        // Idempotent: re-appending replaces the section instead of duplicating it.
1544        append_deferred_tools_prompt_section(&mut prompt, &tools);
1545        assert_eq!(prompt.matches("[Deferred Tools]").count(), 1);
1546    }
1547
1548    #[test]
1549    fn deferred_tools_section_omits_empty_and_fully_loaded_groups() {
1550        let mut prompt = "Base prompt".to_string();
1551        append_deferred_tools_prompt_section(&mut prompt, &[]);
1552        assert!(!prompt.contains("[Deferred Tools]"));
1553
1554        let loaded = ToolDefinition::function(
1555            "exec_command".to_string(),
1556            "Shell".to_string(),
1557            serde_json::json!({"type": "object"}),
1558        );
1559        let mut prompt = "Base prompt".to_string();
1560        append_deferred_tools_prompt_section(&mut prompt, &[loaded]);
1561        assert!(!prompt.contains("[Deferred Tools]"));
1562    }
1563
1564    #[test]
1565    fn truncate_deferred_description_keeps_boundaries_and_char_safety() {
1566        // Asymmetric boundaries: exactly at the cap stays verbatim, one over
1567        // truncates with an ellipsis. Unicode stays on char boundaries.
1568        let short = "Tools provided by MCP server";
1569        assert_eq!(truncate_deferred_description(short), short);
1570
1571        let empty = "";
1572        assert_eq!(truncate_deferred_description(empty), "");
1573
1574        let exact: String = "a".repeat(DEFERRED_TOOLS_MAX_DESC_CHARS);
1575        assert_eq!(truncate_deferred_description(&exact), exact);
1576
1577        let one_over: String = "a".repeat(DEFERRED_TOOLS_MAX_DESC_CHARS + 1);
1578        let truncated = truncate_deferred_description(&one_over);
1579        assert!(truncated.ends_with("..."));
1580        assert!(!truncated.contains(&"a".repeat(DEFERRED_TOOLS_MAX_DESC_CHARS + 1)));
1581        assert_eq!(truncated.chars().count(), DEFERRED_TOOLS_MAX_DESC_CHARS + 3);
1582
1583        // Multi-byte chars at the cut point must not panic or split bytes.
1584        let unicode_exact = format!("{}🚀", "a".repeat(DEFERRED_TOOLS_MAX_DESC_CHARS - 1));
1585        assert_eq!(unicode_exact.chars().count(), DEFERRED_TOOLS_MAX_DESC_CHARS);
1586        assert_eq!(truncate_deferred_description(&unicode_exact), unicode_exact);
1587
1588        let unicode_over = format!("{}🚀b", "a".repeat(DEFERRED_TOOLS_MAX_DESC_CHARS - 1));
1589        let unicode_truncated = truncate_deferred_description(&unicode_over);
1590        assert!(unicode_truncated.ends_with("..."));
1591        assert!(unicode_truncated.contains("🚀"));
1592
1593        // Trailing blanks inside the window are trimmed before the ellipsis.
1594        let padded = format!("{}   {}", "a".repeat(DEFERRED_TOOLS_MAX_DESC_CHARS - 4), "b".repeat(10));
1595        let padded_truncated = truncate_deferred_description(&padded);
1596        assert!(padded_truncated.ends_with("..."));
1597        assert!(!padded_truncated.contains(" ..."));
1598    }
1599
1600    #[test]
1601    fn test_parallel_tool_call_guidance() {
1602        let tools = vec![
1603            TOOL_EXEC_COMMAND.to_string(),
1604            TOOL_CODE_SEARCH.to_string(),
1605            TOOL_APPLY_PATCH.to_string(),
1606        ];
1607        let guidelines = generate_tool_guidelines_for_profile(&tools, None, ResolvedShellPromptProfile::UnixLike, true);
1608        assert!(guidelines.contains("parallel"), "Should include parallel tool call guidance");
1609        assert!(guidelines.contains("inputs do not depend"), "Should mention independent inputs");
1610    }
1611
1612    #[test]
1613    fn test_read_only_batching_guidance_is_explicit() {
1614        let tools = vec![
1615            TOOL_CODE_SEARCH.to_string(),
1616            TOOL_READ_FILE.to_string(),
1617            TOOL_LIST_FILES.to_string(),
1618        ];
1619        let guidelines = generate_tool_guidelines_for_profile(&tools, None, ResolvedShellPromptProfile::UnixLike, true);
1620
1621        assert!(guidelines.contains("Batch independent read-only calls"));
1622        assert!(guidelines.contains("`read_file` ranges"));
1623        assert!(guidelines.contains("serialize mutations"));
1624        // No exec tools in this profile: the verifier truthful-status rule is
1625        // exec-conditional and must not spend budget here.
1626        assert!(!guidelines.contains("Only terminal exit 0 clears verification"));
1627    }
1628
1629    #[test]
1630    fn execution_agents_can_suggest_planning_for_demanding_tasks() {
1631        let tools = vec![TOOL_START_PLANNING.to_string(), TOOL_EXEC_COMMAND.to_string()];
1632        let guidelines = generate_tool_guidelines_for_profile(&tools, None, ResolvedShellPromptProfile::UnixLike, true);
1633
1634        assert_eq!(guidelines.matches(START_PLANNING_GUIDANCE_LINE).count(), 1);
1635        let minimal = generate_tool_guidelines_with_capabilities(
1636            &tools,
1637            None,
1638            ResolvedShellPromptProfile::UnixLike,
1639            ToolGuidanceProfile::Minimal,
1640            false,
1641        );
1642        assert_eq!(minimal.matches(START_PLANNING_GUIDANCE_LINE).count(), 1);
1643        // Without the tool, no profile mentions it.
1644        let without = generate_tool_guidelines_for_profile(
1645            &[TOOL_EXEC_COMMAND.to_string()],
1646            None,
1647            ResolvedShellPromptProfile::UnixLike,
1648            true,
1649        );
1650        assert!(!without.contains("start_planning"));
1651    }
1652
1653    #[test]
1654    fn markdown_validation_is_optional_in_planning_and_execution() {
1655        let tools = vec![TOOL_EXEC_COMMAND.to_string(), TOOL_READ_FILE.to_string()];
1656        for planning in [false, true] {
1657            let guidance =
1658                generate_runtime_tool_guidelines_for_profile(&tools, planning, ResolvedShellPromptProfile::UnixLike);
1659            assert_eq!(guidance.matches(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE).count(), 1);
1660            assert!(guidance.contains("report skipped"));
1661            assert!(guidance.contains("without installing tools"));
1662            assert!(guidance.contains("Lint errors remain failures"));
1663        }
1664    }
1665
1666    #[test]
1667    fn planning_workflow_runtime_guidance_keeps_exec_read_only() {
1668        let tools = vec![
1669            TOOL_APPLY_PATCH.to_string(),
1670            TOOL_EXEC_COMMAND.to_string(),
1671            TOOL_CODE_SEARCH.to_string(),
1672        ];
1673        let guidelines =
1674            generate_runtime_tool_guidelines_for_profile(&tools, true, ResolvedShellPromptProfile::UnixLike);
1675
1676        assert!(guidelines.contains("Planning workflow active"));
1677        assert!(guidelines.contains("`exec_command` only for read-only verification"));
1678        assert!(!guidelines.contains("<proposed_plan>"));
1679        assert!(!guidelines.contains("Every implementation step"));
1680        assert!(guidelines.contains("omit unused filters"));
1681        assert!(!guidelines.contains("Inspect before edit"));
1682    }
1683
1684    #[test]
1685    fn minimal_planning_addendum_prefers_read_tools_over_shell_reads() {
1686        // Asymmetric pair over read-tool presence: with read tools the
1687        // inspection line names them and prefers them over shell reads;
1688        // without, only the generic small-inspection rule remains. Both
1689        // share the same git-history tail.
1690        let tail = "start git history with `git log --oneline`";
1691        let with_readers = ToolPresence::of(&[TOOL_READ_FILE.to_string(), TOOL_CODE_SEARCH.to_string()]);
1692        let mut guidance = String::new();
1693        append_minimal_planning_addendum(&mut guidance, &with_readers);
1694        assert!(guidance.contains("prefer `read_file`/`code_search` over `exec_command` shell reads"));
1695        assert!(guidance.contains(tail));
1696
1697        let without_readers = ToolPresence::of(&[TOOL_EXEC_COMMAND.to_string()]);
1698        let mut bare = String::new();
1699        append_minimal_planning_addendum(&mut bare, &without_readers);
1700        assert!(!bare.contains("prefer `"));
1701        assert!(!bare.contains("over `exec_command` shell reads"));
1702        assert!(bare.contains(tail));
1703    }
1704
1705    #[test]
1706    fn runtime_tool_guidance_uses_explicit_powershell_profile() {
1707        let tools = vec![
1708            TOOL_APPLY_PATCH.to_string(),
1709            TOOL_EXEC_COMMAND.to_string(),
1710            TOOL_CODE_SEARCH.to_string(),
1711        ];
1712        let guidelines =
1713            generate_runtime_tool_guidelines_for_profile(&tools, false, ResolvedShellPromptProfile::PowerShell);
1714
1715        assert!(guidelines.contains("native PowerShell commands"));
1716        assert!(guidelines.contains("`Get-ChildItem`"));
1717        assert!(guidelines.contains("`Select-String`"));
1718        assert!(guidelines.contains("native PowerShell syntax"));
1719        assert!(!guidelines.contains("`ls`, `rg`, `find`, `cat`, `sed`, and `awk`"));
1720    }
1721
1722    #[test]
1723    fn runtime_tool_guidance_uses_explicit_unix_like_profile() {
1724        let tools = vec![
1725            TOOL_APPLY_PATCH.to_string(),
1726            TOOL_EXEC_COMMAND.to_string(),
1727            TOOL_CODE_SEARCH.to_string(),
1728        ];
1729        let guidelines =
1730            generate_runtime_tool_guidelines_for_profile(&tools, false, ResolvedShellPromptProfile::UnixLike);
1731
1732        assert!(guidelines.contains("`ls`, `find`, `cat`, `sed`, and `awk` for repository browsing"));
1733        assert!(guidelines.contains("Prefer `code_search` over `rg`/`grep` for code"));
1734        assert!(guidelines.contains("Advanced `code_search` takes `query`"));
1735        assert!(guidelines.contains("literal smart-case"));
1736        assert!(guidelines.contains("shell-only tasks"));
1737        assert!(!guidelines.contains("native PowerShell commands"));
1738        assert!(!guidelines.contains("`Get-ChildItem`"));
1739    }
1740
1741    #[test]
1742    fn shell_browse_guidance_lists_rg_only_without_code_search() {
1743        // Asymmetric pair over `has_search`: without the dedicated search
1744        // tool the browse line must name `rg`; with it, `rg` drops out in
1745        // favor of the `code_search` preference suffix.
1746        let without_search = shell_browse_guidance(ResolvedShellPromptProfile::UnixLike, false);
1747        assert!(without_search.contains("`ls`, `rg`, `find`, `cat`, `sed`, and `awk` for repository browsing"));
1748        assert!(!without_search.contains("Prefer `code_search`"));
1749
1750        let with_search = shell_browse_guidance(ResolvedShellPromptProfile::UnixLike, true);
1751        assert!(with_search.contains("`ls`, `find`, `cat`, `sed`, and `awk` for repository browsing"));
1752        assert!(!with_search.contains("`ls`, `rg`, `find`"));
1753        assert!(with_search.contains("Prefer `code_search` over `rg`/`grep` for code"));
1754    }
1755
1756    #[test]
1757    fn runtime_tool_prompt_sections_use_explicit_profile_for_active_tools() {
1758        let mut powershell_prompt = "Base prompt".to_string();
1759        let mut unix_prompt = "Base prompt".to_string();
1760        let snapshot = SessionToolCatalogSnapshot::new(
1761            7,
1762            9,
1763            false,
1764            false,
1765            Some(std::sync::Arc::new(vec![
1766                ToolDefinition::function(
1767                    TOOL_EXEC_COMMAND.to_string(),
1768                    "Shell".to_string(),
1769                    serde_json::json!({"type": "object"}),
1770                ),
1771                ToolDefinition::function(
1772                    TOOL_CODE_SEARCH.to_string(),
1773                    "Bounded source search".to_string(),
1774                    serde_json::json!({"type": "object"}),
1775                ),
1776            ])),
1777            false,
1778        );
1779
1780        append_runtime_tool_prompt_sections_for_profile(
1781            &mut powershell_prompt,
1782            &snapshot,
1783            false,
1784            ResolvedShellPromptProfile::PowerShell,
1785        );
1786        append_runtime_tool_prompt_sections_for_profile(
1787            &mut unix_prompt,
1788            &snapshot,
1789            false,
1790            ResolvedShellPromptProfile::UnixLike,
1791        );
1792
1793        assert!(powershell_prompt.contains("## Active Tools"));
1794        assert!(powershell_prompt.contains("`Get-ChildItem`"));
1795        assert!(powershell_prompt.contains("`Select-String`"));
1796        assert!(!powershell_prompt.contains("`ls`, `rg`, `find`, `cat`, `sed`, and `awk`"));
1797
1798        assert!(unix_prompt.contains("## Active Tools"));
1799        assert!(unix_prompt.contains("`ls`, `find`, `cat`, `sed`, and `awk` for repository browsing"));
1800        assert!(unix_prompt.contains("Prefer `code_search` over `rg`/`grep` for code"));
1801        assert!(unix_prompt.contains("Advanced `code_search` takes `query`"));
1802        assert!(unix_prompt.contains("literal smart-case"));
1803        assert!(!unix_prompt.contains("`Get-ChildItem`"));
1804    }
1805
1806    #[test]
1807    fn runtime_tool_prompt_sections_include_catalog_metadata() {
1808        let mut prompt = "Base prompt".to_string();
1809        let snapshot = SessionToolCatalogSnapshot::new(
1810            7,
1811            9,
1812            true,
1813            false,
1814            Some(std::sync::Arc::new(vec![
1815                ToolDefinition::function(
1816                    TOOL_EXEC_COMMAND.to_string(),
1817                    "Search".to_string(),
1818                    serde_json::json!({"type": "object"}),
1819                ),
1820                ToolDefinition::function(
1821                    TOOL_APPLY_PATCH.to_string(),
1822                    "File".to_string(),
1823                    serde_json::json!({"type": "object"}),
1824                ),
1825            ])),
1826            false,
1827        );
1828
1829        append_runtime_tool_prompt_sections_for_profile(
1830            &mut prompt,
1831            &snapshot,
1832            true,
1833            ShellPromptProfile::Auto.resolve_for_current_platform(),
1834        );
1835
1836        assert!(prompt.contains("## Active Tools"));
1837        assert!(prompt.contains("[Runtime Tool Catalog]"));
1838        assert!(prompt.contains("catalog_tools: 2"));
1839        assert!(prompt.contains("currently_available_tools: exec_command, apply_patch"));
1840        assert!(prompt.contains("request_user_input_enabled: false"));
1841    }
1842
1843    #[test]
1844    fn runtime_tool_prompt_sections_replace_existing_runtime_sections() {
1845        let mut prompt = "Base prompt".to_string();
1846        let first = SessionToolCatalogSnapshot::new(
1847            1,
1848            2,
1849            false,
1850            false,
1851            Some(std::sync::Arc::new(vec![ToolDefinition::function(
1852                TOOL_EXEC_COMMAND.to_string(),
1853                "Search".to_string(),
1854                serde_json::json!({"type": "object"}),
1855            )])),
1856            false,
1857        );
1858        let second = SessionToolCatalogSnapshot::new(
1859            7,
1860            9,
1861            true,
1862            true,
1863            Some(std::sync::Arc::new(vec![ToolDefinition::function(
1864                TOOL_APPLY_PATCH.to_string(),
1865                "File".to_string(),
1866                serde_json::json!({"type": "object"}),
1867            )])),
1868            false,
1869        );
1870
1871        let shell = ShellPromptProfile::Auto.resolve_for_current_platform();
1872        append_runtime_tool_prompt_sections_for_profile(&mut prompt, &first, true, shell);
1873        append_runtime_tool_prompt_sections_for_profile(&mut prompt, &second, true, shell);
1874
1875        assert_eq!(prompt.matches("## Active Tools").count(), 1);
1876        assert_eq!(prompt.matches("[Runtime Tool Catalog]").count(), 1);
1877        assert!(prompt.contains("version: 7"));
1878        assert!(!prompt.contains("version: 1"));
1879        assert!(prompt.contains("request_user_input_enabled: true"));
1880        assert!(!prompt.contains("request_user_input_enabled: false"));
1881    }
1882}