runx-runtime 0.6.19

Native Rust runtime for local runx execution, adapters, harness replay, receipts, and sandboxing.
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
// rust-style-allow: large-file because RuntimeOptions, checkpoint resume, and
// the public graph runner surface are still audited as one Rust cutover unit.
//! The act engine for runx: the single admit -> execute -> seal path every run
//! takes. A standalone skill is a one-act plan and a graph a multi-act plan;
//! both run through this one engine.
//!
//! The public surface lives here: [`Runtime`], [`RuntimeOptions`], [`StepRun`],
//! [`GraphRun`], [`GraphCheckpoint`], and the feature-gated [`run_graph_file`]
//! helper. The internal state machine and the per-step execution helpers live
//! in private submodules.

use std::collections::BTreeMap;
use std::path::Path;

use runx_contracts::{ClosureDisposition, FanoutReceiptSyncPoint, JsonObject, JsonValue, Receipt};
use runx_core::state_machine::{GraphStatus, SequentialGraphState, StepAdmissionWitness};
use runx_parser::ExecutionGraph;
use serde::{Deserialize, Serialize};

use super::graph::load_graph;
use crate::RuntimeError;
use crate::adapter::{InvocationStatus, SkillAdapter, SkillOutput};
use crate::effects::RuntimeEffectRegistry;
use crate::host::{Host, NoopHost};
use crate::journal::ExecutionJournal;
use crate::lifecycle::LifecycleEvent;
use crate::receipts::paths::{RUNX_CWD_ENV, RUNX_PROJECT_DIR_ENV, RUNX_RECEIPT_DIR_ENV};
use crate::receipts::signing::strip_receipt_signing_env;
use crate::receipts::{
    RUNX_RECEIPT_SIGN_ED25519_SEED_BASE64_ENV, RUNX_RECEIPT_SIGN_ISSUER_TYPE_ENV,
    RUNX_RECEIPT_SIGN_KID_ENV, RuntimeReceiptSignatureConfig, RuntimeReceiptSignaturePolicy,
    graph_receipt_with_disposition_and_policy, graph_receipt_with_effects_and_signature_policy,
};
use crate::services::ReceiptServices;
use crate::{PROVIDER_PERMISSION_GRANT_ID_ENV, PROVIDER_PERMISSION_GRANTED_SCOPES_ENV};

mod authority;
mod execution;
mod host_resolution;
mod inputs;
mod scheduler;
mod step_execution;
mod steps;
mod sync;

use execution::GraphExecution;

pub const RUNX_MAX_FANOUT_CONCURRENCY_ENV: &str = "RUNX_MAX_FANOUT_CONCURRENCY";
pub const RUNX_RUN_ID_ENV: &str = "RUNX_RUN_ID";
pub const RUNX_LOCAL_ENV_ALLOWLIST_ENV: &str = "RUNX_LOCAL_ENV_ALLOWLIST";

#[derive(Clone, Debug)]
pub struct RuntimeOptions {
    pub created_at: String,
    pub env: BTreeMap<String, String>,
    pub receipt_signature: RuntimeReceiptSignatureConfig,
    pub effects: RuntimeEffectRegistry,
    /// Credentials delivered to graph step invocations. Defaults to none; a
    /// top-level skill run threads its own delivery here so credential-needing
    /// graph-step tools (e.g. http tools with `${secret:NAME}` headers) resolve.
    pub credential_delivery: crate::credentials::CredentialDelivery,
}

impl RuntimeOptions {
    #[must_use]
    pub fn local_development() -> Self {
        let env = safe_default_env();
        Self {
            created_at: crate::time::now_iso8601(),
            env,
            receipt_signature: RuntimeReceiptSignatureConfig::local_development(),
            effects: RuntimeEffectRegistry::default(),
            credential_delivery: crate::credentials::CredentialDelivery::none(),
        }
    }

    pub fn from_process_env() -> Result<Self, RuntimeError> {
        Self::from_env(safe_default_env())
    }

