Skip to main content

merry_runtime/permission/
guidance.rs

1//! Session-scoped user review guidance collected from interactive permission decisions.
2//!
3//! Kept independent from the rolling `RecordedPermissionDecision` ring buffer so
4//! user-authored `Allow + note` and `Deny + note` guidance persists across busy
5//! sessions (up to [`MAX_SESSION_REVIEW_GUIDANCE`] entries) and can be shared
6//! live between a parent runtime and its managed subagents.
7
8use super::{
9    PermissionAdmissionDecision, PermissionAdmissionReviewSource, PermissionRequest,
10    PermissionedAction, request_json,
11};
12use std::{
13    collections::VecDeque,
14    fmt,
15    sync::{Arc, RwLock},
16};
17
18/// Stable session-local identifier for one user-authored review guidance note.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
20pub struct ReviewGuidanceId(u64);
21
22impl ReviewGuidanceId {
23    /// Returns the raw numeric identifier.
24    #[must_use]
25    pub const fn as_u64(self) -> u64 {
26        self.0
27    }
28
29    /// Reconstructs an identifier from its raw numeric value.
30    #[must_use]
31    pub const fn from_u64(value: u64) -> Self {
32        Self(value)
33    }
34}
35
36impl fmt::Display for ReviewGuidanceId {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        write!(f, "note-{}", self.0)
39    }
40}
41
42/// Maximum number of rolling recorded permission decisions retained per session.
43pub(crate) const MAX_RECORDED_PERMISSION_DECISIONS: usize = 16;
44
45/// Maximum number of user-authored review guidance entries retained per session.
46pub const MAX_SESSION_REVIEW_GUIDANCE: usize = 32;
47
48/// Harness-recorded summary of one prior permission review outcome in this session.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub(crate) struct RecordedPermissionDecision {
51    source: PermissionAdmissionReviewSource,
52    approved: bool,
53    tool_name: String,
54    command: String,
55    requested_json: String,
56    user_note: Option<String>,
57}
58
59impl RecordedPermissionDecision {
60    pub(crate) fn from_request_and_decision(
61        request: &PermissionRequest,
62        decision: &PermissionAdmissionDecision,
63    ) -> Self {
64        Self {
65            source: decision.review().source(),
66            approved: decision.is_approved(),
67            tool_name: request.tool_name().as_str().to_owned(),
68            command: action_command_summary(request.action()),
69            requested_json: request_json::requested_capabilities_json(request.requested())
70                .to_string(),
71            user_note: decision
72                .user_note()
73                .map(str::trim)
74                .filter(|note| !note.is_empty())
75                .map(str::to_owned),
76        }
77    }
78
79    pub(crate) fn render_json_line(&self) -> String {
80        let mut entry = serde_json::json!({
81            "source": self.source.as_str(),
82            "decision": if self.approved { "approved" } else { "denied" },
83            "tool": sanitize_recorded_field(&self.tool_name),
84            "command": sanitize_recorded_field(&self.command),
85            "requested": sanitize_recorded_field(&self.requested_json),
86        });
87        if let Some(note) = self.user_note.as_deref() {
88            entry["user_note"] = serde_json::json!(sanitize_recorded_field(note));
89        }
90        entry.to_string()
91    }
92}
93
94fn action_command_summary(action: &PermissionedAction) -> String {
95    match action {
96        PermissionedAction::Process(intent) => crate::shell_command_for_argv(intent.argv()),
97        PermissionedAction::FileRead { path } => format!("read_file {path}"),
98        PermissionedAction::FileWrite { paths } => format!("apply_patch {}", paths.join(", ")),
99        PermissionedAction::NetworkUrl { tool, url, .. } => format!("{tool} {url}"),
100    }
101}
102
103pub(crate) fn sanitize_recorded_field(text: &str) -> String {
104    const MAX_LEN: usize = 320;
105    let flattened: String = text
106        .chars()
107        .map(|ch| {
108            if matches!(
109                ch,
110                '\r' | '\n' | '\u{0085}' | '\u{000B}' | '\u{000C}' | '\u{2028}' | '\u{2029}'
111            ) {
112                ' '
113            } else {
114                ch
115            }
116        })
117        .collect();
118    crate::compaction::bounded_excerpt(&flattened, MAX_LEN)
119}
120
121/// Whether a human review guidance note accompanied an approval or a denial.
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum ReviewGuidanceDecision {
124    /// Human approved the action and left session guidance for the AI reviewer.
125    Allow,
126    /// Human denied the action and left a binding boundary note.
127    Deny,
128}
129
130impl ReviewGuidanceDecision {
131    /// Returns the wire/prompt label for this guidance decision.
132    #[must_use]
133    pub const fn as_str(self) -> &'static str {
134        match self {
135            Self::Allow => "allow",
136            Self::Deny => "deny",
137        }
138    }
139}
140
141/// One user-authored review note recorded during this session.
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct ReviewGuidanceEntry {
144    id: ReviewGuidanceId,
145    decision: ReviewGuidanceDecision,
146    user_note: String,
147    tool_name: String,
148    command: String,
149    requested_json: String,
150}
151
152impl ReviewGuidanceEntry {
153    /// Creates a review guidance entry from its validated fields.
154    #[must_use]
155    pub fn new(
156        id: ReviewGuidanceId,
157        decision: ReviewGuidanceDecision,
158        user_note: impl Into<String>,
159        tool_name: impl Into<String>,
160        command: impl Into<String>,
161        requested_json: impl Into<String>,
162    ) -> Self {
163        Self {
164            id,
165            decision,
166            user_note: user_note.into().trim().to_owned(),
167            tool_name: tool_name.into(),
168            command: command.into(),
169            requested_json: requested_json.into(),
170        }
171    }
172
173    pub(crate) fn from_request_and_decision(
174        id: ReviewGuidanceId,
175        request: &PermissionRequest,
176        decision: &PermissionAdmissionDecision,
177        user_note: &str,
178    ) -> Self {
179        Self {
180            id,
181            decision: if decision.is_approved() {
182                ReviewGuidanceDecision::Allow
183            } else {
184                ReviewGuidanceDecision::Deny
185            },
186            user_note: user_note.trim().to_owned(),
187            tool_name: request.tool_name().as_str().to_owned(),
188            command: action_command_summary(request.action()),
189            requested_json: request_json::requested_capabilities_json(request.requested())
190                .to_string(),
191        }
192    }
193
194    /// Returns the stable session-local identifier for this guidance entry.
195    #[must_use]
196    pub const fn id(&self) -> ReviewGuidanceId {
197        self.id
198    }
199
200    /// Returns whether the user allowed or denied the action when leaving this note.
201    #[must_use]
202    pub const fn decision(&self) -> ReviewGuidanceDecision {
203        self.decision
204    }
205
206    /// Returns the human-authored guidance note.
207    #[must_use]
208    pub fn user_note(&self) -> &str {
209        &self.user_note
210    }
211
212    /// Returns the tool name associated with the reviewed request.
213    #[must_use]
214    pub fn tool_name(&self) -> &str {
215        &self.tool_name
216    }
217
218    /// Returns the command or file target summary for the reviewed request.
219    #[must_use]
220    pub fn command(&self) -> &str {
221        &self.command
222    }
223
224    pub(crate) fn render_json_line(&self) -> String {
225        serde_json::json!({
226            "decision": self.decision.as_str(),
227            "user_note": sanitize_recorded_field(&self.user_note),
228            "tool": sanitize_recorded_field(&self.tool_name),
229            "command": sanitize_recorded_field(&self.command),
230            "requested": sanitize_recorded_field(&self.requested_json),
231        })
232        .to_string()
233    }
234}
235
236#[derive(Debug)]
237struct SessionReviewGuidanceState {
238    next_id: u64,
239    entries: VecDeque<ReviewGuidanceEntry>,
240}
241
242impl Default for SessionReviewGuidanceState {
243    fn default() -> Self {
244        Self {
245            next_id: 1,
246            entries: VecDeque::new(),
247        }
248    }
249}
250
251/// Thread-safe, cloneable handle to session-scoped human review guidance.
252///
253/// Cloning shares the underlying store so parent and child subagent runtimes
254/// observe user guidance notes live across the session.
255#[derive(Debug, Clone, Default)]
256pub struct SessionReviewGuidance {
257    state: Arc<RwLock<SessionReviewGuidanceState>>,
258}
259
260impl SessionReviewGuidance {
261    /// Creates an empty shared session guidance store.
262    #[must_use]
263    pub fn new() -> Self {
264        Self::default()
265    }
266
267    /// Records a human-supplied note from a settled permission decision.
268    ///
269    /// Model decisions, existing-grant reuses, and decisions without a non-blank
270    /// `user_note` are ignored so only explicit human guidance occupies the
271    /// bounded 32-entry table.
272    pub(crate) fn record_decision(
273        &self,
274        request: &PermissionRequest,
275        decision: &PermissionAdmissionDecision,
276    ) {
277        if decision.review().source() != PermissionAdmissionReviewSource::Host {
278            return;
279        }
280        let Some(note) = decision
281            .user_note()
282            .map(str::trim)
283            .filter(|n| !n.is_empty())
284        else {
285            return;
286        };
287        let mut state = self
288            .state
289            .write()
290            .unwrap_or_else(|poisoned| poisoned.into_inner());
291        let id = ReviewGuidanceId(state.next_id);
292        state.next_id = state.next_id.saturating_add(1);
293        let entry = ReviewGuidanceEntry::from_request_and_decision(id, request, decision, note);
294        if state.entries.len() >= MAX_SESSION_REVIEW_GUIDANCE {
295            state.entries.pop_front();
296        }
297        state.entries.push_back(entry);
298    }
299
300    /// Revokes one recorded session review note by its stable [`ReviewGuidanceId`].
301    ///
302    /// Returns `true` if the entry was found and removed.
303    pub fn revoke(&self, id: ReviewGuidanceId) -> bool {
304        let mut state = self
305            .state
306            .write()
307            .unwrap_or_else(|poisoned| poisoned.into_inner());
308        if let Some(index) = state.entries.iter().position(|entry| entry.id == id) {
309            state.entries.remove(index);
310            true
311        } else {
312            false
313        }
314    }
315
316    /// Returns a point-in-time snapshot of retained user guidance entries.
317    #[must_use]
318    pub fn snapshot(&self) -> Vec<ReviewGuidanceEntry> {
319        let state = self
320            .state
321            .read()
322            .unwrap_or_else(|poisoned| poisoned.into_inner());
323        state.entries.iter().cloned().collect()
324    }
325
326    /// Returns the number of retained guidance entries.
327    #[must_use]
328    pub fn len(&self) -> usize {
329        let state = self
330            .state
331            .read()
332            .unwrap_or_else(|poisoned| poisoned.into_inner());
333        state.entries.len()
334    }
335
336    /// Returns whether no guidance entries have been recorded yet.
337    #[must_use]
338    pub fn is_empty(&self) -> bool {
339        self.len() == 0
340    }
341}
342
343/// Thread-safe, cloneable handle to live workspace-scoped human review notes
344/// injected from the host's per-workspace persistence store.
345///
346/// Cloning shares the underlying vector so parent and child subagent runtimes
347/// observe live additions and deletions without mutating the static cacheable
348/// system prompt prefix.
349#[derive(Debug, Clone, Default)]
350pub struct WorkspaceReviewNotes {
351    notes: Arc<RwLock<Vec<String>>>,
352}
353
354impl WorkspaceReviewNotes {
355    /// Creates an empty shared workspace review notes handle.
356    #[must_use]
357    pub fn new() -> Self {
358        Self::default()
359    }
360
361    /// Creates a shared handle seeded with normalized workspace review notes.
362    #[must_use]
363    pub fn from_notes(notes: Vec<String>) -> Self {
364        let normalized = normalize_workspace_review_notes(notes);
365        Self {
366            notes: Arc::new(RwLock::new(normalized)),
367        }
368    }
369
370    /// Atomically replaces the active workspace review notes.
371    pub fn replace(&self, notes: Vec<String>) {
372        let normalized = normalize_workspace_review_notes(notes);
373        *self
374            .notes
375            .write()
376            .unwrap_or_else(|poisoned| poisoned.into_inner()) = normalized;
377    }
378
379    /// Returns a point-in-time snapshot of active workspace review notes.
380    #[must_use]
381    pub fn snapshot(&self) -> Vec<String> {
382        self.notes
383            .read()
384            .unwrap_or_else(|poisoned| poisoned.into_inner())
385            .clone()
386    }
387}
388
389fn normalize_workspace_review_notes(notes: Vec<String>) -> Vec<String> {
390    let mut out = Vec::new();
391    for note in notes {
392        let trimmed = note.trim();
393        if trimmed.is_empty() {
394            continue;
395        }
396        let owned = trimmed.to_owned();
397        if !out.contains(&owned) {
398            out.push(owned);
399        }
400    }
401    out
402}
403
404pub(crate) fn render_workspace_review_note_json_line(note: &str) -> String {
405    serde_json::json!({
406        "scope": "workspace",
407        "user_note": sanitize_recorded_field(note),
408    })
409    .to_string()
410}