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
//! Runtime-owned permission request and approval review primitives.
//!
//! Permission requests wrap an exact planned action and its minimum capabilities.
//! A process may declare known capabilities before execution; a failed sandboxed
//! action may instead request capabilities discovered from its durable result.
//! Runtime owns admission and executes the exact process action after approval.

use crate::{ActionReviewTrigger, PathAccess, ProcessActionIntent};
use merry_core::{PendingToolCall, ToolName};

const REQUEST_PERMISSIONS_TOOL_NAME: &str = "request_permissions";
const MAX_PERMISSION_REASON_BYTES: usize = 2048;
/// Maximum UTF-8 byte length accepted for a human-supplied permission review note.
pub const MAX_PERMISSION_USER_NOTE_BYTES: usize = 2048;
const MAX_REVIEW_RULES_PER_CATEGORY: usize = 64;
const MAX_REVIEW_RULE_BYTES: usize = 512;
const DEFAULT_PERMISSION_STDOUT_LIMIT_BYTES: usize = 64 * 1024;
const DEFAULT_PERMISSION_STDERR_LIMIT_BYTES: usize = 64 * 1024;
mod channel;
mod decision;
pub(crate) mod environment;
mod guidance;
mod input;
mod payload;
mod request_json;
mod review;

pub use channel::{
    ChannelPermissionAdmissionSource, PermissionReviewRequest, PermissionReviewResponse,
    PermissionReviewResponseError,
};
pub use decision::{
    HostFallbackReason, PermissionActor, PermissionAdmissionContext, PermissionAdmissionDecision,
    PermissionAdmissionError, PermissionAdmissionFuture, PermissionAdmissionResult,
    PermissionAdmissionReview, PermissionAdmissionReviewSource, PermissionAdmissionSource,
    PermissionReviewRisk, PermissionUserAuthorization,
};
pub(crate) use environment::{PermissionReviewEnvironmentMetadata, probe_environment_metadata};
pub(crate) use guidance::{
    MAX_RECORDED_PERMISSION_DECISIONS, RecordedPermissionDecision,
    render_workspace_review_note_json_line,
};
pub use guidance::{
    MAX_SESSION_REVIEW_GUIDANCE, ReviewGuidanceDecision, ReviewGuidanceEntry, ReviewGuidanceId,
    SessionReviewGuidance, WorkspaceReviewNotes,
};
pub(crate) use input::{
    RequestedCapabilitiesInput, normalize_requested_capabilities, normalize_requested_path,
    permission_reason_schema_for_schemars, permission_request_from_call,
    permission_request_from_process_call, process_cwd_schema_for_schemars,
    requested_capabilities_schema_for_schemars, validate_optional_reason,
    validate_optional_user_note,
};
pub use input::{
    parse_permission_request, request_permissions_tool, validate_permission_user_note,
};
pub(crate) use payload::{
    permission_blocked_outcome, permission_denied_outcome, permission_invalid_arguments_outcome,
    permission_review_error_outcome,
};
pub(crate) use request_json::permission_request_fingerprint_json;
pub(crate) use review::ModelBackedPermissionAdmissionSource;

/// Point-in-time snapshot of all active session-scoped permission grants and
/// user-authored review guidance retained by a runtime session.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ActivePermissionGrants {
    grants: Vec<crate::SessionPermissionGrant>,
    review_guidance: Vec<ReviewGuidanceEntry>,
}

impl ActivePermissionGrants {
    /// Creates an active permission snapshot from session grants and review notes.
    #[must_use]
    pub fn new(
        grants: Vec<crate::SessionPermissionGrant>,
        review_guidance: Vec<ReviewGuidanceEntry>,
    ) -> Self {
        Self {
            grants,
            review_guidance,
        }
    }

    /// Returns all active revocable session capability grants.
    #[must_use]
    pub fn grants(&self) -> &[crate::SessionPermissionGrant] {
        &self.grants
    }

    /// Returns all active revocable session review guidance entries.
    #[must_use]
    pub fn review_guidance(&self) -> &[ReviewGuidanceEntry] {
        &self.review_guidance
    }

    /// Returns whether outbound network access is actively granted in this session.
    #[must_use]
    pub fn has_elevated_network(&self) -> bool {
        self.grants.iter().any(|grant| {
            matches!(
                grant.kind(),
                crate::SessionPermissionGrantKind::Network
                    | crate::SessionPermissionGrantKind::NetworkDomain(_)
            )
        })
    }

