ferrik-core 0.0.3

Core runtime, triple-response engine, AI discovery, and testing framework for Ferrik
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
//! Built-in testing framework (`ferrik::testing`) for Ferrik applications.
//!
//! Spawns an isolated application instance backed by an in-memory SQLite database
//! and exposes a fluent triple-interface client (`HTML`, `JSON`, `.ai`, and MCP).

use axum::body::Body;
use axum::http::{header, HeaderMap, Method, Request, StatusCode};
use axum::Router;
use http_body_util::BodyExt;
use sea_orm::DatabaseConnection;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use std::future::Future;
use tower::ServiceExt;

use crate::db;

/// Isolated test harness wrapping an Axum [`Router`] and an in-memory SQLite database.
pub struct TestApp {
    router: Router,
    db: DatabaseConnection,
}

impl TestApp {
    /// Creates a `TestApp` from an existing router and database connection.
    pub fn from_router(router: Router, db: DatabaseConnection) -> Self {
        Self { router, db }
    }

    /// Spawns a new `TestApp` with an isolated in-memory SQLite database.
    ///
    /// The `builder` closure receives the freshly created [`DatabaseConnection`],
    /// runs any pending migrations, and returns the application [`Router`].
    #[cfg(feature = "db-sqlite")]
    pub async fn spawn_with<F, Fut>(builder: F) -> Self
    where
        F: FnOnce(DatabaseConnection) -> Fut,
        Fut: Future<Output = Router>,
    {
        let db = db::connect_in_memory()
            .await
            .expect("Failed to connect to in-memory SQLite database for TestApp");
        let router = builder(db.clone()).await;
        Self { router, db }
    }

    /// Returns a reference to the test database connection.
    pub fn db(&self) -> &DatabaseConnection {
        &self.db
    }

    /// Sends a `GET` request expecting HTML (`Accept: text/html`).
    pub async fn get_html(&self, path: &str) -> TestResponse {
        self.send(
            Method::GET,
            path,
            &[(header::ACCEPT.as_str(), "text/html")],
            Body::empty(),
        )
        .await
    }

    /// Sends a `POST` request with URL-encoded form data.
    pub async fn post_form(&self, path: &str, fields: &[(&str, &str)]) -> TestResponse {
        let encoded = encode_form(fields);
        self.send(
            Method::POST,
            path,
            &[
                (header::CONTENT_TYPE.as_str(), "application/x-www-form-urlencoded"),
                (header::ACCEPT.as_str(), "text/html"),
            ],
            Body::from(encoded),
        )
        .await
    }

    /// Sends a `GET` request expecting JSON (`Accept: application/json`).
    pub async fn get_json(&self, path: &str) -> TestResponse {
        self.send(
            Method::GET,
            path,
            &[(header::ACCEPT.as_str(), "application/json")],
            Body::empty(),
        )
        .await
    }

    /// Sends a `POST` request with a JSON payload.
    pub async fn post_json<T: Serialize>(&self, path: &str, body: &T) -> TestResponse {
        let payload = serde_json::to_vec(body).expect("Failed to serialize JSON request body");
        self.send(
            Method::POST,
            path,
            &[
                (header::CONTENT_TYPE.as_str(), "application/json"),
                (header::ACCEPT.as_str(), "application/json"),
            ],
            Body::from(payload),
        )
        .await
    }

    /// Sends a `PUT` request with a JSON payload.
    pub async fn put_json<T: Serialize>(&self, path: &str, body: &T) -> TestResponse {
        let payload = serde_json::to_vec(body).expect("Failed to serialize JSON request body");
        self.send(
            Method::PUT,
            path,
            &[
                (header::CONTENT_TYPE.as_str(), "application/json"),
                (header::ACCEPT.as_str(), "application/json"),
            ],
            Body::from(payload),
        )
        .await
    }

    /// Sends a `DELETE` request.
    pub async fn delete(&self, path: &str) -> TestResponse {
        self.send(
            Method::DELETE,
            path,
            &[(header::ACCEPT.as_str(), "application/json")],
            Body::empty(),
        )
        .await
    }

    /// Sends a `GET` request expecting AI-Native Markdown (`Accept: text/markdown`).
    pub async fn get_ai(&self, path: &str) -> TestResponse {
        self.send(
            Method::GET,
            path,
            &[
                (header::ACCEPT.as_str(), "text/markdown"),
                ("x-agent-mode", "true"),
            ],
            Body::empty(),
        )
        .await
    }

