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