kj 0.1.1

Kōgnitara external REST API
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
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, // à brancher plus tard sur night_review
    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, // à calculer plus tard
}
#[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();
}