innate 0.1.22

Innate — self-growing procedural knowledge layer for AI agents
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
//! HTTP routing for `innate web`.
//!
//! `route()` is pure (no IO): it takes the parsed request and returns a `Resp`,
//! so it can be unit-tested without a socket. `handle()` does the tiny_http IO
//! and delegates to `route()`.

use std::collections::HashMap;
use std::io::Read;

use serde_json::{json, Value};
use tiny_http::{Header, Method, Request, Response};

use super::assets;
use crate::KnowledgeBase;

/// Shared, immutable-for-the-loop server context.
pub(crate) struct Ctx {
    pub kb: KnowledgeBase,
    pub token: Option<String>,
    pub bind: String,
    pub port: u16,
}

/// A fully-resolved response, independent of the transport.
pub(crate) struct Resp {
    pub status: u16,
    content_type: &'static str,
    pub body: String,
}

fn json_resp(status: u16, v: Value) -> Resp {
    Resp {
        status,
        content_type: "application/json; charset=utf-8",
        body: v.to_string(),
    }
}

fn err(status: u16, msg: &str) -> Resp {
    json_resp(status, json!({ "error": msg }))
}

fn asset(content_type: &'static str, body: &str) -> Resp {
    Resp {
        status: 200,
        content_type,
        body: body.to_string(),
    }
}

// ── tiny_http glue ──────────────────────────────────────────────────────────

pub(crate) fn handle(ctx: &Ctx, mut request: Request) {
    let method = request.method().clone();
    let raw_url = request.url().to_string();
    let (path, query) = split_url(&raw_url);

    // Lower-cased header map for case-insensitive lookups.
    let mut headers: HashMap<String, String> = HashMap::new();
    for h in request.headers() {
        headers.insert(
            h.field.as_str().as_str().to_ascii_lowercase(),
            h.value.as_str().to_string(),
        );
    }

    // Read the body (governance endpoints carry a small JSON payload).
    let mut body = String::new();
    let _ = request
        .as_reader()
        .take(64 * 1024)
        .read_to_string(&mut body);

    let resp = route(ctx, &method, path, query, &headers, &body);

    let header = Header::from_bytes(&b"Content-Type"[..], resp.content_type.as_bytes())
        .expect("static content-type header is valid");
    let response = Response::from_string(resp.body)
        .with_status_code(resp.status)
        .with_header(header);
    let _ = request.respond(response);
}

// ── pure router ─────────────────────────────────────────────────────────────

pub(crate) fn route(
    ctx: &Ctx,
    method: &Method,
    path: &str,
    query: &str,
    headers: &HashMap<String, String>,
    body: &str,
) -> Resp {
    let segs: Vec<&str> = path.trim_matches('/').split('/').collect();

    // When bound to a non-loopback address the server is network-reachable, so
    // read endpoints must also present the token — otherwise any LAN client can
    // dump the whole knowledge base. On loopback (trusted single user) reads
    // stay open so the local UI needs no token for browsing. Static assets are
    // always public so the page can load and then supply the token via header.
    let is_api = segs.first() == Some(&"api");
    if is_api && !super::is_loopback(&ctx.bind) && !token_ok(ctx, headers) {
        return err(403, "missing or invalid token");
    }

    match (method, segs.as_slice()) {
        // Static assets.
        (Method::Get, [""]) | (Method::Get, ["index.html"]) => {
            asset("text/html; charset=utf-8", assets::INDEX_HTML)
        }
        (Method::Get, ["app.js"]) => asset("application/javascript; charset=utf-8", assets::APP_JS),
        (Method::Get, ["style.css"]) => asset("text/css; charset=utf-8", assets::STYLE_CSS),

        // Read endpoints (token required only on non-loopback binds, see above).
        (Method::Get, ["api", "inspect"]) => match ctx.kb.inspect() {
            Ok(v) => json_resp(200, v),
            Err(e) => err(500, &e.to_string()),
        },
        (Method::Get, ["api", "chunks"]) => list_chunks(ctx, query),
        (Method::Get, ["api", "governance"]) => list_governance(ctx, query),
        (Method::Get, ["api", "metrics", "trend"]) => metrics_trend(ctx, query),
        (Method::Get, ["api", "llm-traces"]) => list_llm_traces(query),
        (Method::Get, ["api", "search"]) => search(ctx, query),
        (Method::Get, ["api", "playground"]) => playground(ctx, query),
        (Method::Get, ["api", "daemon"]) => daemon_status(),
        (Method::Get, ["api", "sessions"]) => list_sessions(ctx, query),
        (Method::Get, ["api", "chunk", id]) => match ctx.kb.inspect_id(id) {
            Ok(v) => json_resp(200, v),
            Err(e) => err(404, &e.to_string()),
        },
        (Method::Get, ["api", "chunks", id, "provenance"]) => chunk_provenance(ctx, id, query),

        // Governance endpoints (token + same-origin required).
        (Method::Post, ["api", "chunk", id, action]) => governance(ctx, headers, id, action, body),
        (Method::Post, ["api", "daemon", "restart"]) => daemon_restart(ctx, headers),

        _ => err(404, "not found"),
    }
}

