merry-runtime 0.1.2

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
use super::validation::{
    ProcessActionError, summarize_intent, validate_argv, validate_captured_bytes, validate_cwd,
    validate_output_limit, validate_stdin_text, validate_timeout_secs,
};
use super::{BackgroundProcessControl, BackgroundProcessId};
use crate::{PermissionRequest, RequestedCapability};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::{fmt, future::Future, pin::Pin, sync::Arc};
use thiserror::Error;
use tokio_util::sync::CancellationToken;

/// Maximum accepted byte length for one argv item in a process intent.
///
/// Sized for inline shell/Python scripts (`64 KiB`), staying safely below
/// Linux's `128 KiB` `MAX_ARG_STRLEN` while matching [`MAX_PROCESS_STDIN_TEXT_BYTES`].
pub const MAX_PROCESS_ARG_BYTES: usize = 64 * 1024;
/// Maximum accepted number of argv items in a process intent.
pub const MAX_PROCESS_ARGV_ITEMS: usize = 256;
/// Maximum accepted byte length for a workspace-relative process cwd.
pub const MAX_PROCESS_CWD_BYTES: usize = 4096;
/// Maximum accepted byte length for inline stdin text.
pub const MAX_PROCESS_STDIN_TEXT_BYTES: usize = 64 * 1024;
/// Maximum accepted captured byte limit per process output stream.
pub const MAX_PROCESS_OUTPUT_LIMIT_BYTES: usize = 1024 * 1024;
/// Default foreground wait timeout in seconds before handing off to background.
pub const DEFAULT_PROCESS_WAIT_TIMEOUT_SECS: u64 = 120;
/// Maximum accepted foreground wait timeout in seconds for one `run_process` call.
pub const MAX_PROCESS_WAIT_TIMEOUT_SECS: u64 = 3600;

/// Minimal process environment override policy for SP1.
///
/// This describes environment changes requested by the tool call. It does not
/// decide whether the selected process runner inherits its own current
/// environment; that is part of the runner/sandbox boundary chosen by the
/// runtime builder.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProcessEnvPolicy {
    /// No tool-requested environment overrides.
    #[default]
    Empty,
    /// Test-only stand-in for a future non-empty environment policy.
    #[cfg(test)]
    NonEmptyForTest,
}

impl ProcessEnvPolicy {
    /// Creates the no environment override policy.
    #[must_use]
    pub const fn empty() -> Self {
        Self::Empty
    }
}

/// Explicit admission for the process runner used by the local workspace lane.
///
/// This value is intentionally small and declarative. It records that the
/// caller has selected Merry's local-workspace process profile and accepted
/// the process risk for that profile; it is not proof that any process is
/// actually confined. A host adapter may materialize this profile with a
/// platform-native mechanism, or report that isolation is unavailable. Runtime
/// code treats it as construction-time admission for the configured process
/// runner boundary;
/// argv classification remains a risk signal rather than an executable
/// allowlist.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AcceptedLocalWorkspaceProcessAdmission {
    sandbox_profile: LocalWorkspaceProcessSandboxProfile,
    permission_profile_id: ProcessPermissionProfileId,
}

impl AcceptedLocalWorkspaceProcessAdmission {
    /// Creates admission for the local workspace process profile.
    ///
    /// Calling this explicitly accepts validated process intents for the
    /// declared profile. The selected runner still enforces filesystem,
    /// network, and host-integration capabilities.
    #[must_use]
    pub const fn accept_local_workspace() -> Self {
        Self {
            sandbox_profile: LocalWorkspaceProcessSandboxProfile::LocalWorkspace,
            permission_profile_id: ProcessPermissionProfileId::LOCAL_WORKSPACE,
        }
    }

    /// Creates admission for the explicit unrestricted host process profile.
    ///
    /// The runtime still records and audits the process action, but the host
    /// process backend does not add an operating-system sandbox in this mode.
    /// Review policy remains a separate runtime setting; host admission does
    /// not imply fully trusted execution.
    #[must_use]
    pub const fn accept_host() -> Self {
        Self {
            sandbox_profile: LocalWorkspaceProcessSandboxProfile::Host,
            permission_profile_id: ProcessPermissionProfileId::LOCAL_WORKSPACE_HOST,
        }
    }

