attuned-infer 1.0.0

Fast, transparent inference of human state axes from natural language
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
//! Delta analysis for detecting deviation from baseline behavior.
//!
//! Instead of asking "who is this person?", delta analysis asks
//! "how is this person different right now than usual?"
//!
//! This catches transient states (stress, urgency, frustration) without
//! needing to model stable personality traits.

use crate::features::LinguisticFeatures;
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;

/// Signals derived from deviation analysis.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct DeltaSignals {
    /// Z-score for message length (positive = longer than usual).
    pub length_z: f32,
    /// Z-score for complexity (positive = more complex than usual).
    pub complexity_z: f32,
    /// Z-score for emotional intensity.
    pub emotional_z: f32,
    /// Z-score for formality.
    pub formality_z: f32,
    /// Z-score for urgency indicators.
    pub urgency_z: f32,
    /// Z-score for uncertainty/hedging.
    pub uncertainty_z: f32,
    /// Number of messages in the baseline.
    pub baseline_size: usize,
}

impl DeltaSignals {
    /// Check if any signal is significantly elevated (|z| > threshold).
    pub fn has_significant_deviation(&self, threshold: f32) -> bool {
        self.length_z.abs() > threshold
            || self.complexity_z.abs() > threshold
            || self.emotional_z.abs() > threshold
            || self.formality_z.abs() > threshold
            || self.urgency_z.abs() > threshold
            || self.uncertainty_z.abs() > threshold
    }

    /// Get the most extreme deviation.
    pub fn max_deviation(&self) -> (&'static str, f32) {
        let signals = [
            ("length", self.length_z),
            ("complexity", self.complexity_z),
            ("emotional", self.emotional_z),
            ("formality", self.formality_z),
            ("urgency", self.urgency_z),
            ("uncertainty", self.uncertainty_z),
        ];

        signals
            .into_iter()
            .max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap())
            .unwrap_or(("none", 0.0))
    }
}

/// Running statistics for a single metric.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
struct RunningStat {
    count: usize,
    mean: f64,
    m2: f64, // For Welford's algorithm
}

impl RunningStat {
    fn new() -> Self {
        Self::default()
    }

    /// Update with a new value using Welford's online algorithm.
    fn update(&mut self, value: f64) {
        self.count += 1;
        let delta = value - self.mean;
        self.mean += delta / self.count as f64;
        let delta2 = value - self.mean;
        self.m2 += delta * delta2;
    }

    /// Remove an old value (approximate - assumes FIFO).
    fn remove(&mut self, value: f64) {
        if self.count <= 1 {
            *self = Self::new();
            return;
        }

        // Inverse Welford (approximate)
        let delta = value - self.mean;
        self.mean = (self.mean * self.count as f64 - value) / (self.count - 1) as f64;
        let delta2 = value - self.mean;
        self.m2 -= delta * delta2;
        self.m2 = self.m2.max(0.0); // Numerical stability
        self.count -= 1;
    }

    /// Get current variance.
    fn variance(&self) -> f64 {
        if self.count < 2 {
            return 1.0; // High uncertainty with few samples
        }
        (self.m2 / (self.count - 1) as f64).max(0.001)
    }

    /// Get standard deviation.
    fn std_dev(&self) -> f64 {
        self.variance().sqrt()
    }

    /// Calculate z-score for a new value.
    fn z_score(&self, value: f64) -> f64 {
        if self.count < 3 {
            return 0.0; // Not enough data
        }
        (value - self.mean) / self.std_dev()
    }
}

/// A point in the baseline history.
#[derive(Clone, Debug, Serialize, Deserialize)]
struct BaselinePoint {
    length: f64,
    complexity: f64,
    emotional: f64,
    formality: f64,
    urgency: f64,
    uncertainty: f64,
}

impl From<&LinguisticFeatures> for BaselinePoint {
    fn from(f: &LinguisticFeatures) -> Self {
        Self {
            length: f.word_count as f64,
            complexity: f.complexity_score() as f64,
            emotional: f.emotional_intensity() as f64,
            formality: f.formality_score() as f64,
            urgency: f.urgency_score() as f64,
            uncertainty: f.uncertainty_score() as f64,
        }
    }
}

/// Baseline statistics for a user.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Baseline {
    /// Maximum number of messages to track.
    max_size: usize,
    /// Historical values (FIFO queue).
    history: VecDeque<BaselinePoint>,
    /// Running statistics for each metric.
    length_stat: RunningStat,
    complexity_stat: RunningStat,
    emotional_stat: RunningStat,
    formality_stat: RunningStat,
    urgency_stat: RunningStat,
    uncertainty_stat: RunningStat,
}