    #[must_use]
    pub fn safe_process_env() -> BTreeMap<String, String> {
        safe_default_env()
    }

    pub fn from_env(mut env: BTreeMap<String, String>) -> Result<Self, RuntimeError> {
        let receipt_services =
            ReceiptServices::from_env(&env).map_err(|error| RuntimeError::ReceiptInvalid {
                message: error.to_string(),
            })?;
        strip_receipt_signing_env(&mut env);
        Ok(Self {
            created_at: crate::time::now_iso8601(),
            env,
            receipt_signature: receipt_services.signature_config().clone(),
            effects: RuntimeEffectRegistry::default(),
            credential_delivery: crate::credentials::CredentialDelivery::none(),
        })
    }

    #[must_use]
    pub fn signature_policy(&self) -> RuntimeReceiptSignaturePolicy<'_> {
        self.receipt_signature.signature_policy()
    }
}

fn safe_default_env() -> BTreeMap<String, String> {
    safe_default_env_from(crate::services::process_env_value)
}

fn safe_default_env_from(
    mut value_for_key: impl FnMut(&str) -> Option<String>,
) -> BTreeMap<String, String> {
    let allowed = [
        "PATH",
        "SystemRoot",
        "PATHEXT",
        RUNX_RECEIPT_DIR_ENV,
        RUNX_RECEIPT_SIGN_KID_ENV,
        RUNX_RECEIPT_SIGN_ED25519_SEED_BASE64_ENV,
        RUNX_RECEIPT_SIGN_ISSUER_TYPE_ENV,
        crate::sandbox::RUNX_SANDBOX_ALLOW_DECLARED_POLICY_ONLY_ENV,
        RUNX_MAX_FANOUT_CONCURRENCY_ENV,
        RUNX_RUN_ID_ENV,
        RUNX_PROJECT_DIR_ENV,
        RUNX_CWD_ENV,
        PROVIDER_PERMISSION_GRANT_ID_ENV,
        PROVIDER_PERMISSION_GRANTED_SCOPES_ENV,
        "RUNX_HTTP_ALLOW_PRIVATE_NETWORK",
        "RUNX_REGISTRY_DIR",
        "RUNX_REGISTRY_URL",
    ];
    let mut env = allowed
        .into_iter()
        .filter_map(|key| value_for_key(key).map(|value| (key.to_owned(), value)))
        .collect::<BTreeMap<_, _>>();

    if let Some(raw_allowlist) = value_for_key(RUNX_LOCAL_ENV_ALLOWLIST_ENV) {
        for key in parse_local_env_allowlist(&raw_allowlist) {
            if let Some(value) = value_for_key(&key) {
                env.insert(key, value);
            }
        }
    }

    env
}

fn parse_local_env_allowlist(raw: &str) -> impl Iterator<Item = String> + '_ {
    raw.split([',', ' ', '\n', '\t'])
        .map(str::trim)
        .filter(|key| !key.is_empty())
        .filter(|key| {
            key.bytes()
                .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_')
        })
        .filter(|key| !key.starts_with("RUNX_RECEIPT_SIGN_"))
        .map(ToOwned::to_owned)
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StepRun {
    pub step_id: String,
    pub attempt: u32,
    pub skill: String,
    pub runner: Option<String>,
    pub fanout_group: Option<String>,
    pub output: SkillOutput,
    pub outputs: JsonObject,
    pub receipt: Receipt,
    pub admission_witness: StepAdmissionWitness,
}