    #[cfg(test)]
    pub(crate) const fn for_test_permission_profile_id(
        permission_profile_id: ProcessPermissionProfileId,
    ) -> Self {
        Self {
            sandbox_profile: LocalWorkspaceProcessSandboxProfile::LocalWorkspace,
            permission_profile_id,
        }
    }

    /// Returns the declared sandbox profile for this admission.
    #[must_use]
    pub const fn sandbox_profile(self) -> LocalWorkspaceProcessSandboxProfile {
        self.sandbox_profile
    }

    /// Returns the permission profile admitted by this construction-time grant.
    #[must_use]
    pub const fn permission_profile_id(self) -> ProcessPermissionProfileId {
        self.permission_profile_id
    }
}

/// Declared sandbox/profile associated with local workspace process admission.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LocalWorkspaceProcessSandboxProfile {
    /// Local workspace process profile.
    LocalWorkspace,
    /// Explicit unrestricted host process profile.
    Host,
}

impl LocalWorkspaceProcessSandboxProfile {
    /// Returns the stable profile label used in process composition identity.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::LocalWorkspace => "local-workspace",
            Self::Host => "host",
        }
    }
}

/// Stable identifier for a runtime-owned process permission profile.
///
/// Permission profiles describe filesystem, network, and side-effect
/// capability. They are separate from concrete command classification and from
/// model-visible tool profiles.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ProcessPermissionProfileId(&'static str);

impl ProcessPermissionProfileId {
    /// Read-only process lane for bounded inspection commands.
    pub const READ_ONLY: Self = Self("process.read_only");
    /// Local workspace process lane.
    pub const LOCAL_WORKSPACE: Self = Self("process.local_workspace");
    /// Local workspace process lane accepted for the unrestricted host profile.
    pub const LOCAL_WORKSPACE_HOST: Self = Self("process.local_workspace.host");
    /// Read-only shell wrapper lane for plain command sequences under a real shell runner.
    pub const SHELL_READ_ONLY: Self = Self("process.shell.read_only");
    /// Process lane admitted by an explicit permission request review.
    pub const APPROVED_PERMISSION_REQUEST: Self = Self("process.permission_request.approved");

    /// Returns the stable profile identifier string.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        self.0
    }
}

impl Serialize for ProcessPermissionProfileId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str((*self).as_str())
    }
}

impl<'de> Deserialize<'de> for ProcessPermissionProfileId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        match value.as_str() {
            "process.read_only" => Ok(Self::READ_ONLY),
            "process.local_workspace" => Ok(Self::LOCAL_WORKSPACE),
            "process.local_workspace.host" => Ok(Self::LOCAL_WORKSPACE_HOST),
            "process.shell.read_only" => Ok(Self::SHELL_READ_ONLY),
            "process.permission_request.approved" => Ok(Self::APPROVED_PERMISSION_REQUEST),
            _ => Err(serde::de::Error::custom(format!(
                "unsupported process permission profile id `{value}`"
            ))),
        }
    }
}

impl fmt::Display for ProcessPermissionProfileId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Boxed process runner future used for object-safe runtime process boundaries.
///
/// The runner boundary is runtime-owned and provider-neutral. It accepts only a
/// validated [`ProcessActionIntent`] and a cancellation-aware context.
pub type ProcessRunnerFuture<'a> = Pin<Box<dyn Future<Output = ProcessRunnerResult> + Send + 'a>>;

/// Result returned by a runtime-owned process runner.
pub type ProcessRunnerResult = Result<ProcessRunnerOutput, ProcessRunnerError>;

/// Live incremental output chunk emitted while a process action is running.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProcessOutputChunk {
    /// Tool call that owns the running process.
    pub call_id: merry_core::ToolCallId,
    /// Which output pipe produced the chunk.
    pub stream: merry_core::ToolOutputStream,
    /// Lossy UTF-8 text chunk.
    pub delta: String,
}

/// Non-blocking sink for forwarding bounded live process output chunks to UI observers.
#[derive(Debug, Clone)]
pub struct ProcessOutputSink {
    call_id: merry_core::ToolCallId,
    sender: tokio::sync::mpsc::Sender<ProcessOutputChunk>,
}

impl ProcessOutputSink {
    /// Creates a live output sink bound to one active tool call.
    #[must_use]
    pub fn new(
        call_id: merry_core::ToolCallId,
        sender: tokio::sync::mpsc::Sender<ProcessOutputChunk>,
    ) -> Self {
        Self { call_id, sender }
    }

