attuned-http 1.0.1

HTTP reference server for Attuned
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
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
//! HTTP request handlers.

use attuned_core::{
    HealthCheck, HealthState, HealthStatus, PromptContext, RuleTranslator, Source, StateSnapshot,
    Translator,
};
use attuned_store::StateStore;
use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::IntoResponse,
    Json,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::Instant;

#[cfg(feature = "inference")]
use attuned_infer::{Baseline, InferenceConfig, InferenceEngine, InferenceSource};
#[cfg(feature = "inference")]
use dashmap::DashMap;
#[cfg(feature = "inference")]
use std::collections::HashMap;

/// Application state shared across handlers.
pub struct AppState<S: StateStore> {
    /// The state store backend.
    pub store: Arc<S>,
    /// The translator for converting state to context.
    pub translator: Arc<dyn Translator>,
    /// Server start time for uptime calculation.
    pub start_time: Instant,
    /// Inference engine (optional, requires "inference" feature).
    #[cfg(feature = "inference")]
    pub inference_engine: Option<InferenceEngine>,
    /// Per-user baselines for delta analysis.
    #[cfg(feature = "inference")]
    pub baselines: Arc<DashMap<String, Baseline>>,
}

impl<S: StateStore> AppState<S> {
    /// Create new application state.
    pub fn new(store: S) -> Self {
        Self {
            store: Arc::new(store),
            translator: Arc::new(RuleTranslator::default()),
            start_time: Instant::now(),
            #[cfg(feature = "inference")]
            inference_engine: None,
            #[cfg(feature = "inference")]
            baselines: Arc::new(DashMap::new()),
        }
    }

    /// Create application state with inference enabled.
    #[cfg(feature = "inference")]
    pub fn with_inference(store: S, config: Option<InferenceConfig>) -> Self {
        let engine = match config {
            Some(c) => InferenceEngine::with_config(c),
            None => InferenceEngine::default(),
        };
        Self {
            store: Arc::new(store),
            translator: Arc::new(RuleTranslator::default()),
            start_time: Instant::now(),
            inference_engine: Some(engine),
            baselines: Arc::new(DashMap::new()),
        }
    }
}

/// Request body for upserting state.
#[derive(Debug, Deserialize)]
pub struct UpsertStateRequest {
    /// User ID to update state for.
    pub user_id: String,
    /// Source of the state data.
    #[serde(default)]
    pub source: SourceInput,
    /// Confidence level of the state data.
    #[serde(default = "default_confidence")]
    pub confidence: f32,
    /// Axis values to set.
    pub axes: std::collections::BTreeMap<String, f32>,
    /// Optional message text for inference (requires "inference" feature).
    /// When provided, axes are inferred from the message and merged with explicit axes.
    /// Explicit axes always override inferred values.
    #[serde(default)]
    pub message: Option<String>,
}

fn default_confidence() -> f32 {
    1.0
}

/// Source of state data in API requests.
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SourceInput {
    /// User explicitly provided this state.
    #[default]
    SelfReport,
    /// State was inferred from behavior.
    Inferred,
    /// Combination of self-report and inference.
    Mixed,
}

impl From<SourceInput> for Source {
    fn from(s: SourceInput) -> Self {
        match s {
            SourceInput::SelfReport => Source::SelfReport,
            SourceInput::Inferred => Source::Inferred,
            SourceInput::Mixed => Source::Mixed,
        }
    }
}

/// Response for state operations.
#[derive(Debug, Serialize)]
pub struct StateResponse {
    /// User ID.
    pub user_id: String,
    /// Timestamp of last update (Unix ms).
    pub updated_at_unix_ms: i64,
    /// Source of the state data.
    pub source: String,
    /// Confidence level.
    pub confidence: f32,
    /// Axis values.
    pub axes: std::collections::BTreeMap<String, f32>,
}

impl From<StateSnapshot> for StateResponse {
    fn from(s: StateSnapshot) -> Self {
        Self {
            user_id: s.user_id,
            updated_at_unix_ms: s.updated_at_unix_ms,
            source: s.source.to_string(),
            confidence: s.confidence,
            axes: s.axes,
        }
    }
}