#[derive(Clone, Debug)]
pub struct GraphRun {
    pub graph: ExecutionGraph,
    pub state: SequentialGraphState,
    pub steps: Vec<StepRun>,
    pub sync_points: Vec<FanoutReceiptSyncPoint>,
    pub receipt: Receipt,
    pub journal: ExecutionJournal,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GraphCheckpoint {
    pub graph_name: String,
    pub state: SequentialGraphState,
    pub steps: Vec<StepRun>,
    pub sync_points: Vec<FanoutReceiptSyncPoint>,
    pub journal: ExecutionJournal,
}

pub struct Runtime<A> {
    adapter: A,
    options: RuntimeOptions,
    step_types: steps::StepTypeRegistry<A>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BlockedGraphOutcome {
    Error,
    Receipt,
}

impl<A> Runtime<A>
where
    A: SkillAdapter,
{
    pub fn new(adapter: A, options: RuntimeOptions) -> Self {
        Self {
            adapter,
            options,
            step_types: steps::StepTypeRegistry::builtins(),
        }
    }

    pub(crate) fn options(&self) -> &RuntimeOptions {
        &self.options
    }

    pub fn run_graph_file(&self, graph_path: &Path) -> Result<GraphRun, RuntimeError> {
        let mut host = NoopHost;
        self.run_graph_file_with_host(graph_path, &mut host)
    }

    pub fn run_graph_file_with_host(
        &self,
        graph_path: &Path,
        host: &mut dyn Host,
    ) -> Result<GraphRun, RuntimeError> {
        let graph = load_graph(graph_path)?;
        let graph_dir = graph_path.parent().unwrap_or_else(|| Path::new("."));
        self.run_graph_with_host_outcome(graph_dir, graph, host, BlockedGraphOutcome::Error)
    }

    pub(crate) fn run_graph_file_for_harness(
        &self,
        graph_path: &Path,
        host: &mut dyn Host,
    ) -> Result<GraphRun, RuntimeError> {
        let graph = load_graph(graph_path)?;
        let graph_dir = graph_path.parent().unwrap_or_else(|| Path::new("."));
        self.run_graph_with_host_outcome(graph_dir, graph, host, BlockedGraphOutcome::Receipt)
    }

    pub fn run_graph_with_host(
        &self,
        graph_dir: &Path,
        graph: ExecutionGraph,
        host: &mut dyn Host,
    ) -> Result<GraphRun, RuntimeError> {
        self.run_graph_with_host_outcome(graph_dir, graph, host, BlockedGraphOutcome::Error)
    }

    // rust-style-allow: long-function because graph execution drives one ordered
    // ready-node loop (admit, dispatch to host, fold outcomes, advance frontier)
    // whose step sequencing must stay in a single scope to keep the run auditable.
    fn run_graph_with_host_outcome(
        &self,
        graph_dir: &Path,
        graph: ExecutionGraph,
        host: &mut dyn Host,
        blocked_outcome: BlockedGraphOutcome,
    ) -> Result<GraphRun, RuntimeError> {
        let mut execution = GraphExecution::new(&graph);
        match execution.run(self, graph_dir, &graph, host, None) {
            Ok(()) => {
                let receipt = graph_receipt_with_effects_and_signature_policy(
                    &graph.name,
                    &mut execution.runs,
                    execution.sync_points.clone(),
                    &self.options.created_at,
                    self.options.effects.clone(),
                    self.options.signature_policy(),
                )?;
                execution.record_lifecycle(
                    host,
                    LifecycleEvent::graph_completed(&graph.name, &receipt),
                )?;
                Ok(execution.finish(graph, receipt))
            }
            Err(RuntimeError::GraphBlocked { step_id, reason })
                if blocked_outcome == BlockedGraphOutcome::Receipt =>
            {
                let receipt = graph_receipt_with_disposition_and_policy(
                    &graph.name,
                    &mut execution.runs,
                    execution.sync_points.clone(),
                    &self.options.created_at,
                    crate::receipts::GraphClosure {
                        disposition: ClosureDisposition::Blocked,
                        reason_code: "graph_blocked".to_owned(),
                        summary: format!("graph {} blocked at {step_id}: {reason}", graph.name),
                    },
                    self.options.effects.clone(),
                    self.options.signature_policy(),
                )?;
                execution.record_lifecycle(
                    host,
                    LifecycleEvent::graph_blocked(&graph.name, &step_id, &receipt),
                )?;
                Ok(execution.finish(graph, receipt))
            }
            // A governed authority denial is a policy block, not a runtime fault:
            // under the receipt-sealing outcome it seals a signed blocked receipt,
            // the same as any other graph block, so the refusal is provable.
            Err(RuntimeError::AuthorityDenied {
                verb,
                step_id,
                reason,
            }) if blocked_outcome == BlockedGraphOutcome::Receipt => {
                let receipt = graph_receipt_with_disposition_and_policy(
                    &graph.name,
                    &mut execution.runs,
                    execution.sync_points.clone(),
                    &self.options.created_at,
                    crate::receipts::GraphClosure {
                        disposition: ClosureDisposition::Blocked,
                        reason_code: "authority_denied".to_owned(),
                        summary: format!(
                            "graph {} denied {verb:?} at {step_id}: {reason}",
                            graph.name
                        ),
                    },
                    self.options.effects.clone(),
                    self.options.signature_policy(),
                )?;
                execution.record_lifecycle(
                    host,
                    LifecycleEvent::graph_blocked(&graph.name, &step_id, &receipt),
                )?;
                Ok(execution.finish(graph, receipt))
            }
            Err(error) => Err(error),
        }
    }

    pub fn run_graph_file_until_steps(
        &self,
        graph_path: &Path,
        max_steps: usize,
    ) -> Result<GraphCheckpoint, RuntimeError> {
        let mut host = NoopHost;
        self.run_graph_file_until_steps_with_host(graph_path, max_steps, &mut host)
    }

    pub fn run_graph_file_until_steps_with_host(
        &self,
        graph_path: &Path,
        max_steps: usize,
        host: &mut dyn Host,
    ) -> Result<GraphCheckpoint, RuntimeError> {
        let graph = load_graph(graph_path)?;
        let graph_dir = graph_path.parent().unwrap_or_else(|| Path::new("."));
        self.run_graph_until_steps_with_host(graph_dir, &graph, max_steps, host)
    }

    pub fn run_graph_until_steps_with_host(
        &self,
        graph_dir: &Path,
        graph: &ExecutionGraph,
        max_steps: usize,
        host: &mut dyn Host,
    ) -> Result<GraphCheckpoint, RuntimeError> {
        let mut execution = GraphExecution::new(graph);
        execution.run(self, graph_dir, graph, host, Some(max_steps))?;
        Ok(execution.checkpoint(graph.name.clone()))
    }

    pub fn resume_graph_file(
        &self,
        graph_path: &Path,
        checkpoint: GraphCheckpoint,
    ) -> Result<GraphRun, RuntimeError> {
        let mut host = NoopHost;
        self.resume_graph_file_with_host(graph_path, checkpoint, &mut host)
    }

    pub fn resume_graph_file_with_host(
        &self,
        graph_path: &Path,
        checkpoint: GraphCheckpoint,
        host: &mut dyn Host,
    ) -> Result<GraphRun, RuntimeError> {
        let graph = load_graph(graph_path)?;
        let graph_dir = graph_path.parent().unwrap_or_else(|| Path::new("."));
        self.resume_graph_with_host(graph_dir, graph, checkpoint, host)
    }

    pub fn resume_graph_with_host(
        &self,
        graph_dir: &Path,
        graph: ExecutionGraph,
        checkpoint: GraphCheckpoint,
        host: &mut dyn Host,
    ) -> Result<GraphRun, RuntimeError> {
        let mut execution = GraphExecution::from_checkpoint(&graph, checkpoint)?;
        execution.run(self, graph_dir, &graph, host, None)?;
        let receipt = graph_receipt_with_effects_and_signature_policy(
            &graph.name,
            &mut execution.runs,
            execution.sync_points.clone(),
            &self.options.created_at,
            self.options.effects.clone(),
            self.options.signature_policy(),
        )?;
        execution.record_lifecycle(host, LifecycleEvent::graph_completed(&graph.name, &receipt))?;
        Ok(execution.finish(graph, receipt))
    }

    pub(crate) fn seal_completed_graph_checkpoint_with_host(
        &self,
        graph: ExecutionGraph,
        checkpoint: GraphCheckpoint,
        host: &mut dyn Host,
    ) -> Result<GraphRun, RuntimeError> {
        if checkpoint.state.status != GraphStatus::Succeeded {
            return Err(RuntimeError::GraphBlocked {
                step_id: "graph".to_owned(),
                reason: format!(
                    "cannot seal graph checkpoint with status {:?}",
                    checkpoint.state.status
                ),
            });
        }
        let mut execution = GraphExecution::from_checkpoint(&graph, checkpoint)?;
        let receipt = graph_receipt_with_effects_and_signature_policy(
            &graph.name,
            &mut execution.runs,
            execution.sync_points.clone(),
            &self.options.created_at,
            self.options.effects.clone(),
            self.options.signature_policy(),
        )?;
        execution.record_lifecycle(host, LifecycleEvent::graph_completed(&graph.name, &receipt))?;
        Ok(execution.finish(graph, receipt))
    }

    pub(crate) fn seal_blocked_graph_checkpoint_with_host(
        &self,
        graph: ExecutionGraph,
        checkpoint: GraphCheckpoint,
        step_id: &str,
        reason_code: impl Into<String>,
        summary: impl Into<String>,
        host: &mut dyn Host,
    ) -> Result<GraphRun, RuntimeError> {
        let mut execution = GraphExecution::from_checkpoint(&graph, checkpoint)?;
        let receipt = graph_receipt_with_disposition_and_policy(
            &graph.name,
            &mut execution.runs,
            execution.sync_points.clone(),
            &self.options.created_at,
            crate::receipts::GraphClosure {
                disposition: ClosureDisposition::Blocked,
                reason_code: reason_code.into(),
                summary: summary.into(),
            },
            self.options.effects.clone(),
            self.options.signature_policy(),
        )?;
        execution.record_lifecycle(
            host,
            LifecycleEvent::graph_blocked(&graph.name, step_id, &receipt),
        )?;
        Ok(execution.finish(graph, receipt))
    }

    pub fn resume_graph_until_steps_with_host(
        &self,
        graph_dir: &Path,
        graph: &ExecutionGraph,
        checkpoint: GraphCheckpoint,
        max_steps: usize,
        host: &mut dyn Host,
    ) -> Result<GraphCheckpoint, RuntimeError> {
        let mut execution = GraphExecution::from_checkpoint(graph, checkpoint)?;
        execution.run(self, graph_dir, graph, host, Some(max_steps))?;
        Ok(execution.checkpoint(graph.name.clone()))
    }
}

#[cfg(feature = "cli-tool")]
pub fn run_graph_file(graph_path: impl AsRef<Path>) -> Result<GraphRun, RuntimeError> {
    let runtime = Runtime::new(
        crate::adapters::cli_tool::CliToolAdapter,
        RuntimeOptions::from_process_env()?,
    );
    runtime.run_graph_file(graph_path.as_ref())
}

// Canonical graph-run payload builder + skill-output wrapper, shared by the
// nested-step path (`runner::steps`) and the skill-front path
// (`skill_front::graph`). `include_receipt_id` adds the `graph_receipt_id` field
// that only the nested-step path surfaces. Every field is an infallible
// clone/`format!`, so payload assembly is total.
pub(crate) fn graph_run_payload(run: &GraphRun, include_receipt_id: bool) -> JsonValue {
    let mut payload = JsonObject::new();
    payload.insert(
        "graph".to_owned(),
        JsonValue::String(run.graph.name.clone()),
    );
    payload.insert(
        "graph_status".to_owned(),
        JsonValue::String(format!("{:?}", run.state.status)),
    );
    if include_receipt_id {
        payload.insert(
            "graph_receipt_id".to_owned(),
            JsonValue::String(run.receipt.id.to_string()),
        );
    }
    let mut step_outputs = JsonObject::new();
    let mut step_summaries = Vec::new();
    for step in &run.steps {
        let mut summary = JsonObject::new();
        summary.insert(
            "step_id".to_owned(),
            JsonValue::String(step.step_id.clone()),
        );
        summary.insert("skill".to_owned(), JsonValue::String(step.skill.clone()));
        summary.insert(
            "status".to_owned(),
            JsonValue::String(if step.output.succeeded() {
                "success".to_owned()
            } else {
                "failure".to_owned()
            }),
        );
        summary.insert(
            "receipt_id".to_owned(),
            JsonValue::String(step.receipt.id.to_string()),
        );
        step_summaries.push(JsonValue::Object(summary));
        step_outputs.insert(
            step.step_id.clone(),
            JsonValue::Object(step.outputs.clone()),
        );
    }
    payload.insert("steps".to_owned(), JsonValue::Array(step_summaries));
    payload.insert("step_outputs".to_owned(), JsonValue::Object(step_outputs));
    JsonValue::Object(payload)
}

pub(crate) fn graph_run_skill_output(
    payload: &JsonValue,
    run: &GraphRun,
) -> Result<SkillOutput, RuntimeError> {
    let stdout = serde_json::to_string(payload)
        .map_err(|source| RuntimeError::json("serializing graph payload", source))?;
    Ok(SkillOutput {
        status: if run.state.status == GraphStatus::Succeeded {
            InvocationStatus::Success
        } else {
            InvocationStatus::Failure
        },
        stdout,
        stderr: String::new(),
        exit_code: Some(0),
        duration_ms: 0,
        metadata: JsonObject::new(),
    })
}

#[cfg(test)]
mod tests {
    use super::{
        RUNX_LOCAL_ENV_ALLOWLIST_ENV, RUNX_RECEIPT_SIGN_ED25519_SEED_BASE64_ENV,
        RUNX_RECEIPT_SIGN_ISSUER_TYPE_ENV, RUNX_RECEIPT_SIGN_KID_ENV, RuntimeOptions,
        safe_default_env_from,
    };
    use crate::sandbox::RUNX_SANDBOX_ALLOW_DECLARED_POLICY_ONLY_ENV;
    use std::collections::BTreeMap;

