ferrik-core 0.0.2

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
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
//! Triple-response engine (`ActionResponse<T>`) supporting HTML (Askama), JSON, and AI Markdown.

use askama::Template;
use axum::async_trait;
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum::http::{header, HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use schemars::{schema_for, JsonSchema};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::convert::Infallible;

use crate::discovery::discovery_link_header;
use crate::error::AppError;

/// Target representation negotiated from the incoming HTTP request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResponseFormat {
    Html,
    Json,
    Ai,
}

/// Axum extractor that negotiates [`ResponseFormat`] from URL patterns and HTTP headers.
///
/// Priority:
/// 1. Explicit URL suffix/prefix: `.json` -> `Json`, `.ai` or `/ai` or `/ai/*` -> `Ai`, `.html` -> `Html`
/// 2. `X-Agent-Mode: true` header -> `Ai`
/// 3. `Accept` header: `text/markdown` -> `Ai`, `application/json` -> `Json`
/// 4. Fallback -> `Html`
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Format(pub ResponseFormat);

impl Format {
    /// Resolves the response format from a request path and headers.
    pub fn negotiate(path: &str, headers: &axum::http::HeaderMap) -> ResponseFormat {
        if path.ends_with(".json") {
            return ResponseFormat::Json;
        }
        if path.ends_with(".ai") || path == "/ai" || path.starts_with("/ai/") {
            return ResponseFormat::Ai;
        }
        if path.ends_with(".html") {
            return ResponseFormat::Html;
        }

        if let Some(val) = headers.get("x-agent-mode").and_then(|v| v.to_str().ok()) {
            if val.eq_ignore_ascii_case("true") || val == "1" {
                return ResponseFormat::Ai;
            }
        }

        if let Some(accept) = headers.get(header::ACCEPT).and_then(|v| v.to_str().ok()) {
            let lower = accept.to_ascii_lowercase();
            if lower.contains("text/markdown") {
                return ResponseFormat::Ai;
            }
            if lower.contains("application/json") && !lower.contains("text/html") {
                return ResponseFormat::Json;
            }
        }

        ResponseFormat::Html
    }
}

#[async_trait]
impl<S> FromRequestParts<S> for Format
where
    S: Send + Sync,
{
    type Rejection = Infallible;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        Ok(Format(Self::negotiate(parts.uri.path(), &parts.headers)))
    }
}

/// Describes a next available action (affordance) exposed in `.ai` responses and manifests.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ActionAffordance {
    pub name: String,
    pub method: String,
    pub path: String,
    pub description: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_schema: Option<Value>,
}

impl ActionAffordance {
    /// Creates an affordance without an input schema (e.g., `GET` or `DELETE` actions).
    pub fn new(
        name: impl Into<String>,
        method: impl Into<String>,
        path: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            method: method.into(),
            path: path.into(),
            description: description.into(),
            input_schema: None,
        }
    }

    /// Creates an affordance with a `schemars`-generated JSON Schema for its input DTO.
    pub fn with_schema<D: JsonSchema>(
        name: impl Into<String>,
        method: impl Into<String>,
        path: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        let schema = serde_json::to_value(schema_for!(D)).ok();
        Self {
            name: name.into(),
            method: method.into(),
            path: path.into(),
            description: description.into(),
            input_schema: schema,
        }
    }
}

/// YAML frontmatter rendered at the top of `.ai` responses.
#[derive(Debug, Clone, Serialize)]
struct AiFrontmatter {
    canonical_url: String,
    title: String,
    status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pagination: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    flash: Option<String>,
}

/// Single-handler, triple-representation controller return type.
///
/// Renders HTML (Askama), JSON, or AI-Native Markdown from the same typed payload `T`.
pub struct ActionResponse<T: Serialize> {
    pub data: T,
    pub format: ResponseFormat,
    pub status: StatusCode,
    pub html: Option<String>,
    pub html_redirect: Option<String>,
    pub canonical_url: String,
    pub title: String,
    pub ai_alternate_url: Option<String>,
    pub actions: Vec<ActionAffordance>,
    pub flash: Option<String>,
    pub pagination: Option<Value>,
}

