merry-runtime 0.1.3

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! Runtime-owned capability retention, independent of host filesystem mechanics.

use super::{
    PermissionedProcessRunnerFactory, ProcessActionIntent, ProcessRunner, ProcessRunnerContext,
    ProcessRunnerError, ProcessRunnerFuture,
};
use crate::{HostIntegration, PathAccess, PathAccessRule, PermissionRequest, RequestedCapability};
use merry_core::ApprovalScope;
use std::{
    fmt,
    path::PathBuf,
    sync::{Arc, RwLock},
};

/// Stable session-local identifier for one retained permission grant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SessionGrantId(u64);

impl SessionGrantId {
    /// Returns the raw numeric identifier.
    #[must_use]
    pub const fn as_u64(self) -> u64 {
        self.0
    }

    /// Reconstructs an identifier from its raw numeric value.
    #[must_use]
    pub const fn from_u64(value: u64) -> Self {
        Self(value)
    }
}

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

/// Capability represented by one active session-scoped permission grant.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionPermissionGrantKind {
    /// Read-only or read-write access to an external path.
    Path {
        /// Normalized host path covered by the grant.
        path: PathBuf,
        /// Access level (`ReadOnly` or `ReadWrite`).
        access: PathAccess,
    },
    /// Outbound network access for the remainder of the session.
    Network,
    /// Exact external domain authorized for web/browser tools in this session.
    NetworkDomain(String),
    /// Forwarded native host integration (SSH agent, GPG agent, or D-Bus).
    HostIntegration(HostIntegration),
}

/// One active, revocable session-scoped permission grant.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionPermissionGrant {
    id: SessionGrantId,
    kind: SessionPermissionGrantKind,
}

impl SessionPermissionGrant {
    /// Creates a grant entry from its stable ID and capability kind.
    #[must_use]
    pub const fn new(id: SessionGrantId, kind: SessionPermissionGrantKind) -> Self {
        Self { id, kind }
    }

    /// Returns the stable identifier used to revoke this grant.
    #[must_use]
    pub const fn id(&self) -> SessionGrantId {
        self.id
    }

    /// Returns the capability authorized by this grant.
    #[must_use]
    pub const fn kind(&self) -> &SessionPermissionGrantKind {
        &self.kind
    }
}

/// Backend facts that constrain retention of an approved path capability.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessPathGrantConstraint {
    /// No additional path constraint was found by the backend.
    Ordinary,
    /// The path belongs to metadata protected independently of ordinary grants.
    ProtectedMetadata,
}

/// A normalized approved path and the constraints found while materializing it.
#[derive(Debug, Clone)]
pub struct ProcessPathGrant {
    rule: PathAccessRule,
    constraint: ProcessPathGrantConstraint,
}

/// An adapter's prepared action runner and normalized capability evidence.
pub struct PreparedProcessPermission {
    runner: Arc<dyn ProcessRunner>,
    grants: Vec<ProcessPathGrant>,
}

impl PreparedProcessPermission {
    /// Packages an already validated runner without retaining its grants.
    #[must_use]
    pub fn new(runner: Arc<dyn ProcessRunner>, grants: Vec<ProcessPathGrant>) -> Self {
        Self { runner, grants }
    }
}

impl ProcessPathGrant {
    /// Constructs backend evidence; this does not grant or retain any authority.
    #[must_use]
    pub fn new(rule: PathAccessRule, constraint: ProcessPathGrantConstraint) -> Self {
        Self { rule, constraint }
    }
}

/// Immutable capabilities retained by one runtime session.
#[derive(Debug, Clone, Default)]
pub struct ProcessSessionPermissionSnapshot {
    path_rules: Vec<PathAccessRule>,
    host_integrations: Vec<HostIntegration>,
    network_allowed: bool,
    allowed_domains: Vec<String>,
    grants: Vec<SessionPermissionGrant>,
}

impl ProcessSessionPermissionSnapshot {
    /// Returns normalized, session-scoped path grants.
    #[must_use]
    pub fn path_rules(&self) -> &[PathAccessRule] {
        &self.path_rules
    }

    /// Returns explicitly approved native host integrations.
    #[must_use]
    pub fn host_integrations(&self) -> &[HostIntegration] {
        &self.host_integrations
    }