    /// Emits a bounded chunk without ever blocking the process reader task.
    pub fn emit(&self, stream: merry_core::ToolOutputStream, bytes: &[u8]) {
        if bytes.is_empty() {
            return;
        }
        const MAX_LIVE_CHUNK_BYTES: usize = 4096;
        let slice = &bytes[..bytes.len().min(MAX_LIVE_CHUNK_BYTES)];
        let delta = String::from_utf8_lossy(slice).into_owned();
        let _ = self.sender.try_send(ProcessOutputChunk {
            call_id: self.call_id.clone(),
            stream,
            delta,
        });
    }
}

/// Context passed to a process runner.
#[derive(Debug, Clone)]
pub struct ProcessRunnerContext {
    cancellation_token: CancellationToken,
    output_sink: Option<ProcessOutputSink>,
}

impl ProcessRunnerContext {
    /// Creates a process runner context with the provided cancellation token.
    #[must_use]
    pub fn new(cancellation_token: CancellationToken) -> Self {
        Self {
            cancellation_token,
            output_sink: None,
        }
    }

    /// Attaches a non-blocking live output sink for streaming stdout/stderr progress.
    #[must_use]
    pub fn with_output_sink(mut self, sink: ProcessOutputSink) -> Self {
        self.output_sink = Some(sink);
        self
    }

    /// Returns the cancellation token for this process action.
    #[must_use]
    pub fn cancellation_token(&self) -> &CancellationToken {
        &self.cancellation_token
    }

    /// Returns the optional live output sink for streaming stdout/stderr progress.
    #[must_use]
    pub fn output_sink(&self) -> Option<&ProcessOutputSink> {
        self.output_sink.as_ref()
    }
}

/// Object-safe runtime process runner boundary.
///
/// Implementations for SP2 are fakes or adapters supplied by tests and higher
/// layers. This trait must not imply shell execution, raw shell parsing, or
/// provider-specific behavior.
pub trait ProcessRunner: Send + Sync {
    /// Runs a validated process intent and returns provider-neutral output.
    fn run<'a>(
        &'a self,
        intent: ProcessActionIntent,
        context: ProcessRunnerContext,
    ) -> ProcessRunnerFuture<'a>;

    /// Returns the session board that retains this runner's background processes.
    ///
    /// Runners that do not keep processes after `run` returns leave this empty.
    fn background_control(&self) -> Option<Arc<dyn BackgroundProcessControl>> {
        None
    }
}

/// Factory for runners created from approved permission requests.
///
/// Implementations translate a runtime-approved request into the concrete
/// process backend/profile for that exact action. Adapters consume read-only
/// session snapshots; runtime owns retention and capability lifetimes through
/// `SessionPermissionedProcessRunnerFactory`. An adapter never records grants
/// or grants authority beyond the runtime-approved request.
pub trait PermissionedProcessRunnerFactory: Send + Sync {
    /// Validates the request against the backend's hard capability policy.
    ///
    /// Backends that do not have additional policy constraints may keep the
    /// default only when they can enforce every capability in the request
    /// through their existing runner. A backend that cannot materialize a
    /// requested path or network grant must reject it. A validation failure
    /// must happen before any reviewer or process side effect is started.
    fn validate_request(&self, _request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
        Ok(())
    }

    /// Returns whether the backend already enforces every capability in the
    /// request for the current process session.
    ///
    /// This query covers capability state only; it does not authorize the
    /// requested action. Implementations must return `false` for capabilities
    /// that are action-scoped, such as network access, or when the backend
    /// cannot prove that the requested access is covered.
    fn request_capabilities_are_satisfied(
        &self,
        _request: &PermissionRequest,
    ) -> Result<bool, ProcessRunnerError> {
        Ok(false)
    }

    /// Prepares one validated action and its normalized path evidence without
    /// changing permission state. Adapters can share a single filesystem view
    /// across validation and materialization. The default retains no paths.
    fn prepare_approved_request(
        &self,
        request: &PermissionRequest,
    ) -> Result<super::PreparedProcessPermission, ProcessRunnerError> {
        self.validate_request(request)?;
        Ok(super::PreparedProcessPermission::new(
            self.runner_for(request),
            Vec::new(),
        ))
    }

    /// Creates the process runner for one approved permission request, without
    /// mutating session state. Runtime handles retention after successful preparation.
    fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner>;
}