    #[test]
    fn safe_default_env_preserves_receipt_signing_inputs() {
        let env = safe_default_env_from(|key| match key {
            RUNX_RECEIPT_SIGN_KID_ENV => Some("kid_prod".to_owned()),
            RUNX_RECEIPT_SIGN_ED25519_SEED_BASE64_ENV => Some("seed".to_owned()),
            RUNX_RECEIPT_SIGN_ISSUER_TYPE_ENV => Some("hosted".to_owned()),
            _ => None,
        });

        assert_eq!(
            env.get(RUNX_RECEIPT_SIGN_KID_ENV),
            Some(&"kid_prod".to_owned())
        );
        assert_eq!(
            env.get(RUNX_RECEIPT_SIGN_ED25519_SEED_BASE64_ENV),
            Some(&"seed".to_owned())
        );
        assert_eq!(
            env.get(RUNX_RECEIPT_SIGN_ISSUER_TYPE_ENV),
            Some(&"hosted".to_owned())
        );
    }

    #[test]
    fn safe_default_env_preserves_sandbox_operator_override() {
        let env = safe_default_env_from(|key| match key {
            RUNX_SANDBOX_ALLOW_DECLARED_POLICY_ONLY_ENV => Some("local".to_owned()),
            _ => None,
        });

        assert_eq!(
            env.get(RUNX_SANDBOX_ALLOW_DECLARED_POLICY_ONLY_ENV),
            Some(&"local".to_owned())
        );
    }

