smos-application 0.2.1

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
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
use super::*;
use smos_domain::{Embedding, FactStatus, NewPendingRequest};

#[tokio::test]
async fn execute_disabled_returns_zero_without_calling_extractor() {
    let facts = InMemoryFacts::default();
    let sessions = RecordingSessions::default();
    let extractor = ScriptedExtractor::new(vec![Err(ProviderError::Unavailable(
        "must not be called".into(),
    ))]);
    let fix = Fix::new();
    let mut uc = build(
        &facts,
        &sessions,
        &extractor,
        &fix.embedder,
        &fix.clock,
        &fix.cfg,
        &fix.extraction_cfg,
    );
    uc.enable_response_extraction = false;

    let n = uc
        .execute("", "TTL=10 prevents refresh loop", &[], &mk(), &sid(1))
        .await
        .unwrap();
    assert_eq!(n, 0);
}

#[tokio::test]
async fn execute_short_input_returns_zero_without_calling_extractor() {
    let facts = InMemoryFacts::default();
    let sessions = RecordingSessions::default();
    let extractor = ScriptedExtractor::new(vec![Err(ProviderError::Unavailable(
        "must not be called".into(),
    ))]);
    let fix = Fix::new();
    let uc = build(
        &facts,
        &sessions,
        &extractor,
        &fix.embedder,
        &fix.clock,
        &fix.cfg,
        &fix.extraction_cfg,
    );

    // "ok" is 2 chars < MIN_INPUT_CHARS (15).
    let n = uc.execute("", "ok", &[], &mk(), &sid(1)).await.unwrap();
    assert_eq!(n, 0);
}

#[tokio::test]
async fn execute_saves_new_pending_fact_and_registers_it() {
    let facts = InMemoryFacts::default();
    let sessions = RecordingSessions::default();
    let extractor = ScriptedExtractor::new(vec![Ok(vec![
        "TTL=10 prevents the token refresh loop".to_string(),
    ])]);
    let fix = Fix::new();
    let uc = build(
        &facts,
        &sessions,
        &extractor,
        &fix.embedder,
        &fix.clock,
        &fix.cfg,
        &fix.extraction_cfg,
    );

    let n = uc
        .execute(
            "",
            "we changed TTL to 10 to stop the loop",
            &[],
            &mk(),
            &sid(1),
        )
        .await
        .unwrap();

    assert_eq!(n, 1);
    let fact = facts
        .get_clone(&FactId::from_content(
            "TTL=10 prevents the token refresh loop",
        ))
        .expect("fact saved");
    assert_eq!(fact.status(), FactStatus::Pending);
    assert_eq!(
        sessions.pending.lock().unwrap().len(),
        1,
        "fact registered on session pending list"
    );
}

#[tokio::test]
async fn execute_unavailable_extractor_skips_gracefully() {
    let facts = InMemoryFacts::default();
    let sessions = RecordingSessions::default();
    // A single Unavailable result: the use case must return Ok(0)
    // immediately WITHOUT retrying. `call_count == 1` (not 3) is the
    // invariant that proves the early-exit on Unavailable.
    let extractor = ScriptedExtractor::new(vec![Err(ProviderError::Unavailable(
        "connection refused".into(),
    ))]);
    let fix = Fix::new();
    let uc = build(
        &facts,
        &sessions,
        &extractor,
        &fix.embedder,
        &fix.clock,
        &fix.cfg,
        &fix.extraction_cfg,
    );

    let n = uc
        .execute("", "some real content long enough", &[], &mk(), &sid(1))
        .await
        .unwrap();
    assert_eq!(n, 0);
    assert_eq!(
        extractor.call_count(),
        1,
        "Unavailable must skip retries — extractor called exactly once"
    );
    assert!(facts.is_empty(), "no fact persisted on graceful skip");
}