impl<T: Serialize> ActionResponse<T> {
    /// Creates a new `ActionResponse` for the negotiated format and typed payload.
    pub fn new(format: ResponseFormat, data: T) -> Self {
        Self {
            data,
            format,
            status: StatusCode::OK,
            html: None,
            html_redirect: None,
            canonical_url: "/".to_string(),
            title: "Ferrik".to_string(),
            ai_alternate_url: None,
            actions: Vec::new(),
            flash: None,
            pagination: None,
        }
    }

    /// Sets pre-rendered HTML for `ResponseFormat::Html`.
    pub fn with_html(mut self, html: impl Into<String>) -> Self {
        self.html = Some(html.into());
        self
    }

    /// Renders a compile-time checked Askama template for `ResponseFormat::Html`.
    ///
    /// Template rendering is skipped when the negotiated format is `Json` or `Ai`.
    pub fn with_template<Tmpl: Template>(mut self, template: &Tmpl) -> Result<Self, AppError> {
        if self.format == ResponseFormat::Html {
            self.html = Some(template.render()?);
        }
        Ok(self)
    }

    /// Sets an HTTP 303 See Other redirect target used only for `ResponseFormat::Html`
    /// (PRG pattern for form submissions). JSON and AI responses still return the typed payload.
    pub fn with_html_redirect(mut self, location: impl Into<String>) -> Self {
        self.html_redirect = Some(location.into());
        self
    }

    pub fn with_status(mut self, status: StatusCode) -> Self {
        self.status = status;
        self
    }

    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    pub fn with_canonical_url(mut self, url: impl Into<String>) -> Self {
        self.canonical_url = url.into();
        self
    }

    pub fn with_ai_alternate(mut self, url: impl Into<String>) -> Self {
        self.ai_alternate_url = Some(url.into());
        self
    }

    pub fn with_action(mut self, action: ActionAffordance) -> Self {
        self.actions.push(action);
        self
    }

    pub fn with_actions(mut self, actions: Vec<ActionAffordance>) -> Self {
        self.actions.extend(actions);
        self
    }

    pub fn with_flash(mut self, flash: impl Into<String>) -> Self {
        self.flash = Some(flash.into());
        self
    }

    pub fn with_pagination(mut self, pagination: Value) -> Self {
        self.pagination = Some(pagination);
        self
    }

    /// Renders the deterministic three-section AI-Native Markdown representation.
    pub fn render_ai_markdown(&self) -> String {
        let frontmatter = AiFrontmatter {
            canonical_url: self.canonical_url.clone(),
            title: self.title.clone(),
            status: if self.status.is_success() {
                "ok".to_string()
            } else {
                format!("error_{}", self.status.as_u16())
            },
            pagination: self.pagination.clone(),
            flash: self.flash.clone(),
        };

        let yaml = serde_yaml::to_string(&frontmatter).unwrap_or_default();
        let mut out = String::new();
        out.push_str("---\n");
        out.push_str(&yaml);
        out.push_str("---\n\n");

        out.push_str(&format!("# {}\n\n", self.title));
        out.push_str("## Data\n\n");

        let value = serde_json::to_value(&self.data).unwrap_or(Value::Null);
        out.push_str(&render_json_as_markdown(&value));

        out.push_str("\n## Available Actions\n\n");
        if self.actions.is_empty() {
            out.push_str("No actions available.\n");
        } else {
            for action in &self.actions {
                out.push_str(&format!(
                    "- **{}** (`{} {}`): {}\n",
                    action.name, action.method, action.path, action.description
                ));
                if let Some(schema) = &action.input_schema {
                    if let Ok(pretty) = serde_json::to_string_pretty(schema) {
                        out.push_str("  ```json\n");
                        for line in pretty.lines() {
                            out.push_str("  ");
                            out.push_str(line);
                            out.push('\n');
                        }
                        out.push_str("  ```\n");
                    }
                }
            }
        }

        out
    }

    fn resolved_ai_alternate(&self) -> String {
        if let Some(url) = &self.ai_alternate_url {
            return url.clone();
        }
        if self.canonical_url == "/" {
            "/ai".to_string()
        } else {
            format!("{}.ai", self.canonical_url.trim_end_matches('/'))
        }
    }
}

