unit 0.26.2

A self-replicating software nanobot — minimal Forth interpreter that is also a networked mesh agent
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
//! Challenge registry for emergent problem-solving.
//!
//! Generalizes `FitnessChallenge` beyond the hardcoded fib10. Challenges can
//! be built-in, discovered from failures, or received from mesh peers.
//! The GP engine evolves solutions; solutions become dictionary words.

use crate::evolve::FitnessChallenge;
use crate::mesh::NodeId;
use std::collections::HashMap;

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/// Unique identifier for a challenge within the registry.
pub type ChallengeId = u64;

/// Where a challenge came from: built-in or discovered at runtime.
#[derive(Clone, Debug, PartialEq)]
pub enum ChallengeOrigin {
    BuiltIn,
    Discovered {
        source_node: NodeId,
        discovered_at: u64,
    },
}

/// A problem to be solved by the GP engine, with metadata for tracking solutions.
#[derive(Clone, Debug)]
pub struct Challenge {
    pub id: ChallengeId,
    pub name: String,
    pub description: String,
    pub target_output: String,
    pub test_input: Option<String>,
    pub max_steps: usize,
    pub seed_programs: Vec<String>,
    pub origin: ChallengeOrigin,
    pub reward: i64,
    pub solved: bool,
    pub solution: Option<String>,
    pub solver: Option<NodeId>,
    pub attempts: u32,
    pub solutions: Vec<(String, NodeId)>, // all verified solutions (program, solver)
}

// ---------------------------------------------------------------------------
// ChallengeRegistry
// ---------------------------------------------------------------------------

/// Manages the set of known challenges and tracks which is currently active.
#[derive(Clone, Debug)]
pub struct ChallengeRegistry {
    pub challenges: HashMap<ChallengeId, Challenge>,
    id_counter: u64,
    pub active_challenge: Option<ChallengeId>,
}

impl ChallengeRegistry {
    /// Creates an empty registry, seeding the ID counter from the node ID to avoid collisions.
    pub fn new(node_id: &NodeId) -> Self {
        // Seed counter from node ID to avoid collisions (same pattern as GoalRegistry).
        let base = ((node_id[4] as u64) << 4 | (node_id[5] as u64 >> 4)) * 10 + 1;
        ChallengeRegistry {
            challenges: HashMap::new(),
            id_counter: base,
            active_challenge: None,
        }
    }

    fn next_id(&mut self) -> ChallengeId {
        let id = self.id_counter;
        self.id_counter += 1;
        id
    }

    /// Registers a built-in challenge and returns its assigned ID.
    pub fn register_builtin(
        &mut self,
        name: &str,
        target_output: &str,
        seeds: Vec<String>,
    ) -> ChallengeId {
        let id = self.next_id();
        self.challenges.insert(
            id,
            Challenge {
                id,
                name: name.to_string(),
                description: format!("built-in challenge: {}", name),
                target_output: target_output.to_string(),
                test_input: None,
                max_steps: 10000,
                seed_programs: seeds,
                origin: ChallengeOrigin::BuiltIn,
                reward: 100,
                solved: false,
                solution: None,
                solver: None,
                attempts: 0,
                solutions: vec![],
            },
        );
        id
    }

    /// Registers a challenge discovered from a failure or received from a peer.
    #[allow(clippy::too_many_arguments)]
    pub fn register_discovered(
        &mut self,
        name: &str,
        desc: &str,
        target_output: &str,
        test_input: Option<String>,
        seed_programs: Vec<String>,
        source_node: NodeId,
        reward: i64,
    ) -> ChallengeId {
        let id = self.next_id();
        self.challenges.insert(
            id,
            Challenge {
                id,
                name: name.to_string(),
                description: desc.to_string(),
                target_output: target_output.to_string(),
                test_input,
                max_steps: 10000,
                seed_programs,
                origin: ChallengeOrigin::Discovered {
                    source_node,
                    discovered_at: 0,
                },
                reward,
                solved: false,
                solution: None,
                solver: None,
                attempts: 0,
                solutions: vec![],
            },
        );
        id
    }

    /// Marks a challenge as solved. Returns true if this is the first solution.
    pub fn mark_solved(&mut self, id: ChallengeId, solution: &str, solver: NodeId) -> bool {
        if let Some(ch) = self.challenges.get_mut(&id) {
            let is_first = !ch.solved;
            if is_first {
                ch.solved = true;
                ch.solution = Some(solution.to_string());
                ch.solver = Some(solver);
            }
            // Track all distinct solutions (cap at 20).
            if ch.solutions.len() < 20 && !ch.solutions.iter().any(|(p, _)| p == solution) {
                ch.solutions.push((solution.to_string(), solver));
            }
            return is_first;
        }
        false
    }

