merry-runtime 0.1.0

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
use super::{CompactedCheckpoint, ContextEntry, ContextError, SessionContextSnapshot};
use crate::{
    memory::{
        ActivatedMemory, MemoryActivationProvenance, MemoryActivationReason, MemoryActivationScore,
        MemoryEvidence, MemoryId, MemoryScope,
    },
    text,
    token_estimate::estimate_text_tokens,
};
use std::{
    cmp::Ordering,
    collections::{BTreeMap, btree_map::Entry},
};

fn format_memory_scope(scope: MemoryScope) -> &'static str {
    match scope {
        MemoryScope::Session => "session",
        MemoryScope::Task => "task",
        MemoryScope::Step => "step",
    }
}

fn format_memory_scopes(scopes: &[MemoryScope]) -> String {
    scopes
        .iter()
        .map(|scope| format_memory_scope(*scope))
        .collect::<Vec<_>>()
        .join(",")
}

fn canonicalize_memory_reason_text(value: &str) -> String {
    text::collapse_whitespace(value).to_lowercase()
}

/// Compiles allowlisted structured runtime state into a deterministic context snapshot.
///
/// Public callers must compile from a session-owned snapshot, not from an
/// arbitrary entry list.
///
/// ```compile_fail
/// use merry_runtime::{ContextCompiler, ContextEntry};
///
/// let compiler = ContextCompiler::new();
/// let entries: Vec<ContextEntry> = Vec::new();
///
/// let _ = compiler.compile(entries);
/// ```
#[derive(Debug, Default)]
pub struct ContextCompiler;

impl ContextCompiler {
    /// Creates a context compiler with default deterministic ordering.
    #[must_use]
    pub fn new() -> Self {
        Self
    }

    /// Compiles structured context entries deterministically.
    ///
    /// Output ordering is deterministic for a given snapshot. The resulting
    /// [`CompiledContext`] is a runtime-owned intermediate, not a stable prompt
    /// format for provider adapters.
    pub fn compile(
        &self,
        snapshot: &SessionContextSnapshot,
    ) -> Result<CompiledContext, ContextError> {
        compile_entries(
            snapshot.entries(),
            snapshot.memories(),
            snapshot.compacted_checkpoint(),
        )
    }

    pub(crate) fn compile_without_compacted_checkpoint(
        &self,
        snapshot: &SessionContextSnapshot,
    ) -> Result<CompiledContext, ContextError> {
        compile_entries(snapshot.entries(), snapshot.memories(), None)
    }
}

fn compile_entries(
    entries: &[ContextEntry],
    memories: &[ActivatedMemory],
    compacted_checkpoint: Option<&CompactedCheckpoint>,
) -> Result<CompiledContext, ContextError> {
    let mut sections = Vec::with_capacity(entries.len());

    for entry in entries {
        match entry {
            ContextEntry::Summary(summary) => {
                sections.push(CompiledContextSection::Summary {
                    id: summary.id().to_owned(),
                    text: summary.text().to_owned(),
                });
            }
        }
    }

    sections.sort_by(|left, right| left.sort_key().cmp(&right.sort_key()));

    for memory in memories {
        if memory.item().evidence().is_empty() {
            return Err(ContextError::MemoryWithoutEvidence {
                memory_id: memory.item().id().as_str().to_owned(),
            });
        }
    }
    let mut memory_projection = canonical_memory_projection(memories);
    memory_projection.sort_by(|left, right| {
        right
            .score
            .cmp(&left.score)
            .then_with(|| left.id.cmp(&right.id))
    });

    Ok(CompiledContext {
        sections,
        memory_projection,
        checkpoint: ContextCheckpointSegment::new(compacted_checkpoint.cloned()),
    })
}

/// Reproducible compiled context snapshot.
///
/// This is a deterministic runtime intermediate for MVP request compilation.
/// It is not a stable serialized prompt contract.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompiledContext {
    sections: Vec<CompiledContextSection>,
    memory_projection: Vec<CompiledMemory>,
    checkpoint: ContextCheckpointSegment,
}

impl CompiledContext {
    /// Ordered public compiled context sections.
    ///
    /// This summary-only view excludes crate-internal projections such as
    /// activated memory.
    #[must_use]
    pub fn sections(&self) -> &[CompiledContextSection] {
        &self.sections
    }

