foundation_ai 0.0.1

AI foundation crate for the eweplatform
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
//! Deterministic test substrate (F21) — `MockModelProvider`, `MockModel`,
//! `MockTool`, message builders, and `ModelInteraction` matchers.
//!
//! WHY: Real LLMs are non-deterministic and slow. The agentic loop, memory
//! triggers, tool DAG, steering, loop detection, circuit breaker, and resume
//! all need deterministic tests with scripted model responses.
//!
//! WHAT: A `MockModelProvider` implementing `RoutableProvider` (F12), driven by
//! `Fn(&ModelInteraction) -> bool` matchers (not regex over strings). Mock tools
//! implementing `ToolImpl` (F09) with `Returns/Fails/FailsThenSucceeds` behaviors.
//! Message builder helpers for readable test setup.

use std::collections::HashMap;
use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
use std::sync::{Arc, RwLock};

use async_trait::async_trait;
use foundation_core::valtron::Stream;

use crate::errors::GenerationResult;
use crate::types::{
    BoxModel, CostStatus, MessageRole, Messages, ModelId, ModelInteraction, ModelOutput,
    ModelParams, ModelProviderDescriptor, ModelProviders, ModelSpec, ModelState, ModelStreamBox,
    StopReason, TextBasedFormatter, TextContent, ToolFormatter, UsageCosting, UsageReport,
    UserModelContent,
};
use crate::types::{ProviderRouter, RoutableProvider};

use super::tool_impl::{ToolCallResult, ToolDefinition, ToolError, ToolImpl};

// ---------------------------------------------------------------------------
// Matchers — Fn(&ModelInteraction) -> bool closures
// ---------------------------------------------------------------------------

type Matcher = Box<dyn Fn(&ModelInteraction, usize) -> bool + Send + Sync>;

// ---------------------------------------------------------------------------
// MockModelProvider
// ---------------------------------------------------------------------------

struct Script {
    matcher: Matcher,
    replies: Vec<Messages>,
}

struct Failure {
    matcher: Matcher,
    error: String,
}

/// A deterministic model provider driven by `ModelInteraction` matchers.
///
/// Implements `RoutableProvider` (F12) so it plugs directly into
/// `ProviderRouter`. Responses are scripted: the first matching script wins.
pub struct MockModelProvider {
    /// Shared so `RoutableProvider::get_model` can hand out a `MockModel` that
    /// resolves against the SAME scripts. Previously the state was owned
    /// outright and `get_model` returned `None`, so the mock could never drive
    /// a routed `AgentLoop` at all — every routed lookup failed with
    /// "no provider registered", which is why the loop's inner states had no
    /// coverage. See specifications/60-agentic-reliability.
    inner: Arc<MockInner>,
    name: String,
}

/// Script state shared between a `MockModelProvider` and the `MockModel`s it
/// hands to the router.
#[derive(Default)]
struct MockInner {
    scripts: RwLock<Vec<Script>>,
    failures: RwLock<Vec<Failure>>,
    call_count: AtomicUsize,
}

impl MockModelProvider {
    #[must_use]
    pub fn new() -> Self {
        Self {
            inner: Arc::new(MockInner::default()),
            name: "mock".into(),
        }
    }

    /// Respond with `reply` when `matcher` returns true for the interaction.
    pub fn on(
        &mut self,
        matcher: impl Fn(&ModelInteraction) -> bool + Send + Sync + 'static,
        reply: Vec<Messages>,
    ) -> &mut Self {
        self.inner.scripts.write().expect("mock scripts poisoned").push(Script {
            matcher: Box::new(move |mi, _| matcher(mi)),
            replies: reply,
        });
        self
    }

    /// Respond with `reply` on the `n`th call (0-indexed).
    pub fn on_nth_call(&mut self, n: usize, reply: Vec<Messages>) -> &mut Self {
        self.inner.scripts.write().expect("mock scripts poisoned").push(Script {
            matcher: Box::new(move |_, call| call == n),
            replies: reply,
        });
        self
    }

