wm-core 9.2.4

Core types, IDs, errors, and shared primitives for the WhiteMagic local-first memory system.
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
//! Effect Row System — Inspired by Koka's Effect Types
//!
//! Every tool declares what resources it reads, writes, invokes, and
//! whether it spawns external processes. This enables compile-time
//! effect safety via Rust traits and runtime governance via Dharma.

use serde::{Deserialize, Serialize};
use std::fmt;

/// A resource that a tool may read from or write to.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Resource {
    /// A specific LMDB galaxy database
    Galaxy(String),
    /// The karma ledger
    KarmaLedger,
    /// The Dharma rule engine
    DharmaRules,
    /// The Tantivy full-text index
    SearchIndex,
    /// The vector embedding store
    VectorStore,
    /// External network (HTTP, gRPC)
    Network,
    /// Local filesystem outside LMDB
    Filesystem,
    /// System process spawning
    Process,
    /// LLM inference (local or remote)
    Inference,
    /// User session state
    Session,
    /// The Gan Ying event bus (persisted to a JSONL log when enabled)
    EventBus,
    /// The coordination lease ledger's acquire/renew path (fixed
    /// `<git-common-dir>/wm-leases.json`): strict mode refuses new claims and
    /// renewals so system stress cannot trap new work (AHIMSA Target A, 9.1.8).
    CoordinationLease,
    /// Owner cleanup of one coordination lease (exact owner + exact scope,
    /// fixed ledger only): the single coordination mutation strict mode
    /// admits (AHIMSA Target A, 9.1.8).
    CoordinationRelease,
}

/// A capability that a tool may invoke.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Capability {
    /// Memory read operations
    MemoryRead,
    /// Memory write operations
    MemoryWrite,
    /// Memory deletion
    MemoryDelete,
    /// Full-text search
    Search,
    /// Vector similarity search
    VectorSearch,
    /// Embedding generation
    Embed,
    /// LLM inference
    LlmInfer,
    /// Tool-to-tool delegation
    Delegate,
    /// External process execution
    Execute,
    /// Network request
    NetworkRequest,
    /// Dream cycle execution
    Dream,
    /// Consciousness update
    CittaUpdate,
}

/// Estimated resource cost for a tool call.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CostEstimate {
    /// Estimated CPU time in nanoseconds (0 = unknown)
    pub cpu_ns: u64,
    /// Estimated memory touched in bytes (0 = unknown)
    pub memory_bytes: u64,
    /// Estimated disk I/O in bytes (0 = unknown)
    pub disk_bytes: u64,
    /// Estimated network I/O in bytes (0 = unknown)
    pub network_bytes: u64,
    /// Whether this tool is expensive enough to skip in Alpha/Theta modes
    pub expensive: bool,
}

/// Kernel-sandbox declaration for a tool — the Landlock A→B seam.
///
/// v0 (declarative/audit-facing): the serve-level Landlock ruleset
/// (`WM_LANDLOCK=1`) confines the whole process's write-class filesystem
/// rights to the store root; this field records nothing enforced per tool.
/// v1 (enforced): tools declaring [`Sandbox::StoreScoped`] become eligible
/// to run on a dedicated Landlock-restricted thread, upgrading the pathway
/// without reworking tool definitions.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Sandbox {
    /// Tool runs with the process's ambient filesystem rights (default).
    /// The serve-level ruleset still applies process-wide when enabled.
    #[default]
    Inherit,
    /// Tool only touches paths beneath the store root — eligible for the
    /// v1 per-tool restricted-thread pathway.
    StoreScoped,
    /// Tool launches external processes — its spawn sites must build
    /// commands through [`crate::Context::spawn`] so the OS runner
    /// (`mandala-sandbox`) can wrap them (B2). Declaring this is the
    /// tool's assertion that it uses the policy; the dispatcher injects
    /// it and loud-degrades when no runner resolves.
    Subprocess,
}

/// The effect row of a tool — what it does to the world.
///
/// Inspired by Koka's effect row system, this is checked at compile time
/// via Rust trait bounds and at runtime by the Dharma governance layer.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct EffectRow {
    /// Resources this tool reads from
    pub reads: Vec<Resource>,
    /// Resources this tool writes to
    pub writes: Vec<Resource>,
    /// Capabilities this tool invokes
    pub invokes: Vec<Capability>,
    /// Whether this tool spawns external processes
    pub spawns: bool,
    /// Whether this tool is destructive (deletes/overwrites data).
    /// Destructive tools require explicit confirmation via `confirm: true` in args.
    pub destructive: bool,
    /// Kernel-sandbox eligibility (Landlock A→B seam, declarative in v0).
    #[serde(default)]
    pub sandbox: Sandbox,
    /// Estimated resource cost
    pub cost: CostEstimate,
}

