mx 0.1.119

A Swiss army knife for Claude Code and multi-agent toolkits
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
//! Schema-agnostic State Tensor Encoding System
//!
//! Implements the tensor encoding system designed by Schemnya.
//! Values-first: encode dimensional values -> derive nearest mood label.
//!
//! The crewu schema defines 5 dimensions:
//! - temperature (ᚣ): cold/precise <-> warm/playful
//! - entropy (ᚤ): ordered/focused <-> chaotic/wild
//! - agency (ᚡ): receptive/yielding <-> active/driving
//! - connection (ᚢ): distant/separate <-> close/merged
//! - weight (ᚠ): light/floating <-> heavy/grounded

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::Path;

/// A dimension definition in a tensor schema
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TensorDimension {
    /// Unique identifier (e.g., "temperature")
    pub id: String,
    /// Human-readable name
    pub name: String,
    /// Optional decorative rune
    #[serde(default)]
    pub rune: Option<String>,
    /// Anchors for low/mid/high values
    pub anchors: DimensionAnchors,
    /// Default value (0.0-1.0)
    #[serde(default = "default_half")]
    pub default: f32,
}

fn default_half() -> f32 {
    0.5
}

/// Anchor descriptions for a dimension
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DimensionAnchors {
    /// Description for low values (near 0.0)
    pub low: String,
    /// Description for mid values (near 0.5)
    #[serde(default)]
    pub mid: Option<String>,
    /// Description for high values (near 1.0)
    pub high: String,
}

/// A mood definition - a named landmark in the state space
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TensorMood {
    /// Human-readable description
    pub description: String,
    /// Canonical tensor values (positional, matching dimension order)
    pub tensor: Vec<f32>,
    /// Which dimensions matter most for this mood (weights)
    #[serde(default)]
    pub weights: Option<Vec<f32>>,
    /// How far from canonical tensor still counts as this mood
    #[serde(default = "default_tolerance")]
    pub tolerance: f32,
}

fn default_tolerance() -> f32 {
    0.3
}

/// The full tensor schema definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TensorSchema {
    /// Schema identifier (e.g., "crewu")
    pub id: String,
    /// Human-readable name
    pub name: String,
    /// Schema version
    #[serde(default = "default_version")]
    pub version: u32,
    /// Ordered list of dimensions
    pub dimensions: Vec<TensorDimension>,
    /// Named moods (landmarks in the space)
    #[serde(default)]
    pub moods: HashMap<String, TensorMood>,
}

fn default_version() -> u32 {
    1
}

impl TensorSchema {
    /// Load schema from a YAML file
    pub fn load(path: &Path) -> Result<Self> {
        let content = fs::read_to_string(path)
            .with_context(|| format!("Failed to read schema file: {:?}", path))?;

        // Try YAML first, fall back to JSON
        serde_yaml::from_str(&content)
            .or_else(|_| serde_json::from_str(&content))
            .with_context(|| format!("Failed to parse schema: {:?}", path))
    }

    /// Load schema by ID from standard locations
    pub fn load_by_id(schema_id: &str) -> Result<Self> {
        // Check env var first
        if let Ok(schema_path) = std::env::var("MX_STATE_SCHEMA") {
            let path = std::path::PathBuf::from(&schema_path);
            if path.exists() {
                let schema = Self::load(&path)?;
                if schema.id == schema_id {
                    return Ok(schema);
                }
            }
        }

        // Check $MX_HOME/schemas/{id}.yaml
        let schemas_dir = crate::paths::schemas_dir();
        let yaml_path = schemas_dir.join(format!("{}.yaml", schema_id));
        if yaml_path.exists() {
            return Self::load(&yaml_path);
        }

        let json_path = schemas_dir.join(format!("{}.json", schema_id));
        if json_path.exists() {
            return Self::load(&json_path);
        }

        bail!(
            "Schema '{}' not found in {}",
            schema_id,
            schemas_dir.display()
        )
    }