#[tokio::test]
async fn execute_retries_on_request_failed_then_succeeds() {
    let facts = InMemoryFacts::default();
    let sessions = RecordingSessions::default();
    let extractor = ScriptedExtractor::new(vec![
        Err(ProviderError::RequestFailed("500".into())),
        Err(ProviderError::RequestFailed("500".into())),
        Ok(vec!["auth.rs uses JWT for tokens".to_string()]),
    ]);
    let fix = Fix::new();
    let uc = build(
        &facts,
        &sessions,
        &extractor,
        &fix.embedder,
        &fix.clock,
        &fix.cfg,
        &fix.extraction_cfg,
    );

    let n = uc
        .execute("", "the auth module uses JWT", &[], &mk(), &sid(1))
        .await
        .unwrap();
    assert_eq!(n, 1);
}

#[tokio::test]
async fn execute_gives_up_after_all_attempts_fail() {
    let facts = InMemoryFacts::default();
    let sessions = RecordingSessions::default();
    let extractor = ScriptedExtractor::new(vec![
        Err(ProviderError::RequestFailed("500".into())),
        Err(ProviderError::RequestFailed("500".into())),
        Err(ProviderError::RequestFailed("500".into())),
    ]);
    let fix = Fix::new();
    let uc = build(
        &facts,
        &sessions,
        &extractor,
        &fix.embedder,
        &fix.clock,
        &fix.cfg,
        &fix.extraction_cfg,
    );

    let result = uc
        .execute("", "content long enough to pass gate", &[], &mk(), &sid(1))
        .await;
    assert!(result.is_err(), "final failure propagates as Err");
    assert!(facts.is_empty());
}

#[tokio::test]
async fn execute_strips_smos_noise_before_extraction() {
    let facts = InMemoryFacts::default();
    let sessions = RecordingSessions::default();
    let extractor = ScriptedExtractor::new(vec![Ok(vec!["a clean fact".to_string()])]);
    let fix = Fix::new();
    let uc = build(
        &facts,
        &sessions,
        &extractor,
        &fix.embedder,
        &fix.clock,
        &fix.cfg,
        &fix.extraction_cfg,
    );

    let content = "real content about the deployment\n<!-- smos:sess_abcdef012345 -->\n<smos-memory session=\"s\">x</smos-memory>";
    let n = uc.execute("", content, &[], &mk(), &sid(1)).await.unwrap();
    assert_eq!(n, 1);
}

#[tokio::test]
async fn execute_cross_session_confirms_existing_fact() {
    let facts = InMemoryFacts::default();
    let sessions = RecordingSessions::default();

    // Seed a fact from session 1.
    let first = Fact::new_pending(NewPendingRequest {
        content: "shared fact content here",
        memory_key: mk(),
        session: sid(1),
        embedding: Embedding::new(vec![1.0]).unwrap(),
        extracted_at: Timestamp::from_unix_secs(1_700_000_000).unwrap(),
        base_confidence: ConfidenceConfig::default().base,
    })
    .unwrap();
    let fid = first.id().clone();
    facts.seed(first);

    let extractor = ScriptedExtractor::new(vec![Ok(vec!["shared fact content here".to_string()])]);
    let fix = Fix::new();
    let uc = build(
        &facts,
        &sessions,
        &extractor,
        &fix.embedder,
        &fix.clock,
        &fix.cfg,
        &fix.extraction_cfg,
    );

    // Same fact observed from session 2 → confirmation, not a new fact.
    let n = uc
        .execute("", "shared fact content here", &[], &mk(), &sid(2))
        .await
        .unwrap();
    assert_eq!(n, 0, "confirmation does not count as a new fact");

    let confirmed = facts.get_clone(&fid).expect("fact still present");
    assert_eq!(
        confirmed.source_sessions().distinct_count(),
        2,
        "provenance grew to two sessions"
    );
    assert!(
        sessions.pending.lock().unwrap().is_empty(),
        "confirmation must not register on the pending list"
    );
}