    #[test]
    fn safe_default_env_preserves_local_operator_allowlisted_env() {
        let env = safe_default_env_from(|key| match key {
            RUNX_LOCAL_ENV_ALLOWLIST_ENV => Some(
                "NITROSEND_API_KEY,NITROSEND_ADMIN_API_KEY RUNX_RECEIPT_SIGN_SECRET bad-key"
                    .to_owned(),
            ),
            "NITROSEND_API_KEY" => Some("nskey_live_test".to_owned()),
            "NITROSEND_ADMIN_API_KEY" => Some("nskey_live_admin".to_owned()),
            "RUNX_RECEIPT_SIGN_SECRET" => Some("secret".to_owned()),
            _ => None,
        });

        assert_eq!(
            env.get("NITROSEND_API_KEY"),
            Some(&"nskey_live_test".to_owned())
        );
        assert_eq!(
            env.get("NITROSEND_ADMIN_API_KEY"),
            Some(&"nskey_live_admin".to_owned())
        );
        assert!(!env.contains_key("RUNX_RECEIPT_SIGN_SECRET"));
        assert!(!env.contains_key("bad-key"));
    }

    #[test]
    fn runtime_options_reject_incomplete_production_signing_env() -> Result<(), String> {
        let env = [(RUNX_RECEIPT_SIGN_KID_ENV.to_owned(), "kid_prod".to_owned())]
            .into_iter()
            .collect::<BTreeMap<_, _>>();

        let error = RuntimeOptions::from_env(env)
            .err()
            .ok_or_else(|| "incomplete signing env unexpectedly succeeded".to_owned())?;
        assert!(
            error
                .to_string()
                .contains("production receipt signing requires")
        );
        Ok(())
    }

