wm-memory 9.2.0

Local-first persistent memory store with sessions and continuity 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
//! Semantic coordinate encoding — Tantivy TF-IDF bridge.
//!
//! Replaces the SHA-256 hash-based `Coordinate5D::encode()` with semantically
//! meaningful coordinates derived from anchor-based term frequency analysis.
//!
//! Three semantic axes (ported from v2's anchor embedding + PCA concept):
//! - **x**: Logic ↔ Emotion
//! - **y**: Micro ↔ Macro
//! - **z**: Time ↔ Space
//!
//! For each axis, two poles of anchor terms are defined. The encoder tokenizes
//! the input text using Tantivy's `SimpleTokenizer` + `LowerCaser` (consistent
//! with the search index), computes term frequencies, and projects to [0, 1]
//! per axis using a smoothed ratio of pole scores.

use ahash::AHashMap;
use tantivy::tokenizer::{LowerCaser, SimpleTokenizer, TextAnalyzer, TokenStream};

use wm_core::Coordinate5D;

/// Semantic scores for the three content-derived axes.
#[derive(Debug, Clone, PartialEq)]
pub struct SemanticScores {
    /// Logic (0.0) ↔ Emotion (1.0)
    pub x: f32,
    /// Micro (0.0) ↔ Macro (1.0)
    pub y: f32,
    /// Time (0.0) ↔ Space (1.0)
    pub z: f32,
}

impl SemanticScores {
    /// Neutral scores (all axes at 0.5 — no semantic signal).
    #[must_use]
    pub const fn neutral() -> Self {
        Self {
            x: 0.5,
            y: 0.5,
            z: 0.5,
        }
    }
}

/// Anchor term sets for the three semantic axes.
#[derive(Debug, Clone)]
struct SemanticAnchors {
    logic: &'static [&'static str],
    emotion: &'static [&'static str],
    micro: &'static [&'static str],
    macro_: &'static [&'static str],
    time: &'static [&'static str],
    space: &'static [&'static str],
}

impl Default for SemanticAnchors {
    fn default() -> Self {
        Self {
            logic: &[
                "algorithm",
                "code",
                "data",
                "function",
                "method",
                "system",
                "process",
                "structure",
                "analysis",
                "compute",
                "parameter",
                "model",
                "formula",
                "theorem",
                "proof",
                "derive",
                "calculate",
                "measure",
                "metric",
                "logic",
                "rational",
                "objective",
                "systematic",
                "technical",
                "engineering",
            ],
            emotion: &[
                "feel",
                "feeling",
                "emotion",
                "love",
                "fear",
                "joy",
                "sad",
                "happy",
                "angry",
                "hope",
                "care",
                "beauty",
                "art",
                "soul",
                "heart",
                "passion",
                "dream",
                "wonder",
                "intuition",
                "empathy",
                "spirit",
                "subjective",
                "personal",
                "emotional",
                "expressive",
            ],
            micro: &[
                "detail",
                "specific",
                "small",
                "local",
                "individual",
                "element",
                "atom",
                "bit",
                "byte",
                "cell",
                "node",
                "token",
                "word",
                "line",
                "step",
                "tiny",
                "precise",
                "exact",
                "narrow",
                "component",
                "unit",
                "instance",
            ],
            macro_: &[
                "global",
                "universe",
                "network",
                "architecture",
                "framework",
                "theory",
                "paradigm",
                "concept",
                "abstract",
                "broad",
                "general",
                "whole",
                "total",
                "infinite",
                "cosmic",
                "universal",
                "grand",
                "scale",
                "overview",
                "ecosystem",
                "pattern",
                "horizon",
            ],
            time: &[
                "time",
                "when",
                "before",
                "after",
                "now",
                "then",
                "past",
                "future",
                "present",
                "moment",
                "duration",
                "temporal",
                "chronological",
                "history",
                "timeline",
                "schedule",
                "deadline",
                "period",
                "phase",
                "cycle",
                "event",
                "sequence",
            ],
            space: &[
                "space",
                "where",
                "here",
                "there",
                "location",
                "position",
                "area",
                "region",
                "zone",
                "place",
                "distance",
                "spatial",
                "coordinate",
                "map",
                "geometry",
                "layout",
                "boundary",
                "field",
                "domain",
                "environment",
                "context",
            ],
        }
    }
}

