dekopon-shell 0.28.0

Sandboxed bash-flavored script interpreter whose commands dispatch to Dekopon capabilities
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
//! A sandboxed, bash-flavored scripting language whose commands dispatch to Dekopon capabilities.
//!
//! Capability calls go through [`CapabilityInvoker`]. `jq` runs in a worker executable supplied by
//! the embedder, with an address-space limit on Linux; the worker is killed on deadline or cancel.
//!
//! # What this is for
//!
//! Exposing one model-facing tool schema per provider capability bloats a system prompt and forces
//! a model into many small round trips. A single scripting tool lets a model express a multi-step
//! plan — loops, conditionals, functions, JSON handling — in one tool call. The "commands" in that
//! script are builtins and the command words loaded providers contribute, each of which proposes a
//! capability invocation; `jq` alone uses a worker process.
//!
//! # Safety model
//!
//! The shell is a native tree-walking evaluator, with bounds enforced in [`limits`]:
//!
//! - a step budget covering statements, loop iterations, function calls, arithmetic nodes, and
//!   values pulled from a `jq` filter,
//! - a shell-function recursion depth cap,
//! - independent output byte and line ceilings with head-and-tail truncation,
//! - a wall-clock deadline, re-read on every step and around every capability call,
//! - a capability-invocation ceiling that is deliberately separate from the step budget,
//! - a cumulative ceiling on the value bytes a script may materialize, which is what bounds memory
//!   for a script that is cheap in steps and expensive in bytes. `jq` also has a worker address-space
//!   limit on Linux.
//!
//! One bound is *not* in [`limits`], because it applies before any budget exists: the parser caps
//! grammar nesting depth at a fixed ceiling. Parsing is recursive and runs on the native stack, so
//! without it a few kilobytes of nested `$( $( ... ) )` aborts the host process instead of
//! returning a [`ScriptOutcome`].
//!
//! The variable namespace is seeded only from the script's own assignments. This interpreter never
//! reads the host process environment — including through `jq`, whose standard library exports an
//! `env` filter that is deliberately not linked.
//!
//! A `jq` filter that does not yield is killed with its worker at the deadline or on cancel.
//!
//! # Observability
//!
//! Each script run opens one `shell.script` span carrying the totals for the whole run, and every
//! command word inside it opens a `shell.command` span — no events — carrying the command word
//! whoever wrote it, its resolution kind, its argv, the value piped into it, what it produced, its
//! exit code, and a stable outcome label. The argv, stdin, and output are each bounded by
//! `dekopon_core::bounded_attribute` beside a byte total. A trace therefore reads as the ordered
//! list of commands a script actually executed rather than as one opaque "a script ran" entry.
//!
//! A model-authored `while` loop can execute tens of thousands of command words inside one tool
//! call, and every one of them gets its span; the `shell.script` span's counters give the totals in
//! constant size beside them.
//!
//! This crate depends on `tracing` and nothing else for that. It knows no exporter, no collector,
//! and no telemetry protocol; the embedding binary's own subscriber decides where these go. The
//! dependency does not compromise the synchronous design constraint below — `tracing` imposes no
//! async runtime and is routinely used from fully synchronous code — but it does mean spans may
//! leave the process, so `interp::telemetry` documents exactly which fields a command carries.
//!
//! # Example
//!
//! ```
//! use dekopon_shell::{CapabilityCallResult, CapabilityInvoker, CommandRun, Interpreter, Limits};
//! use serde_json::{Value, json};
//!
//! /// One provider word, `probe`, whose `upper --text <s>` proposes `cli-probe.upper`.
//! struct Fixture;
//!
//! impl CapabilityInvoker for Fixture {
//!     fn granted(&self) -> Vec<String> {
//!         vec!["cli-probe.upper".to_owned()]
//!     }
//!
//!     fn command_words(&self) -> Vec<String> {
//!         vec!["probe".to_owned()]
//!     }
//!
//!     fn run_command(
//!         &self,
//!         word: &str,
//!         argv: &[String],
//!         _stdin: Option<&str>,
//!     ) -> Option<CommandRun> {
//!         if word != "probe" {
//!             return None;
//!         }
//!         Some(match argv {
//!             [command, flag, text] if command == "upper" && flag == "--text" => {
//!                 CommandRun::Proposed {
//!                     capability: "cli-probe.upper".to_owned(),
//!                     input: json!({ "text": text }),
//!                     secret_use: None,
//!                 }
//!             }
//!             _ => CommandRun::Failed {
//!                 message: "usage: probe upper --text <text>".to_owned(),
//!             },
//!         })
//!     }
//!
//!     fn invoke(
//!         &self,
//!         capability: &str,
//!         input: Value,
//!         secret_use: Option<dekopon_core::SecretUseProposal>,
//!     ) -> CapabilityCallResult {
//!         if secret_use.is_some() {
//!             return dekopon_shell::secret_use_unsupported();
//!         }
//!         assert_eq!(capability, "cli-probe.upper");
//!         let text = input["text"].as_str().unwrap_or_default().to_uppercase();
//!         CapabilityCallResult::Succeeded(json!({ "text": text }))
//!     }
//! }
//!
//! let outcome = Interpreter::new(Limits::default())
//!     .run("probe upper --text hi | cat", &Fixture);
//! assert_eq!(outcome.exit_code.get(), 0);
//! assert_eq!(outcome.output, r#"{"text":"HI"}"#);
//! ```