impl EffectRow {
    /// Create an empty effect row (pure function)
    #[must_use]
    pub fn pure() -> Self {
        Self::default()
    }

    /// Create a read-only effect row
    #[must_use]
    pub fn read_only(resources: Vec<Resource>) -> Self {
        Self {
            reads: resources,
            writes: vec![],
            invokes: vec![],
            spawns: false,
            destructive: false,
            sandbox: Sandbox::Inherit,
            cost: CostEstimate::default(),
        }
    }

    /// Check if this effect row is compatible with a brain-wave state.
    ///
    /// In Alpha/Theta/Delta modes, expensive or write-heavy tools are
    /// filtered out to conserve resources.
    #[must_use]
    pub fn is_available_in(&self, brain_wave: crate::BrainWave) -> bool {
        use crate::BrainWave::{Alpha, Beta, Delta, Gamma, Theta};
        match brain_wave {
            Gamma => true,
            Beta => true,
            Alpha => !self.cost.expensive && self.writes.is_empty(),
            Theta => !self.cost.expensive && self.writes.is_empty() && !self.spawns,
            Delta => false, // Delta: no tools available, only wake on event
        }
    }

    /// True when this row mutates the coordination lease ledger (claim or
    /// same-owner renewal). Strict mode refuses acquisition/renewal so system
    /// stress cannot trap new work (AHIMSA Target A, 9.1.8).
    #[must_use]
    pub fn acquires_coordination_lease(&self) -> bool {
        self.writes
            .iter()
            .any(|r| matches!(r, Resource::CoordinationLease))
    }

    /// True when this row is exactly the coordination owner-cleanup effect:
    /// one `CoordinationRelease` write, no spawns, not destructive. The strict
    /// gate admits this shape (and only this shape) so an already-held lease
    /// can always be released under stress.
    #[must_use]
    pub fn is_coordination_cleanup(&self) -> bool {
        !self.spawns
            && !self.destructive
            && self.writes.len() == 1
            && matches!(self.writes[0], Resource::CoordinationRelease)
    }

    /// True when this row is exactly the no-discovery checkpoint shape: one
    /// Sessions-galaxy write, no spawns, not destructive. The strict gate
    /// admits this shape so a checkpoint can be stored under stress without
    /// repository discovery, filesystem reads, or subprocesses.
    #[must_use]
    pub fn is_no_discovery_checkpoint(&self) -> bool {
        !self.spawns
            && !self.destructive
            && self.writes.len() == 1
            && matches!(&self.writes[0], Resource::Galaxy(g) if g == "sessions")
    }

    /// Check if this effect row conflicts with another (for parallel execution)
    #[must_use]
    pub fn conflicts_with(&self, other: &Self) -> bool {
        // Write-write conflicts
        for w in &self.writes {
            if other.writes.contains(w) || other.reads.contains(w) {
                return true;
            }
        }
        for w in &other.writes {
            if self.reads.contains(w) {
                return true;
            }
        }
        // Both spawn processes — could overload
        if self.spawns && other.spawns {
            return true;
        }
        false
    }
}

