memd 1.9.0

Local memory CLI for AI agents with hybrid retrieval
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
//! Write-admission guardrails for public memory writes.
//!
//! This layer is intentionally conservative. It rejects only records
//! that are clearly low-value or generated-wrapper noise, while leaving
//! existing document/code ingestion compatible.

use crate::auto_priority::has_explicit_priority;
use crate::types::{ChunkType, IngestionMode};

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AdmissionDecision {
    Durable,
    Ephemeral,
    Reject,
}

impl AdmissionDecision {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Durable => "durable",
            Self::Ephemeral => "ephemeral",
            Self::Reject => "reject",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AdmissionOutcome {
    pub decision: AdmissionDecision,
    pub reason: String,
    /// In-band caller warning, e.g. a high-priority write admitted at
    /// downgraded priority.
    pub warning: Option<String>,
}

impl AdmissionOutcome {
    pub fn durable(reason: impl Into<String>) -> Self {
        Self {
            decision: AdmissionDecision::Durable,
            reason: reason.into(),
            warning: None,
        }
    }

    pub fn durable_with_warning(reason: impl Into<String>, warning: impl Into<String>) -> Self {
        Self {
            decision: AdmissionDecision::Durable,
            reason: reason.into(),
            warning: Some(warning.into()),
        }
    }

    pub fn ephemeral(reason: impl Into<String>) -> Self {
        Self {
            decision: AdmissionDecision::Ephemeral,
            reason: reason.into(),
            warning: None,
        }
    }