    /// Load default schema (from MX_STATE_SCHEMA or crewu)
    pub fn load_default() -> Result<Self> {
        // Check MX_STATE_SCHEMA env var
        if let Ok(schema_path) = std::env::var("MX_STATE_SCHEMA") {
            let path = std::path::PathBuf::from(&schema_path);
            if path.exists() {
                return Self::load(&path);
            }
        }

        // Try crewu as default
        Self::load_by_id("crewu")
    }

    /// List available schemas in $MX_HOME/schemas/
    pub fn list_available() -> Result<Vec<String>> {
        let mut schemas = Vec::new();

        let schemas_dir = crate::paths::schemas_dir();
        if schemas_dir.exists() {
            for entry in fs::read_dir(&schemas_dir)? {
                let entry = entry?;
                let path = entry.path();
                if let Some(ext) = path.extension()
                    && (ext == "yaml" || ext == "yml" || ext == "json")
                    && let Some(stem) = path.file_stem()
                {
                    schemas.push(stem.to_string_lossy().to_string());
                }
            }
        }

        schemas.sort();
        schemas.dedup();
        Ok(schemas)
    }

    /// Get dimension by index
    pub fn dimension(&self, index: usize) -> Option<&TensorDimension> {
        self.dimensions.get(index)
    }

    /// Get dimension by ID
    pub fn dimension_by_id(&self, id: &str) -> Option<(usize, &TensorDimension)> {
        self.dimensions.iter().enumerate().find(|(_, d)| d.id == id)
    }

    /// Number of dimensions
    pub fn dimension_count(&self) -> usize {
        self.dimensions.len()
    }
}

/// An encoded state tensor
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateTensor {
    /// Schema ID this tensor belongs to
    pub schema_id: String,
    /// Values for each dimension (positional)
    pub values: Vec<f32>,
}

impl StateTensor {
    /// Create a new state tensor with explicit values
    pub fn new(schema_id: String, values: Vec<f32>) -> Self {
        Self { schema_id, values }
    }

    /// Create a state tensor with default values from schema
    pub fn default_from_schema(schema: &TensorSchema) -> Self {
        let values: Vec<f32> = schema.dimensions.iter().map(|d| d.default).collect();
        Self {
            schema_id: schema.id.clone(),
            values,
        }
    }

    /// Parse values from a pipe-separated string
    /// Format: "0.3|0.2|0.7|0.8|0.4"
    pub fn parse_values(schema: &TensorSchema, input: &str) -> Result<Self> {
        let parts: Vec<&str> = input.split('|').collect();

        if parts.len() != schema.dimension_count() {
            bail!(
                "Expected {} values for schema '{}', got {}",
                schema.dimension_count(),
                schema.id,
                parts.len()
            );
        }

        let mut values = Vec::with_capacity(parts.len());
        for (i, part) in parts.iter().enumerate() {
            let dim = &schema.dimensions[i];
            let value: f32 = part
                .trim()
                .parse()
                .with_context(|| format!("Invalid value for dimension '{}': {}", dim.id, part))?;

            // Clamp to 0.0-1.0 range
            values.push(value.clamp(0.0, 1.0));
        }

        Ok(Self {
            schema_id: schema.id.clone(),
            values,
        })
    }

