Skip to main content

vtcode_config/core/agent/
harness.rs

1//! Harness execution, verification, and tool-result-clearing configuration.
2
3use serde::{Deserialize, Serialize};
4
5use crate::constants::defaults;
6
7use super::approval::{AsyncApprovalConfig, ConfidenceEscalationConfig, SkepticPanelConfig};
8use super::{ContextResetMode, ContinuationPolicy, HarnessOrchestrationMode};
9
10#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
11#[derive(Debug, Clone, Deserialize, Serialize)]
12pub struct AgentHarnessConfig {
13    /// Source exposure policy; advisory by default, independently of verification.
14    #[serde(default)]
15    pub inspection: InspectionConfig,
16    /// Maximum wall clock time (seconds) for tool execution in a turn
17    #[serde(default = "default_harness_max_tool_wall_clock_secs")]
18    pub max_tool_wall_clock_secs: u64,
19    /// Maximum retries for retryable tool errors
20    #[serde(default = "default_harness_max_tool_retries")]
21    pub max_tool_retries: u32,
22    /// Maximum number of tool calls that may execute concurrently within a single parallel batch.
23    /// Set to `0` to disable the cap (unlimited concurrency).  Default: 4.
24    #[serde(default = "default_harness_max_parallel_tool_calls")]
25    pub max_parallel_tool_calls: usize,
26    /// Enable automatic context compaction when token pressure crosses threshold.
27    ///
28    /// Enabled by default. When disabled, normal threshold-triggered automatic
29    /// compaction is skipped; the bounded post-tool recovery path may still
30    /// compact the older prefix as a safety fallback after a provider failure.
31    #[serde(default = "default_harness_auto_compaction_enabled")]
32    pub auto_compaction_enabled: bool,
33    /// Optional absolute compaction threshold (tokens) for native and local compaction.
34    ///
35    /// When set, this may lower the trigger but cannot bypass the resolved
36    /// model capacity or `context.max_context_tokens` safety ceiling.
37    /// The next response budget is reserved before deriving the trigger.
38    #[serde(default)]
39    pub auto_compaction_threshold_tokens: Option<u64>,
40    /// Optional custom instructions for the compaction summarization prompt.
41    /// When set, replaces the default Anthropic compaction prompt entirely.
42    /// Useful for tool-use scenarios to prevent the model from calling tools
43    /// during summarization. Only applies to Anthropic provider.
44    #[serde(default)]
45    pub auto_compaction_instructions: Option<String>,
46    /// Whether to pause after compaction (Anthropic only).
47    /// When true and compaction triggers, the API returns early with
48    /// `stop_reason: "compaction"` and only the compaction block.
49    /// The caller can then insert additional messages before the model
50    /// generates its text response.
51    #[serde(default)]
52    pub auto_compaction_pause_after: bool,
53    /// Automatically compact conversation context when the main session model
54    /// or provider is switched mid-conversation, so the newly selected model
55    /// starts from a summary instead of the outgoing model's raw trace.
56    /// Default: true. Disable to keep the full history across a model switch.
57    #[serde(default = "default_harness_compact_on_model_switch")]
58    pub compact_on_model_switch: bool,
59    /// Provider-native tool-result clearing policy. When enabled, old tool
60    /// results are stripped from the context once it grows past
61    /// `trigger_tokens`, protecting recent results and assistant tool-call batches
62    /// and always retaining at least `clear_at_least_tokens`. This bounds
63    /// per-turn context growth and is enabled by default.
64    #[serde(default)]
65    pub tool_result_clearing: ToolResultClearingConfig,
66    /// Optional maximum estimated API cost in USD before VT Code stops the session.
67    #[serde(default)]
68    pub max_budget_usd: Option<f64>,
69    /// Fraction of `max_budget_usd` at which VT Code emits a one-time
70    /// near-budget warning. Ignored when `max_budget_usd` is unset.
71    #[serde(default = "default_harness_budget_warning_threshold")]
72    pub budget_warning_threshold: f64,
73    /// Controls whether harness-managed continuation loops are enabled.
74    #[serde(default)]
75    pub continuation_policy: ContinuationPolicy,
76    /// When to trigger a context reset — starting a clean session from
77    /// external artifacts only, discarding conversation history. Distinct
78    /// from compaction (which preserves conversational continuity).
79    /// Default: `off` (carry forward history as before).
80    #[serde(default)]
81    pub context_reset_mode: ContextResetMode,
82    /// Number of consecutive stall turns before `on_stall` context reset
83    /// triggers. Ignored unless `context_reset_mode = "on_stall"`.
84    /// Default: 2.
85    #[serde(default = "default_harness_context_reset_stall_threshold")]
86    pub context_reset_stall_threshold: u32,
87    /// Optional compatibility/export JSONL path for harness events.
88    /// Canonical events are always stored under the workspace session store;
89    /// unset configuration creates no global harness file.
90    #[serde(default)]
91    pub event_log_path: Option<String>,
92    /// Select the exec/full-auto harness orchestration path.
93    #[serde(default)]
94    pub orchestration_mode: HarnessOrchestrationMode,
95    /// Maximum generator revision rounds after evaluator rejection.
96    #[serde(default = "default_harness_max_revision_rounds")]
97    pub max_revision_rounds: usize,
98    /// Confidence-based escalation for autonomous decisions.
99    ///
100    /// Implements the escalation decision rule:
101    ///   Escalate iff p_success < tau_conf OR action in A_irreversible OR cost > B_auto
102    ///
103    /// When a tool call is classified as irreversible or below the confidence
104    /// threshold, the harness escalates to blocked-handoff instead of proceeding
105    /// autonomously.  Opt-in (default: disabled).
106    #[serde(default)]
107    pub confidence_escalation: ConfidenceEscalationConfig,
108    /// Async (out-of-band) approval for deferred tool execution requests.
109    ///
110    /// When enabled, approval requests exceeding the auto-approve cost threshold
111    /// write a blocker file and notify the user out-of-band rather than blocking
112    /// on terminal input.  Opt-in (default: disabled).
113    #[serde(default)]
114    async_approval: AsyncApprovalConfig,
115    /// Adversarial multi-model evaluator panel.  When enabled, the harness
116    /// runs the evaluator prompt against every listed model in parallel and
117    /// aggregates the strictest verdict/scorecard across the panel.
118    /// Opt-in (default: disabled).
119    #[serde(default)]
120    pub skeptic_panel: SkepticPanelConfig,
121    /// Autonomous recovery for the anti-blind-editing verification gate.
122    /// When the model emits text instead of running a verifier, the harness
123    /// grants bounded directive retries and (optionally) runs the detected
124    /// project verifier itself instead of forcing manual `continue`.
125    #[serde(default)]
126    pub verification: VerificationAutoRecoveryConfig,
127    /// Tracker-aware auto-continuation: when `task_tracker` still has
128    /// incomplete steps, keep looping / auto-queue the next turn instead of
129    /// ending and nudging the user to resume.
130    #[serde(default)]
131    pub continuation: TrackerContinuationConfig,
132}
133
134impl Default for AgentHarnessConfig {
135    fn default() -> Self {
136        Self {
137            inspection: InspectionConfig::default(),
138            max_tool_wall_clock_secs: default_harness_max_tool_wall_clock_secs(),
139            max_tool_retries: default_harness_max_tool_retries(),
140            max_parallel_tool_calls: default_harness_max_parallel_tool_calls(),
141            auto_compaction_enabled: default_harness_auto_compaction_enabled(),
142            auto_compaction_threshold_tokens: None,
143            auto_compaction_instructions: None,
144            auto_compaction_pause_after: false,
145            compact_on_model_switch: default_harness_compact_on_model_switch(),
146            tool_result_clearing: ToolResultClearingConfig::default(),
147            max_budget_usd: None,
148            budget_warning_threshold: default_harness_budget_warning_threshold(),
149            continuation_policy: ContinuationPolicy::default(),
150            context_reset_mode: ContextResetMode::default(),
151            context_reset_stall_threshold: default_harness_context_reset_stall_threshold(),
152            event_log_path: None,
153            orchestration_mode: HarnessOrchestrationMode::default(),
154            max_revision_rounds: default_harness_max_revision_rounds(),
155            confidence_escalation: ConfidenceEscalationConfig::default(),
156            async_approval: AsyncApprovalConfig::default(),
157            skeptic_panel: SkepticPanelConfig::default(),
158            verification: VerificationAutoRecoveryConfig::default(),
159            continuation: TrackerContinuationConfig::default(),
160        }
161    }
162}
163/// Source inspection policy, independent of post-edit verification.
164#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
165#[derive(Debug, Clone, Default, Deserialize, Serialize)]
166pub struct InspectionConfig {
167    #[serde(default)]
168    pub mode: InspectionMode,
169}
170
171/// Whether missing source exposure blocks mutations.
172#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
173#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
174#[serde(rename_all = "snake_case")]
175pub enum InspectionMode {
176    Enforce,
177    #[default]
178    Warn,
179    Off,
180}
181/// Tracker-aware auto-continuation policy.
182///
183/// When `task_tracker` still has incomplete items, the binary runloop
184/// continues in-turn for status-only responses and, after recoverable
185/// budget/recovery turn ends (or on session resume), auto-queues a bounded
186/// follow-up turn instead of requiring the user to type `continue`.
187#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
188#[derive(Debug, Clone, Deserialize, Serialize)]
189pub struct TrackerContinuationConfig {
190    /// Auto-continue while the task tracker has incomplete steps.
191    /// Default: true.
192    #[serde(default = "default_tracker_auto_continue")]
193    pub auto_continue_tracker: bool,
194    /// Bounded cross-turn auto-continue turns after a recoverable end
195    /// (budget/preview/tool-free recovery) or on resume while tracker work
196    /// remains. The episode budget **progress-resets** when any tracker step
197    /// completes. `0` disables cross-turn tracker auto-queue (in-turn
198    /// continuation still applies when `auto_continue_tracker` is true).
199    /// Default: 32.
200    #[serde(default = "default_tracker_cross_turn_turns")]
201    pub cross_turn_turns: u8,
202}
203
204impl Default for TrackerContinuationConfig {
205    fn default() -> Self {
206        Self {
207            auto_continue_tracker: default_tracker_auto_continue(),
208            cross_turn_turns: default_tracker_cross_turn_turns(),
209        }
210    }
211}
212
213#[inline]
214const fn default_tracker_auto_continue() -> bool {
215    true
216}
217
218#[inline]
219const fn default_tracker_cross_turn_turns() -> u8 {
220    32
221}
222/// Completion verification and bounded corrective recovery.
223///
224/// Editing remains available while checks are missing. At completion, run
225/// missing checks through the normal pipeline. At most one corrective pass
226/// per request is allowed; legacy numeric settings remain parseable and may
227/// disable or tighten this bound, never expand it.
228#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
229#[derive(Debug, Clone, Deserialize, Serialize)]
230pub struct VerificationAutoRecoveryConfig {
231    /// Run missing interactive completion checks through the normal pipeline.
232    /// Default: true. False disables automatic interactive execution and
233    /// corrective recovery; headless mandatory verification remains required.
234    #[serde(default = "default_verification_auto_execute")]
235    pub auto_execute: bool,
236    /// Legacy in-turn recovery bound. Zero disables the corrective pass;
237    /// nonzero values permit at most one pass. Default: 2 for compatibility.
238    #[serde(default = "default_verification_in_turn_attempts")]
239    pub in_turn_attempts: u8,
240    /// Legacy cross-turn recovery bound. Zero disables the corrective pass;
241    /// nonzero values permit at most one pass per request. Default: 2 for compatibility.
242    #[serde(default = "default_verification_cross_turn_turns")]
243    pub cross_turn_turns: u8,
244    /// Explicit verifier command overriding project-marker detection
245    /// (e.g. `"cargo nextest run -p mycrate"`). Must be a standalone verifier
246    /// or pure `&&` chain; pipes and `;`/`||` joins are rejected at use.
247    #[serde(default)]
248    pub default_verifier_override: Option<String>,
249    /// Consecutive failed harness auto-verifications before escalation to a
250    /// manual blocked handoff carrying the failure log. Reset by any success,
251    /// completed turn, or fresh user input. Default: 3.
252    #[serde(default = "default_verification_max_consecutive_failures")]
253    pub max_consecutive_failures: u8,
254}
255
256impl Default for VerificationAutoRecoveryConfig {
257    fn default() -> Self {
258        Self {
259            auto_execute: default_verification_auto_execute(),
260            in_turn_attempts: default_verification_in_turn_attempts(),
261            cross_turn_turns: default_verification_cross_turn_turns(),
262            default_verifier_override: None,
263            max_consecutive_failures: default_verification_max_consecutive_failures(),
264        }
265    }
266}
267#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
268#[derive(Debug, Clone, Deserialize, Serialize)]
269pub struct ToolResultClearingConfig {
270    /// Enables native or request-only local clearing; set `false` to opt out.
271    /// Durable history and events retain full outputs.
272    #[serde(default = "default_tool_result_clearing_enabled")]
273    pub enabled: bool,
274    /// Local clearing caps this at 60% of the provider/session history budget
275    /// after output reserves and system/tool-schema overhead (minimum positive
276    /// cap: 1). Lower configured triggers win; unknown capacity keeps this
277    /// value. Configured values must be positive. Native edit thresholds keep
278    /// the configured value.
279    #[serde(default = "default_tool_result_clearing_trigger_tokens")]
280    pub trigger_tokens: u64,
281    /// Protect newest results. Local clearing also retains all results from
282    /// their originating assistant tool-call batches, matching call IDs across
283    /// reordered completions and intervening directives.
284    #[serde(default = "default_tool_result_clearing_keep_tool_uses")]
285    pub keep_tool_uses: u32,
286    /// Local clearing additionally protects the newest assistant messages with
287    /// tool calls, selected by originating message order (default 2). Protection
288    /// is the union with keep_tool_uses; 0 restores count-based batch retention.
289    /// Native Anthropic context edits continue to use keep_tool_uses only.
290    #[serde(default = "default_tool_result_clearing_keep_recent_tool_batches")]
291    pub keep_recent_tool_batches: u32,
292    #[serde(default = "default_tool_result_clearing_clear_at_least_tokens")]
293    pub clear_at_least_tokens: u64,
294    /// Replace paired `tool_calls[].function.arguments` for stubbed results.
295    /// Leaving inputs in place keeps full `apply_patch`/`write_file` bodies on
296    /// every request after the result was already reclaimed. Defaults to
297    /// `true`; set `false` to opt out. Bare `#[serde(default)]` on a `bool`
298    /// is `false`, so this field names its default fn explicitly.
299    #[serde(default = "default_tool_result_clearing_clear_tool_inputs")]
300    pub clear_tool_inputs: bool,
301}
302
303impl Default for ToolResultClearingConfig {
304    fn default() -> Self {
305        Self {
306            enabled: default_tool_result_clearing_enabled(),
307            trigger_tokens: default_tool_result_clearing_trigger_tokens(),
308            keep_tool_uses: default_tool_result_clearing_keep_tool_uses(),
309            keep_recent_tool_batches: default_tool_result_clearing_keep_recent_tool_batches(),
310            clear_at_least_tokens: default_tool_result_clearing_clear_at_least_tokens(),
311            clear_tool_inputs: default_tool_result_clearing_clear_tool_inputs(),
312        }
313    }
314}
315
316impl ToolResultClearingConfig {
317    pub(crate) fn validate(&self) -> Result<(), String> {
318        if self.trigger_tokens == 0 {
319            return Err("tool_result_clearing.trigger_tokens must be greater than 0".to_string());
320        }
321        if self.keep_tool_uses == 0 {
322            return Err("tool_result_clearing.keep_tool_uses must be greater than 0".to_string());
323        }
324        if self.clear_at_least_tokens == 0 {
325            return Err("tool_result_clearing.clear_at_least_tokens must be greater than 0".to_string());
326        }
327        Ok(())
328    }
329}
330#[inline]
331const fn default_harness_max_tool_wall_clock_secs() -> u64 {
332    defaults::DEFAULT_MAX_TOOL_WALL_CLOCK_SECS
333}
334
335#[inline]
336const fn default_harness_max_tool_retries() -> u32 {
337    defaults::DEFAULT_MAX_TOOL_RETRIES
338}
339
340#[inline]
341const fn default_harness_max_parallel_tool_calls() -> usize {
342    4 // Cap parallel fan-out at 4; set to 0 in vtcode.toml to remove the limit.
343}
344
345#[inline]
346const fn default_harness_auto_compaction_enabled() -> bool {
347    true
348}
349
350const fn default_harness_compact_on_model_switch() -> bool {
351    true
352}
353
354#[inline]
355const fn default_harness_context_reset_stall_threshold() -> u32 {
356    2
357}
358
359#[inline]
360const fn default_verification_auto_execute() -> bool {
361    true
362}
363
364#[inline]
365const fn default_verification_in_turn_attempts() -> u8 {
366    2
367}
368
369#[inline]
370const fn default_verification_cross_turn_turns() -> u8 {
371    2
372}
373
374#[inline]
375const fn default_verification_max_consecutive_failures() -> u8 {
376    3
377}
378
379#[inline]
380const fn default_tool_result_clearing_enabled() -> bool {
381    true
382}
383
384#[inline]
385const fn default_tool_result_clearing_trigger_tokens() -> u64 {
386    // 40k: research/audit turns were observed at ~1M input tokens/turn with
387    // the old 100k trigger — tool results piled up long before any clearing.
388    40_000
389}
390
391#[inline]
392const fn default_tool_result_clearing_keep_recent_tool_batches() -> u32 {
393    2
394}
395
396const fn default_tool_result_clearing_keep_tool_uses() -> u32 {
397    2
398}
399
400#[inline]
401const fn default_tool_result_clearing_clear_at_least_tokens() -> u64 {
402    30_000
403}
404
405#[inline]
406const fn default_tool_result_clearing_clear_tool_inputs() -> bool {
407    true
408}
409
410#[inline]
411const fn default_harness_max_revision_rounds() -> usize {
412    2
413}
414
415#[inline]
416const fn default_harness_budget_warning_threshold() -> f64 {
417    0.75
418}
419
420#[cfg(test)]
421mod inspection_tests {
422    use super::*;
423
424    #[test]
425    fn source_inspection_defaults_warns_and_parses_explicit_modes() {
426        assert_eq!(AgentHarnessConfig::default().inspection.mode, InspectionMode::Warn);
427        for text in ["", "[inspection]"] {
428            let config: AgentHarnessConfig = toml::from_str(text).unwrap();
429            assert_eq!(config.inspection.mode, InspectionMode::Warn);
430        }
431        for (text, expected) in [
432            ("enforce", InspectionMode::Enforce),
433            ("warn", InspectionMode::Warn),
434            ("off", InspectionMode::Off),
435        ] {
436            let config: AgentHarnessConfig = toml::from_str(&format!("[inspection]\nmode = '{text}'")).unwrap();
437            assert_eq!(config.inspection.mode, expected);
438        }
439        assert!(toml::from_str::<AgentHarnessConfig>("[inspection]\nmode = 'permissive'").is_err());
440    }
441}