    pub fn reject(reason: impl Into<String>) -> Self {
        Self {
            decision: AdmissionDecision::Reject,
            reason: reason.into(),
            warning: None,
        }
    }
}

/// Upper bound on a single memory's text. A single chunk is meant to be a
/// bounded note/record; callers chunk large documents before writing. The cap
/// also backstops the `Agent action:` scan against pathological multi-megabyte
/// inputs at the add entry points (all of which route through this gate).
pub const MAX_MEMORY_TEXT_BYTES: usize = 1024 * 1024;

pub fn classify_write(
    chunk_type: ChunkType,
    text: &str,
    tags: &[String],
    mode: IngestionMode,
) -> AdmissionOutcome {
    if text.len() > MAX_MEMORY_TEXT_BYTES {
        return AdmissionOutcome::reject(format!(
            "memory text is {} bytes, over the {}-byte limit; chunk large documents before storing",
            text.len(),
            MAX_MEMORY_TEXT_BYTES
        ));
    }
    let trimmed = text.trim();
    if trimmed.is_empty() {
        return AdmissionOutcome::reject("empty memory text is not useful durable context");
    }

    if is_generated_digest_wrapper(trimmed, tags) {
        return AdmissionOutcome::reject(
            "generated digest wrapper records are not accepted through memory.add",
        );
    }

    if explicit_high_priority(tags) && !has_concrete_agent_action(trimmed) {
        // Admit-and-downgrade instead of reject: losing a legitimate
        // lesson outright costs more than storing it one notch lower.
        return AdmissionOutcome::durable_with_warning(
            "high-priority memory without concrete Agent action; priority downgraded to 7",
            format!(
                "priority:8+ or importance:8+ memories need a concrete 'Agent action:' \
                 sentence (>= 24 chars containing one of: {}); stored at priority 7",
                ACTION_VERBS.join(", ")
            ),
        );
    }

    let explicit_priority = has_explicit_priority(tags);
    if explicit_priority {
        return AdmissionOutcome::durable("explicit priority or importance tag");
    }

    let durable_reason = durable_signal_reason(chunk_type, trimmed, tags);

    if tags.iter().any(|tag| tag == "kind:progress")
        && is_low_signal_progress(trimmed)
        && durable_reason.is_none()
    {
        if mode == IngestionMode::Conversation {
            return AdmissionOutcome::ephemeral(
                "low-signal conversation progress is stored as short-lived hidden context",
            );
        }
        return AdmissionOutcome::reject(
                "low-signal progress chatter needs a concrete result, decision, failure, command, path, or explicit priority",
            );
    }

    if let Some(reason) = durable_reason {
        return AdmissionOutcome::durable(reason);
    }

    AdmissionOutcome::durable("accepted")
}

pub fn is_generated_digest_wrapper(text: &str, tags: &[String]) -> bool {
    let generated = tags.iter().any(|tag| tag == "task:status:generated");
    let digest_like = tags
        .iter()
        .any(|tag| tag.starts_with("task:role:") || tag.starts_with("task:digest:"));
    if generated && digest_like {
        return true;
    }

    let lowered = text.to_ascii_lowercase();
    lowered.starts_with("task digest status generated")
        || lowered.contains("artifact role: highlight_library")
        || lowered.contains("artifact role: project_brief")
        || lowered.contains("artifact role: failure_library")
        || lowered.contains("artifact role: decision_library")
        || lowered.contains("artifact role: evidence_library")
}

fn is_low_signal_progress(text: &str) -> bool {
    let lowered = text.to_ascii_lowercase();
    let compact_words = lowered.split_whitespace().count();
    lowered.starts_with("todo")
        || lowered.starts_with("starting")
        || lowered.starts_with("about to ")
        || lowered.starts_with("working on ")
        || lowered.starts_with("checking ")
        || lowered.starts_with("investigating ")
        || lowered.starts_with("looking into ")
        || (compact_words <= 8
            && !lowered.contains('/')
            && !lowered.contains("http")
            && !lowered.contains("validated")
            && !lowered.contains("root cause"))
}

fn explicit_high_priority(tags: &[String]) -> bool {
    tags.iter().any(|tag| {
        tag.strip_prefix("priority:")
            .or_else(|| tag.strip_prefix("importance:"))
            .and_then(|value| value.parse::<f32>().ok())
            .map(|value| value.is_finite() && value >= 8.0)
            .unwrap_or(false)
    })
}

/// Rewrite `priority:`/`importance:` tags valued 8+ down to 7. Applied
/// when a high-priority write lacks a concrete `Agent action:` line.
pub fn downgrade_high_priority_tags(tags: &mut [String]) {
    for tag in tags.iter_mut() {
        let Some(prefix) = ["priority:", "importance:"]
            .iter()
            .find(|p| tag.starts_with(*p))
        else {
            continue;
        };
        if tag[prefix.len()..]
            .parse::<f32>()
            .map(|v| v.is_finite() && v >= 8.0)
            .unwrap_or(false)
        {
            *tag = format!("{prefix}7");
        }
    }
}

fn has_concrete_agent_action(text: &str) -> bool {
    concrete_agent_action_candidates(text, "agent action:").any(is_concrete_agent_action)
}

fn concrete_agent_action_candidates<'a>(
    text: &'a str,
    marker: &'static str,
) -> impl Iterator<Item = &'a str> {
    let lowered = text.to_ascii_lowercase();
    let mut marker_starts = Vec::new();
    let mut search_start = 0;
    while let Some(relative_start) = lowered[search_start..].find(marker) {
        let marker_start = search_start + relative_start;
        marker_starts.push(marker_start);
        search_start = marker_start + marker.len();
    }

    // O(n) overall: the next marker position is the next element of
    // `marker_starts`, not a fresh forward scan (the previous code re-scanned
    // `lowered[body_start..].find(marker)` per marker, making the whole pass
    // O(n*k) — minutes of CPU on a few MB of repeated markers). Bound the
    // newline search by the next marker so the segments stay disjoint.
    let count = marker_starts.len();
    (0..count).map(move |i| {
        let body_start = marker_starts[i] + marker.len();
        let next_marker = marker_starts.get(i + 1).copied().unwrap_or(text.len());
        let line_end = text[body_start..next_marker]
            .find(['\n', '\r'])
            .map(|offset| body_start + offset)
            .unwrap_or(next_marker);
        text[body_start..line_end].trim()
    })
}