    /// Parse named dimension values from a space-separated string
    /// Format: "temp=0.8 entropy=0.75 agency=0.4 connection=0.9 weight=0.6"
    /// Dimension names can be abbreviated (matches prefix of dimension ID)
    pub fn parse_named_dimensions(schema: &TensorSchema, input: &str) -> Result<Self> {
        use std::collections::HashMap;

        // Parse the key=value pairs
        let mut named_values: HashMap<String, f32> = HashMap::new();
        for part in input.split_whitespace() {
            let kv: Vec<&str> = part.split('=').collect();
            if kv.len() != 2 {
                bail!("Invalid dimension format '{}'. Expected 'name=value'", part);
            }

            let name = kv[0].trim().to_lowercase();
            let value: f32 = kv[1]
                .trim()
                .parse()
                .with_context(|| format!("Invalid value for dimension '{}': {}", name, kv[1]))?;

            named_values.insert(name, value.clamp(0.0, 1.0));
        }

        // Match named values to schema dimensions (support abbreviations)
        let mut values = Vec::with_capacity(schema.dimensions.len());
        for dim in &schema.dimensions {
            let dim_id_lower = dim.id.to_lowercase();

            // Try exact match first
            let value = if let Some(&v) = named_values.get(&dim_id_lower) {
                v
            } else {
                // Try prefix match
                let prefix_match = named_values
                    .iter()
                    .find(|(k, _)| dim_id_lower.starts_with(k.as_str()))
                    .map(|(_, &v)| v);

                match prefix_match {
                    Some(v) => v,
                    None => bail!(
                        "No value provided for dimension '{}'. Available: {}",
                        dim.id,
                        schema
                            .dimensions
                            .iter()
                            .map(|d| &d.id)
                            .cloned()
                            .collect::<Vec<_>>()
                            .join(", ")
                    ),
                }
            };

            values.push(value);
        }

        Ok(Self {
            schema_id: schema.id.clone(),
            values,
        })
    }

    /// Encode to the standard string format
    /// Format: @state:crewu|0.3|0.2|0.7|0.8|0.4
    pub fn encode(&self) -> String {
        let values_str: Vec<String> = self.values.iter().map(|v| format!("{:.2}", v)).collect();
        format!("@state:{}|{}", self.schema_id, values_str.join("|"))
    }

    /// Encode with optional rune decoration
    /// Format: @state:crewu|ᚣ0.30|ᚤ0.20|ᚡ0.70|ᚢ0.80|ᚠ0.40
    pub fn encode_with_runes(&self, schema: &TensorSchema) -> String {
        let parts: Vec<String> = self
            .values
            .iter()
            .enumerate()
            .map(|(i, v)| {
                let rune = schema
                    .dimensions
                    .get(i)
                    .and_then(|d| d.rune.as_ref())
                    .map(|r| r.as_str())
                    .unwrap_or("");
                format!("{}{:.2}", rune, v)
            })
            .collect();
        format!("@state:{}|{}", self.schema_id, parts.join("|"))
    }

    /// Decode from standard string format
    pub fn decode(input: &str) -> Result<Self> {
        let input = input.trim();

        if !input.starts_with("@state:") {
            bail!("Invalid tensor format: must start with @state:");
        }

        let rest = &input[7..]; // Skip "@state:"
        let parts: Vec<&str> = rest.split('|').collect();

        if parts.is_empty() {
            bail!("Invalid tensor format: missing schema ID");
        }

        let schema_id = parts[0].to_string();

        let mut values = Vec::with_capacity(parts.len() - 1);
        for part in parts.iter().skip(1) {
            // Strip any rune prefix (non-digit, non-dot characters)
            let value_str: String = part
                .chars()
                .skip_while(|c| !c.is_ascii_digit() && *c != '.' && *c != '-')
                .collect();

            let value: f32 = value_str
                .parse()
                .with_context(|| format!("Invalid value: {}", part))?;
            values.push(value.clamp(0.0, 1.0));
        }

        Ok(Self { schema_id, values })
    }

    /// Calculate weighted Euclidean distance to a mood
    pub fn distance_to_mood(&self, mood: &TensorMood) -> f32 {
        if self.values.len() != mood.tensor.len() {
            return f32::MAX;
        }

        let weights = mood.weights.as_ref();

        let sum: f32 = self
            .values
            .iter()
            .zip(mood.tensor.iter())
            .enumerate()
            .map(|(i, (v1, v2))| {
                let weight = weights.and_then(|w| w.get(i)).copied().unwrap_or(1.0);
                weight * (v1 - v2).powi(2)
            })
            .sum();

        sum.sqrt()
    }

