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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
//! MFBP Command Handler
//!
//! Executes requests against the MindFry database.
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, RwLock};
use std::time::Instant;
use crate::arena::Lineage;
use crate::graph::Bond;
use crate::MindFry;
use super::message::*;
use super::Request;
/// Command handler for MFBP requests
pub struct CommandHandler {
/// Reference to the MindFry database
db: Arc<RwLock<MindFry>>,
/// Server start time
start_time: Instant,
/// Is decay frozen?
is_frozen: bool,
}
impl CommandHandler {
/// Create a new command handler
pub fn new(db: Arc<RwLock<MindFry>>) -> Self {
Self {
db,
start_time: Instant::now(),
is_frozen: false,
}
}
/// Handle a request and return a response
pub fn handle(&mut self, request: Request) -> Response {
match request {
// ═══════════════════════════════════════════════════════════════
// LINEAGE OPERATIONS
// ═══════════════════════════════════════════════════════════════
Request::LineageCreate {
id,
energy,
threshold,
decay_rate,
} => {
let mut db = self.db.write().unwrap();
let key = self.hash_key(&id);
if db.psyche.lookup(key).is_some() {
return Response::Error {
code: ErrorCode::LineageExists,
message: format!("Lineage '{}' already exists", id),
};
}
let lineage = Lineage::with_config(energy, threshold, decay_rate);
db.psyche.alloc_with_key(key, lineage);
Response::Ok(ResponseData::Ack)
}
Request::LineageGet { id, flags } => {
use crate::protocol::QueryFlags;
let query_flags = QueryFlags::from_bits_truncate(flags);
let _bypass = query_flags.contains(QueryFlags::BYPASS_FILTERS);
let _include_repressed = query_flags.contains(QueryFlags::INCLUDE_REPRESSED);
let no_side_effects = query_flags.contains(QueryFlags::NO_SIDE_EFFECTS);
// Use read or write lock based on side effects
if no_side_effects {
let db = self.db.read().unwrap();
let key = self.hash_key(&id);
match db.psyche.lookup(key) {
Some(lineage_id) => match db.psyche.get(lineage_id) {
Some(lineage) => {
// TODO: Check antagonism suppression here
use crate::protocol::{LineageResult, LineageStatus};
Response::Ok(ResponseData::LineageResult(LineageResult {
status: LineageStatus::Found,
info: Some(LineageInfo {
id,
energy: lineage.current_energy(),
threshold: lineage.threshold,
decay_rate: lineage.decay_rate,
rigidity: lineage.rigidity,
is_conscious: lineage.is_conscious(),
last_access_ms: lineage.last_access / 1_000_000,
}),
}))
}
None => {
use crate::protocol::{LineageResult, LineageStatus};
Response::Ok(ResponseData::LineageResult(LineageResult {
status: LineageStatus::NotFound,
info: None,
}))
}
},
None => {
use crate::protocol::{LineageResult, LineageStatus};
Response::Ok(ResponseData::LineageResult(LineageResult {
status: LineageStatus::NotFound,
info: None,
}))
}
}
} else {
// Observer effect: stimulate on read
let mut db = self.db.write().unwrap();
let key = self.hash_key(&id);
match db.psyche.lookup(key) {
Some(lineage_id) => match db.psyche.get_mut(lineage_id) {
Some(lineage) => {
// Observer effect: reading strengthens memory
lineage.stimulate(0.01);
use crate::protocol::{LineageResult, LineageStatus};
Response::Ok(ResponseData::LineageResult(LineageResult {
status: LineageStatus::Found,
info: Some(LineageInfo {
id,
energy: lineage.current_energy(),
threshold: lineage.threshold,
decay_rate: lineage.decay_rate,
rigidity: lineage.rigidity,
is_conscious: lineage.is_conscious(),
last_access_ms: lineage.last_access / 1_000_000,
}),
}))
}
None => {
use crate::protocol::{LineageResult, LineageStatus};
Response::Ok(ResponseData::LineageResult(LineageResult {
status: LineageStatus::NotFound,
info: None,
}))
}
},
None => {
use crate::protocol::{LineageResult, LineageStatus};
Response::Ok(ResponseData::LineageResult(LineageResult {
status: LineageStatus::NotFound,
info: None,
}))
}
}
}
}
Request::LineageStimulate { id, delta, flags } => {
use crate::dynamics::SynapseEngine;
use crate::protocol::StimulateFlags;
let stim_flags = StimulateFlags::from_bits_truncate(flags);
let no_propagate = stim_flags.contains(StimulateFlags::NO_PROPAGATE);
let mut db = self.db.write().unwrap();
let key = self.hash_key(&id);
match db.psyche.lookup(key) {
Some(lineage_id) => {
// Phase 1: Stimulate the target
let found = match db.psyche.get_mut(lineage_id) {
Some(lineage) => {
lineage.stimulate(delta);
true
}
None => false,
};
if !found {
return Response::Error {
code: ErrorCode::LineageNotFound,
message: format!("Lineage '{}' not found", id),
};
}
// Phase 2: Propagate (after first borrow ends)
if !no_propagate {
tracing::debug!(
"[Propagate] Starting from '{}' with delta {}",
id,
delta
);
// Use a temporary synapse engine
let synapse = SynapseEngine::new();
// SAFETY: bonds is read-only during propagate, psyche is mutated.
// We use raw pointers to bypass Rust's borrow checker limitation
// with RwLockWriteGuard which doesn't allow partial borrows.
let bonds_ptr = &db.bonds as *const _;
let affected = synapse.propagate(
&mut db.psyche,
unsafe { &*bonds_ptr },
lineage_id,
delta,
);
tracing::debug!("[Propagate] Affected {} nodes", affected);
}
Response::Ok(ResponseData::Ack)
}
None => Response::Error {
code: ErrorCode::LineageNotFound,
message: format!("Lineage '{}' not found", id),
},
}
}
Request::LineageForget { id } => {
let mut db = self.db.write().unwrap();
let key = self.hash_key(&id);
match db.psyche.lookup(key) {
Some(lineage_id) => {
if db.psyche.free(lineage_id) {
Response::Ok(ResponseData::Ack)
} else {
Response::Error {
code: ErrorCode::LineageNotFound,
message: format!("Lineage '{}' already forgotten", id),
}
}
}
None => Response::Error {
code: ErrorCode::LineageNotFound,
message: format!("Lineage '{}' not found", id),
},
}
}
Request::LineageTouch { id } => {
let mut db = self.db.write().unwrap();
let key = self.hash_key(&id);
match db.psyche.lookup(key) {
Some(lineage_id) => match db.psyche.get_mut(lineage_id) {
Some(lineage) => {
lineage.touch();
Response::Ok(ResponseData::Ack)
}
None => Response::Error {
code: ErrorCode::LineageNotFound,
message: format!("Lineage '{}' not found", id),
},
},
None => Response::Error {
code: ErrorCode::LineageNotFound,
message: format!("Lineage '{}' not found", id),
},
}
}
// ═══════════════════════════════════════════════════════════════
// BOND OPERATIONS
// ═══════════════════════════════════════════════════════════════
Request::BondConnect {
source,
target,
strength,
polarity,
} => {
use crate::setun::Trit;
let mut db = self.db.write().unwrap();
let src_key = self.hash_key(&source);
let tgt_key = self.hash_key(&target);
let src_id = match db.psyche.lookup(src_key) {
Some(id) => id,
None => {
return Response::Error {
code: ErrorCode::LineageNotFound,
message: format!("Source lineage '{}' not found", source),
};
}
};
let tgt_id = match db.psyche.lookup(tgt_key) {
Some(id) => id,
None => {
return Response::Error {
code: ErrorCode::LineageNotFound,
message: format!("Target lineage '{}' not found", target),
};
}
};
let mut bond = Bond::new(src_id, tgt_id, strength);
// Apply polarity
bond.polarity = match polarity {
1 => Trit::True, // Synergy
0 => Trit::Unknown, // Neutral
-1 => Trit::False, // Antagonism
_ => Trit::True, // Default to synergy
};
match db.bonds.connect(bond) {
Some(_) => Response::Ok(ResponseData::Ack),
None => Response::Error {
code: ErrorCode::Internal,
message: "Failed to create bond".into(),
},
}
}
Request::BondReinforce {
source,
target,
delta,
} => {
let mut db = self.db.write().unwrap();
let src_key = self.hash_key(&source);
let tgt_key = self.hash_key(&target);
let src_id = match db.psyche.lookup(src_key) {
Some(id) => id,
None => {
return Response::Error {
code: ErrorCode::LineageNotFound,
message: format!("Source lineage '{}' not found", source),
};
}
};
let tgt_id = match db.psyche.lookup(tgt_key) {
Some(id) => id,
None => {
return Response::Error {
code: ErrorCode::LineageNotFound,
message: format!("Target lineage '{}' not found", target),
};
}
};
match db.bonds.find_bond(src_id, tgt_id) {
Some(bond_id) => {
if let Some(bond) = db.bonds.get_mut(bond_id) {
bond.reinforce(delta);
Response::Ok(ResponseData::Ack)
} else {
Response::Error {
code: ErrorCode::BondNotFound,
message: "Bond not found".into(),
}
}
}
None => Response::Error {
code: ErrorCode::BondNotFound,
message: format!("No bond between '{}' and '{}'", source, target),
},
}
}
Request::BondSever { source, target } => {
let mut db = self.db.write().unwrap();
let src_key = self.hash_key(&source);
let tgt_key = self.hash_key(&target);
let src_id = match db.psyche.lookup(src_key) {
Some(id) => id,
None => {
return Response::Error {
code: ErrorCode::LineageNotFound,
message: format!("Source lineage '{}' not found", source),
};
}
};
let tgt_id = match db.psyche.lookup(tgt_key) {
Some(id) => id,
None => {
return Response::Error {
code: ErrorCode::LineageNotFound,
message: format!("Target lineage '{}' not found", target),
};
}
};
match db.bonds.find_bond(src_id, tgt_id) {
Some(bond_id) => {
db.bonds.disconnect(bond_id);
Response::Ok(ResponseData::Ack)
}
None => Response::Error {
code: ErrorCode::BondNotFound,
message: format!("No bond between '{}' and '{}'", source, target),
},
}
}
Request::BondNeighbors { id } => {
let db = self.db.read().unwrap();
let key = self.hash_key(&id);
match db.psyche.lookup(key) {
Some(lineage_id) => {
let neighbors: Vec<NeighborInfo> = db
.bonds
.neighbors_with_strength(lineage_id)
.map(|(neighbor_id, strength)| {
// TODO: Reverse lookup ID to string
// For now, use numeric ID as string
NeighborInfo {
id: format!("lineage_{}", neighbor_id.0),
bond_strength: strength,
is_learned: false, // TODO: Track this
}
})
.collect();
Response::Ok(ResponseData::Neighbors(neighbors))
}
None => Response::Error {
code: ErrorCode::LineageNotFound,
message: format!("Lineage '{}' not found", id),
},
}
}
// ═══════════════════════════════════════════════════════════════
// QUERY OPERATIONS
// ═══════════════════════════════════════════════════════════════
Request::QueryConscious { min_energy } => {
use crate::setun::Trit;
let db = self.db.read().unwrap();
// Use Cortex for ternary consciousness evaluation
// Lucid (+1) or Dreaming (0) count as "aware"
let lineages: Vec<LineageInfo> = db
.psyche
.iter()
.filter(|(_, l)| {
// First check energy threshold
if l.current_energy() < min_energy {
return false;
}
// Use Cortex to evaluate consciousness state
let state = db
.cortex
.consciousness_state(l.current_energy() as f64, l.threshold as f64);
// Accept Lucid (+1) and Dreaming (0), reject Dormant (-1)
state != Trit::False
})
.map(|(id, l)| {
// Calculate ternary state for response
let state = db
.cortex
.consciousness_state(l.current_energy() as f64, l.threshold as f64);
LineageInfo {
id: format!("lineage_{}", id.0),
energy: l.current_energy(),
threshold: l.threshold,
decay_rate: l.decay_rate,
rigidity: l.rigidity,
// True if Lucid (+1), false if Dreaming (0)
is_conscious: state == Trit::True,
last_access_ms: l.last_access / 1_000_000,
}
})
.collect();
Response::Ok(ResponseData::Lineages(lineages))
}
Request::QueryTopK { k } => {
let db = self.db.read().unwrap();
let mut lineages: Vec<_> = db
.psyche
.iter()
.map(|(id, l)| (id, l.current_energy()))
.collect();
lineages.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
let top_k: Vec<LineageInfo> = lineages
.into_iter()
.take(k as usize)
.filter_map(|(id, _)| {
db.psyche.get(id).map(|l| LineageInfo {
id: format!("lineage_{}", id.0),
energy: l.current_energy(),
threshold: l.threshold,
decay_rate: l.decay_rate,
rigidity: l.rigidity,
is_conscious: l.is_conscious(),
last_access_ms: l.last_access / 1_000_000,
})
})
.collect();
Response::Ok(ResponseData::Lineages(top_k))
}
Request::QueryTrauma { min_rigidity } => {
let db = self.db.read().unwrap();
let traumatized: Vec<LineageInfo> = db
.psyche
.iter()
.filter(|(_, l)| l.rigidity >= min_rigidity)
.map(|(id, l)| LineageInfo {
id: format!("lineage_{}", id.0),
energy: l.current_energy(),
threshold: l.threshold,
decay_rate: l.decay_rate,
rigidity: l.rigidity,
is_conscious: l.is_conscious(),
last_access_ms: l.last_access / 1_000_000,
})
.collect();
Response::Ok(ResponseData::Lineages(traumatized))
}
Request::QueryPattern { pattern: _pattern } => {
// TODO: Implement pattern matching
Response::Error {
code: ErrorCode::Internal,
message: "Pattern query not yet implemented".into(),
}
}
// ═══════════════════════════════════════════════════════════════
// SYSTEM OPERATIONS
// ═══════════════════════════════════════════════════════════════
Request::Ping => Response::Ok(ResponseData::Pong),
Request::Stats => {
let db = self.db.read().unwrap();
let stats = db
.psyche
.iter()
.fold((0usize, 0f32), |(conscious, energy), (_, l)| {
(
conscious + if l.is_conscious() { 1 } else { 0 },
energy + l.current_energy(),
)
});
Response::Ok(ResponseData::Stats(StatsInfo {
lineage_count: db.psyche.len(),
bond_count: db.bonds.len(),
conscious_count: stats.0,
total_energy: stats.1,
is_frozen: self.is_frozen,
uptime_secs: self.start_time.elapsed().as_secs(),
}))
}
Request::Snapshot { name } => {
let db = self.db.read().unwrap();
// Check if store is attached
if let Some(ref store) = db.store {
use crate::persistence::snapshot::PhysicsSnapshot;
let physics = PhysicsSnapshot::default();
match store.take_snapshot(
Some(&name),
&db.psyche,
&db.strata,
&db.bonds,
Some(&db.cortex),
physics,
) {
Ok(meta) => {
tracing::info!(
"📸 Snapshot '{}' saved ({} lineages, {} bonds)",
name,
meta.lineage_count,
meta.bond_count
);
Response::Ok(ResponseData::SnapshotCreated { name })
}
Err(e) => {
tracing::error!("Failed to save snapshot: {}", e);
Response::Error {
code: ErrorCode::Internal,
message: format!("Snapshot failed: {}", e),
}
}
}
} else {
// No store attached - just ack
Response::Ok(ResponseData::SnapshotCreated { name })
}
}
Request::Restore { name } => {
let mut db = self.db.write().unwrap();
if let Some(ref store) = db.store {
// Find snapshot by name
match store.get_snapshot_by_name(&name) {
Ok(Some(snapshot)) => {
// Restore arenas
match store.restore_snapshot(
&snapshot,
db.psyche.capacity(),
db.bonds.capacity(),
64,
) {
Ok((psyche, strata, bonds, _physics)) => {
db.psyche = psyche;
db.strata = strata;
db.bonds = bonds;
// Restore Cortex if available
if let Some(ref cortex_data) = snapshot.cortex_data {
if let Ok(cortex) = bincode::deserialize(cortex_data) {
db.cortex = cortex;
}
}
tracing::info!(
"🔄 Restored from snapshot '{}' ({} lineages)",
name,
db.psyche.len()
);
Response::Ok(ResponseData::Ack)
}
Err(e) => Response::Error {
code: ErrorCode::Internal,
message: format!("Restore failed: {}", e),
},
}
}
Ok(None) => Response::Error {
code: ErrorCode::SnapshotNotFound,
message: format!("Snapshot '{}' not found", name),
},
Err(e) => Response::Error {
code: ErrorCode::Internal,
message: format!("Restore error: {}", e),
},
}
} else {
Response::Error {
code: ErrorCode::Internal,
message: "No storage attached".into(),
}
}
}
Request::Freeze { frozen } => {
self.is_frozen = frozen;
Response::Ok(ResponseData::Ack)
}
Request::PhysicsTune {
param: _param,
value: _value,
} => {
// TODO: Implement physics tuning
Response::Ok(ResponseData::Ack)
}
Request::MoodSet { mood } => {
let mut db = self.db.write().unwrap();
db.cortex.set_mood(mood as f64);
Response::Ok(ResponseData::Ack)
}
// ═══════════════════════════════════════════════════════════════
// STREAM OPERATIONS
// ═══════════════════════════════════════════════════════════════
Request::Subscribe {
events_mask: _events_mask,
} => {
// TODO: Implement event subscription
Response::Ok(ResponseData::Ack)
}
Request::Unsubscribe => {
// TODO: Implement unsubscribe
Response::Ok(ResponseData::Ack)
}
}
}
/// Hash a string key using DefaultHasher
fn hash_key(&self, key: &str) -> u64 {
let mut hasher = DefaultHasher::new();
key.hash(&mut hasher);
hasher.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn setup_handler() -> CommandHandler {
let db = Arc::new(RwLock::new(MindFry::new()));
CommandHandler::new(db)
}
#[test]
fn test_ping() {
let mut handler = setup_handler();
let response = handler.handle(Request::Ping);
match response {
Response::Ok(ResponseData::Pong) => {}
_ => panic!("Expected Pong"),
}
}
#[test]
fn test_lineage_create_and_get() {
let mut handler = setup_handler();
// Create
let response = handler.handle(Request::LineageCreate {
id: "test".into(),
energy: 0.8,
threshold: 0.5,
decay_rate: 0.001,
});
assert!(matches!(response, Response::Ok(ResponseData::Ack)));
// Get
let response = handler.handle(Request::LineageGet {
id: "test".into(),
flags: 0,
});
match response {
Response::Ok(ResponseData::LineageResult(result)) => {
assert_eq!(result.status, LineageStatus::Found);
let info = result.info.unwrap();
assert_eq!(info.id, "test");
assert!(info.energy > 0.7);
}
_ => panic!("Expected LineageResult"),
}
}
#[test]
fn test_lineage_not_found() {
let mut handler = setup_handler();
let response = handler.handle(Request::LineageGet {
id: "nonexistent".into(),
flags: 0,
});
match response {
Response::Ok(ResponseData::LineageResult(result)) => {
assert_eq!(result.status, LineageStatus::NotFound);
assert!(result.info.is_none());
}
_ => panic!("Expected LineageResult with NotFound status"),
}
}
#[test]
fn test_stats() {
let mut handler = setup_handler();
// Create some lineages
handler.handle(Request::LineageCreate {
id: "a".into(),
energy: 1.0,
threshold: 0.5,
decay_rate: 0.001,
});
handler.handle(Request::LineageCreate {
id: "b".into(),
energy: 0.3,
threshold: 0.5,
decay_rate: 0.001,
});
let response = handler.handle(Request::Stats);
match response {
Response::Ok(ResponseData::Stats(stats)) => {
assert_eq!(stats.lineage_count, 2);
assert_eq!(stats.conscious_count, 1); // Only "a" is conscious
}
_ => panic!("Expected Stats"),
}
}
}