/// Error response format.
#[derive(Debug, Serialize)]
pub struct ErrorResponse {
    /// Error details.
    pub error: ErrorDetail,
}

/// Detailed error information.
#[derive(Debug, Serialize)]
pub struct ErrorDetail {
    /// Error code.
    pub code: String,
    /// Human-readable error message.
    pub message: String,
    /// Request ID for correlation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request_id: Option<String>,
}

impl ErrorResponse {
    /// Create a new error response.
    pub fn new(code: &str, message: &str) -> Self {
        Self {
            error: ErrorDetail {
                code: code.to_string(),
                message: message.to_string(),
                request_id: None,
            },
        }
    }
}

/// POST /v1/state - Upsert state
#[tracing::instrument(skip(state, body))]
#[allow(unused_mut)] // mut needed when inference feature is enabled
pub async fn upsert_state<S: StateStore + 'static>(
    State(state): State<Arc<AppState<S>>>,
    Json(body): Json<UpsertStateRequest>,
) -> impl IntoResponse {
    let mut axes = body.axes;
    let mut source: Source = body.source.into();

    // Run inference if enabled and message provided
    #[cfg(feature = "inference")]
    if let (Some(engine), Some(message)) = (&state.inference_engine, &body.message) {
        // Get or create baseline for user
        let mut baseline_ref = state
            .baselines
            .entry(body.user_id.clone())
            .or_insert_with(|| engine.new_baseline());

        // Run inference with baseline
        let inferred = engine.infer_with_baseline(message, &mut baseline_ref, None);

        // Merge: explicit axes override inferred
        for estimate in inferred.all() {
            if !axes.contains_key(&estimate.axis) {
                // Only use inferred if not explicitly provided
                axes.insert(estimate.axis.clone(), estimate.value);
            }
        }

        // Mark source as mixed if we used inference
        if !inferred.is_empty() && source == Source::SelfReport {
            source = Source::Mixed;
        }
    }

    let snapshot = match StateSnapshot::builder()
        .user_id(&body.user_id)
        .source(source)
        .confidence(body.confidence)
        .axes(axes.into_iter())
        .build()
    {
        Ok(s) => s,
        Err(e) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(ErrorResponse::new("VALIDATION_ERROR", &e.to_string())),
            )
                .into_response();
        }
    };

    match state.store.upsert_latest(snapshot).await {
        Ok(()) => StatusCode::NO_CONTENT.into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse::new("STORE_ERROR", &e.to_string())),
        )
            .into_response(),
    }
}

/// GET /v1/state/:user_id - Get state
#[tracing::instrument(skip(state))]
pub async fn get_state<S: StateStore + 'static>(
    State(state): State<Arc<AppState<S>>>,
    Path(user_id): Path<String>,
) -> impl IntoResponse {
    match state.store.get_latest(&user_id).await {
        Ok(Some(snapshot)) => Json(StateResponse::from(snapshot)).into_response(),
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(ErrorResponse::new(
                "USER_NOT_FOUND",
                &format!("No state found for user {}", user_id),
            )),
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse::new("STORE_ERROR", &e.to_string())),
        )
            .into_response(),
    }
}

/// DELETE /v1/state/:user_id - Delete state
#[tracing::instrument(skip(state))]
pub async fn delete_state<S: StateStore + 'static>(
    State(state): State<Arc<AppState<S>>>,
    Path(user_id): Path<String>,
) -> impl IntoResponse {
    match state.store.delete(&user_id).await {
        Ok(()) => StatusCode::NO_CONTENT.into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse::new("STORE_ERROR", &e.to_string())),
        )
            .into_response(),
    }
}

/// GET /v1/context/:user_id - Get translated context
#[tracing::instrument(skip(state))]
pub async fn get_context<S: StateStore + 'static>(
    State(state): State<Arc<AppState<S>>>,
    Path(user_id): Path<String>,
) -> impl IntoResponse {
    match state.store.get_latest(&user_id).await {
        Ok(Some(snapshot)) => {
            let context = state.translator.to_prompt_context(&snapshot);
            Json(context).into_response()
        }
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(ErrorResponse::new(
                "USER_NOT_FOUND",
                &format!("No state found for user {}", user_id),
            )),
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse::new("STORE_ERROR", &e.to_string())),
        )
            .into_response(),
    }
}