    /// Find the nearest mood within tolerance
    pub fn nearest_mood<'a>(
        &self,
        schema: &'a TensorSchema,
    ) -> Option<(&'a str, &'a TensorMood, f32)> {
        let mut nearest: Option<(&str, &TensorMood, f32)> = None;

        for (name, mood) in &schema.moods {
            let distance = self.distance_to_mood(mood);

            if distance <= mood.tolerance {
                match &nearest {
                    None => nearest = Some((name.as_str(), mood, distance)),
                    Some((_, _, prev_dist)) if distance < *prev_dist => {
                        nearest = Some((name.as_str(), mood, distance));
                    }
                    _ => {}
                }
            }
        }

        nearest
    }

    /// Generate a human-readable description
    pub fn describe(&self, schema: &TensorSchema) -> String {
        let mut parts = Vec::new();

        for (i, value) in self.values.iter().enumerate() {
            if let Some(dim) = schema.dimensions.get(i) {
                let anchor_desc = if *value < 0.33 {
                    &dim.anchors.low
                } else if *value > 0.66 {
                    &dim.anchors.high
                } else {
                    dim.anchors.mid.as_ref().unwrap_or(&dim.anchors.low)
                };
                parts.push(format!("{}: {:.2} ({})", dim.name, value, anchor_desc));
            }
        }

        parts.join(", ")
    }

    /// Format as self-documenting bootstrap output
    /// Returns a multi-line string ready for session bootstrap:
    /// - Line 1: Wake State with rune-encoded stele
    /// - Line 2: Rune legend showing dimension mapping
    /// - Line 3: Empty line
    /// - Line 4: Human-readable description with interpolated anchors
    pub fn format_bootstrap(&self, schema: &TensorSchema) -> Result<String> {
        use std::fmt::Write;

        let mut output = String::new();

        // Line 1: Wake State with rune-encoded stele
        writeln!(
            &mut output,
            "Wake State: {}",
            self.encode_with_runes(schema)
        )?;

        // Line 2: Rune legend
        let legend_parts: Vec<String> = schema
            .dimensions
            .iter()
            .filter_map(|dim| dim.rune.as_ref().map(|rune| format!("{}={}", rune, dim.id)))
            .collect();

        if !legend_parts.is_empty() {
            writeln!(&mut output, "({})", legend_parts.join(", "))?;
        }

        // Line 3: Empty line
        writeln!(&mut output)?;

        // Line 4: Human-readable description with interpolated anchors
        let desc_parts: Vec<String> = self
            .values
            .iter()
            .enumerate()
            .filter_map(|(i, value)| {
                schema.dimensions.get(i).map(|dim| {
                    // Interpolate between low, mid, and high anchors
                    let anchor_desc = self.interpolate_anchor_description(dim, *value);
                    format!("{} ({:.1})", anchor_desc, value)
                })
            })
            .collect();

        write!(&mut output, "{}.", desc_parts.join(", "))?;

        Ok(output)
    }

    /// Interpolate anchor description based on value
    /// Returns a human-readable description interpolated from the schema's anchors
    fn interpolate_anchor_description(&self, dim: &TensorDimension, value: f32) -> String {
        // Get anchor descriptions
        let low = &dim.anchors.low;
        let high = &dim.anchors.high;

        // For values < 0.33: use low anchor
        // For values > 0.66: use high anchor
        // For values 0.33-0.66: use mid anchor or "moderately {high}"
        if value < 0.33 {
            low.clone()
        } else if value > 0.66 {
            high.clone()
        } else {
            // Middle range - use mid anchor if available, otherwise blend
            if let Some(mid) = &dim.anchors.mid {
                mid.clone()
            } else {
                // Blend toward high if > 0.5, toward low if < 0.5
                if value > 0.5 {
                    format!("moderately {}", high)
                } else {
                    format!("moderately {}", low)
                }
            }
        }
    }

    /// Get value for a dimension by ID
    pub fn get(&self, schema: &TensorSchema, dim_id: &str) -> Option<f32> {
        schema
            .dimension_by_id(dim_id)
            .and_then(|(idx, _)| self.values.get(idx))
            .copied()
    }

    /// Set value for a dimension by ID
    pub fn set(&mut self, schema: &TensorSchema, dim_id: &str, value: f32) -> Result<()> {
        let (idx, _) = schema
            .dimension_by_id(dim_id)
            .ok_or_else(|| anyhow::anyhow!("Unknown dimension: {}", dim_id))?;

        if idx < self.values.len() {
            self.values[idx] = value.clamp(0.0, 1.0);
        }

        Ok(())
    }
}