/// Compatibility factory that always returns the same runner.
#[derive(Clone)]
pub struct StaticPermissionedProcessRunnerFactory {
    runner: Arc<dyn ProcessRunner>,
}

impl StaticPermissionedProcessRunnerFactory {
    /// Creates a static runner factory.
    #[must_use]
    pub fn new(runner: Arc<dyn ProcessRunner>) -> Self {
        Self { runner }
    }
}

impl PermissionedProcessRunnerFactory for StaticPermissionedProcessRunnerFactory {
    fn validate_request(&self, request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
        if request
            .requested()
            .iter()
            .any(|capability| matches!(capability, RequestedCapability::Path(_)))
        {
            return Err(ProcessRunnerError::infrastructure(
                "static permissioned process runner cannot enforce requested path capabilities",
            ));
        }
        if request
            .requested()
            .iter()
            .any(|capability| matches!(capability, RequestedCapability::HostIntegration(_)))
        {
            return Err(ProcessRunnerError::infrastructure(
                "static permissioned process runner cannot enforce requested host integrations",
            ));
        }
        Ok(())
    }

    fn runner_for(&self, _request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
        Arc::clone(&self.runner)
    }
}

/// Provider-neutral, typed intent for a local process action.
///
/// The argv vector is intentionally open and does not enumerate allowed
/// commands. This value is proposal evidence only in SP1; it is not an
/// executor and must not be treated as authorization to spawn a process.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProcessActionIntent {
    summary: String,
    argv: Vec<String>,
    cwd: Option<String>,
    env_policy: ProcessEnvPolicy,
    stdin_text: Option<String>,
    stdout_limit_bytes: usize,
    stderr_limit_bytes: usize,
    #[serde(default)]
    background: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    timeout_secs: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    display_name: Option<String>,
}

impl ProcessActionIntent {
    /// Creates a validated process action intent.
    pub fn new(
        argv: Vec<String>,
        cwd: Option<String>,
        env_policy: ProcessEnvPolicy,
        stdin_text: Option<String>,
        stdout_limit_bytes: usize,
        stderr_limit_bytes: usize,
    ) -> Result<Self, ProcessActionError> {
        validate_argv(&argv)?;
        let cwd = validate_cwd(cwd)?;
        validate_stdin_text(stdin_text.as_deref())?;
        validate_output_limit("stdout_limit_bytes", stdout_limit_bytes)?;
        validate_output_limit("stderr_limit_bytes", stderr_limit_bytes)?;
        let summary = summarize_intent(&argv, cwd.as_deref());

        Ok(Self {
            summary,
            argv,
            cwd,
            env_policy,
            stdin_text,
            stdout_limit_bytes,
            stderr_limit_bytes,
            background: false,
            timeout_secs: None,
            display_name: None,
        })
    }

    /// Keeps the process after the tool returns when `background` is true.
    ///
    /// The default waits until the process exits or reaches its wait timeout.
    /// A retained background process stays until stopped or the owning session ends.
    #[must_use]
    pub fn with_background(mut self, background: bool) -> Self {
        self.background = background;
        self
    }

    /// Sets an optional foreground wait timeout in seconds (`1..=MAX_PROCESS_WAIT_TIMEOUT_SECS`).
    ///
    /// When a foreground command is still running after this timeout, the runner
    /// does not kill it; it retains the process in the background and returns
    /// its id and partial output so the calling LLM can decide how to proceed.
    pub fn with_timeout_secs(
        mut self,
        timeout_secs: Option<u64>,
    ) -> Result<Self, ProcessActionError> {
        self.timeout_secs = validate_timeout_secs(timeout_secs)?;
        Ok(self)
    }

