Skip to main content

merry_runtime/process/
contracts.rs

1use super::validation::{
2    ProcessActionError, summarize_intent, validate_argv, validate_captured_bytes, validate_cwd,
3    validate_output_limit, validate_stdin_text, validate_timeout_secs,
4};
5use super::{BackgroundProcessControl, BackgroundProcessId};
6use crate::{PermissionRequest, RequestedCapability};
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8use std::{fmt, future::Future, pin::Pin, sync::Arc};
9use thiserror::Error;
10use tokio_util::sync::CancellationToken;
11
12/// Maximum accepted byte length for one argv item in a process intent.
13///
14/// Sized for inline shell/Python scripts (`64 KiB`), staying safely below
15/// Linux's `128 KiB` `MAX_ARG_STRLEN` while matching [`MAX_PROCESS_STDIN_TEXT_BYTES`].
16pub const MAX_PROCESS_ARG_BYTES: usize = 64 * 1024;
17/// Maximum accepted number of argv items in a process intent.
18pub const MAX_PROCESS_ARGV_ITEMS: usize = 256;
19/// Maximum accepted byte length for a workspace-relative process cwd.
20pub const MAX_PROCESS_CWD_BYTES: usize = 4096;
21/// Maximum accepted byte length for inline stdin text.
22pub const MAX_PROCESS_STDIN_TEXT_BYTES: usize = 64 * 1024;
23/// Maximum accepted captured byte limit per process output stream.
24pub const MAX_PROCESS_OUTPUT_LIMIT_BYTES: usize = 1024 * 1024;
25/// Default foreground wait timeout in seconds before handing off to background.
26pub const DEFAULT_PROCESS_WAIT_TIMEOUT_SECS: u64 = 120;
27/// Maximum accepted foreground wait timeout in seconds for one `run_process` call.
28pub const MAX_PROCESS_WAIT_TIMEOUT_SECS: u64 = 3600;
29
30/// Minimal process environment override policy for SP1.
31///
32/// This describes environment changes requested by the tool call. It does not
33/// decide whether the selected process runner inherits its own current
34/// environment; that is part of the runner/sandbox boundary chosen by the
35/// runtime builder.
36#[non_exhaustive]
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
38#[serde(rename_all = "snake_case")]
39pub enum ProcessEnvPolicy {
40    /// No tool-requested environment overrides.
41    #[default]
42    Empty,
43    /// Test-only stand-in for a future non-empty environment policy.
44    #[cfg(test)]
45    NonEmptyForTest,
46}
47
48impl ProcessEnvPolicy {
49    /// Creates the no environment override policy.
50    #[must_use]
51    pub const fn empty() -> Self {
52        Self::Empty
53    }
54}
55
56/// Explicit admission for the process runner used by the local workspace lane.
57///
58/// This value is intentionally small and declarative. It records that the
59/// caller has selected Merry's local-workspace process profile and accepted
60/// the process risk for that profile; it is not proof that any process is
61/// actually confined. A host adapter may materialize this profile with a
62/// platform-native mechanism, or report that isolation is unavailable. Runtime
63/// code treats it as construction-time admission for the configured process
64/// runner boundary;
65/// argv classification remains a risk signal rather than an executable
66/// allowlist.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub struct AcceptedLocalWorkspaceProcessAdmission {
69    sandbox_profile: LocalWorkspaceProcessSandboxProfile,
70    permission_profile_id: ProcessPermissionProfileId,
71}
72
73impl AcceptedLocalWorkspaceProcessAdmission {
74    /// Creates admission for the local workspace process profile.
75    ///
76    /// Calling this explicitly accepts validated process intents for the
77    /// declared profile. The selected runner still enforces filesystem,
78    /// network, and host-integration capabilities.
79    #[must_use]
80    pub const fn accept_local_workspace() -> Self {
81        Self {
82            sandbox_profile: LocalWorkspaceProcessSandboxProfile::LocalWorkspace,
83            permission_profile_id: ProcessPermissionProfileId::LOCAL_WORKSPACE,
84        }
85    }
86
87    /// Creates admission for the explicit unrestricted host process profile.
88    ///
89    /// The runtime still records and audits the process action, but the host
90    /// process backend does not add an operating-system sandbox in this mode.
91    /// Review policy remains a separate runtime setting; host admission does
92    /// not imply fully trusted execution.
93    #[must_use]
94    pub const fn accept_host() -> Self {
95        Self {
96            sandbox_profile: LocalWorkspaceProcessSandboxProfile::Host,
97            permission_profile_id: ProcessPermissionProfileId::LOCAL_WORKSPACE_HOST,
98        }
99    }
100
101    #[cfg(test)]
102    pub(crate) const fn for_test_permission_profile_id(
103        permission_profile_id: ProcessPermissionProfileId,
104    ) -> Self {
105        Self {
106            sandbox_profile: LocalWorkspaceProcessSandboxProfile::LocalWorkspace,
107            permission_profile_id,
108        }
109    }
110
111    /// Returns the declared sandbox profile for this admission.
112    #[must_use]
113    pub const fn sandbox_profile(self) -> LocalWorkspaceProcessSandboxProfile {
114        self.sandbox_profile
115    }
116
117    /// Returns the permission profile admitted by this construction-time grant.
118    #[must_use]
119    pub const fn permission_profile_id(self) -> ProcessPermissionProfileId {
120        self.permission_profile_id
121    }
122}
123
124/// Declared sandbox/profile associated with local workspace process admission.
125#[non_exhaustive]
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum LocalWorkspaceProcessSandboxProfile {
128    /// Local workspace process profile.
129    LocalWorkspace,
130    /// Explicit unrestricted host process profile.
131    Host,
132}
133
134impl LocalWorkspaceProcessSandboxProfile {
135    /// Returns the stable profile label used in process composition identity.
136    #[must_use]
137    pub const fn as_str(self) -> &'static str {
138        match self {
139            Self::LocalWorkspace => "local-workspace",
140            Self::Host => "host",
141        }
142    }
143}
144
145/// Stable identifier for a runtime-owned process permission profile.
146///
147/// Permission profiles describe filesystem, network, and side-effect
148/// capability. They are separate from concrete command classification and from
149/// model-visible tool profiles.
150#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
151pub struct ProcessPermissionProfileId(&'static str);
152
153impl ProcessPermissionProfileId {
154    /// Read-only process lane for bounded inspection commands.
155    pub const READ_ONLY: Self = Self("process.read_only");
156    /// Local workspace process lane.
157    pub const LOCAL_WORKSPACE: Self = Self("process.local_workspace");
158    /// Local workspace process lane accepted for the unrestricted host profile.
159    pub const LOCAL_WORKSPACE_HOST: Self = Self("process.local_workspace.host");
160    /// Read-only shell wrapper lane for plain command sequences under a real shell runner.
161    pub const SHELL_READ_ONLY: Self = Self("process.shell.read_only");
162    /// Process lane admitted by an explicit permission request review.
163    pub const APPROVED_PERMISSION_REQUEST: Self = Self("process.permission_request.approved");
164
165    /// Returns the stable profile identifier string.
166    #[must_use]
167    pub const fn as_str(self) -> &'static str {
168        self.0
169    }
170}
171
172impl Serialize for ProcessPermissionProfileId {
173    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
174    where
175        S: Serializer,
176    {
177        serializer.serialize_str((*self).as_str())
178    }
179}
180
181impl<'de> Deserialize<'de> for ProcessPermissionProfileId {
182    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
183    where
184        D: Deserializer<'de>,
185    {
186        let value = String::deserialize(deserializer)?;
187        match value.as_str() {
188            "process.read_only" => Ok(Self::READ_ONLY),
189            "process.local_workspace" => Ok(Self::LOCAL_WORKSPACE),
190            "process.local_workspace.host" => Ok(Self::LOCAL_WORKSPACE_HOST),
191            "process.shell.read_only" => Ok(Self::SHELL_READ_ONLY),
192            "process.permission_request.approved" => Ok(Self::APPROVED_PERMISSION_REQUEST),
193            _ => Err(serde::de::Error::custom(format!(
194                "unsupported process permission profile id `{value}`"
195            ))),
196        }
197    }
198}
199
200impl fmt::Display for ProcessPermissionProfileId {
201    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
202        formatter.write_str(self.as_str())
203    }
204}
205
206/// Boxed process runner future used for object-safe runtime process boundaries.
207///
208/// The runner boundary is runtime-owned and provider-neutral. It accepts only a
209/// validated [`ProcessActionIntent`] and a cancellation-aware context.
210pub type ProcessRunnerFuture<'a> = Pin<Box<dyn Future<Output = ProcessRunnerResult> + Send + 'a>>;
211
212/// Result returned by a runtime-owned process runner.
213pub type ProcessRunnerResult = Result<ProcessRunnerOutput, ProcessRunnerError>;
214
215/// Live incremental output chunk emitted while a process action is running.
216#[derive(Debug, Clone, PartialEq, Eq)]
217pub struct ProcessOutputChunk {
218    /// Tool call that owns the running process.
219    pub call_id: merry_core::ToolCallId,
220    /// Which output pipe produced the chunk.
221    pub stream: merry_core::ToolOutputStream,
222    /// Lossy UTF-8 text chunk.
223    pub delta: String,
224}
225
226/// Non-blocking sink for forwarding bounded live process output chunks to UI observers.
227#[derive(Debug, Clone)]
228pub struct ProcessOutputSink {
229    call_id: merry_core::ToolCallId,
230    sender: tokio::sync::mpsc::Sender<ProcessOutputChunk>,
231}
232
233impl ProcessOutputSink {
234    /// Creates a live output sink bound to one active tool call.
235    #[must_use]
236    pub fn new(
237        call_id: merry_core::ToolCallId,
238        sender: tokio::sync::mpsc::Sender<ProcessOutputChunk>,
239    ) -> Self {
240        Self { call_id, sender }
241    }
242
243    /// Emits a bounded chunk without ever blocking the process reader task.
244    pub fn emit(&self, stream: merry_core::ToolOutputStream, bytes: &[u8]) {
245        if bytes.is_empty() {
246            return;
247        }
248        const MAX_LIVE_CHUNK_BYTES: usize = 4096;
249        let slice = &bytes[..bytes.len().min(MAX_LIVE_CHUNK_BYTES)];
250        let delta = String::from_utf8_lossy(slice).into_owned();
251        let _ = self.sender.try_send(ProcessOutputChunk {
252            call_id: self.call_id.clone(),
253            stream,
254            delta,
255        });
256    }
257}
258
259/// Context passed to a process runner.
260#[derive(Debug, Clone, Default)]
261pub struct ProcessRunnerContext {
262    cancellation_token: CancellationToken,
263    output_sink: Option<ProcessOutputSink>,
264}
265
266impl ProcessRunnerContext {
267    /// Creates a process runner context with the provided cancellation token.
268    #[must_use]
269    pub fn new(cancellation_token: CancellationToken) -> Self {
270        Self {
271            cancellation_token,
272            output_sink: None,
273        }
274    }
275
276    /// Attaches a non-blocking live output sink for streaming stdout/stderr progress.
277    #[must_use]
278    pub fn with_output_sink(mut self, sink: ProcessOutputSink) -> Self {
279        self.output_sink = Some(sink);
280        self
281    }
282
283    /// Returns the cancellation token for this process action.
284    #[must_use]
285    pub fn cancellation_token(&self) -> &CancellationToken {
286        &self.cancellation_token
287    }
288
289    /// Returns the optional live output sink for streaming stdout/stderr progress.
290    #[must_use]
291    pub fn output_sink(&self) -> Option<&ProcessOutputSink> {
292        self.output_sink.as_ref()
293    }
294}
295
296/// Object-safe runtime process runner boundary.
297///
298/// Implementations for SP2 are fakes or adapters supplied by tests and higher
299/// layers. This trait must not imply shell execution, raw shell parsing, or
300/// provider-specific behavior.
301pub trait ProcessRunner: Send + Sync {
302    /// Runs a validated process intent and returns provider-neutral output.
303    fn run<'a>(
304        &'a self,
305        intent: ProcessActionIntent,
306        context: ProcessRunnerContext,
307    ) -> ProcessRunnerFuture<'a>;
308
309    /// Returns the session board that retains this runner's background processes.
310    ///
311    /// Runners that do not keep processes after `run` returns leave this empty.
312    fn background_control(&self) -> Option<Arc<dyn BackgroundProcessControl>> {
313        None
314    }
315}
316
317/// Factory for runners created from approved permission requests.
318///
319/// Implementations translate a runtime-approved request into the concrete
320/// process backend/profile for that exact action. Adapters consume read-only
321/// session snapshots; runtime owns retention and capability lifetimes through
322/// `SessionPermissionedProcessRunnerFactory`. An adapter never records grants
323/// or grants authority beyond the runtime-approved request.
324pub trait PermissionedProcessRunnerFactory: Send + Sync {
325    /// Validates the request against the backend's hard capability policy.
326    ///
327    /// Backends that do not have additional policy constraints may keep the
328    /// default only when they can enforce every capability in the request
329    /// through their existing runner. A backend that cannot materialize a
330    /// requested path or network grant must reject it. A validation failure
331    /// must happen before any reviewer or process side effect is started.
332    fn validate_request(&self, _request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
333        Ok(())
334    }
335
336    /// Returns whether the backend already enforces every capability in the
337    /// request for the current process session.
338    ///
339    /// This query covers capability state only; it does not authorize the
340    /// requested action. Implementations must return `false` for capabilities
341    /// that are action-scoped, such as network access, or when the backend
342    /// cannot prove that the requested access is covered.
343    fn request_capabilities_are_satisfied(
344        &self,
345        _request: &PermissionRequest,
346    ) -> Result<bool, ProcessRunnerError> {
347        Ok(false)
348    }
349
350    /// Returns whether any requested path targets built-in Merry protected
351    /// metadata (`providers/`, `MERRY_API_KEY_FILE`, or a `ProductReadOnly`
352    /// write target), so runtime keeps approval single-action (`Once`) and
353    /// defaults interactive review UIs to `Deny`.
354    fn targets_protected_metadata(&self, _request: &PermissionRequest) -> bool {
355        false
356    }
357
358    /// Prepares one validated action and its normalized path evidence without
359    /// changing permission state. Adapters can share a single filesystem view
360    /// across validation and materialization. The default retains no paths.
361    fn prepare_approved_request(
362        &self,
363        request: &PermissionRequest,
364    ) -> Result<super::PreparedProcessPermission, ProcessRunnerError> {
365        self.validate_request(request)?;
366        Ok(super::PreparedProcessPermission::new(
367            self.runner_for(request),
368            Vec::new(),
369        ))
370    }
371
372    /// Creates the process runner for one approved permission request, without
373    /// mutating session state. Runtime handles retention after successful preparation.
374    fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner>;
375
376    /// Creates the process runner for one approved permission request under an
377    /// explicit [`merry_core::ApprovalScope`].
378    ///
379    /// [`merry_core::ApprovalScope::Once`] must not retain any session grant.
380    /// [`merry_core::ApprovalScope::Session`] retains eligible capabilities
381    /// when backed by a session-scoped permission store.
382    fn runner_for_decision(
383        &self,
384        request: &PermissionRequest,
385        _scope: merry_core::ApprovalScope,
386    ) -> Arc<dyn ProcessRunner> {
387        self.runner_for(request)
388    }
389}
390
391/// Compatibility factory that always returns the same runner.
392#[derive(Clone)]
393pub struct StaticPermissionedProcessRunnerFactory {
394    runner: Arc<dyn ProcessRunner>,
395}
396
397impl StaticPermissionedProcessRunnerFactory {
398    /// Creates a static runner factory.
399    #[must_use]
400    pub fn new(runner: Arc<dyn ProcessRunner>) -> Self {
401        Self { runner }
402    }
403}
404
405impl PermissionedProcessRunnerFactory for StaticPermissionedProcessRunnerFactory {
406    fn validate_request(&self, request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
407        if request
408            .requested()
409            .iter()
410            .any(|capability| matches!(capability, RequestedCapability::Path(_)))
411        {
412            return Err(ProcessRunnerError::infrastructure(
413                "static permissioned process runner cannot enforce requested path capabilities",
414            ));
415        }
416        if request
417            .requested()
418            .iter()
419            .any(|capability| matches!(capability, RequestedCapability::HostIntegration(_)))
420        {
421            return Err(ProcessRunnerError::infrastructure(
422                "static permissioned process runner cannot enforce requested host integrations",
423            ));
424        }
425        Ok(())
426    }
427
428    fn runner_for(&self, _request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
429        Arc::clone(&self.runner)
430    }
431}
432
433/// Provider-neutral, typed intent for a local process action.
434///
435/// The argv vector is intentionally open and does not enumerate allowed
436/// commands. This value is proposal evidence only in SP1; it is not an
437/// executor and must not be treated as authorization to spawn a process.
438#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
439#[serde(deny_unknown_fields)]
440pub struct ProcessActionIntent {
441    summary: String,
442    argv: Vec<String>,
443    cwd: Option<String>,
444    env_policy: ProcessEnvPolicy,
445    stdin_text: Option<String>,
446    stdout_limit_bytes: usize,
447    stderr_limit_bytes: usize,
448    #[serde(default)]
449    background: bool,
450    #[serde(default, skip_serializing_if = "Option::is_none")]
451    timeout_secs: Option<u64>,
452    #[serde(default, skip_serializing_if = "Option::is_none")]
453    display_name: Option<String>,
454}
455
456impl ProcessActionIntent {
457    /// Creates a validated process action intent.
458    pub fn new(
459        argv: Vec<String>,
460        cwd: Option<String>,
461        env_policy: ProcessEnvPolicy,
462        stdin_text: Option<String>,
463        stdout_limit_bytes: usize,
464        stderr_limit_bytes: usize,
465    ) -> Result<Self, ProcessActionError> {
466        validate_argv(&argv)?;
467        let cwd = validate_cwd(cwd)?;
468        validate_stdin_text(stdin_text.as_deref())?;
469        validate_output_limit("stdout_limit_bytes", stdout_limit_bytes)?;
470        validate_output_limit("stderr_limit_bytes", stderr_limit_bytes)?;
471        let summary = summarize_intent(&argv, cwd.as_deref());
472
473        Ok(Self {
474            summary,
475            argv,
476            cwd,
477            env_policy,
478            stdin_text,
479            stdout_limit_bytes,
480            stderr_limit_bytes,
481            background: false,
482            timeout_secs: None,
483            display_name: None,
484        })
485    }
486
487    /// Keeps the process after the tool returns when `background` is true.
488    ///
489    /// The default waits until the process exits or reaches its wait timeout.
490    /// A retained background process stays until stopped or the owning session ends.
491    #[must_use]
492    pub fn with_background(mut self, background: bool) -> Self {
493        self.background = background;
494        self
495    }
496
497    /// Sets an optional foreground wait timeout in seconds (`1..=MAX_PROCESS_WAIT_TIMEOUT_SECS`).
498    ///
499    /// When a foreground command is still running after this timeout, the runner
500    /// does not kill it; it retains the process in the background and returns
501    /// its id and partial output so the calling LLM can decide how to proceed.
502    pub fn with_timeout_secs(
503        mut self,
504        timeout_secs: Option<u64>,
505    ) -> Result<Self, ProcessActionError> {
506        self.timeout_secs = validate_timeout_secs(timeout_secs)?;
507        Ok(self)
508    }
509
510    /// Attaches an optional short human-readable label for a retained process.
511    #[must_use]
512    pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
513        self.display_name = display_name.and_then(|value| {
514            let normalized = value.split_whitespace().collect::<Vec<_>>().join(" ");
515            if normalized.is_empty() {
516                None
517            } else {
518                Some(normalized.chars().take(80).collect())
519            }
520        });
521        self
522    }
523
524    /// Returns a compact deterministic summary of the process intent.
525    #[must_use]
526    pub fn summary(&self) -> &str {
527        &self.summary
528    }
529
530    /// Returns the exact argv vector.
531    #[must_use]
532    pub fn argv(&self) -> &[String] {
533        &self.argv
534    }
535
536    /// Returns the workspace-relative cwd, or `None` for the workspace root.
537    #[must_use]
538    pub fn cwd(&self) -> Option<&str> {
539        self.cwd.as_deref()
540    }
541
542    /// Returns the typed environment policy.
543    #[must_use]
544    pub const fn env_policy(&self) -> ProcessEnvPolicy {
545        self.env_policy
546    }
547
548    /// Returns optional inline stdin text.
549    #[must_use]
550    pub fn stdin_text(&self) -> Option<&str> {
551        self.stdin_text.as_deref()
552    }
553
554    /// Returns whether the runner should retain the process after the tool returns.
555    #[must_use]
556    pub const fn background(&self) -> bool {
557        self.background
558    }
559
560    /// Returns the explicit foreground wait timeout override in seconds, if set.
561    #[must_use]
562    pub const fn timeout_secs(&self) -> Option<u64> {
563        self.timeout_secs
564    }
565
566    /// Returns the effective foreground wait timeout in seconds.
567    #[must_use]
568    pub const fn effective_wait_timeout_secs(&self) -> u64 {
569        match self.timeout_secs {
570            Some(secs) => secs,
571            None => DEFAULT_PROCESS_WAIT_TIMEOUT_SECS,
572        }
573    }
574
575    /// Returns the optional human-readable display name for this process.
576    #[must_use]
577    pub fn display_name(&self) -> Option<&str> {
578        self.display_name.as_deref()
579    }
580
581    /// Returns the stdout capture limit in bytes.
582    #[must_use]
583    pub const fn stdout_limit_bytes(&self) -> usize {
584        self.stdout_limit_bytes
585    }
586
587    /// Returns the stderr capture limit in bytes.
588    #[must_use]
589    pub const fn stderr_limit_bytes(&self) -> usize {
590        self.stderr_limit_bytes
591    }
592}
593
594/// Bounded output returned by a process runner.
595///
596/// Process output is an opaque byte stream. The runner keeps the exact bounded
597/// bytes and a loss-tolerant UTF-8 view separately so binary tools cannot turn a
598/// successful process into an infrastructure error merely by writing invalid
599/// UTF-8. Internal execution audit evidence stores byte counts and truncation
600/// flags, not these payloads.
601#[derive(Debug, Clone, PartialEq, Eq)]
602pub struct ProcessRunnerOutput {
603    status: ProcessExitStatus,
604    stdout_data: Vec<u8>,
605    stdout_text: String,
606    stdout_bytes: usize,
607    stdout_truncated: bool,
608    stderr_data: Vec<u8>,
609    stderr_text: String,
610    stderr_bytes: usize,
611    stderr_truncated: bool,
612    running_pid: Option<u32>,
613    background_process_id: Option<BackgroundProcessId>,
614    wait_timed_out_secs: Option<u64>,
615}
616
617impl ProcessRunnerOutput {
618    /// Creates validated process runner output for a previously validated intent.
619    pub fn new(
620        intent: &ProcessActionIntent,
621        status: ProcessExitStatus,
622        stdout_text: impl Into<String>,
623        stdout_truncated: bool,
624        stderr_text: impl Into<String>,
625        stderr_truncated: bool,
626    ) -> Result<Self, ProcessActionError> {
627        Self::from_bytes(
628            intent,
629            status,
630            stdout_text.into().into_bytes(),
631            stdout_truncated,
632            stderr_text.into().into_bytes(),
633            stderr_truncated,
634        )
635    }
636
637    /// Creates output from exact bounded process bytes.
638    pub fn from_bytes(
639        intent: &ProcessActionIntent,
640        status: ProcessExitStatus,
641        stdout_data: Vec<u8>,
642        stdout_truncated: bool,
643        stderr_data: Vec<u8>,
644        stderr_truncated: bool,
645    ) -> Result<Self, ProcessActionError> {
646        validate_captured_bytes(
647            "stdout_bytes",
648            stdout_data.len(),
649            intent.stdout_limit_bytes(),
650        )?;
651        validate_captured_bytes(
652            "stderr_bytes",
653            stderr_data.len(),
654            intent.stderr_limit_bytes(),
655        )?;
656
657        Ok(Self {
658            status,
659            stdout_text: String::from_utf8_lossy(&stdout_data).into_owned(),
660            stdout_bytes: stdout_data.len(),
661            stdout_data,
662            stdout_truncated,
663            stderr_text: String::from_utf8_lossy(&stderr_data).into_owned(),
664            stderr_bytes: stderr_data.len(),
665            stderr_data,
666            stderr_truncated,
667            running_pid: None,
668            background_process_id: None,
669            wait_timed_out_secs: None,
670        })
671    }
672
673    /// Records the pid of a process that is still running.
674    #[must_use]
675    pub fn with_running_pid(mut self, pid: u32) -> Self {
676        self.running_pid = Some(pid);
677        self
678    }
679
680    /// Records the id of a process retained after this call returns.
681    #[must_use]
682    pub fn with_background_process_id(mut self, id: BackgroundProcessId) -> Self {
683        self.background_process_id = Some(id);
684        self
685    }
686
687    /// Records that a foreground wait elapsed after `secs` seconds without killing
688    /// the still-running process, handing it off to the background supervisor.
689    #[must_use]
690    pub fn with_wait_timed_out_secs(mut self, secs: u64) -> Self {
691        self.wait_timed_out_secs = Some(secs);
692        self
693    }
694
695    /// Returns the provider-neutral completion status.
696    #[must_use]
697    pub const fn status(&self) -> ProcessExitStatus {
698        self.status
699    }
700
701    /// Returns bounded stdout payload for the result artifact.
702    #[must_use]
703    pub fn stdout_text(&self) -> &str {
704        &self.stdout_text
705    }
706
707    /// Returns the exact bounded stdout bytes.
708    #[must_use]
709    pub fn stdout_data(&self) -> &[u8] {
710        &self.stdout_data
711    }
712
713    /// Returns whether stdout was valid UTF-8 without replacement.
714    #[must_use]
715    pub fn stdout_is_utf8(&self) -> bool {
716        std::str::from_utf8(&self.stdout_data).is_ok()
717    }
718
719    /// Returns captured stdout byte count.
720    #[must_use]
721    pub const fn stdout_bytes(&self) -> usize {
722        self.stdout_bytes
723    }
724
725    /// Returns whether stdout capture was truncated.
726    #[must_use]
727    pub const fn stdout_truncated(&self) -> bool {
728        self.stdout_truncated
729    }
730
731    /// Returns bounded stderr payload for the result artifact.
732    #[must_use]
733    pub fn stderr_text(&self) -> &str {
734        &self.stderr_text
735    }
736
737    /// Returns the exact bounded stderr bytes.
738    #[must_use]
739    pub fn stderr_data(&self) -> &[u8] {
740        &self.stderr_data
741    }
742
743    /// Returns whether stderr was valid UTF-8 without replacement.
744    #[must_use]
745    pub fn stderr_is_utf8(&self) -> bool {
746        std::str::from_utf8(&self.stderr_data).is_ok()
747    }
748
749    /// Returns captured stderr byte count.
750    #[must_use]
751    pub const fn stderr_bytes(&self) -> usize {
752        self.stderr_bytes
753    }
754
755    /// Returns whether stderr capture was truncated.
756    #[must_use]
757    pub const fn stderr_truncated(&self) -> bool {
758        self.stderr_truncated
759    }
760
761    /// Returns the pid when the process is still running.
762    #[must_use]
763    pub const fn running_pid(&self) -> Option<u32> {
764        self.running_pid
765    }
766
767    /// Returns the id of a process retained after this call returns.
768    #[must_use]
769    pub fn background_process_id(&self) -> Option<&BackgroundProcessId> {
770        self.background_process_id.as_ref()
771    }
772
773    /// Returns the foreground wait timeout in seconds when the call handed off a
774    /// still-running command to the background without killing it.
775    #[must_use]
776    pub const fn wait_timed_out_secs(&self) -> Option<u64> {
777        self.wait_timed_out_secs
778    }
779
780    /// Returns whether the process output represents successful completion.
781    ///
782    /// A process that is still running counts as success so the turn can continue.
783    #[must_use]
784    pub const fn ok(&self) -> bool {
785        matches!(
786            self.status,
787            ProcessExitStatus::Exited(0) | ProcessExitStatus::Running
788        )
789    }
790
791    /// Builds payload-free internal execution evidence for the given intent.
792    pub fn execution_evidence(
793        &self,
794        intent: &ProcessActionIntent,
795        permission_profile_id: ProcessPermissionProfileId,
796    ) -> Result<ProcessExecutionEvidence, ProcessActionError> {
797        ProcessExecutionEvidence::new(
798            intent,
799            permission_profile_id,
800            self.status,
801            self.stdout_bytes,
802            self.stdout_truncated,
803            self.stderr_bytes,
804            self.stderr_truncated,
805        )
806    }
807}
808
809/// Provider-neutral process completion status.
810#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
811#[serde(rename_all = "snake_case")]
812pub enum ProcessExitStatus {
813    /// The process exited with an integer code.
814    Exited(i32),
815    /// The process was cancelled before normal completion.
816    Cancelled,
817    /// The process could not be started by the future process executor.
818    FailedToStart,
819    /// The process runner reported a domain failure before normal completion.
820    DomainFailed,
821    /// The process was still running when the tool returned.
822    ///
823    /// The runner keeps it until the owning session ends.
824    Running,
825}
826
827impl ProcessExitStatus {
828    /// Returns the exit code when the process reached normal exit.
829    #[must_use]
830    pub const fn exit_code(self) -> Option<i32> {
831        match self {
832            Self::Exited(code) => Some(code),
833            Self::Cancelled | Self::FailedToStart | Self::DomainFailed | Self::Running => None,
834        }
835    }
836}
837
838/// Infrastructure errors returned by a process runner.
839#[derive(Debug, Clone, PartialEq, Eq, Error)]
840pub enum ProcessRunnerError {
841    /// Process runner was cancelled cooperatively before producing output.
842    #[error("process runner cancelled")]
843    Cancelled,
844
845    /// The runner infrastructure failed before producing durable output.
846    #[error("process runner infrastructure error: {message}")]
847    Infrastructure {
848        /// Actionable infrastructure failure detail.
849        message: String,
850    },
851}
852
853impl ProcessRunnerError {
854    /// Creates an infrastructure process runner error.
855    #[must_use]
856    pub fn infrastructure(message: impl Into<String>) -> Self {
857        Self::Infrastructure {
858            message: message.into(),
859        }
860    }
861}
862
863/// Provider-neutral evidence recorded after a process action executes.
864///
865/// This stores bounded metadata only: the validated intent identity, completion
866/// status, captured byte counts, and truncation flags. It contains no provider
867/// wire data and no stdout/stderr payload.
868#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
869#[serde(deny_unknown_fields)]
870pub struct ProcessExecutionEvidence {
871    intent_summary: String,
872    argv: Vec<String>,
873    cwd: Option<String>,
874    permission_profile_id: ProcessPermissionProfileId,
875    status: ProcessExitStatus,
876    stdout_bytes: usize,
877    stdout_truncated: bool,
878    stderr_bytes: usize,
879    stderr_truncated: bool,
880}
881
882impl ProcessExecutionEvidence {
883    /// Creates validated process execution evidence for a previously proposed intent.
884    pub fn new(
885        intent: &ProcessActionIntent,
886        permission_profile_id: ProcessPermissionProfileId,
887        status: ProcessExitStatus,
888        stdout_bytes: usize,
889        stdout_truncated: bool,
890        stderr_bytes: usize,
891        stderr_truncated: bool,
892    ) -> Result<Self, ProcessActionError> {
893        validate_captured_bytes("stdout_bytes", stdout_bytes, intent.stdout_limit_bytes())?;
894        validate_captured_bytes("stderr_bytes", stderr_bytes, intent.stderr_limit_bytes())?;
895
896        Ok(Self {
897            intent_summary: intent.summary().to_owned(),
898            argv: intent.argv().to_vec(),
899            cwd: intent.cwd().map(str::to_owned),
900            permission_profile_id,
901            status,
902            stdout_bytes,
903            stdout_truncated,
904            stderr_bytes,
905            stderr_truncated,
906        })
907    }
908
909    /// Returns the compact process intent summary.
910    #[must_use]
911    pub fn intent_summary(&self) -> &str {
912        &self.intent_summary
913    }
914
915    /// Returns the exact argv copied from the validated intent.
916    #[must_use]
917    pub fn argv(&self) -> &[String] {
918        &self.argv
919    }
920
921    /// Returns the workspace-relative cwd copied from the validated intent.
922    #[must_use]
923    pub fn cwd(&self) -> Option<&str> {
924        self.cwd.as_deref()
925    }
926
927    /// Returns the permission profile used for this process execution.
928    #[must_use]
929    pub const fn permission_profile_id(&self) -> ProcessPermissionProfileId {
930        self.permission_profile_id
931    }
932
933    /// Returns the provider-neutral completion status.
934    #[must_use]
935    pub const fn status(&self) -> ProcessExitStatus {
936        self.status
937    }
938
939    /// Returns the exit code when the process reached normal exit.
940    #[must_use]
941    pub const fn exit_code(&self) -> Option<i32> {
942        self.status.exit_code()
943    }
944
945    /// Returns captured stdout byte count.
946    #[must_use]
947    pub const fn stdout_bytes(&self) -> usize {
948        self.stdout_bytes
949    }
950
951    /// Returns whether stdout capture was truncated.
952    #[must_use]
953    pub const fn stdout_truncated(&self) -> bool {
954        self.stdout_truncated
955    }
956
957    /// Returns captured stderr byte count.
958    #[must_use]
959    pub const fn stderr_bytes(&self) -> usize {
960        self.stderr_bytes
961    }
962
963    /// Returns whether stderr capture was truncated.
964    #[must_use]
965    pub const fn stderr_truncated(&self) -> bool {
966        self.stderr_truncated
967    }
968
969    pub(crate) fn matches_intent(&self, intent: &ProcessActionIntent) -> bool {
970        self.intent_summary == intent.summary()
971            && self.argv == intent.argv()
972            && self.cwd.as_deref() == intent.cwd()
973            && self.stdout_bytes <= intent.stdout_limit_bytes()
974            && self.stderr_bytes <= intent.stderr_limit_bytes()
975    }
976}