use axum::http::Method;
use axum::http::header::{AUTHORIZATION, CONTENT_TYPE};
use axum::{
Json,
extract::{Path, State},
http::StatusCode,
};
use axum::{Router, routing::get};
use klm::storage::KpackRecipe;
use klm::{EvidenceRelation, Kognitara};
use serde::Serialize;
use std::fs::{self, File};
use std::io::{BufRead, BufReader};
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::SystemTime;
use tokio::sync::RwLock;
use tower_http::cors::{Any, CorsLayer};
#[derive(Serialize)]
pub struct TreeNode {
pub id: String,
pub brain: u8,
pub label: String,
pub description: String,
pub origin: String,
pub confidence: f32,
pub plasticity: f32,
pub affective_valence: f32,
pub tags: Vec<String>,
}
#[derive(Serialize)]
pub struct TreeLink {
pub source: String,
pub target: String,
pub relation: String,
pub weight: f32,
}
#[derive(Serialize)]
pub struct TreeResponse {
pub nodes: Vec<TreeNode>,
pub edges: Vec<TreeLink>,
}
#[derive(Serialize)]
pub struct DiffResponse {
pub id: u64,
pub can_validate: bool,
pub time: TimeInfo,
pub proposal: ProposalInfo,
pub changes: Changes,
pub impact: Impact,
pub reflections: Vec<ReflectionInfo>,
}
#[derive(Serialize)]
pub struct TimeInfo {
pub created_at: i64,
pub age_seconds: i64,
pub examinations: u64, pub last_examination: Option<i64>,
pub min_wait_hours: u64,
pub remaining_sec: i64,
}
#[derive(Serialize)]
pub struct ProposalInfo {
pub label: String,
pub origin: String,
pub confidence: f32,
pub description: String,
pub tags: Vec<String>,
}
#[derive(Serialize)]
pub struct Changes {
pub add_concept: bool,
pub add_edges: Vec<EdgeChange>,
}
#[derive(Serialize)]
pub struct EdgeChange {
pub from: String,
pub relation: String,
pub to: String,
}
#[derive(Serialize)]
pub struct Impact {
pub neighbor_concepts: usize,
pub potential_contradictions: usize,
}
#[derive(Serialize)]
pub struct ReflectionInfo {
pub stage: String,
pub question: String,
pub created_at: i64,
}
#[derive(Serialize)]
pub struct Proposal {
pub id: u64,
pub statement: String,
pub revision: usize,
pub created_at: i64,
pub evidence_count: usize,
pub has_contradiction: bool,
pub current_timestamp: i64,
}
pub async fn k_status(State(state): State<AppState>) -> Result<Json<StatusResponse>, StatusCode> {
let mind = state.mind().await?;
let now = klm::current_timestamp();
let concepts: usize = mind
.swarm
.brains
.values()
.map(|brain| brain.tree.concepts.len())
.sum();
let hypotheses = mind.hypotheses.hypotheses.len();
let ready_proposals = mind
.hypotheses
.hypotheses
.iter()
.filter(|h| is_hypothesis_ready(h, now))
.count();
Ok(Json(StatusResponse {
epoch: mind.swarm.global_epoch,
concepts,
hypotheses,
sanctuary: mind.sanctuary.sanctuary_name.clone(),
ready_proposals,
}))
}
pub async fn k_tree(State(state): State<AppState>) -> Result<Json<TreeResponse>, StatusCode> {
let mind = state.mind().await?;
let mut nodes = Vec::new();
let mut edges = Vec::new();
for (coord, brain) in &mind.swarm.brains {
for concept in brain.tree.concepts.values() {
nodes.push(TreeNode {
id: concept.id.0.clone(),
brain: coord.0,
label: concept.label.clone(),
description: concept.description.clone(),
origin: format!("{:?}", concept.origin),
confidence: concept.confidence,
plasticity: concept.plasticity,
affective_valence: concept.affective_valence,
tags: concept.tags.clone(),
});
}
for edge in &brain.tree.edges {
edges.push(TreeLink {
source: edge.source.0.clone(),
target: edge.target.0.clone(),
relation: format!("{:?}", edge.relation_type),
weight: edge.weight,
});
}
}
Ok(Json(TreeResponse { nodes, edges }))
}
pub async fn k_proposals(State(state): State<AppState>) -> Result<Json<Vec<Proposal>>, StatusCode> {
let mind = state.mind().await?;
let current_timestamp = klm::current_timestamp();
let proposals: Vec<Proposal> = mind
.hypotheses
.hypotheses
.iter()
.map(|h| {
let revision = h.revision();
let evidence_count = h.evidence.iter().filter(|e| e.revision == revision).count();
let has_contradiction = h.evidence.iter().any(|e| {
e.revision == revision && matches!(e.relation, EvidenceRelation::Contradicts)
});
Proposal {
id: h.id,
statement: h.statement.clone(),
revision,
created_at: h.created_at,
evidence_count,
has_contradiction,
current_timestamp,
}
})
.collect();
Ok(Json(proposals))
}
pub async fn k_diff(
State(state): State<AppState>,
Path(id): Path<u64>,
) -> Result<Json<DiffResponse>, StatusCode> {
let mind = state.mind().await?;
let now = klm::current_timestamp();
let hypothesis = mind
.hypotheses
.hypotheses
.iter()
.find(|h| h.id == id)
.ok_or(StatusCode::NOT_FOUND)?;
let age_seconds = now.saturating_sub(hypothesis.created_at);
let min_wait_sec = 12 * 3600;
let remaining_sec = (min_wait_sec as i64).saturating_sub(age_seconds);
let can_validate = is_hypothesis_ready(hypothesis, now);
let label = hypothesis
.statement
.split_whitespace()
.take(4)
.collect::<Vec<_>>()
.join(" ");
let reflections: Vec<ReflectionInfo> = mind
.swarm
.brains
.values()
.flat_map(|brain| &brain.learner.socratic_engine.reflections)
.filter(|r| {
let prefix: String = hypothesis.statement.chars().take(40).collect();
r.examined_hypothesis.contains(&prefix)
|| hypothesis
.related_concepts
.iter()
.any(|cid| r.concepts.contains(cid))
})
.map(|r| ReflectionInfo {
stage: format!("{:?}", r.stage),
question: r.maieutic_question.clone(),
created_at: r.created_at,
})
.collect();
let response = DiffResponse {
id,
can_validate,
time: TimeInfo {
created_at: hypothesis.created_at,
age_seconds,
examinations: 0,
last_examination: None,
min_wait_hours: 12,
remaining_sec,
},
proposal: ProposalInfo {
label,
origin: "HarvestedSeed".into(),
confidence: 0.65,
description: hypothesis.statement.clone(),
tags: vec![],
},
changes: Changes {
add_concept: true,
add_edges: vec![],
},
impact: Impact {
neighbor_concepts: hypothesis.related_concepts.len(),
potential_contradictions: if hypothesis
.evidence
.iter()
.any(|e| matches!(e.relation, EvidenceRelation::Contradicts))
{
1
} else {
0
},
},
reflections,
};
Ok(Json(response))
}
pub fn load_kognitara(path: &std::path::Path) -> Result<Kognitara, String> {
let file = File::open(path).map_err(|e| format!("Cannot open registry: {e}"))?;
let reader = BufReader::new(file);
let mut last_valid_recipe: Option<KpackRecipe> = None;
let mut lines_count = 0usize;
for line in reader.lines().map_while(Result::ok) {
if let Ok(recipe) = serde_json::from_str::<KpackRecipe>(&line) {
last_valid_recipe = Some(recipe);
lines_count += 1;
}
}
let recipe = last_valid_recipe.ok_or("No valid Kpack recipe found in the registry")?;
let json_bytes = recipe
.decode()
.map_err(|e| format!("Kpack decompression failed: {e}"))?;
let mind: Kognitara = serde_json::from_slice(&json_bytes)
.map_err(|e| format!("Failed to reconstruct Kognitara: {e}"))?;
println!(
"Loaded from iteration {} — Sanctuary: {} — Epoch: {}",
lines_count, mind.sanctuary.sanctuary_name, mind.swarm.global_epoch
);
Ok(mind)
}
pub struct SnapshotCache {
mind: Arc<Kognitara>,
modified: Option<SystemTime>,
}
#[derive(Clone)]
pub struct AppState {
pub data_path: Arc<PathBuf>,
pub cache: Arc<RwLock<SnapshotCache>>,
}
impl AppState {
async fn mind(&self) -> Result<Arc<Kognitara>, StatusCode> {
let current_mtime = fs::metadata(&*self.data_path)
.and_then(|m| m.modified())
.ok();
{
let guard = self.cache.read().await;
if guard.modified == current_mtime {
return Ok(guard.mind.clone());
}
}
let mut guard = self.cache.write().await;
if guard.modified != current_mtime
&& let Ok(new_mind) = load_kognitara(&self.data_path)
{
guard.mind = Arc::new(new_mind);
guard.modified = current_mtime;
}
Ok(guard.mind.clone())
}
}
fn is_hypothesis_ready(h: &klm::Hypothesis, now: i64) -> bool {
let revision = h.revision();
let age_seconds = now.saturating_sub(h.created_at);
let has_contradiction = h
.evidence
.iter()
.any(|e| e.revision == revision && matches!(e.relation, EvidenceRelation::Contradicts));
age_seconds >= 12 * 3600 && !has_contradiction
}
#[derive(Serialize)]
pub struct StatusResponse {
pub epoch: u64,
pub concepts: usize,
pub hypotheses: usize,
pub sanctuary: String,
pub ready_proposals: usize, }
#[derive(Serialize)]
pub struct BrainInfo {
pub id: u8,
pub phase: String,
pub concepts_count: usize,
pub edges_count: usize,
pub cognitive_tension: f32,
}
pub async fn k_brains(State(state): State<AppState>) -> Result<Json<Vec<BrainInfo>>, StatusCode> {
let mind = state.mind().await?;
let brains = mind
.swarm
.brains
.iter()
.map(|(coord, brain)| BrainInfo {
id: coord.0,
phase: format!("{:?}", brain.phase),
concepts_count: brain.tree.concepts.len(),
edges_count: brain.tree.edges.len(),
cognitive_tension: brain.state.cognitive_tension,
})
.collect();
Ok(Json(brains))
}
#[derive(Serialize)]
pub struct ReflectionEntry {
pub brain: u8,
pub stage: String,
pub examined_hypothesis: String,
pub maieutic_question: String,
pub interior_monologue: String,
pub created_at: i64,
}
pub async fn k_reflections(
State(state): State<AppState>,
) -> Result<Json<Vec<ReflectionEntry>>, StatusCode> {
let mind = state.mind().await?;
let mut entries: Vec<ReflectionEntry> = mind
.swarm
.brains
.iter()
.flat_map(|(coord, brain)| {
brain
.learner
.socratic_engine
.reflections
.iter()
.map(move |r| ReflectionEntry {
brain: coord.0,
stage: format!("{:?}", r.stage),
examined_hypothesis: r.examined_hypothesis.clone(),
maieutic_question: r.maieutic_question.clone(),
interior_monologue: r.interior_monologue.clone(),
created_at: r.created_at,
})
})
.collect();
entries.sort_by_key(|a| std::cmp::Reverse(a.created_at));
Ok(Json(entries))
}
#[derive(Serialize)]
pub struct FamilyMemberInfo {
pub id: String,
pub name: String,
pub role: String,
pub trust_level: f32,
pub affective_affinity: f32,
pub interaction_count: u64,
pub last_interacted_at: i64,
pub anecdotes: Vec<String>,
}
#[derive(Serialize)]
pub struct FamilyResponse {
pub sanctuary_name: String,
pub members: Vec<FamilyMemberInfo>,
}
pub async fn k_family(State(state): State<AppState>) -> Result<Json<FamilyResponse>, StatusCode> {
let mind = state.mind().await?;
let members = mind
.sanctuary
.members
.values()
.map(|m| {
let anecdotes = mind
.sanctuary
.bonds
.get(&m.id)
.map(|b| b.shared_anecdotes.clone())
.unwrap_or_default();
FamilyMemberInfo {
id: m.id.0.clone(),
name: m.name.clone(),
role: format!("{:?}", m.role),
trust_level: m.trust_level,
affective_affinity: m.affective_affinity,
interaction_count: m.interaction_count,
last_interacted_at: m.last_interacted_at,
anecdotes,
}
})
.collect();
Ok(Json(FamilyResponse {
sanctuary_name: mind.sanctuary.sanctuary_name.clone(),
members,
}))
}
#[tokio::main]
async fn main() {
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods([Method::GET, Method::POST])
.allow_headers([CONTENT_TYPE, AUTHORIZATION]);
let data_path = std::env::var("KOGNITARA_DATA")
.map(PathBuf::from)
.unwrap_or_else(|_| PathBuf::from("/mnt/kognitara/data"));
let modified = fs::metadata(&data_path).and_then(|m| m.modified()).ok();
let mind = load_kognitara(&data_path).expect("Failed to load Kognitara");
let state = AppState {
data_path: Arc::new(data_path),
cache: Arc::new(RwLock::new(SnapshotCache {
mind: Arc::new(mind),
modified,
})),
};
let app = Router::new()
.route("/status", get(k_status))
.route("/brains", get(k_brains))
.route("/proposals", get(k_proposals))
.route("/diff/{id}", get(k_diff))
.route("/tree", get(k_tree))
.route("/reflections", get(k_reflections))
.route("/family", get(k_family))
.layer(cors)
.with_state(state);
let addr = SocketAddr::from(([0, 0, 0, 0], 7789));
println!("listening on http://{}", addr);
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
axum::serve(listener, app).await.unwrap();
}