impl<T: Serialize> IntoResponse for ActionResponse<T> {
    fn into_response(self) -> Response {
        match self.format {
            ResponseFormat::Json => {
                let body = serde_json::to_string(&self.data).unwrap_or_else(|_| "{}".to_string());
                (
                    self.status,
                    [(header::CONTENT_TYPE, "application/json; charset=utf-8")],
                    body,
                )
                    .into_response()
            }
            ResponseFormat::Ai => {
                let md = self.render_ai_markdown();
                (
                    self.status,
                    [(header::CONTENT_TYPE, "text/markdown; charset=utf-8")],
                    md,
                )
                    .into_response()
            }
            ResponseFormat::Html => {
                if let Some(location) = self.html_redirect {
                    return axum::response::Redirect::to(&location).into_response();
                }
                let html = self.html.clone().unwrap_or_else(|| {
                    format!(
                        "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>{}</title></head><body><main><h1>{}</h1></main></body></html>",
                        self.title, self.title
                    )
                });
                let link_header = discovery_link_header(&self.resolved_ai_alternate());
                let mut resp = (
                    self.status,
                    [(header::CONTENT_TYPE, "text/html; charset=utf-8")],
                    html,
                )
                    .into_response();
                if let Ok(hv) = HeaderValue::from_str(&link_header) {
                    resp.headers_mut().insert(header::LINK, hv);
                }
                resp
            }
        }
    }
}

/// Converts a JSON value into compact, deterministic Markdown tables or lists.
fn render_json_as_markdown(value: &Value) -> String {
    match value {
        Value::Object(map) => {
            if map.is_empty() {
                return "_Empty object._\n".to_string();
            }
            let mut out = String::from("| Field | Value |\n| :--- | :--- |\n");
            for (k, v) in map {
                out.push_str(&format!("| {} | {} |\n", escape_md_cell(k), format_scalar(v)));
            }
            out
        }
        Value::Array(items) => {
            if items.is_empty() {
                return "_No records found._\n".to_string();
            }
            if let Some(Value::Object(first)) = items.first() {
                let columns: Vec<&String> = first.keys().collect();
                let mut out = String::new();
                out.push('|');
                for col in &columns {
                    out.push_str(&format!(" {} |", escape_md_cell(col)));
                }
                out.push('\n');
                out.push('|');
                for _ in &columns {
                    out.push_str(" :--- |");
                }
                out.push('\n');
                for item in items {
                    if let Value::Object(obj) = item {
                        out.push('|');
                        for col in &columns {
                            let cell = obj.get(*col).map(format_scalar).unwrap_or_default();
                            out.push_str(&format!(" {} |", cell));
                        }
                        out.push('\n');
                    }
                }
                out
            } else {
                let mut out = String::new();
                for item in items {
                    out.push_str(&format!("- {}\n", format_scalar(item)));
                }
                out
            }
        }
        other => format!("{}\n", format_scalar(other)),
    }
}

fn format_scalar(value: &Value) -> String {
    match value {
        Value::Null => "null".to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
        Value::String(s) => escape_md_cell(s),
        Value::Array(_) | Value::Object(_) => {
            escape_md_cell(&serde_json::to_string(value).unwrap_or_default())
        }
    }
}

