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