    #[test]
    fn runtime_options_reject_missing_production_signing_env() -> Result<(), String> {
        let error = RuntimeOptions::from_env(BTreeMap::new())
            .err()
            .ok_or_else(|| "missing signing env unexpectedly succeeded".to_owned())?;
        assert!(
            error
                .to_string()
                .contains("governed runtime receipt signing")
        );
        Ok(())
    }

    #[test]
    fn runtime_options_reject_malformed_production_signing_seed() -> Result<(), String> {
        let env = [
            (RUNX_RECEIPT_SIGN_KID_ENV.to_owned(), "kid_prod".to_owned()),
            (
                RUNX_RECEIPT_SIGN_ED25519_SEED_BASE64_ENV.to_owned(),
                "not-base64".to_owned(),
            ),
            (
                RUNX_RECEIPT_SIGN_ISSUER_TYPE_ENV.to_owned(),
                "hosted".to_owned(),
            ),
        ]
        .into_iter()
        .collect::<BTreeMap<_, _>>();

        let error = RuntimeOptions::from_env(env)
            .err()
            .ok_or_else(|| "malformed signing env unexpectedly succeeded".to_owned())?;
        assert!(
            error
                .to_string()
                .contains("production receipt signer key material is malformed")
        );
        Ok(())
    }

