dekopon-shell 0.16.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
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
//! A sandboxed, bash-flavored scripting language whose commands dispatch to Dekopon capabilities.
//!
//! This crate is a pure interpreter library. It has no notion of Wasmtime, provider components, the
//! broker, HTTP, the filesystem, or the process environment. Everything a script can reach outside
//! its own value space goes through one seam, [`CapabilityInvoker`], which the embedding binary
//! implements.
//!
//! # 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; none is an operating-system process.
//!
//! # Safety model
//!
//! There is no operating-system sandbox here. This is a native tree-walking evaluator, so every
//! bound is hand-built 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.
//!
//! 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.
//!
//! One residual is stated rather than hidden: a `jq` filter that never produces an output cannot be
//! stopped cooperatively, so one that outlives its script keeps a thread busy. See
//! [`abandoned_filter_workers`].
//!
//! # 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 | jq -r .text", &Fixture);
//! assert_eq!(outcome.exit_code.get(), 0);
//! assert_eq!(outcome.output, "HI");
//! ```

#![forbid(unsafe_code)]

use std::sync::Arc;

use serde_json::Value;

mod ast;
mod builtins;
mod dispatch;
mod interp;
mod lexer;
pub mod limits;
mod parser;
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};

/// Model-facing metadata for one capability, used by `cap --describe`.
///
/// There is no input schema here: a capability is used through the provider command word that
/// proposes it, and that word's `--help` is where its arguments are documented.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CapabilityDescription {
    /// Canonical capability identifier.
    pub capability: String,
    /// Human-readable operation description.
    pub description: String,
}

/// The outcome of one capability invocation.
///
/// The variants mirror the exit-code mapping in [`ExitCode`]: a capability that ran and failed is
/// materially different from one that policy refused, which is different again from one that does
/// not exist. Collapsing them would hide an authorization refusal behind a generic failure.
#[derive(Clone, Debug, PartialEq)]
pub enum CapabilityCallResult {
    /// The capability ran and produced output.
    Succeeded(Value),
    /// Authorization refused the invocation. The capability was found but not permitted.
    Denied {
        /// Why the invocation was refused.
        reason: String,
    },
    /// The capability ran and failed.
    Failed {
        /// The stable failure classification, such as `provider-failure` or `provider-timeout`.
        error: String,
        /// The provider's own failure code and message, when the classification came from one.
        ///
        /// Rendered after the classification rather than in place of it. A class alone tells a
        /// model only that the call failed; the provider's sentence is what says whether it should
        /// change the request, wait, or stop — and for an upstream refusal it is the refusal
        /// itself, which nothing else in the run holds.
        detail: Option<ProviderFailureDetail>,
    },
    /// No such capability is reachable from this session.
    NotFound,
}

/// What a provider did with one of its command words.
///
/// A provider command word behaves like its own command-line program: it can turn an argv into a
/// capability proposal, print its own help or usage text, or refuse the argv outright. Those are
/// kept apart because the interpreter charges and reports them differently, and apart again from
/// a run that never reached the provider's answer, which is not a usage error however it failed.
#[derive(Clone, Debug, PartialEq)]
pub enum CommandRun {
    /// The provider proposed a capability, authorized and charged like every capability call.
    Proposed {
        /// The capability identifier the provider chose.
        capability: String,
        /// The input it assembled from the argv and stdin.
        input: Value,
        /// The public secret reference the provider's command asked this call to use, if any.
        ///
        /// Handed to [`CapabilityInvoker::invoke`] unchanged. It is intent, never authority: the
        /// broker authorizes it separately from the capability, and an invoker with no broker
        /// behind it refuses it with [`secret_use_unsupported`].
        secret_use: Option<SecretUseProposal>,
    },
    /// The provider produced text of its own — help, a version, a usage error — and chose the
    /// exit status; no capability call is charged.
    Rendered {
        /// Text for the script's stdout, exactly as the provider wrote it.
        stdout: String,
        /// Text for the script's diagnostic stream, exactly as the provider wrote it.
        stderr: String,
        /// The exit status the provider chose, `0` for help and `2` for a usage error by
        /// convention.
        status: u8,
    },
    /// The provider declined the argv; reported as a usage error at exit `2`.
    Failed {
        /// Why the provider declined.
        message: String,
    },
    /// The run itself failed before the provider could answer — the broker was unreachable, the
    /// host refused or trapped, the task did not complete — and is reported like a capability
    /// that ran and errored, at exit `1`. Telling the model to fix its argv would be wrong.
    Errored {
        /// What failed, naming its cause; never a path.
        message: String,
    },
    /// The run was refused before or during dispatch — the session was cancelled underneath it —
    /// and is reported like a refused capability, at exit `126`.
    Denied {
        /// Why the run was refused.
        reason: String,
    },
}

