clawft-kernel 0.5.2

WeftOS kernel: boot sequence, process table, service registry, and health subsystem
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
//! HTTP API for WeftOS task execution.
//!
//! Provides a lightweight HTTP endpoint that Paperclip (and other
//! orchestrators) can call to submit tasks to the WeftOS kernel.
//!
//! # Endpoints
//!
//! - `POST /api/v1/execute` -- submit a task for agent execution
//! - `POST /api/v1/govern`  -- evaluate a governance decision
//! - `GET  /api/v1/health`  -- liveness probe
//!
//! # Feature Gate
//!
//! This module is gated behind the `http-api` feature flag and is
//! **not** included in the default feature set.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use crate::governance::{
    EffectVector, GovernanceDecision, GovernanceEngine, GovernanceRequest, GovernanceResult,
};

// ── Request / Response types ──────────────────────────────────

/// Request body for `POST /api/v1/execute`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecuteRequest {
    /// Identifier of the agent to execute the task.
    pub agent_id: String,

    /// Task description or prompt.
    pub task: String,

    /// Additional context passed to the agent pipeline.
    #[serde(default)]
    pub context: HashMap<String, serde_json::Value>,
}

/// Response body for `POST /api/v1/execute`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecuteResponse {
    /// Execution result (agent output).
    pub result: String,

    /// Confidence or quality score (0.0 -- 1.0).
    pub score: f64,

    /// Tokens consumed during execution.
    pub tokens_used: u64,

    /// Unique execution ID for traceability.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_id: Option<String>,
}

/// Request body for `POST /api/v1/govern`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GovernRequest {
    /// Action being proposed.
    pub action: String,

    /// Agent requesting the action.
    pub agent_id: String,

    /// Additional context for governance evaluation.
    #[serde(default)]
    pub context: HashMap<String, serde_json::Value>,
}

/// Response body for `POST /api/v1/govern`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GovernResponse {
    /// Governance decision: `"permit"`, `"deny"`, or `"escalate"`.
    pub decision: String,

    /// Cryptographic attestation (ExoChain hash, if available).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attestation: Option<String>,

    /// Chain hash for audit trail linkage.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub chain_hash: Option<String>,

    /// Rules that were evaluated.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evaluated_rules: Vec<String>,

    /// Effect vector magnitude that was scored.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effect_magnitude: Option<f64>,
}

/// Health check response for `GET /api/v1/health`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthResponse {
    /// Service status: `"ok"` or `"degraded"`.
    pub status: String,

    /// Kernel version.
    pub version: String,

    /// Uptime in seconds (if tracked).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uptime_secs: Option<u64>,
}

/// Error response returned on failure.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorResponse {
    /// Machine-readable error code.
    pub code: String,

    /// Human-readable error message.
    pub message: String,
}

// ── HTTP API handler ──────────────────────────────────────────

/// The kernel-side HTTP API handler.
///
/// This is a transport-agnostic dispatcher: it accepts parsed request
/// types and returns serializable response types. The actual HTTP
/// server binding (hyper, axum, warp, etc.) is left to the binary
/// crate or daemon that embeds the kernel.
///
/// # Example
///
/// ```rust,ignore
/// let handler = HttpApiHandler::new(governance_engine);
/// let resp = handler.handle_execute(request).await;
/// ```
pub struct HttpApiHandler {
    governance: GovernanceEngine,
}

impl HttpApiHandler {
    /// Create a new handler backed by the given governance engine.
    pub fn new(governance: GovernanceEngine) -> Self {
        Self { governance }
    }

    /// Handle `POST /api/v1/execute`.
    ///
    /// In a full integration this would:
    /// 1. Look up the agent by `agent_id` in the process table.
    /// 2. Feed the task through the 7-stage pipeline.
    /// 3. Return the pipeline result.
    ///
    /// This stub validates the request and returns a structured
    /// response so the adapter wire format is exercised end-to-end.
    pub fn handle_execute(&self, req: &ExecuteRequest) -> Result<ExecuteResponse, ErrorResponse> {
        if req.agent_id.is_empty() {
            return Err(ErrorResponse {
                code: "INVALID_AGENT_ID".into(),
                message: "agent_id must not be empty".into(),
            });
        }
        if req.task.is_empty() {
            return Err(ErrorResponse {
                code: "INVALID_TASK".into(),
                message: "task must not be empty".into(),
            });
        }

        // In production, this dispatches to the kernel's agent pipeline.
        // For now, return a well-typed stub so the adapter protocol is
        // fully exercisable.
        let execution_id = uuid::Uuid::new_v4().to_string();
        Ok(ExecuteResponse {
            result: format!("Task accepted for agent '{}'", req.agent_id),
            score: 0.0,
            tokens_used: 0,
            execution_id: Some(execution_id),
        })
    }