    /// Returns whether any host integration is actively granted in this session.
    #[must_use]
    pub fn has_elevated_host_integrations(&self) -> bool {
        self.grants.iter().any(|grant| {
            matches!(
                grant.kind(),
                crate::SessionPermissionGrantKind::HostIntegration(_)
            )
        })
    }

    /// Returns whether no session grants or session review notes are active.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.grants.is_empty() && self.review_guidance.is_empty()
    }
}

/// User-trusted custom rules and environment notes for AI permission review.
///
/// Sourced exclusively from trusted global configuration (never project-local
/// hidden files) so a repository cannot silently relax its own review rules.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PermissionReviewRules {
    environment: Vec<String>,
    allow: Vec<String>,
    soft_deny: Vec<String>,
    hard_deny: Vec<String>,
}

impl PermissionReviewRules {
    /// Constructs validated reviewer rules from global configuration lists.
    pub fn new(
        environment: Vec<String>,
        allow: Vec<String>,
        soft_deny: Vec<String>,
        hard_deny: Vec<String>,
    ) -> Result<Self, PermissionAdmissionError> {
        Ok(Self {
            environment: validate_review_rule_list("environment", environment)?,
            allow: validate_review_rule_list("allow", allow)?,
            soft_deny: validate_review_rule_list("soft_deny", soft_deny)?,
            hard_deny: validate_review_rule_list("hard_deny", hard_deny)?,
        })
    }

    /// Returns whether all four rule lists are empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.environment.is_empty()
            && self.allow.is_empty()
            && self.soft_deny.is_empty()
            && self.hard_deny.is_empty()
    }

    /// Returns trusted environment context entries.
    #[must_use]
    pub fn environment(&self) -> &[String] {
        &self.environment
    }

    /// Returns custom routine-allow carve-outs (never override hard-deny).
    #[must_use]
    pub fn allow(&self) -> &[String] {
        &self.allow
    }

    /// Returns custom soft-deny rules (clearable by explicit user authorization).
    #[must_use]
    pub fn soft_deny(&self) -> &[String] {
        &self.soft_deny
    }

    /// Returns custom hard-deny rules (critical; never auto-approved).
    #[must_use]
    pub fn hard_deny(&self) -> &[String] {
        &self.hard_deny
    }
}

fn validate_review_rule_list(
    category: &str,
    entries: Vec<String>,
) -> Result<Vec<String>, PermissionAdmissionError> {
    if entries.len() > MAX_REVIEW_RULES_PER_CATEGORY {
        return Err(PermissionAdmissionError::InvalidArguments {
            message: format!(
                "permissions.review.{category} may contain at most {MAX_REVIEW_RULES_PER_CATEGORY} entries"
            ),
        });
    }
    let mut normalized = Vec::with_capacity(entries.len());
    for entry in entries {
        let trimmed = entry.trim();
        if trimmed.is_empty() {
            return Err(PermissionAdmissionError::InvalidArguments {
                message: format!("permissions.review.{category} entries must not be blank"),
            });
        }
        if trimmed.len() > MAX_REVIEW_RULE_BYTES {
            return Err(PermissionAdmissionError::InvalidArguments {
                message: format!(
                    "permissions.review.{category} entry exceeds {MAX_REVIEW_RULE_BYTES} bytes"
                ),
            });
        }
        if trimmed.chars().any(char::is_control) {
            return Err(PermissionAdmissionError::InvalidArguments {
                message: format!(
                    "permissions.review.{category} entries must not contain control characters"
                ),
            });
        }
        normalized.push(trimmed.to_owned());
    }
    Ok(normalized)
}

/// How much runtime should trust the host/runtime owner for permission gates.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuntimeTrustLevel {
    /// Agentic/coding-agent runtime. Permissioned actions require review.
    Agent,
    /// Trusted SDK or host app runtime. The host may explicitly disable review.
    TrustedSdk,
}

/// Review mode for explicit permission requests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PermissionReviewMode {
    /// Runtime chooses the conservative default for the trust level.
    DefaultForTrust,
    /// Always route permission requests through a review source.
    Required,
    /// Allow an injected non-model admission source to decide without model review.
    HostDecisionOnly,
    /// Try AI review first, then wait on an injected host source when the AI
    /// review denies the request or cannot produce a decision.
    ModelThenHostFallback,
    /// Explicit SDK/host mode that admits configured registered tools without
    /// an AI or human approval round.
    FullyTrusted,
    /// Deny every permission request and action review without consulting a
    /// reviewer. Actions that need no approval still run.
    DenyAll,
}