/// Interactive guided state capture
pub fn guided_capture(schema: &TensorSchema) -> Result<StateTensor> {
    use std::io::{self, Write};

    println!("\n{} ({})\n", schema.name, schema.id);
    println!("Enter values 0.0-1.0 for each dimension.\n");

    let mut values = Vec::with_capacity(schema.dimensions.len());

    for dim in &schema.dimensions {
        let rune = dim
            .rune
            .as_ref()
            .map(|r| format!("{} ", r))
            .unwrap_or_default();

        println!("{}{}:", rune, dim.name);
        println!("  Low (0.0): {}", dim.anchors.low);
        if let Some(mid) = &dim.anchors.mid {
            println!("  Mid (0.5): {}", mid);
        }
        println!("  High (1.0): {}", dim.anchors.high);
        println!("  Default: {:.2}", dim.default);

        print!("> ");
        io::stdout().flush()?;

        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        let input = input.trim();

        let value: f32 = if input.is_empty() {
            dim.default
        } else {
            input
                .parse()
                .with_context(|| format!("Invalid number: {}", input))?
        };

        values.push(value.clamp(0.0, 1.0));
        println!();
    }

    Ok(StateTensor {
        schema_id: schema.id.clone(),
        values,
    })
}

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

    fn test_schema() -> TensorSchema {
        TensorSchema {
            id: "test".to_string(),
            name: "Test Schema".to_string(),
            version: 1,
            dimensions: vec![
                TensorDimension {
                    id: "dim1".to_string(),
                    name: "Dimension 1".to_string(),
                    rune: Some("A".to_string()),
                    anchors: DimensionAnchors {
                        low: "low1".to_string(),
                        mid: Some("mid1".to_string()),
                        high: "high1".to_string(),
                    },
                    default: 0.5,
                },
                TensorDimension {
                    id: "dim2".to_string(),
                    name: "Dimension 2".to_string(),
                    rune: Some("B".to_string()),
                    anchors: DimensionAnchors {
                        low: "low2".to_string(),
                        mid: None,
                        high: "high2".to_string(),
                    },
                    default: 0.5,
                },
            ],
            moods: HashMap::from([
                (
                    "calm".to_string(),
                    TensorMood {
                        description: "Calm state".to_string(),
                        tensor: vec![0.2, 0.3],
                        weights: Some(vec![1.0, 0.8]),
                        tolerance: 0.3,
                    },
                ),
                (
                    "excited".to_string(),
                    TensorMood {
                        description: "Excited state".to_string(),
                        tensor: vec![0.8, 0.9],
                        weights: Some(vec![0.9, 1.0]),
                        tolerance: 0.3,
                    },
                ),
            ]),
        }
    }

    #[test]
    fn test_parse_values() {
        let schema = test_schema();
        let tensor = StateTensor::parse_values(&schema, "0.3|0.7").unwrap();

        assert_eq!(tensor.schema_id, "test");
        assert_eq!(tensor.values.len(), 2);
        assert!((tensor.values[0] - 0.3).abs() < 0.01);
        assert!((tensor.values[1] - 0.7).abs() < 0.01);
    }

    #[test]
    fn test_encode_decode_roundtrip() {
        let tensor = StateTensor::new("crewu".to_string(), vec![0.3, 0.2, 0.7, 0.8, 0.4]);
        let encoded = tensor.encode();

        assert!(encoded.starts_with("@state:crewu|"));

        let decoded = StateTensor::decode(&encoded).unwrap();
        assert_eq!(decoded.schema_id, "crewu");
        assert_eq!(decoded.values.len(), 5);

        for (a, b) in tensor.values.iter().zip(decoded.values.iter()) {
            assert!((a - b).abs() < 0.01);
        }
    }

    #[test]
    fn test_nearest_mood() {
        let schema = test_schema();
        let tensor = StateTensor::new("test".to_string(), vec![0.25, 0.35]);

        let (name, _, distance) = tensor.nearest_mood(&schema).unwrap();
        assert_eq!(name, "calm");
        assert!(distance < 0.3);
    }

    #[test]
    fn test_distance_with_weights() {
        let schema = test_schema();

        // Close to calm but with different dimensions
        let tensor1 = StateTensor::new("test".to_string(), vec![0.2, 0.5]);
        let tensor2 = StateTensor::new("test".to_string(), vec![0.4, 0.3]);

        let calm = schema.moods.get("calm").unwrap();
        let dist1 = tensor1.distance_to_mood(calm);
        let dist2 = tensor2.distance_to_mood(calm);

        // tensor1 should be closer because dim2 has lower weight (0.8 vs 1.0)
        assert!(dist1 < dist2);
    }

    #[test]
    fn test_parse_named_dimensions() {
        let schema = test_schema();

        // Test full names
        let tensor = StateTensor::parse_named_dimensions(&schema, "dim1=0.3 dim2=0.7").unwrap();
        assert_eq!(tensor.schema_id, "test");
        assert_eq!(tensor.values.len(), 2);
        assert!((tensor.values[0] - 0.3).abs() < 0.01);
        assert!((tensor.values[1] - 0.7).abs() < 0.01);

        // Test case insensitivity
        let tensor2 = StateTensor::parse_named_dimensions(&schema, "DIM1=0.4 DIM2=0.8").unwrap();
        assert!((tensor2.values[0] - 0.4).abs() < 0.01);
        assert!((tensor2.values[1] - 0.8).abs() < 0.01);

        // Test abbreviations (prefix match)
        let tensor3 = StateTensor::parse_named_dimensions(&schema, "d=0.5 dim2=0.6").unwrap();
        assert!((tensor3.values[0] - 0.5).abs() < 0.01);
        assert!((tensor3.values[1] - 0.6).abs() < 0.01);
    }

    #[test]
    fn test_parse_named_dimensions_missing() {
        let schema = test_schema();

        // Should error when dimension is missing
        let result = StateTensor::parse_named_dimensions(&schema, "dim1=0.3");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("No value provided for dimension 'dim2'")
        );
    }

    #[test]
    fn test_format_bootstrap() {
        let schema = test_schema();
        let tensor = StateTensor::new("test".to_string(), vec![0.8, 0.2]);

        let output = tensor.format_bootstrap(&schema).unwrap();

        // Should contain Wake State line
        assert!(output.contains("Wake State:"));
        // Should contain rune-encoded tensor
        assert!(output.contains("@state:test"));
        // Should contain legend
        assert!(output.contains("A=dim1"));
        assert!(output.contains("B=dim2"));
        // Should contain human-readable descriptions
        assert!(output.contains("high1"));
        assert!(output.contains("low2"));
    }

    #[test]
    fn test_interpolate_anchor_description() {
        let dim = TensorDimension {
            id: "test".to_string(),
            name: "Test".to_string(),
            rune: None,
            anchors: DimensionAnchors {
                low: "cold".to_string(),
                mid: Some("balanced".to_string()),
                high: "hot".to_string(),
            },
            default: 0.5,
        };

        let tensor = StateTensor::new("test".to_string(), vec![0.0]);

        // Low value
        assert_eq!(tensor.interpolate_anchor_description(&dim, 0.2), "cold");

        // High value
        assert_eq!(tensor.interpolate_anchor_description(&dim, 0.8), "hot");

        // Mid value with mid anchor
        assert_eq!(tensor.interpolate_anchor_description(&dim, 0.5), "balanced");

        // Mid value without mid anchor
        let dim_no_mid = TensorDimension {
            id: "test".to_string(),
            name: "Test".to_string(),
            rune: None,
            anchors: DimensionAnchors {
                low: "cold".to_string(),
                mid: None,
                high: "hot".to_string(),
            },
            default: 0.5,
        };

        assert_eq!(
            tensor.interpolate_anchor_description(&dim_no_mid, 0.6),
            "moderately hot"
        );
        assert_eq!(
            tensor.interpolate_anchor_description(&dim_no_mid, 0.4),
            "moderately cold"
        );
    }
}