    /// Returns whether outbound network access was explicitly granted for this session.
    #[must_use]
    pub const fn network_allowed(&self) -> bool {
        self.network_allowed
    }

    /// Returns exact external hostnames granted for web/browser tools in this session.
    #[must_use]
    pub fn allowed_domains(&self) -> &[String] {
        &self.allowed_domains
    }

    /// Returns whether `host` matches an exact domain granted in this session.
    #[must_use]
    pub fn allows_domain(&self, host: &str) -> bool {
        let Some(normalized) = crate::normalize_network_domain(host) else {
            return false;
        };
        self.allowed_domains
            .iter()
            .any(|domain| domain == &normalized)
    }

    /// Returns all active session grants with their stable revocation identifiers.
    #[must_use]
    pub fn grants(&self) -> &[SessionPermissionGrant] {
        &self.grants
    }
}

#[derive(Debug, Clone)]
struct ProcessSessionPermissionState {
    next_id: u64,
    path_grants: Vec<(SessionGrantId, PathAccessRule)>,
    host_integrations: Vec<(SessionGrantId, HostIntegration)>,
    network_grant_id: Option<SessionGrantId>,
    domain_grants: Vec<(SessionGrantId, String)>,
}

impl Default for ProcessSessionPermissionState {
    fn default() -> Self {
        Self {
            next_id: 1,
            path_grants: Vec::new(),
            host_integrations: Vec::new(),
            network_grant_id: None,
            domain_grants: Vec::new(),
        }
    }
}

impl ProcessSessionPermissionState {
    fn allocate_id(&mut self) -> SessionGrantId {
        let id = SessionGrantId(self.next_id);
        self.next_id = self.next_id.saturating_add(1);
        id
    }

    fn from_snapshot(snapshot: ProcessSessionPermissionSnapshot) -> Self {
        let mut state = Self::default();
        if snapshot.network_allowed {
            state.network_grant_id = Some(state.allocate_id());
        }
        state.retain_domains(snapshot.allowed_domains);
        let mut integrations = snapshot.host_integrations;
        integrations.sort_unstable();
        integrations.dedup();
        for integration in integrations {
            let id = state.allocate_id();
            state.host_integrations.push((id, integration));
        }
        for rule in snapshot.path_rules {
            let id = state.allocate_id();
            state.path_grants.push((id, rule));
        }
        normalize_grant_entries(&mut state.path_grants);
        state
    }

    fn snapshot(&self) -> ProcessSessionPermissionSnapshot {
        let path_rules = self
            .path_grants
            .iter()
            .map(|(_, rule)| rule.clone())
            .collect();
        let host_integrations = self
            .host_integrations
            .iter()
            .map(|(_, integration)| *integration)
            .collect();
        let network_allowed = self.network_grant_id.is_some();
        let allowed_domains = self
            .domain_grants
            .iter()
            .map(|(_, domain)| domain.clone())
            .collect();
        let grants = self.ordered_grants();
        ProcessSessionPermissionSnapshot {
            path_rules,
            host_integrations,
            network_allowed,
            allowed_domains,
            grants,
        }
    }

    fn ordered_grants(&self) -> Vec<SessionPermissionGrant> {
        let mut grants = Vec::with_capacity(
            usize::from(self.network_grant_id.is_some())
                + self.domain_grants.len()
                + self.host_integrations.len()
                + self.path_grants.len(),
        );
        if let Some(id) = self.network_grant_id {
            grants.push(SessionPermissionGrant::new(
                id,
                SessionPermissionGrantKind::Network,
            ));
        }
        for (id, domain) in &self.domain_grants {
            grants.push(SessionPermissionGrant::new(
                *id,
                SessionPermissionGrantKind::NetworkDomain(domain.clone()),
            ));
        }
        for &(id, integration) in &self.host_integrations {
            grants.push(SessionPermissionGrant::new(
                id,
                SessionPermissionGrantKind::HostIntegration(integration),
            ));
        }
        for (id, rule) in &self.path_grants {
            grants.push(SessionPermissionGrant::new(
                *id,
                SessionPermissionGrantKind::Path {
                    path: rule.path().to_path_buf(),
                    access: rule.access(),
                },
            ));
        }
        grants
    }