/// P4: state-KPI snapshot series for the Web trend view (`metric_snapshots`, newest
/// first). `?limit=N` (default 30, max 365). Read-only; empty array before any snapshot.
fn metrics_trend(ctx: &Ctx, query: &str) -> Resp {
    let limit = parse_query(query)
        .get("limit")
        .and_then(|v| v.parse::<usize>().ok())
        .unwrap_or(30)
        .clamp(1, 365);
    match ctx.kb.storage.recent_snapshots(limit) {
        Ok(rows) => json_resp(200, json!({ "snapshots": rows, "limit": limit })),
        Err(e) => err(500, &e.to_string()),
    }
}

fn list_chunks(ctx: &Ctx, query: &str) -> Resp {
    let params = parse_query(query);
    let state = params
        .get("state")
        .map(String::as_str)
        .filter(|s| !s.is_empty());
    let origin = params
        .get("origin")
        .map(String::as_str)
        .filter(|s| !s.is_empty());
    let limit = params
        .get("limit")
        .and_then(|v| v.parse::<usize>().ok())
        .unwrap_or(50)
        .min(500);
    let offset = params
        .get("offset")
        .and_then(|v| v.parse::<usize>().ok())
        .unwrap_or(0);

    match ctx.kb.storage.list_chunks(state, origin, limit, offset) {
        Ok(rows) => json_resp(
            200,
            json!({ "chunks": rows, "limit": limit, "offset": offset }),
        ),
        Err(e) => err(500, &e.to_string()),
    }
}

/// Read-only review queue: chunks the feedback loop has flagged for human
/// adjudication, strongest evidence first. This is what makes the human-review
/// backlog *visible and measurable* in the UI, rather than buried in inspect.
fn list_governance(ctx: &Ctx, query: &str) -> Resp {
    let params = parse_query(query);
    let state = params
        .get("state")
        .map(String::as_str)
        .filter(|s| !s.is_empty())
        .unwrap_or("pending");
    let limit = params
        .get("limit")
        .and_then(|v| v.parse::<usize>().ok())
        .unwrap_or(100)
        .min(500);
    match ctx.kb.storage.list_governance_proposals(state, limit) {
        Ok(rows) => json_resp(200, json!({ "proposals": rows, "state": state })),
        Err(e) => err(500, &e.to_string()),
    }
}

/// Recent LLM/embedding HTTP call traces (newest first) for agent debugging.
/// Reads `~/.innate/logs/llm_trace.log`; does not touch the knowledge db.
/// Optional filters: `kind` (chat|embedding), `status` (ok|http_4xx|rate_limited|…).
fn list_llm_traces(query: &str) -> Resp {
    let params = parse_query(query);
    let kind = params
        .get("kind")
        .map(String::as_str)
        .filter(|s| !s.is_empty());
    let status = params
        .get("status")
        .map(String::as_str)
        .filter(|s| !s.is_empty());
    let limit = params
        .get("limit")
        .and_then(|v| v.parse::<usize>().ok())
        .unwrap_or(200)
        .min(2000);
    match crate::llm_trace::read_recent(limit, kind, status) {
        Ok(traces) => json_resp(200, json!({ "traces": traces, "limit": limit })),
        Err(e) => err(500, &e.to_string()),
    }
}

/// R3 — full-text (FTS5/BM25) search over active chunks. `?q=...&limit=N`
/// (default 20, max 100). Read-only and trace-free (never writes usage traces),
/// so it is safe to call repeatedly from the UI search box. Returns hydrated
/// chunk rows in lexical-relevance order with their normalised BM25 score.
fn search(ctx: &Ctx, query: &str) -> Resp {
    let params = parse_query(query);
    let q = params.get("q").map(String::as_str).unwrap_or("").trim();
    if q.is_empty() {
        return json_resp(200, json!({ "query": "", "results": [] }));
    }
    let limit = params
        .get("limit")
        .and_then(|v| v.parse::<usize>().ok())
        .unwrap_or(20)
        .clamp(1, 100);

    let hits = match ctx.kb.storage.search_lexical(q, limit) {
        Ok(h) => h,
        Err(e) => return err(500, &e.to_string()),
    };
    let ids: Vec<&str> = hits.iter().map(|(id, _)| id.as_str()).collect();
    let chunks = match ctx.kb.storage.get_chunks_by_ids(&ids) {
        Ok(c) => c,
        Err(e) => return err(500, &e.to_string()),
    };
    // Preserve lexical-relevance order and attach each chunk's score.
    let results: Vec<Value> = hits
        .iter()
        .filter_map(|(id, score)| {
            chunks.get(id).map(|chunk| {
                let r3 = (f64::from(*score) * 1000.0).round() / 1000.0;
                json!({ "score": r3, "chunk": chunk })
            })
        })
        .collect();
    json_resp(200, json!({ "query": q, "results": results, "limit": limit }))
}