fn is_concrete_agent_action(action: &str) -> bool {
    action.chars().count() >= 24 && contains_action_verb(action)
}

/// Validate an action body supplied separately from the `Agent action:` label.
/// Consolidation uses this so model-authored guidance and direct writes share
/// the same concrete-action contract.
pub fn is_concrete_agent_action_text(action: &str) -> bool {
    is_concrete_agent_action(action.trim())
}

/// Imperative verbs that make an `Agent action:` sentence concrete.
/// Shared with memory-md rendering so the gate and the renderer agree.
pub(crate) const ACTION_VERBS: &[&str] = &[
    "apply",
    "avoid",
    "check",
    "configure",
    "confirm",
    "disable",
    "do",
    "enable",
    "export",
    "follow",
    "include",
    "keep",
    "pin",
    "point",
    "prefer",
    "record",
    "review",
    "resolve",
    "reuse",
    "run",
    "set",
    "treat",
    "update",
    "use",
    "verify",
    "write",
];

fn contains_action_verb(text: &str) -> bool {
    text.split(|ch: char| !ch.is_ascii_alphabetic())
        .any(|word| ACTION_VERBS.contains(&word.to_ascii_lowercase().as_str()))
}

fn durable_signal_reason(
    chunk_type: ChunkType,
    text: &str,
    tags: &[String],
) -> Option<&'static str> {
    if matches!(chunk_type, ChunkType::Decision | ChunkType::Code) {
        return Some(match chunk_type {
            ChunkType::Decision => "decision chunk type",
            ChunkType::Code => "code or path-bearing chunk type",
            _ => unreachable!(),
        });
    }

    if let Some(reason) = tags.iter().find_map(|tag| match tag.as_str() {
        "kind:decision" => Some("decision tag"),
        "kind:evidence" => Some("evidence tag"),
        "kind:finish" => Some("finished task outcome tag"),
        "kind:consolidated" => Some("consolidated durable lesson tag"),
        "kind:run" => Some("run/result evidence tag"),
        _ => None,
    }) {
        return Some(reason);
    }

    let lowered = text.to_ascii_lowercase();
    if lowered.contains("decision:") || lowered.contains("rationale:") {
        return Some("decision with rationale");
    }
    if lowered.contains("validated:")
        || lowered.contains("validation:")
        || lowered.contains("reproduced")
        || lowered.contains("confirmed")
        || lowered.contains("passed")
    {
        return Some("validated result");
    }
    if lowered.contains("root cause") || lowered.contains("failed because") {
        return Some("root-cause failure");
    }
    if lowered.contains("fix:") || lowered.contains("fixed by") || lowered.contains("solution:") {
        return Some("validated fix");
    }
    if lowered.contains("command:")
        || lowered.contains("path:")
        || lowered.contains("parameter:")
        || lowered.contains("parameters:")
        || lowered.contains("/home/")
        || lowered.contains("crates/")
        || lowered.contains("tasks/")
        || lowered.contains(".rs")
        || lowered.contains(".md")
        || lowered.contains("http://")
        || lowered.contains("https://")
    {
        return Some("command/path/parameter evidence");
    }
    if lowered.contains("next step:")
        || lowered.contains("follow-up:")
        || lowered.contains("followup:")
    {
        return Some("durable follow-up");
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    fn tags(values: &[&str]) -> Vec<String> {
        values.iter().map(|value| value.to_string()).collect()
    }

    #[test]
    fn rejects_generated_digest_wrapper_tags() {
        let outcome = classify_write(
            ChunkType::Summary,
            "Task digest status generated. Summary: Highlight library for p contains 0 ranked lessons.",
            &tags(&["task:status:generated", "task:role:highlight_library"]),
            IngestionMode::Document,
        );
        assert_eq!(outcome.decision, AdmissionDecision::Reject);
        assert!(outcome.reason.contains("generated digest wrapper"));
    }

    #[test]
    fn rejects_obvious_progress_chatter() {
        let outcome = classify_write(
            ChunkType::Summary,
            "starting to inspect the code",
            &tags(&["kind:progress"]),
            IngestionMode::Document,
        );
        assert_eq!(outcome.decision, AdmissionDecision::Reject);
        assert!(outcome.reason.contains("low-signal progress"));
    }

    #[test]
    fn downgrades_low_signal_conversation_progress_to_ephemeral() {
        let outcome = classify_write(
            ChunkType::Summary,
            "starting to inspect the code",
            &tags(&["kind:progress"]),
            IngestionMode::Conversation,
        );
        assert_eq!(outcome.decision, AdmissionDecision::Ephemeral);
        assert!(outcome.reason.contains("short-lived hidden context"));
    }

    #[test]
    fn accepts_progress_with_concrete_validation() {
        let outcome = classify_write(
            ChunkType::Summary,
            "Validation: cargo test -p memd passed after fixing digest idempotence.",
            &tags(&["kind:progress"]),
            IngestionMode::Document,
        );
        assert_eq!(outcome.decision, AdmissionDecision::Durable);
    }

    #[test]
    fn accepts_required_durable_categories_with_specific_reasons() {
        let cases = [
            (
                ChunkType::Summary,
                "Decision: keep project aliases explicit. Rationale: silent merging hides scope drift.",
                vec!["kind:progress"],
                "decision with rationale",
            ),
            (
                ChunkType::Summary,
                "Fix: validate alias project IDs before search.",
                vec!["kind:progress"],
                "validated fix",
            ),
            (
                ChunkType::Summary,
                "Validation: cargo test -p memd passed after fixing alias lookup.",
                vec!["kind:progress"],
                "validated result",
            ),
            (
                ChunkType::Summary,
                "Root cause: generated digest wrappers were written as durable summaries.",
                vec!["kind:progress"],
                "root-cause failure",
            ),
            (
                ChunkType::Trace,
                "Command: cargo test -p memd write_admission -- --nocapture.",
                vec!["kind:progress"],
                "command/path/parameter evidence",
            ),
            (
                ChunkType::Summary,
                "Path: crates/memd/src/write_admission.rs holds the write-admission classifier.",
                vec!["kind:progress"],
                "command/path/parameter evidence",
            ),
            (
                ChunkType::Summary,
                "Follow-up: run memory-md useful-top-10 evaluator after Phase 3 rendering changes.",
                vec!["kind:progress"],
                "durable follow-up",
            ),
            (
                ChunkType::Summary,
                "Observed result from benchmark smoke.",
                vec!["kind:evidence"],
                "evidence tag",
            ),
        ];

        for (chunk_type, text, case_tags, expected_reason) in cases {
            let outcome = classify_write(
                chunk_type,
                text,
                &case_tags
                    .iter()
                    .map(|tag| tag.to_string())
                    .collect::<Vec<_>>(),
                IngestionMode::Document,
            );
            assert_eq!(outcome.decision, AdmissionDecision::Durable, "{text}");
            assert_eq!(outcome.reason, expected_reason, "{text}");
        }
    }

    #[test]
    fn downgrades_high_priority_without_agent_action() {
        let outcome = classify_write(
            ChunkType::Summary,
            "starting",
            &tags(&["kind:progress", "priority:9"]),
            IngestionMode::Document,
        );
        // Admitted, not rejected — but downgraded with an in-band
        // warning naming the verb allowlist.
        assert_eq!(outcome.decision, AdmissionDecision::Durable);
        assert!(outcome.reason.contains("downgraded to 7"));
        let warning = outcome.warning.expect("downgrade warning");
        assert!(warning.contains("Agent action"));
        assert!(
            warning.contains("set"),
            "warning lists the allowlist: {warning}"
        );
    }

    #[test]
    fn nonfinite_or_garbage_priority_does_not_bypass_the_gate() {
        // `priority:garbage`/`priority:inf`/`priority:nan` must not count as an
        // explicit priority and short-circuit a low-signal write to durable.
        for bad in [
            "priority:garbage",
            "priority:inf",
            "priority:nan",
            "importance:inf",
        ] {
            let outcome = classify_write(
                ChunkType::Summary,
                "starting", // low-signal progress chatter
                &tags(&["kind:progress", bad]),
                IngestionMode::Document,
            );
            assert_eq!(
                outcome.decision,
                AdmissionDecision::Reject,
                "tag {bad} must not bypass the low-signal gate"
            );
        }
        // A finite high-priority value is still honoured (downgrade path).
        let ok = classify_write(
            ChunkType::Summary,
            "starting",
            &tags(&["kind:progress", "priority:8.5"]),
            IngestionMode::Document,
        );
        assert_eq!(ok.decision, AdmissionDecision::Durable);
    }

    #[test]
    fn oversize_text_is_rejected_before_the_marker_scan() {
        let huge = "a".repeat(MAX_MEMORY_TEXT_BYTES + 1);
        let outcome = classify_write(
            ChunkType::Doc,
            &huge,
            &tags(&["kind:note"]),
            IngestionMode::Document,
        );
        assert_eq!(outcome.decision, AdmissionDecision::Reject);
        assert!(outcome.reason.contains("over the"));
    }

    #[test]
    fn accepts_high_priority_with_expanded_verbs() {
        // "set"/"pin" were missing from the old 16-verb allowlist and
        // rejected legitimate lessons in testing.
        let outcome = classify_write(
            ChunkType::Summary,
            "Validation: batch size fix passed. Agent action: always set ALPHA_EMBED_BATCH=32 before running the embed worker.",
            &tags(&["kind:finish", "priority:9"]),
            IngestionMode::Document,
        );
        assert_eq!(outcome.decision, AdmissionDecision::Durable);
        assert!(outcome.warning.is_none());
    }

    #[test]
    fn downgrade_high_priority_tags_rewrites_only_eight_plus() {
        let mut tags = vec![
            "priority:9".to_string(),
            "importance:8".to_string(),
            "priority:5".to_string(),
            "kind:finish".to_string(),
        ];
        downgrade_high_priority_tags(&mut tags);
        assert_eq!(
            tags,
            vec![
                "priority:7".to_string(),
                "importance:7".to_string(),
                "priority:5".to_string(),
                "kind:finish".to_string(),
            ]
        );
    }

    #[test]
    fn accepts_high_priority_with_agent_action() {
        let outcome = classify_write(
            ChunkType::Summary,
            "Validation: cache key fix passed. Agent action: Verify tenant_id and project_id before reusing cached retrieval results.",
            &tags(&["kind:progress", "priority:9"]),
            IngestionMode::Document,
        );
        assert_eq!(outcome.decision, AdmissionDecision::Durable);
    }

    #[test]
    fn accepts_high_priority_when_marker_is_explained_before_action() {
        let outcome = classify_write(
            ChunkType::Summary,
            "Validation: memory quality gate passed. High-priority records mention Agent action: in documentation. Agent action: Write every high-priority durable memory with a concrete action sentence that tells future agents what to verify or reuse.",
            &tags(&["kind:finish", "priority:9"]),
            IngestionMode::Document,
        );
        assert_eq!(outcome.decision, AdmissionDecision::Durable);
    }

    #[test]
    fn accepts_high_priority_action_with_path_punctuation() {
        let outcome = classify_write(
            ChunkType::Summary,
            "Validation: installed skill bundle. Agent action: Verify future agent sessions read the refreshed ~/.agents/skills/memd skill and use memd 0.61.0 before diagnosing memory-quality behavior.",
            &tags(&["kind:finish", "priority:9"]),
            IngestionMode::Document,
        );
        assert_eq!(outcome.decision, AdmissionDecision::Durable);
    }
}