    /// Returns the number of distinct solutions recorded for a challenge.
    pub fn solution_count(&self, id: ChallengeId) -> usize {
        self.challenges.get(&id).map_or(0, |c| c.solutions.len())
    }

    /// Formats all solutions for a challenge as a human-readable string.
    pub fn format_solutions(&self, id: ChallengeId) -> String {
        match self.challenges.get(&id) {
            Some(ch) if !ch.solutions.is_empty() => {
                let mut out = format!("--- {} solutions for {} ---\n", ch.solutions.len(), ch.name);
                for (i, (prog, solver)) in ch.solutions.iter().enumerate() {
                    let tokens = prog.split_whitespace().count();
                    out.push_str(&format!(
                        "  {}. \"{}\" ({} tokens) from {}\n",
                        i + 1,
                        prog,
                        tokens,
                        crate::mesh::id_to_hex(solver)
                    ));
                }
                out
            }
            _ => format!("no solutions for challenge #{}\n", id),
        }
    }

    /// Summarizes solution diversity across all solved challenges.
    pub fn colony_diversity(&self) -> String {
        let solved: Vec<&Challenge> = self.challenges.values().filter(|c| c.solved).collect();
        if solved.is_empty() {
            return "no solved challenges yet\n".to_string();
        }
        let total_solutions: usize = solved.iter().map(|c| c.solutions.len()).sum();
        let avg = total_solutions as f64 / solved.len() as f64;
        let most_diverse = solved.iter().max_by_key(|c| c.solutions.len());
        let mut out = format!(
            "--- colony diversity ---\nchallenges solved: {}\ntotal solutions: {}\navg solutions per challenge: {:.1}\n",
            solved.len(), total_solutions, avg
        );
        if let Some(md) = most_diverse {
            out.push_str(&format!(
                "most diverse: {} ({} solutions)\n",
                md.name,
                md.solutions.len()
            ));
        }
        out
    }

    /// Returns all unsolved challenges, sorted by reward descending.
    pub fn get_unsolved(&self) -> Vec<&Challenge> {
        let mut unsolved: Vec<&Challenge> =
            self.challenges.values().filter(|c| !c.solved).collect();
        unsolved.sort_by(|a, b| b.reward.cmp(&a.reward));
        unsolved
    }

    /// Looks up a challenge by ID.
    pub fn get_challenge(&self, id: ChallengeId) -> Option<&Challenge> {
        self.challenges.get(&id)
    }

    /// Convert a Challenge to the FitnessChallenge format consumed by the GP engine.
    pub fn to_fitness_challenge(&self, id: ChallengeId) -> Option<FitnessChallenge> {
        let ch = self.challenges.get(&id)?;
        Some(FitnessChallenge {
            name: ch.name.clone(),
            target_output: ch.target_output.clone(),
            max_steps: ch.max_steps,
            seed_programs: ch.seed_programs.clone(),
        })
    }

    /// Merge a challenge received from a peer. Accept if new or if solved
    /// status is more advanced (same pattern as GoalRegistry::merge_goal).
    pub fn merge_challenge(&mut self, challenge: Challenge) {
        if let Some(existing) = self.challenges.get(&challenge.id) {
            // Update if incoming is solved and ours isn't.
            if challenge.solved && !existing.solved {
                self.challenges.insert(challenge.id, challenge);
            }
        } else {
            if challenge.id >= self.id_counter {
                self.id_counter = challenge.id + 1;
            }
            self.challenges.insert(challenge.id, challenge);
        }
    }

    /// Formats all challenges as a human-readable summary.
    pub fn format_challenges(&self) -> String {
        if self.challenges.is_empty() {
            return "no challenges\n".to_string();
        }
        let mut out = format!("--- {} challenges ---\n", self.challenges.len());
        let mut sorted: Vec<&Challenge> = self.challenges.values().collect();
        sorted.sort_by_key(|c| c.id);
        for ch in sorted {
            let status = if ch.solved { "SOLVED" } else { "unsolved" };
            out.push_str(&format!(
                "  #{} {} [{}] reward={} attempts={}\n",
                ch.id, ch.name, status, ch.reward, ch.attempts
            ));
            if let Some(ref sol) = ch.solution {
                out.push_str(&format!("    solution: {}\n", sol));
            }
        }
        if let Some(active) = self.active_challenge {
            out.push_str(&format!("active: #{}\n", active));
        }
        out
    }

    /// Returns the currently active challenge, if any.
    pub fn active(&self) -> Option<&Challenge> {
        self.active_challenge
            .and_then(|id| self.challenges.get(&id))
    }

    /// Sets the active challenge by ID. Returns false if the ID is unknown.
    pub fn set_active(&mut self, id: ChallengeId) -> bool {
        if self.challenges.contains_key(&id) {
            self.active_challenge = Some(id);
            true
        } else {
            false
        }
    }