impl PermissionReviewMode {
    /// Returns whether the caller explicitly disabled permission review.
    pub(crate) const fn is_fully_trusted(self) -> bool {
        matches!(self, Self::FullyTrusted)
    }

    /// Returns whether every permission request is rejected without review.
    pub(crate) const fn is_deny_all(self) -> bool {
        matches!(self, Self::DenyAll)
    }

    pub(crate) fn requires_model_review(self, trust_level: RuntimeTrustLevel) -> bool {
        match self {
            Self::DefaultForTrust => trust_level == RuntimeTrustLevel::Agent,
            Self::Required => true,
            Self::HostDecisionOnly => false,
            Self::ModelThenHostFallback => true,
            Self::FullyTrusted | Self::DenyAll => false,
        }
    }
}

/// Extra capability requested for a permissioned action.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RequestedCapability {
    /// Allow network access in the selected permissioned backend/profile.
    Network,
    /// Allow web/browser network access to one exact hostname.
    NetworkDomain(String),
    /// Allow filesystem access to one path in the selected backend/profile.
    Path(RequestedPathCapability),
    /// Allow one explicitly configured host integration in the selected
    /// permissioned backend/profile.
    HostIntegration(HostIntegration),
}

/// Host integration and supporting client files exposed to inner process actions.
/// Trusted global configuration is the capability ceiling and preauthorizes the
/// inner action sandbox; an integration the configuration did not enable can
/// still be requested for one permissioned action when the backend supports it
/// and its endpoint is visible.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum HostIntegration {
    /// The user's SSH authentication agent socket and read-only known-hosts files.
    SshAgent,
    /// The user's D-Bus session bus socket, commonly used by keyring clients.
    SessionBus,
    /// The native GnuPG agent and read-only public-key client integration, separate from SSH.
    GpgAgent,
}

impl HostIntegration {
    /// Returns the stable model/configuration name for this integration.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::SshAgent => "ssh-agent",
            Self::SessionBus => "dbus",
            Self::GpgAgent => "gpg-agent",
        }
    }
}

/// Requested filesystem capability for one path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestedPathCapability {
    path: String,
    access: PathAccess,
}

impl RequestedPathCapability {
    pub fn new(path: String, access: PathAccess) -> Result<Self, PermissionAdmissionError> {
        let path = normalize_requested_path(&path)?;
        Ok(Self { path, access })
    }

    #[must_use]
    pub fn path(&self) -> &str {
        &self.path
    }

    #[must_use]
    pub const fn access(&self) -> PathAccess {
        self.access
    }
}

/// Exact action covered by a permission request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PermissionedAction {
    /// Execute one validated process intent.
    Process(ProcessActionIntent),
    /// Read a file outside the current workspace access policy via an in-process tool.
    FileRead { path: String },
    /// Create, update, or delete file(s) outside the current workspace access policy via an in-process tool.
    FileWrite { paths: Vec<String> },
    /// Fetch or navigate to an external URL via an in-process web/browser tool.
    NetworkUrl {
        /// Tool name (`web_fetch`, `browser_tab`, etc.).
        tool: String,
        /// Target URL being accessed.
        url: String,
        /// Normalized exact destination hostname.
        host: String,
    },
}

impl PermissionedAction {
    #[must_use]
    pub fn kind(&self) -> &'static str {
        match self {
            Self::Process(_) => "process",
            Self::FileRead { .. } => "file_read",
            Self::FileWrite { .. } => "file_write",
            Self::NetworkUrl { .. } => "network_url",
        }
    }

    #[must_use]
    pub fn summary(&self) -> String {
        match self {
            Self::Process(intent) => intent.summary().to_owned(),
            Self::FileRead { path } => format!("read {path}"),
            Self::FileWrite { paths } => format!("write {}", paths.join(", ")),
            Self::NetworkUrl { tool, url, .. } => format!("{tool} {url}"),
        }
    }
}

