Skip to main content

gate4agent_shell_native/
lib.rs

1//! Native effect execution for gate4agent control-plane sessions.
2
3mod efficiency;
4mod provider_supervisor;
5
6pub use efficiency::ShellEfficiencyFacts;
7// Re-exported so a caller of `ShellEfficiencyFacts::record_foreground_probe`
8// (e.g. `gate4agent-runtime-native`, which does not itself depend on the
9// `gate4agent` crate) can name the type of the value it is handing in
10// without picking up a new dependency edge for it.
11pub use gate4agent::pty::ForegroundProbeTiming;
12pub use provider_supervisor::{
13    NativeProviderExecutor, NativeProviderExit, NativeProviderOperation,
14    NativeProviderOperationError, NativeProviderResultPoll, PhysicalExitAck,
15    ProviderOperationKey, ProviderOperationSnapshot, ProviderSupervisor,
16    ProviderSupervisorBuildError, ProviderSupervisorFault, ProviderSupervisorFaultKind,
17    ProviderStopCause, ProviderSupervisorSnapshot, ProviderSupervisorState,
18    ProviderSupervisorTick, DEFAULT_PROVIDER_STOP_GRACE,
19    MAX_PROVIDER_FORCE_STOP_ATTEMPTS, MAX_PROVIDER_STOP_SIGNAL_ATTEMPTS,
20    MAX_PROVIDER_SUPERVISOR_EVENTS, MAX_PROVIDER_SUPERVISOR_OPERATIONS,
21    MAX_PROVIDER_SUPERVISOR_OUTCOMES_PER_TICK, MAX_PROVIDER_SUPERVISOR_TOMBSTONES,
22    MAX_PROVIDER_SUPERVISOR_WORK_PER_TICK,
23};
24
25use gate4agent::acp::protocol::{McpServerConfig, SessionMode};
26use gate4agent::agent::{is_agent_foreground_wrapper, is_expected_agent_process, ReadinessStatus};
27use gate4agent::pty::cli::codex::strip_ansi_codes;
28use gate4agent::pty::cli::{create_pipeline, ClassificationPipeline, MessageClass, ParsedMessage};
29use gate4agent::pty::event::PtyMouseProtocolEncoding;
30use gate4agent::pty::{
31    PtyAttachment, PtyEvent, PtyEventEnvelope, PtyEventReceiver, PtyForegroundObservation,
32    PtyReplayCursor, PtySession, PtyTerminalSnapshot, RateLimitDetector, VteParser,
33};
34use gate4agent::{
35    AcpSession, AcpSessionOptions, AgentEvent, CliTool, HostDecisionAuthority, HostPolicy,
36    HostRequestDecision, HostRequestOutcome, LaunchRequest, OperatorPermissionChoice,
37    PipeProcessOptions, PipeSession, PromptFraming,
38    ReadinessIntent, ReadinessPermit, ReadinessTracker, RpcId, RuntimePlatform, SessionConfig,
39    StopReason,
40};
41use gate4agent_adapters::{
42    build_resume_plan_for_identity, builtin_adapter_registry, AdapterRuntimeRegistry,
43    CodexPtySessionIdentityExtractor, KimiPtySessionIdentityExtractor, OneShotSessionPersistence,
44};
45use gate4agent_catalog::{
46    approval_level_resolution, ApprovalLevelResolution, AgentRegistry, AgentSpec, EnvMutation,
47    McpServerSpec, ModeId,
48};
49use gate4agent_shell_one_shot::NativeOneShotSession;
50use gate4agent_types::{
51    AdapterFamily, AgentCommand, AgentId, AgentInstanceId, ApprovalLevel, CapabilityProbeFailure,
52    ContextWindowUsage as ProviderContextWindowUsage, ControlEffect,
53    ControlObservation, EffectEnvelope, ForegroundProcess, ForegroundProcessKind,
54    ForegroundRequirement, HostDecisionAuthority as ProviderHostDecisionAuthority,
55    HostRequestDecision as ProviderHostRequestDecision,
56    HostRequestOutcome as ProviderHostRequestOutcome, InputAction, ObservationEnvelope,
57    OperationId, OperatorGateInput,
58    OperatorGateKind, OperatorGateOption, OperatorGateOptionSemantics, OperatorGateState,
59    OperatorGateSubject, PipeProtocol,
60    PreparedInputKind, PromptPayload, ProviderAvailableCommand, ProviderConfigChoice,
61    ProviderConfigOption, ProviderConfigOptionKind, ProviderEvent, ProviderInteractionKind,
62    ProviderInteractionOption, ProviderInteractionResponse, ProviderInteractionTarget,
63    ProviderModeInfo, ProviderPlanPriority,
64    ProviderPlanStatus, ProviderPlanStep,
65    ProviderRateLimitKind, ProviderRuntimeCapability, ProviderRuntimePolicy,
66    ProviderSessionIdentity, ProviderSessionKey, ProviderStopReason,
67    ProviderSource, PtyScreenState, ResumeLaunchRequest, SessionGeneration, StartRequest,
68    TerminalFrame, TerminalMouseProtocolEncoding, TerminalSize, TokenUsage, TransportKind,
69    OPERATOR_GATE_OPTIONS_MAX, WORKING_DIRECTORY_MAX_BYTES,
70};
71use std::collections::{BTreeMap, VecDeque};
72use std::ffi::{OsStr, OsString};
73use std::path::PathBuf;
74use std::sync::Mutex;
75use std::time::{Duration, Instant};
76use tokio::sync::broadcast;
77use uuid::Uuid;
78
79const INSTANCE_LAUNCH_ARGS_MAX: usize = 128;
80const INSTANCE_LAUNCH_ARG_MAX_BYTES: usize = 65_536;
81const INSTANCE_LAUNCH_ARGS_TOTAL_MAX_BYTES: usize = 262_144;
82const RESERVED_CLAUDE_LAUNCH_FLAGS: &[&str] = &[
83    "--continue",
84    "--print",
85    "--prompt",
86    "--prompt-interactive",
87    "--resume",
88    "--session-id",
89    "-c",
90    "-p",
91    "-r",
92];
93
94/// Translates a resolved [`McpServerSpec`] into the one ACP `session/new`
95/// stdio entry the agent should register
96/// (`gate4agent::acp::protocol::McpServerConfig`). This is the ACP half of
97/// the same door a PTY child gets by installing the identical spec's `env`
98/// pairs into its own OS environment instead
99/// (`gate4agent-runtime-native::launch_profiles::NativeMcpServerLaunchOverlay`):
100/// the spec is resolved once, in-process, by `gate4agent-runtime-native` and
101/// handed down here as a typed value through `NativeSpawnOverlay`/
102/// `NativeEffectRequest` -- never a wire type, and never re-read out of a
103/// well-known environment key. This crate cannot depend on
104/// `gate4agent-runtime-native` (the dependency runs the other way), which is
105/// why the spec type itself lives one level below both, in
106/// `gate4agent-catalog`.
107///
108/// Server naming, program path, args, and every environment entry are
109/// entirely the caller's concern; this function does not interpret them.
110fn mcp_server_acp_entry(spec: &McpServerSpec) -> McpServerConfig {
111    McpServerConfig::stdio(
112        spec.name().to_owned(),
113        spec.program().to_string_lossy().into_owned(),
114        spec.args()
115            .iter()
116            .map(|arg| arg.to_string_lossy().into_owned())
117            .collect::<Vec<_>>(),
118        spec.env()
119            .iter()
120            .map(|(key, value)| (key.to_string_lossy().into_owned(), value.to_string_lossy().into_owned()))
121            .collect::<Vec<_>>(),
122    )
123}
124
125#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
126pub struct NativeSessionKey {
127    pub instance_id: AgentInstanceId,
128    pub generation: SessionGeneration,
129}
130
131struct NativeSpawnRequest {
132    agent_id: AgentId,
133    transport: TransportKind,
134    request: StartRequest,
135    runtime_policy: ProviderRuntimePolicy,
136    launch_extra_args: Vec<OsString>,
137    instance_extra_args: Vec<OsString>,
138    resumed_provider_session: Option<gate4agent_types::ProviderSessionIdentity>,
139    one_shot_session_persistence: OneShotSessionPersistence,
140}
141
142struct OwnedPtySession {
143    session: PtySession,
144    spawn_operation_id: OperationId,
145    last_terminal_sequence: u64,
146    terminal_stale_published: bool,
147    runtime_policy: ProviderRuntimePolicy,
148    provider: Option<OwnedPtyProvider>,
149    /// Set once at the spawn site and never mutated -- this is what lets
150    /// `reclassify_foreground` resolve the session's `AgentSpec` from
151    /// `NativeEffectShell::catalog` without holding a borrow of `session`
152    /// across the same loop iteration it awaits `observe_foreground` on.
153    agent_id: AgentId,
154    last_screen_gate: Option<OperatorGateState>,
155    last_screen_failure: Option<&'static str>,
156    last_foreground_verdict: Option<ForegroundVerdict>,
157    last_screen_state: PtyScreenState,
158    /// Whether this generation's merged state has ever been `Ready` WITH
159    /// something on screen. Text crash/missing-command markers are only
160    /// trustworthy before this flips -- see the gate in
161    /// `collect_terminal_frames`. The screen-content half is load-bearing:
162    /// `Ready` is proved by foreground process identity and so arrives
163    /// within a frame or two of spawn, while the terminal is still blank,
164    /// and arming on a blank frame retires the failure detector before any
165    /// failure text can exist. Never reset in place; a new generation gets
166    /// a fresh `OwnedPtySession`, so `false` is simply this field's initial
167    /// value at the spawn site.
168    ever_reached_ready: bool,
169    /// Whether any frame of this generation has carried non-blank screen
170    /// text yet. Read by the process-only path in `reclassify_foreground`,
171    /// which has no snapshot of its own to test and would otherwise arm
172    /// `ever_reached_ready` on a blank screen.
173    screen_had_content: bool,
174    /// `None` means disarmed -- the session reached `Ready` and stays
175    /// unprobed until its text disagrees again. See
176    /// `NativeEffectShell::reclassify_foreground` for the cadence this
177    /// drives.
178    next_foreground_probe: Option<Instant>,
179}
180
181struct OwnedPtyProvider {
182    source: ProviderSource,
183    receiver: PtyEventReceiver,
184    replay: VecDeque<PtyEventEnvelope>,
185    pending_events: VecDeque<ProviderEvent>,
186    utf8: Utf8ChunkDecoder,
187    pipeline: Mutex<ClassificationPipeline>,
188    rate_limits: RateLimitFeed,
189    kimi_identity: Option<KimiPtySessionIdentityExtractor>,
190    semantic_events: bool,
191    provider_session_started: bool,
192    next_provider_sequence: u64,
193}
194
195/// Buffers ANSI-stripped PTY output across output chunks before running
196/// rate-limit detection over it.
197///
198/// PTY reads are chunked arbitrarily -- neither the OS nor this crate's
199/// own reader loop promises "one call per terminal row" or even "one call
200/// per escape sequence". Two separate problems follow from that, and this
201/// type exists to solve both rather than hoping a caller's chunk
202/// boundaries are ever polite:
203///
204/// - An ANSI escape sequence split across two chunks must still be
205///   recognized as one escape, not leak its tail bytes into the visible
206///   text as a false line-break in the middle of `\x1b[m`. `VteParser`
207///   already solves this -- its own `vte::Parser` state machine persists
208///   across calls, so an escape completes correctly regardless of where
209///   a chunk boundary falls -- this type just keeps ONE `VteParser` alive
210///   for the provider's whole lifetime instead of a fresh, stateless one
211///   per chunk (which would forget an escape's first half).
212/// - A LOGICAL LINE (e.g. codex's `/status` quota-state row) can itself
213///   be split across chunks at a point that is not inside any escape.
214///   `VteParser::parse` only returns the printable text produced by the
215///   bytes handed to THAT call, so two separate calls can each return one
216///   half of the same row, and neither half alone matches the quota-state
217///   pattern. This type accumulates cleaned text across calls and runs
218///   detection over everything seen so far, keeping whatever has not yet
219///   been confirmed complete (the tail after the last newline) instead of
220///   discarding a still-forming row.
221struct RateLimitFeed {
222    detector: RateLimitDetector,
223    vte: VteParser,
224    buffer: String,
225}
226
227impl RateLimitFeed {
228    fn new_for_tool(tool: CliTool) -> Self {
229        Self {
230            detector: RateLimitDetector::new_for_tool(tool),
231            vte: VteParser::new(),
232            buffer: String::new(),
233        }
234    }
235
236    /// Strip ANSI from one more raw PTY chunk, fold it into the pending
237    /// line buffer, and run detection over everything accumulated so far
238    /// -- not just the newest chunk, since a match can straddle a chunk
239    /// boundary. Lines already terminated by `\n` are then dropped from
240    /// the buffer regardless of whether they matched: a later chunk
241    /// cannot retroactively extend a row that has already ended. The
242    /// unterminated tail (a row still in progress) is always kept -- but
243    /// see `RATE_LIMIT_FEED_BUFFER_MAX_BYTES` for what happens when that
244    /// tail itself grows unreasonably large.
245    fn detect(&mut self, raw: &str) -> Option<gate4agent::core::types::RateLimitInfo> {
246        let cleaned = self.vte.parse(raw);
247        self.buffer.push_str(&cleaned);
248        let info = self.detector.detect(&self.buffer);
249        if let Some(last_newline) = self.buffer.rfind('\n') {
250            self.buffer.drain(..=last_newline);
251        } else if self.buffer.len() > RATE_LIMIT_FEED_BUFFER_MAX_BYTES {
252            // A full-screen redraw (codex's main screen, not `/status`)
253            // can run for a long time using only cursor-addressing escapes
254            // and never emit a `\n` at all, so "no newline yet" cannot be
255            // trusted to mean "a row is still in progress" indefinitely.
256            // No real quota-state or refusal line approaches this length;
257            // past it, keep only the tail so an indefinitely long redraw
258            // cannot grow this buffer for the life of the session.
259            let mut cut = self.buffer.len() - RATE_LIMIT_FEED_BUFFER_MAX_BYTES;
260            while !self.buffer.is_char_boundary(cut) {
261                cut += 1;
262            }
263            self.buffer.drain(..cut);
264        }
265        info
266    }
267}
268
269/// Well past the longest quota-state or refusal line this detector
270/// recognizes (all under 200 bytes); see `RateLimitFeed::detect`.
271const RATE_LIMIT_FEED_BUFFER_MAX_BYTES: usize = 8192;
272
273#[derive(Default)]
274struct Utf8ChunkDecoder {
275    pending: Vec<u8>,
276}
277
278impl Utf8ChunkDecoder {
279    fn push(&mut self, bytes: &[u8]) -> String {
280        self.pending.extend_from_slice(bytes);
281        let mut decoded = String::new();
282        loop {
283            match std::str::from_utf8(&self.pending) {
284                Ok(text) => {
285                    decoded.push_str(text);
286                    self.pending.clear();
287                    break;
288                }
289                Err(error) => {
290                    let valid = error.valid_up_to();
291                    if valid > 0 {
292                        let text = std::str::from_utf8(&self.pending[..valid])
293                            .expect("validated UTF-8 prefix");
294                        decoded.push_str(text);
295                        self.pending.drain(..valid);
296                        continue;
297                    }
298                    let Some(invalid) = error.error_len() else {
299                        break;
300                    };
301                    decoded.push('\u{fffd}');
302                    self.pending.drain(..invalid.min(self.pending.len()));
303                }
304            }
305        }
306        decoded
307    }
308
309    fn clear(&mut self) {
310        self.pending.clear();
311    }
312}
313
314struct OwnedProviderSession<S> {
315    source: ProviderSource,
316    session: S,
317    events: broadcast::Receiver<AgentEvent>,
318    pending_events: VecDeque<AgentEvent>,
319    /// Already wire-typed `ProviderEvent`s seeded at the spawn site with no
320    /// `AgentEvent` counterpart to carry them through `pending_events` --
321    /// today, only `ProviderEvent::SessionIdentityObserved` for a freshly
322    /// spawned ACP session (see the `TransportKind::Acp` arm of
323    /// `spawn_native`). Drained by `drain_provider_stream` immediately after
324    /// `pending_events` empties and before the live broadcast stream, so an
325    /// event seeded here lands right after whatever `pending_events` seeded
326    /// (`AgentEvent::SessionStart`, chiefly) rather than racing it.
327    pending_provider_events: VecDeque<ProviderEvent>,
328    next_provider_sequence: u64,
329    observed_exit_code: Option<i32>,
330    runtime_policy: ProviderRuntimePolicy,
331}
332
333/// Executes native effects and returns exactly one completion observation for
334/// each accepted effect. Logical lifecycle state remains owned by the engine.
335pub struct NativeEffectShell {
336    catalog: AgentRegistry,
337    legacy_adapters: AdapterRuntimeRegistry<CliTool>,
338    pty_sessions: BTreeMap<NativeSessionKey, OwnedPtySession>,
339    pipe_sessions: BTreeMap<NativeSessionKey, OwnedProviderSession<PipeSession>>,
340    one_shot_sessions: BTreeMap<NativeSessionKey, OwnedProviderSession<NativeOneShotSession>>,
341    acp_sessions: BTreeMap<NativeSessionKey, OwnedProviderSession<AcpSession>>,
342    pending_observations: VecDeque<ObservationEnvelope>,
343    /// Plain efficiency facts from `collect_terminal_frames` and
344    /// `reclassify_foreground` -- see `ShellEfficiencyFacts`'s own doc
345    /// comment for why this crate stops at plain facts rather than
346    /// computing a distribution itself.
347    efficiency_facts: ShellEfficiencyFacts,
348}
349
350impl NativeEffectShell {
351    pub fn new(catalog: AgentRegistry) -> Self {
352        Self::new_with_runtime_adapters(catalog, builtin_legacy_adapter_runtimes())
353    }
354
355    /// Builds a native shell with consumer-provided compatibility runtimes.
356    ///
357    /// The runtime registry is deliberately separate from the declarative
358    /// catalog: both the adapter family and revision must resolve before a
359    /// process is spawned.
360    pub fn new_with_runtime_adapters(
361        catalog: AgentRegistry,
362        legacy_adapters: AdapterRuntimeRegistry<CliTool>,
363    ) -> Self {
364        Self {
365            catalog,
366            legacy_adapters,
367            pty_sessions: BTreeMap::new(),
368            pipe_sessions: BTreeMap::new(),
369            one_shot_sessions: BTreeMap::new(),
370            acp_sessions: BTreeMap::new(),
371            pending_observations: VecDeque::new(),
372            efficiency_facts: ShellEfficiencyFacts::default(),
373        }
374    }
375
376    /// Hand the caller everything `collect_terminal_frames` and
377    /// `reclassify_foreground` recorded since the last call, and reset the
378    /// facts back to empty. Called once per worker-loop iteration by
379    /// `gate4agent-runtime-native::publish_shell_observations`, the only
380    /// place with somewhere to fold these into a distribution.
381    pub fn take_efficiency_facts(&mut self) -> ShellEfficiencyFacts {
382        self.efficiency_facts.take()
383    }
384
385    pub fn active_session_count(&self) -> usize {
386        self.pty_sessions.len()
387            + self.pipe_sessions.len()
388            + self.one_shot_sessions.len()
389            + self.acp_sessions.len()
390    }
391
392    pub fn spawn_operation_id(&self, key: NativeSessionKey) -> Option<OperationId> {
393        self.pty_sessions
394            .get(&key)
395            .map(|owned| owned.spawn_operation_id)
396    }
397
398    pub fn terminal_snapshot(&self, key: NativeSessionKey) -> Result<PtyTerminalSnapshot, String> {
399        self.pty_sessions
400            .get(&key)
401            .ok_or_else(|| missing_session_message(key))?
402            .session
403            .terminal_snapshot()
404            .map_err(|error| error.to_string())
405    }
406
407    pub async fn execute(&mut self, envelope: EffectEnvelope) -> ObservationEnvelope {
408        self.execute_with_environment(envelope, Vec::new()).await
409    }
410
411    /// Backward-compatible name for PTY-only callers. OneShot launches now
412    /// receive the same shell-owned mutations.
413    pub async fn execute_with_pty_env(
414        &mut self,
415        envelope: EffectEnvelope,
416        pty_env: Vec<EnvMutation>,
417    ) -> ObservationEnvelope {
418        self.execute_with_environment(envelope, pty_env).await
419    }
420
421    /// Execute an effect with shell-owned environment injected only into a
422    /// newly spawned provider process. The canonical start request cannot set
423    /// these authority variables itself.
424    pub async fn execute_with_environment(
425        &mut self,
426        envelope: EffectEnvelope,
427        environment: Vec<EnvMutation>,
428    ) -> ObservationEnvelope {
429        self.execute_with_launch_overlay(envelope, environment, Vec::new())
430            .await
431    }
432
433    /// Execute an effect with host-only environment and optional PTY argv
434    /// applied only to a newly spawned provider process.
435    pub async fn execute_with_launch_overlay(
436        &mut self,
437        envelope: EffectEnvelope,
438        environment: Vec<EnvMutation>,
439        extra_args: Vec<OsString>,
440    ) -> ObservationEnvelope {
441        self.execute_with_launch_overlay_and_persistence(
442            envelope,
443            environment,
444            extra_args,
445            OneShotSessionPersistence::Ephemeral,
446        )
447        .await
448    }
449
450    /// Execute an effect with host-only launch mutations and an explicit
451    /// OneShotText session persistence policy.
452    pub async fn execute_with_launch_overlay_and_persistence(
453        &mut self,
454        envelope: EffectEnvelope,
455        environment: Vec<EnvMutation>,
456        extra_args: Vec<OsString>,
457        one_shot_session_persistence: OneShotSessionPersistence,
458    ) -> ObservationEnvelope {
459        self.execute_with_launch_context(
460            envelope,
461            environment,
462            extra_args,
463            one_shot_session_persistence,
464            None,
465        )
466        .await
467    }
468
469    pub async fn execute_with_launch_context(
470        &mut self,
471        envelope: EffectEnvelope,
472        environment: Vec<EnvMutation>,
473        extra_args: Vec<OsString>,
474        one_shot_session_persistence: OneShotSessionPersistence,
475        mcp_server: Option<McpServerSpec>,
476    ) -> ObservationEnvelope {
477        let EffectEnvelope {
478            operation_id,
479            instance_id,
480            generation,
481            effect,
482        } = envelope;
483        let key = NativeSessionKey {
484            instance_id,
485            generation,
486        };
487
488        let observation = {
489            match effect {
490                ControlEffect::Spawn {
491                    agent_id,
492                    transport,
493                    runtime_policy,
494                    request,
495                } => {
496                    self.spawn_native(
497                        key,
498                        operation_id,
499                        NativeSpawnRequest {
500                            agent_id,
501                            transport,
502                            request,
503                            runtime_policy,
504                            launch_extra_args: Vec::new(),
505                            instance_extra_args: extra_args,
506                            resumed_provider_session: None,
507                            one_shot_session_persistence,
508                        },
509                        environment,
510                        mcp_server,
511                    )
512                    .await
513                }
514                ControlEffect::SpawnResume {
515                    agent_id,
516                    transport,
517                    provider_session,
518                    runtime_policy,
519                    request,
520                } => {
521                    self.spawn_resume(
522                        key,
523                        operation_id,
524                        agent_id,
525                        transport,
526                        provider_session,
527                        runtime_policy,
528                        request,
529                        environment,
530                        extra_args,
531                        one_shot_session_persistence,
532                        mcp_server,
533                    )
534                    .await
535                }
536                ControlEffect::Stop { force } => self.stop_native(key, force).await,
537                ControlEffect::WriteInput {
538                    input,
539                    required_foreground,
540                } => match self.pty_sessions.get(&key) {
541                    Some(owned) => match required_foreground {
542                        ForegroundRequirement::Any
543                            if matches!(
544                                input.kind(),
545                                PreparedInputKind::TerminalText
546                                    | PreparedInputKind::TerminalBytes
547                                    | PreparedInputKind::TerminalControl
548                            ) =>
549                        {
550                            match owned.session.send_terminal_input(input).await {
551                                Ok(()) => ControlObservation::InputCompleted,
552                                Err(error) => ControlObservation::InputFailed {
553                                    message: error.to_string(),
554                                },
555                            }
556                        }
557                        ForegroundRequirement::Shell
558                            if input.kind() == PreparedInputKind::ShellCommand =>
559                        {
560                            if !owned.runtime_policy.semantic_readiness {
561                                ControlObservation::InputFailed {
562                                    message: "semantic shell input is not admitted by the provider runtime policy"
563                                        .to_owned(),
564                                }
565                            } else {
566                                match owned.session.send_shell_input(input).await {
567                                    Ok(()) => ControlObservation::InputCompleted,
568                                    Err(error) => ControlObservation::InputFailed {
569                                        message: error.to_string(),
570                                    },
571                                }
572                            }
573                        }
574                        ForegroundRequirement::Agent { agent_id }
575                            if matches!(
576                                input.kind(),
577                                PreparedInputKind::InsertDraft
578                                    | PreparedInputKind::SubmitPrompt
579                                    | PreparedInputKind::AgentCommand
580                            ) && &agent_id == owned.session.agent_id() =>
581                        {
582                            if !owned.runtime_policy.semantic_readiness
583                                || !owned.runtime_policy.structured_prompt
584                            {
585                                return completion_observation(
586                                    operation_id,
587                                    instance_id,
588                                    generation,
589                                    ControlObservation::InputFailed {
590                                        message: "semantic input is not admitted by the provider runtime policy"
591                                            .to_owned(),
592                                    },
593                                );
594                            }
595                            let intent = match input.kind() {
596                                PreparedInputKind::InsertDraft
597                                | PreparedInputKind::AgentCommand => ReadinessIntent::DraftPaste,
598                                PreparedInputKind::SubmitPrompt => ReadinessIntent::FollowupPrompt,
599                                PreparedInputKind::ShellCommand
600                                | PreparedInputKind::TerminalText
601                                | PreparedInputKind::TerminalBytes
602                                | PreparedInputKind::TerminalControl => unreachable!(),
603                            };
604                            let Some(spec) = self.catalog.get(&agent_id).cloned() else {
605                                return completion_observation(
606                                    operation_id,
607                                    instance_id,
608                                    generation,
609                                    ControlObservation::InputFailed {
610                                        message: "session agent disappeared from native catalog"
611                                            .to_owned(),
612                                    },
613                                );
614                            };
615                            match wait_for_readiness(&owned.session, &spec, intent, false).await {
616                                Ok(permit) => {
617                                    let result = if input.kind() == PreparedInputKind::AgentCommand
618                                    {
619                                        owned.session.send_agent_command_input(input, permit).await
620                                    } else {
621                                        owned.session.send_prepared_input(input, permit).await
622                                    };
623                                    match result {
624                                        Ok(()) => ControlObservation::InputCompleted,
625                                        Err(error) => ControlObservation::InputFailed {
626                                            message: error.to_string(),
627                                        },
628                                    }
629                                }
630                                Err(message) => ControlObservation::InputFailed { message },
631                            }
632                        }
633                        required_foreground => ControlObservation::InputFailed {
634                            message: format!(
635                                "prepared input kind {:?} does not satisfy route {:?}",
636                                input.kind(),
637                                required_foreground
638                            ),
639                        },
640                    },
641                    None => ControlObservation::InputFailed {
642                        message: "typed PTY input requires a PTY session".to_owned(),
643                    },
644                },
645                ControlEffect::SubmitPrompt { prompt } => match self.acp_sessions.get(&key) {
646                    Some(owned) if !owned.runtime_policy.structured_prompt => {
647                        ControlObservation::InputFailed {
648                            message: "structured prompt is not admitted by the provider runtime policy"
649                                .to_owned(),
650                        }
651                    }
652                    Some(owned) => match owned.session.start_prompt(&prompt).await {
653                        Ok(()) => ControlObservation::InputCompleted,
654                        Err(error) => ControlObservation::InputFailed {
655                            message: error.to_string(),
656                        },
657                    },
658                    None => ControlObservation::InputFailed {
659                        message: "semantic follow-up prompts require an ACP session".to_owned(),
660                    },
661                },
662                ControlEffect::Interrupt => match self.acp_sessions.get(&key) {
663                    Some(owned) => match owned.session.cancel().await {
664                        Ok(()) => ControlObservation::InputCompleted,
665                        Err(error) => ControlObservation::InputFailed {
666                            message: error.to_string(),
667                        },
668                    },
669                    None => ControlObservation::InputFailed {
670                        message: "semantic interrupt requires an ACP session".to_owned(),
671                    },
672                },
673                ControlEffect::ResolveInteraction { target, response } => {
674                    resolve_acp_interaction_observation(
675                        self.acp_sessions.get(&key).map(|owned| &owned.session),
676                        target,
677                        response,
678                    )
679                }
680                ControlEffect::SetSessionMode { mode_id } => {
681                    set_acp_session_mode_observation(
682                        self.acp_sessions.get(&key).map(|owned| &owned.session),
683                        mode_id,
684                    )
685                    .await
686                }
687                ControlEffect::SetSessionConfigOption {
688                    option_id,
689                    value_json,
690                } => {
691                    set_acp_session_config_option_observation(
692                        self.acp_sessions.get(&key).map(|owned| &owned.session),
693                        option_id,
694                        value_json,
695                    )
696                    .await
697                }
698                ControlEffect::SetSessionModel { model_id } => {
699                    set_acp_session_model_observation(
700                        self.acp_sessions.get(&key).map(|owned| &owned.session),
701                        model_id,
702                    )
703                }
704                ControlEffect::Resize { size } if !size.is_valid() => {
705                    ControlObservation::ResizeFailed {
706                        message: "terminal size is outside the supported range".to_owned(),
707                    }
708                }
709                ControlEffect::Resize { size } => match self.pty_sessions.get(&key) {
710                    Some(owned) => match owned.session.resize(size.rows, size.columns).await {
711                        Ok(()) => ControlObservation::ResizeCompleted { size },
712                        Err(error) => ControlObservation::ResizeFailed {
713                            message: error.to_string(),
714                        },
715                    },
716                    None => ControlObservation::ResizeFailed {
717                        message: "terminal resize requires a PTY session".to_owned(),
718                    },
719                },
720                ControlEffect::ObserveForeground => match self.pty_sessions.get(&key) {
721                    Some(owned) => match owned.session.observe_foreground().await {
722                        Ok(observation) => ControlObservation::ForegroundObserved {
723                            process: canonical_foreground(
724                                owned.session.agent_id().clone(),
725                                &observation,
726                            ),
727                        },
728                        Err(error) => ControlObservation::ForegroundFailed {
729                            message: error.to_string(),
730                        },
731                    },
732                    None => ControlObservation::ForegroundFailed {
733                        message: "foreground observation requires a PTY session".to_owned(),
734                    },
735                },
736                ControlEffect::ProbeCapabilities { .. } => {
737                    ControlObservation::CapabilityProbeFailed {
738                        failure: CapabilityProbeFailure::ExecutorUnavailable,
739                    }
740                }
741                ControlEffect::DiscoverHistory { .. } | ControlEffect::LoadHistory { .. } => {
742                    ControlObservation::HistoryFailed {
743                        message: "history effects require the dedicated native history authority"
744                            .to_owned(),
745                    }
746                }
747                ControlEffect::AuthorizeResume { .. } => ControlObservation::ResumeFailed {
748                    message: "resume authorization requires the dedicated native authority"
749                        .to_owned(),
750                },
751            }
752        };
753
754        completion_observation(operation_id, instance_id, generation, observation)
755    }
756
757    async fn spawn_native(
758        &mut self,
759        key: NativeSessionKey,
760        operation_id: OperationId,
761        spawn: NativeSpawnRequest,
762        pty_env: Vec<EnvMutation>,
763        mcp_server: Option<McpServerSpec>,
764    ) -> ControlObservation {
765        let NativeSpawnRequest {
766            agent_id,
767            transport,
768            request,
769            runtime_policy,
770            mut launch_extra_args,
771            instance_extra_args,
772            resumed_provider_session,
773            one_shot_session_persistence,
774        } = spawn;
775        if let Err(message) =
776            validate_instance_launch_arguments(&agent_id, transport, &instance_extra_args)
777        {
778            return ControlObservation::SpawnFailed { message };
779        }
780        if let Err(message) = validate_spawn_runtime_policy(
781            runtime_policy,
782            transport,
783            request.initial_prompt.is_some(),
784            resumed_provider_session.is_some(),
785        ) {
786            return ControlObservation::SpawnFailed { message };
787        }
788        if self.session_exists(key) {
789            return ControlObservation::SpawnFailed {
790                message: format!(
791                    "native session {:?}/{:?} already exists",
792                    key.instance_id, key.generation
793                ),
794            };
795        }
796        if !request.terminal_size.is_valid() {
797            return ControlObservation::SpawnFailed {
798                message: "terminal size is outside the supported range".to_owned(),
799            };
800        }
801        if request.working_directory.is_empty()
802            || request.working_directory.len() > WORKING_DIRECTORY_MAX_BYTES
803            || request.working_directory.contains('\0')
804        {
805            return ControlObservation::SpawnFailed {
806                message: "working directory is invalid".to_owned(),
807            };
808        }
809        let Some(spec) = self.catalog.get(&agent_id).cloned() else {
810            return ControlObservation::SpawnFailed {
811                message: format!("agent '{agent_id}' is absent from native catalog"),
812            };
813        };
814        let working_dir = PathBuf::from(&request.working_directory);
815
816        match transport {
817            TransportKind::Pty if !spec.capabilities.transports.pty => {
818                ControlObservation::SpawnFailed {
819                    message: format!("agent '{agent_id}' does not support PTY transport"),
820                }
821            }
822            TransportKind::Pty => {
823                // Only the interactive PTY path renders anything to color;
824                // the Pipe/OneShotText arm below spawns a plain pipe with
825                // no terminal device behind it, so `pty_env` is left as the
826                // caller passed it there.
827                let pty_env = with_pty_terminal_capability_defaults(pty_env);
828                let fresh_provider_session = prepare_fresh_pty_provider_session(
829                    spec.capabilities.transports.pty_adapter.as_ref(),
830                    resumed_provider_session.is_some(),
831                    runtime_policy.provider_session_identity,
832                    &mut launch_extra_args,
833                );
834                launch_extra_args.extend(instance_extra_args);
835                let mut authoritative_provider_session = resumed_provider_session
836                    .clone()
837                    .or(fresh_provider_session);
838                let probe_kimi_identity = should_probe_pty_identity(
839                    runtime_policy,
840                    spec.capabilities.transports.pty_adapter.as_ref(),
841                    authoritative_provider_session.is_some(),
842                    "kimi",
843                );
844                let probe_codex_identity = should_probe_pty_identity(
845                    runtime_policy,
846                    spec.capabilities.transports.pty_adapter.as_ref(),
847                    authoritative_provider_session.is_some(),
848                    "codex",
849                );
850                // This is the last point before the OS-level PTY spawn where
851                // the program and its arguments are still plain, structured
852                // data (`spec.launch.program`/`fixed_args` are catalog
853                // constants; `launch_extra_args` is the dynamic, per-session
854                // portion). Provider secrets are environment-only by this
855                // repo's own convention (never argv, see `gate4agent/CLAUDE.md`),
856                // so `fixed_args` needs no redaction; `launch_extra_args`
857                // still gets a defensive per-token credential-shape check
858                // in case a provider CLI's own argv convention differs.
859                // The initial prompt itself is arbitrary-length user text,
860                // not an operational argument, so only its presence is
861                // logged, never its contents.
862                tracing::info!(
863                    agent_id = %agent_id,
864                    instance_id = ?key.instance_id,
865                    generation = ?key.generation,
866                    terminal_size = ?request.terminal_size,
867                    program = %spec.launch.program,
868                    fixed_args = ?spec.launch.fixed_args,
869                    extra_args = ?redact_provider_arguments(&launch_extra_args),
870                    has_initial_prompt = request.initial_prompt.is_some(),
871                    "spawning provider process over a PTY",
872                );
873                match PtySession::spawn_agent_with_size(
874                    &spec,
875                    LaunchRequest {
876                        working_dir,
877                        env: pty_env,
878                        platform: RuntimePlatform::current(),
879                        prompt: request.initial_prompt,
880                        session_options: request.session_options,
881                        extra_args: launch_extra_args,
882                    },
883                    request.terminal_size.rows,
884                    request.terminal_size.columns,
885                )
886                .await
887                {
888                Ok(mut session) => {
889                    if probe_kimi_identity {
890                        match probe_fresh_kimi_session_identity(&session, &spec).await {
891                            Ok(Some(identity)) => authoritative_provider_session = Some(identity),
892                            Ok(None) => {}
893                            Err(error) => {
894                                let message = match session.shutdown().await {
895                                    Ok(_) => error,
896                                    Err(shutdown_error) => {
897                                        format!("{error}; PTY cleanup failed: {shutdown_error}")
898                                    }
899                                };
900                                return ControlObservation::SpawnFailed { message };
901                            }
902                        }
903                    }
904                    if probe_codex_identity {
905                        match probe_fresh_codex_session_identity(&session, &spec).await {
906                            Ok(Some(identity)) => authoritative_provider_session = Some(identity),
907                            Ok(None) => {}
908                            Err(error) => {
909                                let message = match session.shutdown().await {
910                                    Ok(_) => error,
911                                    Err(shutdown_error) => {
912                                        format!("{error}; PTY cleanup failed: {shutdown_error}")
913                                    }
914                                };
915                                return ControlObservation::SpawnFailed { message };
916                            }
917                        }
918                    }
919                    if let Err(error) = deliver_pending_initial_prompt(&mut session, &spec).await {
920                        let message = match session.shutdown().await {
921                            Ok(_) => error,
922                            Err(shutdown_error) => {
923                                format!("{error}; PTY cleanup failed: {shutdown_error}")
924                            }
925                        };
926                        return ControlObservation::SpawnFailed { message };
927                    }
928                    let process_id = session.root_pid();
929                    let provider = match spec.capabilities.transports.pty_adapter.as_ref() {
930                        _ if !should_attach_pty_provider_stream(runtime_policy) => None,
931                        Some(adapter) => {
932                            let tool = match self
933                                .legacy_adapters
934                                .resolve(AdapterFamily::PtySemantic, adapter)
935                            {
936                                Ok(tool) => *tool,
937                                Err(error) => {
938                                    let _ = session.shutdown().await;
939                                    return ControlObservation::SpawnFailed {
940                                        message: error.to_string(),
941                                    };
942                                }
943                            };
944                            match session.attach_events(session.beginning_cursor()) {
945                                Ok(attachment) => {
946                                    let mut pending_events = VecDeque::new();
947                                    let mut provider_session_started = false;
948                                    if let Some(identity) = authoritative_provider_session {
949                                        pending_events.push_back(ProviderEvent::SessionStarted {
950                                            session_id: identity.id.clone(),
951                                            model: String::new(),
952                                            tools: Vec::new(),
953                                        });
954                                        pending_events.push_back(
955                                            ProviderEvent::SessionIdentityObserved { identity },
956                                        );
957                                        provider_session_started = true;
958                                    }
959                                    let is_kimi = tool == CliTool::KimiCode;
960                                    Some(OwnedPtyProvider {
961                                        source: ProviderSource {
962                                            family: AdapterFamily::PtySemantic,
963                                            binding: adapter.clone(),
964                                        },
965                                        receiver: attachment.receiver,
966                                        replay: attachment.replay.into(),
967                                        pending_events,
968                                        utf8: Utf8ChunkDecoder::default(),
969                                        pipeline: Mutex::new(create_pipeline(tool)),
970                                        rate_limits: RateLimitFeed::new_for_tool(tool),
971                                        kimi_identity: (runtime_policy.provider_session_identity
972                                            && is_kimi
973                                            && !provider_session_started)
974                                            .then(KimiPtySessionIdentityExtractor::default),
975                                        semantic_events: runtime_policy.semantic_readiness,
976                                        provider_session_started,
977                                        next_provider_sequence: 1,
978                                    })
979                                }
980                                Err(error) => {
981                                    let _ = session.shutdown().await;
982                                    return ControlObservation::SpawnFailed {
983                                        message: error.to_string(),
984                                    };
985                                }
986                            }
987                        }
988                        None => None,
989                    };
990                    self.pty_sessions.insert(
991                        key,
992                        OwnedPtySession {
993                            session,
994                            spawn_operation_id: operation_id,
995                            last_terminal_sequence: 0,
996                            terminal_stale_published: false,
997                            runtime_policy,
998                            provider,
999                            agent_id,
1000                            last_screen_gate: None,
1001                            last_screen_failure: None,
1002                            last_foreground_verdict: None,
1003                            last_screen_state: PtyScreenState::default(),
1004                            ever_reached_ready: false,
1005                            screen_had_content: false,
1006                            // Armed immediately -- the first
1007                            // `reclassify_foreground` tick after spawn
1008                            // probes this session right away rather than
1009                            // waiting a full `FOREGROUND_RECLASSIFY_INTERVAL`.
1010                            next_foreground_probe: Some(Instant::now()),
1011                        },
1012                    );
1013                    ControlObservation::Spawned { process_id }
1014                }
1015                    Err(error) => {
1016                        let message = error.to_string();
1017                        tracing::warn!(
1018                            agent_id = %agent_id,
1019                            instance_id = ?key.instance_id,
1020                            generation = ?key.generation,
1021                            program = %spec.launch.program,
1022                            fixed_args = ?spec.launch.fixed_args,
1023                            cause = %message,
1024                            "provider process failed to start",
1025                        );
1026                        ControlObservation::SpawnFailed { message }
1027                    }
1028                }
1029            }
1030            TransportKind::Pipe => {
1031                let Some(pipe_spec) = spec.capabilities.transports.pipe.as_ref() else {
1032                    return ControlObservation::SpawnFailed {
1033                        message: format!("agent '{agent_id}' does not support Pipe transport"),
1034                    };
1035                };
1036                let prompt = request.initial_prompt.unwrap_or_default();
1037                if pipe_spec.protocol == PipeProtocol::OneShotText {
1038                    let Some(binding) = spec.capabilities.adapters.one_shot.as_ref() else {
1039                        return ControlObservation::SpawnFailed {
1040                            message: format!(
1041                                "agent '{agent_id}' does not declare OneShot capability"
1042                            ),
1043                        };
1044                    };
1045                    if binding != &pipe_spec.adapter {
1046                        return ControlObservation::SpawnFailed {
1047                            message: format!(
1048                                "agent '{agent_id}' has mismatched OneShot transport bindings"
1049                            ),
1050                        };
1051                    }
1052                    return match NativeOneShotSession::spawn_with_environment_and_persistence(
1053                        &spec,
1054                        binding,
1055                        &prompt,
1056                        request.session_options.as_ref(),
1057                        &working_dir,
1058                        &pty_env,
1059                        one_shot_session_persistence,
1060                    )
1061                    .await
1062                    {
1063                        Ok(session) => {
1064                            let process_id = session.process_id();
1065                            let events = session.subscribe();
1066                            self.one_shot_sessions.insert(
1067                                key,
1068                                OwnedProviderSession {
1069                                    source: ProviderSource {
1070                                        family: AdapterFamily::OneShot,
1071                                        binding: binding.clone(),
1072                                    },
1073                                    session,
1074                                    events,
1075                                    pending_events: VecDeque::new(),
1076                                    pending_provider_events: VecDeque::new(),
1077                                    next_provider_sequence: 1,
1078                                    observed_exit_code: None,
1079                                    runtime_policy,
1080                                },
1081                            );
1082                            ControlObservation::Spawned { process_id }
1083                        }
1084                        Err(error) => ControlObservation::SpawnFailed {
1085                            message: error.to_string(),
1086                        },
1087                    };
1088                }
1089                let tool = match self
1090                    .legacy_adapters
1091                    .resolve(AdapterFamily::Pipe, &pipe_spec.adapter)
1092                {
1093                    Ok(tool) => *tool,
1094                    Err(error) => {
1095                        return ControlObservation::SpawnFailed {
1096                            message: error.to_string(),
1097                        }
1098                    }
1099                };
1100                let source = ProviderSource {
1101                    family: AdapterFamily::Pipe,
1102                    binding: pipe_spec.adapter.clone(),
1103                };
1104                let config = SessionConfig {
1105                    tool,
1106                    working_dir,
1107                    env_vars: Vec::new(),
1108                    name: None,
1109                };
1110                if resumed_provider_session.is_some() && pipe_spec.launch_override.is_some() {
1111                    return ControlObservation::SpawnFailed {
1112                        message: format!(
1113                            "agent '{agent_id}' cannot resume through a catalog launch override"
1114                        ),
1115                    };
1116                }
1117                let mut options = PipeProcessOptions::default();
1118                if let Some(identity) = resumed_provider_session.as_ref() {
1119                    options.claude.resume_session_id = Some(identity.id.clone());
1120                }
1121                let spawned = match pipe_spec.launch_override.as_ref() {
1122                    Some(launch) => {
1123                        PipeSession::spawn_with_launch(
1124                            config,
1125                            &prompt,
1126                            launch,
1127                            pipe_spec.prompt_delivery,
1128                        )
1129                        .await
1130                    }
1131                    None => {
1132                        PipeSession::spawn(config, &prompt, options).await
1133                    }
1134                };
1135                match spawned {
1136                    Ok(session) => {
1137                        let process_id = session.process_id();
1138                        let events = session.subscribe();
1139                        let pending_events = if pipe_spec.protocol == PipeProtocol::SemanticNdjson {
1140                            VecDeque::from([AgentEvent::SessionStart {
1141                                session_id: session.session_id().to_owned(),
1142                                model: String::new(),
1143                                tools: Vec::new(),
1144                            }])
1145                        } else {
1146                            VecDeque::new()
1147                        };
1148                        self.pipe_sessions.insert(
1149                            key,
1150                            OwnedProviderSession {
1151                                source,
1152                                session,
1153                                events,
1154                                pending_events,
1155                                pending_provider_events: VecDeque::new(),
1156                                next_provider_sequence: 1,
1157                                observed_exit_code: None,
1158                                runtime_policy,
1159                            },
1160                        );
1161                        ControlObservation::Spawned { process_id }
1162                    }
1163                    Err(error) => ControlObservation::SpawnFailed {
1164                        message: error.to_string(),
1165                    },
1166                }
1167            }
1168            TransportKind::Acp => {
1169                let Some(acp_spec) = spec.capabilities.transports.acp else {
1170                    return ControlObservation::SpawnFailed {
1171                        message: format!("agent '{agent_id}' does not support ACP transport"),
1172                    };
1173                };
1174                let tool = match self
1175                    .legacy_adapters
1176                    .resolve(AdapterFamily::Acp, &acp_spec.adapter)
1177                {
1178                    Ok(tool) => *tool,
1179                    Err(error) => {
1180                        return ControlObservation::SpawnFailed {
1181                            message: error.to_string(),
1182                        }
1183                    }
1184                };
1185                let source = ProviderSource {
1186                    family: AdapterFamily::Acp,
1187                    binding: acp_spec.adapter.clone(),
1188                };
1189                // ACP is the transport this project opens programmatically --
1190                // unlike a PTY, there is no human at a terminal to pick
1191                // permission flags. Measured live: both running ACP adapters
1192                // (claude, codex) came up with no `--permission-mode` flag
1193                // reaching them at all and no permission request ever
1194                // appearing, because `npx`-wrapped specs never receive one
1195                // (`applicable_approval_args`, `src/acp/spawn.rs`) -- the
1196                // adapter simply started in its own default, confirmed on
1197                // the wire as `mode:Mode="auto"`, which approves itself.
1198                // Argv was fiction for ACP; the level lives in `session/
1199                // set_mode` instead now, for every provider, npx-wrapped or
1200                // the vendor's own binary alike -- one mechanism per
1201                // transport (`applicable_approval_args` never forwards an
1202                // approval flag to an ACP-spawned process any more).
1203                //
1204                // `required_acp_mode` resolves the concrete ACP mode id this
1205                // level needs from `gate4agent_catalog::approval_level_
1206                // resolution`'s own `acp_mode_id` column, and refuses BEFORE
1207                // a process is even spawned whenever no mechanism exists to
1208                // enforce the request: `ApprovalLevelResolution::Unsupported`
1209                // (today, `grok`/`kimi` at `ReadOnly`), or a `Supported` row
1210                // this catalog has no sourced ACP mode id for yet (today,
1211                // every level on `codex`/`grok`/`kimi` except `Unmanaged`).
1212                // Silently proceeding either way would spawn the vendor's
1213                // own default instead -- a wider authority than requested,
1214                // the exact defect this rewrite closes. `Unmanaged` is the
1215                // one level that legitimately resolves to "apply nothing" --
1216                // it imposes nothing by definition.
1217                let acp_mode_id = match required_acp_mode(&agent_id, request.approval_level) {
1218                    Ok(mode_id) => mode_id,
1219                    Err(message) => return ControlObservation::SpawnFailed { message },
1220                };
1221                // The MCP-server door (gate4agent-arc-mailbox-and-task-layer
1222                // Slice A(ii)): `mcp_server` carries the node's resolved MCP
1223                // server overlay whenever one was prepared for this spawn,
1224                // transport-agnostic same as every other launch-profile
1225                // mutation -- see `mcp_server_acp_entry`'s own doc comment.
1226                // `None` when the node prepared none, which keeps
1227                // `mcp_servers` empty and changes nothing else.
1228                let mcp_servers: Vec<McpServerConfig> =
1229                    mcp_server.as_ref().map(mcp_server_acp_entry).into_iter().collect();
1230                if !mcp_servers.is_empty() {
1231                    // State-change line: this is the point measured live to
1232                    // be silently empty on the wire before the ACP v1 shape
1233                    // fix (`McpServerConfig`, `src/acp/protocol.rs`) -- a
1234                    // nameless, map-shaped entry the agent's own adapter
1235                    // dropped before ever registering it, so `tools/list`
1236                    // never ran. Names only, never `env` (may carry
1237                    // tokens/endpoints).
1238                    tracing::info!(
1239                        agent_id = %agent_id,
1240                        instance_id = ?key.instance_id,
1241                        mcp_server_names = ?mcp_servers.iter().map(McpServerConfig::name).collect::<Vec<_>>(),
1242                        "acp session/new carries {} mcp server(s)",
1243                        mcp_servers.len(),
1244                    );
1245                }
1246                // Codex station network_access first slice: argv-only `-c`
1247                // overlays arrive as instance_extra_args (same channel as
1248                // catalog windows_wsl_setup). Merge after approval flags.
1249                let mut approval_level_args =
1250                    acp_approval_level_args(&agent_id, request.approval_level);
1251                for argument in &instance_extra_args {
1252                    approval_level_args.push(argument.to_string_lossy().into_owned());
1253                }
1254                let acp_options = AcpSessionOptions {
1255                    host_policy: host_policy_for_approval_level(request.approval_level),
1256                    // Empty for an agent that announced an `acp_mode_id` for
1257                    // this level: that one is applied through
1258                    // `session/set_mode` below, once the handshake is up,
1259                    // and its argv stays clean (see this branch's own
1260                    // comment above and `applicable_approval_args`,
1261                    // `src/acp/spawn.rs`). An agent that announced NO mode
1262                    // has no such mechanism -- measured 2026-09-09, kimi
1263                    // announces none at any level, so an empty argv left it
1264                    // running at the vendor's own default and it refused
1265                    // every `g4a_*` MCP tool call at its OWN approval
1266                    // prompt without ever sending the host a
1267                    // `session/request_permission`. For that shape argv is
1268                    // the only lever there is. Codex `-c` network overlays
1269                    // may still append via `instance_extra_args` above.
1270                    approval_level_args,
1271                    defer_permission_requests: defers_permission_requests(
1272                        &agent_id,
1273                        request.approval_level,
1274                    ),
1275                    mcp_servers,
1276                    ..AcpSessionOptions::default()
1277                };
1278                let spawned = match acp_spec.launch_override.as_ref() {
1279                    Some(launch) => {
1280                        AcpSession::spawn_with_launch(tool, &working_dir, acp_options, launch)
1281                            .await
1282                    }
1283                    None => AcpSession::spawn(tool, &working_dir, acp_options).await,
1284                };
1285                match spawned {
1286                    Ok(session) => {
1287                        // Subscribe before session/load: history is replayed before its reply.
1288                        let events = session.subscribe();
1289                        tracing::info!(capabilities = ?session.capability_names(),
1290                            "ACP initialize capabilities");
1291                        if let Some(identity) = resumed_provider_session.as_ref() {
1292                            if !session.supports_load_session() {
1293                                let _ = session.kill().await;
1294                                return ControlObservation::SpawnFailed {
1295                                    message: "ACP session/load unsupported".to_owned(),
1296                                };
1297                            }
1298                            if let Err(error) = session.load_session(&identity.id).await {
1299                                let _ = session.kill().await;
1300                                return ControlObservation::SpawnFailed { message: error.to_string() };
1301                            }
1302                        }
1303                        if let Some(mode_id) = acp_mode_id.as_ref() {
1304                            if let Err(message) =
1305                                apply_acp_approval_mode(&session, mode_id, request.approval_level)
1306                                    .await
1307                            {
1308                                let _ = session.kill().await;
1309                                return ControlObservation::SpawnFailed { message };
1310                            }
1311                        }
1312                        let process_id = session.process_id();
1313                        let session_id = session
1314                            .acp_session_id()
1315                            .await
1316                            .unwrap_or_else(|| session.session_id().to_owned());
1317                        // Binds a freshly created record from `IdentityPending`
1318                        // to `Live` (`gate4agent-node`'s `reconcile_managed_
1319                        // record` on `ProviderEvent::SessionIdentityObserved`)
1320                        // as soon as the session exists, mirroring the PTY
1321                        // path's own identity seeding
1322                        // (`prepare_fresh_pty_provider_session`/
1323                        // `probe_fresh_*_session_identity`) for the transport
1324                        // ACP's own spec makes this a protocol MUST for:
1325                        // `session/new` MUST return a `sessionId`, and both
1326                        // shipped adapters map it onto the provider's own
1327                        // durable session id (`AcpSession::
1328                        // provider_reported_session_id`'s own doc comment).
1329                        //
1330                        // Gated on `runtime_policy.provider_session_identity`
1331                        // -- the same capability the PTY path checks before
1332                        // treating any identity as authoritative -- so a
1333                        // spawn that never asked for identity tracking stays
1334                        // silent rather than warning on every ACP session
1335                        // whose caller has no interest in one.
1336                        //
1337                        // `provider_reported_session_id` (NOT `session_id`
1338                        // above) is the signal here: `session_id` already
1339                        // falls back to the host-local id the moment the
1340                        // agent's `session/new` response carries no
1341                        // `sessionId`, so it can never itself distinguish "the
1342                        // agent reported one" from "the agent violated ACP's
1343                        // MUST and this build filled in its own" -- exactly
1344                        // the distinction the `IdentityPending` refusal
1345                        // downstream depends on.
1346                        let identity_observed = if runtime_policy.provider_session_identity {
1347                            match session.provider_reported_session_id().await {
1348                                Some(id) => Some(ProviderEvent::SessionIdentityObserved {
1349                                    identity: ProviderSessionIdentity {
1350                                        key: ProviderSessionKey::SessionId,
1351                                        id,
1352                                        transcript_path: None,
1353                                    },
1354                                }),
1355                                None => {
1356                                    tracing::warn!(
1357                                        agent_id = %agent_id,
1358                                        adapter = %acp_spec.adapter.id,
1359                                        "ACP session/new returned no sessionId; provider \
1360                                         session identity stays IdentityPending",
1361                                    );
1362                                    None
1363                                }
1364                            }
1365                        } else {
1366                            None
1367                        };
1368                        if let Some(prompt) = request.initial_prompt {
1369                            if let Err(error) = session.start_prompt(&prompt).await {
1370                                let _ = session.kill().await;
1371                                return ControlObservation::SpawnFailed {
1372                                    message: error.to_string(),
1373                                };
1374                            }
1375                        }
1376                        // Read before `session` moves into the map below.
1377                        let announced_mode = session.current_mode_id();
1378                        self.acp_sessions.insert(
1379                            key,
1380                            OwnedProviderSession {
1381                                source,
1382                                session,
1383                                events,
1384                                pending_events: {
1385                                    let mut seeded = VecDeque::from([AgentEvent::SessionStart {
1386                                        session_id,
1387                                        model: String::new(),
1388                                        tools: Vec::new(),
1389                                    }]);
1390                                    // Announce the mode catalogue once, at
1391                                    // session start.
1392                                    //
1393                                    // `ModeCatalog` reaches the operator only
1394                                    // from a `ModeChanged`, so without this it
1395                                    // is emitted solely when a mode CHANGES --
1396                                    // and an operator cannot change a mode
1397                                    // without knowing an id, which is what the
1398                                    // catalogue carries. That is a closed
1399                                    // loop: the one thing needed to ask is
1400                                    // only published in reply to asking.
1401                                    //
1402                                    // Both halves are handshake facts, not
1403                                    // inventions: `available_modes` is the
1404                                    // list the agent returned from
1405                                    // `session/new`, and `current_mode_id` is
1406                                    // what it said it is in right now. Seeding
1407                                    // them as a `ModeChanged` is a small
1408                                    // misnomer -- nothing changed -- but the
1409                                    // payload is the state, and the operator
1410                                    // needs the state before it can ever
1411                                    // change.
1412                                    if let Some(mode_id) = announced_mode {
1413                                        seeded.push_back(AgentEvent::ModeChanged { mode_id });
1414                                    }
1415                                    seeded
1416                                },
1417                                pending_provider_events: VecDeque::from_iter(identity_observed),
1418                                next_provider_sequence: 1,
1419                                observed_exit_code: None,
1420                                runtime_policy,
1421                            },
1422                        );
1423                        ControlObservation::Spawned { process_id }
1424                    }
1425                    Err(error) => ControlObservation::SpawnFailed {
1426                        message: error.to_string(),
1427                    },
1428                }
1429            }
1430        }
1431    }
1432
1433    async fn spawn_resume(
1434        &mut self,
1435        key: NativeSessionKey,
1436        operation_id: OperationId,
1437        agent_id: AgentId,
1438        transport: TransportKind,
1439        provider_session: gate4agent_types::ProviderSessionIdentity,
1440        runtime_policy: ProviderRuntimePolicy,
1441        request: ResumeLaunchRequest,
1442        pty_env: Vec<EnvMutation>,
1443        instance_extra_args: Vec<OsString>,
1444        one_shot_session_persistence: OneShotSessionPersistence,
1445        mcp_server: Option<McpServerSpec>,
1446    ) -> ControlObservation {
1447        if let Err(message) = validate_spawn_runtime_policy(
1448            runtime_policy,
1449            transport,
1450            request.initial_prompt.is_some(),
1451            true,
1452        ) {
1453            return ControlObservation::SpawnFailed { message };
1454        }
1455        if let Err(error) = request.validate() {
1456            return ControlObservation::SpawnFailed {
1457                message: error.to_string(),
1458            };
1459        }
1460        let Some(spec) = self.catalog.get(&agent_id) else {
1461            return ControlObservation::SpawnFailed {
1462                message: format!("agent '{agent_id}' is absent from native catalog"),
1463            };
1464        };
1465        let Some(binding) = spec.capabilities.adapters.resume.as_ref() else {
1466            return ControlObservation::SpawnFailed {
1467                message: format!("agent '{agent_id}' does not declare Resume capability"),
1468            };
1469        };
1470        let plan = match build_resume_plan_for_identity(&binding.id, &provider_session) {
1471            Ok(Some(plan)) => plan,
1472            Ok(None) => {
1473                return ControlObservation::SpawnFailed {
1474                    message: format!("agent '{agent_id}' has no live Resume plan"),
1475                }
1476            }
1477            Err(error) => {
1478                return ControlObservation::SpawnFailed {
1479                    message: error.to_string(),
1480                }
1481            }
1482        };
1483        if transport == TransportKind::Pipe {
1484            let Some(pipe) = spec.capabilities.transports.pipe.as_ref() else {
1485                return ControlObservation::SpawnFailed {
1486                    message: format!("agent '{agent_id}' does not support Pipe transport"),
1487                };
1488            };
1489            if pipe.protocol != PipeProtocol::StructuredJsonl {
1490                return ControlObservation::SpawnFailed {
1491                    message: format!(
1492                        "agent '{agent_id}' does not expose a resumable structured Pipe contract"
1493                    ),
1494                };
1495            }
1496        }
1497        let start = StartRequest {
1498            working_directory: request.working_directory,
1499            terminal_size: request.terminal_size,
1500            initial_prompt: request.initial_prompt,
1501            // A resume reattaches to a provider session that already has a
1502            // process running with whatever argv it was originally spawned
1503            // with -- there is no fresh CLI invocation here to apply an
1504            // approval level to, the same reasoning that leaves
1505            // `session_options` unset on a resume above.
1506            session_options: None,
1507            approval_level: ApprovalLevel::default(),
1508        };
1509        self.spawn_native(
1510            key,
1511            operation_id,
1512            NativeSpawnRequest {
1513                agent_id,
1514                transport,
1515                request: start,
1516                runtime_policy,
1517                launch_extra_args: if transport == TransportKind::Pty {
1518                    plan.args.into_iter().map(OsString::from).collect()
1519                } else {
1520                    Vec::new()
1521                },
1522                instance_extra_args,
1523                resumed_provider_session: Some(provider_session),
1524                one_shot_session_persistence,
1525            },
1526            pty_env,
1527            mcp_server,
1528        )
1529        .await
1530    }
1531
1532    async fn stop_native(&mut self, key: NativeSessionKey, force: bool) -> ControlObservation {
1533        if let Some(owned) = self.pty_sessions.remove(&key) {
1534            let shutdown = owned.session.shutdown().await;
1535            return match shutdown {
1536                Ok(outcome) => ControlObservation::StopCompleted {
1537                    forced: force || outcome.termination.is_some(),
1538                    exit_code: outcome.exit_code,
1539                    // The last classification this session ever computed --
1540                    // stamped through unchanged, same as every other frame;
1541                    // nothing observes this session again after this point.
1542                    final_terminal: Some(terminal_frame(outcome.terminal, owned.last_screen_state.clone())),
1543                },
1544                Err(error) => {
1545                    eprintln!(
1546                        "[gate4agent-shell-native] PTY stop failed for {key:?} (force={force}): {error}",
1547                    );
1548                    ControlObservation::StopFailed {
1549                        message: error.to_string(),
1550                    }
1551                }
1552            };
1553        }
1554        if let Some(owned) = self.pipe_sessions.remove(&key) {
1555            // `PipeSession::stop` reads `force`: `false` waits up to
1556            // `PIPE_GRACEFUL_STOP_BOUND_SECS` for the process to exit on its
1557            // own (stdin is already closed by spawn time for every
1558            // supported CLI, so this is "let the run finish" rather than a
1559            // new signal) before falling back to a kill; `true` kills
1560            // immediately, same as the old unconditional `kill()` call this
1561            // replaces. `Err(_) if reader_finished()` below is the race
1562            // where a `force = true` kill loses to the process already
1563            // having exited on its own between the map lookup and the kill
1564            // attempt -- `stop`'s own graceful path already reports that
1565            // case as `Ok` with `forced: false`, so this arm is only ever
1566            // reached on the `force = true` side of `stop`.
1567            return match owned.session.stop(force).await {
1568                Ok(outcome) => ControlObservation::StopCompleted {
1569                    forced: outcome.forced,
1570                    exit_code: outcome.exit_code.or(owned.observed_exit_code),
1571                    final_terminal: None,
1572                },
1573                Err(_) if owned.session.reader_finished() => ControlObservation::StopCompleted {
1574                    forced: false,
1575                    exit_code: owned.observed_exit_code,
1576                    final_terminal: None,
1577                },
1578                Err(error) => ControlObservation::StopFailed {
1579                    message: error.to_string(),
1580                },
1581            };
1582        }
1583        if let Some(mut owned) = self.one_shot_sessions.remove(&key) {
1584            return match owned.session.kill().await {
1585                Ok(()) => ControlObservation::StopCompleted {
1586                    forced: true,
1587                    exit_code: owned.observed_exit_code,
1588                    final_terminal: None,
1589                },
1590                Err(_) if owned.session.reader_finished() => ControlObservation::StopCompleted {
1591                    forced: false,
1592                    exit_code: owned.observed_exit_code,
1593                    final_terminal: None,
1594                },
1595                Err(error) => ControlObservation::StopFailed {
1596                    message: error.to_string(),
1597                },
1598            };
1599        }
1600        if let Some(owned) = self.acp_sessions.remove(&key) {
1601            // `AcpSession::stop` reads `force`: `false` closes stdin and
1602            // waits up to `ACP_GRACEFUL_STOP_BOUND_SECS` for the adapter to
1603            // exit on its own before falling back to a kill; `true` kills
1604            // immediately, same as the old unconditional `kill()` call this
1605            // replaces. `Err(_) if reader_finished()` below is the race
1606            // where a `force = true` kill loses to the process already
1607            // having exited on its own between the map lookup and the kill
1608            // attempt -- `stop`'s own graceful path already reports that
1609            // case as `Ok` with `forced: false`, so this arm is only ever
1610            // reached on the `force = true` side of `stop`.
1611            return match owned.session.stop(force).await {
1612                Ok(outcome) => ControlObservation::StopCompleted {
1613                    forced: outcome.forced,
1614                    exit_code: outcome.exit_code.or(owned.observed_exit_code),
1615                    final_terminal: None,
1616                },
1617                Err(_) if owned.session.reader_finished() => ControlObservation::StopCompleted {
1618                    forced: false,
1619                    exit_code: owned.observed_exit_code,
1620                    final_terminal: None,
1621                },
1622                Err(error) => ControlObservation::StopFailed {
1623                    message: error.to_string(),
1624                },
1625            };
1626        }
1627        // A kill this function skips entirely -- nothing owns `key` in any
1628        // transport map -- must say so out loud: silently returning
1629        // `StopFailed` here left no trail at the point where the skip
1630        // actually happened, only a message string several layers removed
1631        // from anyone watching this process's own output.
1632        eprintln!("[gate4agent-shell-native] stop skipped: no session owns {key:?} in any transport map");
1633        ControlObservation::StopFailed {
1634            message: missing_session_message(key),
1635        }
1636    }
1637
1638    fn session_exists(&self, key: NativeSessionKey) -> bool {
1639        self.pty_sessions.contains_key(&key)
1640            || self.pipe_sessions.contains_key(&key)
1641            || self.one_shot_sessions.contains_key(&key)
1642            || self.acp_sessions.contains_key(&key)
1643    }
1644
1645    /// Convert naturally exited PTY children into generation-bound lifecycle
1646    /// observations. Runtime ticks call this before accepting new commands.
1647    pub async fn collect_exits(&mut self) -> Vec<ObservationEnvelope> {
1648        let completed: Vec<_> = self
1649            .pty_sessions
1650            .iter()
1651            .filter_map(|(key, owned)| owned.session.reader_finished().then_some(*key))
1652            .collect();
1653        let mut observations = Vec::with_capacity(completed.len());
1654        for key in completed {
1655            let owned = self
1656                .pty_sessions
1657                .remove(&key)
1658                .expect("completed key came from the owned session map");
1659            let last_screen_state = owned.last_screen_state.clone();
1660            let (exit_code, final_terminal) = match owned.session.shutdown().await {
1661                Ok(outcome) => (
1662                    outcome.exit_code,
1663                    Some(terminal_frame(outcome.terminal, last_screen_state)),
1664                ),
1665                Err(_) => (None, None),
1666            };
1667            observations.push(ObservationEnvelope {
1668                operation_id: None,
1669                instance_id: key.instance_id,
1670                generation: key.generation,
1671                observation: ControlObservation::ProcessExited {
1672                    exit_code,
1673                    final_terminal,
1674                },
1675            });
1676        }
1677        collect_provider_exits(&mut self.pipe_sessions, &mut observations, |session| {
1678            session.reader_finished()
1679        });
1680        collect_provider_exits(&mut self.one_shot_sessions, &mut observations, |session| {
1681            session.reader_finished()
1682        });
1683        collect_provider_exits(&mut self.acp_sessions, &mut observations, |session| {
1684            session.reader_finished()
1685        });
1686        observations
1687    }
1688
1689    /// Drain normalized provider events without mixing them with replaceable
1690    /// terminal frames. Broadcast lag is converted into an explicit stale gap.
1691    pub fn collect_provider_events(&mut self) -> Vec<ObservationEnvelope> {
1692        let mut observations = self.pending_observations.drain(..).collect::<Vec<_>>();
1693        for (key, owned) in &mut self.pty_sessions {
1694            if let Some(provider) = &mut owned.provider {
1695                drain_pty_provider(*key, provider, &mut observations);
1696            }
1697        }
1698        collect_provider_map(&mut self.pipe_sessions, &mut observations, |_| Vec::new());
1699        collect_provider_map(&mut self.one_shot_sessions, &mut observations, |_| Vec::new());
1700        // Retire deferred permission requests whose deadline has passed,
1701        // BEFORE draining -- so the `RpcIncomingRequest` each expiry emits is
1702        // picked up by the very same drain rather than waiting a whole tick
1703        // to be reported.
1704        //
1705        // This call is what makes the deadline real. Without it a deferred
1706        // request has a `deadline` field nobody ever reads, and a session
1707        // whose operator never answers waits forever on a promise the code
1708        // makes and never keeps -- the agent blocked on a permission it will
1709        // never be told about. Deferral is only safe because this runs on
1710        // every tick; nothing else in the process calls it.
1711        for owned in self.acp_sessions.values() {
1712            owned.session.expire_deadlines();
1713        }
1714        collect_provider_map(&mut self.acp_sessions, &mut observations, AcpSession::available_modes);
1715        observations
1716    }
1717
1718    /// Capture only changed terminal frames. Snapshot failures become an
1719    /// explicit stale observation once, until a later successful frame heals it.
1720    ///
1721    /// The sequence is checked BEFORE the capture, not after. This runs on
1722    /// the per-session worker tick (20ms, so ~50 times a second per live
1723    /// PTY session), and `terminal_state` is not a cheap read: it renders
1724    /// the visible screen twice and clones the whole `vt100::Screen` to
1725    /// walk its scrollback row by row. Asking it first and comparing
1726    /// sequences afterwards meant every idle session rebuilt its entire
1727    /// screen fifty times a second purely to discover nothing had changed,
1728    /// and then dropped the result -- with a couple of dozen sessions open
1729    /// that is the machine's time, all of it wasted. `terminal_sequence`
1730    /// answers the same question by reading one integer.
1731    pub fn collect_terminal_frames(&mut self) -> Vec<ObservationEnvelope> {
1732        let mut observations = Vec::new();
1733        // Split borrows taken up front: the loop below needs a mutable
1734        // borrow of `pty_sessions` for its whole body, and `efficiency_facts`
1735        // is a disjoint field this function also writes to on every branch
1736        // -- see `ShellEfficiencyFacts`'s own doc comment for why this crate
1737        // is the one recording facts rather than a distribution.
1738        let pty_sessions = &mut self.pty_sessions;
1739        let efficiency_facts = &mut self.efficiency_facts;
1740        for (key, owned) in pty_sessions {
1741            if terminal_state_capture_should_skip(
1742                owned.session.terminal_sequence(),
1743                owned.last_terminal_sequence,
1744            ) {
1745                efficiency_facts.record_terminal_state_skip();
1746                continue;
1747            }
1748            let capture_start = Instant::now();
1749            let terminal_state = owned.session.terminal_state();
1750            efficiency_facts.record_terminal_state_capture(capture_start.elapsed());
1751            match terminal_state {
1752                Ok(snapshot) if snapshot.sequence > owned.last_terminal_sequence => {
1753                    owned.last_terminal_sequence = snapshot.sequence;
1754                    owned.terminal_stale_published = false;
1755
1756                    // `snapshot.contents` is already in memory for the
1757                    // `TerminalFrame` below, so both text matchers run for
1758                    // free here -- no extra syscall, no extra capture.
1759                    owned.last_screen_gate = startup_operator_gate(&snapshot.contents);
1760                    // `screen_failure`'s markers are crash SHAPES, and as
1761                    // raw bytes those are indistinguishable from an agent
1762                    // choosing to render the same text while explaining or
1763                    // running someone else's failure. Before this
1764                    // generation has ever rendered its own UI, nothing else
1765                    // could have put a crash banner on the screen, so the
1766                    // marker genuinely means the CLI failed to come up;
1767                    // once it has been `Ready`, the identical bytes are
1768                    // ordinary content, not state, so the matcher is not
1769                    // even run.
1770                    owned.last_screen_failure =
1771                        screen_failure_for_generation(&snapshot.contents, owned.ever_reached_ready);
1772                    let merged = classify_pty_screen_state(
1773                        owned.last_foreground_verdict.as_ref(),
1774                        owned.last_screen_gate.as_ref(),
1775                        owned.last_screen_failure,
1776                    );
1777                    // Arm the crash-marker window only on a `Ready` that had
1778                    // SOMETHING on screen. `Ready` is proved by foreground
1779                    // process identity, so it lands within a frame or two of
1780                    // spawn, while the terminal is still blank -- measured at
1781                    // frame 2 for all four providers. Arming on that blank
1782                    // frame closed the window before any failure text could
1783                    // exist: Grok without a key prints `API key required` at
1784                    // frame 4 and sat at `Ready` forever, because the matcher
1785                    // for it was never reached. A blank screen is not evidence
1786                    // the agent came up, so it must not retire the detector.
1787                    if !snapshot.contents.trim().is_empty() {
1788                        owned.screen_had_content = true;
1789                    }
1790                    if merged == PtyScreenState::Ready && owned.screen_had_content {
1791                        owned.ever_reached_ready = true;
1792                    }
1793                    if merged != owned.last_screen_state {
1794                        if foreground_probe_rearms_immediately(&owned.last_screen_state, &merged) {
1795                            owned.next_foreground_probe = Some(Instant::now());
1796                        }
1797                        owned.last_screen_state = merged.clone();
1798                        observations.push(ObservationEnvelope {
1799                            operation_id: None,
1800                            instance_id: key.instance_id,
1801                            generation: key.generation,
1802                            observation: ControlObservation::ScreenState {
1803                                state: merged.clone(),
1804                            },
1805                        });
1806                    }
1807
1808                    let frame = terminal_frame(snapshot, merged);
1809                    efficiency_facts.record_terminal_frame_published(terminal_frame_byte_len(&frame));
1810                    observations.push(ObservationEnvelope {
1811                        operation_id: None,
1812                        instance_id: key.instance_id,
1813                        generation: key.generation,
1814                        observation: ControlObservation::TerminalFrame { frame },
1815                    });
1816                }
1817                Ok(_) => {}
1818                Err(error) if !owned.terminal_stale_published => {
1819                    owned.terminal_stale_published = true;
1820                    observations.push(ObservationEnvelope {
1821                        operation_id: None,
1822                        instance_id: key.instance_id,
1823                        generation: key.generation,
1824                        observation: ControlObservation::TerminalStale {
1825                            message: error.to_string(),
1826                        },
1827                    });
1828                }
1829                Err(_) => {}
1830            }
1831        }
1832        observations
1833    }
1834
1835    /// Refresh the foreground half of `PtyScreenState` for whichever
1836    /// sessions are due, per `next_foreground_probe`.
1837    ///
1838    /// Deliberately not folded into `collect_terminal_frames`: that method
1839    /// is synchronous and only pays for a real capture when the terminal
1840    /// sequence says the screen changed, but
1841    /// `PtySession::observe_foreground_timed` is async and walks the live OS
1842    /// process tree
1843    /// (`CreateToolhelp32Snapshot` on Windows) unconditionally every time
1844    /// it is called. Running that walk once per changed frame would scale
1845    /// a syscall with output rate -- exactly the cost
1846    /// `collect_terminal_frames`'s own sequence gate exists to avoid. The
1847    /// cost here is bounded by the count of sessions NOT currently
1848    /// `Ready`, never by output rate and never by total session count: a
1849    /// session that reaches `Ready` disarms itself (see
1850    /// `foreground_probe_schedule`) and is never probed again until its
1851    /// text disagrees.
1852    pub async fn reclassify_foreground(&mut self) -> Vec<ObservationEnvelope> {
1853        let catalog = &self.catalog;
1854        let now = Instant::now();
1855        let due: Vec<NativeSessionKey> = self
1856            .pty_sessions
1857            .iter()
1858            .filter(|(_, owned)| owned.next_foreground_probe.is_some_and(|at| now >= at))
1859            .map(|(key, _)| *key)
1860            .collect();
1861
1862        let mut observations = Vec::new();
1863        for key in due {
1864            let Some(owned) = self.pty_sessions.get_mut(&key) else {
1865                continue;
1866            };
1867            let probe_result = owned.session.observe_foreground_timed().await;
1868            match probe_result {
1869                Ok((observation, timing)) => {
1870                    // Recorded on success only: `timing` covers all three
1871                    // components (queue, lock wait, walk) exactly when the
1872                    // walk itself ran to completion and returned a real
1873                    // observation. On error (see below) the walk may have
1874                    // failed partway through, in the mutex, or never been
1875                    // dispatched at all (`spawn_blocking` panicked), so
1876                    // there is no single component that is reliably "the
1877                    // cost of this probe" to attribute a failure to -- unlike
1878                    // `terminal_state_capture`, which always completes or
1879                    // never starts, a foreground probe can fail after
1880                    // dispatch, after acquiring the lock, or during the walk,
1881                    // and only the success path knows which.
1882                    self.efficiency_facts.record_foreground_probe(timing);
1883                    let verdict = match catalog.get(&owned.agent_id) {
1884                        Some(spec) => resolve_foreground_verdict(
1885                            spec,
1886                            &observation,
1887                            RuntimePlatform::current(),
1888                        ),
1889                        // The catalog is loaded once at startup and does not
1890                        // shrink at runtime; this branch exists only so a
1891                        // hypothetical gap fails toward the conservative
1892                        // "not confirmed as the agent" reading rather than
1893                        // panicking or silently keeping a stale verdict.
1894                        None => ForegroundVerdict::Foreign {
1895                            process: observation.observed_process.clone(),
1896                        },
1897                    };
1898                    owned.last_foreground_verdict = Some(verdict);
1899                    let merged = classify_pty_screen_state(
1900                        owned.last_foreground_verdict.as_ref(),
1901                        owned.last_screen_gate.as_ref(),
1902                        owned.last_screen_failure,
1903                    );
1904                    // A foreground-only transition into `Ready` (text was
1905                    // already clean; only the process signal was missing)
1906                    // must ALSO close the `screen_failure` window for
1907                    // future text passes -- see `collect_terminal_frames`.
1908                    if merged == PtyScreenState::Ready && owned.screen_had_content {
1909                        owned.ever_reached_ready = true;
1910                    }
1911                    if merged != owned.last_screen_state {
1912                        owned.last_screen_state = merged.clone();
1913                        observations.push(ObservationEnvelope {
1914                            operation_id: None,
1915                            instance_id: key.instance_id,
1916                            generation: key.generation,
1917                            observation: ControlObservation::ScreenState { state: merged },
1918                        });
1919                    }
1920                    owned.next_foreground_probe =
1921                        match foreground_probe_schedule(&owned.last_screen_state) {
1922                            ForegroundProbeSchedule::Disarmed => None,
1923                            ForegroundProbeSchedule::Armed => {
1924                                Some(now + FOREGROUND_RECLASSIFY_INTERVAL)
1925                            }
1926                        };
1927                }
1928                Err(_) => {
1929                    // A failed OS process-tree walk is `Unknown`'s territory
1930                    // -- it says nothing was confirmed, not that the
1931                    // process is wrong. Leave whatever verdict/state is
1932                    // already recorded alone and simply try again next
1933                    // cadence rather than fabricating a `NotAgent` verdict
1934                    // or a `Ready` one.
1935                    owned.next_foreground_probe = Some(now + FOREGROUND_RECLASSIFY_INTERVAL);
1936                }
1937            }
1938        }
1939        observations
1940    }
1941}
1942
1943/// ConPTY does not populate `TERM`/`COLORTERM` in the environment it hands
1944/// to a spawned child; a provider CLI reads exactly those two variables to
1945/// decide whether the terminal in front of it renders color, so a
1946/// Windows-hosted PTY session comes up monochrome unless something else
1947/// supplies them. These are the values truecolor-capable terminals
1948/// (xterm.js, WezTerm, ...) advertise about themselves.
1949const PTY_TERM_DEFAULT_KEY: &str = "TERM";
1950const PTY_TERM_DEFAULT_VALUE: &str = "xterm-256color";
1951const PTY_COLORTERM_DEFAULT_KEY: &str = "COLORTERM";
1952const PTY_COLORTERM_DEFAULT_VALUE: &str = "truecolor";
1953
1954/// Fill in the PTY terminal-capability defaults above for whichever of the
1955/// two keys the caller has not already mutated. A caller-supplied
1956/// `EnvMutation` for `TERM`/`COLORTERM` -- whether it sets or removes the
1957/// variable -- always wins: this only appends a default into a gap, it
1958/// never overwrites or reorders an existing entry.
1959fn with_pty_terminal_capability_defaults(mut pty_env: Vec<EnvMutation>) -> Vec<EnvMutation> {
1960    let already_mutated = |env: &[EnvMutation], key: &str| {
1961        env.iter()
1962            .any(|mutation| mutation.key.as_os_str() == OsStr::new(key))
1963    };
1964    if !already_mutated(&pty_env, PTY_TERM_DEFAULT_KEY) {
1965        pty_env.push(EnvMutation {
1966            key: OsString::from(PTY_TERM_DEFAULT_KEY),
1967            value: Some(OsString::from(PTY_TERM_DEFAULT_VALUE)),
1968        });
1969    }
1970    if !already_mutated(&pty_env, PTY_COLORTERM_DEFAULT_KEY) {
1971        pty_env.push(EnvMutation {
1972            key: OsString::from(PTY_COLORTERM_DEFAULT_KEY),
1973            value: Some(OsString::from(PTY_COLORTERM_DEFAULT_VALUE)),
1974        });
1975    }
1976    pty_env
1977}
1978
1979fn missing_session_message(key: NativeSessionKey) -> String {
1980    format!(
1981        "native session {:?}/{:?} does not exist",
1982        key.instance_id, key.generation
1983    )
1984}
1985
1986/// Map the spawn request's `ApprovalLevel` to the ACP host authority mode
1987/// that answers `session/request_permission` for the SAME session -- the
1988/// PTY transport lets a human at the keyboard pick their own agent's
1989/// permission flags (see `gate4agent_catalog::LaunchRequest`, which carries
1990/// no approval axis at all), but ACP is opened by this process with nobody
1991/// at a terminal, so it is the one transport where `approval_level` also has
1992/// to steer the host side of the session, not just the spawned process's own
1993/// argv (`approval_level_args`).
1994///
1995/// `FullAuto` must never land on a refusing `HostPolicy` (`ReadOnly` or
1996/// `Deny`): that combination launches the process believing it holds full
1997/// autonomy while every host permission request it makes gets silently
1998/// refused, which is worse than either policy alone -- so `FullAuto` maps to
1999/// `HostPolicy::Yolo`, the one mode that grants everything without asking.
2000/// `ReadOnly` maps to `HostPolicy::ReadOnly` for the same reason in reverse.
2001///
2002/// `Moderate` has no dedicated `HostPolicy` variant -- ACP's four host modes
2003/// are coarser than the three managed `ApprovalLevel` steps -- so it falls
2004/// back to `HostPolicy::Auto`, the same mode `Unmanaged` ("impose nothing")
2005/// uses. Both already mean "allow reads, writes, and execution, but decide
2006/// per request rather than blanket-granting" (see `HostPolicy::Auto`'s own
2007/// doc comment), which is the correct non-extreme default whether the
2008/// request asked for a deliberate middle ground or asked for nothing to be
2009/// imposed at all.
2010fn host_policy_for_approval_level(level: ApprovalLevel) -> HostPolicy {
2011    match level {
2012        ApprovalLevel::FullAuto => HostPolicy::Yolo,
2013        ApprovalLevel::ReadOnly => HostPolicy::ReadOnly,
2014        ApprovalLevel::Moderate | ApprovalLevel::Unmanaged => HostPolicy::Auto,
2015    }
2016}
2017
2018/// Whether a session at this approval level parks a `session/request_
2019/// permission` for an operator instead of answering it from policy on the
2020/// spot (`AcpSessionOptions::defer_permission_requests`).
2021///
2022/// Reads `asks_for_permission` straight off
2023/// `gate4agent_catalog::approval_level_resolution` -- the provider's own
2024/// vendor mode, declared beside its flag -- rather than matching on the
2025/// `ApprovalLevel`'s name. That distinction used to matter in practice: this
2026/// function previously matched on the level alone and assumed `ReadOnly`
2027/// never asks, but claude's `ReadOnly` launched `--permission-mode default`,
2028/// claude's own **interactive** mode, which asks about everything. A live
2029/// run under that flag produced a completed tool call and zero
2030/// `host-request-observed` because deferral was off for the one level that
2031/// was actually asking. `approval_level_resolution`'s `ReadOnly` row for
2032/// claude now launches `plan` (which genuinely never asks) instead, so the
2033/// caller (this transport's own ACP spawn branch) must already have refused
2034/// the spawn outright for any provider `approval_level_resolution` marks
2035/// `Unsupported` for this level -- see that call site -- before this
2036/// function is reached; `Unsupported` here is defensive-only and defers,
2037/// the conservative choice, rather than assuming silence.
2038///
2039/// `Unmanaged` always resolves `asks_for_permission: false` -- it decides
2040/// `session/request_permission` immediately (auto-approve) rather than
2041/// parking it, since some providers' ACP clients won't wait out a deferred
2042/// decision (kimi reports the call as refused). The managed levels'
2043/// `asks_for_permission` still varies per provider and per level -- that is
2044/// a fact about today's four providers' vendor modes, not a rule this
2045/// function encodes; a fifth provider or a vendor mode change could shift it
2046/// without this function's logic changing at all, which is the point of
2047/// reading the catalog instead of the level.
2048fn defers_permission_requests(agent_id: &AgentId, level: ApprovalLevel) -> bool {
2049    match approval_level_resolution(agent_id, level) {
2050        ApprovalLevelResolution::Supported {
2051            asks_for_permission,
2052            ..
2053        } => asks_for_permission,
2054        ApprovalLevelResolution::Unsupported => true,
2055    }
2056}
2057
2058/// How long [`apply_acp_approval_mode`] waits, after a successful
2059/// `session/set_mode` RPC ack, for the agent's own `current_mode_update`
2060/// notification to corroborate it. Bounded because the notification is
2061/// documented as optional -- `AcpSession::set_mode`'s own doc comment: "an
2062/// agent is not required to also send one after acking this call" -- so an
2063/// agent that never sends it must never stall a spawn indefinitely. The RPC
2064/// ack itself (checked before this wait starts) is the authoritative
2065/// confirmation; this wait is corroboration only, and a timeout here does
2066/// not undo it.
2067const ACP_MODE_CONFIRMATION_TIMEOUT: Duration = Duration::from_secs(5);
2068
2069/// Resolve the concrete ACP mode id [`apply_acp_approval_mode`] must confirm
2070/// and apply for `agent_id` at `level`, or the exact refusal message when no
2071/// mechanism exists to enforce it at all.
2072///
2073/// Outcomes:
2074/// - `Ok(Some(id))` — catalog named a sourced `acp_mode_id`; spawn applies it
2075///   via `session/set_mode` (claude/codex managed levels today).
2076/// - `Ok(None)` for [`ApprovalLevel::Unmanaged`] — imposes nothing.
2077/// - `Ok(None)` when the level is `Supported` with `acp_mode_id: None` **and**
2078///   non-empty vendor `args` — argv is the only lever left (grok FullAuto /
2079///   Moderate; kimi FullAuto). `acp_approval_level_args` carries those flags
2080///   into the process ahead of the ACP subcommand.
2081/// - `Err` for [`ApprovalLevelResolution::Unsupported`] (e.g. grok ReadOnly)
2082///   or a `Supported` row with neither mode id nor flags (kimi Moderate /
2083///   ReadOnly today): refuse rather than launch at the vendor default
2084///   (`mode:Mode="auto"`), which approves itself.
2085fn required_acp_mode(agent_id: &AgentId, level: ApprovalLevel) -> Result<Option<ModeId>, String> {
2086    let (acp_mode_id, carries_argv_flags) = match approval_level_resolution(agent_id, level) {
2087        ApprovalLevelResolution::Unsupported => (None, false),
2088        ApprovalLevelResolution::Supported { acp_mode_id, args, .. } => {
2089            (acp_mode_id, !args.is_empty())
2090        }
2091    };
2092    match (acp_mode_id, level) {
2093        (Some(mode_id), _) => Ok(Some(mode_id)),
2094        (None, ApprovalLevel::Unmanaged) => Ok(None),
2095        // No mode, but the level carries vendor flags: `acp_approval_level_args`
2096        // puts those in the agent's own argv, so the level IS applied and this
2097        // is not a launch at the vendor's default. The refusal below exists to
2098        // stop a session running at wider authority than asked for -- it must
2099        // not also block the one mechanism that narrows it. Measured
2100        // 2026-09-09: kimi announces no ACP modes at all, so before this every
2101        // level but `Unmanaged` refused outright and its own `--yolo` was
2102        // unreachable.
2103        (None, _) if carries_argv_flags => Ok(None),
2104        (None, _) => Err(format!(
2105            "agent '{agent_id}' has no verified ACP mode for {level:?} and the level carries no \
2106             vendor flags to apply through argv either; refusing rather than launching at the \
2107             vendor's own (wider-authority) default"
2108        )),
2109    }
2110}
2111
2112/// The vendor approval flags an ACP-spawned agent needs in its own argv.
2113///
2114/// Exactly the complement of [`required_acp_mode`]: a level that resolved an
2115/// `acp_mode_id` is applied over the wire by `session/set_mode`, so that
2116/// agent's argv stays clean and this returns nothing. A level that resolved
2117/// NO mode has no wire mechanism at all, and returning nothing there means
2118/// launching at the vendor's own default -- the exact wider-authority defect
2119/// the mode machinery exists to close, just reached from the other side.
2120///
2121/// Measured 2026-09-09: every kimi row carries `acp_mode_id: None` (kimi.exe
2122/// 0.29.0 announces no modes), so kimi ran at its own default and refused
2123/// every `g4a_*` MCP tool call at its internal approval prompt without ever
2124/// sending the host a `session/request_permission` -- unreachable by policy,
2125/// by deferral, and by `set_mode` alike. Its `FullAuto` row already carries
2126/// the flag that turns that gate off (`--yolo`); it simply never reached the
2127/// process.
2128fn acp_approval_level_args(agent_id: &AgentId, level: ApprovalLevel) -> Vec<String> {
2129    match approval_level_resolution(agent_id, level) {
2130        ApprovalLevelResolution::Supported { args, acp_mode_id: None, .. } => args,
2131        ApprovalLevelResolution::Supported { acp_mode_id: Some(_), .. } => Vec::new(),
2132        ApprovalLevelResolution::Unsupported => Vec::new(),
2133    }
2134}
2135
2136/// Named refusal for [`apply_acp_approval_mode`]: `level` resolved a real
2137/// catalog `acp_mode_id`, but this agent's own `session/new` handshake never
2138/// announced a mode with that id -- so the mechanism that would apply it
2139/// (`session/set_mode`) has nothing to call. Refusing by name, carrying
2140/// exactly what the agent DID offer, is the alternative to the defect this
2141/// whole rewrite exists to close: silently leaving the session running at
2142/// whichever mode the agent came up in on its own.
2143#[derive(Debug)]
2144struct ApprovalLevelNotOfferedByAgent {
2145    level: ApprovalLevel,
2146    offered: Vec<String>,
2147}
2148
2149impl std::fmt::Display for ApprovalLevelNotOfferedByAgent {
2150    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2151        write!(
2152            formatter,
2153            "ApprovalLevelNotOfferedByAgent {{ level: {:?}, offered: {:?} }}",
2154            self.level, self.offered
2155        )
2156    }
2157}
2158
2159/// `None` when `offered` (the agent's own `session/new` mode catalog) names
2160/// `mode_id`; `Some(message)` -- an [`ApprovalLevelNotOfferedByAgent`],
2161/// stringified -- when it does not. A free function, independent of a live
2162/// [`AcpSession`], so the refusal can be exercised directly against a
2163/// fixture mode list rather than only through a real spawn.
2164fn approval_level_not_offered_message(
2165    level: ApprovalLevel,
2166    mode_id: &ModeId,
2167    offered: &[SessionMode],
2168) -> Option<String> {
2169    if offered.iter().any(|mode| mode.id == mode_id.as_str()) {
2170        None
2171    } else {
2172        Some(
2173            ApprovalLevelNotOfferedByAgent {
2174                level,
2175                offered: offered.iter().map(|mode| mode.id.clone()).collect(),
2176            }
2177            .to_string(),
2178        )
2179    }
2180}
2181
2182/// Apply `mode_id` to a freshly handshaken ACP session (Item 2 of the
2183/// `session/set_mode` approval-level rewrite): refuse by name
2184/// (`approval_level_not_offered_message`) when the agent's own `session/new`
2185/// mode catalog never named this id, otherwise call `session/set_mode` and
2186/// wait, bounded by [`ACP_MODE_CONFIRMATION_TIMEOUT`], for the agent's own
2187/// `current_mode_update` to corroborate it -- only then is the session
2188/// considered up at the requested level.
2189///
2190/// The RPC ack from `AcpSession::set_mode` is the authoritative
2191/// confirmation (it already updates the session's own cached
2192/// `current_mode_id` synchronously on success, and an agent rejecting an
2193/// unknown mode id returns an RPC error there, not a silent no-op); the wait
2194/// on this function's own subscription is corroboration only. A provider
2195/// that never sends `current_mode_update` at all -- permitted by the ACP
2196/// spec -- times out here and the spawn still proceeds, because the RPC ack
2197/// that already succeeded is not undone by a notification that was never
2198/// guaranteed in the first place.
2199async fn apply_acp_approval_mode(
2200    session: &AcpSession,
2201    mode_id: &ModeId,
2202    level: ApprovalLevel,
2203) -> Result<(), String> {
2204    if let Some(message) =
2205        approval_level_not_offered_message(level, mode_id, &session.available_modes())
2206    {
2207        return Err(message);
2208    }
2209
2210    // Subscribed BEFORE `set_mode` is sent, so a fast `current_mode_update`
2211    // cannot race ahead of this receiver's creation and be missed.
2212    let mut confirmation = session.subscribe();
2213    session
2214        .set_mode(mode_id.as_str())
2215        .await
2216        .map_err(|error| format!("session/set_mode to '{mode_id}' failed: {error}"))?;
2217
2218    let _ = tokio::time::timeout(ACP_MODE_CONFIRMATION_TIMEOUT, async {
2219        loop {
2220            match confirmation.recv().await {
2221                Ok(AgentEvent::ModeChanged { mode_id: changed }) if changed == mode_id.as_str() => {
2222                    return;
2223                }
2224                Ok(_) => continue,
2225                Err(_) => return,
2226            }
2227        }
2228    })
2229    .await;
2230
2231    Ok(())
2232}
2233
2234fn validate_spawn_runtime_policy(
2235    policy: ProviderRuntimePolicy,
2236    transport: TransportKind,
2237    has_initial_prompt: bool,
2238    is_resume: bool,
2239) -> Result<(), String> {
2240    policy
2241        .validate()
2242        .map_err(|error| format!("provider runtime policy is invalid: {error}"))?;
2243    // ACP speaks a structured protocol over stdio, not a PTY -- none of the
2244    // capabilities below describe anything that exists for it; they all
2245    // gate inferring provider state from terminal text. The transport-
2246    // support gate for ACP already lives in the kernel
2247    // (`spec.capabilities.transports.acp.is_some()`), so this PTY-semantic
2248    // policy simply does not apply here. Mirrors `gate4agent-runtime-native`'s
2249    // `validate_effect_runtime_policy`, which enforces the same rule one
2250    // layer up.
2251    if transport != TransportKind::Acp {
2252        require_runtime_capability(policy, ProviderRuntimeCapability::RawPtyLifecycle)?;
2253        if transport != TransportKind::Pty {
2254            require_runtime_capability(policy, ProviderRuntimeCapability::SemanticReadiness)?;
2255        }
2256        if has_initial_prompt {
2257            require_runtime_capability(policy, ProviderRuntimeCapability::SemanticReadiness)?;
2258            require_runtime_capability(policy, ProviderRuntimeCapability::StructuredPrompt)?;
2259        }
2260        if is_resume && has_initial_prompt {
2261            require_runtime_capability(policy, ProviderRuntimeCapability::ProviderSessionIdentity)?;
2262            require_runtime_capability(policy, ProviderRuntimeCapability::SemanticResume)?;
2263        }
2264    }
2265    Ok(())
2266}
2267
2268
2269fn is_codex_config_c_overlay_args(arguments: &[OsString]) -> bool {
2270    if arguments.is_empty() || arguments.len() % 2 != 0 {
2271        return false;
2272    }
2273    arguments.chunks_exact(2).all(|pair| {
2274        pair[0].as_os_str() == "-c"
2275            && pair[1]
2276                .to_str()
2277                .is_some_and(|value| !value.is_empty() && value.contains('=') && !value.contains('\0'))
2278    })
2279}
2280
2281fn validate_instance_launch_arguments(
2282    agent_id: &AgentId,
2283    transport: TransportKind,
2284    arguments: &[OsString],
2285) -> Result<(), String> {
2286    if arguments.is_empty() {
2287        return Ok(());
2288    }
2289    let acp_codex_c_overlay = transport == TransportKind::Acp
2290        && agent_id.as_str() == "codex"
2291        && is_codex_config_c_overlay_args(arguments);
2292    if transport != TransportKind::Pty && !acp_codex_c_overlay {
2293        return Err(
2294            "native instance launch arguments require PTY transport (or Codex -c overlays on ACP)"
2295                .to_owned(),
2296        );
2297    }
2298    if arguments.len() > INSTANCE_LAUNCH_ARGS_MAX {
2299        return Err("native instance launch argument count exceeds its bound".to_owned());
2300    }
2301    let mut total_bytes = 0usize;
2302    for argument in arguments {
2303        let argument = argument.to_string_lossy();
2304        if argument.contains('\0') {
2305            return Err("native instance launch argument is invalid".to_owned());
2306        }
2307        if argument.len() > INSTANCE_LAUNCH_ARG_MAX_BYTES {
2308            return Err("native instance launch argument exceeds its bound".to_owned());
2309        }
2310        total_bytes = total_bytes.saturating_add(argument.len());
2311        if total_bytes > INSTANCE_LAUNCH_ARGS_TOTAL_MAX_BYTES {
2312            return Err("native instance launch argument payload exceeds its bound".to_owned());
2313        }
2314        if agent_id.as_str() == "claude"
2315            && RESERVED_CLAUDE_LAUNCH_FLAGS.iter().any(|reserved| {
2316                argument == *reserved
2317                    || (reserved.starts_with("--")
2318                        && argument
2319                            .strip_prefix(reserved)
2320                            .is_some_and(|suffix| suffix.starts_with('=')))
2321                    || (reserved.len() == 2
2322                        && argument
2323                            .strip_prefix(reserved)
2324                            .is_some_and(|suffix| {
2325                                !suffix.is_empty() && !suffix.starts_with('-')
2326                            }))
2327            })
2328        {
2329            return Err(
2330                "native instance launch arguments conflict with Claude session, resume, or prompt authority"
2331                    .to_owned(),
2332            );
2333        }
2334    }
2335    Ok(())
2336}
2337
2338/// True if `value` has the shape of a bearer credential rather than an
2339/// ordinary CLI flag, path, or session identifier.
2340///
2341/// Gate4Agent's own secrets are environment-only and never argv (see
2342/// `gate4agent/CLAUDE.md`), so this should not fire for anything this repo
2343/// itself constructs. It exists as defense-in-depth against a provider CLI
2344/// whose own argv convention accepts a credential positionally. The check is
2345/// deliberately keyword/prefix-based rather than an entropy heuristic: a
2346/// generic "long hex/base64 string" rule would also catch legitimate,
2347/// diagnostically valuable arguments such as a resume session UUID -- which
2348/// is also why [`has_prefixed_hex64_credential_shape`] requires the leading
2349/// `<prefix>_` before it will call a bare hex string a credential at all.
2350fn argument_looks_like_credential(value: &str) -> bool {
2351    const CREDENTIAL_PREFIXES: &[&str] = &["sk-", "sk_", "ghp_", "gho_", "ghs_", "xox", "bearer "];
2352    const CREDENTIAL_MARKERS: &[&str] = &[
2353        "apikey", "api_key", "api-key", "secret", "password", "passwd", "token=",
2354    ];
2355    let lower = value.to_ascii_lowercase();
2356    CREDENTIAL_PREFIXES
2357        .iter()
2358        .any(|prefix| lower.starts_with(prefix))
2359        || CREDENTIAL_MARKERS
2360            .iter()
2361            .any(|marker| lower.contains(marker))
2362        || has_prefixed_hex64_credential_shape(&lower)
2363}
2364
2365/// True if `value` is exactly a short lowercase-alphanumeric prefix (2-8
2366/// characters), an underscore, and 64 lowercase hex characters -- the shape
2367/// every gate4agent-owned or caller-owned bearer credential uses (e.g. the
2368/// hatchery operator token, `g4aho_` + 64 hex, or the H3B local-capability
2369/// token, `g4ah3_` + 64 hex), regardless of which prefix a particular caller
2370/// picks. A bare 64-hex digest with no prefix is deliberately excluded: a
2371/// commit hash, a SHA-256 checksum, or a session digest is legitimate,
2372/// diagnostically valuable argument text, not a credential.
2373fn has_prefixed_hex64_credential_shape(lower: &str) -> bool {
2374    let Some((prefix, digest)) = lower.split_once('_') else {
2375        return false;
2376    };
2377    (2..=8).contains(&prefix.len())
2378        && prefix
2379            .bytes()
2380            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
2381        && digest.len() == 64
2382        && digest
2383            .bytes()
2384            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
2385}
2386
2387/// Renders one provider-CLI argument for a log line: verbatim unless it
2388/// matches [`argument_looks_like_credential`], in which case it is replaced
2389/// with a fixed placeholder rather than printed.
2390fn redact_provider_argument(value: &OsStr) -> String {
2391    let text = value.to_string_lossy();
2392    if argument_looks_like_credential(&text) {
2393        "[redacted-credential-shaped-argument]".to_owned()
2394    } else {
2395        text.into_owned()
2396    }
2397}
2398
2399/// Renders a full provider-CLI argument list for a log line, redacting any
2400/// individual argument that looks like a credential.
2401fn redact_provider_arguments(values: &[OsString]) -> Vec<String> {
2402    values.iter().map(|value| redact_provider_argument(value)).collect()
2403}
2404
2405fn require_runtime_capability(
2406    policy: ProviderRuntimePolicy,
2407    capability: ProviderRuntimeCapability,
2408) -> Result<(), String> {
2409    if policy.admits(capability) {
2410        Ok(())
2411    } else {
2412        Err(format!(
2413            "provider runtime capability {capability:?} is not admitted"
2414        ))
2415    }
2416}
2417
2418fn should_attach_pty_provider_stream(policy: ProviderRuntimePolicy) -> bool {
2419    policy.semantic_readiness || policy.provider_session_identity
2420}
2421
2422fn should_probe_pty_identity(
2423    policy: ProviderRuntimePolicy,
2424    adapter: Option<&gate4agent_types::AdapterBinding>,
2425    authoritative_identity_present: bool,
2426    expected_adapter: &str,
2427) -> bool {
2428    !authoritative_identity_present
2429        && policy.semantic_readiness
2430        && policy.structured_prompt
2431        && policy.provider_session_identity
2432        && adapter.is_some_and(|adapter| adapter.id.as_str() == expected_adapter)
2433}
2434
2435fn prepare_fresh_pty_provider_session(
2436    adapter: Option<&gate4agent_types::AdapterBinding>,
2437    is_resume: bool,
2438    identity_permitted: bool,
2439    launch_extra_args: &mut Vec<OsString>,
2440) -> Option<ProviderSessionIdentity> {
2441    let adapter = adapter?;
2442    if is_resume || !identity_permitted || adapter.id.as_str() != "claude-code" {
2443        return None;
2444    }
2445    let identity = ProviderSessionIdentity {
2446        key: ProviderSessionKey::SessionId,
2447        id: Uuid::new_v4().to_string(),
2448        transcript_path: None,
2449    };
2450    launch_extra_args.push(OsString::from("--session-id"));
2451    launch_extra_args.push(OsString::from(&identity.id));
2452    Some(identity)
2453}
2454
2455fn drain_pty_provider(
2456    key: NativeSessionKey,
2457    provider: &mut OwnedPtyProvider,
2458    observations: &mut Vec<ObservationEnvelope>,
2459) {
2460    while let Some(event) = provider.pending_events.pop_front() {
2461        push_provider_observation(key, provider, event, observations);
2462    }
2463
2464    loop {
2465        let envelope = match provider.replay.pop_front() {
2466            Some(envelope) => Some(envelope),
2467            None => provider.receiver.try_recv().unwrap_or_default(),
2468        };
2469        let Some(envelope) = envelope else {
2470            break;
2471        };
2472        match envelope.event {
2473            PtyEvent::Output(data) => {
2474                let raw = provider.utf8.push(&data);
2475                if raw.is_empty() {
2476                    continue;
2477                }
2478                if provider.semantic_events {
2479                    if let Some(info) = provider.rate_limits.detect(&raw) {
2480                        push_provider_observation(
2481                            key,
2482                            provider,
2483                            rate_limit_event(info),
2484                            observations,
2485                        );
2486                    }
2487                }
2488                let identity = provider
2489                    .kimi_identity
2490                    .as_mut()
2491                    .and_then(|extractor| extractor.push(&raw));
2492                if let Some(identity) = identity {
2493                    if !provider.provider_session_started {
2494                        push_provider_observation(
2495                            key,
2496                            provider,
2497                            ProviderEvent::SessionStarted {
2498                                session_id: identity.id.clone(),
2499                                model: String::new(),
2500                                tools: Vec::new(),
2501                            },
2502                            observations,
2503                        );
2504                        provider.provider_session_started = true;
2505                    }
2506                    push_provider_observation(
2507                        key,
2508                        provider,
2509                        ProviderEvent::SessionIdentityObserved { identity },
2510                        observations,
2511                    );
2512                }
2513                if provider.semantic_events {
2514                    let messages = provider
2515                        .pipeline
2516                        .get_mut()
2517                        .unwrap_or_else(|poisoned| poisoned.into_inner())
2518                        .process(&raw);
2519                    for message in messages {
2520                        if let Some(event) = parsed_provider_event(message) {
2521                            push_provider_observation(key, provider, event, observations);
2522                        }
2523                    }
2524                }
2525            }
2526            PtyEvent::DataGap {
2527                from_sequence,
2528                to_sequence,
2529                ..
2530            } => {
2531                provider.utf8.clear();
2532                if let Some(extractor) = &mut provider.kimi_identity {
2533                    extractor.reset_stream();
2534                }
2535                provider
2536                    .pipeline
2537                    .get_mut()
2538                    .unwrap_or_else(|poisoned| poisoned.into_inner())
2539                    .clear();
2540                let missed = to_sequence
2541                    .checked_sub(from_sequence)
2542                    .and_then(|difference| difference.checked_add(1));
2543                if let Some((source_sequence, missed)) = missed.and_then(|missed| {
2544                    reserve_provider_gap_sequence(&mut provider.next_provider_sequence, missed)
2545                        .map(|source_sequence| (source_sequence, missed))
2546                }) {
2547                    observations.push(ObservationEnvelope {
2548                        operation_id: None,
2549                        instance_id: key.instance_id,
2550                        generation: key.generation,
2551                        observation: ControlObservation::ProviderGap {
2552                            source: provider.source.clone(),
2553                            source_sequence,
2554                            missed,
2555                        },
2556                    });
2557                }
2558            }
2559            PtyEvent::ReaderError { message } | PtyEvent::OperatorActionRequired { message } => {
2560                push_provider_observation(
2561                    key,
2562                    provider,
2563                    ProviderEvent::Error { message },
2564                    observations,
2565                );
2566            }
2567            PtyEvent::Started
2568            | PtyEvent::Resized(_)
2569            | PtyEvent::ForegroundProcess(_)
2570            | PtyEvent::SnapshotAvailable { .. }
2571            | PtyEvent::Exited { .. } => {}
2572        }
2573    }
2574}
2575
2576fn push_provider_observation(
2577    key: NativeSessionKey,
2578    provider: &mut OwnedPtyProvider,
2579    event: ProviderEvent,
2580    observations: &mut Vec<ObservationEnvelope>,
2581) {
2582    let sequence = provider.next_provider_sequence;
2583    provider.next_provider_sequence = provider.next_provider_sequence.saturating_add(1);
2584    observations.push(ObservationEnvelope {
2585        operation_id: None,
2586        instance_id: key.instance_id,
2587        generation: key.generation,
2588        observation: ControlObservation::ProviderEvent {
2589            source: provider.source.clone(),
2590            sequence,
2591            event,
2592        },
2593    });
2594}
2595
2596fn reserve_provider_gap_sequence(next_sequence: &mut u64, missed: u64) -> Option<u64> {
2597    if missed == 0 {
2598        return None;
2599    }
2600    let Some(source_sequence) = missed
2601        .checked_sub(1)
2602        .and_then(|offset| next_sequence.checked_add(offset))
2603    else {
2604        *next_sequence = u64::MAX;
2605        return None;
2606    };
2607    let Some(next) = source_sequence.checked_add(1) else {
2608        *next_sequence = u64::MAX;
2609        return None;
2610    };
2611    *next_sequence = next;
2612    Some(source_sequence)
2613}
2614
2615fn parsed_provider_event(message: ParsedMessage) -> Option<ProviderEvent> {
2616    match message.class {
2617        MessageClass::AiResponse => Some(ProviderEvent::Text {
2618            text: message.content,
2619            is_delta: message.metadata.is_partial,
2620        }),
2621        MessageClass::ThinkingIndicator => Some(ProviderEvent::Thinking {
2622            text: message.content,
2623        }),
2624        MessageClass::Error => Some(ProviderEvent::Error {
2625            message: message.content,
2626        }),
2627        MessageClass::PromptReady => Some(ProviderEvent::Ready),
2628        MessageClass::ToolApproval => Some(ProviderEvent::InteractionRequested {
2629            request_id: None,
2630            interaction_kind: ProviderInteractionKind::Approval,
2631            tool_name: message
2632                .metadata
2633                .tool_name
2634                .unwrap_or_else(|| "unknown".to_owned()),
2635            // A PTY screen has no structured title or option list to read
2636            // off it the way ACP's `session/request_permission` does --
2637            // this source has none, not a dropped one.
2638            title: None,
2639            prompt: message.content,
2640            options: Vec::new(),
2641            agent_id: None,
2642        }),
2643        MessageClass::InfoMessage
2644        | MessageClass::UiElement
2645        | MessageClass::UserEcho
2646        | MessageClass::Menu
2647        | MessageClass::Raw => None,
2648    }
2649}
2650
2651fn rate_limit_event(info: gate4agent::core::types::RateLimitInfo) -> ProviderEvent {
2652    ProviderEvent::RateLimited {
2653        limit_type: provider_rate_limit_kind(info.limit_type),
2654        resets_at: info.resets_at.map(|value| value.to_rfc3339()),
2655        usage_percent: info.usage_percent.map(|value| value.to_string()),
2656        raw_message: info.raw_message,
2657    }
2658}
2659
2660/// Map `gate4agent`'s `HostRequestDecision`/`HostDecisionAuthority` onto
2661/// this crate's wire-typed `ProviderHostRequestDecision`/
2662/// `ProviderHostDecisionAuthority` -- `gate4agent-types` cannot depend on
2663/// `gate4agent` (see that crate's own `CLAUDE.md`), so the conversion lives
2664/// here, the shell that already depends on both. A plain match, not
2665/// `format!("{:?}", ..)`: the wire carries the typed value itself.
2666fn provider_host_request_decision(decision: HostRequestDecision) -> ProviderHostRequestDecision {
2667    match decision {
2668        HostRequestDecision::Granted { by } => {
2669            ProviderHostRequestDecision::Granted { by: provider_host_decision_authority(by) }
2670        }
2671        HostRequestDecision::Denied { by } => {
2672            ProviderHostRequestDecision::Denied { by: provider_host_decision_authority(by) }
2673        }
2674        HostRequestDecision::Deferred => ProviderHostRequestDecision::Deferred,
2675    }
2676}
2677
2678fn provider_host_decision_authority(by: HostDecisionAuthority) -> ProviderHostDecisionAuthority {
2679    match by {
2680        HostDecisionAuthority::Gate => ProviderHostDecisionAuthority::Gate,
2681        HostDecisionAuthority::Policy => ProviderHostDecisionAuthority::Policy,
2682        HostDecisionAuthority::Operator => ProviderHostDecisionAuthority::Operator,
2683        HostDecisionAuthority::DeadlinePolicy => ProviderHostDecisionAuthority::DeadlinePolicy,
2684    }
2685}
2686
2687/// Map `gate4agent`'s `HostRequestOutcome` onto this crate's wire-typed
2688/// `ProviderHostRequestOutcome` -- same reason `provider_host_request_
2689/// decision` exists rather than a `From` impl on either side. Carried
2690/// through verbatim, the same convention `reason` already follows on this
2691/// mapping: bounding happens at `ProviderEvent::validate_ingress`
2692/// (`PROVIDER_EVENT_TEXT_MAX_BYTES`, rejecting rather than truncating), not
2693/// here.
2694fn provider_host_request_outcome(outcome: HostRequestOutcome) -> ProviderHostRequestOutcome {
2695    match outcome {
2696        HostRequestOutcome::Executed => ProviderHostRequestOutcome::Executed,
2697        HostRequestOutcome::Failed { error } => ProviderHostRequestOutcome::Failed { error },
2698    }
2699}
2700
2701/// Map the detector's own `RateLimitType` onto the wire-typed
2702/// `ProviderRateLimitKind`. A plain match, not `format!("{:?}", ..)`: the
2703/// wire carries the typed value itself, not a Debug-rendering of it.
2704fn provider_rate_limit_kind(
2705    limit_type: gate4agent::core::types::RateLimitType,
2706) -> ProviderRateLimitKind {
2707    use gate4agent::core::types::RateLimitType;
2708    match limit_type {
2709        RateLimitType::Session => ProviderRateLimitKind::Session,
2710        RateLimitType::Daily => ProviderRateLimitKind::Daily,
2711        RateLimitType::Weekly => ProviderRateLimitKind::Weekly,
2712        RateLimitType::Unknown => ProviderRateLimitKind::Unknown,
2713    }
2714}
2715
2716/// `mode_catalogue` reads the mode catalogue off `owned.session` for
2717/// transports that have one -- only `AcpSession::available_modes()` does
2718/// (see `provider_event`'s doc comment); `collect_provider_map`'s two
2719/// non-ACP call sites pass `|_| Vec::new()` since their `AgentEvent` stream
2720/// never carries `ModeChanged` in the first place.
2721fn collect_provider_map<S>(
2722    sessions: &mut BTreeMap<NativeSessionKey, OwnedProviderSession<S>>,
2723    observations: &mut Vec<ObservationEnvelope>,
2724    mode_catalogue: impl Fn(&S) -> Vec<SessionMode>,
2725) {
2726    for (key, owned) in sessions {
2727        let available_modes = mode_catalogue(&owned.session);
2728        drain_provider_stream(
2729            *key,
2730            &owned.source,
2731            &mut owned.events,
2732            &mut owned.pending_events,
2733            &mut owned.pending_provider_events,
2734            &mut owned.next_provider_sequence,
2735            Some(&mut owned.observed_exit_code),
2736            observations,
2737            &available_modes,
2738        );
2739    }
2740}
2741
2742/// Pushes one already-sequenced `ProviderEvent` onto `observations`, sharing
2743/// the same per-session `next_provider_sequence` counter regardless of which
2744/// of `drain_provider_stream`'s three sources (`pending_events` mapped
2745/// through `provider_event`, raw `pending_provider_events`, or the live
2746/// broadcast stream) produced it -- so sequence numbers stay contiguous
2747/// across all three.
2748fn push_sequenced_provider_event(
2749    key: NativeSessionKey,
2750    source: &ProviderSource,
2751    next_provider_sequence: &mut u64,
2752    observations: &mut Vec<ObservationEnvelope>,
2753    event: ProviderEvent,
2754) {
2755    let sequence = *next_provider_sequence;
2756    *next_provider_sequence = next_provider_sequence.saturating_add(1);
2757    observations.push(ObservationEnvelope {
2758        operation_id: None,
2759        instance_id: key.instance_id,
2760        generation: key.generation,
2761        observation: ControlObservation::ProviderEvent {
2762            source: source.clone(),
2763            sequence,
2764            event,
2765        },
2766    });
2767}
2768
2769fn drain_provider_stream(
2770    key: NativeSessionKey,
2771    source: &ProviderSource,
2772    events: &mut broadcast::Receiver<AgentEvent>,
2773    pending_events: &mut VecDeque<AgentEvent>,
2774    pending_provider_events: &mut VecDeque<ProviderEvent>,
2775    next_provider_sequence: &mut u64,
2776    mut observed_exit_code: Option<&mut Option<i32>>,
2777    observations: &mut Vec<ObservationEnvelope>,
2778    available_modes: &[SessionMode],
2779) {
2780    loop {
2781        // `pending_events` (seeded `AgentEvent`s, e.g. `SessionStart`) drains
2782        // first and fully, in order; only once it is empty does
2783        // `pending_provider_events` (seeded raw `ProviderEvent`s, e.g.
2784        // `SessionIdentityObserved`, with no `AgentEvent` counterpart to
2785        // carry them) get a turn, and only once THAT is empty does this fall
2786        // through to the live broadcast stream -- so anything seeded at the
2787        // spawn site always reaches `observations` ahead of anything the
2788        // provider itself emits afterwards, and in the exact relative order
2789        // the spawn site seeded it in.
2790        if let Some(event) = pending_events.pop_front() {
2791            match event {
2792                AgentEvent::Exited { code } => {
2793                    if let Some(exit_code) = observed_exit_code.as_deref_mut() {
2794                        *exit_code = Some(code);
2795                    }
2796                }
2797                event => {
2798                    if let Some(event) = provider_event(event, available_modes) {
2799                        push_sequenced_provider_event(
2800                            key,
2801                            source,
2802                            next_provider_sequence,
2803                            observations,
2804                            event,
2805                        );
2806                    }
2807                }
2808            }
2809            continue;
2810        }
2811        if let Some(event) = pending_provider_events.pop_front() {
2812            push_sequenced_provider_event(key, source, next_provider_sequence, observations, event);
2813            continue;
2814        }
2815        match events.try_recv() {
2816            Ok(AgentEvent::Exited { code }) => {
2817                if let Some(exit_code) = observed_exit_code.as_deref_mut() {
2818                    *exit_code = Some(code);
2819                }
2820            }
2821            Ok(event) => {
2822                if let Some(event) = provider_event(event, available_modes) {
2823                    push_sequenced_provider_event(
2824                        key,
2825                        source,
2826                        next_provider_sequence,
2827                        observations,
2828                        event,
2829                    );
2830                }
2831            }
2832            Err(broadcast::error::TryRecvError::Lagged(missed)) => {
2833                if let Some(source_sequence) =
2834                    reserve_provider_gap_sequence(next_provider_sequence, missed)
2835                {
2836                    observations.push(ObservationEnvelope {
2837                        operation_id: None,
2838                        instance_id: key.instance_id,
2839                        generation: key.generation,
2840                        observation: ControlObservation::ProviderGap {
2841                            source: source.clone(),
2842                            source_sequence,
2843                            missed,
2844                        },
2845                    });
2846                }
2847            }
2848            Err(broadcast::error::TryRecvError::Empty | broadcast::error::TryRecvError::Closed) => {
2849                break
2850            }
2851        }
2852    }
2853}
2854
2855fn collect_provider_exits<S>(
2856    sessions: &mut BTreeMap<NativeSessionKey, OwnedProviderSession<S>>,
2857    observations: &mut Vec<ObservationEnvelope>,
2858    finished: impl Fn(&S) -> bool,
2859) {
2860    let completed: Vec<_> = sessions
2861        .iter()
2862        .filter_map(|(key, owned)| {
2863            (owned.observed_exit_code.is_some() || finished(&owned.session)).then_some(*key)
2864        })
2865        .collect();
2866    for key in completed {
2867        let owned = sessions
2868            .remove(&key)
2869            .expect("completed provider key came from the owned session map");
2870        observations.push(ObservationEnvelope {
2871            operation_id: None,
2872            instance_id: key.instance_id,
2873            generation: key.generation,
2874            observation: ControlObservation::ProcessExited {
2875                exit_code: owned.observed_exit_code,
2876                final_terminal: None,
2877            },
2878        });
2879    }
2880}
2881
2882/// Prefix tags [`encode_rpc_request_id`] / [`decode_rpc_request_id`] use to
2883/// keep an `RpcId::Number` and an `RpcId::String` from colliding once both
2884/// are flattened into the bare `Option<String>` that
2885/// `ProviderEvent::InteractionRequested::request_id` and
2886/// `ProviderInteractionTarget::provider_request_id` carry.
2887const RPC_REQUEST_ID_NUMBER_PREFIX: &str = "number:";
2888const RPC_REQUEST_ID_STRING_PREFIX: &str = "string:";
2889
2890/// Encode a JSON-RPC id as the `request_id` string carried on
2891/// `ProviderEvent::InteractionRequested` -- minted once, in `provider_event`'s
2892/// `AgentEvent::RpcIncomingRequest` arm, the moment a `session/request_
2893/// permission` call is first reported `HostRequestDecision::Deferred`. Read
2894/// back by [`decode_rpc_request_id`] when a later `ResolveInteraction`
2895/// effect needs to find this exact pending request again in
2896/// `AcpSession::resolve_pending_request` (`gate4agent::acp::session`).
2897///
2898/// Tagged rather than a bare `to_string()`: an agent-issued
2899/// `RpcId::Number(42)` and `RpcId::String("42".into())` are different ids on
2900/// the wire and must not collide into the same encoded string.
2901fn encode_rpc_request_id(id: &RpcId) -> String {
2902    match id {
2903        RpcId::Number(number) => format!("{RPC_REQUEST_ID_NUMBER_PREFIX}{number}"),
2904        RpcId::String(value) => format!("{RPC_REQUEST_ID_STRING_PREFIX}{value}"),
2905    }
2906}
2907
2908/// Inverse of [`encode_rpc_request_id`]. `None` covers both an unrecognized
2909/// tag and a `number:` tag whose remainder does not parse as a `u64` --
2910/// either way, not an id this process ever minted, so there is nothing to
2911/// look up in `AcpSession`'s pending-request map.
2912fn decode_rpc_request_id(raw: &str) -> Option<RpcId> {
2913    if let Some(number) = raw.strip_prefix(RPC_REQUEST_ID_NUMBER_PREFIX) {
2914        return number.parse::<u64>().ok().map(RpcId::Number);
2915    }
2916    raw.strip_prefix(RPC_REQUEST_ID_STRING_PREFIX)
2917        .map(|value| RpcId::String(value.to_owned()))
2918}
2919
2920/// Resolve a `ControlEffect::ResolveInteraction` naming exactly why it
2921/// could not be routed, when it could not be -- see
2922/// `docs/gate4agent/plans/gate4agent-acp-control-plane-on-the-wire-2026-09-02.md`
2923/// §4a-§5, where this is called "the deferral organ, not the plumbing" that
2924/// was still missing.
2925///
2926/// `session` is `None` for every transport this crate owns other than a
2927/// live ACP session for `key` -- PTY and pipe sessions never defer a
2928/// `session/request_permission` call in the first place (only
2929/// `AcpSessionOptions::defer_permission_requests` does, and that field only
2930/// exists on `AcpSessionOptions`), so there is never anything for them to
2931/// resolve here.
2932fn resolve_acp_interaction_observation(
2933    session: Option<&AcpSession>,
2934    target: ProviderInteractionTarget,
2935    response: ProviderInteractionResponse,
2936) -> ControlObservation {
2937    let interaction_id = target.interaction_id;
2938    let fail = |message: String| ControlObservation::InteractionResolutionFailed {
2939        interaction_id,
2940        message,
2941    };
2942    let Some(session) = session else {
2943        return fail("semantic interaction resolution requires an ACP session".to_owned());
2944    };
2945    let Some(provider_request_id) = target.provider_request_id.as_deref() else {
2946        return fail("ACP interaction resolution requires a provider request id".to_owned());
2947    };
2948    let Some(id) = decode_rpc_request_id(provider_request_id) else {
2949        return fail(format!(
2950            "ACP interaction resolution request id {provider_request_id:?} is not a valid JSON-RPC id"
2951        ));
2952    };
2953    match resolve_acp_permission_interaction(session, &id, response) {
2954        Ok(()) => ControlObservation::InteractionResolutionCompleted { interaction_id },
2955        Err(message) => fail(message),
2956    }
2957}
2958
2959/// Route an operator's `ProviderInteractionResponse` for a deferred ACP
2960/// `session/request_permission` call into
2961/// `AcpSession::resolve_pending_request_as` (`gate4agent::acp::session`).
2962///
2963/// The operator states an intent, not an option id, and that is deliberate:
2964/// an ACP agent offers whatever subset of the four `PermissionOptionKind`
2965/// values it likes, and an `optionId` it never offered is ignored rather
2966/// than refused -- so a fabricated one would grant nothing while reporting
2967/// success. Selecting a REAL offered option is therefore
2968/// `AcpSession`'s job, since it is the side that holds the pending request's
2969/// own params; it walks the same preference order `HostPolicy` walks,
2970/// through one shared selector, so an approval means the same thing whether
2971/// policy or a human produced it. If the agent offered nothing in the
2972/// requested direction the answer is `Cancelled`, which every ACP agent
2973/// accepts as complete.
2974///
2975/// This is also why the wire verb carries a `ProviderInteractionResponse` --
2976/// the same approve/deny vocabulary a PTY interaction uses -- rather than an
2977/// ACP-specific option id: all three chains say the same thing to an
2978/// operator, and only the ACP path has to know what an option id is.
2979///
2980/// `Answer` never applies here: ACP `session/request_permission` only ever
2981/// offers allow/deny options, never a free-text one.
2982fn resolve_acp_permission_interaction(
2983    session: &AcpSession,
2984    id: &RpcId,
2985    response: ProviderInteractionResponse,
2986) -> Result<(), String> {
2987    let choice = match response {
2988        ProviderInteractionResponse::ApproveOnce => OperatorPermissionChoice::Approve,
2989        ProviderInteractionResponse::Deny => OperatorPermissionChoice::Reject,
2990        ProviderInteractionResponse::Answer { .. } => {
2991            return Err("ACP permission interactions do not accept free-text answers".to_owned())
2992        }
2993    };
2994    session.resolve_pending_request_as(id, choice).map_err(|error| error.to_string())
2995}
2996
2997/// Resolve a `ControlEffect::SetSessionMode` against a live ACP session's
2998/// own advertised mode catalogue, naming exactly why it could not be
2999/// routed when it could not be -- same refusal-by-name discipline as
3000/// [`resolve_acp_interaction_observation`].
3001///
3002/// There is no `supports_*` probe for session modes (unlike
3003/// `AcpSession::supports_session_list` and its siblings): the ACP
3004/// `sessionCapabilities` flags block carries no `modes` key at all, so the
3005/// mode catalogue seeded at handshake (`AcpSession::available_modes`) IS
3006/// the capability signal -- empty means the agent never advertised any
3007/// modes, non-empty-but-missing-this-id means it advertised modes but not
3008/// this one.
3009async fn set_acp_session_mode_observation(
3010    session: Option<&AcpSession>,
3011    mode_id: String,
3012) -> ControlObservation {
3013    let Some(session) = session else {
3014        return ControlObservation::SessionModeSetFailed {
3015            message: "session mode switch requires an ACP session".to_owned(),
3016        };
3017    };
3018    let catalogue = session.available_modes();
3019    if catalogue.is_empty() {
3020        return ControlObservation::SessionModeSetFailed {
3021            message: "the provider announces no session-mode capability".to_owned(),
3022        };
3023    }
3024    if !catalogue.iter().any(|mode| mode.id == mode_id) {
3025        return ControlObservation::SessionModeSetFailed {
3026            message: format!("the provider never offered mode {mode_id:?}"),
3027        };
3028    }
3029    match session.set_mode(&mode_id).await {
3030        Ok(()) => ControlObservation::SessionModeSet { mode_id },
3031        Err(error) => ControlObservation::SessionModeSetFailed {
3032            message: error.to_string(),
3033        },
3034    }
3035}
3036
3037/// Resolve a `ControlEffect::SetSessionConfigOption` against a live ACP
3038/// session's own advertised config-option catalogue -- same capability
3039/// reasoning as [`set_acp_session_mode_observation`] (no dedicated
3040/// `supports_*` probe; the catalogue seeded at handshake, `AcpSession::
3041/// config_options`, is the capability signal).
3042///
3043/// `value_json` arrives already validated as parseable JSON at the wire
3044/// boundary (`gate4agent-node-protocol`'s `deserialize_acp_config_value_
3045/// json`) and bounds-checked again at the engine
3046/// (`gate4agent_types::validate_session_config_value_json`), but is only
3047/// ever carried as text up to here -- `gate4agent-types` does not depend on
3048/// `serde_json`. Parsing it into the `serde_json::Value` `AcpSession::
3049/// set_config_option` actually takes is this function's job; the target
3050/// type is inferred from that call rather than named directly, so this
3051/// crate never needs its own `serde_json` dependency.
3052async fn set_acp_session_config_option_observation(
3053    session: Option<&AcpSession>,
3054    option_id: String,
3055    value_json: String,
3056) -> ControlObservation {
3057    let Some(session) = session else {
3058        return ControlObservation::SessionConfigOptionSetFailed {
3059            message: "session config-option switch requires an ACP session".to_owned(),
3060        };
3061    };
3062    let catalogue = session.config_options();
3063    if catalogue.is_empty() {
3064        return ControlObservation::SessionConfigOptionSetFailed {
3065            message: "the provider announces no session config-option capability".to_owned(),
3066        };
3067    }
3068    if !catalogue.iter().any(|option| option.id == option_id) {
3069        return ControlObservation::SessionConfigOptionSetFailed {
3070            message: format!("the provider never offered config option {option_id:?}"),
3071        };
3072    }
3073    let value = match value_json.parse() {
3074        Ok(value) => value,
3075        Err(error) => {
3076            return ControlObservation::SessionConfigOptionSetFailed {
3077                message: format!("session config option value is not valid JSON: {error}"),
3078            }
3079        }
3080    };
3081    match session.set_config_option(&option_id, value).await {
3082        Ok(()) => ControlObservation::SessionConfigOptionSet { option_id },
3083        Err(error) => ControlObservation::SessionConfigOptionSetFailed {
3084            message: error.to_string(),
3085        },
3086    }
3087}
3088
3089/// Resolve a `ControlEffect::SetSessionModel`. Unlike session modes and
3090/// config options, `AcpSession` exposes no setter at all for this --
3091/// `available_models`/`current_model_id` observe Grok's vendor `_x.ai/
3092/// models/update` catalogue, but no live capture has ever shown a
3093/// host-invocable RPC to request a switch (ACP proper has no `session/
3094/// set_model`, and no vendor extension for one has been verified). Refuses
3095/// by name rather than fabricate a call the crate documented it would
3096/// never invent -- see `ControlCommand::SetSessionModel`'s doc comment.
3097fn set_acp_session_model_observation(
3098    session: Option<&AcpSession>,
3099    model_id: String,
3100) -> ControlObservation {
3101    if session.is_none() {
3102        return ControlObservation::SessionModelSetFailed {
3103            message: "session model switch requires an ACP session".to_owned(),
3104        };
3105    }
3106    ControlObservation::SessionModelSetFailed {
3107        message: format!(
3108            "this provider offers no host-invocable model-switch method (requested model {model_id:?})"
3109        ),
3110    }
3111}
3112
3113/// Maps one `AgentEvent` onto the wire-typed `ProviderEvent`. `available_
3114/// modes` is used ONLY by the `AgentEvent::ModeChanged` arm -- it carries
3115/// the mode catalogue `AcpSession::available_modes()` read at handshake
3116/// (`session/new`), so a mode change reports the SAME catalogue the agent
3117/// actually offered, not just the id that changed. Every other arm ignores
3118/// it; passing `&[]` from a non-ACP transport (which never emits
3119/// `ModeChanged` in the first place -- see `update_to_event`'s
3120/// `CurrentModeUpdate` arm, `gate4agent`'s `src/acp/protocol.rs`) changes
3121/// nothing observable.
3122/// Maps `gate4agent`'s own `StopReason` onto the wire-typed
3123/// `ProviderStopReason` mirror -- see that type's own doc comment for why
3124/// this crate keeps a second copy rather than sharing one.
3125fn map_provider_stop_reason(reason: StopReason) -> ProviderStopReason {
3126    match reason {
3127        StopReason::EndTurn => ProviderStopReason::EndTurn,
3128        StopReason::MaxTokens => ProviderStopReason::MaxTokens,
3129        StopReason::MaxTurnRequests => ProviderStopReason::MaxTurnRequests,
3130        StopReason::Refusal => ProviderStopReason::Refusal,
3131        StopReason::Cancelled => ProviderStopReason::Cancelled,
3132        StopReason::Other(value) => ProviderStopReason::Other { value },
3133        StopReason::ProviderError { code, message, vendor_code } => {
3134            ProviderStopReason::ProviderError { code, message, vendor_code }
3135        }
3136    }
3137}
3138
3139fn provider_event(event: AgentEvent, available_modes: &[SessionMode]) -> Option<ProviderEvent> {
3140    match event {
3141        AgentEvent::SessionStart {
3142            session_id,
3143            model,
3144            tools,
3145        } => Some(ProviderEvent::SessionStarted {
3146            session_id,
3147            model,
3148            tools,
3149        }),
3150        AgentEvent::Text { text, is_delta } => Some(ProviderEvent::Text { text, is_delta }),
3151        AgentEvent::Thinking { text } => Some(ProviderEvent::Thinking { text }),
3152        AgentEvent::ToolStart { id, name, input } => Some(ProviderEvent::ToolStarted {
3153            id,
3154            name,
3155            input_json: input.to_string(),
3156            agent_id: None,
3157        }),
3158        AgentEvent::ToolResult {
3159            id,
3160            output,
3161            is_error,
3162            duration_ms,
3163            non_execution_kind,
3164        } => Some(ProviderEvent::ToolCompleted {
3165            id,
3166            output,
3167            is_error,
3168            duration_ms,
3169            agent_id: None,
3170            non_execution_kind,
3171        }),
3172        AgentEvent::TurnComplete {
3173            input_tokens,
3174            output_tokens,
3175            cache_read_tokens,
3176            cache_write_tokens,
3177            reasoning_tokens,
3178            context_window,
3179            is_cumulative,
3180        } => Some(ProviderEvent::TurnCompleted {
3181            usage: TokenUsage {
3182                input_tokens,
3183                output_tokens,
3184                cache_read_tokens,
3185                cache_write_tokens,
3186                reasoning_tokens,
3187                context_window,
3188            },
3189            is_cumulative,
3190        }),
3191        AgentEvent::ContextWindowUsage { usage } => {
3192            Some(ProviderEvent::ContextWindowUsage {
3193                usage: ProviderContextWindowUsage {
3194                    uncached_input_tokens: usage.uncached_input_tokens,
3195                    cache_read_tokens: usage.cache_read_tokens,
3196                    cache_write_tokens: usage.cache_write_tokens,
3197                    output_tokens: usage.output_tokens,
3198                    unattributed_tokens: usage.unattributed_tokens,
3199                    used_tokens: usage.used_tokens,
3200                    capacity_tokens: usage.capacity_tokens,
3201                },
3202            })
3203        }
3204        AgentEvent::SessionEnd {
3205            result,
3206            cost_usd,
3207            is_error,
3208            stop_reason,
3209        } => Some(ProviderEvent::SessionEnded {
3210            result,
3211            cost_usd: cost_usd.map(|cost| cost.to_string()),
3212            is_error,
3213            stop_reason: stop_reason.map(map_provider_stop_reason),
3214        }),
3215        AgentEvent::Error { message } => Some(ProviderEvent::Error { message }),
3216        // ACP-only: `acp::session::AcpSession::start_prompt` synthesizes
3217        // this locally when a `session/prompt` call ends without a success
3218        // response (an agent RPC error, the session closing mid-call, or
3219        // `prompt_timeout` elapsing) -- see that event's own doc comment.
3220        // `ProviderEvent::TurnInterrupted` carries no `reason` field (it
3221        // predates this source and is also used by a PTY-side interrupt
3222        // with no text of its own to attach), so the reason is logged here
3223        // rather than silently dropped -- this is the one place downstream
3224        // of the ACP session that ever sees it.
3225        AgentEvent::TurnInterrupted { reason } => {
3226            tracing::warn!(reason = %reason, "acp turn interrupted");
3227            Some(ProviderEvent::TurnInterrupted)
3228        }
3229        AgentEvent::PtyParsed(message) => parsed_provider_event(message),
3230        AgentEvent::PtyReady => Some(ProviderEvent::Ready),
3231        AgentEvent::PtyToolApproval {
3232            tool_name,
3233            description,
3234        } => Some(ProviderEvent::InteractionRequested {
3235            request_id: None,
3236            interaction_kind: ProviderInteractionKind::Approval,
3237            tool_name,
3238            // A PTY screen has no structured title or option list to read
3239            // off it the way ACP's `session/request_permission` does --
3240            // this source has none, not a dropped one.
3241            title: None,
3242            prompt: description.unwrap_or_default(),
3243            options: Vec::new(),
3244            agent_id: None,
3245        }),
3246        AgentEvent::RateLimit(info) => Some(rate_limit_event(info)),
3247        // A `session/request_permission` call the host left `Deferred` (see
3248        // `AcpSessionOptions::defer_permission_requests`) is the one host
3249        // request an operator can actually act on -- so, ONLY for that
3250        // first, deferred sighting of a given id, this becomes an
3251        // `InteractionRequested` carrying the id (`encode_rpc_request_id`)
3252        // instead of the audit-only `HostRequestObserved` every other host
3253        // request becomes. The SAME id's eventual `Granted`/`Denied`
3254        // (`HostRequestDecision`'s doc comment on `Deferred`) still falls
3255        // through to `HostRequestObserved` below, exactly as before -- see
3256        // `docs/gate4agent/plans/gate4agent-acp-control-plane-on-the-wire-2026-09-02.md`
3257        // §4a.2, which is what this replaces (`id: _`, the id silently
3258        // dropped, so an ACP permission request never became an
3259        // `InteractionRequested` at all).
3260        AgentEvent::RpcIncomingRequest {
3261            id,
3262            method,
3263            params,
3264            decision,
3265            // A `Deferred` sighting never carries a reason -- nothing has
3266            // decided this request yet (see `AgentEvent::
3267            // RpcIncomingRequest`'s own doc comment).
3268            reason: _,
3269            // Nothing has run yet either -- always `Executed` for a
3270            // `Deferred` sighting (see `HostRequestOutcome`'s own doc
3271            // comment).
3272            outcome: _,
3273        } if method == "session/request_permission"
3274            && matches!(decision, HostRequestDecision::Deferred) =>
3275        {
3276            let tool_call = params.as_ref().and_then(|params| params.get("toolCall"));
3277            let field = |name: &str| {
3278                tool_call
3279                    .and_then(|tool_call| tool_call.get(name))
3280                    .and_then(|value| value.as_str())
3281                    .filter(|value| !value.is_empty())
3282                    .map(str::to_owned)
3283            };
3284            // `kind` is the tool's CLASS (`execute`, `edit`, `read`, ...) and
3285            // `title` is the human sentence describing this particular call.
3286            // They are two different things and the operator needs both: the
3287            // class is what the node hashes into `tool_class` for the
3288            // observation, and the title is the actual question. Putting the
3289            // title in `tool_name` and leaving `prompt` empty -- which is
3290            // what this did -- showed the operator a correlation id and a
3291            // sentence-shaped tool name, and never the question itself.
3292            let title = field("title");
3293            // The agent's own offered options -- read straight off the top-
3294            // level `options` array `PermissionRequestParams::options`
3295            // names in `src/acp/protocol.rs` (`option_id`/`name`/`kind`,
3296            // each `PermissionOption` field's own verified wire name:
3297            // `optionId`/`name`/`kind`), not `toolCall` -- `options` is a
3298            // sibling of `toolCall` on the request, not nested under it.
3299            // `kind` is carried verbatim as the ACP wire's own snake_case
3300            // string (`allow_once`, `reject_always`, ...); nothing here
3301            // reinterprets it. Without this the operator is choosing
3302            // approve/deny from a list they cannot see -- survivable for
3303            // two options, a guess for three or more.
3304            let options: Vec<ProviderInteractionOption> = params
3305                .as_ref()
3306                .and_then(|params| params.get("options"))
3307                .and_then(|options| options.as_array())
3308                .map(|options| {
3309                    options
3310                        .iter()
3311                        .filter_map(|option| {
3312                            let option_id = option.get("optionId")?.as_str()?.to_owned();
3313                            let name = option.get("name")?.as_str()?.to_owned();
3314                            let kind = option.get("kind")?.as_str()?.to_owned();
3315                            Some(ProviderInteractionOption { option_id, name, kind })
3316                        })
3317                        .collect()
3318                })
3319                .unwrap_or_default();
3320            Some(ProviderEvent::InteractionRequested {
3321                request_id: Some(encode_rpc_request_id(&id)),
3322                interaction_kind: ProviderInteractionKind::Approval,
3323                tool_name: field("kind").unwrap_or(method),
3324                title,
3325                prompt: field("title").unwrap_or_default(),
3326                options,
3327                agent_id: None,
3328            })
3329        }
3330        AgentEvent::RpcIncomingRequest {
3331            id: _,
3332            method,
3333            params,
3334            decision,
3335            // `outcome` distinguishes a `Granted` request that ran cleanly
3336            // from one that was authorized and then failed WHILE EXECUTING
3337            // (`HostRequestOutcome::Failed` -- e.g. a `terminal/create`
3338            // spawn error; see that type's own doc comment). Carried
3339            // through, never dropped: an execution failure must reach the
3340            // operator as `Granted` + `Failed { error }`, not an
3341            // undifferentiated `Granted` that silently swallows the
3342            // failure text.
3343            outcome,
3344            reason,
3345        } => Some(ProviderEvent::HostRequestObserved {
3346            method,
3347            params_json: params.map(|value| value.to_string()).unwrap_or_default(),
3348            decision: provider_host_request_decision(decision),
3349            outcome: provider_host_request_outcome(outcome),
3350            reason,
3351        }),
3352        AgentEvent::RpcNotification { method, params } => {
3353            Some(ProviderEvent::UnrecognizedNotification {
3354                method,
3355                payload_json: params.to_string(),
3356            })
3357        }
3358        AgentEvent::Started { .. } | AgentEvent::Exited { .. } | AgentEvent::PtyRaw { .. } => None,
3359        AgentEvent::UserMessage { text, is_delta } => {
3360            Some(ProviderEvent::UserMessage { text, is_delta })
3361        }
3362        AgentEvent::Plan { steps } => Some(ProviderEvent::Plan {
3363            steps: steps.into_iter().map(provider_plan_step).collect(),
3364        }),
3365        AgentEvent::AvailableCommandsUpdate { commands } => {
3366            Some(ProviderEvent::AvailableCommandsUpdated {
3367                commands: commands
3368                    .into_iter()
3369                    .map(|command| ProviderAvailableCommand {
3370                        name: command.name,
3371                        description: command.description,
3372                        input_hint: command.input_hint,
3373                    })
3374                    .collect(),
3375            })
3376        }
3377        AgentEvent::ModeChanged { mode_id } => Some(ProviderEvent::ModeChanged {
3378            mode_id,
3379            available: available_modes.iter().cloned().map(provider_mode_info).collect(),
3380        }),
3381        AgentEvent::SessionInfoUpdate { title } => {
3382            Some(ProviderEvent::SessionInfoUpdated { title })
3383        }
3384        AgentEvent::UsageUpdate {
3385            used_tokens,
3386            context_window,
3387            cost_amount,
3388            cost_currency,
3389        } => Some(ProviderEvent::UsageUpdated {
3390            used_tokens,
3391            context_window,
3392            cost_amount: cost_amount.map(|amount| amount.to_string()),
3393            cost_currency,
3394        }),
3395        AgentEvent::ConfigOptionsUpdate { options } => Some(ProviderEvent::ConfigOptionsUpdated {
3396            options: options.into_iter().map(provider_config_option).collect(),
3397        }),
3398        // Grok vendor `_x.ai/*` extensions (see `gate4agent::acp::protocol::
3399        // parse_vendor_notification`) -- not yet bridged to `ProviderEvent`.
3400        // No `ProviderEvent` variant exists for any of these today; adding
3401        // one is a separate, larger change across this crate's validation
3402        // (`ProviderEventValidationError`), the observation pipeline, and
3403        // the TUI, not part of parsing the ACP wire itself.
3404        AgentEvent::ModelsUpdate { .. }
3405        | AgentEvent::ProviderModelChanged { .. }
3406        | AgentEvent::SettingsUpdate { .. }
3407        | AgentEvent::HookExecutionUpdate { .. }
3408        | AgentEvent::McpServersUpdate { .. }
3409        | AgentEvent::McpInitProgress { .. }
3410        | AgentEvent::McpInitialized { .. }
3411        | AgentEvent::AnnouncementsUpdate { .. } => None,
3412    }
3413}
3414
3415/// Map the ACP wire priority onto the typed `ProviderPlanPriority`. A
3416/// plain match, not `format!("{:?}", ..)` -- see `provider_rate_limit_kind`
3417/// for why: the wire carries the typed value itself.
3418fn provider_plan_priority(priority: gate4agent::core::types::PlanStepPriority) -> ProviderPlanPriority {
3419    use gate4agent::core::types::PlanStepPriority;
3420    match priority {
3421        PlanStepPriority::High => ProviderPlanPriority::High,
3422        PlanStepPriority::Medium => ProviderPlanPriority::Medium,
3423        PlanStepPriority::Low => ProviderPlanPriority::Low,
3424    }
3425}
3426
3427/// Map the ACP wire status onto the typed `ProviderPlanStatus`.
3428fn provider_plan_status(status: gate4agent::core::types::PlanStepStatus) -> ProviderPlanStatus {
3429    use gate4agent::core::types::PlanStepStatus;
3430    match status {
3431        PlanStepStatus::Pending => ProviderPlanStatus::Pending,
3432        PlanStepStatus::InProgress => ProviderPlanStatus::InProgress,
3433        PlanStepStatus::Completed => ProviderPlanStatus::Completed,
3434    }
3435}
3436
3437fn provider_plan_step(step: gate4agent::core::types::PlanStep) -> ProviderPlanStep {
3438    ProviderPlanStep {
3439        content: step.content,
3440        priority: provider_plan_priority(step.priority),
3441        status: provider_plan_status(step.status),
3442    }
3443}
3444
3445/// Maps one ACP `SessionMode` (`gate4agent::acp::protocol::SessionMode`,
3446/// `session/new`'s `modes.availableModes`) onto the wire-typed
3447/// `ProviderModeInfo` carried on `ProviderEvent::ModeChanged::available`.
3448fn provider_mode_info(mode: SessionMode) -> ProviderModeInfo {
3449    ProviderModeInfo {
3450        id: mode.id,
3451        name: mode.name,
3452        description: mode.description,
3453    }
3454}
3455
3456/// Map the ACP wire config-option kind onto the typed
3457/// `ProviderConfigOptionKind`.
3458fn provider_config_option_kind(
3459    kind: gate4agent::core::types::ConfigOptionKind,
3460) -> ProviderConfigOptionKind {
3461    use gate4agent::core::types::ConfigOptionKind;
3462    match kind {
3463        ConfigOptionKind::Select => ProviderConfigOptionKind::Select,
3464        ConfigOptionKind::Boolean => ProviderConfigOptionKind::Boolean,
3465        ConfigOptionKind::Unknown => ProviderConfigOptionKind::Unknown,
3466    }
3467}
3468
3469/// `gate4agent-types` is a pure data contract and does not depend on
3470/// `serde_json`, so the option's current value and each choice's value --
3471/// both `serde_json::Value` in `gate4agent::core::types::ConfigOptionInfo`
3472/// -- cross the boundary pre-serialized to JSON text, same convention as
3473/// `ToolStarted::input_json` above.
3474fn provider_config_option(option: gate4agent::core::types::ConfigOptionInfo) -> ProviderConfigOption {
3475    ProviderConfigOption {
3476        id: option.id,
3477        name: option.name,
3478        description: option.description,
3479        category: option.category,
3480        kind: provider_config_option_kind(option.kind),
3481        value_json: option.value.to_string(),
3482        choices: option
3483            .choices
3484            .into_iter()
3485            .map(|choice| ProviderConfigChoice {
3486                value_json: choice.value.to_string(),
3487                label: choice.label,
3488            })
3489            .collect(),
3490    }
3491}
3492
3493fn builtin_legacy_adapter_runtimes() -> AdapterRuntimeRegistry<CliTool> {
3494    // Each of the four fleet providers registers only the transport families
3495    // it actually declares in the built-in adapter registry -- Grok, for
3496    // instance, is ACP-only and has no `PtySemantic`/`Pipe` descriptor.
3497    // Absence of a family for a given provider is not an error; only a
3498    // duplicate registration is.
3499    let definitions = [
3500        ("claude-code", CliTool::ClaudeCode),
3501        ("codex", CliTool::Codex),
3502        ("kimi", CliTool::KimiCode),
3503        ("grok", CliTool::Grok),
3504    ];
3505    let mut runtimes = AdapterRuntimeRegistry::default();
3506    for (id, tool) in definitions {
3507        for family in [
3508            AdapterFamily::PtySemantic,
3509            AdapterFamily::Pipe,
3510            AdapterFamily::Acp,
3511        ] {
3512            let Some(binding) = builtin_adapter_registry().binding(family, id) else {
3513                continue;
3514            };
3515            runtimes
3516                .insert(family, binding.clone(), tool)
3517                .expect("built-in native adapter runtime must be unique");
3518        }
3519    }
3520
3521    runtimes
3522}
3523
3524fn terminal_frame(snapshot: PtyTerminalSnapshot, screen_state: PtyScreenState) -> TerminalFrame {
3525    TerminalFrame {
3526        sequence: snapshot.sequence,
3527        size: TerminalSize {
3528            rows: snapshot.size.rows,
3529            columns: snapshot.size.cols,
3530        },
3531        cursor_row: snapshot.cursor.0,
3532        cursor_column: snapshot.cursor.1,
3533        contents: snapshot.contents,
3534        formatted: snapshot.formatted,
3535        scrollback_formatted: snapshot.scrollback_formatted,
3536        alternate_screen: snapshot.alternate_screen,
3537        mouse_protocol_enabled: snapshot.mouse_protocol_enabled,
3538        mouse_protocol_encoding: match snapshot.mouse_protocol_encoding {
3539            PtyMouseProtocolEncoding::Default => TerminalMouseProtocolEncoding::Default,
3540            PtyMouseProtocolEncoding::Utf8 => TerminalMouseProtocolEncoding::Utf8,
3541            PtyMouseProtocolEncoding::Sgr => TerminalMouseProtocolEncoding::Sgr,
3542        },
3543        // Carried through unchanged from the PTY snapshot -- this crate does
3544        // not restamp it, see `TerminalFrame::produced_at_unix_ms`'s own doc.
3545        produced_at_unix_ms: snapshot.produced_at_unix_ms,
3546        screen_state,
3547        // Known at capture time: `PtyTerminalSnapshot::bracketed_paste` is
3548        // read off the same `vt100::Screen` as `contents`/`formatted`, so
3549        // `Some` here always means "sampled", never "unknown" -- see
3550        // `TerminalFrame::bracketed_paste`'s own doc for what `None` means.
3551        bracketed_paste: Some(snapshot.bracketed_paste),
3552    }
3553}
3554
3555/// Whether the cheap `terminal_sequence()` gate should skip the expensive
3556/// `terminal_state()` call outright -- true exactly when the sequence read
3557/// is no newer than what this session already captured. An `Err` from the
3558/// cheap read does NOT skip: it falls through so the real call is attempted
3559/// (and reports its own failure through the normal `terminal_state()`
3560/// error path), matching the pre-instrumentation behaviour of the
3561/// `matches!` this replaces.
3562fn terminal_state_capture_should_skip<E>(sequence: Result<u64, E>, last_captured: u64) -> bool {
3563    matches!(sequence, Ok(sequence) if sequence <= last_captured)
3564}
3565
3566/// Total wire-relevant byte size of one [`TerminalFrame`] -- `formatted`
3567/// plus every row of `scrollback_formatted` summed. This is exactly what
3568/// gets handed to the c2 relay/harness/operator wire per frame (`contents`
3569/// never leaves the node), which is why it is the number the frame-bytes
3570/// distribution reports.
3571fn terminal_frame_byte_len(frame: &TerminalFrame) -> u64 {
3572    let scrollback_bytes: usize = frame.scrollback_formatted.iter().map(Vec::len).sum();
3573    (frame.formatted.len() + scrollback_bytes) as u64
3574}
3575
3576fn canonical_foreground(
3577    agent_id: AgentId,
3578    observation: &PtyForegroundObservation,
3579) -> ForegroundProcess {
3580    let kind = if observation.readiness.process_name.as_deref() == Some(agent_id.as_str()) {
3581        ForegroundProcessKind::Agent { agent_id }
3582    } else if observation.readiness.is_shell {
3583        ForegroundProcessKind::Shell
3584    } else {
3585        ForegroundProcessKind::Other
3586    };
3587    ForegroundProcess {
3588        root_process_id: observation.root_pid,
3589        process_id: observation.observed_pid,
3590        process_name: observation.observed_process.clone(),
3591        kind,
3592    }
3593}
3594
3595fn completion_observation(
3596    operation_id: OperationId,
3597    instance_id: AgentInstanceId,
3598    generation: SessionGeneration,
3599    observation: ControlObservation,
3600) -> ObservationEnvelope {
3601    ObservationEnvelope {
3602        operation_id: Some(operation_id),
3603        instance_id,
3604        generation,
3605        observation,
3606    }
3607}
3608
3609async fn wait_for_readiness(
3610    session: &PtySession,
3611    spec: &AgentSpec,
3612    intent: ReadinessIntent,
3613    detect_startup_gates: bool,
3614) -> Result<ReadinessPermit, String> {
3615    let started = Instant::now();
3616    let (terminal, attachment) = attach_readiness_boundary(session)?;
3617    let mut receiver = attachment.receiver;
3618    let mut tracker = ReadinessTracker::new(spec, RuntimePlatform::current(), intent);
3619    let mut diagnostics = ReadinessDiagnostics {
3620        draft_signal: Some(spec.readiness.draft_signal),
3621        ..ReadinessDiagnostics::default()
3622    };
3623    seed_readiness_from_terminal(
3624        &terminal,
3625        &mut tracker,
3626        &mut diagnostics,
3627        elapsed_ms(started),
3628    )?;
3629    let interval = Duration::from_millis(spec.readiness.poll_interval_ms.max(1));
3630    let mut next_probe = Instant::now();
3631
3632    for event in attachment.replay {
3633        observe_readiness_event(
3634            &mut tracker,
3635            &mut diagnostics,
3636            event.event,
3637            elapsed_ms(started),
3638        )?;
3639        if detect_startup_gates {
3640            ensure_no_readiness_operator_gate(&diagnostics, spec)?;
3641            ensure_no_startup_operator_gate(session, spec)?;
3642        }
3643    }
3644
3645    loop {
3646        if detect_startup_gates {
3647            ensure_no_startup_operator_gate(session, spec)?;
3648        }
3649        if Instant::now() >= next_probe {
3650            let foreground = session
3651                .observe_foreground()
3652                .await
3653                .map_err(|error| error.to_string())?;
3654            diagnostics.observe_foreground(&foreground.readiness);
3655            tracker.observe_foreground(&foreground.readiness, elapsed_ms(started));
3656            next_probe = Instant::now() + interval;
3657        }
3658        tracker.poll(elapsed_ms(started));
3659        if readiness_complete(tracker.status(), &diagnostics)? {
3660            if detect_startup_gates {
3661                ensure_no_startup_operator_gate(session, spec)?;
3662            }
3663            return tracker
3664                .into_permit()
3665                .ok_or_else(|| "ready tracker did not issue a permit".to_owned());
3666        }
3667
3668        let wait = next_probe.saturating_duration_since(Instant::now());
3669        match tokio::time::timeout(wait, receiver.recv()).await {
3670            Ok(Ok(event)) => {
3671                if matches!(&event.event, PtyEvent::DataGap { .. }) {
3672                    let (terminal, attachment) = attach_readiness_boundary(session)?;
3673                    receiver = attachment.receiver;
3674                    tracker = ReadinessTracker::new(
3675                        spec,
3676                        RuntimePlatform::current(),
3677                        intent,
3678                    );
3679                    diagnostics = ReadinessDiagnostics {
3680                        draft_signal: Some(spec.readiness.draft_signal),
3681                        ..ReadinessDiagnostics::default()
3682                    };
3683                    seed_readiness_from_terminal(
3684                        &terminal,
3685                        &mut tracker,
3686                        &mut diagnostics,
3687                        elapsed_ms(started),
3688                    )?;
3689                    for retained in attachment.replay {
3690                        observe_readiness_event(
3691                            &mut tracker,
3692                            &mut diagnostics,
3693                            retained.event,
3694                            elapsed_ms(started),
3695                        )?;
3696                    }
3697                } else {
3698                    observe_readiness_event(
3699                        &mut tracker,
3700                        &mut diagnostics,
3701                        event.event,
3702                        elapsed_ms(started),
3703                    )?;
3704                }
3705                if detect_startup_gates {
3706                    ensure_no_readiness_operator_gate(&diagnostics, spec)?;
3707                    ensure_no_startup_operator_gate(session, spec)?;
3708                }
3709            }
3710            Ok(Err(error)) => return Err(error.to_string()),
3711            Err(_) => {
3712                tracker.poll(elapsed_ms(started));
3713            }
3714        }
3715        if readiness_complete(tracker.status(), &diagnostics)? {
3716            if detect_startup_gates {
3717                ensure_no_startup_operator_gate(session, spec)?;
3718            }
3719            return tracker
3720                .into_permit()
3721                .ok_or_else(|| "ready tracker did not issue a permit".to_owned());
3722        }
3723    }
3724}
3725
3726fn attach_readiness_boundary(
3727    session: &PtySession,
3728) -> Result<(PtyTerminalSnapshot, PtyAttachment), String> {
3729    let terminal = session.terminal_state().map_err(|error| error.to_string())?;
3730    let cursor = PtyReplayCursor {
3731        provider_revision: terminal.provider_revision.clone(),
3732        generation: terminal.generation,
3733        next_sequence: terminal.sequence.saturating_add(1).max(1),
3734    };
3735    let attachment = session
3736        .attach_events(cursor)
3737        .map_err(|error| error.to_string())?;
3738    Ok((terminal, attachment))
3739}
3740
3741fn seed_readiness_from_terminal(
3742    terminal: &PtyTerminalSnapshot,
3743    tracker: &mut ReadinessTracker<'_>,
3744    diagnostics: &mut ReadinessDiagnostics,
3745    elapsed_ms: u64,
3746) -> Result<(), String> {
3747    const ENABLE_BRACKETED_PASTE: &[u8] = b"\x1b[?2004h";
3748    if terminal.bracketed_paste {
3749        diagnostics.observe_output(ENABLE_BRACKETED_PASTE);
3750        tracker.observe_output(ENABLE_BRACKETED_PASTE, elapsed_ms);
3751    }
3752    if !terminal.formatted.is_empty() {
3753        diagnostics.observe_output(&terminal.formatted);
3754        tracker.observe_output(&terminal.formatted, elapsed_ms);
3755    }
3756    Ok(())
3757}
3758
3759const STARTUP_GATE_SETTLE_MS: u64 = 350;
3760const STARTUP_GATE_POLL_MS: u64 = 25;
3761/// Steady-state cadence for `NativeEffectShell::reclassify_foreground`.
3762///
3763/// `wait_for_readiness` already polls the foreground far tighter than this
3764/// during startup (`spec.readiness.poll_interval_ms`, 150ms by default),
3765/// because a session takes at most a few seconds to come up and getting
3766/// that window right matters. This constant is not that -- it governs the
3767/// STEADY STATE: a session that has been sitting non-`Ready` for a long
3768/// time, which is exactly the incident this module fixes (an update
3769/// screen with nobody watching it). A session that reaches `Ready` stops
3770/// being probed at all (see `foreground_probe_schedule`), so the cost of
3771/// this interval is bounded by the count of sessions that are NOT
3772/// `Ready`, never by output rate and never by total session count. One
3773/// process-tree walk a second for a handful of stuck sessions is ample.
3774const FOREGROUND_RECLASSIFY_INTERVAL: Duration = Duration::from_secs(1);
3775// Codex rust-v0.144.0 keeps Enter in newline mode for 120 ms after
3776// Windows paste-burst activity. Wait beyond that window only after the TUI
3777// visibly incorporates the deferred initial prompt.
3778const CODEX_PASTE_ENTER_SUPPRESSION_MS: u64 = 120;
3779const CODEX_POST_RENDER_MARGIN_MS: u64 = 30;
3780const CODEX_SESSION_STATUS_PROBE_TIMEOUT_MS: u64 = 5_000;
3781const KIMI_SESSION_STATUS_PROBE_TIMEOUT_MS: u64 = 5_000;
3782
3783async fn probe_fresh_codex_session_identity(
3784    session: &PtySession,
3785    spec: &AgentSpec,
3786) -> Result<Option<ProviderSessionIdentity>, String> {
3787    let permit = match wait_for_readiness(session, spec, ReadinessIntent::DraftPaste, true).await {
3788        Ok(permit) => permit,
3789        Err(_) => return Ok(None),
3790    };
3791    if wait_for_startup_operator_gate(session, spec).await.is_err() {
3792        return Ok(None);
3793    }
3794    let baseline = session
3795        .terminal_state()
3796        .map_err(|error| error.to_string())?;
3797    let mut extractor = CodexPtySessionIdentityExtractor::default();
3798    session
3799        .send_input_action(
3800            InputAction::AgentCommand(AgentCommand {
3801                agent_id: spec.id.clone(),
3802                name: "status".to_owned(),
3803                arguments: Vec::new(),
3804            }),
3805            permit,
3806        )
3807        .await
3808        .map_err(|error| format!("Codex /status identity probe failed: {error}"))?;
3809
3810    let deadline = Instant::now()
3811        + Duration::from_millis(
3812            spec.readiness
3813                .timeout_ms
3814                .min(CODEX_SESSION_STATUS_PROBE_TIMEOUT_MS)
3815                .max(1),
3816        );
3817    loop {
3818        let snapshot = session
3819            .terminal_state()
3820            .map_err(|error| error.to_string())?;
3821        if snapshot.sequence > baseline.sequence {
3822            if let Some(identity) = extractor.observe_screen(&snapshot.contents) {
3823                return Ok(Some(identity));
3824            }
3825        }
3826        if Instant::now() >= deadline {
3827            return Ok(None);
3828        }
3829        tokio::time::sleep(Duration::from_millis(STARTUP_GATE_POLL_MS)).await;
3830    }
3831}
3832
3833async fn probe_fresh_kimi_session_identity(
3834    session: &PtySession,
3835    spec: &AgentSpec,
3836) -> Result<Option<ProviderSessionIdentity>, String> {
3837    let permit = match wait_for_readiness(
3838        session,
3839        spec,
3840        ReadinessIntent::FollowupPrompt,
3841        true,
3842    )
3843    .await
3844    {
3845        Ok(permit) => permit,
3846        Err(_) => return Ok(None),
3847    };
3848    if wait_for_startup_operator_gate(session, spec).await.is_err() {
3849        return Ok(None);
3850    }
3851    let baseline = session
3852        .terminal_state()
3853        .map_err(|error| error.to_string())?;
3854    let mut extractor = KimiPtySessionIdentityExtractor::default();
3855    if let Some(identity) = extractor.observe_screen(&baseline.contents) {
3856        return Ok(Some(identity));
3857    }
3858    session
3859        .send_input_action(
3860            InputAction::SubmitPrompt(PromptPayload {
3861                text: "/status".to_owned(),
3862                framing: PromptFraming::BracketedPaste,
3863            }),
3864            permit,
3865        )
3866        .await
3867        .map_err(|error| format!("Kimi /status identity probe failed: {error}"))?;
3868
3869    let deadline = Instant::now()
3870        + Duration::from_millis(
3871            spec.readiness
3872                .timeout_ms
3873                .min(KIMI_SESSION_STATUS_PROBE_TIMEOUT_MS)
3874                .max(1),
3875        );
3876    loop {
3877        let snapshot = session
3878            .terminal_state()
3879            .map_err(|error| error.to_string())?;
3880        if snapshot.sequence > baseline.sequence {
3881            if let Some(identity) = extractor.observe_screen(&snapshot.contents) {
3882                return Ok(Some(identity));
3883            }
3884        }
3885        if Instant::now() >= deadline {
3886            return Ok(None);
3887        }
3888        tokio::time::sleep(Duration::from_millis(STARTUP_GATE_POLL_MS)).await;
3889    }
3890}
3891
3892async fn deliver_pending_initial_prompt(
3893    session: &mut PtySession,
3894    spec: &AgentSpec,
3895) -> Result<(), String> {
3896    if session.pending_followup_prompt().is_none() {
3897        return Ok(());
3898    }
3899    let mut permit =
3900        wait_for_readiness(session, spec, ReadinessIntent::FollowupPrompt, true).await?;
3901    wait_for_startup_operator_gate(session, spec).await?;
3902    let render_confirmed_submit = spec.id.as_str() == "claude"
3903        || (RuntimePlatform::current() == RuntimePlatform::Windows
3904            && spec.id.as_str() == "codex");
3905    if render_confirmed_submit {
3906        let prompt = session
3907            .pending_followup_prompt()
3908            .ok_or_else(|| "deferred initial prompt disappeared before paste".to_owned())?
3909            .to_owned();
3910        let baseline = session
3911            .terminal_state()
3912            .map_err(|error| error.to_string())?;
3913        let inserted = session
3914            .insert_pending_followup_prompt(PromptFraming::BracketedPaste, &permit)
3915            .await
3916            .map_err(|error| error.to_string())?;
3917        if !inserted {
3918            return Err("deferred initial prompt was not inserted".to_owned());
3919        }
3920        wait_for_prompt_render(
3921            session,
3922            spec,
3923            &prompt,
3924            &baseline,
3925            spec.readiness.timeout_ms,
3926        )
3927        .await?;
3928        if RuntimePlatform::current() == RuntimePlatform::Windows && spec.id.as_str() == "codex" {
3929            tokio::time::sleep(Duration::from_millis(
3930                CODEX_PASTE_ENTER_SUPPRESSION_MS + CODEX_POST_RENDER_MARGIN_MS,
3931            ))
3932            .await;
3933        }
3934        permit = wait_for_readiness(session, spec, ReadinessIntent::FollowupPrompt, true).await?;
3935        wait_for_startup_operator_gate(session, spec).await?;
3936    }
3937    ensure_no_startup_operator_gate(session, spec)?;
3938    let submitted = session
3939        .submit_pending_followup(PromptFraming::BracketedPaste, permit)
3940        .await
3941        .map_err(|error| error.to_string())?;
3942    if !submitted {
3943        return Err("deferred initial prompt disappeared before delivery".to_owned());
3944    }
3945    Ok(())
3946}
3947
3948async fn wait_for_prompt_render(
3949    session: &PtySession,
3950    spec: &AgentSpec,
3951    prompt: &str,
3952    baseline: &PtyTerminalSnapshot,
3953    timeout_ms: u64,
3954) -> Result<(), String> {
3955    let probe = prompt_render_probe(&gate4agent_types::sanitize_prompt_text(prompt));
3956    let deadline = Instant::now() + Duration::from_millis(timeout_ms.max(1));
3957    loop {
3958        let snapshot = session.terminal_state().map_err(|error| error.to_string())?;
3959        if let Some(gate) = startup_operator_gate(&snapshot.contents) {
3960            return Err(startup_operator_error(spec, &gate));
3961        }
3962        if prompt_rendered(&snapshot, baseline, &probe) {
3963            return Ok(());
3964        }
3965        if Instant::now() >= deadline {
3966            let tail = terminal_tail(&snapshot.contents);
3967            let compact_tail = compact_alphanumeric(&tail);
3968            let baseline_tail = terminal_tail(&baseline.contents).to_ascii_lowercase();
3969            let normalized_tail = tail.to_ascii_lowercase();
3970            let retained = render_ack_event_summary(session, baseline.sequence);
3971            let foreground = session.observe_foreground().await.ok();
3972            let foreground_name = foreground
3973                .as_ref()
3974                .and_then(|observation| observation.readiness.process_name.as_deref())
3975                .map(safe_process_label)
3976                .unwrap_or_else(|| "none".to_owned());
3977            let child_live = retained.exit_code.is_none() && foreground.is_some();
3978            return Err(format!(
3979                "agent '{}' initial prompt paste was not rendered before submit; Enter was not sent (baseline_sequence={} current_sequence={} sequence_delta={} cursor_changed={} bracketed_baseline={} bracketed_current={} tail_chars={} probe_chars={} probe_match={} placeholder_baseline={} placeholder_current={} child_live={} foreground={} retained_output={} retained_foreground={} retained_snapshots={} retained_resized={} retained_gaps={} retained_reader_errors={} retained_operator_actions={} retained_exit_code={} output_flags={})",
3980                spec.id,
3981                baseline.sequence,
3982                snapshot.sequence,
3983                snapshot.sequence.saturating_sub(baseline.sequence),
3984                snapshot.cursor != baseline.cursor,
3985                baseline.bracketed_paste,
3986                snapshot.bracketed_paste,
3987                tail.chars().count(),
3988                probe.chars().count(),
3989                !probe.is_empty() && compact_tail.contains(&probe),
3990                paste_placeholder_visible(&baseline_tail),
3991                paste_placeholder_visible(&normalized_tail),
3992                child_live,
3993                foreground_name,
3994                retained.output,
3995                retained.foreground,
3996                retained.snapshots,
3997                retained.resized,
3998                retained.gaps,
3999                retained.reader_errors,
4000                retained.operator_actions,
4001                retained
4002                    .exit_code
4003                    .map_or_else(|| "none".to_owned(), |code| code.to_string()),
4004                if retained.output_flags.is_empty() {
4005                    "none".to_owned()
4006                } else {
4007                    retained.output_flags.join(",")
4008                },
4009            ));
4010        }
4011        tokio::time::sleep(Duration::from_millis(STARTUP_GATE_POLL_MS)).await;
4012    }
4013}
4014
4015#[derive(Default)]
4016struct RenderAckEventSummary {
4017    output: usize,
4018    foreground: usize,
4019    snapshots: usize,
4020    resized: usize,
4021    gaps: usize,
4022    reader_errors: usize,
4023    operator_actions: usize,
4024    exit_code: Option<i32>,
4025    output_flags: Vec<&'static str>,
4026}
4027
4028fn render_ack_event_summary(session: &PtySession, baseline_sequence: u64) -> RenderAckEventSummary {
4029    let mut summary = RenderAckEventSummary::default();
4030    let Ok(attachment) = session.attach_retained_events() else {
4031        return summary;
4032    };
4033    for envelope in attachment
4034        .replay
4035        .into_iter()
4036        .filter(|envelope| envelope.sequence > baseline_sequence)
4037    {
4038        match envelope.event {
4039            PtyEvent::Output(bytes) => {
4040                summary.output = summary.output.saturating_add(1);
4041                observe_render_ack_output_flags(&mut summary.output_flags, &bytes);
4042            }
4043            PtyEvent::ForegroundProcess(_) => {
4044                summary.foreground = summary.foreground.saturating_add(1);
4045            }
4046            PtyEvent::SnapshotAvailable { .. } => {
4047                summary.snapshots = summary.snapshots.saturating_add(1);
4048            }
4049            PtyEvent::Resized(_) => {
4050                summary.resized = summary.resized.saturating_add(1);
4051            }
4052            PtyEvent::DataGap { .. } => {
4053                summary.gaps = summary.gaps.saturating_add(1);
4054            }
4055            PtyEvent::ReaderError { .. } => {
4056                summary.reader_errors = summary.reader_errors.saturating_add(1);
4057            }
4058            PtyEvent::OperatorActionRequired { .. } => {
4059                summary.operator_actions = summary.operator_actions.saturating_add(1);
4060            }
4061            PtyEvent::Exited { code } => summary.exit_code = Some(code),
4062            PtyEvent::Started => {}
4063        }
4064    }
4065    summary
4066}
4067
4068fn observe_render_ack_output_flags(flags: &mut Vec<&'static str>, bytes: &[u8]) {
4069    let normalized = String::from_utf8_lossy(bytes).to_ascii_lowercase();
4070    for (label, marker) in [
4071        ("error", "error"),
4072        ("panic", "panic"),
4073        ("fatal", "fatal"),
4074        ("login", "login"),
4075        ("auth", "auth"),
4076        ("permission", "permission"),
4077        ("rate-limit", "rate limit"),
4078        ("usage-limit", "usage limit"),
4079        ("update", "update"),
4080        ("working", "working"),
4081        ("thinking", "thinking"),
4082    ] {
4083        if normalized.contains(marker) && !flags.contains(&label) {
4084            flags.push(label);
4085        }
4086    }
4087}
4088
4089fn safe_process_label(process_name: &str) -> String {
4090    process_name
4091        .chars()
4092        .take(64)
4093        .map(|character| {
4094            if character.is_ascii_alphanumeric() || matches!(character, '.' | '_' | '-') {
4095                character
4096            } else {
4097                '?'
4098            }
4099        })
4100        .collect()
4101}
4102
4103fn prompt_rendered(
4104    snapshot: &PtyTerminalSnapshot,
4105    baseline: &PtyTerminalSnapshot,
4106    probe: &str,
4107) -> bool {
4108    if snapshot.sequence <= baseline.sequence {
4109        return false;
4110    }
4111    let tail = terminal_tail(&snapshot.contents);
4112    let compact = compact_alphanumeric(&tail);
4113    if !probe.is_empty() && compact.contains(probe) {
4114        return true;
4115    }
4116    let normalized_tail = tail.to_ascii_lowercase();
4117    let normalized_baseline = terminal_tail(&baseline.contents).to_ascii_lowercase();
4118    paste_placeholder_visible(&normalized_tail)
4119        && !paste_placeholder_visible(&normalized_baseline)
4120}
4121
4122fn paste_placeholder_visible(normalized_tail: &str) -> bool {
4123    // Codex collapses larger pastes as `[Pasted Content ...]`; Claude 2.1.223
4124    // uses `[Pasted text #N ...]`. Treat only those vendor-owned render
4125    // markers as proof that the TUI consumed the bracketed paste.
4126    normalized_tail.contains("[pasted content")
4127        || normalized_tail.contains("[pasted text #")
4128}
4129
4130fn terminal_tail(contents: &str) -> String {
4131    let mut lines = contents.lines().rev().take(12).collect::<Vec<_>>();
4132    lines.reverse();
4133    lines.join("\n")
4134}
4135
4136fn prompt_render_probe(prompt: &str) -> String {
4137    let compact = compact_alphanumeric(prompt);
4138    let chars = compact.chars().collect::<Vec<_>>();
4139    chars[chars.len().saturating_sub(32)..].iter().collect()
4140}
4141
4142fn compact_alphanumeric(value: &str) -> String {
4143    value
4144        .chars()
4145        .filter(|character| character.is_alphanumeric())
4146        .flat_map(char::to_lowercase)
4147        .collect()
4148}
4149
4150async fn wait_for_startup_operator_gate(
4151    session: &PtySession,
4152    spec: &AgentSpec,
4153) -> Result<(), String> {
4154    let deadline = Instant::now() + Duration::from_millis(STARTUP_GATE_SETTLE_MS);
4155    loop {
4156        ensure_no_startup_operator_gate(session, spec)?;
4157        let now = Instant::now();
4158        if now >= deadline {
4159            return Ok(());
4160        }
4161        tokio::time::sleep(
4162            deadline
4163                .saturating_duration_since(now)
4164                .min(Duration::from_millis(STARTUP_GATE_POLL_MS)),
4165        )
4166        .await;
4167    }
4168}
4169
4170/// Refuses a prompt submission while a known operator gate is on screen.
4171///
4172/// Deliberately checks gates ONLY, never `screen_failure`. A crash banner
4173/// means "the CLI fell over" solely before the agent has rendered its own
4174/// UI; afterwards the identical bytes mean "the agent is showing you a
4175/// crash" -- a test it ran, a traceback it was asked to explain. What
4176/// separates the two is not the text but WHEN it appeared, and this
4177/// function has no way to date its evidence: it holds a screen snapshot
4178/// and a spec, and is called from seven sites spanning both the startup
4179/// window and long-running follow-up delivery. A check that cannot tell
4180/// those apart would refuse work from a perfectly healthy session every
4181/// time its pane happened to show a failing subprocess.
4182///
4183/// The `Failing` classification is not lost by this -- it is computed
4184/// where the window IS known (`collect_terminal_frames`, gated on
4185/// `OwnedPtySession::ever_reached_ready`), published upstream, and enforced
4186/// by the callers that gate dispatch on `PtyScreenState`. Gates are
4187/// different in kind and stay here: a trust or update prompt is legitimate
4188/// at any point in a session's life, so it needs no window to be believed.
4189fn ensure_no_startup_operator_gate(session: &PtySession, spec: &AgentSpec) -> Result<(), String> {
4190    let snapshot = session.terminal_state().map_err(|error| error.to_string())?;
4191    match startup_operator_gate(&snapshot.contents) {
4192        Some(gate) => Err(startup_operator_error(spec, &gate)),
4193        None => Ok(()),
4194    }
4195}
4196
4197fn startup_operator_error(spec: &AgentSpec, gate: &OperatorGateState) -> String {
4198    format!(
4199        "agent '{}' requires operator action at startup ({gate}); initial prompt was not submitted",
4200        spec.id
4201    )
4202}
4203
4204fn ensure_no_readiness_operator_gate(
4205    diagnostics: &ReadinessDiagnostics,
4206    spec: &AgentSpec,
4207) -> Result<(), String> {
4208    match &diagnostics.operator_gate {
4209        Some(gate) => Err(startup_operator_error(spec, gate)),
4210        None => Ok(()),
4211    }
4212}
4213
4214/// Whitespace-collapse and lowercase raw PTY screen text before pattern
4215/// matching. Shared by `startup_operator_gate` and `screen_failure` so the
4216/// two agree on what "the same phrase" means -- if they normalized
4217/// independently, a line-wrap difference or a run of extra spaces could
4218/// make one matcher see a phrase the other misses for no reason connected
4219/// to the actual screen content.
4220fn normalize_screen_text(contents: &str) -> String {
4221    contents
4222        .split_whitespace()
4223        .collect::<Vec<_>>()
4224        .join(" ")
4225        .to_ascii_lowercase()
4226}
4227
4228/// Phrases showing a package manager actively installing or updating a
4229/// package. Generic across npm/pip/yarn/pnpm rather than any one vendor's
4230/// package name, so a wrapper script fronting any provider CLI is
4231/// recognized the same way -- see the `PACKAGE_MANAGER_UPDATE_COMPLETION_MARKERS`
4232/// doc below for why a bare occurrence of one of these alone is not enough.
4233const PACKAGE_MANAGER_INSTALL_MARKERS: &[&str] = &[
4234    "npm install -g",
4235    "npm i -g",
4236    "npm update -g",
4237    "pip install --upgrade",
4238    "pip install -u",
4239    "yarn global add",
4240    "pnpm add -g",
4241];
4242
4243/// Phrases showing the install/update above reached a terminal state and
4244/// wants the CLI relaunched. Required to co-occur with a marker from
4245/// `PACKAGE_MANAGER_INSTALL_MARKERS` so a screen that merely MENTIONS a
4246/// package-manager command (an agent explaining how to install something,
4247/// for instance) never matches on the install phrase alone.
4248const PACKAGE_MANAGER_UPDATE_COMPLETION_MARKERS: &[&str] = &[
4249    "update ran successfully",
4250    "please restart",
4251    "update complete",
4252    "updated successfully",
4253];
4254
4255/// Builds the classified `OperatorGateState` for a matched `kind`/`subject`
4256/// pair, filling `input`/`options` from whatever `parse_operator_gate_options`
4257/// can read off the RAW (un-normalized, multi-line) screen text. Every
4258/// `startup_operator_gate` match arm goes through this one function so
4259/// option-list recognition is uniform across every gate kind rather than
4260/// hand-wired per branch -- a kind this module has not yet seen an option
4261/// layout for simply gets `OperatorGateInput::Unknown` and no options,
4262/// exactly like a kind whose options this parser fails to recognize on a
4263/// given screen; there is no special-casing between "not implemented yet"
4264/// and "not recognized this time".
4265fn operator_gate(kind: OperatorGateKind, subject: OperatorGateSubject, contents: &str) -> OperatorGateState {
4266    let (input, options) = parse_operator_gate_options(contents);
4267    OperatorGateState::new(kind)
4268        .with_subject(subject)
4269        .with_options(input, options)
4270}
4271
4272fn startup_operator_gate(contents: &str) -> Option<OperatorGateState> {
4273    let normalized = normalize_screen_text(contents);
4274    if [
4275        "trust this folder",
4276        "trust the files in this folder",
4277        "trust the contents of this directory",
4278        "do you trust this directory",
4279    ]
4280    .iter()
4281    .any(|marker| normalized.contains(marker))
4282    {
4283        return Some(operator_gate(
4284            OperatorGateKind::WorkspaceTrust,
4285            OperatorGateSubject::Directory { path: None },
4286            contents,
4287        ));
4288    }
4289    if normalized.contains("quick safety check")
4290        && (normalized.contains("yes, i trust this folder")
4291            || normalized.contains("continue without these permissions"))
4292    {
4293        return Some(operator_gate(
4294            OperatorGateKind::WorkspaceTrust,
4295            OperatorGateSubject::Directory { path: None },
4296            contents,
4297        ));
4298    }
4299    // A CLI's own hook-trust prompt at startup (seen from Codex): a set of
4300    // shell hooks it discovered need to be reviewed/trusted before they are
4301    // allowed to run, distinct from `WorkspaceTrust` above -- that gate is
4302    // about trusting the PROJECT DIRECTORY, this one is about trusting
4303    // SHELL HOOKS the CLI found inside it, and an operator reading `kind`
4304    // should be able to tell which question is being asked. Required to
4305    // co-occur with the screen's own "decline" option rather than matching
4306    // on "hooks need review" alone, so an agent's ordinary narration that
4307    // merely uses the word "hooks" (explaining a git hook, a React hook, a
4308    // build hook) never matches: real narration essentially never also
4309    // contains the literal refusal phrasing "continue without trusting"
4310    // this same prompt renders. The number of hooks reported (which varies
4311    // run to run, and is not read into `subject`'s `count` -- no matcher
4312    // here parses it off the screen) plays no part in the match.
4313    if normalized.contains("hooks need review") && normalized.contains("continue without trusting")
4314    {
4315        return Some(operator_gate(
4316            OperatorGateKind::HookTrust,
4317            OperatorGateSubject::Hooks { count: None },
4318            contents,
4319        ));
4320    }
4321    if [
4322        "select authentication method",
4323        "choose how to authenticate",
4324        "no auth type is selected",
4325    ]
4326    .iter()
4327    .any(|marker| normalized.contains(marker))
4328    {
4329        return Some(operator_gate(
4330            OperatorGateKind::Authentication,
4331            OperatorGateSubject::Account,
4332            contents,
4333        ));
4334    }
4335    if normalized.contains("sign in")
4336        && (normalized.contains("openai")
4337            || normalized.contains("chatgpt")
4338            || normalized.contains("codex"))
4339    {
4340        return Some(operator_gate(
4341            OperatorGateKind::Authentication,
4342            OperatorGateSubject::Account,
4343            contents,
4344        ));
4345    }
4346    // Claude's own login-method chooser: a numbered list ("1. Claude ...",
4347    // "2. API usage billing", "3. 3rd-party platform ...") rendered under
4348    // "Select login method:". It shares neither "sign in" nor
4349    // "openai"/"chatgpt"/"codex" with the branch above, so that branch
4350    // never catches it. The phrase itself is specific enough (no ordinary
4351    // agent narration renders this exact prompt line) to stand alone,
4352    // matching the precedent set by "select authentication method" and
4353    // "choose how to authenticate" above.
4354    if normalized.contains("select login method") {
4355        return Some(operator_gate(
4356            OperatorGateKind::Authentication,
4357            OperatorGateSubject::Account,
4358            contents,
4359        ));
4360    }
4361    // Claude's OAuth wait screen: a URL to open in a browser plus a slot to
4362    // paste back the authorization code once that flow completes. Required
4363    // to co-occur with "paste code" (the screen's own field label) rather
4364    // than matching on "sign in" alone -- "sign in" by itself is common
4365    // enough in an agent's ordinary narration to be untrustworthy, the same
4366    // reasoning the branch above already applies via its own companion
4367    // words. No option list is rendered here -- it is one free-text slot,
4368    // not a choice from a list -- so `input` is set directly to
4369    // `TextEntry` rather than routed through `operator_gate`'s option-list
4370    // parser, which would find nothing on this screen shape and fall back
4371    // to `Unknown`.
4372    if normalized.contains("sign in") && normalized.contains("paste code") {
4373        return Some(
4374            OperatorGateState::new(OperatorGateKind::Authentication)
4375                .with_subject(OperatorGateSubject::Account)
4376                .with_options(OperatorGateInput::TextEntry, Vec::new()),
4377        );
4378    }
4379    if normalized.contains("kimi code update available")
4380        && normalized.contains("install update now")
4381    {
4382        return Some(operator_gate(
4383            OperatorGateKind::VendorUpdate,
4384            OperatorGateSubject::Unknown,
4385            contents,
4386        ));
4387    }
4388    // A wrapper script self-updating via a package manager before the real
4389    // CLI ever launches -- the case that produced the incident this module
4390    // fixes: an npm-driven wrapper ran an update to completion and printed
4391    // nothing that looked like the agent, while every consumer still saw a
4392    // live, `status: running` PTY. This shares `VendorUpdate` with the Kimi
4393    // in-app case just above on purpose, not by omission: both are "the CLI
4394    // is updating itself", the only difference is WHICH process drives it
4395    // (the agent's own composer vs. a wrapper script's package-manager
4396    // install), and an operator reading `kind` should see one meaning for
4397    // that fact regardless of which vendor's update mechanism produced it.
4398    if PACKAGE_MANAGER_INSTALL_MARKERS
4399        .iter()
4400        .any(|marker| normalized.contains(marker))
4401        && PACKAGE_MANAGER_UPDATE_COMPLETION_MARKERS
4402            .iter()
4403            .any(|marker| normalized.contains(marker))
4404    {
4405        return Some(operator_gate(
4406            OperatorGateKind::VendorUpdate,
4407            OperatorGateSubject::Unknown,
4408            contents,
4409        ));
4410    }
4411    if normalized.contains("choose the text style that looks best with your terminal") {
4412        return Some(operator_gate(
4413            OperatorGateKind::TerminalAppearance,
4414            OperatorGateSubject::Appearance,
4415            contents,
4416        ));
4417    }
4418    if normalized.contains("welcome to claude code for")
4419        && (normalized.contains("open files") || normalized.contains("selected lines"))
4420    {
4421        return Some(operator_gate(
4422            OperatorGateKind::Onboarding,
4423            OperatorGateSubject::Unknown,
4424            contents,
4425        ));
4426    }
4427    if normalized.contains("welcome to claude code")
4428        && (normalized.contains("press enter") || normalized.contains("enter to continue"))
4429    {
4430        return Some(operator_gate(
4431            OperatorGateKind::Onboarding,
4432            OperatorGateSubject::Unknown,
4433            contents,
4434        ));
4435    }
4436    if normalized.contains("migration") && normalized.contains("enter confirm") && normalized.contains("esc")
4437    {
4438        return Some(operator_gate(
4439            OperatorGateKind::ConfigurationMigration,
4440            OperatorGateSubject::Unknown,
4441            contents,
4442        ));
4443    }
4444    None
4445}
4446
4447/// Reads the recognized on-screen choice list, if any, off the RAW
4448/// (multi-line, un-normalized) screen text -- called uniformly by every
4449/// `startup_operator_gate` match arm through `operator_gate`. Recognizes
4450/// exactly two rendered shapes, both observed verbatim on a live stand:
4451///
4452/// - a NUMBERED list (Codex's hook-trust prompt): each option line starts,
4453///   after an optional leading cursor glyph (`›`) and whitespace, with
4454///   `N.`; `Some` lines from `parse_numbered_gate_option_line` win outright
4455///   over the arrow shape below, so a screen that happens to also contain an
4456///   arrow glyph elsewhere (a Codex composer prompt sharing the pane, say)
4457///   is still read as the numbered list it actually is.
4458/// - an ARROW list (Kimi's workspace-trust prompt): the currently selected
4459///   option carries a leading `❯`; the other options carry no glyph at all,
4460///   so they are told apart from the description line rendered under each
4461///   one (`"Enable project MCP servers. Remembered for this folder."` under
4462///   `"Trust this folder"`, for instance) by `parse_arrow_gate_option_line`'s
4463///   own filter -- see that function's doc comment for the exact rule.
4464///
4465/// Neither line is stable across CLIs, and this parser recognizes nothing
4466/// else: a screen matching neither shape returns `(Unknown, vec![])`, never
4467/// a guess built from partial matches.
4468fn parse_operator_gate_options(contents: &str) -> (OperatorGateInput, Vec<OperatorGateOption>) {
4469    let numbered: Vec<OperatorGateOption> = contents
4470        .lines()
4471        .filter_map(parse_numbered_gate_option_line)
4472        .take(OPERATOR_GATE_OPTIONS_MAX)
4473        .collect();
4474    if !numbered.is_empty() {
4475        return (OperatorGateInput::NumberedList, numbered);
4476    }
4477    let arrow: Vec<OperatorGateOption> = contents
4478        .lines()
4479        .filter_map(parse_arrow_gate_option_line)
4480        .take(OPERATOR_GATE_OPTIONS_MAX)
4481        .collect();
4482    if !arrow.is_empty() {
4483        return (OperatorGateInput::ArrowList, arrow);
4484    }
4485    (OperatorGateInput::Unknown, Vec::new())
4486}
4487
4488/// Parses one line of a numbered option list -- `"› 1. Review hooks"`,
4489/// `"  2. Trust all and continue"` -- into `(selected, text)`. `selected` is
4490/// true only when the line carries the leading `›` cursor glyph Codex draws
4491/// on the highlighted row; every other line in the same list has none.
4492/// Returns `None` for any line that, once a leading glyph is stripped, does
4493/// not start with `<digits>.` -- an instruction line like `"Press enter to
4494/// confirm or esc to go back"` is exactly this shape and is meant to fall
4495/// through untouched.
4496/// Cursor glyphs vendors draw ahead of the selected row of an option list.
4497/// Kept as one set shared by both list parsers: which glyph a vendor picks
4498/// says nothing about whether its list is numbered or marker-only, and
4499/// teaching one parser a glyph the other does not know is exactly how the
4500/// selected row went missing before.
4501const GATE_CURSOR_GLYPHS: [char; 2] = ['\u{203a}', '\u{276f}'];
4502
4503fn parse_numbered_gate_option_line(line: &str) -> Option<OperatorGateOption> {
4504    let trimmed = line.trim_start();
4505    // Vendors mark the cursor row of a NUMBERED list with the marker BEFORE
4506    // the number (`> 2. Dark mode`), and they do not agree on the glyph:
4507    // Codex draws U+203A, Claude draws U+276F, and both appear ahead of the
4508    // digit rather than ahead of the text. Recognizing only one of them cost
4509    // the whole row -- the cursor line failed to parse as an option at all,
4510    // so the list came back one item short and with nothing marked selected,
4511    // observed live on Claude's theme chooser and Codex's login chooser.
4512    let (selected, rest) = match trimmed.strip_prefix(GATE_CURSOR_GLYPHS) {
4513        Some(stripped) => (true, stripped.trim_start()),
4514        None => (false, trimmed),
4515    };
4516    let digits_end = rest.find(|character: char| !character.is_ascii_digit()).unwrap_or(0);
4517    if digits_end == 0 {
4518        return None;
4519    }
4520    let text = rest[digits_end..].strip_prefix('.')?.trim();
4521    if text.is_empty() {
4522        return None;
4523    }
4524    Some(OperatorGateOption {
4525        semantics: classify_operator_gate_option_semantics(text),
4526        text: text.to_owned(),
4527        selected,
4528    })
4529}
4530
4531/// Parses one line of an arrow-navigated option list -- `"❯ Don't trust"`,
4532/// `"  Trust this folder"` -- into `(selected, text)`. `selected` is true
4533/// only when the line carries the leading `❯` cursor glyph.
4534///
4535/// Distinguishing an option TITLE from the description/header/instruction
4536/// prose around it (`"Enable project MCP servers. Remembered for this
4537/// folder."` under `"Trust this folder"`; `"Do you trust the files in this
4538/// folder?"` above it; `"Press enter to confirm or esc to go back"` below a
4539/// DIFFERENT screen's numbered list entirely) cannot rely on the glyph
4540/// alone, since only the currently-selected title ever carries one. A
4541/// candidate line is accepted as an option only if EITHER it carries the
4542/// `❯` marker (the screen's own cursor is unambiguous proof this is a real,
4543/// currently-selected option, whatever its wording), OR it both looks like
4544/// a short menu label rather than a sentence (no `.`, `?`, `!`, or `:`
4545/// anywhere in it -- a description or instruction is a full sentence
4546/// carrying one of these; an option label like `"Trust this folder"` or
4547/// `"Don't trust"` never does) AND its own text uses one of the recognized
4548/// option verbs (`classify_operator_gate_option_semantics` returns
4549/// something other than `Unknown`) -- an unmarked line whose wording this
4550/// module does not recognize as a choice-verb is left as prose rather than
4551/// guessed into an option with `semantics: Unknown`. The arrow-key legend
4552/// itself (`"↑↓ navigate · Enter select · Esc exit"`) is excluded
4553/// explicitly rather than relying on either rule catching it.
4554fn parse_arrow_gate_option_line(line: &str) -> Option<OperatorGateOption> {
4555    let trimmed = line.trim();
4556    if trimmed.is_empty()
4557        || trimmed
4558            .chars()
4559            .any(|character| matches!(character, '.' | '?' | '!' | ':'))
4560    {
4561        return None;
4562    }
4563    let lower = trimmed.to_ascii_lowercase();
4564    if lower.contains('\u{2191}') || lower.contains('\u{2193}') || lower.contains("navigate") {
4565        return None;
4566    }
4567    let (selected, rest) = match trimmed.strip_prefix(GATE_CURSOR_GLYPHS) {
4568        Some(stripped) => (true, stripped.trim()),
4569        None => (false, trimmed),
4570    };
4571    if rest.is_empty() || !rest.chars().any(|character| character.is_alphabetic()) {
4572        return None;
4573    }
4574    let semantics = classify_operator_gate_option_semantics(rest);
4575    if !selected && semantics == OperatorGateOptionSemantics::Unknown {
4576        return None;
4577    }
4578    Some(OperatorGateOption {
4579        semantics,
4580        text: rest.to_owned(),
4581        selected,
4582    })
4583}
4584
4585/// Infers what choosing a given on-screen option does from the verb in its
4586/// OWN text -- never from its position or number, since neither is stable
4587/// across CLIs or screen wraps. Decline phrasing is checked before accept
4588/// phrasing so `"Continue without trusting"` (contains both "continue" and
4589/// "without trusting") reads as `Decline`, matching what the option
4590/// actually does; an option whose text uses none of these verbs classifies
4591/// `Unknown` rather than a guessed default.
4592fn classify_operator_gate_option_semantics(text: &str) -> OperatorGateOptionSemantics {
4593    let lower = text.to_ascii_lowercase();
4594    if lower.contains("review") {
4595        OperatorGateOptionSemantics::Inspect
4596    } else if lower.contains("don't trust")
4597        || lower.contains("do not trust")
4598        || lower.contains("without trusting")
4599        || lower.contains("decline")
4600    {
4601        OperatorGateOptionSemantics::Decline
4602    } else if lower.contains("trust") || lower.contains("continue") || lower.contains("proceed") {
4603        OperatorGateOptionSemantics::Accept
4604    } else if lower.contains("exit") || lower.contains("quit") || lower.contains("cancel") {
4605        OperatorGateOptionSemantics::Exit
4606    } else {
4607        OperatorGateOptionSemantics::Unknown
4608    }
4609}
4610
4611/// True if `line` ends in a bare shell-prompt character -- used only to
4612/// raise confidence on the one `screen_failure` marker
4613/// (`"no such file or directory"`) that is otherwise too generic to trust
4614/// alone; see that bucket's own comment.
4615fn looks_like_shell_prompt_line(line: &str) -> bool {
4616    matches!(line.trim_end().chars().last(), Some('$' | '%' | '#' | '>'))
4617}
4618
4619/// Screens where the foreground process already matches the agent (this is
4620/// NOT the `NotAgent` process-mismatch case) but the screen itself shows
4621/// the process came up wrong or fell over. Nothing typed into THIS screen
4622/// fixes it, which is the line that separates `Failing` from
4623/// `OperatorGate`: a gate is resolved by typing an answer into the pane, a
4624/// failure is not.
4625///
4626/// Every marker here is a crash SHAPE -- a stack-trace banner, a shell's
4627/// own "command not found" line -- and as raw bytes a crash shape is
4628/// indistinguishable from an agent CHOOSING to render that same text while
4629/// explaining, or running, someone else's failure (`cargo test` hitting a
4630/// failing assertion, a script the agent ran that threw, a bug report it
4631/// was asked to read). Text alone cannot tell "the CLI crashed" from "the
4632/// CLI is showing you a crash" -- both put identical bytes on screen. The
4633/// one window where these markers ARE trustworthy is before this
4634/// generation's session has ever reached `Ready`: with no prior render of
4635/// the agent's own UI, there is nothing else on the screen that could have
4636/// produced a crash banner, so it genuinely means the launch failed. That
4637/// is why this function's caller in `collect_terminal_frames` stops
4638/// calling it at all once `Ready`, rather than trying to make the matching
4639/// itself tell healthy narration apart from a real crash -- no marker set
4640/// can do that from bytes alone.
4641fn screen_failure(contents: &str) -> Option<&'static str> {
4642    let normalized = normalize_screen_text(contents);
4643
4644    // A language runtime's own uncaught-exception banner -- fixed strings
4645    // a runtime prints verbatim at the head of a crash dump, not phrasing
4646    // a chat transcript would casually reproduce in this exact shape.
4647    // `"fatal error:"` is deliberately NOT included: it is also what a
4648    // C/C++ compiler prints for an ordinary missing-header build error, and
4649    // a wrapper script's build step can emit that while the real CLI still
4650    // comes up fine afterwards -- untrustworthy even in the startup window
4651    // without a second signal this function does not have.
4652    if ["panicked at", "unhandled exception", "traceback (most recent call last)"]
4653        .iter()
4654        .any(|marker| normalized.contains(marker))
4655    {
4656        return Some("crash");
4657    }
4658
4659    // A shell reporting that the launch command itself does not exist.
4660    // The first two are OS/shell-owned sentence shapes on their own. The
4661    // third, `"no such file or directory"`, is common enough in ordinary
4662    // ENOENT discussion that it needs a companion signal -- a line that
4663    // itself ends in a bare shell prompt -- before it counts.
4664    if normalized.contains("command not found")
4665        || normalized.contains("is not recognized as an internal or external command")
4666        || (normalized.contains("no such file or directory")
4667            && contents.lines().any(looks_like_shell_prompt_line))
4668    {
4669        return Some("missing command");
4670    }
4671
4672    // A provider CLI's own missing-credential banner at launch -- Grok with
4673    // no key configured prints exactly this one line and never renders
4674    // anything else again, which makes it a crash SHAPE in the same sense
4675    // as the buckets above: nothing typed into this screen fixes it, only a
4676    // restart with a credential configured. Required to co-occur with the
4677    // literal `GROK_API_KEY` env var name rather than matching "api key
4678    // required" alone -- that phrase in the abstract is common enough in an
4679    // agent's own prose (explaining a DIFFERENT provider's setup, say) to be
4680    // untrustworthy alone; the exact env var name is specific to this one
4681    // banner.
4682    if normalized.contains("api key required") && normalized.contains("grok_api_key") {
4683        return Some("missing api key");
4684    }
4685
4686    None
4687}
4688
4689/// The window gate on `screen_failure`, factored into its own pure
4690/// function so the "stop trusting crash markers once this generation has
4691/// ever been `Ready`" rule is unit-testable without constructing a live
4692/// `OwnedPtySession` (which owns a real PTY and cannot be built in a unit
4693/// test). `collect_terminal_frames` calls this, not `screen_failure`
4694/// directly.
4695fn screen_failure_for_generation(contents: &str, ever_reached_ready: bool) -> Option<&'static str> {
4696    if ever_reached_ready {
4697        None
4698    } else {
4699        screen_failure(contents)
4700    }
4701}
4702
4703/// The foreground half of the classification, resolved by the caller so
4704/// the merge itself stays a pure function.
4705#[derive(Clone, Debug, Eq, PartialEq)]
4706enum ForegroundVerdict {
4707    /// Foreground is the agent's own binary, or a tolerated wrapper.
4708    Agent,
4709    /// Foreground is something else. Carries what was actually seen.
4710    Foreign { process: String },
4711}
4712
4713/// Merge the foreground and text signals into one screen classification.
4714///
4715/// The ORDER below, not the branches, is the part worth reading closely:
4716///
4717/// 1. A foreign foreground wins outright, even over a matching gate or
4718///    failure text pattern, because the process signal is structurally
4719///    exhaustive in the one way that matters -- it never needs to
4720///    recognize an updater's specific wording to say "this is not the
4721///    agent". A vendor wrapper whose text this module's matchers do not
4722///    yet know about still gets caught here.
4723/// 2. With no foreign foreground, `Failing` outranks `OperatorGate`: a
4724///    crashed screen can still have a leftover gate prompt sitting in
4725///    view above the crash dump, and "broken" is the more urgent of the
4726///    two truths for an operator to hear -- reporting "waiting for input"
4727///    about a session that has actually fallen over sends someone to type
4728///    into a pane that cannot use it.
4729/// 3. `OperatorGate` next, for the "resolvable by typing" reason
4730///    documented on `PtyScreenState` itself.
4731/// 4. With no foreground observation at all, the answer is `Unknown`, not
4732///    `Ready` -- a clean text read is NEVER, by itself, proof the screen
4733///    is the agent's. `Ready` requires the foreground to have been
4734///    checked AND to have matched, per the asymmetry documented on
4735///    `PtyScreenState::Ready`.
4736/// 5. Only once foreground is confirmed AND no gate/failure text matched
4737///    does the merge land on `Ready`.
4738fn classify_pty_screen_state(
4739    foreground: Option<&ForegroundVerdict>,
4740    gate: Option<&OperatorGateState>,
4741    failure: Option<&'static str>,
4742) -> PtyScreenState {
4743    if let Some(ForegroundVerdict::Foreign { process }) = foreground {
4744        return PtyScreenState::NotAgent {
4745            observed_process: process.clone(),
4746        };
4747    }
4748    if let Some(reason) = failure {
4749        return PtyScreenState::Failing {
4750            reason: reason.to_owned(),
4751        };
4752    }
4753    if let Some(gate) = gate {
4754        return PtyScreenState::OperatorGate { gate: gate.clone() };
4755    }
4756    if foreground.is_some() {
4757        PtyScreenState::Ready
4758    } else {
4759        PtyScreenState::Unknown
4760    }
4761}
4762
4763/// Resolve what an OS process-tree observation means for classification,
4764/// reusing the exact matchers `ReadinessTracker::observe_foreground` trusts
4765/// at startup so this module's tolerance for a spawning wrapper
4766/// (`node`/`python`/`python3`) never drifts from readiness's own -- a false
4767/// `NotAgent` on a legitimate wrapper would be a regression on what
4768/// readiness already tolerates.
4769///
4770/// Deliberately looser than `ReadinessTracker::observe_foreground` in one
4771/// respect: it does not gate the wrapper tolerance behind
4772/// `has_child_processes`/a poll-count threshold. Those exist there to
4773/// decide "confident enough to flip session status to Running" from a
4774/// process signal ALONE. Here the text signal still has to independently
4775/// agree before the merge can reach `Ready` (see `classify_pty_screen_state`),
4776/// so being more permissive about which process counts as plausible never
4777/// lets a bad screen through on the process signal by itself.
4778fn resolve_foreground_verdict(
4779    spec: &AgentSpec,
4780    observation: &PtyForegroundObservation,
4781    platform: RuntimePlatform,
4782) -> ForegroundVerdict {
4783    let process_name = observation
4784        .readiness
4785        .process_name
4786        .as_deref()
4787        .unwrap_or(observation.observed_process.as_str());
4788    if is_expected_agent_process(spec, process_name, platform)
4789        || is_agent_foreground_wrapper(process_name, platform)
4790    {
4791        ForegroundVerdict::Agent
4792    } else {
4793        ForegroundVerdict::Foreign {
4794            process: observation.observed_process.clone(),
4795        }
4796    }
4797}
4798
4799/// Whether `NativeEffectShell::reclassify_foreground` should schedule
4800/// another probe after a fresh classification, factored out as a small
4801/// pure function so the decision is testable without constructing a live
4802/// `OwnedPtySession` (which owns a real PTY and cannot be built in a unit
4803/// test).
4804#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4805enum ForegroundProbeSchedule {
4806    /// The session reached `Ready` -- stop probing until text disagrees.
4807    Disarmed,
4808    /// Still unresolved, or freshly non-ready -- probe again after the interval.
4809    Armed,
4810}
4811
4812fn foreground_probe_schedule(state: &PtyScreenState) -> ForegroundProbeSchedule {
4813    if matches!(state, PtyScreenState::Ready) {
4814        ForegroundProbeSchedule::Disarmed
4815    } else {
4816        ForegroundProbeSchedule::Armed
4817    }
4818}
4819
4820/// Whether a text-only reclassification that just changed the merged state
4821/// (inside `collect_terminal_frames`) should force the foreground probe due
4822/// immediately, rather than waiting for its normal cadence. Factored out
4823/// for the same testability reason as `foreground_probe_schedule`: a
4824/// session that was `Ready` and whose text just started matching a gate or
4825/// failure pattern needs its foreground re-checked promptly, since the
4826/// last thing anyone probed was clean and the screen no longer agrees.
4827fn foreground_probe_rearms_immediately(previous: &PtyScreenState, next: &PtyScreenState) -> bool {
4828    matches!(previous, PtyScreenState::Ready) && !matches!(next, PtyScreenState::Ready)
4829}
4830
4831fn observe_readiness_event(
4832    tracker: &mut ReadinessTracker<'_>,
4833    diagnostics: &mut ReadinessDiagnostics,
4834    event: PtyEvent,
4835    elapsed_ms: u64,
4836) -> Result<(), String> {
4837    match event {
4838        PtyEvent::Output(data) => {
4839            diagnostics.observe_output(&data);
4840            tracker.observe_output(&data, elapsed_ms);
4841        }
4842        PtyEvent::ForegroundProcess(observation) => {
4843            diagnostics.observe_foreground(&observation.readiness);
4844            tracker.observe_foreground(&observation.readiness, elapsed_ms);
4845        }
4846        PtyEvent::DataGap { .. } => {
4847            return Err("PTY replay gap prevents positive readiness proof".to_owned());
4848        }
4849        PtyEvent::ReaderError { message } | PtyEvent::OperatorActionRequired { message } => {
4850            return Err(message);
4851        }
4852        PtyEvent::Exited { code } => {
4853            return Err(format!("PTY exited with code {code} before readiness"));
4854        }
4855        PtyEvent::Started | PtyEvent::Resized(_) | PtyEvent::SnapshotAvailable { .. } => {}
4856    }
4857    Ok(())
4858}
4859
4860#[derive(Default)]
4861struct ReadinessDiagnostics {
4862    draft_signal: Option<gate4agent_types::DraftReadySignal>,
4863    output_bytes: usize,
4864    output_chunks: usize,
4865    tail: Vec<u8>,
4866    saw_bracketed_paste: bool,
4867    saw_cursor_show: bool,
4868    saw_cursor_hide: bool,
4869    saw_alternate_screen: bool,
4870    saw_clear_screen: bool,
4871    saw_claude_composer: bool,
4872    saw_codex_composer: bool,
4873    saw_named_foreground: bool,
4874    operator_gate: Option<OperatorGateState>,
4875}
4876
4877impl ReadinessDiagnostics {
4878    fn observe_output(&mut self, data: &[u8]) {
4879        const SIGNAL_TAIL_BYTES: usize = 4_096;
4880        self.output_bytes = self.output_bytes.saturating_add(data.len());
4881        self.output_chunks = self.output_chunks.saturating_add(1);
4882        let mut combined = Vec::with_capacity(self.tail.len().saturating_add(data.len()));
4883        combined.extend_from_slice(&self.tail);
4884        combined.extend_from_slice(data);
4885        self.saw_bracketed_paste |= readiness_bytes_contain(&combined, b"\x1b[?2004h");
4886        self.saw_cursor_show |= readiness_bytes_contain(&combined, b"\x1b[?25h");
4887        self.saw_cursor_hide |= readiness_bytes_contain(&combined, b"\x1b[?25l");
4888        self.saw_alternate_screen |= readiness_bytes_contain(&combined, b"\x1b[?1049h");
4889        self.saw_clear_screen |= readiness_bytes_contain(&combined, b"\x1b[2J");
4890        self.saw_claude_composer |= readiness_bytes_contain(&combined, "❯".as_bytes());
4891        self.saw_codex_composer |= readiness_bytes_contain(&combined, "›".as_bytes());
4892        let text = String::from_utf8_lossy(&combined);
4893        self.operator_gate = self
4894            .operator_gate
4895            .take()
4896            .or_else(|| startup_operator_gate(&strip_ansi_codes(&text)));
4897        self.tail = combined[combined.len().saturating_sub(SIGNAL_TAIL_BYTES)..].to_vec();
4898    }
4899
4900    fn observe_foreground(&mut self, foreground: &gate4agent::agent::ForegroundObservation) {
4901        self.saw_named_foreground |= foreground.process_name.is_some();
4902    }
4903
4904    fn summary(&self) -> String {
4905        format!(
4906            "draft_signal={:?} output_bytes={} output_chunks={} named_foreground={} bracketed_paste={} cursor_show={} cursor_hide={} alternate_screen={} clear_screen={} claude_composer={} codex_composer={} csi={}",
4907            self.draft_signal,
4908            self.output_bytes,
4909            self.output_chunks,
4910            self.saw_named_foreground,
4911            self.saw_bracketed_paste,
4912            self.saw_cursor_show,
4913            self.saw_cursor_hide,
4914            self.saw_alternate_screen,
4915            self.saw_clear_screen,
4916            self.saw_claude_composer,
4917            self.saw_codex_composer,
4918            readiness_csi_signatures(&self.tail),
4919        )
4920    }
4921}
4922
4923fn readiness_csi_signatures(bytes: &[u8]) -> String {
4924    let mut signatures = Vec::new();
4925    let mut index = 0;
4926    while index + 2 < bytes.len() && signatures.len() < 32 {
4927        if bytes[index] != 0x1b || bytes[index + 1] != b'[' {
4928            index += 1;
4929            continue;
4930        }
4931        let mut end = index + 2;
4932        while end < bytes.len() && end.saturating_sub(index) <= 24 {
4933            let byte = bytes[end];
4934            if (0x40..=0x7e).contains(&byte) {
4935                let signature = String::from_utf8_lossy(&bytes[index + 2..=end]).into_owned();
4936                if !signatures.iter().any(|existing| existing == &signature) {
4937                    signatures.push(signature);
4938                }
4939                index = end;
4940                break;
4941            }
4942            if !(0x20..=0x3f).contains(&byte) {
4943                break;
4944            }
4945            end += 1;
4946        }
4947        index += 1;
4948    }
4949    if signatures.is_empty() {
4950        "none".to_owned()
4951    } else {
4952        signatures.join("|")
4953    }
4954}
4955
4956fn readiness_bytes_contain(haystack: &[u8], needle: &[u8]) -> bool {
4957    haystack
4958        .windows(needle.len())
4959        .any(|window| window == needle)
4960}
4961
4962fn readiness_complete(
4963    status: ReadinessStatus,
4964    diagnostics: &ReadinessDiagnostics,
4965) -> Result<bool, String> {
4966    match status {
4967        ReadinessStatus::Waiting => Ok(false),
4968        ReadinessStatus::Ready(_) => Ok(true),
4969        ReadinessStatus::TimedOut => Err(format!(
4970            "PTY readiness timed out ({})",
4971            diagnostics.summary()
4972        )),
4973    }
4974}
4975
4976fn elapsed_ms(started: Instant) -> u64 {
4977    u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)
4978}
4979
4980#[cfg(test)]
4981mod tests {
4982    use super::{
4983        acp_approval_level_args,
4984        approval_level_not_offered_message,
4985        classify_operator_gate_option_semantics,
4986        classify_pty_screen_state,
4987        defers_permission_requests,
4988        foreground_probe_rearms_immediately, foreground_probe_schedule,
4989        argument_looks_like_credential, host_policy_for_approval_level,
4990        mcp_server_acp_entry,
4991        parse_operator_gate_options, prepare_fresh_pty_provider_session,
4992        prompt_render_probe, prompt_rendered, required_acp_mode,
4993        reserve_provider_gap_sequence, resolve_foreground_verdict, screen_failure,
4994        screen_failure_for_generation, with_pty_terminal_capability_defaults,
4995        should_attach_pty_provider_stream, should_probe_pty_identity, startup_operator_gate,
4996        terminal_frame, terminal_frame_byte_len, terminal_state_capture_should_skip,
4997        validate_instance_launch_arguments, validate_spawn_runtime_policy,
4998        ForegroundProbeSchedule, ForegroundVerdict, ReadinessDiagnostics, RateLimitFeed,
4999        Utf8ChunkDecoder,
5000    };
5001    use gate4agent::acp::protocol::{McpServerConfig, SessionMode};
5002    use gate4agent::HostPolicy;
5003    use gate4agent_adapters::builtin_adapter_registry;
5004    use gate4agent_catalog::{EnvMutation, McpServerSpec, ModeId};
5005    use gate4agent::agent::ForegroundObservation;
5006    use gate4agent::core::types::{
5007        AgentEvent, ContextWindowUsage as AgentContextWindowUsage, HostDecisionAuthority,
5008        HostRequestDecision, HostRequestOutcome, RateLimitType,
5009    };
5010    use gate4agent::pty::event::PtyMouseProtocolEncoding;
5011    use gate4agent::pty::{PtyForegroundObservation, PtyForegroundSource, RateLimitDetector};
5012    use gate4agent::CliTool;
5013    use gate4agent_types::{
5014        AdapterFamily, AgentId, ApprovalLevel,
5015        HostDecisionAuthority as ProviderHostDecisionAuthority,
5016        HostRequestDecision as ProviderHostRequestDecision,
5017        HostRequestOutcome as ProviderHostRequestOutcome, OperatorGateInput,
5018        OperatorGateKind, OperatorGateOptionSemantics, OperatorGateState, OperatorGateSubject,
5019        ProviderEvent, ProviderInteractionKind, ProviderInteractionOption, ProviderRuntimePolicy,
5020        PtyScreenState, RuntimePlatform, TerminalMouseProtocolEncoding, TransportKind,
5021    };
5022    use std::ffi::{OsStr, OsString};
5023
5024    fn snapshot(sequence: u64, contents: &str) -> super::PtyTerminalSnapshot {
5025        super::PtyTerminalSnapshot {
5026            pty_id: "fixture".to_owned(),
5027            provider_revision: "fixture-r1".to_owned(),
5028            generation: 1,
5029            sequence,
5030            size: gate4agent::pty::PtySize { rows: 24, cols: 80 },
5031            cursor: (0, 0),
5032            bracketed_paste: false,
5033            contents: contents.to_owned(),
5034            formatted: Vec::new(),
5035            scrollback_formatted: Vec::new(),
5036            alternate_screen: false,
5037            mouse_protocol_enabled: false,
5038            mouse_protocol_encoding: PtyMouseProtocolEncoding::Default,
5039            produced_at_unix_ms: 0,
5040        }
5041    }
5042
5043    #[test]
5044    fn terminal_frame_preserves_scrollback_and_terminal_input_metadata() {
5045        let mut snapshot = snapshot(7, "visible");
5046        snapshot.scrollback_formatted = vec![b"older".to_vec()];
5047        snapshot.alternate_screen = true;
5048        snapshot.mouse_protocol_enabled = true;
5049        snapshot.mouse_protocol_encoding = PtyMouseProtocolEncoding::Sgr;
5050        snapshot.produced_at_unix_ms = 1_700_000_000_000;
5051
5052        let frame = terminal_frame(snapshot, PtyScreenState::default());
5053        assert_eq!(frame.scrollback_formatted, vec![b"older".to_vec()]);
5054        assert!(frame.alternate_screen);
5055        assert!(frame.mouse_protocol_enabled);
5056        assert_eq!(frame.mouse_protocol_encoding, TerminalMouseProtocolEncoding::Sgr);
5057        // `terminal_frame` must carry the stamp through, never recompute it.
5058        assert_eq!(frame.produced_at_unix_ms, 1_700_000_000_000);
5059    }
5060
5061    #[test]
5062    fn terminal_frame_byte_len_sums_formatted_and_every_scrollback_row() {
5063        let mut snapshot = snapshot(9, "visible");
5064        snapshot.formatted = b"\x1b[2Jvisible".to_vec();
5065        snapshot.scrollback_formatted =
5066            vec![b"row one".to_vec(), b"row two, longer".to_vec()];
5067        let expected = snapshot.formatted.len()
5068            + snapshot.scrollback_formatted[0].len()
5069            + snapshot.scrollback_formatted[1].len();
5070
5071        let frame = terminal_frame(snapshot, PtyScreenState::default());
5072        assert_eq!(terminal_frame_byte_len(&frame), expected as u64);
5073    }
5074
5075    #[test]
5076    fn the_sequence_gate_skips_only_when_the_sequence_did_not_advance() {
5077        assert!(terminal_state_capture_should_skip(Ok::<u64, ()>(5), 5));
5078        assert!(terminal_state_capture_should_skip(Ok::<u64, ()>(4), 5));
5079        assert!(!terminal_state_capture_should_skip(Ok::<u64, ()>(6), 5));
5080        // A failed cheap read never skips -- the real call is attempted so
5081        // its own error path (stale-published bookkeeping) still runs.
5082        assert!(!terminal_state_capture_should_skip(Err::<u64, ()>(()), 5));
5083    }
5084
5085    #[test]
5086    fn structured_context_usage_maps_without_pty_inference() {
5087        let mapped = super::provider_event(
5088            AgentEvent::ContextWindowUsage {
5089                usage: AgentContextWindowUsage {
5090                    uncached_input_tokens: 70,
5091                    cache_read_tokens: 20,
5092                    cache_write_tokens: 0,
5093                    output_tokens: 10,
5094                    unattributed_tokens: 5,
5095                    used_tokens: 105,
5096                    capacity_tokens: 100,
5097                },
5098            },
5099            &[],
5100        );
5101        assert_eq!(
5102            mapped,
5103            Some(ProviderEvent::ContextWindowUsage {
5104                usage: gate4agent_types::ContextWindowUsage {
5105                    uncached_input_tokens: 70,
5106                    cache_read_tokens: 20,
5107                    cache_write_tokens: 0,
5108                    output_tokens: 10,
5109                    unattributed_tokens: 5,
5110                    used_tokens: 105,
5111                    capacity_tokens: 100,
5112                }
5113            })
5114        );
5115        assert_eq!(
5116            ProviderEvent::ContextWindowUsage {
5117                usage: gate4agent_types::ContextWindowUsage {
5118                    uncached_input_tokens: 70,
5119                    cache_read_tokens: 20,
5120                    cache_write_tokens: 0,
5121                    output_tokens: 10,
5122                    unattributed_tokens: 5,
5123                    used_tokens: 104,
5124                    capacity_tokens: 100,
5125                },
5126            }
5127            .validate_ingress(),
5128            Err(gate4agent_types::ProviderEventValidationError::ContextWindowSegmentsMismatch {
5129                segment_sum: 105,
5130                used_tokens: 104,
5131            })
5132        );
5133        assert!(
5134            super::provider_event(AgentEvent::PtyRaw { data: b"105/100".to_vec() }, &[]).is_none()
5135        );
5136    }
5137
5138    /// `AgentEvent::TurnInterrupted` (synthesized by `acp::session::
5139    /// AcpSession::start_prompt` when a `session/prompt` call ends without a
5140    /// success response) must reach `ProviderEvent::TurnInterrupted` --
5141    /// `gate4agent-engine`'s snapshot reducer is the one place that resets
5142    /// `ProviderActivity` away from `Blocked` back to `Idle` for it, closing
5143    /// the stuck-forever "turn in flight" bug measured live against
5144    /// codex-acp 1.10.0 (a `session/prompt` RPC error left every subsequent
5145    /// prompt refused for the rest of the session).
5146    #[test]
5147    fn turn_interrupted_maps_to_the_provider_event_that_unblocks_the_next_prompt() {
5148        let mapped = super::provider_event(
5149            AgentEvent::TurnInterrupted {
5150                reason: "session/prompt timed out after 120s".to_owned(),
5151            },
5152            &[],
5153        );
5154        assert_eq!(mapped, Some(ProviderEvent::TurnInterrupted));
5155    }
5156
5157    #[test]
5158    fn tool_result_non_execution_kind_carries_through_to_tool_completed() {
5159        let mapped = super::provider_event(
5160            AgentEvent::ToolResult {
5161                id: "t1".to_owned(),
5162                output: "denied".to_owned(),
5163                is_error: true,
5164                duration_ms: None,
5165                non_execution_kind: Some("permission-rule".to_owned()),
5166            },
5167            &[],
5168        );
5169        assert_eq!(
5170            mapped,
5171            Some(ProviderEvent::ToolCompleted {
5172                id: "t1".to_owned(),
5173                output: "denied".to_owned(),
5174                is_error: true,
5175                duration_ms: None,
5176                agent_id: None,
5177                non_execution_kind: Some("permission-rule".to_owned()),
5178            })
5179        );
5180    }
5181
5182    #[test]
5183    fn session_end_stop_reason_carries_through_to_session_ended() {
5184        use gate4agent::StopReason;
5185
5186        let refusal = super::provider_event(
5187            AgentEvent::SessionEnd {
5188                result: "refusal".to_owned(),
5189                cost_usd: None,
5190                is_error: true,
5191                stop_reason: Some(StopReason::Refusal),
5192            },
5193            &[],
5194        );
5195        assert_eq!(
5196            refusal,
5197            Some(ProviderEvent::SessionEnded {
5198                result: "refusal".to_owned(),
5199                cost_usd: None,
5200                is_error: true,
5201                stop_reason: Some(gate4agent_types::ProviderStopReason::Refusal),
5202            })
5203        );
5204
5205        let quota = super::provider_event(
5206            AgentEvent::SessionEnd {
5207                result: "JSON-RPC error -32603: Internal error".to_owned(),
5208                cost_usd: None,
5209                is_error: true,
5210                stop_reason: Some(StopReason::ProviderError {
5211                    code: -32603,
5212                    message: "You've hit your usage limit.".to_owned(),
5213                    vendor_code: Some("usageLimitExceeded".to_owned()),
5214                }),
5215            },
5216            &[],
5217        );
5218        assert_eq!(
5219            quota,
5220            Some(ProviderEvent::SessionEnded {
5221                result: "JSON-RPC error -32603: Internal error".to_owned(),
5222                cost_usd: None,
5223                is_error: true,
5224                stop_reason: Some(gate4agent_types::ProviderStopReason::ProviderError {
5225                    code: -32603,
5226                    message: "You've hit your usage limit.".to_owned(),
5227                    vendor_code: Some("usageLimitExceeded".to_owned()),
5228                }),
5229            })
5230        );
5231    }
5232
5233    #[test]
5234    fn host_request_reaches_the_operator_with_method_and_host_decision() {
5235        let denied = super::provider_event(
5236            AgentEvent::RpcIncomingRequest {
5237                id: gate4agent::rpc::message::RpcId::Number(1),
5238                method: "fs/read_text_file".to_owned(),
5239                params: None,
5240                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::Policy },
5241                outcome: HostRequestOutcome::Executed,
5242                reason: None,
5243            },
5244            &[],
5245        );
5246        assert_eq!(
5247            denied,
5248            Some(ProviderEvent::HostRequestObserved {
5249                method: "fs/read_text_file".to_owned(),
5250                params_json: String::new(),
5251                decision: ProviderHostRequestDecision::Denied {
5252                    by: ProviderHostDecisionAuthority::Policy
5253                },
5254                outcome: ProviderHostRequestOutcome::Executed,
5255                reason: None,
5256            })
5257        );
5258
5259        let granted = super::provider_event(
5260            AgentEvent::RpcIncomingRequest {
5261                id: gate4agent::rpc::message::RpcId::Number(2),
5262                method: "terminal/create".to_owned(),
5263                params: None,
5264                decision: HostRequestDecision::Granted { by: HostDecisionAuthority::Policy },
5265                outcome: HostRequestOutcome::Executed,
5266                reason: None,
5267            },
5268            &[],
5269        );
5270        assert_eq!(
5271            granted,
5272            Some(ProviderEvent::HostRequestObserved {
5273                method: "terminal/create".to_owned(),
5274                params_json: String::new(),
5275                decision: ProviderHostRequestDecision::Granted {
5276                    by: ProviderHostDecisionAuthority::Policy
5277                },
5278                outcome: ProviderHostRequestOutcome::Executed,
5279                reason: None,
5280            })
5281        );
5282
5283        // Every authority carries through, not just the outcome -- a gate
5284        // block and an operator's answer must remain distinguishable on the
5285        // wire, and a deadline expiry must never be mistaken for one.
5286        let gate_denied = super::provider_event(
5287            AgentEvent::RpcIncomingRequest {
5288                id: gate4agent::rpc::message::RpcId::Number(3),
5289                method: "terminal/create".to_owned(),
5290                params: None,
5291                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::Gate },
5292                outcome: HostRequestOutcome::Executed,
5293                reason: None,
5294            },
5295            &[],
5296        );
5297        assert_eq!(
5298            gate_denied,
5299            Some(ProviderEvent::HostRequestObserved {
5300                method: "terminal/create".to_owned(),
5301                params_json: String::new(),
5302                decision: ProviderHostRequestDecision::Denied {
5303                    by: ProviderHostDecisionAuthority::Gate
5304                },
5305                outcome: ProviderHostRequestOutcome::Executed,
5306                reason: None,
5307            })
5308        );
5309
5310        let operator_granted = super::provider_event(
5311            AgentEvent::RpcIncomingRequest {
5312                id: gate4agent::rpc::message::RpcId::Number(4),
5313                method: "session/request_permission".to_owned(),
5314                params: None,
5315                decision: HostRequestDecision::Granted { by: HostDecisionAuthority::Operator },
5316                outcome: HostRequestOutcome::Executed,
5317                reason: None,
5318            },
5319            &[],
5320        );
5321        assert_eq!(
5322            operator_granted,
5323            Some(ProviderEvent::HostRequestObserved {
5324                method: "session/request_permission".to_owned(),
5325                params_json: String::new(),
5326                decision: ProviderHostRequestDecision::Granted {
5327                    by: ProviderHostDecisionAuthority::Operator
5328                },
5329                outcome: ProviderHostRequestOutcome::Executed,
5330                reason: None,
5331            })
5332        );
5333
5334        let deadline_denied = super::provider_event(
5335            AgentEvent::RpcIncomingRequest {
5336                id: gate4agent::rpc::message::RpcId::Number(5),
5337                method: "session/request_permission".to_owned(),
5338                params: None,
5339                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::DeadlinePolicy },
5340                outcome: HostRequestOutcome::Executed,
5341                reason: None,
5342            },
5343            &[],
5344        );
5345        assert_eq!(
5346            deadline_denied,
5347            Some(ProviderEvent::HostRequestObserved {
5348                method: "session/request_permission".to_owned(),
5349                params_json: String::new(),
5350                decision: ProviderHostRequestDecision::Denied {
5351                    by: ProviderHostDecisionAuthority::DeadlinePolicy
5352                },
5353                outcome: ProviderHostRequestOutcome::Executed,
5354                reason: None,
5355            })
5356        );
5357
5358        // `session/request_permission` + `Deferred` is deliberately absent
5359        // here -- that combination becomes an `InteractionRequested`, not a
5360        // `HostRequestObserved`; see
5361        // `deferred_acp_permission_request_becomes_an_interaction_with_its_id`
5362        // below.
5363    }
5364
5365    /// K1c's split: an authorized (`Granted`) host request that failed
5366    /// WHILE EXECUTING (e.g. a `terminal/create` spawn error) must carry
5367    /// `HostRequestOutcome::Failed` through to `ProviderEvent::
5368    /// HostRequestObserved` verbatim -- never dropped, and never collapsed
5369    /// into `Denied`: the request WAS authorized, only its execution
5370    /// failed.
5371    #[test]
5372    fn granted_host_request_execution_failure_carries_through_as_a_failed_outcome() {
5373        let spawn_error = "terminal/create spawn failed: os error 3";
5374        let mapped = super::provider_event(
5375            AgentEvent::RpcIncomingRequest {
5376                id: gate4agent::rpc::message::RpcId::Number(10),
5377                method: "terminal/create".to_owned(),
5378                params: None,
5379                decision: HostRequestDecision::Granted { by: HostDecisionAuthority::Policy },
5380                outcome: HostRequestOutcome::Failed { error: spawn_error.to_owned() },
5381                reason: None,
5382            },
5383            &[],
5384        );
5385        assert_eq!(
5386            mapped,
5387            Some(ProviderEvent::HostRequestObserved {
5388                method: "terminal/create".to_owned(),
5389                params_json: String::new(),
5390                decision: ProviderHostRequestDecision::Granted {
5391                    by: ProviderHostDecisionAuthority::Policy
5392                },
5393                outcome: ProviderHostRequestOutcome::Failed { error: spawn_error.to_owned() },
5394                reason: None,
5395            })
5396        );
5397        mapped.expect("mapped").validate_ingress().expect("bounded free-text error validates");
5398    }
5399
5400    /// The bug this change fixes: the gate's own refusal text used to be
5401    /// computed, then thrown away -- an observer got the categorical
5402    /// `Denied { by: Gate }` and nothing naming WHY. `reason` now rides the
5403    /// SAME `AgentEvent::RpcIncomingRequest` → `ProviderEvent::
5404    /// HostRequestObserved` mapping every other field already used,
5405    /// verbatim, bounded by `validate_ingress`.
5406    #[test]
5407    fn host_request_reason_carries_through_to_the_operator() {
5408        let gate_text =
5409            "blocked by dangerous-command gate: rule=filesystem-wipe, argument=rm -rf /";
5410        let denied = super::provider_event(
5411            AgentEvent::RpcIncomingRequest {
5412                id: gate4agent::rpc::message::RpcId::Number(9),
5413                method: "terminal/create".to_owned(),
5414                params: None,
5415                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::Gate },
5416                outcome: HostRequestOutcome::Executed,
5417                reason: Some(gate_text.to_owned()),
5418            },
5419            &[],
5420        );
5421        assert_eq!(
5422            denied,
5423            Some(ProviderEvent::HostRequestObserved {
5424                method: "terminal/create".to_owned(),
5425                params_json: String::new(),
5426                decision: ProviderHostRequestDecision::Denied {
5427                    by: ProviderHostDecisionAuthority::Gate
5428                },
5429                outcome: ProviderHostRequestOutcome::Executed,
5430                reason: Some(gate_text.to_owned()),
5431            })
5432        );
5433
5434        // `validate_ingress` accepts the reason as ordinary bounded free
5435        // text -- the same bound `ToolCompleted::output` uses, proving this
5436        // is not smuggled through the categorical `Error::detail` field the
5437        // owner's incident named (that validator only accepts `a-z0-9-`).
5438        denied.expect("mapped").validate_ingress().expect("bounded free-text reason validates");
5439    }
5440
5441    #[test]
5442    fn deferred_acp_permission_request_becomes_an_interaction_with_its_id() {
5443        let with_title = super::provider_event(
5444            AgentEvent::RpcIncomingRequest {
5445                id: gate4agent::rpc::message::RpcId::Number(6),
5446                method: "session/request_permission".to_owned(),
5447                params: Some(serde_json::json!({
5448                    "sessionId": "s1",
5449                    "toolCall": {"toolCallId": "t1", "kind": "edit", "title": "Edit src/main.rs"},
5450                    "options": [
5451                        {"optionId": "allow", "name": "Allow", "kind": "allow_once"},
5452                        {"optionId": "reject", "name": "Reject", "kind": "reject_once"},
5453                    ],
5454                })),
5455                decision: HostRequestDecision::Deferred,
5456                outcome: HostRequestOutcome::Executed,
5457                reason: None,
5458            },
5459            &[],
5460        );
5461        // `kind` is the tool CLASS and `title` is the question. They are two
5462        // different things and the operator needs both: putting the title in
5463        // `tool_name` and leaving `prompt` empty -- which this asserted
5464        // before -- showed a correlation id and a sentence-shaped tool name,
5465        // and never the question itself. `title`/`options` now carry the
5466        // agent's own values instead of arriving empty -- the operator's
5467        // approve/deny answer must resolve against an option list they can
5468        // actually see.
5469        assert_eq!(
5470            with_title,
5471            Some(ProviderEvent::InteractionRequested {
5472                request_id: Some("number:6".to_owned()),
5473                interaction_kind: ProviderInteractionKind::Approval,
5474                tool_name: "edit".to_owned(),
5475                title: Some("Edit src/main.rs".to_owned()),
5476                prompt: "Edit src/main.rs".to_owned(),
5477                options: vec![
5478                    ProviderInteractionOption {
5479                        option_id: "allow".to_owned(),
5480                        name: "Allow".to_owned(),
5481                        kind: "allow_once".to_owned(),
5482                    },
5483                    ProviderInteractionOption {
5484                        option_id: "reject".to_owned(),
5485                        name: "Reject".to_owned(),
5486                        kind: "reject_once".to_owned(),
5487                    },
5488                ],
5489                agent_id: None,
5490            })
5491        );
5492
5493        // No `kind` on the wire (or no params at all) -- falls back to the
5494        // method name rather than an empty `tool_name`, which
5495        // `ProviderEvent::validate_ingress` rejects. An absent `title`
5496        // leaves `prompt` empty rather than inventing a question, and no
5497        // params at all means no option list to read, not a dropped one.
5498        let without_title = super::provider_event(
5499            AgentEvent::RpcIncomingRequest {
5500                id: gate4agent::rpc::message::RpcId::String("agent-7".to_owned()),
5501                method: "session/request_permission".to_owned(),
5502                params: None,
5503                decision: HostRequestDecision::Deferred,
5504                outcome: HostRequestOutcome::Executed,
5505                reason: None,
5506            },
5507            &[],
5508        );
5509        assert_eq!(
5510            without_title,
5511            Some(ProviderEvent::InteractionRequested {
5512                request_id: Some("string:agent-7".to_owned()),
5513                interaction_kind: ProviderInteractionKind::Approval,
5514                tool_name: "session/request_permission".to_owned(),
5515                title: None,
5516                prompt: String::new(),
5517                options: Vec::new(),
5518                agent_id: None,
5519            })
5520        );
5521
5522        // The SAME id's eventual outcome (not itself `Deferred` anymore)
5523        // still reaches the operator as the ordinary audit trail, exactly
5524        // as every other host request does.
5525        let resolved = super::provider_event(
5526            AgentEvent::RpcIncomingRequest {
5527                id: gate4agent::rpc::message::RpcId::Number(6),
5528                method: "session/request_permission".to_owned(),
5529                params: None,
5530                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::Operator },
5531                outcome: HostRequestOutcome::Executed,
5532                reason: None,
5533            },
5534            &[],
5535        );
5536        assert_eq!(
5537            resolved,
5538            Some(ProviderEvent::HostRequestObserved {
5539                method: "session/request_permission".to_owned(),
5540                params_json: String::new(),
5541                decision: ProviderHostRequestDecision::Denied {
5542                    by: ProviderHostDecisionAuthority::Operator
5543                },
5544                outcome: ProviderHostRequestOutcome::Executed,
5545                reason: None,
5546            })
5547        );
5548    }
5549
5550    #[test]
5551    fn unrecognized_notification_reaches_the_operator_as_a_raw_event_instead_of_vanishing() {
5552        let mapped = super::provider_event(
5553            AgentEvent::RpcNotification {
5554                method: "session/update".to_owned(),
5555                params: Default::default(),
5556            },
5557            &[],
5558        );
5559        assert_eq!(
5560            mapped,
5561            Some(ProviderEvent::UnrecognizedNotification {
5562                method: "session/update".to_owned(),
5563                payload_json: "null".to_owned(),
5564            })
5565        );
5566    }
5567
5568    #[test]
5569    fn pty_terminal_capability_defaults_never_override_a_caller_supplied_term() {
5570        let caller_supplied = vec![EnvMutation {
5571            key: OsString::from("TERM"),
5572            value: Some(OsString::from("dumb")),
5573        }];
5574        let filled = with_pty_terminal_capability_defaults(caller_supplied);
5575
5576        let term_values: Vec<_> = filled
5577            .iter()
5578            .filter(|mutation| mutation.key.as_os_str() == OsStr::new("TERM"))
5579            .collect();
5580        assert_eq!(term_values.len(), 1, "TERM must not be duplicated");
5581        assert_eq!(term_values[0].value.as_deref(), Some(OsStr::new("dumb")));
5582
5583        let colorterm = filled
5584            .iter()
5585            .find(|mutation| mutation.key.as_os_str() == OsStr::new("COLORTERM"))
5586            .expect("COLORTERM default is filled in when the caller left it unset");
5587        assert_eq!(colorterm.value.as_deref(), Some(OsStr::new("truecolor")));
5588    }
5589
5590    // -----------------------------------------------------------------------
5591    // mcp_server_acp_entry — the ACP half of the door
5592    // (gate4agent-arc-mailbox-and-task-layer Slice A(ii))
5593    // -----------------------------------------------------------------------
5594
5595    #[test]
5596    fn mcp_server_acp_entry_translates_a_spec_into_one_stdio_entry() {
5597        let spec = McpServerSpec::new(
5598            "test-mcp-server",
5599            OsString::from("C:\\example\\example-mcp-server.exe"),
5600            vec![OsString::from("--session-proxy")],
5601            vec![
5602                (
5603                    OsString::from("TEST_MCP_SESSION_ENDPOINT"),
5604                    OsString::from("\\\\.\\pipe\\example-mcp-server-s1"),
5605                ),
5606                (
5607                    OsString::from("TEST_MCP_SESSION_TOKEN"),
5608                    OsString::from("tok-abc"),
5609                ),
5610            ],
5611        )
5612        .unwrap();
5613
5614        let server = mcp_server_acp_entry(&spec);
5615        match server {
5616            McpServerConfig::Stdio { name, command, args, env } => {
5617                assert_eq!(name, "test-mcp-server", "ACP v1 requires a name; the adapter registers by it");
5618                assert_eq!(command, "C:\\example\\example-mcp-server.exe");
5619                assert_eq!(args, vec!["--session-proxy".to_string()]);
5620                assert_eq!(env.len(), 2, "exactly the entries the spec was given, nothing else");
5621                assert_eq!(
5622                    env.iter().find(|pair| pair.name == "TEST_MCP_SESSION_ENDPOINT").map(|pair| pair.value.as_str()),
5623                    Some("\\\\.\\pipe\\example-mcp-server-s1")
5624                );
5625                assert_eq!(
5626                    env.iter().find(|pair| pair.name == "TEST_MCP_SESSION_TOKEN").map(|pair| pair.value.as_str()),
5627                    Some("tok-abc")
5628                );
5629            }
5630            McpServerConfig::Sse { .. } => panic!("expected Stdio variant"),
5631        }
5632    }
5633
5634    #[test]
5635    fn mcp_server_acp_entry_carries_zero_env_pairs_when_the_spec_carries_none() {
5636        let spec = McpServerSpec::new(
5637            "test-mcp-server",
5638            OsString::from("C:\\example\\example-mcp-server.exe"),
5639            vec![OsString::from("--session-proxy")],
5640            Vec::new(),
5641        )
5642        .unwrap();
5643
5644        let server = mcp_server_acp_entry(&spec);
5645        match server {
5646            McpServerConfig::Stdio { env, .. } => assert!(env.is_empty()),
5647            McpServerConfig::Sse { .. } => panic!("expected Stdio variant"),
5648        }
5649    }
5650
5651    #[test]
5652    fn credential_shape_rule_matches_prefixed_hex64_not_bare_digest_or_uuid() {
5653        let hex64 = "a1b2c3d4e5f6".repeat(5) + "a1b2";
5654        assert_eq!(hex64.len(), 64);
5655
5656        let prefixed_token = format!("g4aho_{hex64}");
5657        assert!(
5658            argument_looks_like_credential(&prefixed_token),
5659            "a short lowercase prefix plus '_' plus 64 lowercase hex chars is a credential"
5660        );
5661
5662        assert!(
5663            !argument_looks_like_credential(&hex64),
5664            "a bare 64-hex digest with no prefix is a legitimate diagnostic, not a credential"
5665        );
5666
5667        assert!(
5668            !argument_looks_like_credential("550e8400-e29b-41d4-a716-446655440000"),
5669            "a UUID must not be mistaken for a prefixed-hex64 credential"
5670        );
5671    }
5672
5673    #[test]
5674    fn native_instance_launch_arguments_fail_closed_before_shell_spawn() {
5675        let claude = AgentId::new("claude").unwrap();
5676        assert_eq!(
5677            validate_instance_launch_arguments(
5678                &claude,
5679                TransportKind::Pipe,
5680                &[OsString::from("--bundle-mode")],
5681            )
5682            .unwrap_err(),
5683            "native instance launch arguments require PTY transport (or Codex -c overlays on ACP)"
5684        );
5685        assert_eq!(
5686            validate_instance_launch_arguments(
5687                &claude,
5688                TransportKind::Pty,
5689                &[OsString::from("--resume=session-secret")],
5690            )
5691            .unwrap_err(),
5692            "native instance launch arguments conflict with Claude session, resume, or prompt authority"
5693        );
5694        assert!(validate_instance_launch_arguments(
5695            &claude,
5696            TransportKind::Pty,
5697            &[
5698                OsString::from("--permission-mode"),
5699                OsString::from("default"),
5700            ],
5701        )
5702        .is_ok());
5703    }
5704
5705    /// Classifies `contents` and returns just the `kind` -- the same check
5706    /// every case below cares about, without repeating `.map(|gate|
5707    /// gate.kind)` at every call site.
5708    fn kind_of(contents: &str) -> Option<OperatorGateKind> {
5709        startup_operator_gate(contents).map(|gate| gate.kind)
5710    }
5711
5712    #[test]
5713    fn startup_operator_gates_are_classified_without_returning_terminal_text() {
5714        assert_eq!(kind_of(" Trust this\nfolder? "), Some(OperatorGateKind::WorkspaceTrust));
5715        assert_eq!(
5716            kind_of("No auth type is selected"),
5717            Some(OperatorGateKind::Authentication)
5718        );
5719        assert_eq!(
5720            kind_of("Sign in with OpenAI to use Codex"),
5721            Some(OperatorGateKind::Authentication)
5722        );
5723        // Claude's login-method chooser and its OAuth code-paste wait
5724        // screen -- both previously misread as `Ready` because neither
5725        // contains "openai"/"chatgpt"/"codex", so the branch above never
5726        // caught them. Verbatim shape from `terminal-read` on a clean
5727        // macOS arm64 stand with no vendor login.
5728        assert_eq!(
5729            kind_of(
5730                "Claude Code can be used with your Claude subscription or billed based on \
5731                 API usage through your Console account.\n\
5732                 Select login method:\n\
5733                 \u{276f} 1. Claude ...\n\
5734                 2. API usage billing\n\
5735                 3. 3rd-party platform \u{b7} Amazon Bedrock ..."
5736            ),
5737            Some(OperatorGateKind::Authentication)
5738        );
5739        assert_eq!(
5740            kind_of(
5741                "Browser didn't open? Use the url below to sign in (c to copy)\n\
5742                 https://claude.com/oauth/authorize?client_id=abc&redirect_uri=https%3A%2F%2Fconsole.anthropic.com&code_challenge=xyz\n\
5743                 Paste code here"
5744            ),
5745            Some(OperatorGateKind::Authentication)
5746        );
5747        // Ordinary narration reusing "sign in" and "paste" separately, but
5748        // never as the screen's own "paste code" field label, must not
5749        // false-positive -- the same companion-word discipline the
5750        // OpenAI/Codex sign-in branch already applies above.
5751        assert_eq!(
5752            kind_of(
5753                "Once you sign in, copy the generated token and paste it into your .env file; \
5754                 no code entry happens on this screen."
5755            ),
5756            None
5757        );
5758        assert_eq!(
5759            kind_of("Kimi Code Update Available\nInstall update now (0.32.0)\nEnter confirm"),
5760            Some(OperatorGateKind::VendorUpdate)
5761        );
5762        assert_eq!(
5763            kind_of(
5764                "Welcome to Claude Code\nChoose the text style that looks best with your terminal"
5765            ),
5766            Some(OperatorGateKind::TerminalAppearance)
5767        );
5768        assert_eq!(
5769            kind_of(
5770                "Welcome to Claude Code for VS Code\nClaude has context of open files and selected lines"
5771            ),
5772            Some(OperatorGateKind::Onboarding)
5773        );
5774        assert_eq!(
5775            kind_of("Welcome to Claude Code\n❯ Press Enter to continue"),
5776            Some(OperatorGateKind::Onboarding)
5777        );
5778        assert_eq!(kind_of("Welcome to Claude Code\n❯ ready\nEnter to send"), None);
5779        assert_eq!(
5780            kind_of(
5781                "Quick safety check: Is this a project you trust?\nYes, I trust this folder\nNo, continue without these permissions"
5782            ),
5783            Some(OperatorGateKind::WorkspaceTrust)
5784        );
5785        assert_eq!(kind_of("ready for a prompt"), None);
5786        // Regression test for the incident this module fixes: a provider
5787        // CLI's wrapper self-updated via npm before the real agent ever
5788        // launched, and every consumer saw `status: running` on a live PTY
5789        // that was actually showing this text. Verbatim transcript.
5790        assert_eq!(
5791            kind_of(
5792                "Updating Codex via `npm install -g @openai/codex`...\n\
5793                 npm warn cleanup Failed to remove some directories\n\
5794                 Update ran successfully! Please restart Codex."
5795            ),
5796            Some(OperatorGateKind::VendorUpdate)
5797        );
5798        // Regression test for the live-stand incident this branch fixes:
5799        // Codex's startup hook-trust prompt was classified `Ready` because
5800        // no marker recognized it, so a prompt injected into the PTY landed
5801        // in this blocking select-list instead of the agent. Verbatim
5802        // transcript from `terminal-read`, 40x120 -- note this capture wraps
5803        // the `› 1. Review hooks` marker onto the end of the preceding
5804        // sentence, so it is deliberately NOT the clean list shape the
5805        // dedicated option-parsing tests below assert on; this test only
5806        // pins the `kind`, same as it always has.
5807        assert_eq!(
5808            kind_of(
5809                "  Hooks need review\n\
5810                   6 hooks are new or changed.\n\
5811                   Hooks can run outside the sandbox after you trust them.\u{203a} 1. Review hooks\n\
5812                   2. Trust all and continue\n\
5813                   3. Continue without trusting (hooks won't run)  Press enter to confirm or esc to go back"
5814            ),
5815            Some(OperatorGateKind::HookTrust)
5816        );
5817        // Same screen, different hook count -- the match must not depend on
5818        // the number.
5819        assert_eq!(
5820            kind_of(
5821                "  Hooks need review\n\
5822                   42 hooks are new or changed.\n\
5823                   Hooks can run outside the sandbox after you trust them.\u{203a} 1. Review hooks\n\
5824                   2. Trust all and continue\n\
5825                   3. Continue without trusting (hooks won't run)  Press enter to confirm or esc to go back"
5826            ),
5827            Some(OperatorGateKind::HookTrust)
5828        );
5829        // Ordinary agent narration that happens to mention hooks and trust
5830        // must NOT be classified as this gate -- it lacks the screen's own
5831        // "continue without trusting" refusal phrasing.
5832        assert_eq!(
5833            kind_of(
5834                "I reviewed the pre-commit hooks in this repo and they look safe to trust; \
5835                 I'll leave the hooks config as-is and continue with the refactor."
5836            ),
5837            None
5838        );
5839    }
5840
5841    /// Codex's hook-trust prompt rendered as a clean numbered list (the
5842    /// shape actually described by the task this parser was written for,
5843    /// as opposed to the line-wrapped capture pinned by `kind` alone
5844    /// above): `parse_operator_gate_options` reads all three choices, marks
5845    /// the `›`-prefixed one selected, and infers accept/inspect/decline
5846    /// from each option's own verb -- never from its number or position.
5847    #[test]
5848    fn startup_operator_gate_parses_a_numbered_hook_trust_option_list() {
5849        let contents = "Hooks need review\n\
5850             \u{203a} 1. Review hooks\n  \
5851             2. Trust all and continue\n  \
5852             3. Continue without trusting (hooks won't run)\n\
5853             Press enter to confirm or esc to go back";
5854        let gate = startup_operator_gate(contents).expect("hook trust must classify");
5855        assert_eq!(gate.kind, OperatorGateKind::HookTrust);
5856        assert_eq!(gate.input, OperatorGateInput::NumberedList);
5857        assert_eq!(
5858            gate.options,
5859            vec![
5860                gate4agent_types::OperatorGateOption {
5861                    text: "Review hooks".to_owned(),
5862                    semantics: OperatorGateOptionSemantics::Inspect,
5863                    selected: true,
5864                },
5865                gate4agent_types::OperatorGateOption {
5866                    text: "Trust all and continue".to_owned(),
5867                    semantics: OperatorGateOptionSemantics::Accept,
5868                    selected: false,
5869                },
5870                gate4agent_types::OperatorGateOption {
5871                    text: "Continue without trusting (hooks won't run)".to_owned(),
5872                    semantics: OperatorGateOptionSemantics::Decline,
5873                    selected: false,
5874                },
5875            ],
5876        );
5877    }
5878
5879    /// Kimi's workspace-trust prompt rendered as an arrow-navigated list
5880    /// with a description line under each title: `parse_operator_gate_options`
5881    /// reads the two TITLES ("Trust this folder", "Don't trust") as options,
5882    /// marks the `❯`-prefixed one selected, and does NOT mistake either
5883    /// description line (both full sentences, ending in `.`) for a third
5884    /// and fourth option.
5885    #[test]
5886    fn startup_operator_gate_parses_an_arrow_workspace_trust_option_list() {
5887        let contents = "Do you trust the files in this folder?\n  \
5888             Trust this folder\n  \
5889             Enable project MCP servers. Remembered for this folder.\n\u{276f} \
5890             Don't trust\n  \
5891             Exit Kimi Code. Asked again next launch.\n  \
5892             \u{2191}\u{2193} navigate \u{b7} Enter select \u{b7} Esc exit";
5893        let gate = startup_operator_gate(contents).expect("workspace trust must classify");
5894        assert_eq!(gate.kind, OperatorGateKind::WorkspaceTrust);
5895        assert_eq!(gate.input, OperatorGateInput::ArrowList);
5896        assert_eq!(
5897            gate.options,
5898            vec![
5899                gate4agent_types::OperatorGateOption {
5900                    text: "Trust this folder".to_owned(),
5901                    semantics: OperatorGateOptionSemantics::Accept,
5902                    selected: false,
5903                },
5904                gate4agent_types::OperatorGateOption {
5905                    text: "Don't trust".to_owned(),
5906                    semantics: OperatorGateOptionSemantics::Decline,
5907                    selected: true,
5908                },
5909            ],
5910        );
5911    }
5912
5913    /// A matched gate whose screen carries no recognized option list (every
5914    /// other `kind` this module classifies today) must NOT invent one --
5915    /// `input` stays `Unknown` and `options` stays empty, never a guess.
5916    #[test]
5917    fn startup_operator_gate_without_a_recognized_option_list_reports_unknown_input() {
5918        let gate = startup_operator_gate("No auth type is selected")
5919            .expect("authentication must classify");
5920        assert_eq!(gate.kind, OperatorGateKind::Authentication);
5921        assert_eq!(gate.input, OperatorGateInput::Unknown);
5922        assert!(gate.options.is_empty());
5923    }
5924
5925    /// Claude's login-method chooser renders its selected row with a `❯`
5926    /// cursor glyph where Codex draws `›`, and both sit AHEAD of the number rather
5927    /// than ahead of the text. `parse_numbered_gate_option_line` knew only
5928    /// Codex's glyph, so the cursor row failed to parse as an option at
5929    /// all: the list came back one item short AND with nothing marked
5930    /// selected -- observed live on this screen and on Codex's own login
5931    /// chooser. Both glyphs are read now, so all three options are present
5932    /// and the cursor row carries `selected`.
5933    #[test]
5934    fn startup_operator_gate_parses_claudes_login_method_chooser_including_its_cursor_row() {
5935        let contents = "Select login method:\n\
5936             \u{276f} 1. Claude ...\n\
5937             2. API usage billing\n\
5938             3. 3rd-party platform \u{b7} Amazon Bedrock ...";
5939        let gate = startup_operator_gate(contents).expect("authentication must classify");
5940        assert_eq!(gate.kind, OperatorGateKind::Authentication);
5941        assert_eq!(gate.subject, OperatorGateSubject::Account);
5942        assert_eq!(gate.input, OperatorGateInput::NumberedList);
5943        assert_eq!(
5944            gate.options,
5945            vec![
5946                gate4agent_types::OperatorGateOption {
5947                    text: "Claude ...".to_owned(),
5948                    semantics: OperatorGateOptionSemantics::Unknown,
5949                    selected: true,
5950                },
5951                gate4agent_types::OperatorGateOption {
5952                    text: "API usage billing".to_owned(),
5953                    semantics: OperatorGateOptionSemantics::Unknown,
5954                    selected: false,
5955                },
5956                gate4agent_types::OperatorGateOption {
5957                    text: "3rd-party platform \u{b7} Amazon Bedrock ...".to_owned(),
5958                    semantics: OperatorGateOptionSemantics::Unknown,
5959                    selected: false,
5960                },
5961            ],
5962        );
5963    }
5964
5965    /// Claude's OAuth wait screen has no option list at all -- a URL to
5966    /// open and one free-text slot to paste the resulting code back into --
5967    /// so `input` is `TextEntry` with no options, never routed through the
5968    /// numbered/arrow option-list parser.
5969    #[test]
5970    fn startup_operator_gate_oauth_wait_screen_reports_text_entry_input() {
5971        let contents = "Browser didn't open? Use the url below to sign in (c to copy)\n\
5972             https://claude.com/oauth/authorize?client_id=abc&redirect_uri=https%3A%2F%2Fconsole.anthropic.com&code_challenge=xyz\n\
5973             Paste code here";
5974        let gate = startup_operator_gate(contents).expect("oauth wait screen must classify");
5975        assert_eq!(gate.kind, OperatorGateKind::Authentication);
5976        assert_eq!(gate.subject, OperatorGateSubject::Account);
5977        assert_eq!(gate.input, OperatorGateInput::TextEntry);
5978        assert!(gate.options.is_empty());
5979    }
5980
5981    /// `parse_operator_gate_options` is the parser both dedicated tests
5982    /// above exercise indirectly through `startup_operator_gate`; this pins
5983    /// it directly against the same two shapes so a regression in the
5984    /// standalone parser is caught even if some future `kind` branch stops
5985    /// calling it through `operator_gate`.
5986    #[test]
5987    fn parse_operator_gate_options_recognizes_numbered_and_arrow_shapes_and_nothing_else() {
5988        assert_eq!(
5989            parse_operator_gate_options("Press enter to confirm or esc to go back"),
5990            (OperatorGateInput::Unknown, Vec::new()),
5991        );
5992        let (input, options) = parse_operator_gate_options(
5993            "\u{203a} 1. Review hooks\n  2. Trust all and continue",
5994        );
5995        assert_eq!(input, OperatorGateInput::NumberedList);
5996        assert_eq!(options.len(), 2);
5997        let (input, options) = parse_operator_gate_options(
5998            "  Trust this folder\n  Enable project MCP servers. Remembered for this folder.\n\u{276f} Don't trust",
5999        );
6000        assert_eq!(input, OperatorGateInput::ArrowList);
6001        assert_eq!(options.len(), 2);
6002    }
6003
6004    #[test]
6005    fn classify_operator_gate_option_semantics_reads_the_verb_not_the_position() {
6006        assert_eq!(
6007            classify_operator_gate_option_semantics("Review hooks"),
6008            OperatorGateOptionSemantics::Inspect,
6009        );
6010        assert_eq!(
6011            classify_operator_gate_option_semantics("Trust all and continue"),
6012            OperatorGateOptionSemantics::Accept,
6013        );
6014        assert_eq!(
6015            classify_operator_gate_option_semantics("Continue without trusting (hooks won't run)"),
6016            OperatorGateOptionSemantics::Decline,
6017        );
6018        assert_eq!(
6019            classify_operator_gate_option_semantics("Don't trust"),
6020            OperatorGateOptionSemantics::Decline,
6021        );
6022        assert_eq!(
6023            classify_operator_gate_option_semantics("Exit Kimi Code"),
6024            OperatorGateOptionSemantics::Exit,
6025        );
6026        assert_eq!(
6027            classify_operator_gate_option_semantics("Something unrecognized"),
6028            OperatorGateOptionSemantics::Unknown,
6029        );
6030    }
6031
6032    #[test]
6033    fn screen_failure_recognizes_crash_and_missing_command_banners() {
6034        assert_eq!(
6035            screen_failure("thread 'main' panicked at 'index out of bounds', src/main.rs:12:5"),
6036            Some("crash")
6037        );
6038        assert_eq!(
6039            screen_failure("Traceback (most recent call last):\n  File \"a.py\", line 1"),
6040            Some("crash")
6041        );
6042        assert_eq!(
6043            screen_failure("bash: fooagent: command not found"),
6044            Some("missing command")
6045        );
6046        assert_eq!(
6047            screen_failure("C:\\workspace> fooagent\n'fooagent' is not recognized as an internal or external command"),
6048            Some("missing command")
6049        );
6050        assert_eq!(
6051            screen_failure(
6052                "workspace/project $ fooagent: no such file or directory\nworkspace/project $"
6053            ),
6054            Some("missing command")
6055        );
6056        // Bare ENOENT prose with no trailing shell-prompt line is exactly
6057        // the generic case this bucket must NOT fire on alone.
6058        assert_eq!(
6059            screen_failure("The build log mentions no such file or directory near line 40."),
6060            None
6061        );
6062        // `"fatal error:"` was deliberately dropped: a build step inside a
6063        // wrapper script can print this while the real CLI still comes up
6064        // fine, so it is not a crash SHAPE this function trusts at all.
6065        assert_eq!(
6066            screen_failure("fooagent-installer: fatal error: missing header <stdio.h>"),
6067            None
6068        );
6069    }
6070
6071    #[test]
6072    fn screen_failure_recognizes_grok_missing_api_key_banner() {
6073        // Verbatim transcript: Grok launched with no credential configured
6074        // prints exactly this one line and never renders anything else --
6075        // no gate to answer, no crash trace, just a dead PTY a blind
6076        // `Ready` write would silently swallow.
6077        assert_eq!(
6078            screen_failure(
6079                "\u{274c} Error: API key required. Set GROK_API_KEY environment variable, \
6080                 use --api-key flag, or set \"apiKey\" field in ~/.grok/user-settings.json"
6081            ),
6082            Some("missing api key")
6083        );
6084        // Generic prose about needing an API key, with no vendor-specific
6085        // env var name, must not false-positive -- an agent explaining a
6086        // DIFFERENT provider's setup routinely says exactly this.
6087        assert_eq!(
6088            screen_failure(
6089                "You'll need an API key for this provider before it works; check the docs \
6090                 for how to configure one."
6091            ),
6092            None
6093        );
6094    }
6095
6096    #[test]
6097    fn screen_failure_no_longer_has_an_authentication_expired_bucket() {
6098        // Two common words matched anywhere on one 80x24 screen is not a
6099        // signal -- an agent's own prose explaining an auth bug ("the
6100        // token has expired") used to flip a healthy session to `Failing`.
6101        // The bucket is gone entirely, not narrowed.
6102        assert_eq!(
6103            screen_failure("Your session token has expired. Please re-authenticate."),
6104            None
6105        );
6106        assert_eq!(
6107            screen_failure("The stored credential was revoked by the workspace admin."),
6108            None
6109        );
6110    }
6111
6112    #[test]
6113    fn screen_failure_does_not_false_positive_on_an_agent_narrating_an_error() {
6114        // The false-positive direction matters more than coverage here: an
6115        // agent CLI renders arbitrary text back at a human, including logs
6116        // and error messages it was asked to explain. None of the phrases
6117        // below are in the exact failure SHAPE this module matches on.
6118        let narration = "I looked at the traceback you pasted -- it's a Python \
6119             exception, a plain ValueError from a retry loop, not a real crash. \
6120             Our harness logs the word fatal in its own banner for visibility, \
6121             but nothing actually panicked. The command definitely exists; it \
6122             just needed different flags, and your token is still valid.";
6123        assert_eq!(screen_failure(narration), None);
6124    }
6125
6126    #[test]
6127    fn screen_failure_for_generation_ignores_every_marker_once_the_session_was_ever_ready() {
6128        // Each of these is a screen from a HEALTHY, already-`Ready` session
6129        // whose own routine work happens to render a crash-shaped string.
6130        // This is the regression this whole gate exists to close: before
6131        // it, every one of these flipped a working session to `Failing`.
6132        let shell_command_not_found = "$ frobnicate --help\nbash: frobnicate: command not found\n$";
6133        assert_eq!(
6134            screen_failure_for_generation(shell_command_not_found, true),
6135            None
6136        );
6137
6138        let python_traceback_from_a_ran_script = "$ python broken.py\n\
6139             Traceback (most recent call last):\n  File \"broken.py\", line 3, in <module>\n\
6140             ValueError: bad input\n$";
6141        assert_eq!(
6142            screen_failure_for_generation(python_traceback_from_a_ran_script, true),
6143            None
6144        );
6145
6146        let cargo_test_panic = "running 1 test\n\
6147             error[E0308]: mismatched types\n\
6148             thread 'tests::it_fails' panicked at 'assertion failed', src/lib.rs:9:5\n\
6149             test result: FAILED. 0 passed; 1 failed";
6150        assert_eq!(screen_failure_for_generation(cargo_test_panic, true), None);
6151
6152        let agent_narrating_an_expired_token = "The API token has expired; \
6153             I revoked the old credential and issued a new one for you.";
6154        assert_eq!(
6155            screen_failure_for_generation(agent_narrating_an_expired_token, true),
6156            None
6157        );
6158
6159        // Pin the narrowing from the other side too: the exact same
6160        // screens are still real evidence of a broken LAUNCH inside the
6161        // startup window, before this generation has ever rendered its
6162        // own UI.
6163        assert_eq!(
6164            screen_failure_for_generation(shell_command_not_found, false),
6165            Some("missing command")
6166        );
6167        assert_eq!(
6168            screen_failure_for_generation(python_traceback_from_a_ran_script, false),
6169            Some("crash")
6170        );
6171        assert_eq!(screen_failure_for_generation(cargo_test_panic, false), Some("crash"));
6172    }
6173
6174    #[test]
6175    fn classify_pty_screen_state_lets_a_foreign_process_win_over_a_matching_gate_text() {
6176        // The process signal outranks the text signal outright: it does not
6177        // need to recognize an updater's specific wording to know the
6178        // screen is not the agent's, so it wins even when the text ALSO
6179        // happens to match a known gate pattern.
6180        let foreign = ForegroundVerdict::Foreign {
6181            process: "npm".to_owned(),
6182        };
6183        assert_eq!(
6184            classify_pty_screen_state(Some(&foreign), None, None),
6185            PtyScreenState::NotAgent {
6186                observed_process: "npm".to_owned()
6187            }
6188        );
6189        let vendor_update_gate = OperatorGateState::new(OperatorGateKind::VendorUpdate);
6190        assert_eq!(
6191            classify_pty_screen_state(Some(&foreign), Some(&vendor_update_gate), None),
6192            PtyScreenState::NotAgent {
6193                observed_process: "npm".to_owned()
6194            }
6195        );
6196    }
6197
6198    #[test]
6199    fn classify_pty_screen_state_reports_a_gate_only_when_foreground_matches() {
6200        let authentication_gate = OperatorGateState::new(OperatorGateKind::Authentication);
6201        assert_eq!(
6202            classify_pty_screen_state(Some(&ForegroundVerdict::Agent), Some(&authentication_gate), None),
6203            PtyScreenState::OperatorGate {
6204                gate: authentication_gate.clone()
6205            }
6206        );
6207    }
6208
6209    #[test]
6210    fn classify_pty_screen_state_reports_failing_for_a_matched_foreground() {
6211        assert_eq!(
6212            classify_pty_screen_state(Some(&ForegroundVerdict::Agent), None, Some("crash")),
6213            PtyScreenState::Failing {
6214                reason: "crash".to_owned()
6215            }
6216        );
6217    }
6218
6219    #[test]
6220    fn classify_pty_screen_state_prefers_failing_over_a_co_occurring_gate() {
6221        // Pins the precedence: a crashed screen can still carry a leftover
6222        // gate prompt above the crash dump, and `Failing` is the more
6223        // urgent of the two truths.
6224        let authentication_gate = OperatorGateState::new(OperatorGateKind::Authentication);
6225        assert_eq!(
6226            classify_pty_screen_state(
6227                Some(&ForegroundVerdict::Agent),
6228                Some(&authentication_gate),
6229                Some("crash")
6230            ),
6231            PtyScreenState::Failing {
6232                reason: "crash".to_owned()
6233            }
6234        );
6235    }
6236
6237    #[test]
6238    fn classify_pty_screen_state_reaches_ready_only_with_matched_foreground_and_clean_text() {
6239        assert_eq!(
6240            classify_pty_screen_state(Some(&ForegroundVerdict::Agent), None, None),
6241            PtyScreenState::Ready
6242        );
6243    }
6244
6245    #[test]
6246    fn classify_pty_screen_state_never_reaches_ready_without_a_foreground_observation() {
6247        // The one case that must never regress: a clean text read alone is
6248        // never proof of `Ready`.
6249        assert_eq!(classify_pty_screen_state(None, None, None), PtyScreenState::Unknown);
6250    }
6251
6252    #[test]
6253    fn resolve_foreground_verdict_tolerates_a_spawning_wrapper_like_readiness_does() {
6254        // The fixture spec's `expected_processes` does not name "node", so
6255        // this only passes if the wrapper-tolerance branch (mirroring
6256        // `ReadinessTracker::observe_foreground`'s own `node`/`python`/
6257        // `python3` tolerance) is actually what resolves it -- proving the
6258        // existing wrapper tolerance is not regressed. Fed into
6259        // `classify_pty_screen_state` with clean text, this is what reaches
6260        // `Ready` rather than `NotAgent` for a legitimate spawning wrapper.
6261        let spec = gate4agent_testkit::interactive_agent_spec();
6262        let observation = PtyForegroundObservation {
6263            root_pid: 1,
6264            observed_pid: 2,
6265            observed_process: "node".to_owned(),
6266            readiness: ForegroundObservation {
6267                process_name: Some("node".to_owned()),
6268                has_child_processes: true,
6269                is_shell: false,
6270            },
6271            source: PtyForegroundSource::ProcessTree,
6272        };
6273        let verdict = resolve_foreground_verdict(&spec, &observation, RuntimePlatform::current());
6274        assert_eq!(verdict, ForegroundVerdict::Agent);
6275        assert_eq!(
6276            classify_pty_screen_state(Some(&verdict), None, None),
6277            PtyScreenState::Ready
6278        );
6279    }
6280
6281    #[test]
6282    fn foreground_probe_disarms_only_once_ready_and_rearms_on_a_fresh_gate() {
6283        assert_eq!(
6284            foreground_probe_schedule(&PtyScreenState::Ready),
6285            ForegroundProbeSchedule::Disarmed
6286        );
6287        assert_eq!(
6288            foreground_probe_schedule(&PtyScreenState::Unknown),
6289            ForegroundProbeSchedule::Armed
6290        );
6291        assert_eq!(
6292            foreground_probe_schedule(&PtyScreenState::OperatorGate {
6293                gate: OperatorGateState::new(OperatorGateKind::VendorUpdate)
6294            }),
6295            ForegroundProbeSchedule::Armed
6296        );
6297    }
6298
6299    #[test]
6300    fn text_only_gate_transition_rearms_the_probe_only_when_leaving_ready() {
6301        let gate = PtyScreenState::OperatorGate {
6302            gate: OperatorGateState::new(OperatorGateKind::VendorUpdate),
6303        };
6304        assert!(foreground_probe_rearms_immediately(
6305            &PtyScreenState::Ready,
6306            &gate
6307        ));
6308        // Was never `Ready` in the first place -- nothing to rearm early
6309        // for, the session's normal cadence already has it covered.
6310        assert!(!foreground_probe_rearms_immediately(
6311            &PtyScreenState::Unknown,
6312            &gate
6313        ));
6314    }
6315
6316    #[test]
6317    fn readiness_diagnostics_detects_an_ansi_split_gate_without_exposing_text() {
6318        let mut diagnostics = ReadinessDiagnostics::default();
6319        diagnostics.observe_output(b"\x1b[31mNo auth ");
6320        diagnostics.observe_output(b"\x1b[0mtype is selected");
6321        assert_eq!(
6322            diagnostics.operator_gate.as_ref().map(|gate| gate.kind),
6323            Some(OperatorGateKind::Authentication)
6324        );
6325        assert!(!diagnostics.summary().contains("No auth"));
6326    }
6327
6328    #[test]
6329    fn semantic_utf8_decoder_preserves_codepoints_split_across_pty_reads() {
6330        let mut decoder = Utf8ChunkDecoder::default();
6331        let bytes = "ready Привет".as_bytes();
6332        let split = bytes
6333            .windows(2)
6334            .position(|window| window[0] >= 0x80 && window[1] >= 0x80)
6335            .expect("Cyrillic text contains adjacent UTF-8 bytes")
6336            + 1;
6337        let first = decoder.push(&bytes[..split]);
6338        let second = decoder.push(&bytes[split..]);
6339        assert_eq!(format!("{first}{second}"), "ready Привет");
6340        assert!(!first.contains('\u{fffd}'));
6341        assert!(!second.contains('\u{fffd}'));
6342    }
6343
6344    #[test]
6345    fn semantic_utf8_decoder_replaces_invalid_bytes_without_stalling() {
6346        let mut decoder = Utf8ChunkDecoder::default();
6347        assert_eq!(decoder.push(b"ok\xfftail"), "ok\u{fffd}tail");
6348        assert_eq!(decoder.push(" Привет".as_bytes()), " Привет");
6349    }
6350
6351    #[test]
6352    fn fresh_claude_pty_preassigns_the_exact_vendor_session_id_argv() {
6353        let claude = builtin_adapter_registry()
6354            .binding(AdapterFamily::PtySemantic, "claude-code")
6355            .expect("Claude PTY binding");
6356        let mut args = Vec::new();
6357        let identity = prepare_fresh_pty_provider_session(Some(claude), false, true, &mut args)
6358            .expect("fresh Claude provider identity");
6359        let parsed = uuid::Uuid::parse_str(&identity.id).expect("valid Claude UUID");
6360        assert_eq!(parsed.get_version_num(), 4);
6361        assert_eq!(identity.key, gate4agent_types::ProviderSessionKey::SessionId);
6362        assert!(identity.transcript_path.is_none());
6363        assert_eq!(args, [OsString::from("--session-id"), OsString::from(identity.id)]);
6364    }
6365
6366    #[test]
6367    fn fresh_codex_and_resumed_claude_do_not_preassign_a_second_identity() {
6368        let adapters = builtin_adapter_registry();
6369        let codex = adapters
6370            .binding(AdapterFamily::PtySemantic, "codex")
6371            .expect("Codex PTY binding");
6372        let claude = adapters
6373            .binding(AdapterFamily::PtySemantic, "claude-code")
6374            .expect("Claude PTY binding");
6375        let mut codex_args = Vec::new();
6376        assert!(prepare_fresh_pty_provider_session(Some(codex), false, true, &mut codex_args)
6377            .is_none());
6378        assert!(codex_args.is_empty());
6379
6380        let mut resume_args = vec![OsString::from("--resume"), OsString::from("vendor-id")];
6381        assert!(prepare_fresh_pty_provider_session(Some(claude), true, true, &mut resume_args)
6382            .is_none());
6383        assert_eq!(
6384            resume_args,
6385            [OsString::from("--resume"), OsString::from("vendor-id")]
6386        );
6387    }
6388
6389    #[test]
6390    fn raw_pty_policy_omits_all_identity_and_semantic_startup_paths() {
6391        let adapters = builtin_adapter_registry();
6392        let claude = adapters
6393            .binding(AdapterFamily::PtySemantic, "claude-code")
6394            .expect("Claude PTY binding");
6395        let codex = adapters
6396            .binding(AdapterFamily::PtySemantic, "codex")
6397            .expect("Codex PTY binding");
6398        let kimi = adapters
6399            .binding(AdapterFamily::PtySemantic, "kimi")
6400            .expect("Kimi PTY binding");
6401        let policy = ProviderRuntimePolicy::raw_pty();
6402        let mut args = Vec::new();
6403
6404        assert!(prepare_fresh_pty_provider_session(Some(claude), false, false, &mut args)
6405            .is_none());
6406        assert!(args.is_empty());
6407        assert!(!should_probe_pty_identity(policy, Some(codex), false, "codex"));
6408        assert!(!should_probe_pty_identity(policy, Some(kimi), false, "kimi"));
6409        assert!(!should_attach_pty_provider_stream(policy));
6410    }
6411
6412    #[test]
6413    fn identity_probe_requires_structured_prompt_for_codex_and_kimi() {
6414        let adapters = builtin_adapter_registry();
6415        let codex = adapters
6416            .binding(AdapterFamily::PtySemantic, "codex")
6417            .expect("Codex PTY binding");
6418        let kimi = adapters
6419            .binding(AdapterFamily::PtySemantic, "kimi")
6420            .expect("Kimi PTY binding");
6421        let without_structured_prompt =
6422            ProviderRuntimePolicy::new(true, true, false, true, false, false)
6423                .expect("identity observation policy without structured prompt");
6424
6425        assert!(!should_probe_pty_identity(
6426            without_structured_prompt,
6427            Some(codex),
6428            false,
6429            "codex",
6430        ));
6431        assert!(!should_probe_pty_identity(
6432            without_structured_prompt,
6433            Some(kimi),
6434            false,
6435            "kimi",
6436        ));
6437
6438        let with_structured_prompt =
6439            ProviderRuntimePolicy::new(true, true, true, true, false, false)
6440                .expect("identity probe policy");
6441        assert!(should_probe_pty_identity(
6442            with_structured_prompt,
6443            Some(codex),
6444            false,
6445            "codex",
6446        ));
6447        assert!(should_probe_pty_identity(
6448            with_structured_prompt,
6449            Some(kimi),
6450            false,
6451            "kimi",
6452        ));
6453    }
6454
6455    #[test]
6456    fn runtime_policy_admits_raw_native_resume_but_denies_unverified_prompt_injection() {
6457        let raw = ProviderRuntimePolicy::raw_pty();
6458        assert!(validate_spawn_runtime_policy(raw, TransportKind::Pty, false, false).is_ok());
6459        assert!(validate_spawn_runtime_policy(raw, TransportKind::Pty, true, false)
6460            .unwrap_err()
6461            .contains("SemanticReadiness"));
6462        assert!(validate_spawn_runtime_policy(raw, TransportKind::Pty, false, true).is_ok());
6463        assert!(validate_spawn_runtime_policy(raw, TransportKind::Pty, true, true)
6464            .unwrap_err()
6465            .contains("SemanticReadiness"));
6466
6467        let resume_without_prompt =
6468            ProviderRuntimePolicy::new(true, false, false, true, true, false)
6469                .expect("identity and resume policy");
6470        assert!(validate_spawn_runtime_policy(
6471            resume_without_prompt,
6472            TransportKind::Pty,
6473            false,
6474            true,
6475        )
6476        .is_ok());
6477        assert!(validate_spawn_runtime_policy(
6478            resume_without_prompt,
6479            TransportKind::Pty,
6480            true,
6481            true,
6482        )
6483        .unwrap_err()
6484        .contains("SemanticReadiness"));
6485    }
6486
6487    #[test]
6488    fn acp_transport_bypasses_the_pty_semantic_policy_gate_pty_and_pipe_still_enforce_it() {
6489        // A provider that speaks ACP and nothing else (no raw PTY, no
6490        // verified terminal semantics) admits none of these capabilities --
6491        // exactly grok's real policy. `TransportKind::Acp` must not care:
6492        // ACP has no terminal to infer state from, so none of this policy
6493        // applies to it.
6494        let no_pty_capabilities_at_all = ProviderRuntimePolicy::new(
6495            false, false, false, false, false, false,
6496        )
6497        .expect("an all-false policy is internally valid");
6498        assert!(validate_spawn_runtime_policy(
6499            no_pty_capabilities_at_all,
6500            TransportKind::Acp,
6501            false,
6502            false,
6503        )
6504        .is_ok());
6505        // The same all-false policy is still correctly refused for Pty and
6506        // Pipe -- this fix narrows the gate to skip Acp specifically, it
6507        // does not weaken it for the transports that do need it.
6508        assert!(validate_spawn_runtime_policy(
6509            no_pty_capabilities_at_all,
6510            TransportKind::Pty,
6511            false,
6512            false,
6513        )
6514        .unwrap_err()
6515        .contains("RawPtyLifecycle"));
6516        assert!(validate_spawn_runtime_policy(
6517            no_pty_capabilities_at_all,
6518            TransportKind::Pipe,
6519            false,
6520            false,
6521        )
6522        .unwrap_err()
6523        .contains("RawPtyLifecycle"));
6524    }
6525
6526    #[test]
6527    fn prompt_render_probe_ignores_terminal_wrapping_and_uses_the_tail() {
6528        let prompt = "prefix with spaces\nand punctuation: final-render-token-1234567890";
6529        let probe = prompt_render_probe(prompt);
6530        assert!("screen prefix with spaces and punctuation final render token 1234567890"
6531            .chars()
6532            .filter(|character| character.is_alphanumeric())
6533            .flat_map(char::to_lowercase)
6534            .collect::<String>()
6535            .contains(&probe));
6536        assert!(probe.chars().count() <= 32);
6537    }
6538
6539    #[test]
6540    fn prompt_render_requires_new_sequence_and_visible_tail_evidence() {
6541        let probe = prompt_render_probe("final render token");
6542        let baseline = snapshot(7, "old composer");
6543        assert!(!prompt_rendered(
6544            &snapshot(7, "final\nrender\ntoken"),
6545            &baseline,
6546            &probe
6547        ));
6548        assert!(!prompt_rendered(
6549            &snapshot(8, "unrelated redraw"),
6550            &baseline,
6551            &probe
6552        ));
6553        assert!(prompt_rendered(
6554            &snapshot(8, "composer\nfinal\nrender\ntoken"),
6555            &baseline,
6556            &probe
6557        ));
6558        assert!(prompt_rendered(
6559            &snapshot(8, "composer [Pasted Content 4096 chars]"),
6560            &baseline,
6561            &probe
6562        ));
6563        assert!(prompt_rendered(
6564            &snapshot(8, "composer [Pasted text #1 +6 lines]"),
6565            &baseline,
6566            &probe
6567        ));
6568    }
6569
6570    #[test]
6571    fn an_existing_paste_placeholder_cannot_pass_on_an_unrelated_redraw() {
6572        let probe = prompt_render_probe("a new long prompt");
6573        assert!(!prompt_rendered(
6574            &snapshot(8, "composer [Pasted Content 4096 chars]\nunrelated redraw"),
6575            &snapshot(7, "composer [Pasted Content 4096 chars]"),
6576            &probe
6577        ));
6578        assert!(!prompt_rendered(
6579            &snapshot(8, "composer [Pasted text #1 +6 lines]\nunrelated redraw"),
6580            &snapshot(7, "composer [Pasted text #1 +6 lines]"),
6581            &probe
6582        ));
6583    }
6584
6585    #[test]
6586    fn punctuation_only_prompt_cannot_pass_on_an_unrelated_redraw() {
6587        let probe = prompt_render_probe("!?---");
6588        assert!(probe.is_empty());
6589        assert!(!prompt_rendered(
6590            &snapshot(2, "unrelated redraw"),
6591            &snapshot(1, "old composer"),
6592            &probe
6593        ));
6594    }
6595
6596    #[test]
6597    fn prompt_probe_matches_the_sanitized_terminal_payload() {
6598        let prompt = "payload\u{1b}tail";
6599        let sanitized = gate4agent_types::sanitize_prompt_text(prompt);
6600        let probe = prompt_render_probe(&sanitized);
6601        assert!(prompt_rendered(
6602            &snapshot(2, "composer payload<ESC>tail"),
6603            &snapshot(1, "old composer"),
6604            &probe
6605        ));
6606    }
6607
6608    #[test]
6609    fn lag_and_data_gap_reserve_missed_provider_source_positions() {
6610        let mut next = 7;
6611        assert_eq!(reserve_provider_gap_sequence(&mut next, 3), Some(9));
6612        assert_eq!(next, 10);
6613        assert_eq!(reserve_provider_gap_sequence(&mut next, 0), None);
6614        assert_eq!(next, 10);
6615
6616        next = u64::MAX;
6617        assert_eq!(reserve_provider_gap_sequence(&mut next, 1), None);
6618        assert_eq!(next, u64::MAX);
6619    }
6620
6621    // --- RateLimitFeed: ANSI-stripping and chunk reassembly ---
6622    //
6623    // Regression coverage for a live-stand defect: `provider.rate_limits`
6624    // used to be a bare `RateLimitDetector` fed the RAW PTY stream, escape
6625    // codes and all. codex's own `/status` render puts `\x1b[m` between
6626    // `limit:` and the progress bar, and `\x1b[2m` between `left` and
6627    // `(resets ...)` -- both inside gaps the quota-state regex's `\s*`
6628    // cannot see through -- so not one quota-state fact was ever observed
6629    // on a real run, despite the pattern being correct on clean text.
6630
6631    /// The exact live bytes from the coordinator's capture (real `\x1b[m`
6632    /// and `\x1b[2m`, real `\r\n`), transcribed verbatim.
6633    const CODEX_STATUS_RAW_ANSI: &str = "│  5h limit:             \x1b[m[████████████████████] 100% left\x1b[2m (resets 00:08 on 31 Aug) │\r\n│  Weekly limit:         \x1b[m[████████████████████] 100% left\x1b[2m (resets 19:08 on 6 Sep)  │";
6634
6635    #[test]
6636    fn bare_detector_misses_the_live_ansi_sample_that_rate_limit_feed_catches() {
6637        // This is the defect itself: matching the untouched raw stream
6638        // fails on real codex output, exactly as observed live.
6639        let bare = RateLimitDetector::new_for_tool(CliTool::Codex);
6640        assert!(bare.detect(CODEX_STATUS_RAW_ANSI).is_none());
6641
6642        // `RateLimitFeed` strips ANSI (via `VteParser`) before matching,
6643        // so the same bytes must now be recognized.
6644        let mut feed = RateLimitFeed::new_for_tool(CliTool::Codex);
6645        let info = feed
6646            .detect(CODEX_STATUS_RAW_ANSI)
6647            .expect("quota-state line must be recognized once ANSI is stripped");
6648        assert_eq!(info.limit_type, RateLimitType::Session);
6649        assert_eq!(info.usage_percent, Some(0.0));
6650        assert_eq!(info.resets_at_text.as_deref(), Some("00:08 on 31 Aug"));
6651    }
6652
6653    #[test]
6654    fn rate_limit_feed_reassembles_a_quota_state_line_split_mid_escape_and_mid_row() {
6655        // A live PTY chunk boundary has no reason to land anywhere
6656        // convenient -- here it falls INSIDE the `\x1b[2m` escape itself
6657        // (right after the ESC byte), on top of splitting the row.
6658        let first =
6659            "│  5h limit:             \x1b[m[████████████████████] 100% left\x1b";
6660        let second = "[2m (resets 00:08 on 31 Aug) │\r\n";
6661
6662        let mut feed = RateLimitFeed::new_for_tool(CliTool::Codex);
6663        assert!(
6664            feed.detect(first).is_none(),
6665            "the row is not complete yet, so nothing should match on the first chunk"
6666        );
6667        let info = feed
6668            .detect(second)
6669            .expect("the row completes once the second chunk arrives");
6670        assert_eq!(info.limit_type, RateLimitType::Session);
6671        assert_eq!(info.resets_at_text.as_deref(), Some("00:08 on 31 Aug"));
6672    }
6673
6674    #[test]
6675    fn rate_limit_feed_strips_ansi_before_matching_a_colored_failure_message() {
6676        // Failure patterns run through the same `RateLimitFeed::detect`
6677        // entry point as quota-state ones, so a vendor coloring its own
6678        // refusal text must not defeat detection either.
6679        let raw = "\x1b[31mError: rate limit exceeded\x1b[0m. Please wait.";
6680        let mut feed = RateLimitFeed::new_for_tool(CliTool::Codex);
6681        let info = feed
6682            .detect(raw)
6683            .expect("a colored refusal message must still be recognized");
6684        assert_eq!(info.limit_type, RateLimitType::Unknown);
6685    }
6686
6687    #[test]
6688    fn rate_limit_feed_bounds_its_buffer_across_a_newline_free_redraw() {
6689        // A full-screen redraw with no `\n` at all (cursor-addressing
6690        // only) must not grow the pending-line buffer without bound for
6691        // as long as it runs -- and a real line must still be caught once
6692        // it finally arrives.
6693        let mut feed = RateLimitFeed::new_for_tool(CliTool::Codex);
6694        let noise = "x".repeat(super::RATE_LIMIT_FEED_BUFFER_MAX_BYTES * 3);
6695        assert!(feed.detect(&noise).is_none());
6696        assert!(feed.buffer.len() <= super::RATE_LIMIT_FEED_BUFFER_MAX_BYTES);
6697
6698        let info = feed
6699            .detect(CODEX_STATUS_RAW_ANSI)
6700            .expect("a real quota-state line must still be recognized after the noise");
6701        assert_eq!(info.limit_type, RateLimitType::Session);
6702    }
6703
6704    // -----------------------------------------------------------------------
6705    // host_policy_for_approval_level -- ApprovalLevel -> HostPolicy for ACP
6706    // -----------------------------------------------------------------------
6707
6708    #[test]
6709    fn full_auto_maps_to_the_permissive_host_policy() {
6710        // The one combination that must never happen is `FullAuto` paired
6711        // with a refusing `HostPolicy` -- the process believes it has full
6712        // autonomy while the host silently refuses it.
6713        assert_eq!(host_policy_for_approval_level(ApprovalLevel::FullAuto), HostPolicy::Yolo);
6714    }
6715
6716    #[test]
6717    fn read_only_maps_to_the_read_only_host_policy() {
6718        assert_eq!(
6719            host_policy_for_approval_level(ApprovalLevel::ReadOnly),
6720            HostPolicy::ReadOnly
6721        );
6722    }
6723
6724    #[test]
6725    fn moderate_and_unmanaged_both_fall_back_to_the_default_host_policy() {
6726        assert_eq!(host_policy_for_approval_level(ApprovalLevel::Moderate), HostPolicy::Auto);
6727        assert_eq!(host_policy_for_approval_level(ApprovalLevel::Unmanaged), HostPolicy::Auto);
6728        assert_eq!(HostPolicy::default(), HostPolicy::Auto);
6729    }
6730
6731    #[test]
6732    fn no_approval_level_ever_maps_to_a_refusing_policy_except_read_only_itself() {
6733        // Guards the "never full auto + refusing host" invariant generally:
6734        // `Deny` must never be reachable from this mapping at all -- it is
6735        // not one of the four `ApprovalLevel` outcomes, only `ReadOnly`'s
6736        // own deliberate restriction is.
6737        for level in [
6738            ApprovalLevel::FullAuto,
6739            ApprovalLevel::Moderate,
6740            ApprovalLevel::ReadOnly,
6741            ApprovalLevel::Unmanaged,
6742        ] {
6743            assert_ne!(
6744                host_policy_for_approval_level(level),
6745                HostPolicy::Deny,
6746                "{level:?} must never map to HostPolicy::Deny"
6747            );
6748        }
6749    }
6750
6751    // -----------------------------------------------------------------------
6752    // defers_permission_requests -- reads `asks_for_permission` off the
6753    // catalog's per-(provider, level) vendor-mode table instead of matching
6754    // on the ApprovalLevel's own name (the bug this whole axis exists to
6755    // remove -- see the function's own doc comment).
6756    // -----------------------------------------------------------------------
6757
6758    #[test]
6759    fn defers_permission_requests_matches_the_verified_provider_table() {
6760        // Source of truth: `gate4agent_catalog::launch::approval_level_resolution`
6761        // at HEAD (commit 7b6a8d2) and
6762        // `docs/gate4agent/audits/gate4agent-acp-slice1-proof-2026-09-02.md`
6763        // (session/new modes measured live, 2026-09-02).
6764        let claude = AgentId::new("claude").unwrap();
6765        assert!(!defers_permission_requests(&claude, ApprovalLevel::FullAuto));
6766        assert!(defers_permission_requests(&claude, ApprovalLevel::Moderate));
6767        // claude's `ReadOnly` now launches `default` (`plan` neither refuses
6768        // nor asks over ACP, measured twice) -- claude's own interactive
6769        // mode, which does ask about every write.
6770        assert!(defers_permission_requests(&claude, ApprovalLevel::ReadOnly));
6771        // `Unmanaged` never defers: it decides `session/request_permission`
6772        // immediately (auto-approve), since some providers' ACP clients
6773        // won't wait out a parked decision.
6774        assert!(!defers_permission_requests(&claude, ApprovalLevel::Unmanaged));
6775
6776        let codex = AgentId::new("codex").unwrap();
6777        assert!(!defers_permission_requests(&codex, ApprovalLevel::FullAuto));
6778        // codex's `Moderate` ACP mode (`agent`, "Approve for me") wrote and
6779        // reported success with no `session/request_permission` at all --
6780        // measured live, unlike the PTY `on-request` flag it shares a row
6781        // with.
6782        assert!(!defers_permission_requests(&codex, ApprovalLevel::Moderate));
6783        assert!(defers_permission_requests(&codex, ApprovalLevel::ReadOnly));
6784        // `Unmanaged` never defers -- see the claude row's comment above.
6785        assert!(!defers_permission_requests(&codex, ApprovalLevel::Unmanaged));
6786
6787        let grok = AgentId::new("grok").unwrap();
6788        assert!(!defers_permission_requests(&grok, ApprovalLevel::FullAuto));
6789        assert!(defers_permission_requests(&grok, ApprovalLevel::Moderate));
6790        // `ReadOnly` is `Unsupported` for grok -- the ACP spawn branch must
6791        // already have refused the session before this function would ever
6792        // see it live; the conservative fallback here still defers.
6793        assert!(defers_permission_requests(&grok, ApprovalLevel::ReadOnly));
6794        // `Unmanaged` never defers -- see the claude row's comment above.
6795        assert!(!defers_permission_requests(&grok, ApprovalLevel::Unmanaged));
6796
6797        let kimi = AgentId::new("kimi").unwrap();
6798        assert!(!defers_permission_requests(&kimi, ApprovalLevel::FullAuto));
6799        // kimi's `Moderate` ACP mode is genuinely named `auto` and wrote
6800        // silently, measured live -- it does not ask.
6801        assert!(!defers_permission_requests(&kimi, ApprovalLevel::Moderate));
6802        // kimi's `ReadOnly` ACP mode (`plan`) refuses silently rather than
6803        // asking -- measured live, a write outside the working directory
6804        // produced no question at all.
6805        assert!(!defers_permission_requests(&kimi, ApprovalLevel::ReadOnly));
6806        // `Unmanaged` never defers -- see the claude row's comment above.
6807        assert!(!defers_permission_requests(&kimi, ApprovalLevel::Unmanaged));
6808    }
6809
6810    // -----------------------------------------------------------------------
6811    // required_acp_mode / approval_level_not_offered_message -- Item 3's
6812    // table: one row per provider x level, plus the regression guard that
6813    // `auto` is unreachable without an explicit choice.
6814    // -----------------------------------------------------------------------
6815
6816    fn session_mode(id: &str) -> SessionMode {
6817        SessionMode { id: id.to_owned(), name: id.to_owned(), description: None }
6818    }
6819
6820    #[test]
6821    fn required_acp_mode_matches_the_sourced_table() {
6822        // Source of truth: `gate4agent_catalog::launch::approval_level_resolution`
6823        // at HEAD (commit 7b6a8d2) and
6824        // `docs/gate4agent/audits/gate4agent-acp-slice1-proof-2026-09-02.md`
6825        // (session/new modes measured live, 2026-09-02).
6826        let claude = AgentId::new("claude").unwrap();
6827        assert_eq!(
6828            required_acp_mode(&claude, ApprovalLevel::FullAuto),
6829            Ok(Some(ModeId::new("bypassPermissions")))
6830        );
6831        assert_eq!(
6832            required_acp_mode(&claude, ApprovalLevel::Moderate),
6833            Ok(Some(ModeId::new("acceptEdits")))
6834        );
6835        // measured live: `plan` neither refuses nor asks over ACP, so
6836        // `ReadOnly` moved to `default`, the one claude mode where both an
6837        // in-cwd and an out-of-cwd write raised `session/request_permission`.
6838        assert_eq!(
6839            required_acp_mode(&claude, ApprovalLevel::ReadOnly),
6840            Ok(Some(ModeId::new("default")))
6841        );
6842        assert_eq!(required_acp_mode(&claude, ApprovalLevel::Unmanaged), Ok(None));
6843
6844        let codex = AgentId::new("codex").unwrap();
6845        assert_eq!(
6846            required_acp_mode(&codex, ApprovalLevel::FullAuto),
6847            Ok(Some(ModeId::new("agent-full-access")))
6848        );
6849        assert_eq!(
6850            required_acp_mode(&codex, ApprovalLevel::Moderate),
6851            Ok(Some(ModeId::new("agent")))
6852        );
6853        assert_eq!(
6854            required_acp_mode(&codex, ApprovalLevel::ReadOnly),
6855            Ok(Some(ModeId::new("read-only")))
6856        );
6857        assert_eq!(required_acp_mode(&codex, ApprovalLevel::Unmanaged), Ok(None));
6858
6859        // kimi: `acp_mode_id` is `None` for every managed level -- measured
6860        // 2026-09-05, `kimi.exe` 0.29.0's `session/new` result carries
6861        // `configOptions` (a `model` select) and no `modes` field at all.
6862        // The 2026-09-02 `yolo`/`auto`/`plan` measurement this table used to
6863        // pin was a different build: the npm shell shim running under WSL
6864        // interop, not this native binary.
6865        // `FullAuto` is the one kimi level that carries vendor flags
6866        // (`--yolo`), so argv applies it and there is nothing left to refuse;
6867        // `Moderate`/`ReadOnly` carry none (their `--auto`/`--plan` remain
6868        // UNCONFIRMED under `kimi acp`) and still refuse, because for those
6869        // no mechanism exists at all.
6870        let kimi = AgentId::new("kimi").unwrap();
6871        assert_eq!(required_acp_mode(&kimi, ApprovalLevel::FullAuto), Ok(None));
6872        assert_eq!(
6873            acp_approval_level_args(&kimi, ApprovalLevel::FullAuto),
6874            vec!["--auto".to_owned()],
6875            "kimi's FullAuto must reach the process through argv, since it has no ACP mode"
6876        );
6877        for level in [ApprovalLevel::Moderate, ApprovalLevel::ReadOnly] {
6878            assert!(
6879                required_acp_mode(&kimi, level).is_err(),
6880                "kimi at {level:?} has neither a sourced ACP mode id nor vendor flags, so it must refuse"
6881            );
6882        }
6883        assert_eq!(required_acp_mode(&kimi, ApprovalLevel::Unmanaged), Ok(None));
6884        assert!(
6885            acp_approval_level_args(&kimi, ApprovalLevel::Unmanaged).is_empty(),
6886            "Unmanaged imposes nothing, so it must add no argv flags either"
6887        );
6888
6889        // grok: `acp_mode_id` is `None` for every managed level (no live
6890        // mode catalogue sourced yet — slice-1 skipped grok). `FullAuto` and
6891        // `Moderate` are `Supported` with argv flags, so they resolve
6892        // `Ok(None)` and apply through argv; `ReadOnly` is outright
6893        // `Unsupported` and refuses. Flag spellings for FullAuto remain
6894        // UNCONFIRMED against Grok Build's own CLI surface (catalog docs).
6895        let grok = AgentId::new("grok").unwrap();
6896        assert_eq!(required_acp_mode(&grok, ApprovalLevel::FullAuto), Ok(None));
6897        assert_eq!(
6898            acp_approval_level_args(&grok, ApprovalLevel::FullAuto),
6899            vec!["--always-approve".to_owned()],
6900        );
6901        assert_eq!(required_acp_mode(&grok, ApprovalLevel::Moderate), Ok(None));
6902        assert_eq!(
6903            acp_approval_level_args(&grok, ApprovalLevel::Moderate),
6904            vec!["--permission-mode".to_owned(), "auto".to_owned()],
6905        );
6906        assert!(
6907            required_acp_mode(&grok, ApprovalLevel::ReadOnly).is_err(),
6908            "grok at ReadOnly is Unsupported outright, so it must refuse"
6909        );
6910        assert_eq!(required_acp_mode(&grok, ApprovalLevel::Unmanaged), Ok(None));
6911    }
6912
6913    /// The regression guard for the whole change: no provider x level may
6914    /// silently resolve to nothing (which would leave the session running
6915    /// at the agent's own default, e.g. the live-measured `auto`) unless the
6916    /// level itself is `Unmanaged`. Every other level is either a concrete
6917    /// mode id or an outright refusal. kimi no longer has an exception here:
6918    /// measured 2026-09-05, `kimi.exe` 0.29.0 offers no ACP modes at all, so
6919    /// every one of its managed levels now refuses (`Err`) rather than
6920    /// sourcing a mode id -- the `Moderate` row's `auto` exception this
6921    /// guard used to carry was the 2026-09-02 npm-shim-under-WSL-interop
6922    /// measurement, a different build.
6923    #[test]
6924    fn required_acp_mode_never_silently_permits_auto_except_for_unmanaged() {
6925        for id in ["claude", "codex", "grok", "kimi"] {
6926            let agent = AgentId::new(id).unwrap();
6927            for level in [ApprovalLevel::FullAuto, ApprovalLevel::Moderate, ApprovalLevel::ReadOnly] {
6928                match required_acp_mode(&agent, level) {
6929                    Ok(Some(mode_id)) => assert_ne!(
6930                        mode_id.as_str(),
6931                        "auto",
6932                        "{id} at {level:?} must never silently resolve the vendor's own default 'auto'"
6933                    ),
6934                    Ok(None) => assert!(
6935                        !acp_approval_level_args(&agent, level).is_empty(),
6936                        "{id} at {level:?} resolved Ok(None) while carrying no vendor flags -- \
6937                         that leaves the session at the agent's own default. Only Unmanaged, or a \
6938                         level argv actually applies, may resolve to no mode"
6939                    ),
6940                    Err(_) => {} // refused outright -- also never reaches `auto`
6941                }
6942            }
6943            assert_eq!(
6944                required_acp_mode(&agent, ApprovalLevel::Unmanaged),
6945                Ok(None),
6946                "{id}: Unmanaged is the one level allowed to apply nothing"
6947            );
6948        }
6949    }
6950
6951    #[test]
6952    fn approval_level_not_offered_message_refuses_by_name_and_lists_what_was_offered() {
6953        let offered = vec![session_mode("bypassPermissions"), session_mode("default")];
6954        let mode_id = ModeId::new("plan");
6955        let message = approval_level_not_offered_message(ApprovalLevel::ReadOnly, &mode_id, &offered)
6956            .expect("'plan' was not among the offered modes");
6957        assert!(message.contains("ApprovalLevelNotOfferedByAgent"));
6958        assert!(message.contains("bypassPermissions"));
6959        assert!(message.contains("default"));
6960        assert!(message.contains("ReadOnly"));
6961    }
6962
6963    #[test]
6964    fn approval_level_not_offered_message_is_none_when_the_agent_announced_it() {
6965        let offered = vec![session_mode("plan")];
6966        let mode_id = ModeId::new("plan");
6967        assert_eq!(
6968            approval_level_not_offered_message(ApprovalLevel::ReadOnly, &mode_id, &offered),
6969            None
6970        );
6971    }
6972
6973    #[test]
6974    fn approval_level_not_offered_message_handles_an_agent_that_announces_no_modes_at_all() {
6975        let mode_id = ModeId::new("bypassPermissions");
6976        let message = approval_level_not_offered_message(ApprovalLevel::FullAuto, &mode_id, &[])
6977            .expect("an empty mode catalog never offers anything");
6978        assert!(message.contains("ApprovalLevelNotOfferedByAgent"));
6979        assert!(message.contains("offered: []"));
6980    }
6981
6982    // -----------------------------------------------------------------------
6983    // stop_native — pipe_sessions branch reads `force`.
6984    //
6985    // Regression coverage: this branch used to call
6986    // `owned.session.kill().await` unconditionally, so no headless Pipe run
6987    // could ever end any way other than a forced kill regardless of what the
6988    // caller asked for. `PipeSession::stop`'s own unit tests (`gate4agent`'s
6989    // `pipe::session::tests`) cover the graceful-wait/bound-elapse timing in
6990    // depth; these two only prove the NEW wiring in `stop_native` itself:
6991    // `force` reaches `PipeSession::stop`, and its `PipeStopOutcome` maps
6992    // onto `ControlObservation::StopCompleted` correctly. Built by inserting
6993    // directly into `pipe_sessions` (private field, visible to this child
6994    // module) rather than through `execute()`/`EffectEnvelope`, so this does
6995    // not depend on the catalog/spawn-plan machinery at all.
6996    // -----------------------------------------------------------------------
6997
6998    use super::{NativeEffectShell, NativeSessionKey, OwnedProviderSession};
6999    use gate4agent_catalog::{AgentRegistry as FixtureAgentRegistry, AgentSpec as FixtureAgentSpec};
7000    use gate4agent_types::ControlObservation;
7001    use std::collections::VecDeque;
7002
7003    fn fixture_pipe_key() -> NativeSessionKey {
7004        NativeSessionKey {
7005            instance_id: gate4agent_types::AgentInstanceId(9_001),
7006            generation: gate4agent_types::SessionGeneration(1),
7007        }
7008    }
7009
7010    fn fixture_pipe_source() -> gate4agent_types::ProviderSource {
7011        gate4agent_types::ProviderSource {
7012            family: AdapterFamily::Pipe,
7013            binding: gate4agent_types::AdapterBinding::new(
7014                gate4agent_types::AdapterId::new("fixture").unwrap(),
7015                "1",
7016                gate4agent_types::AdapterVerification::SyntheticFixture,
7017            )
7018            .unwrap(),
7019        }
7020    }
7021
7022    #[cfg(windows)]
7023    fn fixture_graceful_exit_launch() -> gate4agent_types::LaunchSpec {
7024        gate4agent_types::LaunchSpec {
7025            program: "powershell.exe".to_owned(),
7026            fixed_args: vec![
7027                "-NoProfile".to_owned(),
7028                "-NonInteractive".to_owned(),
7029                "-Command".to_owned(),
7030                "[Console]::In.ReadToEnd() | Out-Null; exit 0".to_owned(),
7031            ],
7032        }
7033    }
7034
7035    #[cfg(not(windows))]
7036    fn fixture_graceful_exit_launch() -> gate4agent_types::LaunchSpec {
7037        gate4agent_types::LaunchSpec {
7038            program: "sh".to_owned(),
7039            fixed_args: vec!["-c".to_owned(), "cat >/dev/null; exit 0".to_owned()],
7040        }
7041    }
7042
7043    #[cfg(windows)]
7044    fn fixture_ignore_stdin_launch() -> gate4agent_types::LaunchSpec {
7045        gate4agent_types::LaunchSpec {
7046            program: "powershell.exe".to_owned(),
7047            fixed_args: vec![
7048                "-NoProfile".to_owned(),
7049                "-NonInteractive".to_owned(),
7050                "-Command".to_owned(),
7051                "Start-Sleep -Seconds 30".to_owned(),
7052            ],
7053        }
7054    }
7055
7056    #[cfg(not(windows))]
7057    fn fixture_ignore_stdin_launch() -> gate4agent_types::LaunchSpec {
7058        gate4agent_types::LaunchSpec {
7059            program: "sh".to_owned(),
7060            fixed_args: vec!["-c".to_owned(), "sleep 30".to_owned()],
7061        }
7062    }
7063
7064    async fn spawn_fixture_pipe_shell(
7065        launch: gate4agent_types::LaunchSpec,
7066    ) -> (NativeEffectShell, NativeSessionKey) {
7067        let session = gate4agent::PipeSession::spawn_with_launch(
7068            gate4agent::core::types::SessionConfig::default(),
7069            "prompt",
7070            &launch,
7071            gate4agent_types::PipePromptDelivery::StdinClose,
7072        )
7073        .await
7074        .expect("fixture pipe process must spawn");
7075        let events = session.subscribe();
7076        let key = fixture_pipe_key();
7077        let mut shell = NativeEffectShell::new(
7078            FixtureAgentRegistry::new(std::iter::empty::<FixtureAgentSpec>())
7079                .expect("empty fixture catalog"),
7080        );
7081        shell.pipe_sessions.insert(
7082            key,
7083            OwnedProviderSession {
7084                source: fixture_pipe_source(),
7085                session,
7086                events,
7087                pending_events: VecDeque::new(),
7088                pending_provider_events: VecDeque::new(),
7089                next_provider_sequence: 1,
7090                observed_exit_code: None,
7091                runtime_policy: gate4agent_types::ProviderRuntimePolicy::none(),
7092            },
7093        );
7094        (shell, key)
7095    }
7096
7097    #[tokio::test]
7098    async fn stop_native_pipe_session_reports_the_real_exit_code_when_not_forced() {
7099        let (mut shell, key) = spawn_fixture_pipe_shell(fixture_graceful_exit_launch()).await;
7100
7101        match shell.stop_native(key, false).await {
7102            ControlObservation::StopCompleted {
7103                forced, exit_code, ..
7104            } => {
7105                assert!(!forced, "a process that exits on its own must not be forced");
7106                assert_eq!(exit_code, Some(0));
7107            }
7108            other => panic!("expected StopCompleted, got {other:?}"),
7109        }
7110    }
7111
7112    #[tokio::test]
7113    async fn stop_native_pipe_session_force_true_kills_immediately_without_waiting() {
7114        let (mut shell, key) = spawn_fixture_pipe_shell(fixture_ignore_stdin_launch()).await;
7115
7116        let start = std::time::Instant::now();
7117        match shell.stop_native(key, true).await {
7118            ControlObservation::StopCompleted { forced, .. } => {
7119                assert!(forced, "force=true must always report forced");
7120            }
7121            other => panic!("expected StopCompleted, got {other:?}"),
7122        }
7123        assert!(
7124            start.elapsed()
7125                < std::time::Duration::from_secs(gate4agent::pipe::PIPE_GRACEFUL_STOP_BOUND_SECS),
7126            "force=true must not wait out the graceful bound"
7127        );
7128    }
7129
7130    // -------------------------------------------------------------------
7131    // stop_native -- acp_sessions branch reads `force`.
7132    //
7133    // Regression coverage: this branch used to call
7134    // `owned.session.kill().await` unconditionally after an optional
7135    // `session/cancel`, so `forced` was always `true` regardless of what
7136    // the caller asked for. Fixture mirrors `gate4agent::acp::session`'s
7137    // own `AcpSession::stop` unit tests (which cover the graceful-wait/
7138    // bound-elapse timing in depth): a minimal handshake responder that
7139    // answers `initialize`/`session/new` and exits 0 on stdin EOF. This
7140    // test only proves the NEW wiring in `stop_native` itself: `force`
7141    // reaches `AcpSession::stop`, and its `AcpStopOutcome` maps onto
7142    // `ControlObservation::StopCompleted` correctly.
7143    // -------------------------------------------------------------------
7144
7145    #[cfg(windows)]
7146    fn acp_fixture_launch() -> gate4agent_types::LaunchSpec {
7147        gate4agent_types::LaunchSpec {
7148            program: "powershell.exe".to_owned(),
7149            fixed_args: vec![
7150                "-NoLogo".to_owned(),
7151                "-NoProfile".to_owned(),
7152                "-NonInteractive".to_owned(),
7153                "-ExecutionPolicy".to_owned(),
7154                "Bypass".to_owned(),
7155                "-Command".to_owned(),
7156                ACP_HANDSHAKE_SCRIPT.to_owned(),
7157            ],
7158        }
7159    }
7160
7161    #[cfg(not(windows))]
7162    fn acp_fixture_launch() -> gate4agent_types::LaunchSpec {
7163        gate4agent_types::LaunchSpec {
7164            program: "python3".to_owned(),
7165            fixed_args: vec!["-u".to_owned(), "-c".to_owned(), ACP_HANDSHAKE_SCRIPT.to_owned()],
7166        }
7167    }
7168
7169    #[cfg(windows)]
7170    const ACP_HANDSHAKE_SCRIPT: &str = r#"[Console]::OutputEncoding=[Text.Encoding]::UTF8
7171function Write-JsonLine($value) { [Console]::WriteLine(($value | ConvertTo-Json -Compress -Depth 12)) }
7172$initialize = [Console]::ReadLine() | ConvertFrom-Json
7173Write-JsonLine @{jsonrpc='2.0';id=$initialize.id;result=@{}}
7174$newSession = [Console]::ReadLine() | ConvertFrom-Json
7175Write-JsonLine @{jsonrpc='2.0';id=$newSession.id;result=@{sessionId='fixture-acp-session'}}
7176while ($true) {
7177    $line = [Console]::ReadLine()
7178    if ($null -eq $line) { exit 0 }
7179}"#;
7180    #[cfg(not(windows))]
7181    const ACP_HANDSHAKE_SCRIPT: &str = r#"import json,sys
7182def read_message():
7183 line=sys.stdin.readline()
7184 if not line: return None
7185 return json.loads(line)
7186def write_message(message):
7187 print(json.dumps(message),flush=True)
7188
7189initialize=read_message()
7190write_message({'jsonrpc':'2.0','id':initialize.get('id'),'result':{}})
7191new_session=read_message()
7192write_message({'jsonrpc':'2.0','id':new_session.get('id'),'result':{'sessionId':'fixture-acp-session'}})
7193while True:
7194 msg=read_message()
7195 if msg is None:
7196  sys.exit(0)"#;
7197
7198    fn fixture_acp_key() -> NativeSessionKey {
7199        NativeSessionKey {
7200            instance_id: gate4agent_types::AgentInstanceId(9_002),
7201            generation: gate4agent_types::SessionGeneration(1),
7202        }
7203    }
7204
7205    fn fixture_acp_source() -> gate4agent_types::ProviderSource {
7206        gate4agent_types::ProviderSource {
7207            family: AdapterFamily::Acp,
7208            binding: gate4agent_types::AdapterBinding::new(
7209                gate4agent_types::AdapterId::new("fixture").unwrap(),
7210                "1",
7211                gate4agent_types::AdapterVerification::SyntheticFixture,
7212            )
7213            .unwrap(),
7214        }
7215    }
7216
7217    async fn spawn_fixture_acp_shell() -> (NativeEffectShell, NativeSessionKey) {
7218        let session = gate4agent::acp::AcpSession::spawn_with_launch(
7219            gate4agent::CliTool::ClaudeCode,
7220            &std::env::current_dir().expect("cwd"),
7221            gate4agent::acp::AcpSessionOptions::default(),
7222            &acp_fixture_launch(),
7223        )
7224        .await
7225        .expect("fixture ACP handshake must succeed");
7226        let events = session.subscribe();
7227        let key = fixture_acp_key();
7228        let mut shell = NativeEffectShell::new(
7229            FixtureAgentRegistry::new(std::iter::empty::<FixtureAgentSpec>())
7230                .expect("empty fixture catalog"),
7231        );
7232        shell.acp_sessions.insert(
7233            key,
7234            OwnedProviderSession {
7235                source: fixture_acp_source(),
7236                session,
7237                events,
7238                pending_events: VecDeque::new(),
7239                pending_provider_events: VecDeque::new(),
7240                next_provider_sequence: 1,
7241                observed_exit_code: None,
7242                runtime_policy: gate4agent_types::ProviderRuntimePolicy::none(),
7243            },
7244        );
7245        (shell, key)
7246    }
7247
7248    #[tokio::test]
7249    async fn stop_native_acp_session_reports_the_real_exit_code_when_not_forced() {
7250        let (mut shell, key) = spawn_fixture_acp_shell().await;
7251
7252        match shell.stop_native(key, false).await {
7253            ControlObservation::StopCompleted {
7254                forced, exit_code, ..
7255            } => {
7256                assert!(!forced, "a process that exits on its own must not be forced");
7257                assert_eq!(exit_code, Some(0));
7258            }
7259            other => panic!("expected StopCompleted, got {other:?}"),
7260        }
7261    }
7262
7263    // -------------------------------------------------------------------
7264    // spawn_native -- ACP branch: `ProviderEvent::SessionIdentityObserved`.
7265    //
7266    // Regression coverage for the defect this carries fixed: nothing on the
7267    // ACP path ever emitted `SessionIdentityObserved`, so a managed session
7268    // record for an ACP-spawned agent could never leave
7269    // `ManagedSessionState::IdentityPending` (`gate4agent-node`'s
7270    // `reconcile_managed_record` binds the identity ONLY on that event).
7271    // Built through the full `execute()`/`EffectEnvelope` path (unlike
7272    // `spawn_fixture_acp_shell` above, which inserts an already-spawned
7273    // session directly into `acp_sessions`) so these tests exercise the
7274    // ACTUAL `TransportKind::Acp` arm of `spawn_native`, not a stand-in for
7275    // it -- the same synthetic stdio handshake fixture, extended with a
7276    // second script that omits `sessionId` to name the ACP-MUST violation
7277    // this whole feature exists to survive.
7278    // -------------------------------------------------------------------
7279
7280    #[cfg(windows)]
7281    fn acp_fixture_launch_no_session_id() -> gate4agent_types::LaunchSpec {
7282        gate4agent_types::LaunchSpec {
7283            program: "powershell.exe".to_owned(),
7284            fixed_args: vec![
7285                "-NoLogo".to_owned(),
7286                "-NoProfile".to_owned(),
7287                "-NonInteractive".to_owned(),
7288                "-ExecutionPolicy".to_owned(),
7289                "Bypass".to_owned(),
7290                "-Command".to_owned(),
7291                ACP_HANDSHAKE_SCRIPT_NO_SESSION_ID.to_owned(),
7292            ],
7293        }
7294    }
7295
7296    #[cfg(not(windows))]
7297    fn acp_fixture_launch_no_session_id() -> gate4agent_types::LaunchSpec {
7298        gate4agent_types::LaunchSpec {
7299            program: "python3".to_owned(),
7300            fixed_args: vec![
7301                "-u".to_owned(),
7302                "-c".to_owned(),
7303                ACP_HANDSHAKE_SCRIPT_NO_SESSION_ID.to_owned(),
7304            ],
7305        }
7306    }
7307
7308    #[cfg(windows)]
7309    const ACP_HANDSHAKE_SCRIPT_NO_SESSION_ID: &str = r#"[Console]::OutputEncoding=[Text.Encoding]::UTF8
7310function Write-JsonLine($value) { [Console]::WriteLine(($value | ConvertTo-Json -Compress -Depth 12)) }
7311$initialize = [Console]::ReadLine() | ConvertFrom-Json
7312Write-JsonLine @{jsonrpc='2.0';id=$initialize.id;result=@{}}
7313$newSession = [Console]::ReadLine() | ConvertFrom-Json
7314Write-JsonLine @{jsonrpc='2.0';id=$newSession.id;result=@{}}
7315while ($true) {
7316    $line = [Console]::ReadLine()
7317    if ($null -eq $line) { exit 0 }
7318}"#;
7319    #[cfg(not(windows))]
7320    const ACP_HANDSHAKE_SCRIPT_NO_SESSION_ID: &str = r#"import json,sys
7321def read_message():
7322 line=sys.stdin.readline()
7323 if not line: return None
7324 return json.loads(line)
7325def write_message(message):
7326 print(json.dumps(message),flush=True)
7327
7328initialize=read_message()
7329write_message({'jsonrpc':'2.0','id':initialize.get('id'),'result':{}})
7330new_session=read_message()
7331write_message({'jsonrpc':'2.0','id':new_session.get('id'),'result':{}})
7332while True:
7333 msg=read_message()
7334 if msg is None:
7335  sys.exit(0)"#;
7336
7337    fn fixture_acp_spawn_agent_id() -> AgentId {
7338        AgentId::new("claude").expect("builtin catalog names 'claude'")
7339    }
7340
7341    /// Clones the REAL built-in `claude` spec (so `capabilities.transports.acp`
7342    /// carries the same `AdapterBinding` the default `legacy_adapters`
7343    /// registry (`NativeEffectShell::new`) already resolves) and overrides
7344    /// only `launch_override`, so `spawn_native` execs the synthetic stdio
7345    /// fixture above instead of a real `claude` binary.
7346    fn fixture_acp_spawn_agent_spec(launch: gate4agent_types::LaunchSpec) -> FixtureAgentSpec {
7347        let mut spec = gate4agent_catalog::builtin_registry()
7348            .get(&fixture_acp_spawn_agent_id())
7349            .cloned()
7350            .expect("builtin catalog must declare claude");
7351        spec.capabilities
7352            .transports
7353            .acp
7354            .as_mut()
7355            .expect("claude must declare ACP capability")
7356            .launch_override = Some(launch);
7357        spec
7358    }
7359
7360    fn fixture_acp_spawn_key() -> NativeSessionKey {
7361        NativeSessionKey {
7362            instance_id: gate4agent_types::AgentInstanceId(9_101),
7363            generation: gate4agent_types::SessionGeneration(1),
7364        }
7365    }
7366
7367    /// Spawns through the full `execute()`/`EffectEnvelope` path with
7368    /// `ApprovalLevel::Unmanaged` -- the one level `required_acp_mode`
7369    /// resolves to `Ok(None)` for every agent, so the spawn never calls
7370    /// `session/set_mode` against a fixture that only answers `initialize`/
7371    /// `session/new`.
7372    async fn spawn_native_acp_fixture(
7373        launch: gate4agent_types::LaunchSpec,
7374        provider_session_identity: bool,
7375    ) -> (NativeEffectShell, NativeSessionKey, ControlObservation) {
7376        let mut policy = ProviderRuntimePolicy::none();
7377        policy.provider_session_identity = provider_session_identity;
7378        let key = fixture_acp_spawn_key();
7379        let mut shell = NativeEffectShell::new(
7380            FixtureAgentRegistry::new([fixture_acp_spawn_agent_spec(launch)])
7381                .expect("single-agent fixture catalog"),
7382        );
7383        let envelope = gate4agent_types::EffectEnvelope {
7384            operation_id: gate4agent_types::OperationId(1),
7385            instance_id: key.instance_id,
7386            generation: key.generation,
7387            effect: gate4agent_types::ControlEffect::Spawn {
7388                agent_id: fixture_acp_spawn_agent_id(),
7389                transport: TransportKind::Acp,
7390                runtime_policy: policy,
7391                request: gate4agent_types::StartRequest {
7392                    working_directory: std::env::current_dir()
7393                        .expect("cwd")
7394                        .to_string_lossy()
7395                        .into_owned(),
7396                    terminal_size: gate4agent_types::TerminalSize {
7397                        rows: 24,
7398                        columns: 80,
7399                    },
7400                    initial_prompt: None,
7401                    session_options: None,
7402                    approval_level: ApprovalLevel::Unmanaged,
7403                },
7404            },
7405        };
7406        let observation = shell.execute(envelope).await.observation;
7407        (shell, key, observation)
7408    }
7409
7410    #[tokio::test]
7411    async fn acp_spawn_with_a_real_sessionid_emits_session_identity_observed_after_session_start() {
7412        let (mut shell, key, spawned) =
7413            spawn_native_acp_fixture(acp_fixture_launch(), true).await;
7414        match spawned {
7415            ControlObservation::Spawned { .. } => {}
7416            other => panic!("expected Spawned, got {other:?}"),
7417        }
7418
7419        let mut provider_events = shell
7420            .collect_provider_events()
7421            .into_iter()
7422            .filter_map(|envelope| match envelope.observation {
7423                ControlObservation::ProviderEvent { event, .. } => Some(event),
7424                _ => None,
7425            });
7426
7427        match provider_events.next() {
7428            Some(ProviderEvent::SessionStarted { .. }) => {}
7429            other => panic!("expected SessionStarted first, got {other:?}"),
7430        }
7431        match provider_events.next() {
7432            Some(ProviderEvent::SessionIdentityObserved { identity }) => {
7433                assert_eq!(identity.key, gate4agent_types::ProviderSessionKey::SessionId);
7434                assert_eq!(identity.id, "fixture-acp-session");
7435                assert!(identity.transcript_path.is_none());
7436            }
7437            other => panic!("expected SessionIdentityObserved second, got {other:?}"),
7438        }
7439        assert!(
7440            provider_events.next().is_none(),
7441            "expected exactly one SessionIdentityObserved and nothing after it"
7442        );
7443
7444        let _ = shell.stop_native(key, true).await;
7445    }
7446
7447    #[tokio::test]
7448    async fn acp_spawn_with_no_sessionid_emits_no_session_identity_observed() {
7449        let (mut shell, key, spawned) =
7450            spawn_native_acp_fixture(acp_fixture_launch_no_session_id(), true).await;
7451        match spawned {
7452            ControlObservation::Spawned { .. } => {}
7453            other => panic!("expected Spawned, got {other:?}"),
7454        }
7455
7456        let provider_events: Vec<_> = shell
7457            .collect_provider_events()
7458            .into_iter()
7459            .filter_map(|envelope| match envelope.observation {
7460                ControlObservation::ProviderEvent { event, .. } => Some(event),
7461                _ => None,
7462            })
7463            .collect();
7464
7465        assert!(
7466            provider_events
7467                .iter()
7468                .any(|event| matches!(event, ProviderEvent::SessionStarted { .. })),
7469            "expected SessionStarted even when the agent reported no sessionId, got {provider_events:?}"
7470        );
7471        assert!(
7472            !provider_events
7473                .iter()
7474                .any(|event| matches!(event, ProviderEvent::SessionIdentityObserved { .. })),
7475            "an agent that violates ACP's sessionId MUST must not be granted an identity: \
7476             got {provider_events:?}"
7477        );
7478
7479        let _ = shell.stop_native(key, true).await;
7480    }
7481}
7482
7483#[cfg(test)]
7484mod resume_tests;