impl Baseline {
    /// Create a new baseline tracker.
    pub fn new(max_size: usize) -> Self {
        Self {
            max_size,
            history: VecDeque::with_capacity(max_size),
            length_stat: RunningStat::new(),
            complexity_stat: RunningStat::new(),
            emotional_stat: RunningStat::new(),
            formality_stat: RunningStat::new(),
            urgency_stat: RunningStat::new(),
            uncertainty_stat: RunningStat::new(),
        }
    }

    /// Add a new message to the baseline.
    pub fn add(&mut self, features: &LinguisticFeatures) {
        let point = BaselinePoint::from(features);

        // If at capacity, remove oldest
        if self.history.len() >= self.max_size {
            if let Some(old) = self.history.pop_front() {
                self.length_stat.remove(old.length);
                self.complexity_stat.remove(old.complexity);
                self.emotional_stat.remove(old.emotional);
                self.formality_stat.remove(old.formality);
                self.urgency_stat.remove(old.urgency);
                self.uncertainty_stat.remove(old.uncertainty);
            }
        }

        // Update running statistics
        self.length_stat.update(point.length);
        self.complexity_stat.update(point.complexity);
        self.emotional_stat.update(point.emotional);
        self.formality_stat.update(point.formality);
        self.urgency_stat.update(point.urgency);
        self.uncertainty_stat.update(point.uncertainty);

        self.history.push_back(point);
    }

    /// Number of messages in the baseline.
    pub fn len(&self) -> usize {
        self.history.len()
    }

    /// Check if baseline is empty.
    pub fn is_empty(&self) -> bool {
        self.history.is_empty()
    }

    /// Check if we have enough data for meaningful analysis.
    pub fn is_ready(&self) -> bool {
        self.history.len() >= 5 // Need at least 5 messages
    }

    /// Get baseline mean for message length.
    pub fn mean_length(&self) -> f64 {
        self.length_stat.mean
    }

    /// Get baseline mean for complexity.
    pub fn mean_complexity(&self) -> f64 {
        self.complexity_stat.mean
    }
}

impl Default for Baseline {
    fn default() -> Self {
        Self::new(50) // Default to 50-message window
    }
}

/// Delta analyzer for detecting deviations from baseline.
#[derive(Clone, Debug, Default)]
pub struct DeltaAnalyzer {
    /// Z-score threshold for significance.
    pub significance_threshold: f32,
}

impl DeltaAnalyzer {
    /// Create a new analyzer.
    pub fn new() -> Self {
        Self {
            significance_threshold: 1.5, // ~13% of distribution
        }
    }

    /// Create analyzer with custom threshold.
    pub fn with_threshold(threshold: f32) -> Self {
        Self {
            significance_threshold: threshold,
        }
    }

    /// Analyze a message against the baseline.
    ///
    /// Returns delta signals (z-scores) for each metric.
    /// Positive z-score = higher than usual, negative = lower than usual.
    pub fn analyze(&self, baseline: &Baseline, features: &LinguisticFeatures) -> DeltaSignals {
        if !baseline.is_ready() {
            return DeltaSignals {
                baseline_size: baseline.len(),
                ..Default::default()
            };
        }

        let point = BaselinePoint::from(features);

        DeltaSignals {
            length_z: baseline.length_stat.z_score(point.length) as f32,
            complexity_z: baseline.complexity_stat.z_score(point.complexity) as f32,
            emotional_z: baseline.emotional_stat.z_score(point.emotional) as f32,
            formality_z: baseline.formality_stat.z_score(point.formality) as f32,
            urgency_z: baseline.urgency_stat.z_score(point.urgency) as f32,
            uncertainty_z: baseline.uncertainty_stat.z_score(point.uncertainty) as f32,
            baseline_size: baseline.len(),
        }
    }

    /// Analyze and update baseline in one step.
    ///
    /// Analyzes against current baseline, then adds to baseline.
    pub fn analyze_and_update(
        &self,
        baseline: &mut Baseline,
        features: &LinguisticFeatures,
    ) -> DeltaSignals {
        let signals = self.analyze(baseline, features);
        baseline.add(features);
        signals
    }