/// The extraction pipeline MUST hand distinct embeddings to distinct
/// extracted facts — otherwise Layer 2 dedup would collapse two
/// unrelated facts (cosine ~1) and silently lose data. The
/// `RecordingEmbedder` returns a content-derived one-hot vector so
/// two distinct facts end up with cosine similarity 0; this test
/// pins that contract by checking the recorded calls + the resulting
/// store state.
#[tokio::test]
async fn recording_embedder_yields_distinct_vectors_for_distinct_facts() {
    let facts = InMemoryFacts::default();
    let sessions = RecordingSessions::default();
    let extractor = ScriptedExtractor::new(vec![Ok(vec![
        "alpha configuration directive".to_string(),
        "beta configuration directive".to_string(),
    ])]);
    let (embedder, calls) = RecordingEmbedder::new();
    let clock = clock();
    let cfg = cfg();
    let extraction_cfg = extraction_cfg();
    let uc = build_with_recording_embedder(
        &facts,
        &sessions,
        &extractor,
        &embedder,
        &clock,
        &cfg,
        &extraction_cfg,
    );

    let n = uc
        .execute("", "content covering both directives", &[], &mk(), &sid(1))
        .await
        .unwrap();
    assert_eq!(n, 2, "two distinct facts persisted");
    assert_eq!(
        calls.lock().unwrap().len(),
        2,
        "embedder called once per extracted fact"
    );
    // Two distinct FactIds in the store → no collapse happened.
    let id_a = FactId::from_content("alpha configuration directive");
    let id_b = FactId::from_content("beta configuration directive");
    assert!(facts.contains(&id_a));
    assert!(facts.contains(&id_b));
}

// -----------------------------------------------------------------------
// Empty raw fact in extraction batch — must not crash
// -----------------------------------------------------------------------

/// An empty string in the extracted facts list surfaces as `Err` —
/// the pipeline propagates the underlying domain failure rather than
/// silently dropping the empty entry or persisting a malformed fact.
/// The whole batch fails: the call site (background extraction task)
/// logs the error and the facts that would have been persisted in
/// the same batch are lost too. A future refactor that filters
/// empty raw facts BEFORE the `Fact::new_pending` constructor would
/// change this test from `is_err()` to `n == 1`; that change is
/// intentional and the test should be updated alongside it.
#[tokio::test]
async fn execute_propagates_err_when_batch_contains_empty_raw_fact() {
    let facts = InMemoryFacts::default();
    let sessions = RecordingSessions::default();
    // Mix one empty + one real fact in the extractor output.
    let extractor = ScriptedExtractor::new(vec![Ok(vec![
        String::new(),
        "real fact that should still persist".to_string(),
    ])]);
    let fix = Fix::new();
    let uc = build(
        &facts,
        &sessions,
        &extractor,
        &fix.embedder,
        &fix.clock,
        &fix.cfg,
        &fix.extraction_cfg,
    );

    let result = uc
        .execute(
            "",
            "content long enough to clear MIN_INPUT_CHARS",
            &[],
            &mk(),
            &sid(1),
        )
        .await;
    assert!(
        result.is_err(),
        "empty raw fact must surface as Err (the only safe non-silent path)"
    );
}

/// A long user message MUST NOT let a short assistant reply through the gate.
/// This pins the gate-on-assistant-signal invariant: the gate considers only
/// the cleaned assistant content + tool calls, never the user message. A future
/// regression that moves the gate onto the combined input would let this case
/// through and call the extractor — this test would catch it.
#[tokio::test]
async fn execute_long_user_message_does_not_let_short_assistant_reply_through_gate() {
    let facts = InMemoryFacts::default();
    let sessions = RecordingSessions::default();
    let extractor = ScriptedExtractor::new(vec![Err(ProviderError::Unavailable(
        "must not be called".into(),
    ))]);
    let fix = Fix::new();
    let uc = build(
        &facts,
        &sessions,
        &extractor,
        &fix.embedder,
        &fix.clock,
        &fix.cfg,
        &fix.extraction_cfg,
    );

    let long_user = "Could you please explain in great detail how the authentication subsystem works, including all the moving parts and the rationale behind each decision that was made along the way?";
    let n = uc
        .execute(long_user, "ok", &[], &mk(), &sid(1))
        .await
        .unwrap();
    assert_eq!(
        n, 0,
        "short assistant reply must short-circuit regardless of user message length"
    );
    assert_eq!(
        extractor.call_count(),
        0,
        "gate is on assistant signal only — extractor never invoked"
    );
}