    /// Respond with `reply` for any interaction (catch-all, add last).
    pub fn on_any(&mut self, reply: Vec<Messages>) -> &mut Self {
        self.inner.scripts.write().expect("mock scripts poisoned").push(Script {
            matcher: Box::new(|_, _| true),
            replies: reply,
        });
        self
    }

    /// Fail with `error` when `matcher` matches (checked before scripts).
    pub fn fail_with(
        &mut self,
        matcher: impl Fn(&ModelInteraction) -> bool + Send + Sync + 'static,
        error: impl Into<String>,
    ) -> &mut Self {
        self.inner.failures.write().expect("mock failures poisoned").push(Failure {
            matcher: Box::new(move |mi, _| matcher(mi)),
            error: error.into(),
        });
        self
    }

    /// Number of generate/stream calls so far.
    pub fn call_count(&self) -> usize {
        self.inner.call_count.load(Ordering::Relaxed)
    }

    /// # Errors
    /// Returns [`ToolError`] if the tool execution fails.
    pub fn resolve(&self, mi: &ModelInteraction) -> GenerationResult<Vec<Messages>> {
        self.inner.resolve(mi)
    }
}

impl MockInner {
    fn resolve(&self, mi: &ModelInteraction) -> GenerationResult<Vec<Messages>> {
        let n = self.call_count.fetch_add(1, Ordering::Relaxed);

        for f in self.failures.read().expect("mock failures poisoned").iter() {
            if (f.matcher)(mi, n) {
                return Err(crate::errors::GenerationError::Generic(f.error.clone()));
            }
        }

        for s in self.scripts.read().expect("mock scripts poisoned").iter() {
            if (s.matcher)(mi, n) {
                return Ok(s.replies.clone());
            }
        }

        Err(crate::errors::GenerationError::Generic(
            "MockModelProvider: no matching script for interaction".into(),
        ))
    }
}

impl MockModelProvider {
    /// Wrap this mock into a `ProviderRouter` (single-provider mode).
    #[must_use]
    pub fn into_router(self) -> ProviderRouter {
        ProviderRouter::single(Box::new(self))
    }
}

impl Default for MockModelProvider {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// RoutableProvider for MockModelProvider
// ---------------------------------------------------------------------------

impl RoutableProvider for MockModelProvider {
    fn name(&self) -> &str {
        &self.name
    }

    fn provider_id(&self) -> ModelProviders {
        ModelProviders::Custom("mock".into())
    }

    fn describe(&self) -> Option<ModelProviderDescriptor> {
        None
    }

    fn serves(&self, _model_id: &ModelId) -> bool {
        true
    }

    fn get_one(&self, model_id: &ModelId) -> Option<ModelSpec> {
        Some(ModelSpec {
            name: model_id.name().to_owned(),
            id: model_id.clone(),
            devices: None,
            model_location: None,
            lora_location: None,
        })
    }

    fn get_all(&self, model_id: &ModelId) -> Vec<ModelSpec> {
        self.get_one(model_id).into_iter().collect()
    }

    fn get_model(&self, model_id: &ModelId) -> Option<BoxModel> {
        Some(Box::new(MockModel {
            inner: Arc::clone(&self.inner),
            model_id: model_id.clone(),
        }))
    }
}

// ---------------------------------------------------------------------------
// MockModel — Model impl with scripted responses
// ---------------------------------------------------------------------------

/// A `Model` that replays scripted responses from a shared `MockModelProvider`.
/// Created internally; tests interact through `MockModelProvider`.
pub struct MockModel {
    inner: Arc<MockInner>,
    model_id: ModelId,
}

impl crate::types::Model for MockModel {
    fn spec(&self) -> ModelSpec {
        ModelSpec {
            name: self.model_id.name().to_owned(),
            id: self.model_id.clone(),
            devices: None,
            model_location: None,
            lora_location: None,
        }
    }

    fn tool_formatter(&self) -> Box<dyn ToolFormatter> {
        Box::new(TextBasedFormatter)
    }

    fn descriptor(&self) -> Option<ModelProviderDescriptor> {
        None
    }

    fn costing(&self) -> GenerationResult<UsageReport> {
        Ok(zero_usage())
    }

