wm-tools 9.1.9

Curated tool implementations for the WhiteMagic MCP server.
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
//! Additional tools — count, tags, session_list, citta_coherence, dharma_profiles, nearby.

#![forbid(unsafe_code)]

use async_trait::async_trait;

use serde_json::{Value, json};
use std::sync::Arc;
use wm_core::{Context, EffectRow, Galaxy, Gana, Resource, Tool, ToolStats};
use wm_memory::MemoryStore;

use super::common::{galaxy_name, parse_galaxy, parse_galaxy_or};

pub struct MemoryCountTool {
    store: Arc<MemoryStore>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryCountTool {
    pub fn new(store: Arc<MemoryStore>) -> Self {
        Self {
            store,
            stats: ToolStats::default(),
            effects: EffectRow::read_only(vec![Resource::Galaxy("codex".into())]),
        }
    }
}

#[async_trait]
impl Tool for MemoryCountTool {
    fn input_schema(&self) -> Value {
        super::common::schema(
            &json!({
                "galaxy": super::common::str_prop("Galaxy to count (optional; all memory galaxies when absent)"),
            }),
            &[],
        )
    }
    fn name(&self) -> &str {
        "memory.count"
    }
    fn gana(&self) -> Gana {
        Gana::WinnowingBasket
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "Count memories in a galaxy"
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let galaxy = parse_galaxy_or(args.get("galaxy").and_then(|v| v.as_str()), Galaxy::Codex)?;
        let count = self.store.count(galaxy)?;
        Ok(json!({ "status": "success", "galaxy": galaxy_name(galaxy), "count": count }))
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `memory.tags` — list all unique tags in a galaxy.
pub struct MemoryTagsTool {
    store: Arc<MemoryStore>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryTagsTool {
    pub fn new(store: Arc<MemoryStore>) -> Self {
        Self {
            store,
            stats: ToolStats::default(),
            effects: EffectRow::read_only(vec![Resource::Galaxy("codex".into())]),
        }
    }
}

#[async_trait]
impl Tool for MemoryTagsTool {
    fn input_schema(&self) -> Value {
        super::common::schema(
            &json!({
                "galaxy": super::common::str_prop("Galaxy whose tags to list (optional; default codex)"),
            }),
            &[],
        )
    }
    fn name(&self) -> &str {
        "memory.tags"
    }
    fn gana(&self) -> Gana {
        Gana::Net
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "List all unique tags in a galaxy"
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let galaxy = parse_galaxy_or(args.get("galaxy").and_then(|v| v.as_str()), Galaxy::Codex)?;
        let memories = self.store.scan(galaxy, 10_000)?;
        let tags: std::collections::HashSet<String> = memories
            .iter()
            .flat_map(|m| m.metadata.tags.iter().cloned())
            .collect();
        let mut tag_list: Vec<String> = tags.into_iter().collect();
        tag_list.sort_unstable();
        Ok(
            json!({ "status": "success", "galaxy": galaxy_name(galaxy), "unique_tags": tag_list.len(), "tags": tag_list }),
        )
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `session.list` — list all sessions.
pub struct SessionListTool {
    store: Arc<MemoryStore>,
    stats: ToolStats,
    effects: EffectRow,
}

impl SessionListTool {
    pub fn new(store: Arc<MemoryStore>) -> Self {
        Self {
            store,
            stats: ToolStats::default(),
            effects: EffectRow::read_only(vec![Resource::Galaxy("sessions".into())]),
        }
    }
}

#[async_trait]
impl Tool for SessionListTool {
    fn input_schema(&self) -> Value {
        super::common::schema(
            &json!({
                "session_id": super::common::str_prop("Filter by session UUID"),
                "title": super::common::str_prop("Filter by title substring"),
                "sequence": super::common::int_prop("Filter by start sequence number"),
                "type": super::common::str_prop("Filter by session type"),
            }),
            &[],
        )
    }
    fn name(&self) -> &str {
        "session.list"
    }
    fn gana(&self) -> Gana {
        Gana::StraddlingLegs
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "List session summaries in the Sessions galaxy (turns grouped by session)"
    }
    async fn call(&self, _ctx: &mut Context, _args: Value) -> wm_core::Result<Value> {
        let memories = self.store.scan_all(Galaxy::Sessions)?;

        // Group turns and start markers into session summaries.
        #[derive(Default)]
        struct Summary {
            title: Option<String>,
            turns: u64,
            earliest: Option<chrono::DateTime<chrono::Utc>>,
            latest: Option<chrono::DateTime<chrono::Utc>>,
        }
        let mut summaries: std::collections::HashMap<String, Summary> =
            std::collections::HashMap::new();

        for m in &memories {
            if let Ok(v) = serde_json::from_str::<Value>(&m.content) {
                // session_start: session id lives in the tag.
                if v.get("type").and_then(Value::as_str) == Some("session_start") {
                    if let Some(sid) = m
                        .metadata
                        .tags
                        .iter()
                        .find_map(|t| t.strip_prefix("session:"))
                    {
                        let entry = summaries.entry(sid.to_string()).or_default();
                        entry.title = v.get("title").and_then(Value::as_str).map(String::from);
                    }
                    continue;
                }
                // session_turn (and other session memories): session id in content.
                if let Some(sid) = v.get("session_id").and_then(Value::as_str) {
                    let entry = summaries.entry(sid.to_string()).or_default();
                    let ts = m.metadata.created_at;
                    entry.earliest = Some(entry.earliest.map_or(ts, |e| e.min(ts)));
                    entry.latest = Some(entry.latest.map_or(ts, |l| l.max(ts)));
                    if v.get("sequence").and_then(Value::as_u64).is_some() {
                        entry.turns += 1;
                    }
                }
            }
        }

        let mut sessions: Vec<(String, Summary)> = summaries.into_iter().collect();
        // Most recently active sessions first.
        sessions.sort_by_key(|(_, s)| {
            std::cmp::Reverse(
                s.latest
                    .unwrap_or(chrono::DateTime::<chrono::Utc>::UNIX_EPOCH),
            )
        });
        let total = sessions.len();
        sessions.truncate(100);

        let sessions: Vec<Value> = sessions
            .into_iter()
            .map(|(sid, s)| {
                json!({
                    "session_id": sid,
                    "title": s.title.unwrap_or_else(|| format!("Session {}", &sid[..sid.len().min(8)])),
                    "turns": s.turns,
                    "first_activity": s.earliest.map(|t| t.to_rfc3339()),
                    "last_activity": s.latest.map(|t| t.to_rfc3339()),
                })
            })
            .collect();

        Ok(json!({
            "status": "success",
            "count": total,
            "sessions": sessions,
        }))
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `citta.coherence` — check coherence threshold.
pub struct CittaCoherenceTool {
    stats: ToolStats,
    effects: EffectRow,
}

impl CittaCoherenceTool {
    #[must_use]
    pub fn new() -> Self {
        Self {
            stats: ToolStats::default(),
            effects: EffectRow::pure(),
        }
    }
}

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

#[async_trait]
impl Tool for CittaCoherenceTool {
    fn name(&self) -> &str {
        "citta.coherence"
    }
    fn gana(&self) -> Gana {
        Gana::Ghost
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "Check citta coherence level and whether writes are permitted"
    }
    async fn call(&self, ctx: &mut Context, _args: Value) -> wm_core::Result<Value> {
        let threshold = 0.3f32;
        let can_write = ctx.citta_coherence >= threshold;
        Ok(json!({
            "status": "success",
            "coherence": ctx.citta_coherence,
            "valence": ctx.citta_valence,
            "write_threshold": threshold,
            "can_write": can_write,
        }))
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `dharma.profiles` — list available dharma profiles.
pub struct DharmaProfilesTool {
    stats: ToolStats,
    effects: EffectRow,
}

impl DharmaProfilesTool {
    #[must_use]
    pub fn new() -> Self {
        Self {
            stats: ToolStats::default(),
            effects: EffectRow::pure(),
        }
    }
}

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

#[async_trait]
impl Tool for DharmaProfilesTool {
    fn name(&self) -> &str {
        "dharma.profiles"
    }
    fn gana(&self) -> Gana {
        Gana::ExtendedNet
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "List available dharma governance profiles"
    }
    async fn call(&self, _ctx: &mut Context, _args: Value) -> wm_core::Result<Value> {
        Ok(json!({
            "status": "success",
            "profiles": [
                { "name": "default", "description": "Standard governance — observe and advise" },
                { "name": "strict", "description": "Strict governance — intervene on writes in low coherence" },
                { "name": "research", "description": "Lenient governance — allow experimental tools" },
                { "name": "production", "description": "Hardened governance — panic on dharma violations" },
            ],
        }))
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `memory.nearby` — find memories spatially near a query using 5D coordinates.
pub struct MemoryNearbyTool {
    store: Arc<MemoryStore>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryNearbyTool {
    pub fn new(store: Arc<MemoryStore>) -> Self {
        Self {
            store,
            stats: ToolStats::default(),
            effects: EffectRow::read_only(vec![Resource::Galaxy("codex".into())]),
        }
    }
}

#[async_trait]
impl Tool for MemoryNearbyTool {
    fn name(&self) -> &str {
        "memory.nearby"
    }
    fn gana(&self) -> Gana {
        Gana::Star
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "Find memories spatially near a query text using 5D holographic coordinates"
    }
    fn input_schema(&self) -> Value {
        super::common::schema(
            &json!({
                "query": super::common::str_prop("Query text to locate in 5D space"),
                "limit": super::common::int_prop("Maximum results (default 10)"),
                "radius": super::common::num_prop("Spatial radius cutoff (optional)"),
                "galaxy": super::common::str_prop("Galaxy (default: codex)"),
            }),
            &["query"],
        )
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let query = args.get("query").and_then(|v| v.as_str()).unwrap_or("");
        if query.is_empty() {
            return Err(wm_core::CoreError::InvalidArgs(
                "Missing 'query' parameter".into(),
            ));
        }
        let galaxy_name_str = args
            .get("galaxy")
            .and_then(|v| v.as_str())
            .unwrap_or("codex");
        let galaxy = parse_galaxy(galaxy_name_str)?;
        let radius = args
            .get("radius")
            .and_then(serde_json::Value::as_f64)
            .unwrap_or(0.5) as f32;
        let limit = args
            .get("limit")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(20) as usize;

        let center = wm_core::Coordinate5D::encode(query);
        let memories = self.store.scan(galaxy, 1000)?;

        let candidates: Vec<(usize, wm_core::Coordinate5D)> = memories
            .iter()
            .enumerate()
            .map(|(i, m)| (i, m.metadata.coord5d.clone()))
            .collect();

        let nearby = wm_core::find_nearby(&center, &candidates, radius);

        let results: Vec<Value> = nearby
            .iter()
            .filter(|(idx, _)| crate::expansion::common::mcp_visible(&memories[*idx]))
            .filter(|(idx, _)| crate::expansion::common::validity_visible(&memories[*idx]))
            .take(limit)
            .map(|(idx, dist)| {
                let mem = &memories[*idx];
                json!({
                    "id": mem.metadata.id,
                    "content": mem.content.chars().take(100).collect::<String>(),
                    "distance": dist,
                    "zone": mem.metadata.coord5d.zone().name(),
                    "importance": mem.metadata.importance,
                    "tags": mem.metadata.tags,
                })
            })
            .collect();

        Ok(json!({
            "status": "success",
            "query": query,
            "galaxy": galaxy_name_str,
            "radius": radius,
            "center": {
                "x": center.x,
                "y": center.y,
                "z": center.z,
                "w": center.w,
                "v": center.v,
            },
            "found": results.len(),
            "scanned": memories.len(),
            "nearby": results,
        }))
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

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

    fn open_store() -> (tempfile::TempDir, Arc<MemoryStore>) {
        let tmp = tempfile::tempdir().unwrap();
        let store = Arc::new(MemoryStore::open_default(tmp.path()).unwrap());
        (tmp, store)
    }

    #[tokio::test]
    async fn memory_tags_returns_unique_sorted_tags() {
        let (_tmp, store) = open_store();
        for tags in [["zeta", "alpha"], ["beta", "alpha"]] {
            let mut memory = Memory::new(Galaxy::Codex, "invented tag fixture".into());
            memory.metadata.tags = tags.into_iter().map(String::from).collect();
            store.put(Galaxy::Codex, &memory).unwrap();
        }
        let result = MemoryTagsTool::new(store)
            .call(&mut Context::default(), json!({"galaxy": "codex"}))
            .await
            .unwrap();
        assert_eq!(result["unique_tags"], 3);
        assert_eq!(result["tags"], json!(["alpha", "beta", "zeta"]));
    }

    #[tokio::test]
    async fn citta_coherence_reflects_context_without_claiming_global_state() {
        let mut context = Context {
            citta_coherence: 0.29,
            citta_valence: -0.2,
            ..Context::default()
        };
        let result = CittaCoherenceTool::new()
            .call(&mut context, json!({}))
            .await
            .unwrap();
        assert!((result["coherence"].as_f64().unwrap() - 0.29).abs() < 1e-6);
        assert_eq!(result["can_write"], false);
        assert!((result["write_threshold"].as_f64().unwrap() - 0.3).abs() < 1e-6);
    }

    #[tokio::test]
    async fn dharma_profiles_reports_static_descriptive_catalog() {
        let result = DharmaProfilesTool::new()
            .call(&mut Context::default(), json!({}))
            .await
            .unwrap();
        assert_eq!(result["profiles"].as_array().unwrap().len(), 4);
        assert_eq!(result["profiles"][0]["name"], "default");
    }
}