agentmem 0.1.1

Local-first memory engine for AI coding agents
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
use std::borrow::Borrow;
use std::fmt;
use std::ops::Deref;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::core::validation;
use crate::error::{Result, ValidationError};

/// A validated key used to address values in the store.
///
/// Keys are UTF-8 strings with a constrained structure intended to remain:
///
/// - human-readable
/// - namespace-friendly
/// - safe to persist
/// - predictable for agents and tooling
///
/// Examples:
///
/// - `agent/claude/current_task`
/// - `project/demo/root`
/// - `session/2026-04-12/summary`
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Key(String);

impl Key {
    /// Validates and constructs a new key.
    ///
    /// The input must satisfy the crate's key rules as defined in the
    /// validation module.
    pub fn new(input: impl Into<String>) -> Result<Self> {
        let input = input.into();
        validation::validate_key(&input)?;
        Ok(Self(input))
    }

    /// Constructs a key without validation.
    ///
    /// This is intentionally crate-visible only. External callers should always
    /// go through [`Key::new`] so invariants remain enforced at the boundary.
    #[allow(dead_code)]
    pub(crate) fn new_unchecked(input: String) -> Self {
        Self(input)
    }

    /// Returns the key as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns the namespace portion of the key, if present.
    ///
    /// For a key like `agent/claude/current_task`, the namespace is
    /// `agent/claude`.
    #[must_use]
    pub fn namespace(&self) -> Option<Namespace> {
        self.0
            .rsplit_once('/')
            .and_then(|(prefix, _)| Namespace::new(prefix).ok())
    }

    /// Returns the final segment of the key.
    ///
    /// For a key like `agent/claude/current_task`, the leaf is `current_task`.
    #[must_use]
    pub fn leaf(&self) -> &str {
        self.0.rsplit('/').next().unwrap_or(self.0.as_str())
    }

    /// Returns `true` if the key is within the provided namespace.
    #[must_use]
    pub fn starts_with_namespace(&self, namespace: &Namespace) -> bool {
        if self.0 == namespace.as_str() {
            return true;
        }

        self.0
            .strip_prefix(namespace.as_str())
            .is_some_and(|suffix| suffix.starts_with('/'))
    }