    /// Handle `POST /api/v1/govern`.
    ///
    /// Evaluates the proposed action through the WeftOS governance
    /// engine and returns the decision with optional ExoChain
    /// attestation metadata.
    pub fn handle_govern(&self, req: &GovernRequest) -> Result<GovernResponse, ErrorResponse> {
        if req.agent_id.is_empty() {
            return Err(ErrorResponse {
                code: "INVALID_AGENT_ID".into(),
                message: "agent_id must not be empty".into(),
            });
        }
        if req.action.is_empty() {
            return Err(ErrorResponse {
                code: "INVALID_ACTION".into(),
                message: "action must not be empty".into(),
            });
        }

        // Build governance request from the HTTP payload.
        let mut gov_req = GovernanceRequest::new(&req.agent_id, &req.action);

        // Forward string context entries to governance context.
        for (k, v) in &req.context {
            if let Some(s) = v.as_str() {
                gov_req = gov_req.with_context_entry(k, s);
            }
        }

        // Extract effect dimensions from context if provided.
        let effect = extract_effect_vector(&req.context);
        gov_req = gov_req.with_effect(effect);

        let result: GovernanceResult = self.governance.evaluate(&gov_req);

        let decision_str = match &result.decision {
            GovernanceDecision::Permit | GovernanceDecision::PermitWithWarning(_) => {
                "permit".to_string()
            }
            GovernanceDecision::EscalateToHuman(_) => "escalate".to_string(),
            GovernanceDecision::Deny(_) => "deny".to_string(),
        };

        Ok(GovernResponse {
            decision: decision_str,
            attestation: None, // Populated when ExoChain feature is active.
            chain_hash: None,
            evaluated_rules: result.evaluated_rules,
            effect_magnitude: Some(result.effect.magnitude()),
        })
    }

    /// Handle `GET /api/v1/health`.
    pub fn handle_health(&self) -> HealthResponse {
        HealthResponse {
            status: "ok".into(),
            version: env!("CARGO_PKG_VERSION").into(),
            uptime_secs: None,
        }
    }
}

/// Extract an [`EffectVector`] from the context map.
///
/// Looks for keys `"risk"`, `"fairness"`, `"privacy"`, `"novelty"`,
/// `"security"` and parses their values as f64.
fn extract_effect_vector(context: &HashMap<String, serde_json::Value>) -> EffectVector {
    let f = |key: &str| -> f64 {
        context
            .get(key)
            .and_then(|v| v.as_f64())
            .unwrap_or(0.0)
    };
    EffectVector {
        risk: f("risk"),
        fairness: f("fairness"),
        privacy: f("privacy"),
        novelty: f("novelty"),
        security: f("security"),
    }
}

// ── Route dispatch helper ─────────────────────────────────────

/// Route identifier for the HTTP API.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Route {
    /// POST /api/v1/execute
    Execute,
    /// POST /api/v1/govern
    Govern,
    /// GET /api/v1/health
    Health,
    /// Unknown route.
    NotFound,
}

/// Parse a method + path pair into a [`Route`].
pub fn match_route(method: &str, path: &str) -> Route {
    match (method, path) {
        ("POST", "/api/v1/execute") => Route::Execute,
        ("POST", "/api/v1/govern") => Route::Govern,
        ("GET", "/api/v1/health") => Route::Health,
        _ => Route::NotFound,
    }
}