    /// Pick the highest-reward unsolved challenge and set it as active.
    pub fn next_unsolved(&mut self) -> Option<ChallengeId> {
        let best = self.get_unsolved().first().map(|c| c.id);
        if let Some(id) = best {
            self.active_challenge = Some(id);
        }
        best
    }
}

// ---------------------------------------------------------------------------
// S-expression constructors
// ---------------------------------------------------------------------------

/// Builds an S-expression for broadcasting a challenge to mesh peers.
pub fn sexp_challenge_broadcast(ch: &Challenge) -> String {
    let seeds: Vec<String> = ch
        .seed_programs
        .iter()
        .map(|s| format!("\"{}\"", s.replace('"', "\\\"")))
        .collect();
    format!(
        "(challenge :id {} :name \"{}\" :desc \"{}\" :target \"{}\" :reward {} :seeds ({}))",
        ch.id,
        ch.name.replace('"', "\\\""),
        ch.description.replace('"', "\\\""),
        ch.target_output.replace('"', "\\\""),
        ch.reward,
        seeds.join(" ")
    )
}

/// Builds an S-expression for broadcasting a solution to mesh peers.
pub fn sexp_solution_broadcast(
    challenge_id: ChallengeId,
    solution: &str,
    solver_hex: &str,
) -> String {
    format!(
        "(solution :challenge-id {} :program \"{}\" :solver \"{}\")",
        challenge_id,
        solution.replace('"', "\\\""),
        solver_hex
    )
}

// ---------------------------------------------------------------------------
// Conversion from existing fib10
// ---------------------------------------------------------------------------