/// Runtime-owned normalized permission request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PermissionRequest {
    tool_call_id: merry_core::ToolCallId,
    tool_name: ToolName,
    reason: Option<String>,
    requested: Vec<RequestedCapability>,
    action: PermissionedAction,
    review_context: Vec<PermissionReviewContextEntry>,
    review_only: bool,
    protected_target: bool,
    triggers: Vec<ActionReviewTrigger>,
}

impl PermissionRequest {
    pub(crate) fn new(
        call: &PendingToolCall,
        reason: Option<String>,
        requested: Vec<RequestedCapability>,
        action: PermissionedAction,
        review_context: Vec<PermissionReviewContextEntry>,
    ) -> Result<Self, PermissionAdmissionError> {
        if requested.is_empty() {
            return Err(PermissionAdmissionError::InvalidArguments {
                message: "request_permissions requires at least one requested capability"
                    .to_owned(),
            });
        }
        if let Some(reason) = reason.as_deref() {
            validate_optional_reason(reason)?;
        }

        let requested = normalize_requested_capabilities(requested)?;
        let triggers = match &action {
            PermissionedAction::Process(intent) => {
                crate::process::classify_process_action_review_triggers(intent)
            }
            PermissionedAction::FileRead { .. }
            | PermissionedAction::FileWrite { .. }
            | PermissionedAction::NetworkUrl { .. } => Vec::new(),
        };

        Ok(Self {
            tool_call_id: call.id().clone(),
            tool_name: call.name().clone(),
            reason,
            requested,
            action,
            review_context,
            review_only: false,
            protected_target: false,
            triggers,
        })
    }

    /// Builds a validated domain-scoped network permission request for a web or
    /// browser tool call.
    pub fn for_network_url(
        call: &PendingToolCall,
        tool: impl Into<String>,
        url: impl Into<String>,
        host: impl Into<String>,
        reason: Option<String>,
    ) -> Result<Self, PermissionAdmissionError> {
        let host = host.into();
        Self::new(
            call,
            reason,
            vec![RequestedCapability::NetworkDomain(host.clone())],
            PermissionedAction::NetworkUrl {
                tool: tool.into(),
                url: url.into(),
                host,
            },
            Vec::new(),
        )
    }

    /// Marks this request as targeting a built-in Merry protected path so
    /// approvals remain single-action (`Once`) and default to `Deny` in UIs.
    #[must_use]
    pub(crate) const fn with_protected_target(mut self) -> Self {
        self.protected_target = true;
        self
    }

    /// Creates a review-only request for a high-risk action with structured triggers.
    ///
    /// Unlike a capability request, this does not grant a filesystem or network
    /// capability. It reuses the same admission source to review the exact
    /// action before a separately configured runner executes it.
    pub(crate) fn for_action_review(
        call: &PendingToolCall,
        reason: impl Into<String>,
        action: PermissionedAction,
        review_context: Vec<PermissionReviewContextEntry>,
        triggers: Vec<ActionReviewTrigger>,
    ) -> Self {
        Self {
            tool_call_id: call.id().clone(),
            tool_name: call.name().clone(),
            reason: Some(reason.into()),
            requested: Vec::new(),
            action,
            review_context,
            review_only: true,
            protected_target: false,
            triggers,
        }
    }

    #[must_use]
    pub fn tool_call_id(&self) -> &merry_core::ToolCallId {
        &self.tool_call_id
    }

    #[must_use]
    pub fn tool_name(&self) -> &ToolName {
        &self.tool_name
    }

    #[must_use]
    pub fn reason(&self) -> Option<&str> {
        self.reason.as_deref()
    }

    #[must_use]
    pub fn requested(&self) -> &[RequestedCapability] {
        &self.requested
    }

    /// Returns structured action-review triggers associated with this request.
    #[must_use]
    pub fn triggers(&self) -> &[ActionReviewTrigger] {
        &self.triggers
    }

    /// Returns whether this request is eligible for [`ApprovalScope::Session`]
    /// retention under Merry's hard security rules.
    ///
    /// Destructive, remote-git, privilege, nested-shell, and unparseable
    /// triggers are strictly once-only. Requests that touch `.git` metadata
    /// paths are also once-only.
    #[must_use]
    pub fn allows_session_scope(&self) -> bool {
        if self.protected_target {
            return false;
        }
        if self
            .triggers
            .iter()
            .any(|trigger| !trigger.is_session_grantable())
        {
            return false;
        }
        if self.requested.iter().any(|capability| {
            matches!(
                capability,
                RequestedCapability::Path(path) if is_git_metadata_path_str(path.path())
            )
        }) {
            return false;
        }
        !self.requested.is_empty() || !self.triggers.is_empty()
    }