fn escape_md_cell(input: &str) -> String {
    input.replace('|', "\\|").replace('\n', " ")
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::HeaderMap;
    use http_body_util::BodyExt;

    #[derive(Serialize, JsonSchema)]
    struct SamplePost {
        id: i32,
        title: String,
    }

    #[derive(Template)]
    #[template(source = "<main><h1>{{ title }}</h1></main>", ext = "html")]
    struct SampleTemplate {
        title: String,
    }

    async fn read_body(resp: Response) -> String {
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        String::from_utf8(bytes.to_vec()).unwrap()
    }

    #[test]
    fn negotiates_format_from_url_and_headers() {
        let empty = HeaderMap::new();
        assert_eq!(Format::negotiate("/posts", &empty), ResponseFormat::Html);
        assert_eq!(Format::negotiate("/posts.html", &empty), ResponseFormat::Html);
        assert_eq!(Format::negotiate("/posts.json", &empty), ResponseFormat::Json);
        assert_eq!(Format::negotiate("/posts.ai", &empty), ResponseFormat::Ai);
        assert_eq!(Format::negotiate("/ai", &empty), ResponseFormat::Ai);
        assert_eq!(Format::negotiate("/ai/posts", &empty), ResponseFormat::Ai);

        let mut agent_headers = HeaderMap::new();
        agent_headers.insert("x-agent-mode", HeaderValue::from_static("true"));
        assert_eq!(Format::negotiate("/posts", &agent_headers), ResponseFormat::Ai);

        let mut md_headers = HeaderMap::new();
        md_headers.insert(header::ACCEPT, HeaderValue::from_static("text/markdown"));
        assert_eq!(Format::negotiate("/posts", &md_headers), ResponseFormat::Ai);

        let mut json_headers = HeaderMap::new();
        json_headers.insert(header::ACCEPT, HeaderValue::from_static("application/json"));
        assert_eq!(Format::negotiate("/posts", &json_headers), ResponseFormat::Json);
    }

    #[tokio::test]
    async fn renders_html_with_askama_and_link_header() {
        let tmpl = SampleTemplate {
            title: "Hello".into(),
        };
        let resp = ActionResponse::new(
            ResponseFormat::Html,
            SamplePost {
                id: 1,
                title: "Hello".into(),
            },
        )
        .with_title("Hello")
        .with_canonical_url("/posts/1")
        .with_template(&tmpl)
        .unwrap()
        .into_response();

        assert_eq!(resp.status(), StatusCode::OK);
        let link = resp.headers().get(header::LINK).unwrap().to_str().unwrap();
        assert!(link.contains("/.well-known/ferrik-agent.json"));
        assert!(link.contains("/posts/1.ai"));
        let body = read_body(resp).await;
        assert_eq!(body, "<main><h1>Hello</h1></main>");
    }

    #[tokio::test]
    async fn renders_json_payload() {
        let resp = ActionResponse::new(
            ResponseFormat::Json,
            SamplePost {
                id: 42,
                title: "Ferrik".into(),
            },
        )
        .with_status(StatusCode::CREATED)
        .into_response();

        assert_eq!(resp.status(), StatusCode::CREATED);
        let body = read_body(resp).await;
        let parsed: Value = serde_json::from_str(&body).unwrap();
        assert_eq!(parsed["id"], 42);
        assert_eq!(parsed["title"], "Ferrik");
    }

    #[tokio::test]
    async fn renders_ai_markdown_with_frontmatter_table_and_affordances() {
        let posts = vec![
            SamplePost {
                id: 1,
                title: "First".into(),
            },
            SamplePost {
                id: 2,
                title: "Second".into(),
            },
        ];
        let resp = ActionResponse::new(ResponseFormat::Ai, posts)
            .with_title("Posts")
            .with_canonical_url("/posts")
            .with_flash("Loaded 2 posts")
            .with_pagination(serde_json::json!({ "page": 1, "per_page": 20 }))
            .with_action(ActionAffordance::with_schema::<SamplePost>(
                "create_post",
                "POST",
                "/posts",
                "Create a new post",
            ))
            .into_response();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = read_body(resp).await;
        assert!(body.starts_with("---\n"));
        assert!(body.contains("canonical_url: /posts"));
        assert!(body.contains("title: Posts"));
        assert!(body.contains("flash: Loaded 2 posts"));
        assert!(body.contains("| id | title |"));
        assert!(body.contains("| 1 | First |"));
        assert!(body.contains("## Available Actions"));
        assert!(body.contains("**create_post** (`POST /posts`)"));
        assert!(body.contains("\"SamplePost\""));
    }

    #[test]
    fn renders_empty_and_scalar_markdown_cases() {
        assert_eq!(render_json_as_markdown(&serde_json::json!([])), "_No records found._\n");
        assert_eq!(render_json_as_markdown(&serde_json::json!({})), "_Empty object._\n");
        assert_eq!(
            render_json_as_markdown(&serde_json::json!(["a", "b"])),
            "- a\n- b\n"
        );
        assert_eq!(render_json_as_markdown(&serde_json::json!(123)), "123\n");
    }
}