#![cfg_attr(test, allow(clippy::unwrap_used))]
#![forbid(unsafe_code)]
#![cfg_attr(
    test,
    allow(
        clippy::disallowed_methods,
        clippy::disallowed_types,
        reason = "tests spawn, join and drain freely; production sites carry their own expectation"
    )
)]
use std::{collections::BTreeMap, sync::Arc, time::Duration};

use serde_json::Value;

mod ast;
mod builtins;
mod dispatch;
mod interp;
mod jq_worker;
mod lexer;
pub use jq_worker::{run_jq_worker_if_requested, set_jq_worker_executable};
pub mod limits;
mod parser;
mod tree;
pub use tree::{CallBudget, TreeContext};
pub mod value;

pub use limits::{
    DEFAULT_MAX_CAPABILITY_CALLS, DEFAULT_MAX_OUTPUT_BYTES, DEFAULT_MAX_OUTPUT_LINES,
    DEFAULT_MAX_RECURSION_DEPTH, DEFAULT_MAX_STEPS, DEFAULT_MAX_VALUE_BYTES, DEFAULT_TIMEOUT,
    Limits,
};

use dekopon_core::{ProviderFailureDetail, SecretUseProposal};

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CapabilityDescription {
    pub capability: String,
    pub description: String,
}

#[derive(Clone, Debug, PartialEq)]
pub enum CapabilityCallResult {
    Succeeded(Value),
    Denied {
        reason: String,
    },
    Failed {
        error: String,
        /// The provider's own code and message are rendered after the classification, not instead
        /// of it, since a class alone can't tell a model whether to retry, wait, or stop.
        detail: Option<ProviderFailureDetail>,
    },
    NotFound,
}

#[derive(Clone, Debug, PartialEq)]
pub enum CommandRun {
    Proposed {
        capability: String,
        input: Value,
        /// The secret reference is intent, never authority: the broker authorizes it separately
        /// from the capability, and an invoker with no broker behind it must refuse it rather than
        /// treat it as approved.
        secret_use: Option<SecretUseProposal>,
    },
    Rendered {
        stdout: String,
        stderr: String,
        status: u8,
    },
    Failed {
        message: String,
    },
    /// A run that failed before the provider could answer is reported like an errored capability,
    /// not a usage error, since telling the model to fix its argv would be wrong.
    Errored {
        /// This names the cause of failure and must never be a filesystem path.
        message: String,
    },
    Denied {
        reason: String,
    },
}

pub trait CapabilityInvoker {
    fn cancelled(&self) -> bool {
        false
    }

    fn granted(&self) -> Vec<String>;

    fn is_granted(&self, capability: &str) -> bool {
        self.granted().iter().any(|granted| granted == capability)
    }

    fn command_words(&self) -> Vec<String> {
        Vec::new()
    }

    fn command_word_help(&self) -> BTreeMap<String, String> {
        BTreeMap::new()
    }

    fn has_command_word(&self, word: &str) -> bool {
        self.command_words()
            .iter()
            .any(|candidate| candidate == word)
    }

