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