    /// Stable text snapshot for tests and future adapter work.
    ///
    /// The string is deterministic for a compiled snapshot, but it is a helper
    /// representation rather than a stable provider prompt format.
    #[must_use]
    pub fn to_snapshot(&self) -> String {
        let mut lines = Vec::new();

        self.checkpoint.append_prompt_lines(&mut lines);
        self.append_body_prompt_lines(&mut lines);

        lines.join("\n")
    }

    pub(crate) fn checkpoint_snapshot(&self) -> String {
        let mut lines = Vec::new();
        self.checkpoint.append_prompt_lines(&mut lines);
        lines.join("\n")
    }

    pub(crate) fn body_snapshot(&self) -> String {
        let mut lines = Vec::new();
        self.append_body_prompt_lines(&mut lines);
        lines.join("\n")
    }

    fn append_body_prompt_lines(&self, lines: &mut Vec<String>) {
        for section in &self.sections {
            match section {
                CompiledContextSection::Summary { id, text } => {
                    lines.push(format!("summary:{id}"));
                    lines.push(format!("text:{text}"));
                }
            }
        }

        for memory in &self.memory_projection {
            lines.push(format!("memory:{}", memory.id));
            lines.push(format!(
                "memory-scope:{}",
                format_memory_scope(memory.scope)
            ));
            lines.push(format!("memory-text:{}", memory.text));
            lines.push(format!(
                "memory-activation-source-kind:{}",
                memory.provenance.source_kind().as_str()
            ));
            lines.push(format!(
                "memory-activation-source-label:{}",
                memory.provenance.source_label()
            ));
            lines.push(format!(
                "memory-activation-query:{}",
                memory.provenance.canonical_query()
            ));
            lines.push(format!(
                "memory-activation-allowed-scopes:{}",
                format_memory_scopes(memory.provenance.allowed_scopes())
            ));
            for item in &memory.evidence {
                lines.push(format!("memory-evidence:{}:{}", item.label, item.source));
            }
            for reason in &memory.reasons {
                match reason {
                    CompiledMemoryReason::ScopeAllowed => {
                        lines.push("memory-reason:scope_allowed".to_owned());
                    }
                    CompiledMemoryReason::TriggerMatched(trigger) => {
                        lines.push(format!("memory-reason:trigger:{trigger}"));
                    }
                    CompiledMemoryReason::Ranked { score } => {
                        lines.push(format!(
                            "memory-reason:rank:matches={};priority={};confidence={:.3}",
                            score.trigger_matches(),
                            score.priority(),
                            score.confidence().as_f32()
                        ));
                    }
                    CompiledMemoryReason::ConflictWinner { suppressed } => {
                        lines.push(format!(
                            "memory-reason:conflict_winner:suppressed={}",
                            suppressed
                                .iter()
                                .map(MemoryId::as_str)
                                .collect::<Vec<_>>()
                                .join(",")
                        ));
                    }
                }
            }
        }
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct ContextCheckpointSegment {
    checkpoint: Option<CompactedCheckpoint>,
}

const COMPACTED_CHECKPOINT_HEADER: &str = "compacted-checkpoint:";
const COMPACTED_CHECKPOINT_GUIDANCE: &str = "guidance:This summary is the record of the turns that were removed. Continue from it, and carry it into the next compaction. Re-read workspace files before editing code. A compaction segment named in the summary is the verbatim transcript.";
const COMPACTED_CHECKPOINT_TEXT_PREFIX: &str = "text:";

pub(crate) fn compacted_checkpoint_wrapper_token_ceiling() -> u64 {
    let wrapper = format!(
        "{COMPACTED_CHECKPOINT_HEADER}\n{COMPACTED_CHECKPOINT_GUIDANCE}\n{COMPACTED_CHECKPOINT_TEXT_PREFIX}"
    );
    estimate_text_tokens(&wrapper).saturating_add(1)
}

impl ContextCheckpointSegment {
    fn new(checkpoint: Option<CompactedCheckpoint>) -> Self {
        Self { checkpoint }
    }

    fn append_prompt_lines(&self, lines: &mut Vec<String>) {
        if let Some(checkpoint) = &self.checkpoint {
            lines.push(COMPACTED_CHECKPOINT_HEADER.to_owned());
            lines.push(COMPACTED_CHECKPOINT_GUIDANCE.to_owned());
            lines.push(format!(
                "{COMPACTED_CHECKPOINT_TEXT_PREFIX}{}",
                checkpoint.text()
            ));
        }
    }
}

/// A section in the compiled context snapshot.
///
/// The public compiled section view is summary-only in the MVP. Crate-internal
/// projections remain available to runtime-owned provider request compilation
/// and in [`CompiledContext::to_snapshot`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CompiledContextSection {
    /// Dynamic runtime context summary or note.
    Summary {
        /// Stable summary identifier.
        id: String,
        /// Summary text.
        text: String,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct CompiledMemory {
    id: MemoryId,
    scope: MemoryScope,
    text: String,
    evidence: Vec<CompiledMemoryEvidence>,
    score: MemoryActivationScore,
    provenance: MemoryActivationProvenance,
    reasons: Vec<CompiledMemoryReason>,
}

impl CompiledMemory {
    fn from_activation(memory: &ActivatedMemory) -> Self {
        let mut evidence = memory
            .item()
            .evidence()
            .iter()
            .map(CompiledMemoryEvidence::from_evidence)
            .collect::<Vec<_>>();
        evidence.sort();
        evidence.dedup();

        let mut reasons = memory
            .reasons()
            .iter()
            .map(CompiledMemoryReason::from_reason)
            .collect::<Vec<_>>();
        reasons.sort();
        reasons.dedup();

        Self {
            id: memory.item().id().clone(),
            scope: memory.item().scope(),
            text: memory.item().text().to_owned(),
            evidence,
            score: memory.score(),
            provenance: memory.provenance().clone(),
            reasons,
        }
    }
}

fn canonical_memory_projection(memories: &[ActivatedMemory]) -> Vec<CompiledMemory> {
    let mut by_id = BTreeMap::<MemoryId, CompiledMemory>::new();

    for memory in memories.iter().map(CompiledMemory::from_activation) {
        match by_id.entry(memory.id.clone()) {
            Entry::Occupied(mut entry) => {
                if memory.canonical_key() < entry.get().canonical_key() {
                    entry.insert(memory);
                }
            }
            Entry::Vacant(entry) => {
                entry.insert(memory);
            }
        }
    }

    by_id.into_values().collect()
}

impl CompiledMemory {
    fn canonical_key(&self) -> CompiledMemoryCanonicalKey<'_> {
        (
            std::cmp::Reverse(self.score),
            self.scope,
            self.text.as_str(),
            self.evidence.as_slice(),
            &self.provenance,
            self.reasons.as_slice(),
        )
    }
}

type CompiledMemoryCanonicalKey<'a> = (
    std::cmp::Reverse<MemoryActivationScore>,
    MemoryScope,
    &'a str,
    &'a [CompiledMemoryEvidence],
    &'a MemoryActivationProvenance,
    &'a [CompiledMemoryReason],
);

#[derive(Debug, Clone, PartialEq, Eq)]
struct CompiledMemoryEvidence {
    label: String,
    source: String,
}

impl CompiledMemoryEvidence {
    fn from_evidence(evidence: &MemoryEvidence) -> Self {
        Self {
            label: evidence.label().to_owned(),
            source: evidence.source().to_owned(),
        }
    }