    /// Consumes the key and returns the inner string.
    #[must_use]
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl AsRef<str> for Key {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Borrow<str> for Key {
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl Deref for Key {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl fmt::Display for Key {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl TryFrom<String> for Key {
    type Error = crate::error::AgentMemoryError;

    fn try_from(value: String) -> Result<Self> {
        Self::new(value)
    }
}

impl TryFrom<&str> for Key {
    type Error = crate::error::AgentMemoryError;

    fn try_from(value: &str) -> Result<Self> {
        Self::new(value)
    }
}

/// A validated namespace prefix used to group related keys.
///
/// Namespaces are structured path-like identifiers without trailing slashes.
/// They are intended for agent scoping and project organization.
///
/// Examples:
///
/// - `agent/claude`
/// - `project/demo`
/// - `session/2026-04-12`
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Namespace(String);

impl Namespace {
    /// Validates and constructs a new namespace.
    pub fn new(input: impl Into<String>) -> Result<Self> {
        let input = input.into();
        validation::validate_namespace(&input)?;
        Ok(Self(input))
    }

    /// Constructs a namespace without validation.
    pub(crate) fn new_unchecked(input: String) -> Self {
        Self(input)
    }

    /// Returns the namespace as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns a new key under this namespace.
    ///
    /// The leaf segment is validated before constructing the final key.
    pub fn join(&self, leaf: &str) -> Result<Key> {
        validation::validate_key_leaf(leaf)?;
        Key::new(format!("{}/{}", self.0, leaf))
    }

    /// Returns the parent namespace, if any.
    ///
    /// For `agent/claude`, the parent is `agent`.
    #[must_use]
    pub fn parent(&self) -> Option<Self> {
        self.0
            .rsplit_once('/')
            .map(|(parent, _)| Self::new_unchecked(parent.to_owned()))
    }

    /// Returns the final namespace segment.
    #[must_use]
    pub fn leaf(&self) -> &str {
        self.0.rsplit('/').next().unwrap_or(self.0.as_str())
    }

    /// Consumes the namespace and returns the inner string.
    #[must_use]
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl AsRef<str> for Namespace {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Borrow<str> for Namespace {
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl Deref for Namespace {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl fmt::Display for Namespace {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl TryFrom<String> for Namespace {
    type Error = crate::error::AgentMemoryError;

    fn try_from(value: String) -> Result<Self> {
        Self::new(value)
    }
}

impl TryFrom<&str> for Namespace {
    type Error = crate::error::AgentMemoryError;

    fn try_from(value: &str) -> Result<Self> {
        Self::new(value)
    }
}

/// A validated value stored in the memory engine.
///
/// Values remain text in v1 on purpose. This keeps the initial storage model:
///
/// - inspectable
/// - easy to serialize safely
/// - stable for CLI and agent use
///
/// The wrapper exists so length limits and future policy checks remain
/// centralized rather than spread across the codebase.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Value(String);

impl Value {
    /// Validates and constructs a new value.
    pub fn new(input: impl Into<String>) -> Result<Self> {
        let input = input.into();
        validation::validate_value(&input)?;
        Ok(Self(input))
    }

    /// Constructs a value without validation.
    #[allow(dead_code)]
    pub(crate) fn new_unchecked(input: String) -> Self {
        Self(input)
    }

    /// Returns the value as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the value and returns the inner string.
    #[must_use]
    pub fn into_inner(self) -> String {
        self.0
    }

    /// Returns `true` when the value is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the UTF-8 byte length of the value.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }
}

impl AsRef<str> for Value {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Borrow<str> for Value {
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl Deref for Value {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl TryFrom<String> for Value {
    type Error = crate::error::AgentMemoryError;

    fn try_from(value: String) -> Result<Self> {
        Self::new(value)
    }
}

impl TryFrom<&str> for Value {
    type Error = crate::error::AgentMemoryError;

    fn try_from(value: &str) -> Result<Self> {
        Self::new(value)
    }
}

/// A validated project name used during onboarding and configuration.
///
/// This is intentionally stricter than a free-form display label because it may
/// be used in:
///
/// - default namespaces
/// - config values
/// - file and directory suggestions
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ProjectName(String);

impl ProjectName {
    /// Validates and constructs a new project name.
    pub fn new(input: impl Into<String>) -> Result<Self> {
        let input = input.into();
        validation::validate_project_name(&input)?;
        Ok(Self(input))
    }

    /// Constructs a project name without validation.
    #[allow(dead_code)]
    pub(crate) fn new_unchecked(input: String) -> Self {
        Self(input)
    }

    /// Returns the project name as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns a default namespace rooted under this project.
    ///
    /// Example:
    ///
    /// `my-app` -> `project/my-app`
    pub fn as_project_namespace(&self) -> Namespace {
        Namespace::new_unchecked(format!("project/{}", self.0))
    }

    /// Consumes the project name and returns the inner string.
    #[must_use]
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl AsRef<str> for ProjectName {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Borrow<str> for ProjectName {
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl Deref for ProjectName {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl fmt::Display for ProjectName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl TryFrom<String> for ProjectName {
    type Error = crate::error::AgentMemoryError;

    fn try_from(value: String) -> Result<Self> {
        Self::new(value)
    }
}

impl TryFrom<&str> for ProjectName {
    type Error = crate::error::AgentMemoryError;

    fn try_from(value: &str) -> Result<Self> {
        Self::new(value)
    }
}

/// A validated filesystem path pointing to a store file.
///
/// This wrapper exists to prevent raw `PathBuf` values from floating through
/// the API without basic policy checks.
///
/// Important:
///
/// Validation here is *policy validation*, not a security proof. Paths remain
/// environment-dependent and must still be handled carefully by the storage
/// layer.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct StorePath(PathBuf);

impl StorePath {
    /// Validates and constructs a new store path.
    pub fn new(path: impl Into<PathBuf>) -> Result<Self> {
        let path = path.into();
        validation::validate_store_path(&path)?;
        Ok(Self(path))
    }

    /// Constructs a store path without validation.
    #[allow(dead_code)]
    pub(crate) fn new_unchecked(path: PathBuf) -> Self {
        Self(path)
    }

    /// Returns the path as a borrowed [`Path`].
    #[must_use]
    pub fn as_path(&self) -> &Path {
        &self.0
    }

    /// Returns the parent directory, if one exists.
    #[must_use]
    pub fn parent(&self) -> Option<&Path> {
        self.0.parent()
    }

    /// Returns the file name component, if one exists.
    #[must_use]
    pub fn file_name(&self) -> Option<&std::ffi::OsStr> {
        self.0.file_name()
    }

    /// Consumes the wrapper and returns the inner path buffer.
    #[must_use]
    pub fn into_inner(self) -> PathBuf {
        self.0
    }
}

impl AsRef<Path> for StorePath {
    fn as_ref(&self) -> &Path {
        self.as_path()
    }
}

impl Borrow<Path> for StorePath {
    fn borrow(&self) -> &Path {
        self.as_path()
    }
}

impl Deref for StorePath {
    type Target = Path;

    fn deref(&self) -> &Self::Target {
        self.as_path()
    }
}

impl fmt::Display for StorePath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_path_for_display(&self.0, f)
    }
}

impl TryFrom<PathBuf> for StorePath {
    type Error = crate::error::AgentMemoryError;

    fn try_from(value: PathBuf) -> Result<Self> {
        Self::new(value)
    }
}

impl TryFrom<&Path> for StorePath {
    type Error = crate::error::AgentMemoryError;

    fn try_from(value: &Path) -> Result<Self> {
        Self::new(value.to_path_buf())
    }
}

impl TryFrom<&str> for StorePath {
    type Error = crate::error::AgentMemoryError;

    fn try_from(value: &str) -> Result<Self> {
        Self::new(PathBuf::from(value))
    }
}

/// Writes a path in a user-facing way without panicking on non-UTF-8 content.
fn write_path_for_display(path: &Path, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "{}", path.display())
}

/// A typed key/value entry returned by store iteration and listing APIs.
///
/// This is preferable to returning a tuple in public-facing code because the
/// field names remain self-documenting and easy to evolve.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Entry {
    /// The validated key for this entry.
    pub key: Key,
    /// The validated value for this entry.
    pub value: Value,
}

impl Entry {
    /// Constructs a new entry from validated key and value types.
    #[must_use]
    pub const fn new(key: Key, value: Value) -> Self {
        Self { key, value }
    }

    /// Creates an entry from raw strings after validation.
    pub fn try_new(key: impl Into<String>, value: impl Into<String>) -> Result<Self> {
        Ok(Self {
            key: Key::new(key.into())?,
            value: Value::new(value.into())?,
        })
    }
}

/// A typed request payload for inserting or replacing an entry.
///
/// This can help keep higher-level APIs explicit when we later want methods
/// like `Store::insert(entry)` alongside `Store::set(key, value)`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetRequest {
    /// Target key.
    pub key: Key,
    /// Value to persist.
    pub value: Value,
}

impl SetRequest {
    /// Constructs a new request from validated parts.
    #[must_use]
    pub const fn new(key: Key, value: Value) -> Self {
        Self { key, value }
    }

    /// Constructs a request from raw strings after validation.
    pub fn try_new(key: impl Into<String>, value: impl Into<String>) -> Result<Self> {
        Ok(Self {
            key: Key::new(key.into())?,
            value: Value::new(value.into())?,
        })
    }
}

/// A small typed wrapper used for prefix-based list operations.
///
/// This is intentionally separate from [`Namespace`] so the API can later allow:
///
/// - exact namespaces
/// - looser prefixes
/// - migration filters
///
/// without overloading one type with too many meanings.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct KeyPrefix(String);

impl KeyPrefix {
    /// Validates and constructs a prefix.
    ///
    /// Prefixes use the same structural rules as namespaces in v1.
    pub fn new(input: impl Into<String>) -> Result<Self> {
        let input = input.into();
        validation::validate_namespace(&input)?;
        Ok(Self(input))
    }

    /// Returns the prefix as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns `true` when the provided key matches this prefix.
    #[must_use]
    pub fn matches(&self, key: &Key) -> bool {
        if key.as_str() == self.0 {
            return true;
        }

        key.as_str()
            .strip_prefix(self.0.as_str())
            .is_some_and(|suffix| suffix.starts_with('/'))
    }
}

impl fmt::Display for KeyPrefix {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl TryFrom<&str> for KeyPrefix {
    type Error = crate::error::AgentMemoryError;

    fn try_from(value: &str) -> Result<Self> {
        Self::new(value)
    }
}

impl TryFrom<String> for KeyPrefix {
    type Error = crate::error::AgentMemoryError;

    fn try_from(value: String) -> Result<Self> {
        Self::new(value)
    }
}

/// Ensures a path-like field is never constructed from an empty or malformed
/// user-facing string without validation.
///
/// This helper is kept private because callers should generally use the typed
/// constructors above instead of handling raw validation details here.
fn _ensure_non_empty(field: &'static str, value: &str) -> std::result::Result<(), ValidationError> {
    if value.is_empty() {
        return Err(ValidationError::empty(field));
    }

    Ok(())
}