smos-application 0.1.12

SMOS application layer — use cases and port traits.
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
//! Port-trait shape tests.
//!
//! These tests do NOT exercise any production adapter. They confirm that the
//! port traits are *implementable* (a `Mock*` exists for each), that generic
//! dispatch works (`fn use_it<T: Trait>(t: &T)`), and that the default
//! `embed_batch` is reachable through the `EmbeddingProvider` trait.

#![allow(async_fn_in_trait)]

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use smos_application::errors::{ProviderError, RepoError, UpstreamError};
use smos_application::ports::{
    Clock, EmbeddingProvider, FactRepository, IdGenerator, LlmExtractor, LlmUpstream,
    NliClassifier, RerankProvider, SessionRepository,
};
use smos_application::types::{ChatRequest, ChatResponse, MergeResult, RerankResult, SearchHit};
use smos_domain::{
    Fact, FactId, Heat, MemoryKey, NewPendingRequest, NliResult, NliScores, SessionId,
    SessionState, Timestamp, chat::ToolCall, config::ConfidenceConfig,
};
use std::time::Duration;

// ---------------------------------------------------------------------------
// Mocks — one per port trait.
// ---------------------------------------------------------------------------

#[derive(Clone)]
struct MockClock {
    fixed: Timestamp,
}

impl Default for MockClock {
    fn default() -> Self {
        Self {
            fixed: Timestamp::from_unix_secs(0).expect("epoch"),
        }
    }
}

impl Clock for MockClock {
    fn now(&self) -> Timestamp {
        self.fixed
    }
}

/// Mock `IdGenerator` that hands out deterministic, monotonically-increasing
/// session ids. Mirrors the per-port `Mock*` pattern so `IdGenerator` has the
/// same shape coverage as every other port in this file.
struct CountingIdGenerator {
    counter: Arc<AtomicUsize>,
}

impl CountingIdGenerator {
    fn new() -> Self {
        Self {
            counter: Arc::new(AtomicUsize::new(0)),
        }
    }
}

impl IdGenerator for CountingIdGenerator {
    fn new_session_id(&self) -> SessionId {
        let n = self.counter.fetch_add(1, Ordering::SeqCst) as u64;
        // 12 hex chars, zero-padded — matches the canonical `sess_<12 hex>`
        // shape that `SessionId::from_raw` validates.
        SessionId::from_raw(&format!("sess_{:012x}", n)).expect("well-formed mock id")
    }
}

struct CountingEmbeddingProvider {
    call_count: Arc<AtomicUsize>,
}

impl CountingEmbeddingProvider {
    fn new() -> Self {
        Self {
            call_count: Arc::new(AtomicUsize::new(0)),
        }
    }
}

impl EmbeddingProvider for CountingEmbeddingProvider {
    async fn embed(&self, _text: &str) -> Result<Option<Vec<f32>>, ProviderError> {
        self.call_count.fetch_add(1, Ordering::SeqCst);
        Ok(Some(vec![0.0, 1.0]))
    }
}

struct StubRerankProvider;

impl RerankProvider for StubRerankProvider {
    async fn rerank(
        &self,
        _query: &str,
        documents: &[String],
        top_k: usize,
    ) -> Result<Vec<RerankResult>, ProviderError> {
        Ok(documents
            .iter()
            .take(top_k)
            .enumerate()
            .map(|(i, d)| RerankResult {
                index: i,
                score: 1.0 - i as f32 * 0.1,
                document: d.clone(),
            })
            .collect())
    }
}

struct StubNliClassifier;

impl NliClassifier for StubNliClassifier {
    async fn classify(
        &self,
        _premise: &str,
        _hypothesis: &str,
    ) -> Result<NliResult, ProviderError> {
        Ok(NliResult {
            label: smos_domain::enums::NliLabel::Entailment,
            scores: NliScores {
                entailment: 0.9,
                neutral: 0.05,
                contradiction: 0.05,
            },
            available: true,
        })
    }
}

struct StubLlmExtractor;

impl LlmExtractor for StubLlmExtractor {
    async fn extract_facts(
        &self,
        content: &str,
        _tool_calls: &[ToolCall],
    ) -> Result<Vec<String>, ProviderError> {
        Ok(vec![content.to_string()])
    }
}

struct StubLlmUpstream;

impl LlmUpstream for StubLlmUpstream {
    async fn complete(
        &self,
        _provider_name: &str,
        _request: ChatRequest,
    ) -> Result<ChatResponse, UpstreamError> {
        Ok(ChatResponse::NonStreaming(
            serde_json::json!({"choices": []}),
        ))
    }
}

struct StubFactRepository;