// -----------------------------------------------------------------------
// user_message threading — role markup + gate semantics
// -----------------------------------------------------------------------

/// A non-empty user message is prepended with explicit "User:/Assistant:"
/// role markup so the extractor sees the question→answer pair. The recorded
/// extractor input is the exact combined string.
#[tokio::test]
async fn execute_with_user_message_frames_input_with_role_markup() {
    let facts = InMemoryFacts::default();
    let sessions = RecordingSessions::default();
    let extractor = ScriptedExtractor::new(vec![Ok(vec!["a fact".to_string()])]);
    let fix = Fix::new();
    let uc = build(
        &facts,
        &sessions,
        &extractor,
        &fix.embedder,
        &fix.clock,
        &fix.cfg,
        &fix.extraction_cfg,
    );

    let n = uc
        .execute(
            "  how does auth work?  ",
            "the auth uses JWT",
            &[],
            &mk(),
            &sid(1),
        )
        .await
        .unwrap();
    assert_eq!(n, 1);

    let inputs = extractor.inputs();
    assert_eq!(inputs.len(), 1, "extractor invoked exactly once");
    assert_eq!(
        inputs[0].0, "User:\nhow does auth work?\n\nAssistant:\nthe auth uses JWT",
        "user message trimmed and framed with role labels"
    );
}

/// An empty user message (the import-path shape) produces a label-free input
/// byte-identical to the pre-markup extraction shape — no "Assistant:" prefix.
#[tokio::test]
async fn execute_with_empty_user_message_omits_role_labels() {
    let facts = InMemoryFacts::default();
    let sessions = RecordingSessions::default();
    let extractor = ScriptedExtractor::new(vec![Ok(vec!["a fact".to_string()])]);
    let fix = Fix::new();
    let uc = build(
        &facts,
        &sessions,
        &extractor,
        &fix.embedder,
        &fix.clock,
        &fix.cfg,
        &fix.extraction_cfg,
    );

    uc.execute("", "the auth uses JWT", &[], &mk(), &sid(1))
        .await
        .unwrap();

    let inputs = extractor.inputs();
    assert_eq!(
        inputs[0].0, "the auth uses JWT",
        "no role labels when user_message is empty"
    );
}

/// A response that is ONLY a `<think>` block (no factual answer) must short-
/// circuit: after noise stripping the assistant signal is empty, so extraction
/// is skipped and the extractor is never called.
#[tokio::test]
async fn execute_with_think_only_response_skips_extraction() {
    let facts = InMemoryFacts::default();
    let sessions = RecordingSessions::default();
    let extractor = ScriptedExtractor::new(vec![Err(ProviderError::Unavailable(
        "must not be called".into(),
    ))]);
    let fix = Fix::new();
    let uc = build(
        &facts,
        &sessions,
        &extractor,
        &fix.embedder,
        &fix.clock,
        &fix.cfg,
        &fix.extraction_cfg,
    );

    let think_only =
        "<think>long reasoning that is well over the 15-char floor but carries no fact</think>";
    let n = uc
        .execute("", think_only, &[], &mk(), &sid(1))
        .await
        .unwrap();
    assert_eq!(
        n, 0,
        "think-only response has no extractable assistant signal"
    );
    assert_eq!(
        extractor.call_count(),
        0,
        "extractor never invoked when assistant signal is empty after think-strip"
    );
}