    fn retain_path_rules(&mut self, incoming: impl IntoIterator<Item = PathAccessRule>) {
        for rule in incoming {
            if self.path_grants.iter().any(|(_, existing)| {
                rule.path().starts_with(existing.path()) && existing.access().covers(rule.access())
            }) {
                continue;
            }
            let id = self.allocate_id();
            self.path_grants.push((id, rule));
        }
        normalize_grant_entries(&mut self.path_grants);
    }

    fn retain_host_integration(&mut self, integration: HostIntegration) {
        if self
            .host_integrations
            .iter()
            .any(|(_, existing)| *existing == integration)
        {
            return;
        }
        let id = self.allocate_id();
        self.host_integrations.push((id, integration));
        self.host_integrations
            .sort_unstable_by_key(|(_, item)| *item);
    }

    fn retain_network(&mut self) {
        if self.network_grant_id.is_none() {
            self.network_grant_id = Some(self.allocate_id());
        }
    }

    fn retain_domains(&mut self, incoming: impl IntoIterator<Item = String>) {
        for domain in incoming {
            let Some(normalized) = crate::normalize_network_domain(&domain) else {
                continue;
            };
            if self
                .domain_grants
                .iter()
                .any(|(_, existing)| existing == &normalized)
            {
                continue;
            }
            let id = self.allocate_id();
            self.domain_grants.push((id, normalized));
        }
        self.domain_grants
            .sort_by(|(_, left), (_, right)| left.cmp(right));
    }

    fn revoke(&mut self, id: SessionGrantId) -> bool {
        if self.network_grant_id == Some(id) {
            self.network_grant_id = None;
            return true;
        }
        if let Some(index) = self
            .domain_grants
            .iter()
            .position(|(entry_id, _)| *entry_id == id)
        {
            self.domain_grants.remove(index);
            return true;
        }
        if let Some(index) = self
            .host_integrations
            .iter()
            .position(|(entry_id, _)| *entry_id == id)
        {
            self.host_integrations.remove(index);
            return true;
        }
        if let Some(index) = self
            .path_grants
            .iter()
            .position(|(entry_id, _)| *entry_id == id)
        {
            self.path_grants.remove(index);
            return true;
        }
        false
    }

    fn clear(&mut self) {
        self.path_grants.clear();
        self.host_integrations.clear();
        self.network_grant_id = None;
        self.domain_grants.clear();
    }
}

/// Read-only access supplied to process adapters; it cannot record a grant.
#[derive(Debug, Clone)]
pub struct ProcessSessionPermissionView {
    state: Arc<RwLock<ProcessSessionPermissionState>>,
}

impl ProcessSessionPermissionView {
    /// Captures capabilities for a preparation, failing closed on poisoned state.
    pub fn snapshot(&self) -> Result<ProcessSessionPermissionSnapshot, ProcessRunnerError> {
        self.state
            .read()
            .map(|state| state.snapshot())
            .map_err(|_| {
                ProcessRunnerError::infrastructure(
                    "runtime session permission state lock was poisoned",
                )
            })
    }
}

/// Capability state owned by a single runtime session, never a global store.
///
/// Ordinary paths, host integrations, outbound network, and reversible local
/// git mutations are retained only when explicitly approved with
/// [`ApprovalScope::Session`]. Explicitly reviewed paths and protected
/// metadata remain strictly once-only.
#[derive(Debug, Clone, Default)]
pub struct ProcessSessionPermissions {
    state: Arc<RwLock<ProcessSessionPermissionState>>,
}

impl ProcessSessionPermissions {
    /// Creates an empty, independent session.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates an independent session seeded with an immutable capability snapshot.
    ///
    /// Subsequent grants retained in the returned session stay isolated from any
    /// parent or sibling sessions that produced the snapshot.
    #[must_use]
    pub fn from_snapshot(snapshot: ProcessSessionPermissionSnapshot) -> Self {
        Self {
            state: Arc::new(RwLock::new(ProcessSessionPermissionState::from_snapshot(
                snapshot,
            ))),
        }
    }