    /// Returns a scoped AI agent test client for authenticated agent and MCP calls.
    pub fn as_agent<'a>(&'a self, scopes: &[&str]) -> AgentTestClient<'a> {
        AgentTestClient {
            app: self,
            scopes: scopes.iter().map(|s| s.to_string()).collect(),
            api_key: None,
        }
    }

    async fn send(
        &self,
        method: Method,
        path: &str,
        headers: &[(&str, &str)],
        body: Body,
    ) -> TestResponse {
        let mut builder = Request::builder().method(method).uri(path);
        for (name, value) in headers {
            builder = builder.header(*name, *value);
        }
        let request = builder.body(body).expect("Failed to build test HTTP request");
        let response = self
            .router
            .clone()
            .oneshot(request)
            .await
            .expect("Router service error during test");

        let status = response.status();
        let resp_headers = response.headers().clone();
        let bytes = response
            .into_body()
            .collect()
            .await
            .expect("Failed to read test response body")
            .to_bytes();
        let body_text = String::from_utf8_lossy(&bytes).to_string();

        TestResponse {
            status,
            headers: resp_headers,
            body: body_text,
        }
    }
}

/// Fluent test client scoped to an AI agent identity.
pub struct AgentTestClient<'a> {
    app: &'a TestApp,
    scopes: Vec<String>,
    api_key: Option<String>,
}

impl<'a> AgentTestClient<'a> {
    /// Attaches a bearer Agent API Key (`ferrik_ak_...`) to requests made by this client.
    pub fn with_api_key(mut self, key: impl Into<String>) -> Self {
        self.api_key = Some(key.into());
        self
    }

    /// Sends an AI-mode `GET` request with agent headers.
    pub async fn get_ai(&self, path: &str) -> TestResponse {
        let scopes_header = self.scopes.join(",");
        let mut headers = vec![
            (header::ACCEPT.as_str(), "text/markdown"),
            ("x-agent-mode", "true"),
            ("x-agent-scopes", scopes_header.as_str()),
        ];
        let auth_val;
        if let Some(key) = &self.api_key {
            auth_val = format!("Bearer {}", key);
            headers.push((header::AUTHORIZATION.as_str(), auth_val.as_str()));
        }
        self.app
            .send(Method::GET, path, &headers, Body::empty())
            .await
    }

    /// Invokes an MCP tool via JSON-RPC `POST /mcp`.
    pub async fn call_mcp_tool(&self, tool_name: &str, arguments: Value) -> TestResponse {
        let rpc = serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "tools/call",
            "params": {
                "name": tool_name,
                "arguments": arguments
            }
        });
        let payload = serde_json::to_vec(&rpc).expect("Failed to serialize MCP payload");
        let scopes_header = self.scopes.join(",");
        let mut headers = vec![
            (header::CONTENT_TYPE.as_str(), "application/json"),
            (header::ACCEPT.as_str(), "application/json"),
            ("x-agent-scopes", scopes_header.as_str()),
        ];
        let auth_val;
        if let Some(key) = &self.api_key {
            auth_val = format!("Bearer {}", key);
            headers.push((header::AUTHORIZATION.as_str(), auth_val.as_str()));
        }
        self.app
            .send(Method::POST, "/mcp", &headers, Body::from(payload))
            .await
    }
}

/// Captured HTTP response with fluent assertion helpers.
#[derive(Debug, Clone)]
pub struct TestResponse {
    status: StatusCode,
    headers: HeaderMap,
    body: String,
}

impl TestResponse {
    pub fn status(&self) -> StatusCode {
        self.status
    }

    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    pub fn text(&self) -> &str {
        &self.body
    }

    pub fn json<T: DeserializeOwned>(&self) -> T {
        serde_json::from_str(&self.body).unwrap_or_else(|e| {
            panic!(
                "Failed to parse JSON response ({}): {}\nBody: {}",
                self.status, e, self.body
            )
        })
    }

    pub fn assert_status(&self, expected: StatusCode) -> &Self {
        assert_eq!(
            self.status, expected,
            "Expected HTTP {}, got {}.\nBody:\n{}",
            expected, self.status, self.body
        );
        self
    }