/// Converts the default fib10 fitness challenge into a full `Challenge` struct.
pub fn fib10_as_challenge() -> Challenge {
    let fc = crate::evolve::fib10_challenge();
    Challenge {
        id: 0, // will be assigned by register_builtin
        name: fc.name,
        description: "find the shortest program that outputs 55 (10th Fibonacci)".into(),
        target_output: fc.target_output,
        test_input: None,
        max_steps: fc.max_steps,
        seed_programs: fc.seed_programs,
        origin: ChallengeOrigin::BuiltIn,
        reward: 100,
        solved: false,
        solution: None,
        solver: None,
        attempts: 0,
        solutions: vec![],
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn test_node_id() -> NodeId {
        [0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]
    }

    #[test]
    fn test_register_and_lookup() {
        let mut reg = ChallengeRegistry::new(&test_node_id());
        let id = reg.register_builtin("test", "42 ", vec!["42 .".into()]);
        assert!(reg.get_challenge(id).is_some());
        assert_eq!(reg.get_challenge(id).unwrap().name, "test");
    }

    #[test]
    fn test_mark_solved_lifecycle() {
        let mut reg = ChallengeRegistry::new(&test_node_id());
        let id = reg.register_builtin("test", "42 ", vec![]);
        assert!(!reg.get_challenge(id).unwrap().solved);
        assert!(reg.mark_solved(id, "42 .", test_node_id()));
        assert!(reg.get_challenge(id).unwrap().solved);
        assert_eq!(
            reg.get_challenge(id).unwrap().solution.as_deref(),
            Some("42 .")
        );
        // Can't solve again
        assert!(!reg.mark_solved(id, "other", test_node_id()));
    }

    #[test]
    fn test_merge_challenge_new() {
        let mut reg = ChallengeRegistry::new(&test_node_id());
        let ch = Challenge {
            id: 999,
            name: "remote".into(),
            description: "from peer".into(),
            target_output: "10 ".into(),
            test_input: None,
            max_steps: 5000,
            seed_programs: vec![],
            origin: ChallengeOrigin::Discovered {
                source_node: [0; 8],
                discovered_at: 0,
            },
            reward: 50,
            solved: false,
            solution: None,
            solver: None,
            attempts: 0,
            solutions: vec![],
        };
        reg.merge_challenge(ch);
        assert!(reg.get_challenge(999).is_some());
        assert!(reg.id_counter >= 1000);
    }

    #[test]
    fn test_merge_challenge_solved_update() {
        let mut reg = ChallengeRegistry::new(&test_node_id());
        let id = reg.register_builtin("test", "42 ", vec![]);
        let mut solved = reg.get_challenge(id).unwrap().clone();
        solved.solved = true;
        solved.solution = Some("42 .".into());
        reg.merge_challenge(solved);
        assert!(reg.get_challenge(id).unwrap().solved);
    }

    #[test]
    fn test_merge_challenge_duplicate_ignore() {
        let mut reg = ChallengeRegistry::new(&test_node_id());
        let id = reg.register_builtin("test", "42 ", vec!["seed".into()]);
        let dup = reg.get_challenge(id).unwrap().clone();
        reg.merge_challenge(dup);
        // Still just one challenge
        assert_eq!(reg.challenges.len(), 1);
    }

    #[test]
    fn test_to_fitness_challenge_roundtrip() {
        let mut reg = ChallengeRegistry::new(&test_node_id());
        let fib = fib10_as_challenge();
        let id = reg.register_builtin(&fib.name, &fib.target_output, fib.seed_programs.clone());
        let fc = reg.to_fitness_challenge(id).unwrap();
        assert_eq!(fc.name, "fib10");
        assert_eq!(fc.target_output, "55 ");
        assert_eq!(fc.seed_programs.len(), 5);
    }

    #[test]
    fn test_get_unsolved_ordering() {
        let mut reg = ChallengeRegistry::new(&test_node_id());
        reg.register_builtin("low", "1 ", vec![]);
        let high_id =
            reg.register_discovered("high", "important", "99 ", None, vec![], [0; 8], 200);
        let unsolved = reg.get_unsolved();
        assert_eq!(unsolved.len(), 2);
        assert_eq!(unsolved[0].id, high_id); // higher reward first
    }

    #[test]
    fn test_next_unsolved_picks_highest() {
        let mut reg = ChallengeRegistry::new(&test_node_id());
        reg.register_builtin("low", "1 ", vec![]);
        let high_id = reg.register_discovered("high", "desc", "99 ", None, vec![], [0; 8], 200);
        let picked = reg.next_unsolved();
        assert_eq!(picked, Some(high_id));
        assert_eq!(reg.active_challenge, Some(high_id));
    }

    #[test]
    fn test_sexp_challenge_broadcast() {
        let ch = Challenge {
            id: 42,
            name: "test-challenge".into(),
            description: "a test".into(),
            target_output: "55 ".into(),
            test_input: None,
            max_steps: 10000,
            seed_programs: vec!["0 .".into(), "1 .".into()],
            origin: ChallengeOrigin::BuiltIn,
            reward: 100,
            solved: false,
            solution: None,
            solver: None,
            attempts: 0,
            solutions: vec![],
        };
        let sexp = sexp_challenge_broadcast(&ch);
        assert!(sexp.contains("challenge"));
        assert!(sexp.contains(":id 42"));
        assert!(sexp.contains(":name \"test-challenge\""));
        assert!(sexp.contains(":reward 100"));
        assert!(sexp.contains(":seeds"));
    }

    #[test]
    fn test_sexp_solution_broadcast() {
        let sexp = sexp_solution_broadcast(42, "0 1 10 0 DO OVER + SWAP LOOP DROP .", "aabbccdd");
        assert!(sexp.contains("solution"));
        assert!(sexp.contains(":challenge-id 42"));
        assert!(sexp.contains(":solver \"aabbccdd\""));
    }

    #[test]
    fn test_multiple_solutions() {
        let mut reg = ChallengeRegistry::new(&test_node_id());
        let id = reg.register_builtin("test", "42 ", vec![]);
        // First solution marks solved.
        assert!(reg.mark_solved(id, "42 .", test_node_id()));
        assert_eq!(reg.solution_count(id), 1);
        // Second distinct solution is recorded.
        assert!(!reg.mark_solved(id, "6 7 * .", [0xBB; 8]));
        assert_eq!(reg.solution_count(id), 2);
        // Duplicate solution is ignored.
        assert!(!reg.mark_solved(id, "42 .", [0xCC; 8]));
        assert_eq!(reg.solution_count(id), 2);
    }

    #[test]
    fn test_solution_cap() {
        let mut reg = ChallengeRegistry::new(&test_node_id());
        let id = reg.register_builtin("test", "42 ", vec![]);
        for i in 0..25u8 {
            let prog = format!("{} 42 + 42 - .", i);
            reg.mark_solved(id, &prog, [i; 8]);
        }
        assert_eq!(reg.solution_count(id), 20); // capped
    }

    #[test]
    fn test_colony_diversity() {
        let mut reg = ChallengeRegistry::new(&test_node_id());
        let id = reg.register_builtin("test", "42 ", vec![]);
        reg.mark_solved(id, "42 .", test_node_id());
        reg.mark_solved(id, "6 7 * .", [0xBB; 8]);
        let out = reg.colony_diversity();
        assert!(out.contains("challenges solved: 1"));
        assert!(out.contains("total solutions: 2"));
    }

    #[test]
    fn test_format_challenges() {
        let mut reg = ChallengeRegistry::new(&test_node_id());
        assert!(reg.format_challenges().contains("no challenges"));
        reg.register_builtin("fib10", "55 ", vec![]);
        let out = reg.format_challenges();
        assert!(out.contains("fib10"));
        assert!(out.contains("unsolved"));
    }
}