/// Semantic encoder using Tantivy tokenization and anchor-based TF projection.
///
/// Tokenizes text with `SimpleTokenizer` + `LowerCaser` (same pipeline as the
/// Tantivy search index), then computes term frequencies against anchor term
/// sets for each semantic axis. Produces `SemanticScores` in [0, 1] per axis.
pub struct SemanticEncoder {
    anchors: SemanticAnchors,
}

impl Default for SemanticEncoder {
    fn default() -> Self {
        Self::new()
    }
}

impl SemanticEncoder {
    /// Create a new encoder with default anchor terms and Tantivy tokenization.
    #[must_use]
    pub fn new() -> Self {
        Self {
            anchors: SemanticAnchors::default(),
        }
    }

    /// Encode text into semantic scores (x, y, z) in [0, 1].
    ///
    /// Each axis is computed as:
    /// `axis = (pos_pole + smoothing) / (neg_pole + pos_pole + 2 * smoothing)`
    ///
    /// With smoothing = 0.5, neutral text (no anchor terms) returns 0.5.
    #[must_use]
    pub fn encode(&self, text: &str) -> SemanticScores {
        let freqs = self.term_frequencies(text);
        let x = self.axis_score(&freqs, self.anchors.logic, self.anchors.emotion);
        let y = self.axis_score(&freqs, self.anchors.micro, self.anchors.macro_);
        let z = self.axis_score(&freqs, self.anchors.time, self.anchors.space);
        SemanticScores { x, y, z }
    }

    /// Encode text into a full `Coordinate5D` with temporal and importance context.
    #[must_use]
    pub fn encode_coordinate(
        &self,
        text: &str,
        temporal_weight: f32,
        importance: f32,
    ) -> Coordinate5D {
        let scores = self.encode(text);
        Coordinate5D::from_semantic(scores.x, scores.y, scores.z, temporal_weight, importance)
    }

    /// Compute term frequencies from text using Tantivy tokenization.
    fn term_frequencies(&self, text: &str) -> AHashMap<String, f32> {
        let mut freqs: AHashMap<String, f32> = AHashMap::new();
        let mut analyzer = TextAnalyzer::builder(SimpleTokenizer::default())
            .filter(LowerCaser)
            .build();
        let mut stream = analyzer.token_stream(text);
        while stream.advance() {
            *freqs.entry(stream.token().text.clone()).or_insert(0.0) += 1.0;
        }
        freqs
    }

    /// Compute axis score from term frequencies and two anchor poles.
    fn axis_score(
        &self,
        freqs: &AHashMap<String, f32>,
        neg_pole: &[&str],
        pos_pole: &[&str],
    ) -> f32 {
        let neg = self.pole_score(freqs, neg_pole);
        let pos = self.pole_score(freqs, pos_pole);
        let smoothing = 0.5;
        (pos + smoothing) / 2.0f32.mul_add(smoothing, neg + pos)
    }