    /// Running a command word grants nothing: any proposal it makes is invoked through the same
    /// budget, denial, and telemetry path as every other capability call.
    fn run_command(&self, word: &str, argv: &[String], stdin: Option<&str>) -> Option<CommandRun> {
        let _ = (word, argv, stdin);
        None
    }

    fn describe(&self, capability: &str) -> Option<CapabilityDescription> {
        let _ = capability;
        None
    }

    fn note(&self, text: &str, eta: Option<Duration>) {
        let _ = (text, eta);
    }

    fn script_finished(&self) {}

    fn invoke(
        &self,
        capability: &str,
        input: Value,
        secret_use: Option<SecretUseProposal>,
    ) -> CapabilityCallResult;
}

#[must_use]
pub fn secret_use_unsupported() -> CapabilityCallResult {
    CapabilityCallResult::Denied {
        reason: "secret references require a broker-backed capability".to_owned(),
    }
}

impl<T: CapabilityInvoker + ?Sized> CapabilityInvoker for Arc<T> {
    fn cancelled(&self) -> bool {
        self.as_ref().cancelled()
    }

    fn granted(&self) -> Vec<String> {
        self.as_ref().granted()
    }

    fn is_granted(&self, capability: &str) -> bool {
        self.as_ref().is_granted(capability)
    }

    fn command_words(&self) -> Vec<String> {
        self.as_ref().command_words()
    }

    fn command_word_help(&self) -> BTreeMap<String, String> {
        self.as_ref().command_word_help()
    }

    fn has_command_word(&self, word: &str) -> bool {
        self.as_ref().has_command_word(word)
    }

    fn run_command(&self, word: &str, argv: &[String], stdin: Option<&str>) -> Option<CommandRun> {
        self.as_ref().run_command(word, argv, stdin)
    }

    fn describe(&self, capability: &str) -> Option<CapabilityDescription> {
        self.as_ref().describe(capability)
    }

    fn note(&self, text: &str, eta: Option<Duration>) {
        self.as_ref().note(text, eta);
    }

    fn script_finished(&self) {
        self.as_ref().script_finished();
    }

    fn invoke(
        &self,
        capability: &str,
        input: Value,
        secret_use: Option<SecretUseProposal>,
    ) -> CapabilityCallResult {
        self.as_ref().invoke(capability, input, secret_use)
    }
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct ExitCode(u8);

impl ExitCode {
    pub const SUCCESS: Self = Self(0);
    pub const FAILURE: Self = Self(1);
    pub const SYNTAX: Self = Self(2);
    pub const TIMEOUT: Self = Self(124);
    pub const CANCELLED: Self = Self(130);
    pub const DENIED: Self = Self(126);
    pub const NOT_FOUND: Self = Self(127);

    #[must_use]
    pub fn from_script_exit(status: i64) -> Self {
        Self(u8::try_from(status.rem_euclid(256)).unwrap_or(0))
    }

    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }

    #[must_use]
    pub const fn from_capability_result(result: &CapabilityCallResult) -> Self {
        match result {
            CapabilityCallResult::Succeeded(_) => Self::SUCCESS,
            CapabilityCallResult::Failed { .. } => Self::FAILURE,
            CapabilityCallResult::Denied { .. } => Self::DENIED,
            CapabilityCallResult::NotFound => Self::NOT_FOUND,
        }
    }
}

impl From<ExitCode> for u8 {
    fn from(code: ExitCode) -> Self {
        code.0
    }
}

impl From<u8> for ExitCode {
    fn from(code: u8) -> Self {
        Self(code)
    }
}

impl std::fmt::Display for ExitCode {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "{}", self.0)
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ScriptOutcome {
    pub output: String,
    pub exit_code: ExitCode,
    pub truncated: bool,
    pub capability_calls: u32,
    pub steps: u64,
}

#[derive(Clone, Debug, Default)]
pub struct Interpreter {
    limits: Limits,
}

impl Interpreter {
    #[must_use]
    pub fn new(limits: Limits) -> Self {
        Self { limits }
    }

    #[must_use]
    pub fn limits(&self) -> Limits {
        self.limits
    }