    /// Returns whether this request is eligible for explicit per-workspace
    /// persistence in `$XDG_STATE_HOME/merry/workspace-permissions.json`.
    ///
    /// Protected targets (`providers/`, `MERRY_API_KEY_FILE`, sandboxed
    /// `config.toml`/`state/`), `.git` metadata, local loopback hosts,
    /// action-review triggers, and host integrations are never eligible for
    /// per-workspace persistence.
    #[must_use]
    pub fn allows_workspace_persistence(&self) -> bool {
        if !self.allows_session_scope()
            || self.review_only
            || !self.triggers.is_empty()
            || self.requested.is_empty()
        {
            return false;
        }
        self.requested.iter().all(|capability| match capability {
            RequestedCapability::Network => true,
            RequestedCapability::NetworkDomain(domain) => {
                !crate::is_explicit_local_network_host(domain)
            }
            RequestedCapability::Path(path) => {
                path.access() != PathAccess::Deny && !is_git_metadata_path_str(path.path())
            }
            RequestedCapability::HostIntegration(_) => false,
        })
    }

    /// Returns whether this request is eligible for explicit per-workspace
    /// persistence given an optional AI fallback reason.
    ///
    /// In addition to [`Self::allows_workspace_persistence`], requests flagged
    /// as [`PermissionReviewRisk::Critical`] by the AI reviewer are never
    /// eligible for per-workspace persistence.
    #[must_use]
    pub fn allows_workspace_persistence_for_fallback(
        &self,
        fallback_reason: Option<&HostFallbackReason>,
    ) -> bool {
        let is_critical = matches!(
            fallback_reason,
            Some(HostFallbackReason::ModelDenied(review))
                if review.risk() == PermissionReviewRisk::Critical
        );
        !is_critical && self.allows_workspace_persistence()
    }

    /// Returns whether this request is classified as high-risk (and should
    /// default to `Deny` in interactive review UIs).
    #[must_use]
    pub fn is_high_risk(&self) -> bool {
        self.protected_target
            || self.triggers.iter().any(ActionReviewTrigger::is_high_risk)
            || self.requested.iter().any(|capability| {
                matches!(capability, RequestedCapability::HostIntegration(_))
                    || matches!(
                        capability,
                        RequestedCapability::Path(path) if is_git_metadata_path_str(path.path())
                    )
            })
    }

    /// Returns whether this request asks for network capability.
    #[must_use]
    pub fn requests_network(&self) -> bool {
        self.requested
            .iter()
            .any(|capability| matches!(capability, RequestedCapability::Network))
    }

    /// Returns whether this request targets a built-in Merry protected path
    /// (such as `providers/`, `MERRY_API_KEY_FILE`, or sandboxed `config.toml` / `state/`).
    #[must_use]
    pub const fn is_protected_target(&self) -> bool {
        self.protected_target
    }

    /// Returns whether this request reviews an action without granting a
    /// capability.
    #[must_use]
    pub fn is_action_review(&self) -> bool {
        self.review_only
    }

    #[must_use]
    pub fn action(&self) -> &PermissionedAction {
        &self.action
    }

    #[must_use]
    pub(crate) fn review_context(&self) -> &[PermissionReviewContextEntry] {
        &self.review_context
    }

    /// Returns the stable fingerprint for the exact action and capability set.
    #[must_use]
    pub fn fingerprint(&self) -> String {
        crate::process::stable_process_input_fingerprint(
            permission_request_fingerprint_json(self)
                .to_string()
                .as_bytes(),
        )
    }

    /// Returns the stable identifier used to correlate a host response.
    #[must_use]
    pub fn approval_id(&self) -> String {
        format!("{}:{}", self.tool_call_id(), self.fingerprint())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PermissionReviewContextEntry {
    role: &'static str,
    text: String,
}

impl PermissionReviewContextEntry {
    pub(crate) fn new(role: &'static str, text: String) -> Self {
        Self { role, text }
    }

    fn role(&self) -> &'static str {
        self.role
    }

    fn text(&self) -> &str {
        &self.text
    }
}

fn is_git_metadata_path_str(path: &str) -> bool {
    crate::is_git_metadata_path(std::path::Path::new(path))
}

#[cfg(test)]
mod tests;