    /// Creates an independent session seeded from a read-only parent permission view.
    ///
    /// # Errors
    ///
    /// Fails closed if the parent permission lock was poisoned.
    pub fn from_inherited_view(
        view: &ProcessSessionPermissionView,
    ) -> Result<Self, ProcessRunnerError> {
        Ok(Self::from_snapshot(view.snapshot()?))
    }

    /// Supplies a read-only view to an ordinary or permissioned process backend.
    #[must_use]
    pub fn view(&self) -> ProcessSessionPermissionView {
        ProcessSessionPermissionView {
            state: Arc::clone(&self.state),
        }
    }

    /// Returns all active session grants with stable revocation identifiers.
    ///
    /// # Errors
    ///
    /// Fails closed if the session permission lock was poisoned.
    pub fn grants(&self) -> Result<Vec<SessionPermissionGrant>, ProcessRunnerError> {
        self.state
            .read()
            .map(|state| state.ordered_grants())
            .map_err(|_| {
                ProcessRunnerError::infrastructure(
                    "runtime session permission state lock was poisoned",
                )
            })
    }

    /// Revokes one active session grant by its stable [`SessionGrantId`].
    ///
    /// Returns `Ok(true)` when the grant existed and was removed, or `Ok(false)`
    /// when no active grant matched `id`.
    ///
    /// # Errors
    ///
    /// Fails closed if the session permission lock was poisoned.
    pub fn revoke(&self, id: SessionGrantId) -> Result<bool, ProcessRunnerError> {
        let mut state = self.state.write().map_err(|_| {
            ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
        })?;
        Ok(state.revoke(id))
    }

    /// Wraps an adapter with runtime-owned approval retention. The adapter must
    /// consume this session's read-only view when constructing its runners.
    #[must_use]
    pub fn with_factory<Factory: PermissionedProcessRunnerFactory>(
        self,
        backend: Factory,
    ) -> SessionPermissionedProcessRunnerFactory<Factory> {
        SessionPermissionedProcessRunnerFactory {
            permissions: self,
            backend,
        }
    }

    /// Clears all retained session-scoped grants.
    ///
    /// Used when a live session replaces its process sandbox configuration so
    /// previously approved capabilities do not silently outlive a tightened
    /// baseline.
    ///
    /// # Errors
    ///
    /// Fails closed if the session permission lock was poisoned.
    pub fn clear(&self) -> Result<(), ProcessRunnerError> {
        let mut state = self.state.write().map_err(|_| {
            ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
        })?;
        state.clear();
        Ok(())
    }

    /// Selectively revokes only session grants invalidated by tightening
    /// individual capability policies (such as setting `network = "deny"` or
    /// disabling a specific host integration), preserving unrelated path and
    /// domain grants.
    ///
    /// # Errors
    ///
    /// Fails closed if the session permission lock was poisoned.
    pub fn revoke_denied_capabilities(
        &self,
        network_denied: bool,
        denied_host_integrations: &[HostIntegration],
    ) -> Result<(), ProcessRunnerError> {
        let mut state = self.state.write().map_err(|_| {
            ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
        })?;
        if network_denied {
            state.network_grant_id = None;
            state.domain_grants.clear();
        }
        if !denied_host_integrations.is_empty() {
            state
                .host_integrations
                .retain(|(_, integration)| !denied_host_integrations.contains(integration));
        }
        Ok(())
    }

    /// Retains eligible ordinary path grants for the remainder of this session.
    ///
    /// Protected metadata and deny rules are filtered out and never retained.
    pub fn retain_path_grants(
        &self,
        grants: Vec<ProcessPathGrant>,
    ) -> Result<(), ProcessRunnerError> {
        let mut state = self.state.write().map_err(|_| {
            ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
        })?;
        state.retain_path_rules(grants.into_iter().filter_map(|grant| {
            (grant.constraint == ProcessPathGrantConstraint::Ordinary
                && grant.rule.access() != PathAccess::Deny)
                .then_some(grant.rule)
        }));
        Ok(())
    }

    /// Retains exact external domain grants for web/browser tools for the
    /// remainder of this session.
    pub fn retain_domain_grants(
        &self,
        domains: impl IntoIterator<Item = String>,
    ) -> Result<(), ProcessRunnerError> {
        let mut state = self.state.write().map_err(|_| {
            ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
        })?;
        state.retain_domains(domains);
        Ok(())
    }