    /// Attaches an optional short human-readable label for a retained process.
    #[must_use]
    pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
        self.display_name = display_name.and_then(|value| {
            let normalized = value.split_whitespace().collect::<Vec<_>>().join(" ");
            if normalized.is_empty() {
                None
            } else {
                Some(normalized.chars().take(80).collect())
            }
        });
        self
    }

    /// Returns a compact deterministic summary of the process intent.
    #[must_use]
    pub fn summary(&self) -> &str {
        &self.summary
    }

    /// Returns the exact argv vector.
    #[must_use]
    pub fn argv(&self) -> &[String] {
        &self.argv
    }

    /// Returns the workspace-relative cwd, or `None` for the workspace root.
    #[must_use]
    pub fn cwd(&self) -> Option<&str> {
        self.cwd.as_deref()
    }

    /// Returns the typed environment policy.
    #[must_use]
    pub const fn env_policy(&self) -> ProcessEnvPolicy {
        self.env_policy
    }

    /// Returns optional inline stdin text.
    #[must_use]
    pub fn stdin_text(&self) -> Option<&str> {
        self.stdin_text.as_deref()
    }

    /// Returns whether the runner should retain the process after the tool returns.
    #[must_use]
    pub const fn background(&self) -> bool {
        self.background
    }

    /// Returns the explicit foreground wait timeout override in seconds, if set.
    #[must_use]
    pub const fn timeout_secs(&self) -> Option<u64> {
        self.timeout_secs
    }

    /// Returns the effective foreground wait timeout in seconds.
    #[must_use]
    pub const fn effective_wait_timeout_secs(&self) -> u64 {
        match self.timeout_secs {
            Some(secs) => secs,
            None => DEFAULT_PROCESS_WAIT_TIMEOUT_SECS,
        }
    }

    /// Returns the optional human-readable display name for this process.
    #[must_use]
    pub fn display_name(&self) -> Option<&str> {
        self.display_name.as_deref()
    }

    /// Returns the stdout capture limit in bytes.
    #[must_use]
    pub const fn stdout_limit_bytes(&self) -> usize {
        self.stdout_limit_bytes
    }

    /// Returns the stderr capture limit in bytes.
    #[must_use]
    pub const fn stderr_limit_bytes(&self) -> usize {
        self.stderr_limit_bytes
    }
}

/// Bounded output returned by a process runner.
///
/// Process output is an opaque byte stream. The runner keeps the exact bounded
/// bytes and a loss-tolerant UTF-8 view separately so binary tools cannot turn a
/// successful process into an infrastructure error merely by writing invalid
/// UTF-8. Internal execution audit evidence stores byte counts and truncation
/// flags, not these payloads.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProcessRunnerOutput {
    status: ProcessExitStatus,
    stdout_data: Vec<u8>,
    stdout_text: String,
    stdout_bytes: usize,
    stdout_truncated: bool,
    stderr_data: Vec<u8>,
    stderr_text: String,
    stderr_bytes: usize,
    stderr_truncated: bool,
    running_pid: Option<u32>,
    background_process_id: Option<BackgroundProcessId>,
    wait_timed_out_secs: Option<u64>,
}

impl ProcessRunnerOutput {
    /// Creates validated process runner output for a previously validated intent.
    pub fn new(
        intent: &ProcessActionIntent,
        status: ProcessExitStatus,
        stdout_text: impl Into<String>,
        stdout_truncated: bool,
        stderr_text: impl Into<String>,
        stderr_truncated: bool,
    ) -> Result<Self, ProcessActionError> {
        Self::from_bytes(
            intent,
            status,
            stdout_text.into().into_bytes(),
            stdout_truncated,
            stderr_text.into().into_bytes(),
            stderr_truncated,
        )
    }

    /// Creates output from exact bounded process bytes.
    pub fn from_bytes(
        intent: &ProcessActionIntent,
        status: ProcessExitStatus,
        stdout_data: Vec<u8>,
        stdout_truncated: bool,
        stderr_data: Vec<u8>,
        stderr_truncated: bool,
    ) -> Result<Self, ProcessActionError> {
        validate_captured_bytes(
            "stdout_bytes",
            stdout_data.len(),
            intent.stdout_limit_bytes(),
        )?;
        validate_captured_bytes(
            "stderr_bytes",
            stderr_data.len(),
            intent.stderr_limit_bytes(),
        )?;

        Ok(Self {
            status,
            stdout_text: String::from_utf8_lossy(&stdout_data).into_owned(),
            stdout_bytes: stdout_data.len(),
            stdout_data,
            stdout_truncated,
            stderr_text: String::from_utf8_lossy(&stderr_data).into_owned(),
            stderr_bytes: stderr_data.len(),
            stderr_data,
            stderr_truncated,
            running_pid: None,
            background_process_id: None,
            wait_timed_out_secs: None,
        })
    }

    /// Records the pid of a process that is still running.
    #[must_use]
    pub fn with_running_pid(mut self, pid: u32) -> Self {
        self.running_pid = Some(pid);
        self
    }

