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
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
//! Internal memory activation data shapes.
//!
//! This module is deliberately crate-internal. Activated memory is projected
//! into session-owned context snapshots for compiler use, but it is not part of
//! the provider, event, ledger, or public runtime surface.

// Staged internal activation types are compiled before every call path is wired.
#![cfg_attr(not(test), allow(dead_code))]

use crate::text;
use std::{cmp::Ordering, fmt};
use thiserror::Error;

mod activation;
mod source;

pub(crate) use activation::MemoryActivator;
#[cfg(test)]
pub(crate) use source::MemoryActivationFuture;
pub(crate) use source::{
    MemoryActivationContext, MemoryActivationSource, MemoryStore, StoredMemoryActivationSource,
};

/// Validated internal memory identifier.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct MemoryId(String);

impl MemoryId {
    pub(crate) fn new(value: &str) -> Result<Self, MemoryError> {
        validate_non_blank("memory id", value)?;
        Ok(Self(value.to_owned()))
    }

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

impl fmt::Display for MemoryId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Scope where a memory item applies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum MemoryScope {
    /// Session-wide memory.
    Session,
    /// Task-scoped memory.
    Task,
    /// Step-scoped memory.
    Step,
}

/// Validated confidence in the inclusive 0.0..=1.0 range.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct MemoryConfidence(f32);

impl MemoryConfidence {
    pub(crate) fn new(value: f32) -> Result<Self, MemoryError> {
        if !(0.0..=1.0).contains(&value) {
            return Err(MemoryError::ConfidenceOutOfRange { value });
        }

        let canonical = if value == 0.0 { 0.0 } else { value };
        Ok(Self(canonical))
    }

    #[must_use]
    pub(crate) fn as_f32(self) -> f32 {
        self.0
    }
}

impl Eq for MemoryConfidence {}

impl Ord for MemoryConfidence {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.total_cmp(&other.0)
    }
}

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

/// Provenance note supporting an internal memory item's text.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct MemoryEvidence {
    label: String,
    source: String,
}

impl MemoryEvidence {
    pub(crate) fn new(
        label: impl Into<String>,
        source: impl Into<String>,
    ) -> Result<Self, MemoryError> {
        let label = label.into();
        validate_non_blank("memory evidence label", &label)?;
        let source = source.into();
        validate_non_blank("memory evidence source", &source)?;

        Ok(Self { label, source })
    }

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

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

/// Selection metadata used to rank and deduplicate a memory item.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct MemoryItemSelection {
    triggers: Vec<String>,
    confidence: MemoryConfidence,
    priority: i32,
    conflict_key: Option<String>,
}

impl MemoryItemSelection {
    pub(crate) fn new(
        triggers: Vec<String>,
        confidence: f32,
        priority: i32,
        conflict_key: Option<String>,
    ) -> Result<Self, MemoryError> {
        let mut triggers = triggers
            .into_iter()
            .map(|trigger| {
                validate_non_blank("memory trigger", &trigger)?;
                Ok(canonicalize_match_text(&trigger))
            })
            .collect::<Result<Vec<_>, MemoryError>>()?;
        triggers.sort();
        triggers.dedup();

        let conflict_key = conflict_key
            .map(|key| {
                validate_non_blank("memory conflict key", &key)?;
                Ok(canonicalize_match_text(&key))
            })
            .transpose()?;

        Ok(Self {
            triggers,
            confidence: MemoryConfidence::new(confidence)?,
            priority,
            conflict_key,
        })
    }

    fn into_parts(self) -> (Vec<String>, MemoryConfidence, i32, Option<String>) {
        (
            self.triggers,
            self.confidence,
            self.priority,
            self.conflict_key,
        )
    }
}

/// Stored memory item considered by the deterministic activator.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct MemoryItem {
    id: MemoryId,
    scope: MemoryScope,
    text: String,
    evidence: Vec<MemoryEvidence>,
    triggers: Vec<String>,
    confidence: MemoryConfidence,
    priority: i32,
    conflict_key: Option<String>,
}

impl MemoryItem {
    pub(crate) fn new(
        id: MemoryId,
        scope: MemoryScope,
        text: impl Into<String>,
        evidence: Vec<MemoryEvidence>,
        selection: MemoryItemSelection,
    ) -> Result<Self, MemoryError> {
        let text = text.into();
        validate_non_blank("memory text", &text)?;

        if evidence.is_empty() {
            return Err(MemoryError::EmptyMemoryEvidence { memory_id: id });
        }

        for item in &evidence {
            validate_non_blank("memory evidence label", item.label())?;
        }

        let (triggers, confidence, priority, conflict_key) = selection.into_parts();

        Ok(Self {
            id,
            scope,
            text,
            evidence,
            triggers,
            confidence,
            priority,
            conflict_key,
        })
    }

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

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

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

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

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

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

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

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

