Skip to main content

vtcode_core/tools/registry/
completion_verification.rs

1//! Runtime verification evidence, independent of compactable source exposure.
2
3use std::collections::{HashSet, VecDeque};
4
5use serde_json::Value;
6
7use super::ToolRegistry;
8use crate::config::constants::tools;
9use crate::tools::{command_args, tool_intent};
10
11const OPTIONAL_EVIDENCE_LIMIT: usize = 32;
12
13#[derive(Debug)]
14struct VerifierEvidence {
15    identity: u64,
16    generation: u64,
17    command: String,
18    session_id: Option<String>,
19    exit_code: Option<i64>,
20}
21
22struct RestoredToolCall<'a> {
23    name: &'a str,
24    args: Value,
25}
26
27#[derive(Clone, Copy)]
28enum MutationEvidenceSource {
29    Live,
30    Restored,
31}
32
33#[derive(Debug, Default)]
34pub(super) struct CompletionVerification {
35    generation: u64,
36    history_initialized: bool,
37    next_identity: u64,
38    evidence: VecDeque<VerifierEvidence>,
39    required_commands: Vec<String>,
40    pending_mutation_sessions: HashSet<String>,
41}
42
43impl CompletionVerification {
44    fn mutate(&mut self) {
45        self.generation = self.generation.saturating_add(1);
46    }
47
48    fn launch(&mut self, command: String) -> u64 {
49        self.next_identity = self.next_identity.saturating_add(1);
50        // New launches supersede older evidence for the same command.
51        self.evidence.retain(|entry| entry.command != command);
52        self.evidence.push_back(VerifierEvidence {
53            identity: self.next_identity,
54            generation: self.generation,
55            command,
56            session_id: None,
57            exit_code: None,
58        });
59        self.prune_optional_evidence();
60        self.next_identity
61    }
62
63    fn prune_optional_evidence(&mut self) {
64        let mut pinned = HashSet::new();
65        for command in &self.required_commands {
66            let command = executed_command_identity(command);
67            let mut newest = true;
68            for entry in self
69                .evidence
70                .iter()
71                .rev()
72                .filter(|entry| command_covers_required(&entry.command, &command))
73            {
74                // Keep the newest verdict for each requirement and retain live
75                // handles until their terminal result or cleanup is observed.
76                if newest || entry.session_id.is_some() {
77                    pinned.insert(entry.identity);
78                }
79                newest = false;
80            }
81        }
82        let mut to_remove = self
83            .evidence
84            .iter()
85            .filter(|entry| !pinned.contains(&entry.identity))
86            .count()
87            .saturating_sub(OPTIONAL_EVIDENCE_LIMIT);
88        // Required verdicts and yielded handles remain available until their
89        // command is replaced or released by the tracker.
90        self.evidence.retain(|entry| {
91            if to_remove == 0 || pinned.contains(&entry.identity) {
92                true
93            } else {
94                to_remove -= 1;
95                false
96            }
97        });
98    }
99
100    fn observe(&mut self, identity: u64, output: &Value) {
101        let Some(evidence) = self.evidence.iter_mut().find(|entry| entry.identity == identity) else {
102            return;
103        };
104        if output.get("error").is_some()
105            || output.get("success").and_then(Value::as_bool) == Some(false)
106            || ["blocked", "not_executed", "cancelled", "termination_requested"]
107                .iter()
108                .any(|key| output.get(key).and_then(Value::as_bool) == Some(true))
109        {
110            evidence.session_id = None;
111            evidence.exit_code = None;
112            self.prune_optional_evidence();
113            return;
114        }
115        if evidence
116            .session_id
117            .as_deref()
118            .is_some_and(|expected| command_args::session_id_text(output).is_some_and(|returned| returned != expected))
119        {
120            return;
121        }
122        if let Some(exit_code) = output.get("exit_code").and_then(Value::as_i64) {
123            evidence.exit_code = Some(exit_code);
124            evidence.session_id = None;
125        } else if let Some(session_id) = command_args::session_id_text(output) {
126            evidence.session_id = Some(session_id.to_owned());
127        }
128        self.prune_optional_evidence();
129    }
130
131    fn command_passed(&self, command: &str) -> bool {
132        let command = executed_command_identity(command);
133        self.evidence
134            .iter()
135            .rev()
136            .find(|entry| command_covers_required(&entry.command, &command))
137            .is_some_and(|entry| entry.generation == self.generation && entry.exit_code == Some(0))
138    }
139
140    fn requires_command(&self, command: &str) -> bool {
141        let command = executed_command_identity(command);
142        self.required_commands
143            .iter()
144            .any(|required| command_covers_required(&command, &executed_command_identity(required)))
145    }
146
147    fn pending(&self) -> bool {
148        if !self.pending_mutation_sessions.is_empty() {
149            return true;
150        }
151        if self.generation == 0 {
152            return false;
153        }
154        if !self.required_commands.is_empty() {
155            return self.required_commands.iter().any(|command| !self.command_passed(command));
156        }
157        !self
158            .evidence
159            .back()
160            .is_some_and(|entry| entry.generation == self.generation && entry.exit_code == Some(0))
161    }
162}
163
164fn executed_command_identity(command: &str) -> String {
165    let args = serde_json::json!({"action":"run", "command":command});
166    let executed = tool_intent::shell_args_as_executed(tools::UNIFIED_EXEC, &args);
167    command_args::raw_command_text(&executed)
168        .unwrap_or_else(|| command.to_owned())
169        .trim()
170        .to_owned()
171}
172
173/// Defense boundary: ingest-time verification (`task_tracking::metadata_from_input`,
174/// `task_tracking::apply_metadata_line`) already strips code spans, but
175/// restored/hand-written tracker content may reach here unnormalized, so the
176/// store keeps stripping before `command_passed` compares or harness
177/// auto-verification re-runs the value verbatim.
178use crate::tools::handlers::task_tracking::unwrap_verify_code_span;
179
180fn command_covers_required(command: &str, required: &str) -> bool {
181    command == required
182        || (command.contains("&&") && tool_intent::activity::shell_command_covers_required_check(command, required))
183}
184
185fn is_session_cleanup(args: &Value) -> bool {
186    tool_intent::is_exec_session_cleanup_call(tools::WRITE_STDIN, args)
187        || matches!(tool_intent::command_session_action(args), Some("close" | "terminate"))
188}
189
190fn mutation_targets_are_exempt(name: &str, args: &Value, output: &Value) -> bool {
191    let exempt = |tool_name: &str, targets: &Value| {
192        tool_intent::is_plan_artifact_write(tool_name, targets) || tool_intent::is_docs_only_write(tool_name, targets)
193    };
194    if !exempt(name, args) {
195        return false;
196    }
197    // Built-in file results report canonical targets. Requested prose/planning
198    // aliases must not exempt writes through symlinks to code.
199    let effective_paths: Vec<_> = ["path", "from", "to"]
200        .iter()
201        .filter_map(|key| output.get(*key).and_then(Value::as_str))
202        .chain(
203            output
204                .get("modified_files")
205                .and_then(Value::as_array)
206                .into_iter()
207                .flatten()
208                .filter_map(Value::as_str),
209        )
210        .collect();
211    effective_paths.is_empty() || exempt(tools::WRITE_FILE, &serde_json::json!({"paths":effective_paths}))
212}
213
214impl ToolRegistry {
215    /// True when current-generation evidence satisfies every local obligation.
216    pub fn has_current_completion_verification(&self) -> bool {
217        let state = self.harness_context.completion_verification.lock();
218        let checks_passed = if state.required_commands.is_empty() {
219            state
220                .evidence
221                .back()
222                .is_some_and(|entry| entry.generation == state.generation && entry.exit_code == Some(0))
223        } else {
224            state.required_commands.iter().all(|command| state.command_passed(command))
225        };
226        !state.pending()
227            && checks_passed
228            && !state
229                .evidence
230                .iter()
231                .any(|entry| entry.generation == state.generation && entry.session_id.is_some())
232    }
233
234    /// Drain terminal command results already returned by exec tools. Notification
235    /// consumers retain these identities, independently of compactable history.
236    pub fn take_observed_terminal_exec_results(&self) -> Vec<String> {
237        self.harness_context.terminal_exec_results.lock().drain().collect()
238    }
239
240    /// Reconstruct mutation debt once from restored history; historical checks are not runtime verdicts.
241    pub fn restore_completion_verification_from_history(&self, history: &[crate::llm::provider::Message]) {
242        use crate::llm::provider::MessageRole;
243        {
244            let mut state = self.harness_context.completion_verification.lock();
245            if state.history_initialized {
246                return;
247            }
248            state.history_initialized = true;
249            // A live registry already owns reliable runtime evidence. Only a
250            // newly restored registry reconstructs debt from archived messages.
251            if state.generation != 0 || !state.evidence.is_empty() {
252                return;
253            }
254        }
255        let mut pending = std::collections::HashMap::new();
256        for message in history {
257            if message.role == MessageRole::Assistant {
258                pending.clear();
259                for call in message.tool_calls.iter().flatten() {
260                    if let Some(function) = &call.function
261                        && let Ok(args) = serde_json::from_str::<Value>(&function.arguments)
262                    {
263                        pending.insert(call.id.as_str(), RestoredToolCall { name: function.name.as_str(), args });
264                    }
265                }
266            } else if message.role == MessageRole::Tool
267                && let Some(call) = message.tool_call_id.as_deref().and_then(|id| pending.remove(id))
268                && let Ok(output) = serde_json::from_str::<Value>(message.content.as_text().as_ref())
269            {
270                if self.tracker_adopted_for_request() && call.name == tools::TASK_TRACKER {
271                    self.observe_required_completion_verifiers(&output);
272                }
273                if output.get("cleared").is_some() {
274                    self.observe_completion_mutation_from(
275                        call.name,
276                        &call.args,
277                        &serde_json::json!({"success":true,"exit_code":0}),
278                        MutationEvidenceSource::Restored,
279                    );
280                } else {
281                    self.observe_completion_mutation_from(
282                        call.name,
283                        &call.args,
284                        &output,
285                        MutationEvidenceSource::Restored,
286                    );
287                }
288            }
289        }
290    }
291
292    /// Code changes require an observed exit zero from the same mutation generation.
293    pub fn completion_verification_pending(&self) -> bool {
294        self.harness_context.completion_verification.lock().pending()
295    }
296
297    /// Monotonic identity of the code state used to reject stale completion drafts.
298    pub fn completion_mutation_generation(&self) -> u64 {
299        self.harness_context.completion_verification.lock().generation
300    }
301
302    pub(super) fn observe_required_completion_verifiers(&self, output: &Value) {
303        let Some(items) = output
304            .get("checklist")
305            .and_then(|checklist| checklist.get("items"))
306            .and_then(Value::as_array)
307        else {
308            return;
309        };
310        let mut commands = Vec::new();
311        for command in items
312            .iter()
313            .filter_map(|item| item.get("verify"))
314            .filter_map(Value::as_array)
315            .flatten()
316            .filter_map(Value::as_str)
317        {
318            let command = command.trim();
319            if !command.is_empty() && !commands.iter().any(|existing| existing == command) {
320                commands.push(command.to_owned());
321            }
322        }
323        self.set_required_completion_verifiers(commands);
324    }
325
326    /// Existing tracker verification commands are mandatory, even when another check passes.
327    pub(super) fn set_required_completion_verifiers(&self, commands: Vec<String>) {
328        // Store executable identities: a code-span-wrapped literal can never
329        // match the bare executed command and is itself rejected by preflight
330        // (code spans are command substitution), deadlocking the gate.
331        let mut normalized = Vec::with_capacity(commands.len());
332        for command in commands {
333            let command = unwrap_verify_code_span(&command).to_owned();
334            if !command.is_empty() && !normalized.contains(&command) {
335                normalized.push(command);
336            }
337        }
338        let mut state = self.harness_context.completion_verification.lock();
339        state.required_commands = normalized;
340        state.prune_optional_evidence();
341    }
342
343    pub fn completion_verifier_passed(&self, command: &str) -> bool {
344        self.harness_context.completion_verification.lock().command_passed(command)
345    }
346
347    pub(crate) fn missing_required_completion_verifiers(&self) -> Vec<String> {
348        let state = self.harness_context.completion_verification.lock();
349        state
350            .required_commands
351            .iter()
352            .filter(|command| !state.command_passed(command))
353            .cloned()
354            .collect()
355    }
356
357    /// Resume a current-generation verifier covering the requested check.
358    pub fn pending_completion_verifier_session(&self, command: &str) -> Option<String> {
359        let command = executed_command_identity(command);
360        let state = self.harness_context.completion_verification.lock();
361        state
362            .evidence
363            .iter()
364            .rev()
365            .find(|entry| command_covers_required(&entry.command, &command) && entry.generation == state.generation)
366            .and_then(|entry| entry.session_id.clone())
367    }
368
369    pub fn next_required_completion_verifier(&self) -> Option<String> {
370        let state = self.harness_context.completion_verification.lock();
371        state
372            .required_commands
373            .iter()
374            .find(|command| !state.command_passed(command))
375            .cloned()
376    }
377
378    /// Restore conservatively: historical success cannot establish fresh runtime evidence.
379    /// Call once when restoring a session with recorded code changes or verification debt.
380    pub fn restore_completion_verification_debt(&self) {
381        let mut state = self.harness_context.completion_verification.lock();
382        if state.generation == 0 {
383            state.mutate();
384        }
385    }
386
387    pub fn unverified_completion_reason(&self) -> String {
388        let state = self.harness_context.completion_verification.lock();
389        let evidence = state
390            .evidence
391            .back()
392            .map(|entry| {
393                format!(
394                    " Last command: `{}`; terminal exit: {:?}; launch generation: {}; current generation: {}.",
395                    entry.command, entry.exit_code, entry.generation, state.generation
396                )
397            })
398            .unwrap_or_else(|| " No terminal verifier evidence was observed.".to_string());
399        let remaining = state.required_commands.iter().find(|command| !state.command_passed(command));
400        let required = remaining.map_or_else(String::new, |command| {
401            let preview = vtcode_commons::formatting::truncate_within(command, 1024, "...");
402            format!(
403                " Next required tracker check: `{preview}`. Run this exact command; a different passing check does not satisfy it."
404            )
405        });
406        format!(
407            "Verification is still pending: Unverified: changed code requires fresh verification before successful completion.{evidence}{required}"
408        )
409    }
410
411    pub(super) fn begin_completion_verifier(&self, args: &Value) -> Option<u64> {
412        let command = self.completion_verifier_command(args)?;
413        Some(self.harness_context.completion_verification.lock().launch(command))
414    }
415
416    /// Share verifier accounting with the pacing gate; this grants no execution permission.
417    pub fn is_completion_verifier_call(&self, name: &str, args: &Value) -> bool {
418        tool_intent::is_command_tool(crate::tools::names::canonical_tool_name(name))
419            && self.completion_verifier_command(args).is_some()
420    }
421
422    fn completion_verifier_command(&self, args: &Value) -> Option<String> {
423        let executed = tool_intent::shell_args_as_executed(tools::UNIFIED_EXEC, args);
424        let command = command_args::raw_command_text(&executed)?.trim().to_owned();
425        // A declared repair action still invalidates verification. Inspect all
426        // static segments so a harmless prefix cannot hide a source rewrite.
427        if tool_intent::readonly::static_shell_command_words(&command)
428            .or_else(|| tool_intent::readonly::static_shell_command_words_with_output_plumbing(&command))
429            .is_some_and(|segments| segments.iter().any(|words| command_args::command_uses_source_repair(words)))
430        {
431            return None;
432        }
433        if tool_intent::classify_shell_activity(tools::UNIFIED_EXEC, &executed)
434            != tool_intent::ShellActivity::Verification
435            && !self.harness_context.completion_verification.lock().requires_command(&command)
436        {
437            return None;
438        }
439        let cwd = self
440            .pty_manager()
441            .working_dir_candidate(command_args::working_dir_text(args))
442            .ok()?;
443        if cwd != *self.workspace_root() {
444            return None;
445        }
446        // Empty argv/environment containers are native adapter defaults. Effective
447        // launch context cannot be dropped from a command-only verifier identity.
448        if args
449            .get("args")
450            .is_some_and(|value| !matches!(value, Value::Array(args) if args.is_empty()))
451            || args.get("env").is_some_and(|value| match value {
452                Value::Array(entries) => !entries.is_empty(),
453                Value::Object(env) => !env.is_empty(),
454                _ => true,
455            })
456            || ["shell", "login", "stdin"].iter().any(|key| args.get(key).is_some())
457        {
458            return None;
459        }
460        Some(command)
461    }
462
463    pub(super) fn observe_completion_verifier(
464        &self,
465        launch: Option<u64>,
466        args: &Value,
467        result: &anyhow::Result<Value>,
468    ) {
469        if let Ok(output) = result
470            && output.get("exit_code").and_then(Value::as_i64).is_some()
471            && output.get("error").is_none()
472            && output.get("cancelled").and_then(Value::as_bool) != Some(true)
473            && let Some(session_id) =
474                command_args::session_id_text(output).or_else(|| command_args::session_id_text(args))
475        {
476            self.harness_context.terminal_exec_results.lock().insert(session_id.to_owned());
477        }
478        let mut state = self.harness_context.completion_verification.lock();
479        if let Some(session_id) = command_args::session_id_text(args)
480            && state.pending_mutation_sessions.contains(session_id)
481            && result.as_ref().is_ok_and(|output| {
482                !command_args::session_id_text(output).is_some_and(|returned| returned != session_id)
483                    && (output.get("exit_code").and_then(Value::as_i64).is_some()
484                        || (is_session_cleanup(args)
485                            && output.get("error").is_none()
486                            && output.get("success").and_then(Value::as_bool) != Some(false)))
487            })
488        {
489            state.pending_mutation_sessions.remove(session_id);
490            // A check run while a mutator was active cannot verify its final output.
491            state.mutate();
492        }
493        let identity = launch.or_else(|| {
494            let session_id = command_args::session_id_text(args)?;
495            if tool_intent::classify_tool_intent(tools::UNIFIED_EXEC, args).mutating && !is_session_cleanup(args) {
496                return None;
497            }
498            state
499                .evidence
500                .iter()
501                .rev()
502                .find(|entry| entry.session_id.as_deref() == Some(session_id))
503                .map(|entry| entry.identity)
504        });
505        let Some(identity) = identity else {
506            return;
507        };
508        match result {
509            Ok(output) if !is_session_cleanup(args) => state.observe(identity, output),
510            _ => {
511                // Lost, denied, cancelled, or cleaned-up sessions carry no verdict.
512                if let Some(entry) = state.evidence.iter_mut().find(|entry| entry.identity == identity) {
513                    entry.session_id = None;
514                    entry.exit_code = None;
515                }
516                state.prune_optional_evidence();
517            }
518        }
519    }
520
521    pub(super) fn observe_completion_mutation(&self, name: &str, args: &Value, output: &Value) {
522        self.observe_completion_mutation_from(name, args, output, MutationEvidenceSource::Live);
523    }
524
525    /// Retire verification bookkeeping for exec sessions removed by bulk
526    /// cleanup paths (`terminate_*_exec_sessions_async`, TUI force-cancel)
527    /// that bypass per-call observation. Without this, a terminated mutating
528    /// session stays in `pending_mutation_sessions` forever and every later
529    /// turn reports unverified completion even after fresh checks pass.
530    /// Reuses the single-session cleanup contract (retire the pending boundary
531    /// and any live verifier handle); unknown or still-live ids are harmless
532    /// no-ops. Callers must pass only sessions that are actually gone so a
533    /// live mutator is never released early.
534    pub(super) fn observe_completion_exec_sessions_terminated(&self, session_ids: &[String]) {
535        for session_id in session_ids {
536            let args = serde_json::json!({"action":"close", "session_id":session_id});
537            let result: anyhow::Result<Value> = Ok(serde_json::json!({"success":true}));
538            self.observe_completion_verifier(None, &args, &result);
539        }
540    }
541
542    fn observe_completion_mutation_from(
543        &self,
544        name: &str,
545        args: &Value,
546        output: &Value,
547        source: MutationEvidenceSource,
548    ) {
549        let name = crate::tools::names::canonical_tool_name(name);
550        // Mutation intent also covers coordination and metadata tools. Only
551        // workspace writes, shell mutations, or explicit changed paths incur code debt.
552        if !tool_intent::is_command_tool(name)
553            && !tool_intent::is_edited_file_conflict_guarded_call(name, args)
554            && !matches!(
555                name,
556                tools::DELETE_FILE | tools::MOVE_FILE | tools::COPY_FILE | tools::SEARCH_REPLACE | tools::UNIFIED_FILE
557            )
558            && !output
559                .get("modified_files")
560                .and_then(Value::as_array)
561                .is_some_and(|files| !files.is_empty())
562        {
563            return;
564        }
565        let exec_changed = tool_intent::is_command_tool(name) && tool_intent::activity::exec_output_has_changes(output);
566        if !exec_changed
567            && (mutation_targets_are_exempt(name, args, output)
568                || !tool_intent::classify_tool_intent(name, args).mutating
569                || output.get("error").is_some()
570                || output.get("success").and_then(Value::as_bool) == Some(false)
571                || ["blocked", "not_executed", "cancelled"]
572                    .iter()
573                    .any(|key| output.get(key).and_then(Value::as_bool) == Some(true)))
574        {
575            return;
576        }
577        if tool_intent::is_command_tool(name) && !exec_changed {
578            let executed = tool_intent::shell_args_as_executed(name, args);
579            if tool_intent::classify_shell_activity(name, &executed) != tool_intent::ShellActivity::Mutation
580                || tool_intent::shell_command_is_admitted_verification_attempt(&executed)
581                // Declared checks use the same eligibility rules as verifier launch.
582                // This affects accounting only; execution admission remains authoritative.
583                || self.completion_verifier_command(args).is_some()
584                || (output.get("exit_code").and_then(Value::as_i64) != Some(0)
585                    && command_args::session_id_text(output).is_none())
586            {
587                return;
588            }
589            // Dynamic inspections need a complete nonmutation proof before
590            // they may preserve prior verifier evidence. Admission is unchanged.
591            if let Some(command_text) = command_args::raw_command_text(&executed)
592                .or_else(|| command_args::shell_command_text_with_args(&executed))
593                && !tool_intent::activity::exec_mutation_should_incur_debt(&command_text, output)
594            {
595                return;
596            }
597        }
598        match crate::tools::file_ops::diff_output_has_effective_change(output) {
599            Some(false) if !exec_changed => return,
600            Some(false) | Some(true) => {}
601            None if output.get("success").and_then(Value::as_bool) != Some(true)
602                && output.get("exit_code").and_then(Value::as_i64) != Some(0)
603                && command_args::session_id_text(output).is_none()
604                && !output
605                    .get("modified_files")
606                    .and_then(Value::as_array)
607                    .is_some_and(|files| !files.is_empty()) =>
608            {
609                return;
610            }
611            None => {}
612        }
613        let mut state = self.harness_context.completion_verification.lock();
614        state.mutate();
615        if matches!(source, MutationEvidenceSource::Live)
616            && tool_intent::is_command_tool(name)
617            && output.get("exit_code").and_then(Value::as_i64).is_none()
618            && let Some(session_id) = command_args::session_id_text(output)
619        {
620            state.pending_mutation_sessions.insert(session_id.to_owned());
621        }
622    }
623}
624
625#[cfg(test)]
626mod tests;