    /// Records the id of a process retained after this call returns.
    #[must_use]
    pub fn with_background_process_id(mut self, id: BackgroundProcessId) -> Self {
        self.background_process_id = Some(id);
        self
    }

    /// Records that a foreground wait elapsed after `secs` seconds without killing
    /// the still-running process, handing it off to the background supervisor.
    #[must_use]
    pub fn with_wait_timed_out_secs(mut self, secs: u64) -> Self {
        self.wait_timed_out_secs = Some(secs);
        self
    }

    /// Returns the provider-neutral completion status.
    #[must_use]
    pub const fn status(&self) -> ProcessExitStatus {
        self.status
    }

    /// Returns bounded stdout payload for the result artifact.
    #[must_use]
    pub fn stdout_text(&self) -> &str {
        &self.stdout_text
    }

    /// Returns the exact bounded stdout bytes.
    #[must_use]
    pub fn stdout_data(&self) -> &[u8] {
        &self.stdout_data
    }

    /// Returns whether stdout was valid UTF-8 without replacement.
    #[must_use]
    pub fn stdout_is_utf8(&self) -> bool {
        std::str::from_utf8(&self.stdout_data).is_ok()
    }

    /// Returns captured stdout byte count.
    #[must_use]
    pub const fn stdout_bytes(&self) -> usize {
        self.stdout_bytes
    }

    /// Returns whether stdout capture was truncated.
    #[must_use]
    pub const fn stdout_truncated(&self) -> bool {
        self.stdout_truncated
    }

    /// Returns bounded stderr payload for the result artifact.
    #[must_use]
    pub fn stderr_text(&self) -> &str {
        &self.stderr_text
    }

    /// Returns the exact bounded stderr bytes.
    #[must_use]
    pub fn stderr_data(&self) -> &[u8] {
        &self.stderr_data
    }

    /// Returns whether stderr was valid UTF-8 without replacement.
    #[must_use]
    pub fn stderr_is_utf8(&self) -> bool {
        std::str::from_utf8(&self.stderr_data).is_ok()
    }

    /// Returns captured stderr byte count.
    #[must_use]
    pub const fn stderr_bytes(&self) -> usize {
        self.stderr_bytes
    }

    /// Returns whether stderr capture was truncated.
    #[must_use]
    pub const fn stderr_truncated(&self) -> bool {
        self.stderr_truncated
    }

    /// Returns the pid when the process is still running.
    #[must_use]
    pub const fn running_pid(&self) -> Option<u32> {
        self.running_pid
    }

    /// Returns the id of a process retained after this call returns.
    #[must_use]
    pub fn background_process_id(&self) -> Option<&BackgroundProcessId> {
        self.background_process_id.as_ref()
    }

    /// Returns the foreground wait timeout in seconds when the call handed off a
    /// still-running command to the background without killing it.
    #[must_use]
    pub const fn wait_timed_out_secs(&self) -> Option<u64> {
        self.wait_timed_out_secs
    }

    /// Returns whether the process output represents successful completion.
    ///
    /// A process that is still running counts as success so the turn can continue.
    #[must_use]
    pub const fn ok(&self) -> bool {
        matches!(
            self.status,
            ProcessExitStatus::Exited(0) | ProcessExitStatus::Running
        )
    }

    /// Builds payload-free internal execution evidence for the given intent.
    pub fn execution_evidence(
        &self,
        intent: &ProcessActionIntent,
        permission_profile_id: ProcessPermissionProfileId,
    ) -> Result<ProcessExecutionEvidence, ProcessActionError> {
        ProcessExecutionEvidence::new(
            intent,
            permission_profile_id,
            self.status,
            self.stdout_bytes,
            self.stdout_truncated,
            self.stderr_bytes,
            self.stderr_truncated,
        )
    }
}

/// Provider-neutral process completion status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProcessExitStatus {
    /// The process exited with an integer code.
    Exited(i32),
    /// The process was cancelled before normal completion.
    Cancelled,
    /// The process could not be started by the future process executor.
    FailedToStart,
    /// The process runner reported a domain failure before normal completion.
    DomainFailed,
    /// The process was still running when the tool returned.
    ///
    /// The runner keeps it until the owning session ends.
    Running,
}

