Skip to main content

vtcode_core/prompts/guidelines/
mod.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, remove_prompt_section_after,
7    trim_trailing_newlines,
8};
9use crate::tools::registry::tool_groups;
10
11const TOOL_EXEC_COMMAND: &str = tools::EXEC_COMMAND;
12const TOOL_WRITE_STDIN: &str = tools::WRITE_STDIN;
13const TOOL_CODE_SEARCH: &str = tools::CODE_SEARCH;
14const TOOL_READ_FILE: &str = tools::READ_FILE;
15const TOOL_LIST_FILES: &str = tools::LIST_FILES;
16const TOOL_GREP_FILE: &str = tools::GREP_FILE;
17const TOOL_APPLY_PATCH: &str = tools::APPLY_PATCH;
18const TOOL_REQUEST_USER_INPUT: &str = tools::REQUEST_USER_INPUT;
19const TOOL_ASK_SESSION: &str = tools::ASK_SESSION;
20const TOOL_TASK_TRACKER: &str = tools::TASK_TRACKER;
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 SESSION_MESSAGING_GUIDANCE: &str = "- Peer sessions: `list_sessions` discovers live CLI sessions in this workspace; `ask_session` sends one a question and its `answer_session` reply arrives as a notice on a later turn. Delivery needs the peer running.";
24const 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. For GitHub queries prefer `gh search`/`gh api` via exec_command when available.";
25
26const TOOL_START_PLANNING: &str = tools::START_PLANNING;
27
28const OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE: &str = "- `verify: [skip Markdown lint if unavailable]`: report skipped; review diff/links without installing tools. Lint errors remain failures.";
29
30/// The single home of `start_planning` guidance, shared by the Minimal and
31/// Default Active Tools. The tool itself asks the user before entering
32/// planning (`require_confirmation`), except under full-auto or
33/// skip-confirmations, so the model calls it rather than proposing it in prose.
34const 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.";
35
36/// Planning-workflow `task_tracker` rules that the tracker schema cannot
37/// carry.
38///
39/// The call shapes (list/update/bulk, index vs. index_path vs. items), the
40/// planning index rule, and "update as work progresses" all live in the tool
41/// description and parameter schema, which reach the model with the tool
42/// definitions. Only the tracker-to-verification relation is left, and it
43/// applies equally at every density, so one constant serves both the Minimal
44/// planning addendum and the Default planning Active Tools.
45const PLANNING_TASK_TRACKER_LINE: &str = "- `task_tracker`: keep blockers and verification open. `scope_review` checks cannot satisfy functional `verify` checks.";
46
47/// Context-token ceiling at or below which Active Tools documentation
48/// resolves to the Minimal density.
49const MINIMAL_CONTEXT_TOKEN_CEILING: usize = 32_000;
50
51/// The single home of the parallel-call hint, shared by the Minimal and
52/// Default Active Tools; emitted only when the provider keeps parallel tool
53/// configuration enabled.
54const PARALLEL_TOOLS_LINE: &str = "- Run independent tools in parallel when inputs do not depend on each other.";
55
56/// The single home of the `request_user_input` threshold rule, shared by the
57/// Minimal planning addendum and the planning Active Tools.
58/// The `request_user_input` threshold for the planning workflow.
59///
60/// Planning mode already states this threshold in
61/// `PLANNING_WORKFLOW_INTERVIEW_POLICY_LINE` ("only for a critical blocker
62/// where proceeding could cause materially different, unsafe, or irreversible
63/// work"), which the planning notice always renders. This line therefore
64/// carries only the part the notice does not: that the blocker must survive
65/// repository exploration.
66const REQUEST_USER_INPUT_LINE: &str = "- Use `request_user_input` only for a blocker that repository exploration did not resolve. Set `multi_select: true` for independent checkbox answers; omit it for one radio-button answer.";
67
68/// Read-only capability line shared by the capability-level and
69/// tool-fallback arms of `capability_mode_line`.
70const CAPABILITY_READ_ONLY_LINE: &str =
71    "- Capabilities: read-only. Analyze and search, but do not modify files or run shell commands.";
72
73/// Policy line shared by both shell profiles: the profile governs syntax
74/// examples only, and VT Code never translates flags across shells.
75const 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. VT Code does not translate GNU-to-BSD, BSD-to-GNU, Unix-to-PowerShell, or PowerShell-to-Unix command flags.";
76
77/// Documentation density is independent of the tools a session may execute.
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub(crate) enum ToolGuidanceProfile {
80    Minimal,
81    Default,
82}
83
84impl ToolGuidanceProfile {
85    #[must_use]
86    pub(crate) fn resolve(
87        context_tokens: usize,
88        default_prompt_tokens: usize,
89        max_prompt_tokens: usize,
90        input_usd_per_token: Option<f64>,
91        max_budget_usd: Option<f64>,
92    ) -> Self {
93        let exceeds_cost = input_usd_per_token.zip(max_budget_usd).is_some_and(|(price, budget)| {
94            price.is_finite() && price >= 0.0 && budget.is_finite() && default_prompt_tokens as f64 * price > budget
95        });
96        if (context_tokens > 0 && context_tokens <= MINIMAL_CONTEXT_TOKEN_CEILING)
97            || (max_prompt_tokens > 0 && default_prompt_tokens > max_prompt_tokens)
98            || exceeds_cost
99        {
100            Self::Minimal
101        } else {
102            Self::Default
103        }
104    }
105}
106
107/// Which guidance-gating tools a session exposes, computed once per build so
108/// every Active Tools variant branches on the same membership policy.
109struct ToolPresence {
110    exec: bool,
111    write_stdin: bool,
112    code_search: bool,
113    web_search: bool,
114    read_file: bool,
115    grep_file: bool,
116    list_files: bool,
117    apply_patch: bool,
118    request_user_input: bool,
119    task_tracker: bool,
120    start_planning: bool,
121    matrix: bool,
122    record_decision: bool,
123    session_messaging: bool,
124}
125
126impl ToolPresence {
127    fn of(available_tools: &[String]) -> Self {
128        // Single pass over the tool list: the old form ran one linear
129        // `any()` scan per flag (10 scans per call, up to 4 calls per
130        // model-aware prompt build). Same membership policy, one walk.
131        let mut presence = Self {
132            exec: false,
133            write_stdin: false,
134            code_search: false,
135            web_search: false,
136            read_file: false,
137            grep_file: false,
138            list_files: false,
139            apply_patch: false,
140            request_user_input: false,
141            task_tracker: false,
142            start_planning: false,
143            matrix: false,
144            record_decision: false,
145            session_messaging: 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                TOOL_ASK_SESSION => presence.session_messaging = true,
162                "record_decision" => presence.record_decision = true,
163                _ => {}
164            }
165        }
166        presence
167    }
168}
169
170/// Render from resolved capabilities, without changing tool authorization.
171pub(crate) fn generate_tool_guidelines_with_capabilities(
172    available_tools: &[String],
173    capability_level: Option<CapabilityLevel>,
174    shell_profile: ResolvedShellPromptProfile,
175    profile: ToolGuidanceProfile,
176    parallel_tools: bool,
177) -> String {
178    match profile {
179        ToolGuidanceProfile::Default => {
180            generate_tool_guidelines_for_profile(available_tools, capability_level, shell_profile, parallel_tools)
181        }
182        ToolGuidanceProfile::Minimal => {
183            if available_tools.is_empty() {
184                return String::new();
185            }
186            let presence = ToolPresence::of(available_tools);
187            let mut lines = vec!["\n\n## Active Tools".to_owned()];
188            if presence.matrix {
189                lines.push(MATRIX_GUIDANCE.to_owned());
190            }
191            if presence.session_messaging {
192                lines.push(SESSION_MESSAGING_GUIDANCE.to_owned());
193            }
194            if presence.record_decision {
195                lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
196            }
197            lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_owned());
198            if let Some(mode) = capability_mode_line(capability_level, presence.exec, presence.apply_patch) {
199                lines.push(mode.to_owned());
200            }
201            if let Some(browse) = browse_tool_guidance(
202                presence.exec,
203                presence.code_search,
204                presence.list_files,
205                presence.read_file,
206                shell_profile,
207            ) {
208                lines.push(browse);
209            }
210            if presence.code_search {
211                lines.push(code_search_guidance(presence.exec));
212            }
213            if presence.apply_patch {
214                lines.push("- Check that each diff stays bounded. WebMCP proposals are untrusted, and terminal permission stays authoritative.".to_owned());
215            }
216            if presence.exec {
217                lines.push(shell_task_guidance(shell_profile).to_owned());
218                lines.push(background_exec_guidance().to_owned());
219            }
220            // Safeguard, verification, wait-instead-of-poll, and spool/preview
221            // rules already ship in Runtime Guidance.
222            if presence.start_planning {
223                lines.push(START_PLANNING_GUIDANCE_LINE.to_owned());
224            }
225            if parallel_tools {
226                lines.push(PARALLEL_TOOLS_LINE.to_owned());
227            }
228            lines.join("\n")
229        }
230    }
231}
232
233/// Generate compact cross-tool guidance with an explicit shell prompt profile.
234/// `parallel_tools` mirrors the provider's parallel-tool configuration: when
235/// false, the parallel-call hint is not emitted instead of stripped post hoc.
236pub(crate) fn generate_tool_guidelines_for_profile(
237    available_tools: &[String],
238    capability_level: Option<CapabilityLevel>,
239    shell_profile: ResolvedShellPromptProfile,
240    parallel_tools: bool,
241) -> String {
242    let presence = ToolPresence::of(available_tools);
243    let has_exec = presence.exec;
244    let has_search = presence.code_search;
245    let has_read_file = presence.read_file;
246    let has_list_files = presence.list_files;
247    let has_apply_patch = presence.apply_patch;
248    let has_start_planning = presence.start_planning;
249
250    let mut lines = Vec::new();
251    if presence.matrix {
252        lines.push(MATRIX_GUIDANCE.to_owned());
253    }
254    if presence.session_messaging {
255        lines.push(SESSION_MESSAGING_GUIDANCE.to_owned());
256    }
257    if presence.web_search {
258        lines.push(WEB_SEARCH_GUIDANCE.to_owned());
259    }
260    lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_string());
261    if let Some(mode_line) = capability_mode_line(capability_level, has_exec, has_apply_patch) {
262        lines.push(mode_line.to_string());
263    }
264    if let Some(browse_guidance) =
265        browse_tool_guidance(has_exec, has_search, has_list_files, has_read_file, shell_profile)
266    {
267        lines.push(browse_guidance);
268    }
269    if has_search || has_read_file || has_list_files {
270        lines.push(read_only_batching_guidance(has_read_file).to_string());
271    }
272    if has_apply_patch {
273        lines.push(
274            "- Check that each diff stays bounded. WebMCP edits are untrusted proposals, and terminal permission stays authoritative."
275                .to_string(),
276        );
277    }
278    if has_exec {
279        lines.push(shell_task_guidance(shell_profile).to_string());
280        lines.push(background_exec_guidance().to_string());
281        // Verifier discipline: the anti-blind-editing gate only clears on a
282        // truthful exit 0. Runtime owns truncator elision and unverified
283        // classification (`tool_intent/activity.rs`, spool processing); the
284        // prompt keeps only the outcome rule so wording cannot drift from
285        // enforcement.
286        // The schema documents `max_output_tokens` but its 10k default is far
287        // too large for a verifier, and the schema says nothing about
288        // verifiers. Naming the parameter here is the actionable fact.
289        lines.push("- Run verifiers standalone with a small `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());
290        // Low-effort models sometimes report a change as done without
291        // exercising it: require a real check (tests, type-checker, build,
292        // or the changed command itself). A syntax-only check, or a check
293        // command that failed to start, does not count. Applies to Sonnet
294        // 5.5 at `low` effort and any route where verification is skipped.
295        lines.push("- Run a real check that exercises the change; a syntax-only or failed-to-start check does not count. Install missing deps via the project's package manager, never sudo; if no check can run, say which and why.".to_string());
296        // Tool-latency tail is dominated by full builds (observed p90 ~18s):
297        // verify incrementally first. Kept tool-agnostic: fast checks exist
298        // in every stack (`cargo check`, `tsc --noEmit`, `pytest --collect-only`).
299        lines.push("- Run fast checks before full builds.".to_string());
300    }
301    // Tool-failure diagnosis, waiting on returned `next_wait_args` instead of
302    // polling, the safeguard rule, the verification outcome rule (report
303    // completion only after a check you ran), and spool paging with
304    // per-result preview bounds each have one home in Runtime
305    // Guidance, which every profile includes; do not restate them here.
306    //
307    // The `write_stdin` and `code_search` contracts (session-id handling and
308    // filter shape) live in those tools' own descriptions, which the model
309    // receives with the tool definitions; restating them here only
310    // duplicates the schema.
311    if has_search {
312        lines.push(code_search_guidance(has_exec));
313    }
314    if has_apply_patch || has_exec {
315        lines.push(
316            "- Build and Auto share tools and safety gates; Auto changes confirmation behavior only after explicit approval or full-auto policy."
317                .to_string(),
318        );
319    }
320    if (has_search || has_exec) && parallel_tools {
321        lines.push(PARALLEL_TOOLS_LINE.to_string());
322    }
323    if has_start_planning {
324        lines.push(START_PLANNING_GUIDANCE_LINE.to_string());
325    }
326
327    if lines.is_empty() {
328        return String::new();
329    }
330
331    if presence.record_decision {
332        lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
333    }
334    format!("\n\n## Active Tools\n{}", lines.join("\n"))
335}
336
337pub fn append_runtime_tool_prompt_sections_for_profile(
338    prompt: &mut String,
339    tool_snapshot: &SessionToolCatalogSnapshot,
340    include_catalog_metadata: bool,
341    shell_profile: ResolvedShellPromptProfile,
342) {
343    let names = snapshot_tool_names(tool_snapshot);
344    append_runtime_tool_sections_with_names(prompt, tool_snapshot, names, include_catalog_metadata, shell_profile, 0);
345}
346
347/// Select documentation density using the active route and session budgets.
348pub fn append_runtime_tool_prompt_sections_for_model(
349    prompt: &mut String,
350    tool_snapshot: &SessionToolCatalogSnapshot,
351    include_catalog_metadata: bool,
352    shell_profile: ResolvedShellPromptProfile,
353    provider: &dyn crate::llm::provider::LLMProvider,
354    model: &str,
355    config: Option<&crate::config::VTCodeConfig>,
356) {
357    append_runtime_tool_prompt_sections_for_model_after(
358        prompt,
359        tool_snapshot,
360        include_catalog_metadata,
361        shell_profile,
362        provider,
363        model,
364        config,
365        0,
366    );
367}
368
369/// Append runtime tool guidance while preserving all existing prompt content.
370///
371/// Call this with a fresh base prompt that does not contain generated tool
372/// guidance. The existing prefix may include user-authored section headings.
373pub fn append_fresh_runtime_tool_prompt_sections_for_model(
374    prompt: &mut String,
375    tool_snapshot: &SessionToolCatalogSnapshot,
376    include_catalog_metadata: bool,
377    shell_profile: ResolvedShellPromptProfile,
378    provider: &dyn crate::llm::provider::LLMProvider,
379    model: &str,
380    config: Option<&crate::config::VTCodeConfig>,
381) {
382    let boundary = prompt.len();
383    append_runtime_tool_prompt_sections_for_model_after(
384        prompt,
385        tool_snapshot,
386        include_catalog_metadata,
387        shell_profile,
388        provider,
389        model,
390        config,
391        boundary,
392    );
393}
394
395fn append_runtime_tool_prompt_sections_for_model_after(
396    prompt: &mut String,
397    tool_snapshot: &SessionToolCatalogSnapshot,
398    include_catalog_metadata: bool,
399    shell_profile: ResolvedShellPromptProfile,
400    provider: &dyn crate::llm::provider::LLMProvider,
401    model: &str,
402    config: Option<&crate::config::VTCodeConfig>,
403    boundary: usize,
404) {
405    let names = snapshot_tool_names(tool_snapshot);
406    let default_guidance = append_runtime_tool_sections_with_names(
407        prompt,
408        tool_snapshot,
409        names,
410        include_catalog_metadata,
411        shell_profile,
412        boundary,
413    );
414    let pricing = crate::config::models::model_catalog_entry(provider.name(), model).map(|entry| entry.pricing);
415    let profile = ToolGuidanceProfile::resolve(
416        crate::compaction::effective_context_budget(config, provider, model),
417        vtcode_commons::estimate_tokens(prompt),
418        config.map_or(0, |cfg| cfg.agent.max_system_prompt_tokens as usize),
419        pricing.and_then(|price| price.input),
420        config.and_then(|cfg| cfg.agent.harness.max_budget_usd),
421    );
422    let parallel_tools = provider.supports_parallel_tool_config(model);
423    // The planning mode section owns the output contract at every density.
424    // Default planning tool guidance contains no parallel-call hint.
425    if tool_snapshot.planning_active && profile == ToolGuidanceProfile::Default {
426        return;
427    }
428    remove_prompt_section_after(prompt, boundary, "## Active Tools", SectionBoundaryMode::BracketOrMarkdown);
429    let presence = ToolPresence::of(names);
430    let capability_level = Some(infer_capability_level_from_presence(&presence));
431    let mut guidance = match profile {
432        ToolGuidanceProfile::Default => {
433            let mut guidance = default_guidance;
434            if let (Some(original), Some(effective)) = (
435                capability_mode_line(None, presence.exec, presence.apply_patch),
436                capability_mode_line(capability_level, presence.exec, presence.apply_patch),
437            ) && original != effective
438                && let Some(start) = guidance.find(original)
439            {
440                guidance.replace_range(start..start + original.len(), effective);
441            }
442            if !parallel_tools && let Some(start) = guidance.find(PARALLEL_TOOLS_LINE) {
443                guidance.replace_range(start.saturating_sub(1)..start + PARALLEL_TOOLS_LINE.len(), "");
444            }
445            guidance
446        }
447        ToolGuidanceProfile::Minimal => {
448            generate_tool_guidelines_with_capabilities(names, capability_level, shell_profile, profile, parallel_tools)
449        }
450    };
451    if tool_snapshot.planning_active {
452        append_minimal_planning_addendum(&mut guidance, &presence);
453    }
454    append_prompt_block(prompt, guidance.trim_start_matches('\n'));
455}
456
457/// Replace the runtime tool sections with guidance built from `names`, plus
458/// optional catalog metadata. Return the Default guidance so model-aware
459/// callers can reuse it after measuring the assembled prompt.
460fn append_runtime_tool_sections_with_names(
461    prompt: &mut String,
462    tool_snapshot: &SessionToolCatalogSnapshot,
463    names: &[String],
464    include_catalog_metadata: bool,
465    shell_profile: ResolvedShellPromptProfile,
466    boundary: usize,
467) -> String {
468    remove_prompt_section_after(prompt, boundary, "## Active Tools", SectionBoundaryMode::BracketOrMarkdown);
469    remove_prompt_section_after(prompt, boundary, "[Runtime Tool Catalog]", SectionBoundaryMode::BracketOrMarkdown);
470    if boundary == 0 {
471        trim_trailing_newlines(prompt);
472    }
473
474    let guidelines = generate_runtime_tool_guidelines_for_profile(names, tool_snapshot.planning_active, shell_profile);
475    if !guidelines.is_empty() {
476        append_prompt_block(prompt, guidelines.trim_start_matches('\n'));
477    }
478
479    if include_catalog_metadata && tool_snapshot.snapshot.is_some() {
480        let active_tools = if tool_snapshot.active_tool_names.is_empty() {
481            "none".to_string()
482        } else {
483            tool_snapshot.active_tool_names.join(", ")
484        };
485        // One payload line: this block is machine diagnostics for the
486        // prompt/catalog alignment guard, not model guidance, so it must not
487        // spend prompt lines. The guard parses `key: value` pairs separated
488        // by `;`, so the format stays machine-readable.
489        let catalog_metadata = format!(
490            "[Runtime Tool Catalog]\n- version: {}; epoch: {}; catalog_tools: {}; available_tools: {}; currently_available_tools: {}; request_user_input_enabled: {}",
491            tool_snapshot.version,
492            tool_snapshot.epoch,
493            tool_snapshot.catalog_tools(),
494            tool_snapshot.available_tools(),
495            active_tools,
496            tool_snapshot.request_user_input_enabled,
497        );
498        append_prompt_block(prompt, &catalog_metadata);
499    }
500    guidelines
501}
502
503/// Compact tool reminders; the planning mode section retains the canonical
504/// research, step-quality, output, and persistence contract at every density.
505fn append_minimal_planning_addendum(guidance: &mut String, presence: &ToolPresence) {
506    guidance.push_str("\n- Planning is read-only.");
507    let mut read_tools = Vec::with_capacity(4);
508    if presence.read_file {
509        read_tools.push(TOOL_READ_FILE);
510    }
511    if presence.grep_file {
512        read_tools.push(TOOL_GREP_FILE);
513    }
514    if presence.code_search {
515        read_tools.push(TOOL_CODE_SEARCH);
516    }
517    if presence.list_files {
518        read_tools.push(TOOL_LIST_FILES);
519    }
520    guidance.push_str("\n- Keep inspections small: ");
521    if !read_tools.is_empty() {
522        guidance.push_str(&format!("prefer `{}` over `exec_command` shell reads; ", read_tools.join("`/`")));
523    }
524    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`.");
525    if presence.task_tracker {
526        guidance.push('\n');
527        guidance.push_str(PLANNING_TASK_TRACKER_LINE);
528    }
529    if presence.request_user_input {
530        guidance.push('\n');
531        guidance.push_str(REQUEST_USER_INPUT_LINE);
532    }
533}
534
535/// Append a compact summary of tools omitted from a client-local wire payload.
536///
537/// The listing is bounded like the `## Skills` routing section: at most
538/// `DEFERRED_TOOLS_MAX_GROUPS` groups are named and the rest collapse into one
539/// overflow line, so MCP-heavy sessions cannot bloat every request. Group
540/// descriptions are server-provided and unbounded, so each line is truncated
541/// to `DEFERRED_TOOLS_MAX_DESC_CHARS` characters.
542pub fn append_deferred_tools_prompt_section(prompt: &mut String, tools: &[ToolDefinition]) {
543    remove_prompt_section(prompt, "[Deferred Tools]", SectionBoundaryMode::BracketOrMarkdown);
544    append_fresh_deferred_tools_prompt_section(prompt, tools);
545}
546
547/// Append deferred-tool guidance to a fresh runtime prompt without removing
548/// user-authored sections with the same heading.
549pub fn append_fresh_deferred_tools_prompt_section(prompt: &mut String, tools: &[ToolDefinition]) {
550    let mut groups: Vec<_> = tool_groups(tools)
551        .into_iter()
552        .filter(|group| group.deferred_count > 0)
553        .collect();
554    let overflow = groups.len().saturating_sub(DEFERRED_TOOLS_MAX_GROUPS);
555    groups.truncate(DEFERRED_TOOLS_MAX_GROUPS);
556
557    let mut lines: Vec<String> = groups
558        .into_iter()
559        .map(|group| {
560            let description = truncate_deferred_description(group.description.as_deref().unwrap_or_default());
561            format!("- {} ({} tools): {}", group.name, group.deferred_count, description)
562        })
563        .collect();
564    if overflow > 0 {
565        lines.push(format!("(+{overflow} more deferred groups available — use `search_tools` to find them)"));
566    }
567
568    let unnamespaced_deferred = tools
569        .iter()
570        .filter(|tool| tool.namespace.is_none() && tool.defer_loading == Some(true))
571        .count();
572    if unnamespaced_deferred > 0 {
573        lines.push(format!("- {unnamespaced_deferred} additional deferred tools"));
574    }
575
576    if lines.is_empty() {
577        return;
578    }
579
580    let section = format!(
581        "[Deferred Tools]\n{}\nUse `search_tools` to find a deferred capability. Selected definitions become available in the next request segment.",
582        lines.join("\n")
583    );
584    append_prompt_block(prompt, &section);
585}
586
587/// Maximum deferred-tool groups named in the `[Deferred Tools]` prompt
588/// section before the rest collapse into one overflow line.
589const DEFERRED_TOOLS_MAX_GROUPS: usize = 8;
590/// Maximum characters of a group description in the section. Mirrors the
591/// `## Skills` line truncation: server-provided text must not bloat the prompt.
592const DEFERRED_TOOLS_MAX_DESC_CHARS: usize = 120;
593
594fn truncate_deferred_description(description: &str) -> String {
595    // Single pass: visit at most `MAX + 1` chars. The old form ran
596    // `chars().count()` over the whole string, then `chars().take()` again.
597    let mut chars = description.chars();
598    let truncated: String = chars.by_ref().take(DEFERRED_TOOLS_MAX_DESC_CHARS).collect();
599    if chars.next().is_none() {
600        return description.to_string();
601    }
602    format!("{}...", truncated.trim_end())
603}
604
605fn generate_runtime_tool_guidelines_for_profile(
606    available_tools: &[String],
607    planning_active: bool,
608    shell_profile: ResolvedShellPromptProfile,
609) -> String {
610    if !planning_active {
611        // Measurement parity: this Default-density build feeds the prompt size
612        // that `ToolGuidanceProfile::resolve` reads, so it keeps shipping the
613        // parallel-call hint unconditionally like the static composition path.
614        return generate_tool_guidelines_for_profile(available_tools, None, shell_profile, true);
615    }
616
617    let presence = ToolPresence::of(available_tools);
618    let has_exec = presence.exec;
619    let has_search = presence.code_search;
620    let has_read_file = presence.read_file;
621    let has_list_files = presence.list_files;
622    let has_request_user_input = presence.request_user_input;
623    let has_task_tracker = presence.task_tracker;
624
625    let mut lines = vec!["- Planning workflow active: stay within the read-safe tool list.".to_string()];
626    if presence.web_search {
627        lines.push(WEB_SEARCH_GUIDANCE.to_owned());
628    }
629    lines.push(OPTIONAL_MARKDOWN_VALIDATION_GUIDANCE.to_string());
630    if let Some(browse_guidance) =
631        browse_tool_guidance(has_exec, has_search, has_list_files, has_read_file, shell_profile)
632    {
633        lines.push(browse_guidance);
634    }
635    if has_exec {
636        lines.push("- In Planning workflow, use `exec_command` only for read-only verification.".to_string());
637    }
638    if has_search {
639        lines.push(code_search_guidance(has_exec));
640    }
641    if has_task_tracker {
642        // The tracker call shapes (list/update/bulk, index vs. index_path vs.
643        // items, and "omit unused fields") are documented by the tool
644        // description, which reaches the model with the tool definitions.
645        // This line keeps only the planning-only facts the schema does not
646        // carry.
647        lines.push(PLANNING_TASK_TRACKER_LINE.to_string());
648    }
649    if has_request_user_input {
650        lines.push(REQUEST_USER_INPUT_LINE.to_string());
651    }
652    if has_search || has_exec {
653        lines.push("- If calls repeat without progress, tighten the plan instead of retrying identically.".to_string());
654    }
655    if presence.record_decision {
656        lines.push(PUBLIC_DECISION_GUIDANCE.to_owned());
657    }
658
659    format!("\n\n## Active Tools\n{}", lines.join("\n"))
660}
661
662fn snapshot_tool_names(tool_snapshot: &SessionToolCatalogSnapshot) -> &[String] {
663    &tool_snapshot.active_tool_names
664}
665
666fn browse_tool_guidance(
667    has_exec: bool,
668    has_search: bool,
669    has_list_files: bool,
670    has_read_file: bool,
671    shell_profile: ResolvedShellPromptProfile,
672) -> Option<String> {
673    if has_exec {
674        return Some(shell_browse_guidance(shell_profile, has_search));
675    }
676
677    if !(has_search || has_list_files || has_read_file) {
678        return None;
679    }
680
681    Some("- Use available read-only repository tools for browsing; do not modify files.".to_string())
682}
683
684pub(crate) fn render_shell_profile_guidance(shell_profile: ResolvedShellPromptProfile) -> String {
685    let profile_lines = match shell_profile {
686        ResolvedShellPromptProfile::UnixLike => {
687            "- Active shell profile: `unix_like`.\n- On macOS, write BSD-compatible flags for BSD tools. VT Code does not rewrite GNU flags for macOS BSD tools.\n- Commands run under the user's login shell, which may be zsh: avoid bash-only syntax such as `${PIPESTATUS[...]}` (it expands empty outside bash); rely on the harness-reported exit status instead of capturing codes through pipes."
688        }
689        ResolvedShellPromptProfile::PowerShell => {
690            "- Active shell profile: `powershell`.\n- On native Windows, use WSL when you need Unix-like workflows or Unix command examples."
691        }
692    };
693    format!("## Shell Profile\n{profile_lines}\n{SHELL_PROFILE_POLICY_SUFFIX}")
694}
695
696fn shell_browse_guidance(shell_profile: ResolvedShellPromptProfile, has_search: bool) -> String {
697    // Sessions show `exec_command` + `rg` crowding out `code_search`
698    // (observed 654 exec vs 15 code_search in one run): `rg` scans text
699    // while `code_search` resolves definitions and exact usages, so route
700    // code search to the dedicated tool whenever it is available.
701    const SEARCH_PREFERENCE_UNIX: &str = " Prefer `code_search` over `rg`/`grep` for code.";
702    const SEARCH_PREFERENCE_POWERSHELL: &str = " Prefer `code_search` over `Select-String` for code.";
703    match shell_profile {
704        ResolvedShellPromptProfile::UnixLike => {
705            let mut line = String::from("- Browse the repository with `exec_command.cmd`.");
706            if has_search {
707                line.push_str(SEARCH_PREFERENCE_UNIX);
708            }
709            line
710        }
711        ResolvedShellPromptProfile::PowerShell => {
712            let mut line = "- Browse the repository with `exec_command.cmd`.".to_string();
713            if has_search {
714                line.push_str(SEARCH_PREFERENCE_POWERSHELL);
715            }
716            line
717        }
718    }
719}
720
721fn shell_task_guidance(shell_profile: ResolvedShellPromptProfile) -> &'static str {
722    match shell_profile {
723        ResolvedShellPromptProfile::UnixLike => {
724            "- 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`)."
725        }
726        ResolvedShellPromptProfile::PowerShell => {
727            "- Use native PowerShell syntax in `exec_command.cmd` for shell-only tasks."
728        }
729    }
730}
731
732fn background_exec_guidance() -> &'static str {
733    // `background`, the three-process cap, `session_id`, `monitor_filter`, and
734    // `monitor_digest` are all documented by the `exec_command` schema, which
735    // reaches the model with the tool definitions, and the runtime rejects an
736    // over-limit background start with an actionable error. The only fact the
737    // schema cannot state is *when* to reach for it.
738    "- For long-lived commands, start them in the background rather than blocking a turn."
739}
740
741fn read_only_batching_guidance(has_read_file: bool) -> &'static str {
742    if has_read_file {
743        "- 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."
744    } else {
745        "- Batch independent read-only calls; order dependent reads, and serialize mutations."
746    }
747}
748
749fn code_search_guidance(has_exec: bool) -> String {
750    // The schema owns the query contract ("Literal code or path query",
751    // smart-case) and the filter names. What it cannot state is that `|`
752    // separates alternatives, that a truncated or unavailable result needs a
753    // different query rather than a retry, and that the runtime coerces a
754    // JSON-encoded array or integer. The runtime also emits per-call hints
755    // when it truncates or drops a result category, so this line carries the
756    // standing rule rather than repeating them.
757    const BASE: &str = "- `code_search` queries are literal and smart-case; `|` separates alternatives. On a truncated or unavailable result, change the query instead of retrying it. Do not JSON-encode arrays or integers as strings.";
758    if has_exec {
759        format!("{BASE} Use `exec_command` or a skill for syntax patterns.")
760    } else {
761        BASE.to_string()
762    }
763}
764
765fn capability_mode_line(
766    capability_level: Option<CapabilityLevel>,
767    has_exec: bool,
768    has_file: bool,
769) -> Option<&'static str> {
770    match capability_level {
771        Some(CapabilityLevel::Basic) => {
772            Some("- Capabilities: limited. Ask the user to enable more capabilities if file work is required.")
773        }
774        Some(CapabilityLevel::FileReading | CapabilityLevel::FileListing) => Some(CAPABILITY_READ_ONLY_LINE),
775        _ if !has_exec && !has_file => Some(CAPABILITY_READ_ONLY_LINE),
776        _ => None,
777    }
778}
779
780/// Infer capability level from available tools.
781pub(crate) fn infer_capability_level(available_tools: &[String]) -> CapabilityLevel {
782    infer_capability_level_from_presence(&ToolPresence::of(available_tools))
783}
784
785fn infer_capability_level_from_presence(presence: &ToolPresence) -> CapabilityLevel {
786    if presence.code_search {
787        CapabilityLevel::CodeSearch
788    } else if presence.apply_patch {
789        CapabilityLevel::Editing
790    } else if presence.exec {
791        CapabilityLevel::Bash
792    } else if presence.list_files {
793        CapabilityLevel::FileListing
794    } else if presence.read_file {
795        CapabilityLevel::FileReading
796    } else {
797        CapabilityLevel::Basic
798    }
799}
800
801#[cfg(test)]
802mod tests;