    /// Sum of sublinearly-scaled term frequencies for anchor terms.
    fn pole_score(&self, freqs: &AHashMap<String, f32>, terms: &[&str]) -> f32 {
        let mut score = 0.0f32;
        for term in terms {
            if let Some(&freq) = freqs.get(*term) {
                // Sublinear scaling: 1 + ln(freq) to avoid dominance by repeated terms
                score += 1.0 + freq.ln();
            }
        }
        score
    }
}

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

    #[test]
    fn neutral_text_returns_midpoint() {
        let encoder = SemanticEncoder::new();
        let scores = encoder.encode("the quick brown fox jumps over the lazy dog");
        // No anchor terms in this text — all axes should be near 0.5
        assert!((scores.x - 0.5).abs() < 0.01);
        assert!((scores.y - 0.5).abs() < 0.01);
        assert!((scores.z - 0.5).abs() < 0.01);
    }

    #[test]
    fn empty_text_returns_neutral() {
        let encoder = SemanticEncoder::new();
        let scores = encoder.encode("");
        assert_eq!(scores, SemanticScores::neutral());
    }

    #[test]
    fn logic_text_scores_toward_zero_x() {
        let encoder = SemanticEncoder::new();
        let scores = encoder.encode(
            "The algorithm computes data using a systematic method with precise parameters",
        );
        // Logic-heavy text → x should be below 0.5
        assert!(
            scores.x < 0.5,
            "x = {} should be < 0.5 for logic text",
            scores.x
        );
    }

    #[test]
    fn emotion_text_scores_toward_one_x() {
        let encoder = SemanticEncoder::new();
        let scores = encoder
            .encode("I feel love and joy in my heart, a deep passion and empathy for beauty");
        // Emotion-heavy text → x should be above 0.5
        assert!(
            scores.x > 0.5,
            "x = {} should be > 0.5 for emotion text",
            scores.x
        );
    }

    #[test]
    fn micro_text_scores_toward_zero_y() {
        let encoder = SemanticEncoder::new();
        let scores = encoder
            .encode("Each individual element and tiny detail of the specific component matters");
        // Micro-heavy text → y should be below 0.5
        assert!(
            scores.y < 0.5,
            "y = {} should be < 0.5 for micro text",
            scores.y
        );
    }

    #[test]
    fn macro_text_scores_toward_one_y() {
        let encoder = SemanticEncoder::new();
        let scores =
            encoder.encode("The global architecture is a universal framework on a cosmic scale");
        // Macro-heavy text → y should be above 0.5
        assert!(
            scores.y > 0.5,
            "y = {} should be > 0.5 for macro text",
            scores.y
        );
    }

    #[test]
    fn time_text_scores_toward_zero_z() {
        let encoder = SemanticEncoder::new();
        let scores = encoder.encode(
            "Before and after that moment, the timeline showed a chronological sequence of events",
        );
        // Time-heavy text → z should be below 0.5
        assert!(
            scores.z < 0.5,
            "z = {} should be < 0.5 for time text",
            scores.z
        );
    }

    #[test]
    fn space_text_scores_toward_one_z() {
        let encoder = SemanticEncoder::new();
        let scores = encoder.encode(
            "The spatial layout of the region defines the boundary and geometry of the area",
        );
        // Space-heavy text → z should be above 0.5
        assert!(
            scores.z > 0.5,
            "z = {} should be > 0.5 for space text",
            scores.z
        );
    }

    #[test]
    fn encode_is_deterministic() {
        let encoder = SemanticEncoder::new();
        let a = encoder.encode("The algorithm processes data with logic and analysis");
        let b = encoder.encode("The algorithm processes data with logic and analysis");
        assert_eq!(a, b);
    }

    #[test]
    fn similar_texts_produce_similar_coordinates() {
        let encoder = SemanticEncoder::new();
        let a = encoder.encode_coordinate(
            "The algorithm computes data using a systematic method",
            0.5,
            0.5,
        );
        let b = encoder.encode_coordinate(
            "The algorithm processes data using a systematic approach",
            0.5,
            0.5,
        );
        let c = encoder.encode_coordinate(
            "I feel love and joy in my heart with deep passion",
            0.5,
            0.5,
        );

        let dist_ab = a.semantic_distance_to(&b);
        let dist_ac = a.semantic_distance_to(&c);

        // Similar texts should be closer than dissimilar texts
        assert!(
            dist_ab < dist_ac,
            "dist(a,b)={dist_ab:.4} should be < dist(a,c)={dist_ac:.4}"
        );
    }

    #[test]
    fn encode_coordinate_produces_valid_range() {
        let encoder = SemanticEncoder::new();
        let coord = encoder.encode_coordinate("test content", 0.7, 0.9);
        assert!(coord.x >= 0.0 && coord.x <= 1.0);
        assert!(coord.y >= 0.0 && coord.y <= 1.0);
        assert!(coord.z >= 0.0 && coord.z <= 1.0);
        assert!((coord.w - 0.7).abs() < f32::EPSILON);
        assert!((coord.v - 0.9).abs() < f32::EPSILON);
    }

    #[test]
    fn mixed_content_produces_intermediate_scores() {
        let encoder = SemanticEncoder::new();
        let scores = encoder
            .encode("The algorithm processes data with emotional passion and systematic beauty");
        // Mixed logic + emotion → x should be somewhere in the middle
        assert!(
            (0.3..=0.7).contains(&scores.x),
            "x = {} should be in [0.3, 0.7] for mixed text",
            scores.x
        );
    }

    #[test]
    fn case_insensitive_matching() {
        let encoder = SemanticEncoder::new();
        let lower = encoder.encode("the algorithm computes data");
        let upper = encoder.encode("The ALGORITHM COMPUTES DATA");
        assert_eq!(lower, upper);
    }

    #[test]
    fn semantic_scores_neutral() {
        assert_eq!(
            SemanticScores::neutral(),
            SemanticScores {
                x: 0.5,
                y: 0.5,
                z: 0.5
            }
        );
    }
}