    fn sort_key(&self) -> (&str, &str) {
        (self.source.as_str(), self.label.as_str())
    }
}

impl Ord for CompiledMemoryEvidence {
    fn cmp(&self, other: &Self) -> Ordering {
        self.sort_key().cmp(&other.sort_key())
    }
}

impl PartialOrd for CompiledMemoryEvidence {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum CompiledMemoryReason {
    ScopeAllowed,
    TriggerMatched(String),
    Ranked { score: MemoryActivationScore },
    ConflictWinner { suppressed: Vec<MemoryId> },
}

impl CompiledMemoryReason {
    fn from_reason(reason: &MemoryActivationReason) -> Self {
        match reason {
            MemoryActivationReason::ScopeAllowed => Self::ScopeAllowed,
            MemoryActivationReason::TriggerMatched(trigger) => {
                Self::TriggerMatched(canonicalize_memory_reason_text(trigger))
            }
            MemoryActivationReason::Ranked { score } => Self::Ranked { score: *score },
            MemoryActivationReason::ConflictWinner { suppressed } => {
                let mut suppressed = suppressed.clone();
                suppressed.sort();
                suppressed.dedup();
                Self::ConflictWinner { suppressed }
            }
        }
    }
}

impl CompiledContextSection {
    fn sort_key(&self) -> (&str, &str) {
        match self {
            Self::Summary { id, .. } => ("summary", id.as_str()),
        }
    }
}