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    pub(super) fn observe_required_completion_verifiers(&self, output: &Value) {
298        let Some(items) = output
299            .get("checklist")
300            .and_then(|checklist| checklist.get("items"))
301            .and_then(Value::as_array)
302        else {
303            return;
304        };
305        let mut commands = Vec::new();
306        for command in items
307            .iter()
308            .filter_map(|item| item.get("verify"))
309            .filter_map(Value::as_array)
310            .flatten()
311            .filter_map(Value::as_str)
312        {
313            let command = command.trim();
314            if !command.is_empty() && !commands.iter().any(|existing| existing == command) {
315                commands.push(command.to_owned());
316            }
317        }
318        self.set_required_completion_verifiers(commands);
319    }
320
321    /// Existing tracker verification commands are mandatory, even when another check passes.
322    pub(super) fn set_required_completion_verifiers(&self, commands: Vec<String>) {
323        // Store executable identities: a code-span-wrapped literal can never
324        // match the bare executed command and is itself rejected by preflight
325        // (code spans are command substitution), deadlocking the gate.
326        let mut normalized = Vec::with_capacity(commands.len());
327        for command in commands {
328            let command = unwrap_verify_code_span(&command).to_owned();
329            if !command.is_empty() && !normalized.contains(&command) {
330                normalized.push(command);
331            }
332        }
333        let mut state = self.harness_context.completion_verification.lock();
334        state.required_commands = normalized;
335        state.prune_optional_evidence();
336    }
337
338    pub fn completion_verifier_passed(&self, command: &str) -> bool {
339        self.harness_context.completion_verification.lock().command_passed(command)
340    }
341
342    pub(crate) fn missing_required_completion_verifiers(&self) -> Vec<String> {
343        let state = self.harness_context.completion_verification.lock();
344        state
345            .required_commands
346            .iter()
347            .filter(|command| !state.command_passed(command))
348            .cloned()
349            .collect()
350    }
351
352    /// Resume a current-generation verifier covering the requested check.
353    pub fn pending_completion_verifier_session(&self, command: &str) -> Option<String> {
354        let command = executed_command_identity(command);
355        let state = self.harness_context.completion_verification.lock();
356        state
357            .evidence
358            .iter()
359            .rev()
360            .find(|entry| command_covers_required(&entry.command, &command) && entry.generation == state.generation)
361            .and_then(|entry| entry.session_id.clone())
362    }
363
364    pub fn next_required_completion_verifier(&self) -> Option<String> {
365        let state = self.harness_context.completion_verification.lock();
366        state
367            .required_commands
368            .iter()
369            .find(|command| !state.command_passed(command))
370            .cloned()
371    }
372
373    /// Restore conservatively: historical success cannot establish fresh runtime evidence.
374    /// Call once when restoring a session with recorded code changes or verification debt.
375    pub fn restore_completion_verification_debt(&self) {
376        let mut state = self.harness_context.completion_verification.lock();
377        if state.generation == 0 {
378            state.mutate();
379        }
380    }
381
382    pub fn unverified_completion_reason(&self) -> String {
383        let state = self.harness_context.completion_verification.lock();
384        let evidence = state
385            .evidence
386            .back()
387            .map(|entry| {
388                format!(
389                    " Last command: `{}`; terminal exit: {:?}; launch generation: {}; current generation: {}.",
390                    entry.command, entry.exit_code, entry.generation, state.generation
391                )
392            })
393            .unwrap_or_else(|| " No terminal verifier evidence was observed.".to_string());
394        let remaining = state.required_commands.iter().find(|command| !state.command_passed(command));
395        let required = remaining.map_or_else(String::new, |command| {
396            let preview = vtcode_commons::formatting::truncate_within(command, 1024, "...");
397            format!(
398                " Next required tracker check: `{preview}`. Run this exact command; a different passing check does not satisfy it."
399            )
400        });
401        format!(
402            "Verification is still pending: Unverified: changed code requires fresh verification before successful completion.{evidence}{required}"
403        )
404    }
405
406    pub(super) fn begin_completion_verifier(&self, args: &Value) -> Option<u64> {
407        let command = self.completion_verifier_command(args)?;
408        Some(self.harness_context.completion_verification.lock().launch(command))
409    }
410
411    /// Share verifier accounting with the pacing gate; this grants no execution permission.
412    pub fn is_completion_verifier_call(&self, name: &str, args: &Value) -> bool {
413        tool_intent::is_command_tool(crate::tools::names::canonical_tool_name(name))
414            && self.completion_verifier_command(args).is_some()
415    }
416
417    fn completion_verifier_command(&self, args: &Value) -> Option<String> {
418        let executed = tool_intent::shell_args_as_executed(tools::UNIFIED_EXEC, args);
419        let command = command_args::raw_command_text(&executed)?.trim().to_owned();
420        // A declared repair action still invalidates verification. Inspect all
421        // static segments so a harmless prefix cannot hide a source rewrite.
422        if tool_intent::readonly::static_shell_command_words(&command)
423            .or_else(|| tool_intent::readonly::static_shell_command_words_with_output_plumbing(&command))
424            .is_some_and(|segments| segments.iter().any(|words| command_args::command_uses_source_repair(words)))
425        {
426            return None;
427        }
428        if tool_intent::classify_shell_activity(tools::UNIFIED_EXEC, &executed)
429            != tool_intent::ShellActivity::Verification
430            && !self.harness_context.completion_verification.lock().requires_command(&command)
431        {
432            return None;
433        }
434        let cwd = self
435            .pty_manager()
436            .working_dir_candidate(command_args::working_dir_text(args))
437            .ok()?;
438        if cwd != *self.workspace_root() {
439            return None;
440        }
441        // Empty argv/environment containers are native adapter defaults. Effective
442        // launch context cannot be dropped from a command-only verifier identity.
443        if args
444            .get("args")
445            .is_some_and(|value| !matches!(value, Value::Array(args) if args.is_empty()))
446            || args.get("env").is_some_and(|value| match value {
447                Value::Array(entries) => !entries.is_empty(),
448                Value::Object(env) => !env.is_empty(),
449                _ => true,
450            })
451            || ["shell", "login", "stdin"].iter().any(|key| args.get(key).is_some())
452        {
453            return None;
454        }
455        Some(command)
456    }
457
458    pub(super) fn observe_completion_verifier(
459        &self,
460        launch: Option<u64>,
461        args: &Value,
462        result: &anyhow::Result<Value>,
463    ) {
464        if let Ok(output) = result
465            && output.get("exit_code").and_then(Value::as_i64).is_some()
466            && output.get("error").is_none()
467            && output.get("cancelled").and_then(Value::as_bool) != Some(true)
468            && let Some(session_id) =
469                command_args::session_id_text(output).or_else(|| command_args::session_id_text(args))
470        {
471            self.harness_context.terminal_exec_results.lock().insert(session_id.to_owned());
472        }
473        let mut state = self.harness_context.completion_verification.lock();
474        if let Some(session_id) = command_args::session_id_text(args)
475            && state.pending_mutation_sessions.contains(session_id)
476            && result.as_ref().is_ok_and(|output| {
477                !command_args::session_id_text(output).is_some_and(|returned| returned != session_id)
478                    && (output.get("exit_code").and_then(Value::as_i64).is_some()
479                        || (is_session_cleanup(args)
480                            && output.get("error").is_none()
481                            && output.get("success").and_then(Value::as_bool) != Some(false)))
482            })
483        {
484            state.pending_mutation_sessions.remove(session_id);
485            // A check run while a mutator was active cannot verify its final output.
486            state.mutate();
487        }
488        let identity = launch.or_else(|| {
489            let session_id = command_args::session_id_text(args)?;
490            if tool_intent::classify_tool_intent(tools::UNIFIED_EXEC, args).mutating && !is_session_cleanup(args) {
491                return None;
492            }
493            state
494                .evidence
495                .iter()
496                .rev()
497                .find(|entry| entry.session_id.as_deref() == Some(session_id))
498                .map(|entry| entry.identity)
499        });
500        let Some(identity) = identity else {
501            return;
502        };
503        match result {
504            Ok(output) if !is_session_cleanup(args) => state.observe(identity, output),
505            _ => {
506                // Lost, denied, cancelled, or cleaned-up sessions carry no verdict.
507                if let Some(entry) = state.evidence.iter_mut().find(|entry| entry.identity == identity) {
508                    entry.session_id = None;
509                    entry.exit_code = None;
510                }
511                state.prune_optional_evidence();
512            }
513        }
514    }
515
516    pub(super) fn observe_completion_mutation(&self, name: &str, args: &Value, output: &Value) {
517        self.observe_completion_mutation_from(name, args, output, MutationEvidenceSource::Live);
518    }
519
520    /// Retire verification bookkeeping for exec sessions removed by bulk
521    /// cleanup paths (`terminate_*_exec_sessions_async`, TUI force-cancel)
522    /// that bypass per-call observation. Without this, a terminated mutating
523    /// session stays in `pending_mutation_sessions` forever and every later
524    /// turn reports unverified completion even after fresh checks pass.
525    /// Reuses the single-session cleanup contract (retire the pending boundary
526    /// and any live verifier handle); unknown or still-live ids are harmless
527    /// no-ops. Callers must pass only sessions that are actually gone so a
528    /// live mutator is never released early.
529    pub(super) fn observe_completion_exec_sessions_terminated(&self, session_ids: &[String]) {
530        for session_id in session_ids {
531            let args = serde_json::json!({"action":"close", "session_id":session_id});
532            let result: anyhow::Result<Value> = Ok(serde_json::json!({"success":true}));
533            self.observe_completion_verifier(None, &args, &result);
534        }
535    }
536
537    fn observe_completion_mutation_from(
538        &self,
539        name: &str,
540        args: &Value,
541        output: &Value,
542        source: MutationEvidenceSource,
543    ) {
544        let name = crate::tools::names::canonical_tool_name(name);
545        // Mutation intent also covers coordination and metadata tools. Only
546        // workspace writes, shell mutations, or explicit changed paths incur code debt.
547        if !tool_intent::is_command_tool(name)
548            && !tool_intent::is_edited_file_conflict_guarded_call(name, args)
549            && !matches!(
550                name,
551                tools::DELETE_FILE | tools::MOVE_FILE | tools::COPY_FILE | tools::SEARCH_REPLACE | tools::UNIFIED_FILE
552            )
553            && !output
554                .get("modified_files")
555                .and_then(Value::as_array)
556                .is_some_and(|files| !files.is_empty())
557        {
558            return;
559        }
560        let exec_changed = tool_intent::is_command_tool(name) && tool_intent::activity::exec_output_has_changes(output);
561        if !exec_changed
562            && (mutation_targets_are_exempt(name, args, output)
563                || !tool_intent::classify_tool_intent(name, args).mutating
564                || output.get("error").is_some()
565                || output.get("success").and_then(Value::as_bool) == Some(false)
566                || ["blocked", "not_executed", "cancelled"]
567                    .iter()
568                    .any(|key| output.get(key).and_then(Value::as_bool) == Some(true)))
569        {
570            return;
571        }
572        if tool_intent::is_command_tool(name) && !exec_changed {
573            let executed = tool_intent::shell_args_as_executed(name, args);
574            if tool_intent::classify_shell_activity(name, &executed) != tool_intent::ShellActivity::Mutation
575                || tool_intent::shell_command_is_admitted_verification_attempt(&executed)
576                // Declared checks use the same eligibility rules as verifier launch.
577                // This affects accounting only; execution admission remains authoritative.
578                || self.completion_verifier_command(args).is_some()
579                || (output.get("exit_code").and_then(Value::as_i64) != Some(0)
580                    && command_args::session_id_text(output).is_none())
581            {
582                return;
583            }
584            // Dynamic inspections need a complete nonmutation proof before
585            // they may preserve prior verifier evidence. Admission is unchanged.
586            if let Some(command_text) = command_args::raw_command_text(&executed)
587                .or_else(|| command_args::shell_command_text_with_args(&executed))
588                && !tool_intent::activity::exec_mutation_should_incur_debt(&command_text, output)
589            {
590                return;
591            }
592        }
593        match crate::tools::file_ops::diff_output_has_effective_change(output) {
594            Some(false) if !exec_changed => return,
595            Some(false) | Some(true) => {}
596            None if output.get("success").and_then(Value::as_bool) != Some(true)
597                && output.get("exit_code").and_then(Value::as_i64) != Some(0)
598                && command_args::session_id_text(output).is_none()
599                && !output
600                    .get("modified_files")
601                    .and_then(Value::as_array)
602                    .is_some_and(|files| !files.is_empty()) =>
603            {
604                return;
605            }
606            None => {}
607        }
608        let mut state = self.harness_context.completion_verification.lock();
609        state.mutate();
610        if matches!(source, MutationEvidenceSource::Live)
611            && tool_intent::is_command_tool(name)
612            && output.get("exit_code").and_then(Value::as_i64).is_none()
613            && let Some(session_id) = command_args::session_id_text(output)
614        {
615            state.pending_mutation_sessions.insert(session_id.to_owned());
616        }
617    }
618}
619
620#[cfg(test)]
621mod tests;