impl FactRepository for StubFactRepository {
    async fn save(&self, _fact: &Fact) -> Result<(), RepoError> {
        Ok(())
    }
    async fn get(&self, _id: &FactId, _memory_key: &MemoryKey) -> Result<Option<Fact>, RepoError> {
        Ok(None)
    }
    async fn list_accepted(&self, _memory_key: &MemoryKey) -> Result<Vec<Fact>, RepoError> {
        Ok(Vec::new())
    }
    async fn list_pending(&self, _memory_key: &MemoryKey) -> Result<Vec<Fact>, RepoError> {
        Ok(Vec::new())
    }
    async fn list_memory_keys_for_session(
        &self,
        _session_id: &SessionId,
    ) -> Result<Vec<MemoryKey>, RepoError> {
        Ok(Vec::new())
    }
    async fn list_memory_keys(&self) -> Result<Vec<MemoryKey>, RepoError> {
        Ok(Vec::new())
    }
    async fn search_similar(
        &self,
        _embedding: Vec<f32>,
        _memory_key: &MemoryKey,
        _limit: usize,
    ) -> Result<Vec<SearchHit>, RepoError> {
        Ok(Vec::new())
    }
    async fn update_heat_batch(
        &self,
        _ids: &[FactId],
        _memory_key: &MemoryKey,
        _heat_base: Heat,
        _last_access: Timestamp,
    ) -> Result<(), RepoError> {
        Ok(())
    }
}

struct StubSessionRepository;

