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
//! Session-scoped user review guidance collected from interactive permission decisions.
//!
//! Kept independent from the rolling `RecordedPermissionDecision` ring buffer so
//! user-authored `Allow + note` and `Deny + note` guidance persists across busy
//! sessions (up to [`MAX_SESSION_REVIEW_GUIDANCE`] entries) and can be shared
//! live between a parent runtime and its managed subagents.

use super::{
    PermissionAdmissionDecision, PermissionAdmissionReviewSource, PermissionRequest,
    PermissionedAction, request_json,
};
use std::{
    collections::VecDeque,
    fmt,
    sync::{Arc, RwLock},
};

/// Stable session-local identifier for one user-authored review guidance note.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ReviewGuidanceId(u64);

impl ReviewGuidanceId {
    /// 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 ReviewGuidanceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "note-{}", self.0)
    }
}

/// Maximum number of rolling recorded permission decisions retained per session.
pub(crate) const MAX_RECORDED_PERMISSION_DECISIONS: usize = 16;

/// Maximum number of user-authored review guidance entries retained per session.
pub const MAX_SESSION_REVIEW_GUIDANCE: usize = 32;

/// Harness-recorded summary of one prior permission review outcome in this session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RecordedPermissionDecision {
    source: PermissionAdmissionReviewSource,
    approved: bool,
    tool_name: String,
    command: String,
    requested_json: String,
    user_note: Option<String>,
}

impl RecordedPermissionDecision {
    pub(crate) fn from_request_and_decision(
        request: &PermissionRequest,
        decision: &PermissionAdmissionDecision,
    ) -> Self {
        Self {
            source: decision.review().source(),
            approved: decision.is_approved(),
            tool_name: request.tool_name().as_str().to_owned(),
            command: action_command_summary(request.action()),
            requested_json: request_json::requested_capabilities_json(request.requested())
                .to_string(),
            user_note: decision
                .user_note()
                .map(str::trim)
                .filter(|note| !note.is_empty())
                .map(str::to_owned),
        }
    }

    pub(crate) fn render_json_line(&self) -> String {
        let mut entry = serde_json::json!({
            "source": self.source.as_str(),
            "decision": if self.approved { "approved" } else { "denied" },
            "tool": sanitize_recorded_field(&self.tool_name),
            "command": sanitize_recorded_field(&self.command),
            "requested": sanitize_recorded_field(&self.requested_json),
        });
        if let Some(note) = self.user_note.as_deref() {
            entry["user_note"] = serde_json::json!(sanitize_recorded_field(note));
        }
        entry.to_string()
    }
}

fn action_command_summary(action: &PermissionedAction) -> String {
    match action {
        PermissionedAction::Process(intent) => crate::shell_command_for_argv(intent.argv()),
        PermissionedAction::FileRead { path } => format!("read_file {path}"),
        PermissionedAction::FileWrite { paths } => format!("apply_patch {}", paths.join(", ")),
        PermissionedAction::NetworkUrl { tool, url, .. } => format!("{tool} {url}"),
    }
}

pub(crate) fn sanitize_recorded_field(text: &str) -> String {
    const MAX_LEN: usize = 320;
    let flattened: String = text
        .chars()
        .map(|ch| {
            if matches!(
                ch,
                '\r' | '\n' | '\u{0085}' | '\u{000B}' | '\u{000C}' | '\u{2028}' | '\u{2029}'
            ) {
                ' '
            } else {
                ch
            }
        })
        .collect();
    crate::compaction::bounded_excerpt(&flattened, MAX_LEN)
}

/// Whether a human review guidance note accompanied an approval or a denial.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReviewGuidanceDecision {
    /// Human approved the action and left session guidance for the AI reviewer.
    Allow,
    /// Human denied the action and left a binding boundary note.
    Deny,
}

impl ReviewGuidanceDecision {
    /// Returns the wire/prompt label for this guidance decision.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Allow => "allow",
            Self::Deny => "deny",
        }
    }
}

/// One user-authored review note recorded during this session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReviewGuidanceEntry {
    id: ReviewGuidanceId,
    decision: ReviewGuidanceDecision,
    user_note: String,
    tool_name: String,
    command: String,
    requested_json: String,
}

impl ReviewGuidanceEntry {
    /// Creates a review guidance entry from its validated fields.
    #[must_use]
    pub fn new(
        id: ReviewGuidanceId,
        decision: ReviewGuidanceDecision,
        user_note: impl Into<String>,
        tool_name: impl Into<String>,
        command: impl Into<String>,
        requested_json: impl Into<String>,
    ) -> Self {
        Self {
            id,
            decision,
            user_note: user_note.into().trim().to_owned(),
            tool_name: tool_name.into(),
            command: command.into(),
            requested_json: requested_json.into(),
        }
    }

    pub(crate) fn from_request_and_decision(
        id: ReviewGuidanceId,
        request: &PermissionRequest,
        decision: &PermissionAdmissionDecision,
        user_note: &str,
    ) -> Self {
        Self {
            id,
            decision: if decision.is_approved() {
                ReviewGuidanceDecision::Allow
            } else {
                ReviewGuidanceDecision::Deny
            },
            user_note: user_note.trim().to_owned(),
            tool_name: request.tool_name().as_str().to_owned(),
            command: action_command_summary(request.action()),
            requested_json: request_json::requested_capabilities_json(request.requested())
                .to_string(),
        }
    }

    /// Returns the stable session-local identifier for this guidance entry.
    #[must_use]
    pub const fn id(&self) -> ReviewGuidanceId {
        self.id
    }