impl ProcessExitStatus {
    /// Returns the exit code when the process reached normal exit.
    #[must_use]
    pub const fn exit_code(self) -> Option<i32> {
        match self {
            Self::Exited(code) => Some(code),
            Self::Cancelled | Self::FailedToStart | Self::DomainFailed | Self::Running => None,
        }
    }
}

/// Infrastructure errors returned by a process runner.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum ProcessRunnerError {
    /// Process runner was cancelled cooperatively before producing output.
    #[error("process runner cancelled")]
    Cancelled,

    /// The runner infrastructure failed before producing durable output.
    #[error("process runner infrastructure error: {message}")]
    Infrastructure {
        /// Actionable infrastructure failure detail.
        message: String,
    },
}

impl ProcessRunnerError {
    /// Creates an infrastructure process runner error.
    #[must_use]
    pub fn infrastructure(message: impl Into<String>) -> Self {
        Self::Infrastructure {
            message: message.into(),
        }
    }
}

/// Provider-neutral evidence recorded after a process action executes.
///
/// This stores bounded metadata only: the validated intent identity, completion
/// status, captured byte counts, and truncation flags. It contains no provider
/// wire data and no stdout/stderr payload.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProcessExecutionEvidence {
    intent_summary: String,
    argv: Vec<String>,
    cwd: Option<String>,
    permission_profile_id: ProcessPermissionProfileId,
    status: ProcessExitStatus,
    stdout_bytes: usize,
    stdout_truncated: bool,
    stderr_bytes: usize,
    stderr_truncated: bool,
}

impl ProcessExecutionEvidence {
    /// Creates validated process execution evidence for a previously proposed intent.
    pub fn new(
        intent: &ProcessActionIntent,
        permission_profile_id: ProcessPermissionProfileId,
        status: ProcessExitStatus,
        stdout_bytes: usize,
        stdout_truncated: bool,
        stderr_bytes: usize,
        stderr_truncated: bool,
    ) -> Result<Self, ProcessActionError> {
        validate_captured_bytes("stdout_bytes", stdout_bytes, intent.stdout_limit_bytes())?;
        validate_captured_bytes("stderr_bytes", stderr_bytes, intent.stderr_limit_bytes())?;

        Ok(Self {
            intent_summary: intent.summary().to_owned(),
            argv: intent.argv().to_vec(),
            cwd: intent.cwd().map(str::to_owned),
            permission_profile_id,
            status,
            stdout_bytes,
            stdout_truncated,
            stderr_bytes,
            stderr_truncated,
        })
    }

    /// Returns the compact process intent summary.
    #[must_use]
    pub fn intent_summary(&self) -> &str {
        &self.intent_summary
    }

    /// Returns the exact argv copied from the validated intent.
    #[must_use]
    pub fn argv(&self) -> &[String] {
        &self.argv
    }

    /// Returns the workspace-relative cwd copied from the validated intent.
    #[must_use]
    pub fn cwd(&self) -> Option<&str> {
        self.cwd.as_deref()
    }

    /// Returns the permission profile used for this process execution.
    #[must_use]
    pub const fn permission_profile_id(&self) -> ProcessPermissionProfileId {
        self.permission_profile_id
    }

    /// Returns the provider-neutral completion status.
    #[must_use]
    pub const fn status(&self) -> ProcessExitStatus {
        self.status
    }

    /// Returns the exit code when the process reached normal exit.
    #[must_use]
    pub const fn exit_code(&self) -> Option<i32> {
        self.status.exit_code()
    }

    /// Returns captured stdout byte count.
    #[must_use]
    pub const fn stdout_bytes(&self) -> usize {
        self.stdout_bytes
    }

    /// Returns whether stdout capture was truncated.
    #[must_use]
    pub const fn stdout_truncated(&self) -> bool {
        self.stdout_truncated
    }

    /// Returns captured stderr byte count.
    #[must_use]
    pub const fn stderr_bytes(&self) -> usize {
        self.stderr_bytes
    }

    /// Returns whether stderr capture was truncated.
    #[must_use]
    pub const fn stderr_truncated(&self) -> bool {
        self.stderr_truncated
    }

    pub(crate) fn matches_intent(&self, intent: &ProcessActionIntent) -> bool {
        self.intent_summary == intent.summary()
            && self.argv == intent.argv()
            && self.cwd.as_deref() == intent.cwd()
            && self.stdout_bytes <= intent.stdout_limit_bytes()
            && self.stderr_bytes <= intent.stderr_limit_bytes()
    }
}