    pub fn run(&self, script: &str, invoker: &dyn CapabilityInvoker) -> ScriptOutcome {
        self.run_with_tree(
            script,
            invoker,
            &TreeContext::new(
                self.limits.timeout,
                CallBudget::new(self.limits.max_capability_calls),
            ),
        )
    }

    pub fn run_with_tree(
        &self,
        script: &str,
        invoker: &dyn CapabilityInvoker,
        tree: &TreeContext,
    ) -> ScriptOutcome {
        interp::run_with_tree(script, None, invoker, self.limits, tree)
    }

    pub fn run_with_prev(
        &self,
        script: &str,
        prev: &str,
        invoker: &dyn CapabilityInvoker,
    ) -> ScriptOutcome {
        interp::run(script, Some(prev), invoker, self.limits)
    }
}

pub fn run(script: &str, invoker: &dyn CapabilityInvoker) -> ScriptOutcome {
    Interpreter::new(Limits::default()).run(script, invoker)
}

#[cfg(test)]
mod tests {
    use std::{
        collections::BTreeMap,
        sync::{
            Arc, Mutex,
            atomic::{AtomicBool, AtomicU32, Ordering},
        },
        time::{Duration, Instant},
    };

    use dekopon_core::{SecretDrn, SecretUseProposal};
    use serde_json::{Value, json};

    use super::{
        CallBudget, CapabilityCallResult, CapabilityDescription, CapabilityInvoker, CommandRun,
        ExitCode, Interpreter, Limits, TreeContext,
    };

    #[derive(Default)]
    struct RecordingInvoker {
        secret_uses: Mutex<Vec<Option<SecretUseProposal>>>,
        scripts_finished: AtomicU32,
    }

    impl CapabilityInvoker for RecordingInvoker {
        fn granted(&self) -> Vec<String> {
            vec!["cli-probe.upper".to_owned()]
        }

        fn is_granted(&self, capability: &str) -> bool {
            capability == "gh.pr-view" || capability == "gh-extra"
        }

        fn command_words(&self) -> Vec<String> {
            vec!["gh".to_owned()]
        }

        fn command_word_help(&self) -> BTreeMap<String, String> {
            BTreeMap::from([("gh".to_owned(), "gh: recorded help".to_owned())])
        }

        fn has_command_word(&self, word: &str) -> bool {
            word == "gh-extra"
        }

        fn run_command(
            &self,
            word: &str,
            argv: &[String],
            stdin: Option<&str>,
        ) -> Option<CommandRun> {
            Some(CommandRun::Proposed {
                capability: word.to_owned(),
                input: json!({ "argv": argv, "stdin": stdin }),
                secret_use: None,
            })
        }

        fn describe(&self, capability: &str) -> Option<CapabilityDescription> {
            Some(CapabilityDescription {
                capability: capability.to_owned(),
                description: "recorded".to_owned(),
            })
        }

        fn invoke(
            &self,
            _capability: &str,
            input: Value,
            secret_use: Option<SecretUseProposal>,
        ) -> CapabilityCallResult {
            self.secret_uses
                .lock()
                .expect("recorded secret uses")
                .push(secret_use);
            CapabilityCallResult::Succeeded(input)
        }

        fn script_finished(&self) {
            self.scripts_finished.fetch_add(1, Ordering::Relaxed);
        }
    }

    struct Cancellation(Arc<AtomicBool>);

    impl CapabilityInvoker for Cancellation {
        fn cancelled(&self) -> bool {
            self.0.load(Ordering::Relaxed)
        }
        fn granted(&self) -> Vec<String> {
            Vec::new()
        }
        fn invoke(&self, _: &str, _: Value, _: Option<SecretUseProposal>) -> CapabilityCallResult {
            CapabilityCallResult::NotFound
        }
    }

    #[test]
    fn a_cancelled_loop_stops_before_exhausting_steps() {
        let cancelled = Arc::new(AtomicBool::new(true));
        let limits = Limits {
            max_steps: 100_000,
            ..Limits::default()
        };
        let outcome =
            Interpreter::new(limits).run("while true; do :; done", &Cancellation(cancelled));
        assert_eq!(outcome.exit_code, ExitCode::CANCELLED);
        assert_eq!(
            super::interp::telemetry::fatal_outcome(&super::builtins::FatalError::Limit(
                super::limits::LimitExceeded::Cancelled
            )),
            "cancelled"
        );
        assert!(outcome.steps < 100);
    }