/// The boundary between this interpreter and the real world.
///
/// Implementations decide what a "capability" is: a direct Wasm component call, a broker proposal,
/// or a test fixture. This crate never learns which.
pub trait CapabilityInvoker {
    /// Returns every capability identifier currently available to invoke.
    fn granted(&self) -> Vec<String>;

    /// Reports whether one capability identifier is available, for dispatch-time lookup.
    ///
    /// The default scans [`CapabilityInvoker::granted`]; override it when a cheaper lookup exists.
    fn is_granted(&self, capability: &str) -> bool {
        self.granted().iter().any(|granted| granted == capability)
    }

    /// Returns the command words loaded providers contribute, for dispatch and the prompt.
    ///
    /// Filtered by the embedder to providers this session already holds a grant on, so a principal
    /// with no `gh.*` grant never sees the word and never reaches its rewrite.
    fn command_words(&self) -> Vec<String> {
        Vec::new()
    }

    /// Reports whether one word is a command word a loaded provider contributed.
    ///
    /// This is the membership test [`CapabilityInvoker::is_granted`] already provides for
    /// capabilities, and it is asked of *every* command word a script executes — a loop running
    /// thousands of commands asks it thousands of times. The default builds and scans
    /// [`CapabilityInvoker::command_words`]; override it when a cheaper lookup exists, because
    /// materializing that list per command is what this exists to avoid.
    fn has_command_word(&self, word: &str) -> bool {
        self.command_words()
            .iter()
            .any(|candidate| candidate == word)
    }

    /// Runs one provider command word against its argv and the text piped into it.
    ///
    /// `stdin` is what the script piped in, already rendered to text by the shell's display rule
    /// (strings verbatim, other values as compact JSON); `None` when nothing was piped. `None`
    /// coming back means no loaded provider owns the word; otherwise the [`CommandRun`] says
    /// whether the provider proposed a capability, rendered text of its own, or declined.
    ///
    /// Running the word grants nothing: a proposal is invoked through the same budget, denial, and
    /// telemetry path as every capability call, with its `secret_use` handed to
    /// [`CapabilityInvoker::invoke`] unchanged, and rendered text is charged only against the
    /// script's value and output ceilings.
    fn run_command(&self, word: &str, argv: &[String], stdin: Option<&str>) -> Option<CommandRun> {
        let _ = (word, argv, stdin);
        None
    }

    /// Returns model-facing metadata for one capability, when the implementation has any.
    fn describe(&self, capability: &str) -> Option<CapabilityDescription> {
        let _ = capability;
        None
    }

    /// Hears that one script has finished running against this invoker.
    ///
    /// The runtime that ran the script calls it once, after the interpreter returns and before the
    /// outcome reaches whoever asked for the script. It is the only point at which an invoker
    /// learns nothing more is coming from that script: the interpreter follows a
    /// [`CommandRun::Proposed`] answer with [`CapabilityInvoker::invoke`] only when the capability
    /// is granted, the budget has a call left, and the deadline has not passed. An invoker that
    /// reports each tool use as a started/finished pair finishes here whatever a proposal left
    /// open. The default does nothing, which suits an invoker that keeps nothing per script; a
    /// wrapper forwards it, or the invoker behind the wrapper never hears the script end.
    fn script_finished(&self) {}