    fn generate(
        &self,
        interaction: ModelInteraction,
        _specs: Option<ModelParams>,
    ) -> GenerationResult<Vec<Messages>> {
        self.inner.resolve(&interaction)
    }

    fn stream(
        &self,
        interaction: ModelInteraction,
        _specs: Option<ModelParams>,
    ) -> GenerationResult<ModelStreamBox> {
        let messages = self.inner.resolve(&interaction)?;
        Ok(Box::new(MockStreamIterator::new(messages)))
    }
}

// ---------------------------------------------------------------------------
// MockStreamIterator — replay messages as Stream items
// ---------------------------------------------------------------------------

pub struct MockStreamIterator {
    items: Vec<Messages>,
    pos: usize,
    sent_init: bool,
}

impl MockStreamIterator {
    #[must_use]
    pub fn new(items: Vec<Messages>) -> Self {
        Self {
            items,
            pos: 0,
            sent_init: false,
        }
    }
}

impl Iterator for MockStreamIterator {
    type Item = Stream<Messages, ModelState>;

    fn next(&mut self) -> Option<Self::Item> {
        if !self.sent_init {
            self.sent_init = true;
            return Some(Stream::Init);
        }
        if self.pos < self.items.len() {
            let msg = self.items[self.pos].clone();
            self.pos += 1;
            Some(Stream::Next(msg))
        } else {
            None
        }
    }
}

// ---------------------------------------------------------------------------
// Message builder helpers
// ---------------------------------------------------------------------------

/// Build an `Assistant` text message with zeroed usage.
#[must_use]
pub fn mock_text(s: &str) -> Messages {
    mock_text_usage(s, zero_usage())
}

/// Build an `Assistant` text message with custom `UsageReport`.
#[must_use]
pub fn mock_text_usage(s: &str, usage: UsageReport) -> Messages {
    Messages::Assistant {
        id: foundation_compact::ids::new_scru128(),
        model: ModelId::Name("mock".into(), None),
        timestamp: foundation_compact::SystemTime::UNIX_EPOCH,
        usage,
        content: ModelOutput::Text(TextContent {
            content: s.into(),
            signature: None,
        }),
        stop_reason: StopReason::Stop,
        provider: ModelProviders::Custom("mock".into()),
        error_detail: None,
        signature: None,
        metadata: None,
    }
}

/// Build an `Assistant` tool-call message.
#[must_use]
#[allow(clippy::implicit_hasher)]
pub fn mock_tool_call(name: &str, args: HashMap<String, crate::types::ArgType>) -> Messages {
    Messages::Assistant {
        id: foundation_compact::ids::new_scru128(),
        model: ModelId::Name("mock".into(), None),
        timestamp: foundation_compact::SystemTime::UNIX_EPOCH,
        usage: zero_usage(),
        content: ModelOutput::ToolCall {
            id: format!("call_{name}"),
            name: name.into(),
            arguments: Some(args),
            signature: None,
            depends_on: Vec::new(),
            execution_hint: crate::types::ExecutionHint::Unspecified,
        },
        stop_reason: StopReason::ToolUse,
        provider: ModelProviders::Custom("mock".into()),
        error_detail: None,
        signature: None,
        metadata: None,
    }
}

/// Build a `User` text message (convenience for test prompts).
#[must_use]
pub fn mock_user(s: &str) -> Messages {
    Messages::User {
        id: foundation_compact::ids::new_scru128(),
        role: MessageRole::User,
        content: UserModelContent::Text(TextContent {
            content: s.into(),
            signature: None,
        }),
        signature: None,
    }
}

/// Zeroed `UsageReport` for test messages.
#[must_use]
pub fn zero_usage() -> UsageReport {
    UsageReport {
        input: 0.0,
        output: 0.0,
        cache_read: 0.0,
        cache_write: 0.0,
        total_tokens: 0.0,
        cost: UsageCosting::zero(CostStatus::Estimated),
    }
}

// ---------------------------------------------------------------------------
// Standard matchers
// ---------------------------------------------------------------------------

/// True when the last `User` message content contains `needle`.
pub fn last_user_contains(needle: &str) -> impl Fn(&ModelInteraction) -> bool + Send + Sync + '_ {
    move |mi: &ModelInteraction| {
        mi.messages.iter().rev().any(|m| matches!(
            m,
            Messages::User { content: UserModelContent::Text(t), .. } if t.content.contains(needle)
        ))
    }
}