impl fmt::Display for EffectRow {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "reads:{}, writes:{}, invokes:{}, spawns:{}",
            self.reads.len(),
            self.writes.len(),
            self.invokes.len(),
            self.spawns
        )
    }
}

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

    #[test]
    fn pure_effect_has_no_side_effects() {
        let e = EffectRow::pure();
        assert!(e.reads.is_empty());
        assert!(e.writes.is_empty());
        assert!(!e.spawns);
    }

    #[test]
    fn effect_conflict_detection() {
        let writer = EffectRow {
            writes: vec![Resource::Galaxy("citta".into())],
            ..Default::default()
        };
        let reader = EffectRow {
            reads: vec![Resource::Galaxy("citta".into())],
            ..Default::default()
        };
        assert!(writer.conflicts_with(&reader));
        assert!(reader.conflicts_with(&writer));

        let other_reader = EffectRow {
            reads: vec![Resource::Galaxy("codex".into())],
            ..Default::default()
        };
        assert!(!reader.conflicts_with(&other_reader));
    }

    #[test]
    fn brain_wave_filtering() {
        use crate::BrainWave::*;
        let expensive = EffectRow {
            cost: CostEstimate {
                expensive: true,
                ..Default::default()
            },
            ..Default::default()
        };
        assert!(expensive.is_available_in(Gamma));
        assert!(!expensive.is_available_in(Alpha));
        assert!(!expensive.is_available_in(Delta));
    }

    #[test]
    fn sandbox_seam_defaults_and_serializes() {
        let row = EffectRow::pure();
        assert_eq!(row.sandbox, Sandbox::Inherit);

        let scoped = EffectRow {
            sandbox: Sandbox::StoreScoped,
            ..Default::default()
        };
        assert_eq!(scoped.sandbox, Sandbox::StoreScoped);

        // Serialize round-trip, including payloads from before the field
        // existed (serde default keeps old JSON deserializable).
        let json = serde_json::to_string(&scoped).expect("serialize");
        assert!(json.contains("store_scoped"));
        let back: EffectRow = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back.sandbox, Sandbox::StoreScoped);
        let legacy: EffectRow = serde_json::from_str(
            "{\"reads\":[],\"writes\":[],\"invokes\":[],\"spawns\":false,\"destructive\":false,\
             \"cost\":{\"cpu_ns\":0,\"memory_bytes\":0,\"disk_bytes\":0,\"network_bytes\":0,\"expensive\":false}}",
        )
        .expect("legacy payload without sandbox field");
        assert_eq!(legacy.sandbox, Sandbox::Inherit);
    }

    // ── Property-based tests (proptest) ─────────────────────────────

    use crate::BrainWave;
    use proptest::prelude::*;

    fn arb_resource() -> impl Strategy<Value = Resource> {
        prop_oneof![
            Just(Resource::Galaxy("codex".into())),
            Just(Resource::Galaxy("citta".into())),
            Just(Resource::Filesystem),
            Just(Resource::Network),
            Just(Resource::Process),
        ]
    }

    fn arb_effect_row() -> impl Strategy<Value = EffectRow> {
        (
            proptest::collection::vec(arb_resource(), 0..6),
            proptest::collection::vec(arb_resource(), 0..6),
            any::<bool>(),
            any::<bool>(),
        )
            .prop_map(|(reads, writes, spawns, expensive)| EffectRow {
                reads,
                writes,
                spawns,
                cost: CostEstimate {
                    expensive,
                    ..Default::default()
                },
                ..Default::default()
            })
    }

    proptest! {
        /// Delta must always return false (no tools available in Delta).
        #[test]
        fn delta_blocks_all(effects in arb_effect_row()) {
            prop_assert!(!effects.is_available_in(BrainWave::Delta));
        }

        /// Gamma must always return true (all tools available in Gamma).
        #[test]
        fn gamma_allows_all(effects in arb_effect_row()) {
            prop_assert!(effects.is_available_in(BrainWave::Gamma));
        }

        /// Beta must always return true (all tools available in Beta).
        #[test]
        fn beta_allows_all(effects in arb_effect_row()) {
            prop_assert!(effects.is_available_in(BrainWave::Beta));
        }

        /// Alpha blocks writes and expensive tools.
        #[test]
        fn alpha_blocks_writes_and_expensive(effects in arb_effect_row()) {
            let result = effects.is_available_in(BrainWave::Alpha);
            if !effects.writes.is_empty() || effects.cost.expensive {
                prop_assert!(!result, "Alpha should block writes/expensive: {effects}");
            } else {
                prop_assert!(result, "Alpha should allow pure reads: {effects}");
            }
        }

        /// Theta blocks writes, spawns, and expensive tools.
        #[test]
        fn theta_blocks_writes_spawns_expensive(effects in arb_effect_row()) {
            let result = effects.is_available_in(BrainWave::Theta);
            if !effects.writes.is_empty() || effects.cost.expensive || effects.spawns {
                prop_assert!(!result, "Theta should block: {effects}");
            } else {
                prop_assert!(result, "Theta should allow pure reads: {effects}");
            }
        }

        /// conflicts_with is symmetric: a.conflicts_with(b) == b.conflicts_with(a).
        #[test]
        fn conflicts_symmetric(a in arb_effect_row(), b in arb_effect_row()) {
            let ab = a.conflicts_with(&b);
            let ba = b.conflicts_with(&a);
            prop_assert_eq!(ab, ba, "conflicts_with must be symmetric");
        }

        /// conflicts_with is reflexive for effect rows with writes or spawns.
        #[test]
        fn conflicts_self_with_writes_or_spawns(effects in arb_effect_row()) {
            let self_conflict = effects.conflicts_with(&effects);
            if !effects.writes.is_empty() || effects.spawns {
                prop_assert!(self_conflict, "effect row with writes/spawns should conflict with itself");
            } else {
                prop_assert!(!self_conflict, "pure effect row should not conflict with itself");
            }
        }
    }
}