/// Dispatch a raw JSON body to the appropriate handler and return
/// the JSON response bytes.
///
/// This is a convenience function for embedding in a minimal HTTP
/// server without pulling in a framework dependency.
pub fn dispatch(
    handler: &HttpApiHandler,
    route: &Route,
    body: &[u8],
) -> Result<Vec<u8>, Vec<u8>> {
    match route {
        Route::Execute => {
            let req: ExecuteRequest = serde_json::from_slice(body).map_err(|e| {
                serde_json::to_vec(&ErrorResponse {
                    code: "PARSE_ERROR".into(),
                    message: format!("Invalid JSON: {e}"),
                })
                .unwrap_or_default()
            })?;
            match handler.handle_execute(&req) {
                Ok(resp) => serde_json::to_vec(&resp).map_err(|e| {
                    serde_json::to_vec(&ErrorResponse {
                        code: "INTERNAL".into(),
                        message: e.to_string(),
                    })
                    .unwrap_or_default()
                }),
                Err(err) => Err(serde_json::to_vec(&err).unwrap_or_default()),
            }
        }
        Route::Govern => {
            let req: GovernRequest = serde_json::from_slice(body).map_err(|e| {
                serde_json::to_vec(&ErrorResponse {
                    code: "PARSE_ERROR".into(),
                    message: format!("Invalid JSON: {e}"),
                })
                .unwrap_or_default()
            })?;
            match handler.handle_govern(&req) {
                Ok(resp) => serde_json::to_vec(&resp).map_err(|e| {
                    serde_json::to_vec(&ErrorResponse {
                        code: "INTERNAL".into(),
                        message: e.to_string(),
                    })
                    .unwrap_or_default()
                }),
                Err(err) => Err(serde_json::to_vec(&err).unwrap_or_default()),
            }
        }
        Route::Health => {
            let resp = handler.handle_health();
            serde_json::to_vec(&resp).map_err(|e| {
                serde_json::to_vec(&ErrorResponse {
                    code: "INTERNAL".into(),
                    message: e.to_string(),
                })
                .unwrap_or_default()
            })
        }
        Route::NotFound => Err(serde_json::to_vec(&ErrorResponse {
            code: "NOT_FOUND".into(),
            message: "Unknown route".into(),
        })
        .unwrap_or_default()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_handler() -> HttpApiHandler {
        HttpApiHandler::new(GovernanceEngine::open())
    }

    #[test]
    fn test_execute_success() {
        let handler = make_handler();
        let req = ExecuteRequest {
            agent_id: "agent-1".into(),
            task: "summarise document".into(),
            context: HashMap::new(),
        };
        let resp = handler.handle_execute(&req).unwrap();
        assert!(resp.result.contains("agent-1"));
        assert!(resp.execution_id.is_some());
    }

    #[test]
    fn test_execute_empty_agent_id() {
        let handler = make_handler();
        let req = ExecuteRequest {
            agent_id: String::new(),
            task: "do something".into(),
            context: HashMap::new(),
        };
        let err = handler.handle_execute(&req).unwrap_err();
        assert_eq!(err.code, "INVALID_AGENT_ID");
    }

    #[test]
    fn test_execute_empty_task() {
        let handler = make_handler();
        let req = ExecuteRequest {
            agent_id: "a".into(),
            task: String::new(),
            context: HashMap::new(),
        };
        let err = handler.handle_execute(&req).unwrap_err();
        assert_eq!(err.code, "INVALID_TASK");
    }

    #[test]
    fn test_govern_permit() {
        let handler = make_handler();
        let req = GovernRequest {
            action: "read_file".into(),
            agent_id: "agent-1".into(),
            context: HashMap::new(),
        };
        let resp = handler.handle_govern(&req).unwrap();
        assert_eq!(resp.decision, "permit");
    }

    #[test]
    fn test_govern_empty_action() {
        let handler = make_handler();
        let req = GovernRequest {
            action: String::new(),
            agent_id: "a".into(),
            context: HashMap::new(),
        };
        let err = handler.handle_govern(&req).unwrap_err();
        assert_eq!(err.code, "INVALID_ACTION");
    }

    #[test]
    fn test_health() {
        let handler = make_handler();
        let resp = handler.handle_health();
        assert_eq!(resp.status, "ok");
        assert!(!resp.version.is_empty());
    }

    #[test]
    fn test_route_matching() {
        assert_eq!(match_route("POST", "/api/v1/execute"), Route::Execute);
        assert_eq!(match_route("POST", "/api/v1/govern"), Route::Govern);
        assert_eq!(match_route("GET", "/api/v1/health"), Route::Health);
        assert_eq!(match_route("GET", "/api/v1/execute"), Route::NotFound);
        assert_eq!(match_route("DELETE", "/unknown"), Route::NotFound);
    }

    #[test]
    fn test_dispatch_execute() {
        let handler = make_handler();
        let body = serde_json::to_vec(&ExecuteRequest {
            agent_id: "a1".into(),
            task: "hello".into(),
            context: HashMap::new(),
        })
        .unwrap();
        let result = dispatch(&handler, &Route::Execute, &body);
        assert!(result.is_ok());
        let resp: ExecuteResponse = serde_json::from_slice(&result.unwrap()).unwrap();
        assert!(resp.result.contains("a1"));
    }

    #[test]
    fn test_dispatch_invalid_json() {
        let handler = make_handler();
        let result = dispatch(&handler, &Route::Execute, b"not json");
        assert!(result.is_err());
        let err: ErrorResponse = serde_json::from_slice(&result.unwrap_err()).unwrap();
        assert_eq!(err.code, "PARSE_ERROR");
    }

    #[test]
    fn test_dispatch_not_found() {
        let handler = make_handler();
        let result = dispatch(&handler, &Route::NotFound, b"{}");
        assert!(result.is_err());
    }

    #[test]
    fn test_effect_vector_extraction() {
        let mut ctx = HashMap::new();
        ctx.insert("risk".into(), serde_json::json!(0.7));
        ctx.insert("security".into(), serde_json::json!(0.3));
        let ev = extract_effect_vector(&ctx);
        assert!((ev.risk - 0.7).abs() < f64::EPSILON);
        assert!((ev.security - 0.3).abs() < f64::EPSILON);
        assert!((ev.fairness - 0.0).abs() < f64::EPSILON);
    }
}