    /// Invokes one capability synchronously, carrying the optional typed secret-use intent.
    ///
    /// One method rather than two. A defaulted `invoke_with_secret_use` used to sit beside a
    /// two-argument `invoke`, and every wrapper forwarded the argument it could see: three of them
    /// forwarded `invoke` and inherited the other's deny-by-default, so a DRN proposal a
    /// broker-backed console or gateway session made was refused inside the process that made it
    /// and never reached the broker. There is now one method to forward, and forgetting it is a
    /// compile error rather than a refusal nobody asked for.
    ///
    /// An invoker with no authorizer behind it answers a `Some` proposal with
    /// [`secret_use_unsupported`]. Dropping the field and running the call anyway is the one thing
    /// it must not do: the caller asked for a credential the callee cannot prove it may use.
    ///
    /// This is deliberately synchronous: this crate carries no async runtime dependency, and the
    /// calling binary's model tool loop is untouched. An implementation that is asynchronous
    /// underneath bridges here itself, as a synchronous embedding can do from its blocking task.
    fn invoke(
        &self,
        capability: &str,
        input: Value,
        secret_use: Option<SecretUseProposal>,
    ) -> CapabilityCallResult;
}

/// The refusal an invoker with no authorizer behind it owes a secret-use proposal.
///
/// A public DRN names a secret only the broker may resolve. An invoker that cannot reach one — a
/// direct Wasm registry, an empty local leg, a test fixture — refuses rather than dropping the
/// field and running the call as though it had never been asked for.
#[must_use]
pub fn secret_use_unsupported() -> CapabilityCallResult {
    CapabilityCallResult::Denied {
        reason: "secret references require a broker-backed capability".to_owned(),
    }
}

/// Forwards every method to the shared invoker behind the pointer.
///
/// This is what lets one broker leg be held by a console's shell pane and handed to that session's
/// dispatch at the same time. It replaced a hand-written forwarder that had to be kept in step with
/// the trait by hand and was not.
impl<T: CapabilityInvoker + ?Sized> CapabilityInvoker for Arc<T> {
    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 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 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)
    }
}

/// A script exit code.
///
/// The mapping is fixed and mirrors the conventions a model already knows from bash and coreutils.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct ExitCode(u8);

impl ExitCode {
    /// A capability call, builtin, or script completed successfully.
    pub const SUCCESS: Self = Self(0);
    /// A capability call ran and errored, or a builtin reported a runtime failure.
    pub const FAILURE: Self = Self(1);
    /// A shell parse error or an exhausted resource limit.
    pub const SYNTAX: Self = Self(2);
    /// The script exceeded its wall-clock deadline, matching coreutils `timeout(1)`.
    pub const TIMEOUT: Self = Self(124);
    /// A capability was found but authorization refused it, matching bash's "cannot execute".
    pub const DENIED: Self = Self(126);
    /// An unknown command word, or a proposed capability not granted to this session.
    pub const NOT_FOUND: Self = Self(127);

    /// Wraps a raw status, mirroring bash's `N mod 256` wraparound for `exit N`.
    #[must_use]
    pub fn from_script_exit(status: i64) -> Self {
        Self(u8::try_from(status.rem_euclid(256)).unwrap_or(0))
    }

    /// Returns the numeric exit code.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }

    /// Maps one capability call outcome onto its exit code.
    #[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)
    }
}

/// Everything one script execution produced.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ScriptOutcome {
    /// Combined stdout and stderr, already truncated to the configured ceilings.
    pub output: String,
    /// The script's exit code.
    pub exit_code: ExitCode,
    /// Whether output was dropped to stay under the ceilings.
    pub truncated: bool,
    /// Capability invocations this script drove.
    pub capability_calls: u32,
    /// Evaluation steps this script charged.
    pub steps: u64,
}

/// A configured script interpreter.
#[derive(Clone, Debug, Default)]
pub struct Interpreter {
    limits: Limits,
}

impl Interpreter {
    /// Creates an interpreter under the given bounds.
    #[must_use]
    pub fn new(limits: Limits) -> Self {
        Self { limits }
    }

    /// Returns the configured bounds.
    #[must_use]
    pub fn limits(&self) -> Limits {
        self.limits
    }

