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)]
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    /// Prepares one validated action and its normalized path evidence without
351    /// changing permission state. Adapters can share a single filesystem view
352    /// across validation and materialization. The default retains no paths.
353    fn prepare_approved_request(
354        &self,
355        request: &PermissionRequest,
356    ) -> Result<super::PreparedProcessPermission, ProcessRunnerError> {
357        self.validate_request(request)?;
358        Ok(super::PreparedProcessPermission::new(
359            self.runner_for(request),
360            Vec::new(),
361        ))
362    }
363
364    /// Creates the process runner for one approved permission request, without
365    /// mutating session state. Runtime handles retention after successful preparation.
366    fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner>;
367}
368
369/// Compatibility factory that always returns the same runner.
370#[derive(Clone)]
371pub struct StaticPermissionedProcessRunnerFactory {
372    runner: Arc<dyn ProcessRunner>,
373}
374
375impl StaticPermissionedProcessRunnerFactory {
376    /// Creates a static runner factory.
377    #[must_use]
378    pub fn new(runner: Arc<dyn ProcessRunner>) -> Self {
379        Self { runner }
380    }
381}
382
383impl PermissionedProcessRunnerFactory for StaticPermissionedProcessRunnerFactory {
384    fn validate_request(&self, request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
385        if request
386            .requested()
387            .iter()
388            .any(|capability| matches!(capability, RequestedCapability::Path(_)))
389        {
390            return Err(ProcessRunnerError::infrastructure(
391                "static permissioned process runner cannot enforce requested path capabilities",
392            ));
393        }
394        if request
395            .requested()
396            .iter()
397            .any(|capability| matches!(capability, RequestedCapability::HostIntegration(_)))
398        {
399            return Err(ProcessRunnerError::infrastructure(
400                "static permissioned process runner cannot enforce requested host integrations",
401            ));
402        }
403        Ok(())
404    }
405
406    fn runner_for(&self, _request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
407        Arc::clone(&self.runner)
408    }
409}
410
411/// Provider-neutral, typed intent for a local process action.
412///
413/// The argv vector is intentionally open and does not enumerate allowed
414/// commands. This value is proposal evidence only in SP1; it is not an
415/// executor and must not be treated as authorization to spawn a process.
416#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
417#[serde(deny_unknown_fields)]
418pub struct ProcessActionIntent {
419    summary: String,
420    argv: Vec<String>,
421    cwd: Option<String>,
422    env_policy: ProcessEnvPolicy,
423    stdin_text: Option<String>,
424    stdout_limit_bytes: usize,
425    stderr_limit_bytes: usize,
426    #[serde(default)]
427    background: bool,
428    #[serde(default, skip_serializing_if = "Option::is_none")]
429    timeout_secs: Option<u64>,
430    #[serde(default, skip_serializing_if = "Option::is_none")]
431    display_name: Option<String>,
432}
433
434impl ProcessActionIntent {
435    /// Creates a validated process action intent.
436    pub fn new(
437        argv: Vec<String>,
438        cwd: Option<String>,
439        env_policy: ProcessEnvPolicy,
440        stdin_text: Option<String>,
441        stdout_limit_bytes: usize,
442        stderr_limit_bytes: usize,
443    ) -> Result<Self, ProcessActionError> {
444        validate_argv(&argv)?;
445        let cwd = validate_cwd(cwd)?;
446        validate_stdin_text(stdin_text.as_deref())?;
447        validate_output_limit("stdout_limit_bytes", stdout_limit_bytes)?;
448        validate_output_limit("stderr_limit_bytes", stderr_limit_bytes)?;
449        let summary = summarize_intent(&argv, cwd.as_deref());
450
451        Ok(Self {
452            summary,
453            argv,
454            cwd,
455            env_policy,
456            stdin_text,
457            stdout_limit_bytes,
458            stderr_limit_bytes,
459            background: false,
460            timeout_secs: None,
461            display_name: None,
462        })
463    }
464
465    /// Keeps the process after the tool returns when `background` is true.
466    ///
467    /// The default waits until the process exits or reaches its wait timeout.
468    /// A retained background process stays until stopped or the owning session ends.
469    #[must_use]
470    pub fn with_background(mut self, background: bool) -> Self {
471        self.background = background;
472        self
473    }
474
475    /// Sets an optional foreground wait timeout in seconds (`1..=MAX_PROCESS_WAIT_TIMEOUT_SECS`).
476    ///
477    /// When a foreground command is still running after this timeout, the runner
478    /// does not kill it; it retains the process in the background and returns
479    /// its id and partial output so the calling LLM can decide how to proceed.
480    pub fn with_timeout_secs(
481        mut self,
482        timeout_secs: Option<u64>,
483    ) -> Result<Self, ProcessActionError> {
484        self.timeout_secs = validate_timeout_secs(timeout_secs)?;
485        Ok(self)
486    }
487
488    /// Attaches an optional short human-readable label for a retained process.
489    #[must_use]
490    pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
491        self.display_name = display_name.and_then(|value| {
492            let normalized = value.split_whitespace().collect::<Vec<_>>().join(" ");
493            if normalized.is_empty() {
494                None
495            } else {
496                Some(normalized.chars().take(80).collect())
497            }
498        });
499        self
500    }
501
502    /// Returns a compact deterministic summary of the process intent.
503    #[must_use]
504    pub fn summary(&self) -> &str {
505        &self.summary
506    }
507
508    /// Returns the exact argv vector.
509    #[must_use]
510    pub fn argv(&self) -> &[String] {
511        &self.argv
512    }
513
514    /// Returns the workspace-relative cwd, or `None` for the workspace root.
515    #[must_use]
516    pub fn cwd(&self) -> Option<&str> {
517        self.cwd.as_deref()
518    }
519
520    /// Returns the typed environment policy.
521    #[must_use]
522    pub const fn env_policy(&self) -> ProcessEnvPolicy {
523        self.env_policy
524    }
525
526    /// Returns optional inline stdin text.
527    #[must_use]
528    pub fn stdin_text(&self) -> Option<&str> {
529        self.stdin_text.as_deref()
530    }
531
532    /// Returns whether the runner should retain the process after the tool returns.
533    #[must_use]
534    pub const fn background(&self) -> bool {
535        self.background
536    }
537
538    /// Returns the explicit foreground wait timeout override in seconds, if set.
539    #[must_use]
540    pub const fn timeout_secs(&self) -> Option<u64> {
541        self.timeout_secs
542    }
543
544    /// Returns the effective foreground wait timeout in seconds.
545    #[must_use]
546    pub const fn effective_wait_timeout_secs(&self) -> u64 {
547        match self.timeout_secs {
548            Some(secs) => secs,
549            None => DEFAULT_PROCESS_WAIT_TIMEOUT_SECS,
550        }
551    }
552
553    /// Returns the optional human-readable display name for this process.
554    #[must_use]
555    pub fn display_name(&self) -> Option<&str> {
556        self.display_name.as_deref()
557    }
558
559    /// Returns the stdout capture limit in bytes.
560    #[must_use]
561    pub const fn stdout_limit_bytes(&self) -> usize {
562        self.stdout_limit_bytes
563    }
564
565    /// Returns the stderr capture limit in bytes.
566    #[must_use]
567    pub const fn stderr_limit_bytes(&self) -> usize {
568        self.stderr_limit_bytes
569    }
570}
571
572/// Bounded output returned by a process runner.
573///
574/// Process output is an opaque byte stream. The runner keeps the exact bounded
575/// bytes and a loss-tolerant UTF-8 view separately so binary tools cannot turn a
576/// successful process into an infrastructure error merely by writing invalid
577/// UTF-8. Internal execution audit evidence stores byte counts and truncation
578/// flags, not these payloads.
579#[derive(Debug, Clone, PartialEq, Eq)]
580pub struct ProcessRunnerOutput {
581    status: ProcessExitStatus,
582    stdout_data: Vec<u8>,
583    stdout_text: String,
584    stdout_bytes: usize,
585    stdout_truncated: bool,
586    stderr_data: Vec<u8>,
587    stderr_text: String,
588    stderr_bytes: usize,
589    stderr_truncated: bool,
590    running_pid: Option<u32>,
591    background_process_id: Option<BackgroundProcessId>,
592    wait_timed_out_secs: Option<u64>,
593}
594
595impl ProcessRunnerOutput {
596    /// Creates validated process runner output for a previously validated intent.
597    pub fn new(
598        intent: &ProcessActionIntent,
599        status: ProcessExitStatus,
600        stdout_text: impl Into<String>,
601        stdout_truncated: bool,
602        stderr_text: impl Into<String>,
603        stderr_truncated: bool,
604    ) -> Result<Self, ProcessActionError> {
605        Self::from_bytes(
606            intent,
607            status,
608            stdout_text.into().into_bytes(),
609            stdout_truncated,
610            stderr_text.into().into_bytes(),
611            stderr_truncated,
612        )
613    }
614
615    /// Creates output from exact bounded process bytes.
616    pub fn from_bytes(
617        intent: &ProcessActionIntent,
618        status: ProcessExitStatus,
619        stdout_data: Vec<u8>,
620        stdout_truncated: bool,
621        stderr_data: Vec<u8>,
622        stderr_truncated: bool,
623    ) -> Result<Self, ProcessActionError> {
624        validate_captured_bytes(
625            "stdout_bytes",
626            stdout_data.len(),
627            intent.stdout_limit_bytes(),
628        )?;
629        validate_captured_bytes(
630            "stderr_bytes",
631            stderr_data.len(),
632            intent.stderr_limit_bytes(),
633        )?;
634
635        Ok(Self {
636            status,
637            stdout_text: String::from_utf8_lossy(&stdout_data).into_owned(),
638            stdout_bytes: stdout_data.len(),
639            stdout_data,
640            stdout_truncated,
641            stderr_text: String::from_utf8_lossy(&stderr_data).into_owned(),
642            stderr_bytes: stderr_data.len(),
643            stderr_data,
644            stderr_truncated,
645            running_pid: None,
646            background_process_id: None,
647            wait_timed_out_secs: None,
648        })
649    }
650
651    /// Records the pid of a process that is still running.
652    #[must_use]
653    pub fn with_running_pid(mut self, pid: u32) -> Self {
654        self.running_pid = Some(pid);
655        self
656    }
657
658    /// Records the id of a process retained after this call returns.
659    #[must_use]
660    pub fn with_background_process_id(mut self, id: BackgroundProcessId) -> Self {
661        self.background_process_id = Some(id);
662        self
663    }
664
665    /// Records that a foreground wait elapsed after `secs` seconds without killing
666    /// the still-running process, handing it off to the background supervisor.
667    #[must_use]
668    pub fn with_wait_timed_out_secs(mut self, secs: u64) -> Self {
669        self.wait_timed_out_secs = Some(secs);
670        self
671    }
672
673    /// Returns the provider-neutral completion status.
674    #[must_use]
675    pub const fn status(&self) -> ProcessExitStatus {
676        self.status
677    }
678
679    /// Returns bounded stdout payload for the result artifact.
680    #[must_use]
681    pub fn stdout_text(&self) -> &str {
682        &self.stdout_text
683    }
684
685    /// Returns the exact bounded stdout bytes.
686    #[must_use]
687    pub fn stdout_data(&self) -> &[u8] {
688        &self.stdout_data
689    }
690
691    /// Returns whether stdout was valid UTF-8 without replacement.
692    #[must_use]
693    pub fn stdout_is_utf8(&self) -> bool {
694        std::str::from_utf8(&self.stdout_data).is_ok()
695    }
696
697    /// Returns captured stdout byte count.
698    #[must_use]
699    pub const fn stdout_bytes(&self) -> usize {
700        self.stdout_bytes
701    }
702
703    /// Returns whether stdout capture was truncated.
704    #[must_use]
705    pub const fn stdout_truncated(&self) -> bool {
706        self.stdout_truncated
707    }
708
709    /// Returns bounded stderr payload for the result artifact.
710    #[must_use]
711    pub fn stderr_text(&self) -> &str {
712        &self.stderr_text
713    }
714
715    /// Returns the exact bounded stderr bytes.
716    #[must_use]
717    pub fn stderr_data(&self) -> &[u8] {
718        &self.stderr_data
719    }
720
721    /// Returns whether stderr was valid UTF-8 without replacement.
722    #[must_use]
723    pub fn stderr_is_utf8(&self) -> bool {
724        std::str::from_utf8(&self.stderr_data).is_ok()
725    }
726
727    /// Returns captured stderr byte count.
728    #[must_use]
729    pub const fn stderr_bytes(&self) -> usize {
730        self.stderr_bytes
731    }
732
733    /// Returns whether stderr capture was truncated.
734    #[must_use]
735    pub const fn stderr_truncated(&self) -> bool {
736        self.stderr_truncated
737    }
738
739    /// Returns the pid when the process is still running.
740    #[must_use]
741    pub const fn running_pid(&self) -> Option<u32> {
742        self.running_pid
743    }
744
745    /// Returns the id of a process retained after this call returns.
746    #[must_use]
747    pub fn background_process_id(&self) -> Option<&BackgroundProcessId> {
748        self.background_process_id.as_ref()
749    }
750
751    /// Returns the foreground wait timeout in seconds when the call handed off a
752    /// still-running command to the background without killing it.
753    #[must_use]
754    pub const fn wait_timed_out_secs(&self) -> Option<u64> {
755        self.wait_timed_out_secs
756    }
757
758    /// Returns whether the process output represents successful completion.
759    ///
760    /// A process that is still running counts as success so the turn can continue.
761    #[must_use]
762    pub const fn ok(&self) -> bool {
763        matches!(
764            self.status,
765            ProcessExitStatus::Exited(0) | ProcessExitStatus::Running
766        )
767    }
768
769    /// Builds payload-free internal execution evidence for the given intent.
770    pub fn execution_evidence(
771        &self,
772        intent: &ProcessActionIntent,
773        permission_profile_id: ProcessPermissionProfileId,
774    ) -> Result<ProcessExecutionEvidence, ProcessActionError> {
775        ProcessExecutionEvidence::new(
776            intent,
777            permission_profile_id,
778            self.status,
779            self.stdout_bytes,
780            self.stdout_truncated,
781            self.stderr_bytes,
782            self.stderr_truncated,
783        )
784    }
785}
786
787/// Provider-neutral process completion status.
788#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
789#[serde(rename_all = "snake_case")]
790pub enum ProcessExitStatus {
791    /// The process exited with an integer code.
792    Exited(i32),
793    /// The process was cancelled before normal completion.
794    Cancelled,
795    /// The process could not be started by the future process executor.
796    FailedToStart,
797    /// The process runner reported a domain failure before normal completion.
798    DomainFailed,
799    /// The process was still running when the tool returned.
800    ///
801    /// The runner keeps it until the owning session ends.
802    Running,
803}
804
805impl ProcessExitStatus {
806    /// Returns the exit code when the process reached normal exit.
807    #[must_use]
808    pub const fn exit_code(self) -> Option<i32> {
809        match self {
810            Self::Exited(code) => Some(code),
811            Self::Cancelled | Self::FailedToStart | Self::DomainFailed | Self::Running => None,
812        }
813    }
814}
815
816/// Infrastructure errors returned by a process runner.
817#[derive(Debug, Clone, PartialEq, Eq, Error)]
818pub enum ProcessRunnerError {
819    /// Process runner was cancelled cooperatively before producing output.
820    #[error("process runner cancelled")]
821    Cancelled,
822
823    /// The runner infrastructure failed before producing durable output.
824    #[error("process runner infrastructure error: {message}")]
825    Infrastructure {
826        /// Actionable infrastructure failure detail.
827        message: String,
828    },
829}
830
831impl ProcessRunnerError {
832    /// Creates an infrastructure process runner error.
833    #[must_use]
834    pub fn infrastructure(message: impl Into<String>) -> Self {
835        Self::Infrastructure {
836            message: message.into(),
837        }
838    }
839}
840
841/// Provider-neutral evidence recorded after a process action executes.
842///
843/// This stores bounded metadata only: the validated intent identity, completion
844/// status, captured byte counts, and truncation flags. It contains no provider
845/// wire data and no stdout/stderr payload.
846#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
847#[serde(deny_unknown_fields)]
848pub struct ProcessExecutionEvidence {
849    intent_summary: String,
850    argv: Vec<String>,
851    cwd: Option<String>,
852    permission_profile_id: ProcessPermissionProfileId,
853    status: ProcessExitStatus,
854    stdout_bytes: usize,
855    stdout_truncated: bool,
856    stderr_bytes: usize,
857    stderr_truncated: bool,
858}
859
860impl ProcessExecutionEvidence {
861    /// Creates validated process execution evidence for a previously proposed intent.
862    pub fn new(
863        intent: &ProcessActionIntent,
864        permission_profile_id: ProcessPermissionProfileId,
865        status: ProcessExitStatus,
866        stdout_bytes: usize,
867        stdout_truncated: bool,
868        stderr_bytes: usize,
869        stderr_truncated: bool,
870    ) -> Result<Self, ProcessActionError> {
871        validate_captured_bytes("stdout_bytes", stdout_bytes, intent.stdout_limit_bytes())?;
872        validate_captured_bytes("stderr_bytes", stderr_bytes, intent.stderr_limit_bytes())?;
873
874        Ok(Self {
875            intent_summary: intent.summary().to_owned(),
876            argv: intent.argv().to_vec(),
877            cwd: intent.cwd().map(str::to_owned),
878            permission_profile_id,
879            status,
880            stdout_bytes,
881            stdout_truncated,
882            stderr_bytes,
883            stderr_truncated,
884        })
885    }
886
887    /// Returns the compact process intent summary.
888    #[must_use]
889    pub fn intent_summary(&self) -> &str {
890        &self.intent_summary
891    }
892
893    /// Returns the exact argv copied from the validated intent.
894    #[must_use]
895    pub fn argv(&self) -> &[String] {
896        &self.argv
897    }
898
899    /// Returns the workspace-relative cwd copied from the validated intent.
900    #[must_use]
901    pub fn cwd(&self) -> Option<&str> {
902        self.cwd.as_deref()
903    }
904
905    /// Returns the permission profile used for this process execution.
906    #[must_use]
907    pub const fn permission_profile_id(&self) -> ProcessPermissionProfileId {
908        self.permission_profile_id
909    }
910
911    /// Returns the provider-neutral completion status.
912    #[must_use]
913    pub const fn status(&self) -> ProcessExitStatus {
914        self.status
915    }
916
917    /// Returns the exit code when the process reached normal exit.
918    #[must_use]
919    pub const fn exit_code(&self) -> Option<i32> {
920        self.status.exit_code()
921    }
922
923    /// Returns captured stdout byte count.
924    #[must_use]
925    pub const fn stdout_bytes(&self) -> usize {
926        self.stdout_bytes
927    }
928
929    /// Returns whether stdout capture was truncated.
930    #[must_use]
931    pub const fn stdout_truncated(&self) -> bool {
932        self.stdout_truncated
933    }
934
935    /// Returns captured stderr byte count.
936    #[must_use]
937    pub const fn stderr_bytes(&self) -> usize {
938        self.stderr_bytes
939    }
940
941    /// Returns whether stderr capture was truncated.
942    #[must_use]
943    pub const fn stderr_truncated(&self) -> bool {
944        self.stderr_truncated
945    }
946
947    pub(crate) fn matches_intent(&self, intent: &ProcessActionIntent) -> bool {
948        self.intent_summary == intent.summary()
949            && self.argv == intent.argv()
950            && self.cwd.as_deref() == intent.cwd()
951            && self.stdout_bytes <= intent.stdout_limit_bytes()
952            && self.stderr_bytes <= intent.stderr_limit_bytes()
953    }
954}