/// R6 — Recall Playground: run the full fused-score recall and return the packed
/// knowledge (each item carries its `_fused_score`) plus sparks, for debugging
/// retrieval. `trace=false` so this debug tool never pollutes usage traces /
/// episodic logs. `?q=...&budget=N&top=K&include_sparks=bool`.
fn playground(ctx: &Ctx, query: &str) -> Resp {
    let params = parse_query(query);
    let q = params.get("q").map(String::as_str).unwrap_or("").trim();
    if q.is_empty() {
        return json_resp(200, json!({ "query": "", "knowledge": [], "sparks": [] }));
    }
    let budget = params
        .get("budget")
        .and_then(|v| v.parse::<usize>().ok())
        .unwrap_or(6000)
        .clamp(200, 60_000);
    let top = params.get("top").and_then(|v| v.parse::<usize>().ok());
    let include_sparks = params
        .get("include_sparks")
        .map(|v| v == "true" || v == "1")
        .unwrap_or(false);

    let result = ctx.kb.recall(crate::kb::RecallParams {
        query: q,
        budget,
        trace: false,
        include_sparks,
        top,
        // `web` is not a valid event source; the playground is a local debug tool
        // and runs with trace=false (no episodic_log / usage_trace writes), so it
        // tags the operation_run as `cli`.
        source: "cli",
        expand_deps: "false",
        allow_trim: false,
        refine_mode: "off",
        min_score: None,
        session_only: false,
        rerank: false,
    });
    match result {
        Ok(r) => json_resp(
            200,
            json!({
                "query": q,
                "trace_id": r.trace_id,
                "empty": r.empty,
                "knowledge": r.knowledge,
                "sparks": r.sparks,
            }),
        ),
        Err(e) => err(500, &e.to_string()),
    }
}

/// R7 — daemon health/status card. Reuses `daemon::state::health`, which opens
/// the daemon state db read-only and degrades gracefully when the daemon never
/// ran. Independent of the knowledge db.
fn daemon_status() -> Resp {
    let health = crate::daemon::health(
        &crate::paths::daemon_state_path(),
        &crate::paths::daemon_pid_path(),
        &crate::utils::utc_now_iso(),
    );
    json_resp(200, health)
}

/// R7b — restart (or start) the daemon from the UI. Gated exactly like the
/// governance endpoints (same-origin + token) because it mutates system state.
/// Stop is only attempted when the pid is alive — a stale pid file just means
/// the goal state ("running") is reached by starting. Watch dirs come from
/// settings, falling back to the canonical sessions dir so the button works
/// before any daemon config exists. Returns the fresh health snapshot.
fn daemon_restart(ctx: &Ctx, headers: &HashMap<String, String>) -> Resp {
    if !origin_ok(ctx, headers) {
        return err(403, "cross-origin request rejected");
    }
    if !token_ok(ctx, headers) {
        return err(403, "missing or invalid token");
    }
    if !cfg!(target_os = "linux") {
        return err(400, "the daemon is only supported on Linux");
    }

    let pid_file = crate::paths::daemon_pid_path();
    if crate::daemon::is_running(&pid_file) {
        if let Err(e) = crate::daemon::stop(&pid_file) {
            return err(500, &format!("failed to stop daemon: {e}"));
        }
    }

    let settings = crate::settings::load().unwrap_or_default();
    let mut watch_dirs: Vec<std::path::PathBuf> = crate::settings::resolved_watch_dirs(&settings)
        .into_iter()
        .map(std::path::PathBuf::from)
        .collect();
    if watch_dirs.is_empty() {
        watch_dirs.push(crate::paths::sessions_dir());
    }

    if let Err(e) = crate::daemon::start(
        &watch_dirs,
        &ctx.kb.storage.db_path,
        &pid_file,
        &crate::paths::daemon_state_path(),
        &crate::paths::daemon_log_path(),
    ) {
        return err(500, &format!("failed to start daemon: {e}"));
    }
    json_resp(
        200,
        crate::daemon::health(
            &crate::paths::daemon_state_path(),
            &pid_file,
            &crate::utils::utc_now_iso(),
        ),
    )
}

