use axum::http::Method;
use axum::http::header;
use axum::http::header::{AUTHORIZATION, CONTENT_TYPE};
use axum::response::IntoResponse;
use axum::routing::post;
use axum::{
Json,
extract::{Path, State},
http::StatusCode,
};
use axum::{Router, routing::get};
use klm::storage::KpackRecipe;
use klm::{EvidenceRelation, Kognitara};
use kog::{KogBook, KogBridge, KogLesson, MarginConfig, PrintProfile};
use serde::Serialize;
use std::fs::{self, File};
use std::io::{BufRead, BufReader};
use std::net::SocketAddr;
use std::path::Path as StdPath;
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 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,
}
#[derive(Serialize)]
pub struct NightReviewResponse {
pub total_reviews: usize,
pub items: Vec<serde_json::Value>,
}
#[derive(Serialize)]
pub struct EquivalenceItem {
pub brain: u8,
pub id: u64,
pub left_id: String,
pub left_label: String,
pub right_id: String,
pub right_label: String,
pub source: String,
pub reason: String,
pub active: bool,
pub created_at: i64,
}
#[derive(Deserialize)]
struct ResearchTrace {
#[serde(default)]
pub title: String,
#[serde(default)]
pub source_url: String,
#[serde(default)]
pub snippet: String,
}
#[derive(Deserialize)]
struct ResearchObservation {
#[serde(default)]
pub topic: String,
pub trace: ResearchTrace,
}
#[derive(Serialize)]
pub struct ResearchItem {
pub id: String,
pub topic: String,
pub title: String,
pub domain: String,
pub source_url: String,
pub snippet: String,
pub imported: bool,
pub timestamp: i64,
}
#[derive(Deserialize, Default)]
struct ResearchQueueInfo {
#[serde(default)]
pub pending: Vec<serde_json::Value>,
#[serde(default)]
pub visited: Vec<String>,
#[serde(default)]
pub next_topic: usize,
}
#[derive(Serialize)]
pub struct ResearchResponse {
pub pending_count: usize,
pub visited_count: usize,
pub next_topic_index: usize,
pub items: Vec<ResearchItem>,
}
#[derive(Serialize)]
pub struct TreeConceptDto {
pub id: String,
pub label: String,
pub description: String,
pub confidence: f32,
pub brain: u8,
}
#[derive(Serialize)]
pub struct TreeEdgeDto {
pub from: String,
pub to: String,
pub relation: String,
pub weight: f32,
}
#[derive(Serialize)]
pub struct TreeResponse {
pub concepts: Vec<TreeConceptDto>,
pub edges: Vec<TreeEdgeDto>,
}
pub async fn k_tree(State(state): State<AppState>) -> Result<Json<TreeResponse>, StatusCode> {
let mind = state.mind().await?;
let mut concepts = Vec::new();
let mut edges = Vec::new();
for (coord, brain) in &mind.swarm.brains {
for (cid, concept) in &brain.tree.concepts {
concepts.push(TreeConceptDto {
id: cid.0.clone(),
label: concept.label.clone(),
description: concept.description.clone(),
confidence: concept.confidence,
brain: coord.0,
});
}
for edge in &brain.tree.edges {
edges.push(TreeEdgeDto {
from: edge.source.0.clone(),
to: edge.target.0.clone(),
relation: format!("{:?}", edge.relation_type),
weight: edge.weight,
});
}
}
Ok(Json(TreeResponse { concepts, edges }))
}
#[derive(Serialize)]
pub struct BridgeDto {
pub target: String,
pub note: String,
}
#[derive(Serialize)]
pub struct LessonDto {
pub file_name: String,
pub slug: String,
pub title: String,
pub family: String,
pub level: String,
pub roots: Vec<String>,
pub essence: String,
pub example: String,
pub bridges: Vec<BridgeDto>,
pub question: String,
}
#[derive(Serialize)]
pub struct BookDto {
pub file_name: String,
pub slug: String,
pub title: String,
pub subtitle: String,
pub family: String,
pub commission: String,
pub chapters: Vec<String>,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct PrintProfileDto {
pub file_name: String,
pub name: String,
pub paper: String,
pub font_family: String,
pub font_size_pt: f32,
pub line_leading_em: f32,
pub lang: String,
pub justify: bool,
pub accent_hex: String,
pub inside_mm: f32,
pub outside_mm: f32,
pub top_mm: f32,
pub bottom_mm: f32,
}
impl PrintProfileDto {
fn from_model(file_name: String, p: &PrintProfile) -> Self {
Self {
file_name,
name: p.name.clone(),
paper: p.paper.clone(),
font_family: p.font_family.clone(),
font_size_pt: p.font_size_pt,
line_leading_em: p.line_leading_em,
lang: p.lang.clone(),
justify: p.justify,
accent_hex: p.accent_hex.clone(),
inside_mm: p.margins.inside_mm,
outside_mm: p.margins.outside_mm,
top_mm: p.margins.top_mm,
bottom_mm: p.margins.bottom_mm,
}
}
fn to_model(&self) -> PrintProfile {
PrintProfile {
name: self.name.clone(),
paper: self.paper.clone(),
font_family: self.font_family.clone(),
font_size_pt: self.font_size_pt,
line_leading_em: self.line_leading_em,
lang: self.lang.clone(),
justify: self.justify,
accent_hex: self.accent_hex.clone(),
margins: MarginConfig {
inside_mm: self.inside_mm,
outside_mm: self.outside_mm,
top_mm: self.top_mm,
bottom_mm: self.bottom_mm,
},
}
}
}
#[derive(Serialize)]
pub struct StudioPayload {
pub lessons: Vec<LessonDto>,
pub books: Vec<BookDto>,
pub styles: Vec<PrintProfileDto>,
}
fn lessons_dir_from_state(state: &AppState) -> std::path::PathBuf {
state
.data_path
.parent()
.unwrap_or_else(|| StdPath::new("/mnt/kognitara"))
.join("lessons")
}
pub async fn k_studio(State(state): State<AppState>) -> Json<StudioPayload> {
let dir = lessons_dir_from_state(&state);
let mut lessons = Vec::new();
let mut books = Vec::new();
let mut styles = Vec::new();
if let Ok(entries) = fs::read_dir(&dir) {
for entry in entries.flatten() {
let path = entry.path();
let Some(file_name) = path
.file_name()
.and_then(|s| s.to_str())
.map(str::to_string)
else {
continue;
};
let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("");
let Ok(raw) = fs::read_to_string(&path) else {
continue;
};
match ext {
"kog" => {
if let Ok(l) = KogLesson::from_kog(&raw) {
lessons.push(LessonDto {
file_name,
slug: l.slug,
title: l.title,
family: l.family,
level: l.level,
roots: l.roots,
essence: l.essence,
example: l.example,
bridges: l
.bridges
.into_iter()
.map(|b: KogBridge| BridgeDto {
target: b.target,
note: b.note,
})
.collect(),
question: l.question,
});
}
}
"kogbook" => {
if let Ok(b) = KogBook::from_kogbook(&raw) {
books.push(BookDto {
file_name,
slug: b.slug,
title: b.title,
subtitle: b.subtitle,
family: b.family,
commission: b.commission,
chapters: b.chapters,
});
}
}
"kogstyle" => {
let p = PrintProfile::from_kogstyle(&raw);
styles.push(PrintProfileDto::from_model(file_name, &p));
}
_ => {}
}
}
}
if styles.is_empty() {
styles.push(PrintProfileDto::from_model(
"default.kogstyle".to_string(),
&PrintProfile::default(),
));
}
lessons.sort_by(|a, b| a.title.cmp(&b.title));
books.sort_by(|a, b| a.title.cmp(&b.title));
Json(StudioPayload {
lessons,
books,
styles,
})
}
pub async fn k_save_style(
State(state): State<AppState>,
Json(dto): Json<PrintProfileDto>,
) -> Result<Json<PrintProfileDto>, StatusCode> {
let dir = lessons_dir_from_state(&state);
fs::create_dir_all(&dir).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let safe_slug: String = dto
.name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'-'
}
})
.collect::<String>()
.trim_matches('-')
.to_string();
let file_name = if safe_slug.is_empty() {
"custom.kogstyle".to_string()
} else {
format!("{safe_slug}.kogstyle")
};
let model = dto.to_model();
fs::write(dir.join(&file_name), model.to_kogstyle())
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(PrintProfileDto::from_model(file_name, &model)))
}
#[derive(Deserialize)]
pub struct CompilePdfRequest {
pub target_file: String, pub profile: PrintProfileDto,
}
pub async fn k_compile_pdf(
State(state): State<AppState>,
Json(req): Json<CompilePdfRequest>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
let dir = lessons_dir_from_state(&state);
let safe_name = StdPath::new(&req.target_file)
.file_name()
.and_then(|s| s.to_str())
.ok_or((StatusCode::BAD_REQUEST, "Invalid file name".into()))?;
let target_path = dir.join(safe_name);
let raw = fs::read_to_string(&target_path)
.map_err(|e| (StatusCode::NOT_FOUND, format!("File not found: {e}")))?;
let profile = req.profile.to_model();
let typ_source = if safe_name.ends_with(".kogbook") {
let book =
KogBook::from_kogbook(&raw).map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
let mut chapters = Vec::new();
for ch in &book.chapters {
if let Ok(ch_raw) = fs::read_to_string(dir.join(ch))
&& let Ok(lesson) = KogLesson::from_kog(&ch_raw)
{
chapters.push(lesson);
}
}
book.to_typst_book(&chapters, &profile)
} else {
let lesson =
KogLesson::from_kog(&raw).map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
lesson.to_typst_document(&profile)
};
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis())
.unwrap_or(0);
let tmp_typ = std::env::temp_dir().join(format!("kog_{stamp}.typ"));
let tmp_pdf = std::env::temp_dir().join(format!("kog_{stamp}.pdf"));
fs::write(&tmp_typ, &typ_source)
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
let status = std::process::Command::new("typst")
.arg("compile")
.arg(&tmp_typ)
.arg(&tmp_pdf)
.status()
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Typst error: {e}"),
)
})?;
let _ = fs::remove_file(&tmp_typ);
if !status.success() {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
"Typst compilation failed".into(),
));
}
let pdf_bytes =
fs::read(&tmp_pdf).map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
let _ = fs::remove_file(&tmp_pdf);
let out_name = safe_name
.trim_end_matches(".kogbook")
.trim_end_matches(".kog");
Ok((
[
(header::CONTENT_TYPE, "application/pdf".to_string()),
(
header::CONTENT_DISPOSITION,
format!("attachment; filename=\"{out_name}.pdf\""),
),
],
pdf_bytes,
))
}
pub async fn k_research(
State(state): State<AppState>,
) -> Result<Json<ResearchResponse>, StatusCode> {
let mind = state.mind().await?;
let dir = state
.data_path
.parent()
.unwrap_or_else(|| StdPath::new("/mnt/kognitara"))
.join("research");
let queue_info: ResearchQueueInfo = fs::read(dir.join("queue.state"))
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default();
let mut items = Vec::new();
if let Ok(entries) = fs::read_dir(&dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|s| s.to_str()) != Some("json") {
continue;
}
let Some(id) = path
.file_name()
.and_then(|s| s.to_str())
.map(str::to_string)
else {
continue;
};
let timestamp = entry
.metadata()
.ok()
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
if let Ok(raw) = fs::read(&path)
&& let Ok(obs) = serde_json::from_slice::<ResearchObservation>(&raw)
{
let domain = obs
.trace
.source_url
.strip_prefix("https://")
.and_then(|s| s.split('/').next())
.unwrap_or("fr.wikipedia.org")
.to_string();
items.push(ResearchItem {
imported: mind.imported_research.contains(&id),
id,
topic: obs.topic,
title: obs.trace.title,
domain,
source_url: obs.trace.source_url,
snippet: obs.trace.snippet,
timestamp,
});
}
}
}
items.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
Ok(Json(ResearchResponse {
pending_count: queue_info.pending.len(),
visited_count: queue_info.visited.len(),
next_topic_index: queue_info.next_topic,
items,
}))
}
pub async fn k_equivalences(
State(state): State<AppState>,
) -> Result<Json<Vec<EquivalenceItem>>, StatusCode> {
let mind = state.mind().await?;
let mut items = Vec::new();
for (coord, brain) in &mind.swarm.brains {
for eq in &brain.tree.possible_equivalences {
items.push(EquivalenceItem {
brain: coord.0,
id: eq.id,
left_id: eq.left.0.clone(),
left_label: eq.left_label.clone(),
right_id: eq.right.0.clone(),
right_label: eq.right_label.clone(),
source: eq.source.clone(),
reason: eq.reason.clone(),
active: eq.is_active(),
created_at: eq.created_at,
});
}
}
items.sort_by_key(|a| std::cmp::Reverse(a.created_at));
Ok(Json(items))
}
use serde::Deserialize;
use serde_json::json;
use std::collections::BTreeMap;
#[derive(Serialize, Deserialize, Clone)]
pub struct WikipediaReview {
pub source: String,
pub excerpt: String,
pub examined_at: i64,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct HypothesisReview {
pub id: u64,
pub revision: usize,
pub statement: String,
pub examinations: u64,
pub examined_at: i64,
pub reports: usize,
pub supports: usize,
pub contradicts: usize,
pub contradictions: Vec<String>,
pub questions: Vec<String>,
pub wikipedia: Option<WikipediaReview>,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct ConceptReview {
pub brain: u8,
pub label: String,
pub contradictions: Vec<String>,
pub question: String,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct NightSubject {
pub label: String,
pub kind: String,
pub contradictions: Vec<String>,
}
#[derive(Default, Serialize, Deserialize, Clone)]
pub struct NightSummary {
pub cycles: u64,
pub concept_examinations: u64,
pub hypothesis_examinations: u64,
pub last_run: i64,
pub subjects: BTreeMap<String, NightSubject>,
}
#[derive(Default, Deserialize)]
struct ReviewState {
#[serde(default)]
pub concept_examinations: u64,
#[serde(default)]
pub hypothesis_examinations: u64,
#[serde(default)]
pub last_run: Option<i64>,
#[serde(default)]
pub concepts: Vec<ConceptReview>,
#[serde(default)]
pub hypotheses: BTreeMap<String, HypothesisReview>,
#[serde(default)]
pub summaries: BTreeMap<String, NightSummary>,
}
#[derive(Serialize)]
#[serde(tag = "kind", content = "value")]
enum NightItem<'a> {
Hypothesis(&'a HypothesisReview),
Concept(&'a ConceptReview),
}
pub async fn k_night(State(state): State<AppState>) -> Result<Json<serde_json::Value>, StatusCode> {
let night = read_night_review_state(&state.data_path)?;
let mut items = Vec::new();
if let Some(ref review_state) = night {
let mut reviews: Vec<_> = review_state.hypotheses.values().collect();
reviews.sort_by(|a, b| b.examined_at.cmp(&a.examined_at));
for review in reviews {
items.push(NightItem::Hypothesis(review));
}
for concept in &review_state.concepts {
items.push(NightItem::Concept(concept));
}
}
Ok(Json(json!({
"concept_examinations": night.as_ref().map_or(0, |n| n.concept_examinations),
"hypothesis_examinations": night.as_ref().map_or(0, |n| n.hypothesis_examinations),
"last_run": night.as_ref().and_then(|n| n.last_run),
"items": items
})))
}
fn read_night_review_state(data_path: &StdPath) -> Result<Option<ReviewState>, StatusCode> {
let dir = data_path
.parent()
.unwrap_or_else(|| StdPath::new("/mnt/kognitara"));
let candidates = [
dir.join("research").join("night-review.state"),
dir.join("night-review.state"),
];
for path in candidates {
match fs::read(&path) {
Ok(data) => {
return serde_json::from_slice::<ReviewState>(&data)
.map(Some)
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE);
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(_) => return Err(StatusCode::SERVICE_UNAVAILABLE),
}
}
Ok(None)
}
pub async fn k_morning(
State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let night = read_night_review_state(&state.data_path)?;
let latest = night.as_ref().and_then(|s| s.summaries.last_key_value());
if let Some((date, summary)) = latest {
let subjects: Vec<_> = summary.subjects.values().collect();
let flagged_count = summary
.subjects
.values()
.filter(|s| !s.contradictions.is_empty())
.count();
Ok(Json(json!({
"summary": {
"date": date,
"cycles": summary.cycles,
"concept_examinations": summary.concept_examinations,
"hypothesis_examinations": summary.hypothesis_examinations,
"last_run": summary.last_run,
"subjects_count": summary.subjects.len(),
"flagged_count": flagged_count,
},
"subjects": subjects
})))
} else {
Ok(Json(json!({
"summary": null,
"subjects": []
})))
}
}
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();
let usb_mounted = StdPath::new("/mnt/cubefs-usb").exists()
&& state.data_path.parent().is_some_and(|p| p.exists());
let backup_ok = check_cubefs_backup_ok(StdPath::new("/mnt/cubefs-usb"));
let next_research_ts = get_systemd_next_elapse("klm-research.timer");
let next_backup_ts = get_systemd_next_elapse("klm-backup.timer");
let disk_full = check_disk_full(&state.data_path);
Ok(Json(StatusResponse {
epoch: mind.swarm.global_epoch,
concepts,
hypotheses,
sanctuary: mind.sanctuary.sanctuary_name.clone(),
ready_proposals,
breaths: mind.swarm.cosmic_clock.total_breaths,
tides: mind.swarm.cosmic_clock.total_tides,
season: mind.swarm.cosmic_clock.season.label().to_string(),
conjunctions: mind.swarm.cosmic_clock.conjunctions_experienced,
usb_mounted,
backup_ok,
disk_full,
next_research_ts,
next_backup_ts,
}))
}
fn check_cubefs_backup_ok(backup_dir: &StdPath) -> bool {
let Ok(entries) = fs::read_dir(backup_dir) else {
return false;
};
entries
.filter_map(Result::ok)
.filter_map(|e| e.metadata().ok()?.modified().ok())
.filter_map(|m| m.elapsed().ok())
.any(|age| age.as_secs() < 6 * 3600)
}
fn check_disk_full(path: &StdPath) -> bool {
use std::ffi::CString;
use std::os::unix::ffi::OsStrExt;
let target = if path.exists() {
path
} else {
path.parent().unwrap_or(StdPath::new("/"))
};
let Ok(c_path) = CString::new(target.as_os_str().as_bytes()) else {
return false;
};
unsafe {
let mut stat: libc::statvfs = std::mem::zeroed();
if libc::statvfs(c_path.as_ptr(), &mut stat) == 0 {
let free_bytes = stat.f_bavail as u64 * stat.f_frsize as u64;
return free_bytes < 100 * 1024 * 1024; }
}
false
}
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
}
fn get_systemd_next_elapse(unit: &str) -> Option<i64> {
let output = std::process::Command::new("systemctl")
.args(["--user", "list-timers", unit, "--no-pager", "--no-legend"])
.output()
.ok()?;
let line = String::from_utf8_lossy(&output.stdout).trim().to_string();
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() < 4 {
return None;
}
let date_str = format!(
"{} {} {}",
parts.get(0).expect(""),
parts.get(1).expect(""),
parts.get(2).expect("")
);
let ts_out = std::process::Command::new("date")
.args(["-d", &date_str, "+%s"])
.output()
.ok()?;
String::from_utf8_lossy(&ts_out.stdout)
.trim()
.parse::<i64>()
.ok()
}
#[derive(Serialize)]
pub struct StatusResponse {
pub epoch: u64,
pub concepts: usize,
pub hypotheses: usize,
pub sanctuary: String,
pub ready_proposals: usize, pub breaths: u64,
pub tides: u64,
pub season: String,
pub conjunctions: u64,
pub usb_mounted: bool,
pub backup_ok: bool,
pub disk_full: bool,
pub next_research_ts: Option<i64>,
pub next_backup_ts: Option<i64>,
}
#[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("/studio", get(k_studio))
.route("/studio/styles", post(k_save_style))
.route("/studio/pdf", post(k_compile_pdf))
.route("/research", get(k_research))
.route("/equivalences", get(k_equivalences))
.route("/night", get(k_night))
.route("/morning", get(k_morning))
.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();
}