    /// Parses and evaluates one script.
    ///
    /// This never returns an error: a script failure is a script outcome. Parse errors and limit
    /// trips are reported through [`ScriptOutcome::output`] and [`ScriptOutcome::exit_code`].
    pub fn run(&self, script: &str, invoker: &dyn CapabilityInvoker) -> ScriptOutcome {
        interp::run(script, invoker, self.limits)
    }
}

/// Parses and evaluates one script under default bounds.
pub fn run(script: &str, invoker: &dyn CapabilityInvoker) -> ScriptOutcome {
    Interpreter::new(Limits::default()).run(script, invoker)
}

/// Returns how many abandoned `jq` filter workers are still running in this process.
///
/// jaq offers no interruption point, so a filter that produces no output at all — `jq 'def f: f;
/// f'` — cannot be stopped when its script's deadline passes. Its worker is abandoned and spins
/// until the process exits. A filter that produces output stops at its next one, so this counter
/// falls back to zero on its own; what stays is the non-terminating kind, and each one is a core
/// this process will never get back. `jq` refuses to start new filters once too many have
/// accumulated.
///
/// Only abandoned workers are counted, and only they are threads this process cannot reclaim. An
/// ordinary filter is served by the worker its thread already has, which is reused for the next
/// one and released when that thread exits.
///
/// A long-lived embedder should surface this as a gauge. A one-shot runner can ignore it: the
/// process is about to exit anyway.
#[must_use]
pub fn abandoned_filter_workers() -> usize {
    builtins::jq::abandoned_workers()
}

#[cfg(test)]
mod tests {
    use std::sync::{
        Arc, Mutex,
        atomic::{AtomicU32, Ordering},
    };

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

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

    /// An invoker that overrides every defaulted method with an answer the default cannot give.
    ///
    /// Each override answers for something absent from `granted` or `command_words`, so a caller
    /// that reached the trait default instead of this implementation answers `false`, `None`, or
    /// an empty list — which is exactly the shape of the defect this fixture exists to catch.
    #[derive(Default)]
    struct RecordingInvoker {
        secret_uses: Mutex<Vec<Option<SecretUseProposal>>>,
        /// How many script ends reached this invoker, which the do-nothing default cannot count.
        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"
        }

        fn command_words(&self) -> Vec<String> {
            vec!["gh".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);
        }
    }

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

    /// The pointer is what lets one broker leg be held by a shell pane and by that session's
    /// dispatch at once, so a proposal crossing it has to arrive whole.
    ///
    /// A hand-written forwarder here once dropped the secret-use argument it could not see, and a
    /// DRN proposal a broker-backed session made was refused inside the process that made it.
    /// The `Arc` blanket replaced that forwarder; nothing but this test now holds it to the same
    /// standard, its last other consumer having left with `dekopon-tui`.
    #[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"
        );
    }

    /// Six of this trait's methods have defaults, and a forwarder that omits one silently answers
    /// with the default instead of the invoker's own answer.
    ///
    /// Every override here answers for something the default would have to say `false`, `None`, or
    /// "nothing" about, so an omission fails rather than coinciding.
    #[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>;

        // The default does nothing, so only the invoker behind the pointer can have counted it.
        shared.script_finished();
        assert_eq!(inner.scripts_finished.load(Ordering::Relaxed), 1);

        assert_eq!(shared.granted(), vec!["cli-probe.upper".to_owned()]);
        // Not in `granted`: the default scan would refuse it.
        assert!(shared.is_granted("gh.pr-view"));
        // The default is an empty list and, through it, an empty membership test.
        assert_eq!(shared.command_words(), vec!["gh".to_owned()]);
        assert!(shared.has_command_word("gh-extra"));
        // Both default to `None`.
        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())
        );
    }

    /// One provider word, `httpprobe`, whose proposal names the secret use it was built with.
    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}))
        }
    }

    /// A provider command is the only way a script names a secret, so the funnel that turns its
    /// proposal into an invocation must hand the reference on rather than drop it.
    #[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);
    }
}