    #[test]
    fn a_sleep_wakes_for_cancellation_without_waiting_for_the_deadline() {
        let cancelled = Arc::new(AtomicBool::new(false));
        let flip = Arc::clone(&cancelled);
        let worker = std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(200));
            flip.store(true, Ordering::Relaxed);
        });
        let start = Instant::now();
        let outcome = Interpreter::new(Limits {
            timeout: Duration::from_secs(310),
            ..Limits::default()
        })
        .run("sleep 300", &Cancellation(cancelled));
        worker.join().expect("cancel worker");
        assert_eq!(outcome.exit_code, ExitCode::CANCELLED);
        assert!(start.elapsed() < Duration::from_millis(1500));
    }

    #[test]
    fn interpreters_in_one_tree_share_calls_and_deadline() {
        let limits = Limits {
            timeout: Duration::from_millis(80),
            max_capability_calls: 1,
            ..Limits::default()
        };
        let tree = TreeContext::new(limits.timeout, CallBudget::new(1));
        let invoker = RecordingInvoker::default();
        let interpreter = Interpreter::new(limits);
        assert_eq!(
            interpreter
                .run_with_tree("gh-extra one", &invoker, &tree)
                .capability_calls,
            1
        );
        let second_interpreter = Interpreter::new(limits);
        let second = second_interpreter.run_with_tree("gh-extra two", &invoker, &tree);
        assert_eq!(second.exit_code, ExitCode::SYNTAX);
        assert_eq!(tree.calls().used(), 1);
        std::thread::sleep(Duration::from_millis(100));
        assert_eq!(
            second_interpreter
                .run_with_tree("echo late", &invoker, &tree)
                .exit_code,
            ExitCode::TIMEOUT
        );
    }

    fn proposal() -> SecretUseProposal {
        SecretUseProposal::HttpBearer {
            secret: "drn:com.xrl:secret:prod:api/token"
                .parse::<SecretDrn>()
                .expect("canonical DRN"),
        }
    }

    #[test]
    fn an_arc_hands_a_secret_use_proposal_to_the_invoker_behind_it_unchanged() {
        let inner = Arc::new(RecordingInvoker::default());
        let shared: Arc<dyn CapabilityInvoker> = Arc::clone(&inner) as Arc<dyn CapabilityInvoker>;

        assert_eq!(
            shared.invoke("http-probe.fetch", json!({"url": "https://x"}), None),
            CapabilityCallResult::Succeeded(json!({"url": "https://x"}))
        );
        assert_eq!(
            shared.invoke("http-probe.fetch", json!({}), Some(proposal())),
            CapabilityCallResult::Succeeded(json!({}))
        );

        assert_eq!(
            *inner.secret_uses.lock().expect("recorded secret uses"),
            vec![None, Some(proposal())],
            "the pointer altered a proposal on its way to the invoker behind it"
        );
    }

    #[test]
    fn an_arc_forwards_the_defaulted_methods_instead_of_inheriting_their_defaults() {
        let inner = Arc::new(RecordingInvoker::default());
        let shared: Arc<dyn CapabilityInvoker> = Arc::clone(&inner) as Arc<dyn CapabilityInvoker>;

        shared.script_finished();
        assert_eq!(inner.scripts_finished.load(Ordering::Relaxed), 1);

        assert_eq!(shared.granted(), vec!["cli-probe.upper".to_owned()]);
        assert!(shared.is_granted("gh.pr-view"));
        assert_eq!(shared.command_words(), vec!["gh".to_owned()]);
        assert_eq!(
            shared.command_word_help(),
            BTreeMap::from([("gh".to_owned(), "gh: recorded help".to_owned())])
        );
        assert!(shared.has_command_word("gh-extra"));
        assert_eq!(
            shared.run_command("gh", &["pr".to_owned()], Some("piped")),
            Some(CommandRun::Proposed {
                capability: "gh".to_owned(),
                input: json!({"argv": ["pr"], "stdin": "piped"}),
                secret_use: None,
            })
        );
        assert_eq!(
            shared.describe("gh.pr-view").map(|it| it.description),
            Some("recorded".to_owned())
        );
    }

    struct ProposingInvoker {
        secret_use: Option<SecretUseProposal>,
        invocations: Mutex<Vec<(String, Value, Option<SecretUseProposal>)>>,
    }

    impl ProposingInvoker {
        fn proposing(secret_use: Option<SecretUseProposal>) -> Self {
            Self {
                secret_use,
                invocations: Mutex::new(Vec::new()),
            }
        }
    }

    impl CapabilityInvoker for ProposingInvoker {
        fn granted(&self) -> Vec<String> {
            vec!["http-probe.fetch".to_owned()]
        }

        fn command_words(&self) -> Vec<String> {
            vec!["httpprobe".to_owned()]
        }

        fn run_command(
            &self,
            word: &str,
            argv: &[String],
            stdin: Option<&str>,
        ) -> Option<CommandRun> {
            (word == "httpprobe").then(|| CommandRun::Proposed {
                capability: "http-probe.fetch".to_owned(),
                input: json!({ "argv": argv, "stdin": stdin }),
                secret_use: self.secret_use.clone(),
            })
        }

        fn invoke(
            &self,
            capability: &str,
            input: Value,
            secret_use: Option<SecretUseProposal>,
        ) -> CapabilityCallResult {
            self.invocations
                .lock()
                .expect("recorded invocations")
                .push((capability.to_owned(), input, secret_use));
            CapabilityCallResult::Succeeded(json!({"status": 200}))
        }
    }

    #[test]
    fn a_provider_proposal_hands_its_secret_use_to_invoke() {
        for secret_use in [Some(proposal()), None] {
            let invoker = ProposingInvoker::proposing(secret_use.clone());
            let outcome = Interpreter::new(Limits::default())
                .run("httpprobe fetch --url https://x", &invoker);
            assert_eq!(outcome.exit_code, ExitCode::SUCCESS, "{}", outcome.output);
            assert_eq!(outcome.output, r#"{"status":200}"#);
            assert_eq!(outcome.capability_calls, 1);
            assert_eq!(
                *invoker.invocations.lock().expect("recorded invocations"),
                vec![(
                    "http-probe.fetch".to_owned(),
                    json!({"argv": ["fetch", "--url", "https://x"], "stdin": null}),
                    secret_use,
                )],
                "the proposal's secret use did not reach invoke unchanged"
            );
        }
    }

    #[test]
    fn exit_codes_follow_the_documented_mapping() {
        assert_eq!(ExitCode::SUCCESS.get(), 0);
        assert_eq!(ExitCode::FAILURE.get(), 1);
        assert_eq!(ExitCode::SYNTAX.get(), 2);
        assert_eq!(ExitCode::TIMEOUT.get(), 124);
        assert_eq!(ExitCode::DENIED.get(), 126);
        assert_eq!(ExitCode::NOT_FOUND.get(), 127);
    }

    #[test]
    fn capability_results_map_onto_distinct_codes() {
        assert_eq!(
            ExitCode::from_capability_result(&CapabilityCallResult::Succeeded(
                serde_json::Value::Null
            )),
            ExitCode::SUCCESS
        );
        assert_eq!(
            ExitCode::from_capability_result(&CapabilityCallResult::Failed {
                error: "boom".to_owned(),
                detail: None
            }),
            ExitCode::FAILURE
        );
        assert_eq!(
            ExitCode::from_capability_result(&CapabilityCallResult::Denied {
                reason: "policy".to_owned()
            }),
            ExitCode::DENIED
        );
        assert_eq!(
            ExitCode::from_capability_result(&CapabilityCallResult::NotFound),
            ExitCode::NOT_FOUND
        );
    }

    #[test]
    fn script_exit_wraps_like_bash() {
        assert_eq!(ExitCode::from_script_exit(0).get(), 0);
        assert_eq!(ExitCode::from_script_exit(7).get(), 7);
        assert_eq!(ExitCode::from_script_exit(256).get(), 0);
        assert_eq!(ExitCode::from_script_exit(257).get(), 1);
        assert_eq!(ExitCode::from_script_exit(-1).get(), 255);
    }
}