    #[cfg(test)]
    pub(crate) fn new_unchecked_for_tests(
        id: MemoryId,
        scope: MemoryScope,
        text: impl Into<String>,
        evidence: Vec<MemoryEvidence>,
        selection: MemoryItemSelection,
    ) -> Result<Self, MemoryError> {
        let text = text.into();
        validate_non_blank("memory text", &text)?;

        let (triggers, confidence, priority, conflict_key) = selection.into_parts();

        Ok(Self {
            id,
            scope,
            text,
            evidence,
            triggers,
            confidence,
            priority,
            conflict_key,
        })
    }
}

/// Provider-neutral source category for an activation seed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum MemoryActivationSourceKind {
    /// The activation was seeded from user-visible task input.
    UserQuery,
    /// The activation was seeded from runtime-owned instructions or state.
    RuntimeInstruction,
}

impl MemoryActivationSourceKind {
    #[must_use]
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::UserQuery => "user_query",
            Self::RuntimeInstruction => "runtime_instruction",
        }
    }
}

/// Seed metadata recorded separately from per-memory activation reasons.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct MemoryActivationProvenance {
    canonical_query: String,
    allowed_scopes: Vec<MemoryScope>,
    source_kind: MemoryActivationSourceKind,
    source_label: String,
}

impl MemoryActivationProvenance {
    pub(crate) fn new(
        query: impl Into<String>,
        mut allowed_scopes: Vec<MemoryScope>,
        source_kind: MemoryActivationSourceKind,
        source_label: impl Into<String>,
    ) -> Result<Self, MemoryError> {
        let query = query.into();
        validate_non_blank("memory activation query", &query)?;

        if allowed_scopes.is_empty() {
            return Err(MemoryError::EmptyAllowedScopes);
        }
        allowed_scopes.sort();
        allowed_scopes.dedup();

        let source_label = source_label.into();
        validate_non_blank("memory activation source label", &source_label)?;

        Ok(Self {
            canonical_query: canonicalize_match_text(&query),
            allowed_scopes,
            source_kind,
            source_label: canonicalize_label_text(&source_label),
        })
    }

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

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

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

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

    fn allows_scope(&self, scope: MemoryScope) -> bool {
        self.allowed_scopes.binary_search(&scope).is_ok()
    }
}

/// Query seed and scope policy used for activation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct MemoryActivationSeed {
    provenance: MemoryActivationProvenance,
}

impl MemoryActivationSeed {
    pub(crate) fn new(
        query: impl Into<String>,
        allowed_scopes: Vec<MemoryScope>,
        source_kind: MemoryActivationSourceKind,
        source_label: impl Into<String>,
    ) -> Result<Self, MemoryError> {
        Ok(Self {
            provenance: MemoryActivationProvenance::new(
                query,
                allowed_scopes,
                source_kind,
                source_label,
            )?,
        })
    }

    #[must_use]
    pub(crate) fn query(&self) -> &str {
        self.provenance.canonical_query()
    }

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

    fn allows_scope(&self, scope: MemoryScope) -> bool {
        self.provenance.allows_scope(scope)
    }
}

/// Deterministic activation score.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct MemoryActivationScore {
    trigger_matches: usize,
    priority: i32,
    confidence: MemoryConfidence,
}

impl MemoryActivationScore {
    pub(crate) fn new(
        trigger_matches: usize,
        priority: i32,
        confidence: f32,
    ) -> Result<Self, MemoryError> {
        Ok(Self {
            trigger_matches,
            priority,
            confidence: MemoryConfidence::new(confidence)?,
        })
    }

    #[must_use]
    pub(crate) fn trigger_matches(self) -> usize {
        self.trigger_matches
    }

    #[must_use]
    pub(crate) fn priority(self) -> i32 {
        self.priority
    }

    #[must_use]
    pub(crate) fn confidence(self) -> MemoryConfidence {
        self.confidence
    }
}

impl Ord for MemoryActivationScore {
    fn cmp(&self, other: &Self) -> Ordering {
        self.trigger_matches
            .cmp(&other.trigger_matches)
            .then_with(|| self.priority.cmp(&other.priority))
            .then_with(|| self.confidence.cmp(&other.confidence))
    }
}

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

/// Reasons an internal memory was activated.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum MemoryActivationReason {
    /// The memory item scope was allowed by the activation seed.
    ScopeAllowed,
    /// A trigger matched the activation seed query.
    TriggerMatched(String),
    /// The item was ranked with a deterministic score.
    Ranked { score: MemoryActivationScore },
    /// This item won a conflict group and suppressed lower-ranked items.
    ConflictWinner { suppressed: Vec<MemoryId> },
}