    #[test]
    fn runtime_options_strip_receipt_signing_env_after_signer_construction() -> Result<(), String> {
        let env = [
            (RUNX_RECEIPT_SIGN_KID_ENV.to_owned(), "kid_prod".to_owned()),
            (
                RUNX_RECEIPT_SIGN_ED25519_SEED_BASE64_ENV.to_owned(),
                "QkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkI=".to_owned(),
            ),
            (
                RUNX_RECEIPT_SIGN_ISSUER_TYPE_ENV.to_owned(),
                "hosted".to_owned(),
            ),
            ("RUNX_CWD".to_owned(), "/workspace".to_owned()),
        ]
        .into_iter()
        .collect::<BTreeMap<_, _>>();

        let options = RuntimeOptions::from_env(env).map_err(|error| error.to_string())?;

        assert!(!options.env.contains_key(RUNX_RECEIPT_SIGN_KID_ENV));
        assert!(
            !options
                .env
                .contains_key(RUNX_RECEIPT_SIGN_ED25519_SEED_BASE64_ENV)
        );
        assert!(!options.env.contains_key(RUNX_RECEIPT_SIGN_ISSUER_TYPE_ENV));
        assert_eq!(options.env.get("RUNX_CWD"), Some(&"/workspace".to_owned()));
        Ok(())
    }
}