impl SessionRepository for StubSessionRepository {
    async fn get_or_create(
        &self,
        id: &SessionId,
        memory_key: &MemoryKey,
    ) -> Result<SessionState, RepoError> {
        Ok(SessionState::new(
            id.clone(),
            memory_key.clone(),
            Timestamp::from_unix_secs(0).expect("ts"),
        ))
    }
    async fn collect_expired(
        &self,
        _timeout: Duration,
    ) -> Result<Vec<(SessionId, SessionState)>, RepoError> {
        Ok(Vec::new())
    }
    async fn snapshot_all(&self) -> Result<Vec<(SessionId, SessionState)>, RepoError> {
        Ok(Vec::new())
    }
    async fn add_pending(&self, _id: &SessionId, _fact_ids: &[FactId]) -> Result<(), RepoError> {
        Ok(())
    }
    async fn remove_pending_owned(
        &self,
        _id: &SessionId,
        _owned: &[FactId],
    ) -> Result<(), RepoError> {
        Ok(())
    }
    async fn clear_session(&self, _id: &SessionId) -> Result<(), RepoError> {
        Ok(())
    }
    async fn dedup_and_mark(
        &self,
        _id: &SessionId,
        _memory_key: &MemoryKey,
        candidate_ids: &[FactId],
    ) -> Result<Vec<FactId>, RepoError> {
        Ok(candidate_ids.to_vec())
    }
    async fn save(&self, _id: &SessionId, _state: &SessionState) -> Result<(), RepoError> {
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Generic-dispatch tests — if the trait shape compiles, the test passes.
// ---------------------------------------------------------------------------

async fn use_embedding_provider<T: EmbeddingProvider>(p: &T) -> Vec<Option<Vec<f32>>> {
    p.embed_batch(&["a", "b", "c"]).await.expect("batch")
}

#[tokio::test]
async fn embedding_provider_default_embed_batch_loops_embed_per_call() {
    let provider = CountingEmbeddingProvider::new();
    let out = use_embedding_provider(&provider).await;
    assert_eq!(out.len(), 3);
    // The default `embed_batch` impl must call `embed` once per text.
    assert_eq!(provider.call_count.load(Ordering::SeqCst), 3);
}

#[tokio::test]
async fn rerank_provider_returns_top_k_in_order() {
    let p = StubRerankProvider;
    let docs = vec!["d1".to_string(), "d2".to_string(), "d3".to_string()];
    let out = p.rerank("q", &docs, 2).await.expect("rerank");
    assert_eq!(out.len(), 2);
    assert_eq!(out[0].index, 0);
    assert_eq!(out[1].index, 1);
    assert!(out[0].score >= out[1].score);
}

#[tokio::test]
async fn nli_classifier_returns_verdict() {
    let c = StubNliClassifier;
    let r = c.classify("a", "b").await.expect("classify");
    assert!(r.available);
    assert_eq!(r.label, smos_domain::enums::NliLabel::Entailment);
}

#[tokio::test]
async fn llm_extractor_returns_extracted_strings() {
    let e = StubLlmExtractor;
    let out = e.extract_facts("hello", &[]).await.expect("extract");
    assert_eq!(out, vec!["hello".to_string()]);
}

#[tokio::test]
async fn llm_upstream_returns_non_streaming_value() {
    let u = StubLlmUpstream;
    let resp = u
        .complete("any", ChatRequest::new("m", Vec::new()))
        .await
        .expect("complete");
    match resp {
        ChatResponse::NonStreaming(v) => assert!(v.get("choices").is_some()),
        ChatResponse::Streaming(_) => panic!("expected NonStreaming"),
    }
}

#[tokio::test]
async fn clock_port_returns_fixed_time() {
    let clock = MockClock {
        fixed: Timestamp::from_unix_secs(1_234_567_890).expect("ts"),
    };
    assert_eq!(clock.now().as_unix_secs(), 1_234_567_890);
}

#[tokio::test]
async fn fact_repository_stub_implements_all_methods() {
    let repo = StubFactRepository;
    let mk = MemoryKey::shared();
    let id = FactId::from_content("a");
    // Every method must be callable without panicking.
    repo.save(
        &Fact::new_pending(NewPendingRequest {
            content: "a",
            memory_key: mk.clone(),
            session: SessionId::from_raw("sess_abcdef012345").unwrap(),
            embedding: smos_domain::Embedding::new(vec![1.0]).unwrap(),
            extracted_at: Timestamp::from_unix_secs(0).unwrap(),
            base_confidence: ConfidenceConfig::default().base,
        })
        .unwrap(),
    )
    .await
    .expect("save");
    assert!(repo.get(&id, &mk).await.unwrap().is_none());
    assert!(repo.list_accepted(&mk).await.unwrap().is_empty());
    assert!(repo.list_pending(&mk).await.unwrap().is_empty());
    assert!(
        repo.search_similar(vec![1.0], &mk, 10)
            .await
            .unwrap()
            .is_empty()
    );
    repo.update_heat_batch(
        &[],
        &mk,
        Heat::new(0.5).unwrap(),
        Timestamp::from_unix_secs(1).unwrap(),
    )
    .await
    .expect("heat");
}

#[tokio::test]
async fn session_repository_stub_implements_all_methods() {
    let repo = StubSessionRepository;
    let id = SessionId::from_raw("sess_abcdef012345").unwrap();
    let mk = MemoryKey::shared();
    let state = repo.get_or_create(&id, &mk).await.expect("goc");
    assert_eq!(state.id(), &id);

    assert!(
        repo.collect_expired(Duration::from_secs(60))
            .await
            .unwrap()
            .is_empty()
    );
    assert!(repo.snapshot_all().await.unwrap().is_empty());

    let candidates = vec![FactId::from_content("a"), FactId::from_content("b")];
    let new = repo
        .dedup_and_mark(&id, &mk, &candidates)
        .await
        .expect("dedup");
    assert_eq!(new.len(), 2);

    repo.add_pending(&id, &candidates).await.expect("add");
    repo.remove_pending_owned(&id, &candidates)
        .await
        .expect("remove");
    repo.save(&id, &state).await.expect("save");
    repo.clear_session(&id).await.expect("clear");
}

// ---------------------------------------------------------------------------
// Use-case-style composition test — proves ports compose into a higher-level
// function via generic dispatch (this is how slice 7 use cases will look).
// ---------------------------------------------------------------------------

async fn retrieve_and_dedup<R, S>(
    facts: &R,
    sessions: &S,
    embedding: Vec<f32>,
    memory_key: &MemoryKey,
    session_id: &SessionId,
) -> Result<Vec<FactId>, RepoError>
where
    R: FactRepository + ?Sized,
    S: SessionRepository + ?Sized,
{
    let hits = facts
        .search_similar(embedding, memory_key, 10)
        .await?
        .into_iter()
        .map(|h| h.id)
        .collect::<Vec<_>>();
    sessions.dedup_and_mark(session_id, memory_key, &hits).await
}

#[tokio::test]
async fn ports_compose_into_higher_level_use_case_via_generic_dispatch() {
    let facts = StubFactRepository;
    let sessions = StubSessionRepository;
    let mk = MemoryKey::shared();
    let sid = SessionId::from_raw("sess_abcdef012345").unwrap();
    let new = retrieve_and_dedup(&facts, &sessions, vec![1.0], &mk, &sid)
        .await
        .expect("compose");
    assert!(new.is_empty(), "stub facts return no hits → empty dedup");
}

#[tokio::test]
async fn merge_result_type_compiles_and_carries_data() {
    let r = MergeResult {
        merged: false,
        reason: smos_domain::enums::MergeReason::NoCandidate,
        merged_fact: None,
        nli_result: None,
    };
    assert!(!r.merged);
    assert!(r.merged_fact.is_none());
}

// ---------------------------------------------------------------------------
// IdGenerator — the only port whose primary method is synchronous. Verify it
// (a) implements against a mock, (b) composes via generic dispatch, and
// (c) yields the canonical `sess_<12 hex>` shape so the marker round-trip
// still works.
// ---------------------------------------------------------------------------

fn use_id_generator<G: IdGenerator>(generator: &G) -> SessionId {
    generator.new_session_id()
}

#[test]
fn id_generator_stub_implements_port_and_yields_canonical_shape() {
    let generator = CountingIdGenerator::new();
    let id = use_id_generator(&generator);
    let s = id.as_str();
    assert!(s.starts_with("sess_"));
    let hex = &s["sess_".len()..];
    assert_eq!(hex.len(), 12);
    assert!(hex.chars().all(|c| c.is_ascii_hexdigit()));
    // The id round-trips through the marker pipeline (`to_marker` +
    // `detect_in_text` is the production path that re-discovers the id from
    // the trailing comment).
    let marker = id.to_marker();
    let recovered = smos_application::helpers::session_marker::detect_in_text(&marker);
    assert_eq!(recovered.as_ref(), Some(&id));
}