impl MemoryActivationReason {
    pub(crate) fn trigger_matched(trigger: impl Into<String>) -> Result<Self, MemoryError> {
        let trigger = trigger.into();
        validate_non_blank("memory activation trigger reason", &trigger)?;
        Ok(Self::TriggerMatched(canonicalize_match_text(&trigger)))
    }

    #[must_use]
    pub(crate) fn ranked(score: MemoryActivationScore) -> Self {
        Self::Ranked { score }
    }

    pub(crate) fn conflict_winner(mut suppressed: Vec<MemoryId>) -> Result<Self, MemoryError> {
        if suppressed.is_empty() {
            return Err(MemoryError::BlankActivationReason {
                reason: "conflict winner requires at least one suppressed memory id",
            });
        }

        suppressed.sort();
        suppressed.dedup();
        Ok(Self::ConflictWinner { suppressed })
    }
}

/// Selected memory plus score and activation reasons.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ActivatedMemory {
    item: MemoryItem,
    score: MemoryActivationScore,
    reasons: Vec<MemoryActivationReason>,
    provenance: MemoryActivationProvenance,
}

impl ActivatedMemory {
    pub(crate) fn new(
        item: MemoryItem,
        score: MemoryActivationScore,
        reasons: Vec<MemoryActivationReason>,
        provenance: MemoryActivationProvenance,
    ) -> Result<Self, MemoryError> {
        if reasons.is_empty() {
            return Err(MemoryError::EmptyActivationReasons {
                memory_id: item.id.clone(),
            });
        }

        for reason in &reasons {
            validate_reason(reason)?;
        }

        Ok(Self {
            item,
            score,
            reasons,
            provenance,
        })
    }

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

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

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

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

    fn add_reason(&mut self, reason: MemoryActivationReason) -> Result<(), MemoryError> {
        validate_reason(&reason)?;
        self.reasons.push(reason);
        Ok(())
    }
}

/// Errors raised while constructing or activating internal memory.
#[derive(Debug, Clone, PartialEq, Error)]
pub(crate) enum MemoryError {
    /// A required field was blank.
    #[error("{field} must not be blank")]
    BlankField {
        /// Name of the invalid field.
        field: &'static str,
    },

    /// Confidence was outside the valid range.
    #[error("memory confidence {value} is outside the inclusive 0.0..=1.0 range")]
    ConfidenceOutOfRange {
        /// Rejected confidence value.
        value: f32,
    },

    /// A candidate set or memory store contained the same memory id more than once.
    #[error("memory id {id} appears more than once in memory candidates")]
    DuplicateMemoryId {
        /// Duplicate memory identifier.
        id: MemoryId,
    },

    /// Activation seed did not allow any memory scopes.
    #[error("memory activation seed must allow at least one scope")]
    EmptyAllowedScopes,

    /// Memory text must have at least one exact evidence reference.
    #[error("memory item {memory_id} must have at least one exact evidence reference")]
    EmptyMemoryEvidence {
        /// Memory id that was created without evidence.
        memory_id: MemoryId,
    },

    /// Activated memory requires at least one reason.
    #[error("activated memory {memory_id} must have at least one activation reason")]
    EmptyActivationReasons {
        /// Memory id that was activated without reasons.
        memory_id: MemoryId,
    },

    /// A reason payload was structurally empty.
    #[error("invalid memory activation reason: {reason}")]
    BlankActivationReason {
        /// Actionable reason validation detail.
        reason: &'static str,
    },
}

fn validate_non_blank(field: &'static str, value: &str) -> Result<(), MemoryError> {
    if value.trim().is_empty() {
        return Err(MemoryError::BlankField { field });
    }

    Ok(())
}

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

fn canonicalize_label_text(value: &str) -> String {
    text::collapse_whitespace(value)
}

fn validate_reason(reason: &MemoryActivationReason) -> Result<(), MemoryError> {
    match reason {
        MemoryActivationReason::ScopeAllowed | MemoryActivationReason::Ranked { .. } => Ok(()),
        MemoryActivationReason::TriggerMatched(trigger) => {
            validate_non_blank("memory activation trigger reason", trigger)
        }
        MemoryActivationReason::ConflictWinner { suppressed } => {
            if suppressed.is_empty() {
                return Err(MemoryError::BlankActivationReason {
                    reason: "conflict winner requires at least one suppressed memory id",
                });
            }

            Ok(())
        }
    }
}

#[cfg(test)]
mod tests;