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