/// Request body for inline translation.
#[derive(Debug, Deserialize)]
pub struct TranslateRequest {
    /// Axis values to translate.
    pub axes: std::collections::BTreeMap<String, f32>,
    /// Source of the state data.
    #[serde(default)]
    pub source: SourceInput,
    /// Confidence level.
    #[serde(default = "default_confidence")]
    pub confidence: f32,
}

/// POST /v1/translate - Translate arbitrary state
#[tracing::instrument(skip(state, body))]
pub async fn translate<S: StateStore + 'static>(
    State(state): State<Arc<AppState<S>>>,
    Json(body): Json<TranslateRequest>,
) -> impl IntoResponse {
    let snapshot = match StateSnapshot::builder()
        .user_id("_anonymous")
        .source(body.source.into())
        .confidence(body.confidence)
        .axes(body.axes.into_iter())
        .build()
    {
        Ok(s) => s,
        Err(e) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(ErrorResponse::new("VALIDATION_ERROR", &e.to_string())),
            )
                .into_response();
        }
    };

    let context = state.translator.to_prompt_context(&snapshot);
    Json(context).into_response()
}

/// GET /health - Health check
#[tracing::instrument(skip(state))]
pub async fn health<S: StateStore + HealthCheck + 'static>(
    State(state): State<Arc<AppState<S>>>,
) -> impl IntoResponse {
    let store_health = state.store.check().await;
    let uptime = state.start_time.elapsed().as_secs();

    let status = HealthStatus::from_checks(vec![store_health], uptime);

    let status_code = match status.status {
        HealthState::Healthy => StatusCode::OK,
        HealthState::Degraded => StatusCode::OK,
        HealthState::Unhealthy => StatusCode::SERVICE_UNAVAILABLE,
    };

    (status_code, Json(status))
}

/// GET /ready - Readiness check
#[tracing::instrument(skip(state))]
pub async fn ready<S: StateStore + 'static>(
    State(state): State<Arc<AppState<S>>>,
) -> impl IntoResponse {
    match state.store.health_check().await {
        Ok(true) => StatusCode::OK,
        _ => StatusCode::SERVICE_UNAVAILABLE,
    }
}

/// Response for prompt context.
#[derive(Debug, Serialize)]
pub struct ContextResponse {
    /// Behavioral guidelines for the LLM.
    pub guidelines: Vec<String>,
    /// Suggested tone.
    pub tone: String,
    /// Desired response verbosity.
    pub verbosity: String,
    /// Active flags for special conditions.
    pub flags: Vec<String>,
}

impl From<PromptContext> for ContextResponse {
    fn from(c: PromptContext) -> Self {
        Self {
            guidelines: c.guidelines,
            tone: c.tone,
            verbosity: format!("{:?}", c.verbosity).to_lowercase(),
            flags: c.flags,
        }
    }
}

// ============================================================================
// Inference endpoint (requires "inference" feature)
// ============================================================================

/// Request body for inference endpoint.
#[cfg(feature = "inference")]
#[derive(Debug, Deserialize)]
pub struct InferRequest {
    /// The message text to analyze.
    pub message: String,
    /// Optional user ID for baseline comparison.
    /// If provided, the user's baseline will be updated.
    #[serde(default)]
    pub user_id: Option<String>,
    /// Include debug feature information in response.
    #[serde(default)]
    pub include_features: bool,
}

/// A single axis estimate in the inference response.
#[cfg(feature = "inference")]
#[derive(Debug, Serialize)]
pub struct InferEstimate {
    /// The axis name.
    pub axis: String,
    /// Estimated value in [0.0, 1.0].
    pub value: f32,
    /// Confidence in this estimate.
    pub confidence: f32,
    /// Source of this inference.
    pub source: InferSourceResponse,
}