    /// Returns whether the user allowed or denied the action when leaving this note.
    #[must_use]
    pub const fn decision(&self) -> ReviewGuidanceDecision {
        self.decision
    }

    /// Returns the human-authored guidance note.
    #[must_use]
    pub fn user_note(&self) -> &str {
        &self.user_note
    }

    /// Returns the tool name associated with the reviewed request.
    #[must_use]
    pub fn tool_name(&self) -> &str {
        &self.tool_name
    }

    /// Returns the command or file target summary for the reviewed request.
    #[must_use]
    pub fn command(&self) -> &str {
        &self.command
    }

    pub(crate) fn render_json_line(&self) -> String {
        serde_json::json!({
            "decision": self.decision.as_str(),
            "user_note": sanitize_recorded_field(&self.user_note),
            "tool": sanitize_recorded_field(&self.tool_name),
            "command": sanitize_recorded_field(&self.command),
            "requested": sanitize_recorded_field(&self.requested_json),
        })
        .to_string()
    }
}

#[derive(Debug)]
struct SessionReviewGuidanceState {
    next_id: u64,
    entries: VecDeque<ReviewGuidanceEntry>,
}

impl Default for SessionReviewGuidanceState {
    fn default() -> Self {
        Self {
            next_id: 1,
            entries: VecDeque::new(),
        }
    }
}

/// Thread-safe, cloneable handle to session-scoped human review guidance.
///
/// Cloning shares the underlying store so parent and child subagent runtimes
/// observe user guidance notes live across the session.
#[derive(Debug, Clone, Default)]
pub struct SessionReviewGuidance {
    state: Arc<RwLock<SessionReviewGuidanceState>>,
}

impl SessionReviewGuidance {
    /// Creates an empty shared session guidance store.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Records a human-supplied note from a settled permission decision.
    ///
    /// Model decisions, existing-grant reuses, and decisions without a non-blank
    /// `user_note` are ignored so only explicit human guidance occupies the
    /// bounded 32-entry table.
    pub(crate) fn record_decision(
        &self,
        request: &PermissionRequest,
        decision: &PermissionAdmissionDecision,
    ) {
        if decision.review().source() != PermissionAdmissionReviewSource::Host {
            return;
        }
        let Some(note) = decision
            .user_note()
            .map(str::trim)
            .filter(|n| !n.is_empty())
        else {
            return;
        };
        let mut state = self
            .state
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let id = ReviewGuidanceId(state.next_id);
        state.next_id = state.next_id.saturating_add(1);
        let entry = ReviewGuidanceEntry::from_request_and_decision(id, request, decision, note);
        if state.entries.len() >= MAX_SESSION_REVIEW_GUIDANCE {
            state.entries.pop_front();
        }
        state.entries.push_back(entry);
    }

    /// Revokes one recorded session review note by its stable [`ReviewGuidanceId`].
    ///
    /// Returns `true` if the entry was found and removed.
    pub fn revoke(&self, id: ReviewGuidanceId) -> bool {
        let mut state = self
            .state
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if let Some(index) = state.entries.iter().position(|entry| entry.id == id) {
            state.entries.remove(index);
            true
        } else {
            false
        }
    }

    /// Returns a point-in-time snapshot of retained user guidance entries.
    #[must_use]
    pub fn snapshot(&self) -> Vec<ReviewGuidanceEntry> {
        let state = self
            .state
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        state.entries.iter().cloned().collect()
    }

    /// Returns the number of retained guidance entries.
    #[must_use]
    pub fn len(&self) -> usize {
        let state = self
            .state
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        state.entries.len()
    }

    /// Returns whether no guidance entries have been recorded yet.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// Thread-safe, cloneable handle to live workspace-scoped human review notes
/// injected from the host's per-workspace persistence store.
///
/// Cloning shares the underlying vector so parent and child subagent runtimes
/// observe live additions and deletions without mutating the static cacheable
/// system prompt prefix.
#[derive(Debug, Clone, Default)]
pub struct WorkspaceReviewNotes {
    notes: Arc<RwLock<Vec<String>>>,
}

impl WorkspaceReviewNotes {
    /// Creates an empty shared workspace review notes handle.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a shared handle seeded with normalized workspace review notes.
    #[must_use]
    pub fn from_notes(notes: Vec<String>) -> Self {
        let normalized = normalize_workspace_review_notes(notes);
        Self {
            notes: Arc::new(RwLock::new(normalized)),
        }
    }

    /// Atomically replaces the active workspace review notes.
    pub fn replace(&self, notes: Vec<String>) {
        let normalized = normalize_workspace_review_notes(notes);
        *self
            .notes
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner()) = normalized;
    }

    /// Returns a point-in-time snapshot of active workspace review notes.
    #[must_use]
    pub fn snapshot(&self) -> Vec<String> {
        self.notes
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .clone()
    }
}

fn normalize_workspace_review_notes(notes: Vec<String>) -> Vec<String> {
    let mut out = Vec::new();
    for note in notes {
        let trimmed = note.trim();
        if trimmed.is_empty() {
            continue;
        }
        let owned = trimmed.to_owned();
        if !out.contains(&owned) {
            out.push(owned);
        }
    }
    out
}

pub(crate) fn render_workspace_review_note_json_line(note: &str) -> String {
    serde_json::json!({
        "scope": "workspace",
        "user_note": sanitize_recorded_field(note),
    })
    .to_string()
}