    /// Map delta signals to axis adjustments.
    ///
    /// Returns (axis_name, adjustment) pairs where adjustment is in [-0.3, 0.3].
    pub fn to_axis_adjustments(&self, signals: &DeltaSignals) -> Vec<(&'static str, f32)> {
        let mut adjustments = Vec::new();

        // Helper to convert z-score to bounded adjustment
        let z_to_adj = |z: f32| -> f32 {
            // Sigmoid-like mapping: z=2 → ~0.2, z=3 → ~0.27
            (z / (1.0 + z.abs()) * 0.3).clamp(-0.3, 0.3)
        };

        // Length deviation → cognitive_load (shorter = higher load)
        if signals.length_z.abs() > self.significance_threshold {
            adjustments.push(("cognitive_load", z_to_adj(-signals.length_z)));
        }

        // Complexity deviation
        if signals.complexity_z.abs() > self.significance_threshold {
            adjustments.push(("tolerance_for_complexity", z_to_adj(signals.complexity_z)));
        }

        // Emotional intensity deviation
        if signals.emotional_z.abs() > self.significance_threshold {
            adjustments.push(("emotional_intensity", z_to_adj(signals.emotional_z)));
            // High emotional intensity often correlates with low stability
            adjustments.push(("emotional_stability", z_to_adj(-signals.emotional_z * 0.5)));
        }

        // Formality deviation
        if signals.formality_z.abs() > self.significance_threshold {
            adjustments.push(("formality", z_to_adj(signals.formality_z)));
        }

        // Urgency deviation
        if signals.urgency_z.abs() > self.significance_threshold {
            adjustments.push(("urgency_sensitivity", z_to_adj(signals.urgency_z)));
        }

        // Uncertainty deviation
        if signals.uncertainty_z.abs() > self.significance_threshold {
            adjustments.push(("anxiety_level", z_to_adj(signals.uncertainty_z)));
            adjustments.push(("assertiveness", z_to_adj(-signals.uncertainty_z)));
        }

        adjustments
    }
}

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

    fn make_features(text: &str) -> LinguisticFeatures {
        LinguisticExtractor::new().extract(text)
    }

    #[test]
    fn test_baseline_building() {
        let mut baseline = Baseline::new(10);

        for _ in 0..5 {
            baseline.add(&make_features("This is a normal message."));
        }

        assert_eq!(baseline.len(), 5);
        assert!(baseline.is_ready());
    }

    #[test]
    fn test_baseline_fifo() {
        let mut baseline = Baseline::new(3);

        baseline.add(&make_features("Message one."));
        baseline.add(&make_features("Message two."));
        baseline.add(&make_features("Message three."));
        baseline.add(&make_features("Message four.")); // Should evict first

        assert_eq!(baseline.len(), 3);
    }

    #[test]
    fn test_detect_urgency_spike() {
        let mut baseline = Baseline::default();
        let analyzer = DeltaAnalyzer::new();

        // Build baseline with calm messages
        for _ in 0..10 {
            baseline.add(&make_features(
                "Here is my regular question about the product.",
            ));
        }

        // Analyze urgent message
        let urgent = make_features("URGENT!!! I need help RIGHT NOW! This is critical!!!");
        let signals = analyzer.analyze(&baseline, &urgent);

        // Should detect elevated urgency and emotional intensity
        assert!(signals.urgency_z > 1.0);
        assert!(signals.emotional_z > 1.0);
    }

    #[test]
    fn test_detect_terseness() {
        let mut baseline = Baseline::default();
        let analyzer = DeltaAnalyzer::new();

        // Build baseline with longer messages
        for _ in 0..10 {
            baseline.add(&make_features(
                "I wanted to ask about the features of your product and understand \
                 how it might help with my specific use case in data processing.",
            ));
        }

        // Analyze terse message
        let terse = make_features("ok");
        let signals = analyzer.analyze(&baseline, &terse);

        // Should detect shortened length
        assert!(signals.length_z < -1.0);
    }

    #[test]
    fn test_not_enough_baseline() {
        let baseline = Baseline::default();
        let analyzer = DeltaAnalyzer::new();

        let features = make_features("Hello world");
        let signals = analyzer.analyze(&baseline, &features);

        // Should return zeros when not enough data
        assert_eq!(signals.length_z, 0.0);
        assert!(!baseline.is_ready());
    }

    #[test]
    fn test_axis_adjustments() {
        let analyzer = DeltaAnalyzer::new();

        let signals = DeltaSignals {
            urgency_z: 2.5,
            emotional_z: 0.5, // Below threshold
            ..Default::default()
        };

        let adjustments = analyzer.to_axis_adjustments(&signals);

        // Should have urgency adjustment
        assert!(adjustments
            .iter()
            .any(|(axis, _)| *axis == "urgency_sensitivity"));
        // Should not have emotional adjustment (below threshold)
        assert!(!adjustments
            .iter()
            .any(|(axis, _)| *axis == "emotional_intensity"));
    }

    #[test]
    fn test_max_deviation() {
        let signals = DeltaSignals {
            length_z: 0.5,
            urgency_z: 3.0,
            emotional_z: -2.0,
            ..Default::default()
        };

        let (metric, z) = signals.max_deviation();
        assert_eq!(metric, "urgency");
        assert_eq!(z, 3.0);
    }
}