/// R8 — recent recall→record trace timeline ("Sessions"). `?limit=N` (default 50,
/// max 200), newest first. Read-only projection of `episodic_log`.
/// Provenance timeline for a single chunk (usage outcomes + feedback + distill
/// source + confidence explanation). `?limit=N` caps the event list (default 20,
/// max 100). Read-only.
fn chunk_provenance(ctx: &Ctx, id: &str, query: &str) -> Resp {
    let limit = parse_query(query)
        .get("limit")
        .and_then(|v| v.parse::<usize>().ok())
        .unwrap_or(20)
        .clamp(1, 100);
    match ctx.kb.storage.chunk_provenance(id, limit) {
        Ok(v) => json_resp(200, v),
        Err(e) => err(500, &e.to_string()),
    }
}

fn list_sessions(ctx: &Ctx, query: &str) -> Resp {
    let limit = parse_query(query)
        .get("limit")
        .and_then(|v| v.parse::<usize>().ok())
        .unwrap_or(50)
        .clamp(1, 200);
    match ctx.kb.storage.recent_episodic_logs(limit) {
        Ok(rows) => json_resp(200, json!({ "sessions": rows, "limit": limit })),
        Err(e) => err(500, &e.to_string()),
    }
}

fn governance(
    ctx: &Ctx,
    headers: &HashMap<String, String>,
    id: &str,
    action: &str,
    body: &str,
) -> Resp {
    if !origin_ok(ctx, headers) {
        return err(403, "cross-origin request rejected");
    }
    if !token_ok(ctx, headers) {
        return err(403, "missing or invalid token");
    }

    let reason = serde_json::from_str::<Value>(body)
        .ok()
        .and_then(|v| v.get("reason").and_then(|r| r.as_str()).map(String::from))
        .unwrap_or_default();

    let result = match action {
        "approve" => ctx.kb.approve(id),
        "restore" => ctx.kb.restore(id),
        "archive" => {
            if reason.trim().is_empty() {
                return err(400, "archive requires a non-empty reason");
            }
            ctx.kb.archive(id, &reason)
        }
        "invalidate" => {
            if reason.trim().is_empty() {
                return err(400, "invalidate requires a non-empty reason");
            }
            ctx.kb.invalidate(id, &reason)
        }
        _ => return err(404, "unknown governance action"),
    };

    match result {
        Ok(()) => json_resp(200, json!({ "ok": true, "id": id, "action": action })),
        Err(e) => err(400, &e.to_string()),
    }
}

// ── security helpers ────────────────────────────────────────────────────────

fn token_ok(ctx: &Ctx, headers: &HashMap<String, String>) -> bool {
    match &ctx.token {
        None => true, // --no-token mode
        Some(expected) => headers
            .get("x-innate-token")
            .is_some_and(|got| got == expected),
    }
}

/// CSRF defense: a browser always sends `Origin` on cross-site POSTs. Absent
/// `Origin` (non-browser clients like curl) is allowed but still needs the token.
fn origin_ok(ctx: &Ctx, headers: &HashMap<String, String>) -> bool {
    match headers.get("origin") {
        None => true,
        Some(o) => {
            let mut allowed = vec![
                format!("http://127.0.0.1:{}", ctx.port),
                format!("http://localhost:{}", ctx.port),
                format!("http://{}:{}", ctx.bind, ctx.port),
            ];
            // True same-origin: the `Host` header reflects the address the
            // browser actually connected to (e.g. the LAN IP behind a `0.0.0.0`
            // bind), so `http://<host>` is same-origin even though it differs
            // from the literal bind string. Still strictly equality-checked, so
            // a genuinely cross-site Origin is rejected.
            if let Some(host) = headers.get("host") {
                allowed.push(format!("http://{host}"));
                allowed.push(format!("https://{host}"));
            }
            allowed.iter().any(|a| a == o)
        }
    }
}

// ── parsing helpers ─────────────────────────────────────────────────────────

fn split_url(url: &str) -> (&str, &str) {
    match url.split_once('?') {
        Some((p, q)) => (p, q),
        None => (url, ""),
    }
}

fn parse_query(query: &str) -> HashMap<String, String> {
    let mut map = HashMap::new();
    for pair in query.split('&').filter(|s| !s.is_empty()) {
        let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
        map.insert(url_decode(k), url_decode(v));
    }
    map
}

/// Minimal percent-decoder (handles `%XX` and `+`). Sufficient for the small set
/// of query params the viewer sends; avoids pulling in a urlencoding crate.
fn url_decode(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'+' => out.push(b' '),
            b'%' if i + 2 < bytes.len() => {
                let hi = (bytes[i + 1] as char).to_digit(16);
                let lo = (bytes[i + 2] as char).to_digit(16);
                if let (Some(h), Some(l)) = (hi, lo) {
                    out.push((h * 16 + l) as u8);
                    i += 3;
                    continue;
                }
                out.push(b'%');
            }
            b => out.push(b),
        }
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}