    fn retain(
        &self,
        request: &PermissionRequest,
        grants: Vec<ProcessPathGrant>,
    ) -> Result<(), ProcessRunnerError> {
        let mut state = self.state.write().map_err(|_| {
            ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
        })?;
        state.retain_path_rules(grants.into_iter().filter_map(|grant| {
            (grant.constraint == ProcessPathGrantConstraint::Ordinary
                && grant.rule.access() != PathAccess::Deny)
                .then_some(grant.rule)
        }));
        let mut domains = Vec::new();
        for capability in request.requested() {
            match capability {
                RequestedCapability::HostIntegration(integration) => {
                    state.retain_host_integration(*integration);
                }
                RequestedCapability::NetworkDomain(domain) => {
                    domains.push(domain.clone());
                }
                RequestedCapability::Network | RequestedCapability::Path(_) => {}
            }
        }
        if !domains.is_empty() {
            state.retain_domains(domains);
        }
        if request.requests_network() {
            state.retain_network();
        }
        Ok(())
    }
}

/// Runtime decorator that records approved capabilities, not OS mount policy.
#[derive(Debug, Clone)]
pub struct SessionPermissionedProcessRunnerFactory<Factory> {
    permissions: ProcessSessionPermissions,
    backend: Factory,
}

impl<Factory> SessionPermissionedProcessRunnerFactory<Factory> {
    /// Returns the adapter for backend-specific inspection, without write access
    /// to session permission state.
    #[must_use]
    pub fn backend(&self) -> &Factory {
        &self.backend
    }
}

impl<Factory: PermissionedProcessRunnerFactory> PermissionedProcessRunnerFactory
    for SessionPermissionedProcessRunnerFactory<Factory>
{
    fn validate_request(&self, request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
        self.backend.validate_request(request)
    }

    fn request_capabilities_are_satisfied(
        &self,
        request: &PermissionRequest,
    ) -> Result<bool, ProcessRunnerError> {
        self.backend.request_capabilities_are_satisfied(request)
    }

    fn targets_protected_metadata(&self, request: &PermissionRequest) -> bool {
        self.backend.targets_protected_metadata(request)
    }

    fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
        self.runner_for_decision(request, ApprovalScope::Once)
    }

    fn runner_for_decision(
        &self,
        request: &PermissionRequest,
        scope: ApprovalScope,
    ) -> Arc<dyn ProcessRunner> {
        let result = self
            .backend
            .prepare_approved_request(request)
            .and_then(|prepared| {
                if scope == ApprovalScope::Session {
                    self.permissions.retain(request, prepared.grants)?;
                }
                Ok(prepared.runner)
            });
        match result {
            Ok(runner) => runner,
            Err(error) => Arc::new(RejectedRunner(error)),
        }
    }
}

struct RejectedRunner(ProcessRunnerError);

impl ProcessRunner for RejectedRunner {
    fn run<'a>(
        &'a self,
        _intent: ProcessActionIntent,
        _context: ProcessRunnerContext,
    ) -> ProcessRunnerFuture<'a> {
        Box::pin(async { Err(self.0.clone()) })
    }
}

fn normalize_grant_entries(rules: &mut Vec<(SessionGrantId, PathAccessRule)>) {
    rules.sort_by(|(left_id, left), (right_id, right)| {
        left.path()
            .components()
            .count()
            .cmp(&right.path().components().count())
            .then_with(|| left.path().cmp(right.path()))
            .then_with(|| {
                (left.access() != PathAccess::ReadWrite)
                    .cmp(&(right.access() != PathAccess::ReadWrite))
            })
            .then_with(|| left_id.cmp(right_id))
    });
    let mut retained: Vec<(SessionGrantId, PathAccessRule)> = Vec::with_capacity(rules.len());
    for (id, rule) in rules.drain(..) {
        if !retained.iter().any(|(_, ancestor)| {
            rule.path().starts_with(ancestor.path()) && ancestor.access().covers(rule.access())
        }) {
            retained.push((id, rule));
        }
    }
    *rules = retained;
}

#[cfg(test)]
mod tests;