/// Inference source for API response.
#[cfg(feature = "inference")]
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum InferSourceResponse {
    /// Inferred from linguistic features.
    Linguistic {
        /// Features that contributed to this inference.
        features_used: Vec<String>,
    },
    /// Inferred from deviation from baseline.
    Delta {
        /// Z-score deviation from baseline.
        z_score: f32,
        /// Which metric showed deviation.
        metric: String,
    },
    /// Combined from multiple sources.
    Combined {
        /// Number of sources combined.
        source_count: usize,
    },
    /// Prior/default value.
    Prior {
        /// Reason for this prior.
        reason: String,
    },
}

#[cfg(feature = "inference")]
impl From<&InferenceSource> for InferSourceResponse {
    fn from(source: &InferenceSource) -> Self {
        match source {
            InferenceSource::Linguistic { features_used, .. } => InferSourceResponse::Linguistic {
                features_used: features_used.clone(),
            },
            InferenceSource::Delta {
                z_score, metric, ..
            } => InferSourceResponse::Delta {
                z_score: *z_score,
                metric: metric.clone(),
            },
            InferenceSource::Combined { sources, .. } => InferSourceResponse::Combined {
                source_count: sources.len(),
            },
            InferenceSource::Prior { reason } => InferSourceResponse::Prior {
                reason: reason.clone(),
            },
            InferenceSource::Decayed { original, .. } => {
                // Unwrap to original source
                InferSourceResponse::from(original.as_ref())
            }
            InferenceSource::SelfReport => {
                // Shouldn't happen in inference, but handle gracefully
                InferSourceResponse::Prior {
                    reason: "self_report".into(),
                }
            }
        }
    }
}

/// Response for inference endpoint.
#[cfg(feature = "inference")]
#[derive(Debug, Serialize)]
pub struct InferResponse {
    /// Estimated axes.
    pub estimates: Vec<InferEstimate>,
    /// Debug feature information (if requested).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub features: Option<HashMap<String, serde_json::Value>>,
}

/// POST /v1/infer - Infer axes from message text without storage
#[cfg(feature = "inference")]
#[tracing::instrument(skip(state, body))]
pub async fn infer<S: StateStore + 'static>(
    State(state): State<Arc<AppState<S>>>,
    Json(body): Json<InferRequest>,
) -> impl IntoResponse {
    let Some(engine) = &state.inference_engine else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ErrorResponse::new(
                "INFERENCE_DISABLED",
                "Inference is not enabled on this server",
            )),
        )
            .into_response();
    };

    // Run inference with optional baseline
    let inferred = if let Some(user_id) = &body.user_id {
        let mut baseline_ref = state
            .baselines
            .entry(user_id.clone())
            .or_insert_with(|| engine.new_baseline());
        engine.infer_with_baseline(&body.message, &mut baseline_ref, None)
    } else {
        engine.infer(&body.message)
    };

    // Convert to response format
    let estimates: Vec<InferEstimate> = inferred
        .all()
        .map(|est| InferEstimate {
            axis: est.axis.clone(),
            value: est.value,
            confidence: est.confidence,
            source: InferSourceResponse::from(&est.source),
        })
        .collect();

    // Include features if requested
    let features = if body.include_features {
        let extractor = attuned_infer::LinguisticExtractor::new();
        let f = extractor.extract(&body.message);
        let mut map = HashMap::new();
        map.insert("word_count".into(), serde_json::json!(f.word_count));
        map.insert("sentence_count".into(), serde_json::json!(f.sentence_count));
        map.insert("hedge_count".into(), serde_json::json!(f.hedge_count));
        map.insert(
            "urgency_word_count".into(),
            serde_json::json!(f.urgency_word_count),
        );
        map.insert(
            "negative_emotion_count".into(),
            serde_json::json!(f.negative_emotion_count),
        );
        map.insert(
            "exclamation_ratio".into(),
            serde_json::json!(f.exclamation_ratio),
        );
        map.insert("question_ratio".into(), serde_json::json!(f.question_ratio));
        map.insert("caps_ratio".into(), serde_json::json!(f.caps_ratio));
        map.insert(
            "first_person_ratio".into(),
            serde_json::json!(f.first_person_ratio),
        );
        Some(map)
    } else {
        None
    };

    Json(InferResponse {
        estimates,
        features,
    })
    .into_response()
}