/// True when the `ToolShed` contains a tool named `name`.
pub fn tools_shed_has(name: impl Into<String>) -> impl Fn(&ModelInteraction) -> bool + Send + Sync {
    let name = name.into();
    move |mi: &ModelInteraction| mi.tools_shed.all_tools().iter().any(|t| t.name() == name)
}

/// True when the system prompt contains `needle`.
pub fn system_prompt_contains(
    needle: impl Into<String>,
) -> impl Fn(&ModelInteraction) -> bool + Send + Sync {
    let needle = needle.into();
    move |mi: &ModelInteraction| {
        mi.system_prompt
            .as_ref()
            .is_some_and(|sp| sp.contains(&needle))
    }
}

// ---------------------------------------------------------------------------
// MockTool — ToolImpl with scripted behaviors
// ---------------------------------------------------------------------------

/// Scripted behavior for a `MockTool`.
pub enum ToolBehavior {
    /// Always return this result.
    Returns(ToolCallResult),
    /// Always fail with this error.
    Fails(ToolError),
    /// Fail `failures` times, then succeed (drives F11 retry tests).
    FailsThenSucceeds {
        failures: u32,
        error: ToolError,
        result: ToolCallResult,
    },
}

/// A mock tool implementing `ToolImpl` (F09) with scripted behavior.
pub struct MockTool {
    pub name: String,
    pub description: String,
    pub category: String,
    pub behavior: ToolBehavior,
    attempt: AtomicU32,
}

impl MockTool {
    #[must_use]
    pub fn new(name: impl Into<String>, behavior: ToolBehavior) -> Self {
        Self {
            name: name.into(),
            description: "mock tool".into(),
            // Default to a recognized category so the tool actually populates
            // the ToolShed handed to the model (build_toolshed groups by
            // category). "mock" is not a recognized slot; "shell" is.
            category: "shell".into(),
            behavior,
            attempt: AtomicU32::new(0),
        }
    }

    /// Builder: set custom description.
    #[must_use]
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = desc.into();
        self
    }

    /// Builder: set the tool category (drives which ToolShed slot it fills).
    #[must_use]
    pub fn with_category(mut self, category: impl Into<String>) -> Self {
        self.category = category.into();
        self
    }

    /// A tool that always returns text content.
    #[must_use]
    pub fn returning(name: impl Into<String>, text: impl Into<String>) -> Self {
        Self::new(
            name,
            ToolBehavior::Returns(ToolCallResult {
                content: UserModelContent::Text(TextContent {
                    content: text.into(),
                    signature: None,
                }),
                error_detail: None,
            }),
        )
    }

    /// A tool that always fails.
    #[must_use]
    pub fn failing(name: impl Into<String>, reason: impl Into<String>) -> Self {
        let n: String = name.into();
        Self::new(
            n.clone(),
            ToolBehavior::Fails(ToolError::Execution {
                tool: n,
                reason: reason.into(),
            }),
        )
    }
}

#[async_trait]
impl ToolImpl for MockTool {
    fn definition(&self) -> crate::types::Tool {
        crate::types::Tool::SingleCommand(ToolDefinition {
            name: self.name.clone(),
            category: self.category.clone(),
            description: self.description.clone(),
            arguments: crate::types::Args::from_value(serde_json::json!({})),
            returns: None,
        })
    }

    async fn execute(
        &self,
        _arguments: HashMap<String, crate::types::ArgType>,
    ) -> Result<ToolCallResult, ToolError> {
        match &self.behavior {
            ToolBehavior::Returns(r) => Ok(r.clone()),
            ToolBehavior::Fails(e) => Err(e.clone()),
            ToolBehavior::FailsThenSucceeds {
                failures,
                error,
                result,
            } => {
                let n = self.attempt.fetch_add(1, Ordering::Relaxed);
                if n < *failures {
                    Err(error.clone())
                } else {
                    Ok(result.clone())
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Tests for the mock substrate itself
// ---------------------------------------------------------------------------