    pub fn assert_ok(&self) -> &Self {
        self.assert_status(StatusCode::OK)
    }

    pub fn assert_contains(&self, needle: &str) -> &Self {
        assert!(
            self.body.contains(needle),
            "Expected response body to contain {:?}, but it did not.\nBody:\n{}",
            needle,
            self.body
        );
        self
    }

    pub fn assert_header_contains(&self, name: &str, needle: &str) -> &Self {
        let actual = self
            .headers
            .get(name)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");
        assert!(
            actual.contains(needle),
            "Expected header '{}' to contain {:?}, got {:?}",
            name,
            needle,
            actual
        );
        self
    }

    /// Asserts that an `.ai` Markdown response exposes the given action affordance name.
    pub fn assert_has_action(&self, action_name: &str) -> &Self {
        let marker = format!("**{}**", action_name);
        assert!(
            self.body.contains("## Available Actions") && self.body.contains(&marker),
            "Expected AI response to include action {:?} under '## Available Actions'.\nBody:\n{}",
            action_name,
            self.body
        );
        self
    }
}

fn encode_form(fields: &[(&str, &str)]) -> String {
    fields
        .iter()
        .map(|(k, v)| format!("{}={}", percent_encode(k), percent_encode(v)))
        .collect::<Vec<_>>()
        .join("&")
}

fn percent_encode(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for byte in input.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(byte as char);
            }
            b' ' => out.push('+'),
            other => out.push_str(&format!("%{:02X}", other)),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::response::{ActionAffordance, ActionResponse, Format};
    use axum::routing::{delete, get, post};
    use axum::Json;
    use serde::Deserialize;

    #[derive(Debug, Serialize, Deserialize, PartialEq)]
    struct Item {
        name: String,
    }

    async fn demo_handler(Format(fmt): Format) -> ActionResponse<Item> {
        ActionResponse::new(
            fmt,
            Item {
                name: "widget".into(),
            },
        )
        .with_title("Demo")
        .with_canonical_url("/items")
        .with_html("<main><h1>Demo</h1></main>")
        .with_action(ActionAffordance::new(
            "create_item",
            "POST",
            "/items",
            "Create item",
        ))
    }

    async fn echo_json(Json(item): Json<Item>) -> Json<Item> {
        Json(item)
    }

    async fn delete_item() -> StatusCode {
        StatusCode::NO_CONTENT
    }

    async fn form_handler(body: String) -> String {
        body
    }

    #[tokio::test]
    async fn test_app_supports_html_json_ai_and_agent_clients() {
        let app = TestApp::spawn_with(|_db| async {
            Router::new()
                .route("/items", get(demo_handler).post(echo_json).put(echo_json))
                .route("/items/1", delete(delete_item))
                .route("/form", post(form_handler))
                .route("/mcp", post(|Json(v): Json<Value>| async move { Json(v) }))
        })
        .await;

        app.db().ping().await.unwrap();

        app.get_html("/items")
            .await
            .assert_ok()
            .assert_contains("<h1>Demo</h1>")
            .assert_header_contains("link", "/.well-known/ferrik-agent.json");

        let item: Item = app.get_json("/items").await.assert_ok().json();
        assert_eq!(item.name, "widget");

        app.get_ai("/items")
            .await
            .assert_ok()
            .assert_contains("canonical_url: /items")
            .assert_has_action("create_item");

        let created: Item = app
            .post_json("/items", &Item { name: "new".into() })
            .await
            .assert_ok()
            .json();
        assert_eq!(created.name, "new");

        let updated: Item = app
            .put_json("/items", &Item { name: "upd".into() })
            .await
            .assert_ok()
            .json();
        assert_eq!(updated.name, "upd");

        app.delete("/items/1")
            .await
            .assert_status(StatusCode::NO_CONTENT);

        app.post_form("/form", &[("title", "hello world!")])
            .await
            .assert_ok()
            .assert_contains("title=hello+world%21");

        let agent = app.as_agent(&["items:read", "items:write"]).with_api_key("ferrik_ak_test");
        agent.get_ai("/items").await.assert_ok().assert_has_action("create_item");

        let mcp: Value = agent
            .call_mcp_tool("items_create", serde_json::json!({ "name": "bot" }))
            .await
            .assert_ok()
            .json();
        assert_eq!(mcp["params"]["name"], "items_create");
    }
}