mx 0.1.106

A Swiss army knife for Claude Code and multi-agent toolkits
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
use anyhow::{Result, bail};
use std::collections::HashMap;

use crate::engage::{MatchResult, fuzzy_match};
use crate::knowledge::KnowledgeEntry;
use crate::store::{AgentContext, KnowledgeStore, WakeCascade};
use crate::wake_token::*;

/// Start a new wake ritual session
pub fn begin_ritual(db: &dyn KnowledgeStore, cascade: &WakeCascade) -> Result<String> {
    if cascade.core.is_empty() && cascade.recent.is_empty() && cascade.bridges.is_empty() {
        bail!("No blooms to wake");
    }

    let session = WakeSession::new(cascade);
    let total = session.total();

    // Build lookup map from the cascade we already have
    let all_blooms = build_bloom_map(cascade);

    // Get first bloom
    let first_id = session
        .current_bloom_id()
        .ok_or_else(|| anyhow::anyhow!("No blooms in session"))?;
    let first_bloom = all_blooms
        .get(first_id)
        .ok_or_else(|| anyhow::anyhow!("Bloom not found: {}", first_id))?;

    // Persist session to DB, get back the session_id
    let session_id = db.create_wake_session(&session)?;

    // Return signed token instead of bare session_id
    let token = create_token(&session_id, 0);

    let response = WakeBeginResponse {
        status: "ritual_started".to_string(),
        session: token,
        prompt: BloomPrompt::from(*first_bloom),
        progress: Progress {
            current: 1,
            total,
            remembered: None,
            needed_help: None,
            skipped: None,
        },
    };

    Ok(serde_json::to_string(&response)?)
}

/// Process a wake phrase response
pub fn respond_ritual(
    db: &dyn KnowledgeStore,
    ctx: &AgentContext,
    bloom_id: &str,
    phrase: &str,
    token_str: &str,
) -> Result<String> {
    // Verify token and extract session_id + step
    let (session_id, token_index) =
        verify_token(token_str).map_err(|e| anyhow::anyhow!("Token verification failed: {}", e))?;

    // Load session from DB
    let mut session = db
        .get_wake_session(&session_id)?
        .ok_or_else(|| anyhow::anyhow!("Session not found: {}", session_id))?;

    // Anti-replay: token step must match server-side state
    if session.current_index != token_index {
        bail!(
            "Token out of sync: token step {} but session at step {}",
            token_index,
            session.current_index
        );
    }

    // Fetch blooms by ID from session (source of truth)
    let all_blooms = fetch_blooms_by_ids(db, ctx, &session.bloom_ids)?;

    // Verify we're on the right bloom
    let expected_id = session
        .current_bloom_id()
        .ok_or_else(|| anyhow::anyhow!("Ritual already complete"))?;

    if bloom_id != expected_id {
        let response = WakeErrorResponse {
            status: "error".to_string(),
            error: "invalid_bloom_id".to_string(),
            message: format!("Expected bloom {}, got {}", expected_id, bloom_id),
            expected_id: Some(expected_id.to_string()),
        };
        return Ok(serde_json::to_string(&response)?);
    }

    // Get the bloom
    let bloom = all_blooms
        .get(expected_id)
        .ok_or_else(|| anyhow::anyhow!("Bloom not found: {}", expected_id))?;

    // Get the pre-selected wake phrase from session
    let phrase_idx = session
        .current_phrase_index()
        .ok_or_else(|| anyhow::anyhow!("This bloom has no wake phrase - use --skip instead"))?;

    let wake_phrase = if !bloom.wake_phrases.is_empty() {
        bloom
            .wake_phrases
            .get(phrase_idx)
            .ok_or_else(|| anyhow::anyhow!("Invalid phrase index"))?
            .clone()
    } else if let Some(ref p) = bloom.wake_phrase {
        p.clone()
    } else {
        bail!("This bloom has no wake phrase - use --skip instead");
    };

    // Match the phrase
    let match_result = fuzzy_match(phrase, &wake_phrase);

    match match_result {
        MatchResult::Exact | MatchResult::Close => {
            // SUCCESS! Advance and return bloom
            session.advance_remembered();

            let match_type = if matches!(match_result, MatchResult::Exact) {
                "exact"
            } else {
                "close"
            };

            // Get next bloom if any
            let (next, progress, summary) = get_next_and_progress(&session, &all_blooms)?;

            // Persist updated session (or delete if complete)
            if session.is_complete() {
                db.delete_wake_session(&session_id)?;
            } else {
                db.update_wake_session(&session)?;
            }

            // Create BloomFull with matched phrase
            let mut bloom_full = BloomFull::from(bloom);
            bloom_full.matched_phrase = Some(wake_phrase.clone());

            // New token reflects updated step
            let new_token = create_token(&session_id, session.current_index);

            let response = WakeRespondResponse {
                status: "remembered".to_string(),
                match_type: Some(match_type.to_string()),
                bloom: Some(bloom_full),
                attempt: None,
                hint: None,
                prompt: None,
                session: new_token,
                next,
                progress: Some(progress),
                summary,
            };

            Ok(serde_json::to_string(&response)?)
        }
        MatchResult::Partial | MatchResult::Wrong => {
            // Increment attempt
            session.increment_attempt();
            let attempt = session.attempts_on_current;

            if attempt >= 3 {
                // Max attempts reached - reveal and advance
                session.advance_helped();

                let (next, progress, summary) = get_next_and_progress(&session, &all_blooms)?;

                // Persist updated session (or delete if complete)
                if session.is_complete() {
                    db.delete_wake_session(&session_id)?;
                } else {
                    db.update_wake_session(&session)?;
                }

                // Create BloomFull with revealed phrase
                let mut bloom_full = BloomFull::from(bloom);
                bloom_full.matched_phrase = Some(wake_phrase.clone());

                // New token reflects updated step
                let new_token = create_token(&session_id, session.current_index);

                let response = WakeRespondResponse {
                    status: "revealed".to_string(),
                    match_type: None,
                    bloom: Some(bloom_full),
                    attempt: None,
                    hint: None,
                    prompt: None,
                    session: new_token,
                    next,
                    progress: Some(progress),
                    summary,
                };

                Ok(serde_json::to_string(&response)?)
            } else {
                // Give hint and ask for retry - save incremented attempt count
                db.update_wake_session(&session)?;

                let hint = generate_hint(&wake_phrase, attempt);

                // Same step (retry), but fresh token
                let new_token = create_token(&session_id, session.current_index);

                let response = WakeRespondResponse {
                    status: "incorrect".to_string(),
                    match_type: None,
                    bloom: None,
                    attempt: Some(attempt),
                    hint: Some(hint),
                    prompt: Some(BloomPrompt::from(bloom)),
                    session: new_token,
                    next: None,
                    progress: None,
                    summary: None,
                };

                Ok(serde_json::to_string(&response)?)
            }
        }
    }
}

/// Skip a bloom (for blooms without wake phrase)
pub fn skip_ritual(
    db: &dyn KnowledgeStore,
    ctx: &AgentContext,
    bloom_id: &str,
    token_str: &str,
) -> Result<String> {
    // Verify token and extract session_id + step
    let (session_id, token_index) =
        verify_token(token_str).map_err(|e| anyhow::anyhow!("Token verification failed: {}", e))?;

    // Load session from DB
    let mut session = db
        .get_wake_session(&session_id)?
        .ok_or_else(|| anyhow::anyhow!("Session not found: {}", session_id))?;

    // Anti-replay: token step must match server-side state
    if session.current_index != token_index {
        bail!(
            "Token out of sync: token step {} but session at step {}",
            token_index,
            session.current_index
        );
    }

    // Fetch blooms by ID from session (source of truth)
    let all_blooms = fetch_blooms_by_ids(db, ctx, &session.bloom_ids)?;

    // Verify we're on the right bloom
    let expected_id = session
        .current_bloom_id()
        .ok_or_else(|| anyhow::anyhow!("Ritual already complete"))?;

    if bloom_id != expected_id {
        let response = WakeErrorResponse {
            status: "error".to_string(),
            error: "invalid_bloom_id".to_string(),
            message: format!("Expected bloom {}, got {}", expected_id, bloom_id),
            expected_id: Some(expected_id.to_string()),
        };
        return Ok(serde_json::to_string(&response)?);
    }

    // Get the bloom
    let bloom = all_blooms
        .get(expected_id)
        .ok_or_else(|| anyhow::anyhow!("Bloom not found: {}", expected_id))?;

    // Advance as skipped
    session.advance_skipped();

    let (next, progress, summary) = get_next_and_progress(&session, &all_blooms)?;

    // Persist updated session (or delete if complete)
    if session.is_complete() {
        db.delete_wake_session(&session_id)?;
    } else {
        db.update_wake_session(&session)?;
    }

    // New token reflects updated step
    let new_token = create_token(&session_id, session.current_index);

    let response = WakeSkipResponse {
        status: "skipped".to_string(),
        bloom: BloomFull::from(bloom),
        session: new_token,
        next,
        progress: Some(progress),
        summary,
    };

    Ok(serde_json::to_string(&response)?)
}

/// Fetch blooms by IDs and build lookup map
fn fetch_blooms_by_ids(
    db: &dyn KnowledgeStore,
    ctx: &AgentContext,
    bloom_ids: &[String],
) -> Result<HashMap<String, KnowledgeEntry>> {
    let mut map = HashMap::new();

    for id in bloom_ids {
        if let Some(entry) = db.get(id, ctx)? {
            map.insert(id.clone(), entry);
        } else {
            bail!("Bloom not found in database: {}", id);
        }
    }

    Ok(map)
}

/// Build lookup map of all blooms from cascade
fn build_bloom_map(cascade: &WakeCascade) -> HashMap<String, &KnowledgeEntry> {
    let mut map = HashMap::new();

    for entry in &cascade.core {
        map.insert(entry.id.clone(), entry);
    }
    for entry in &cascade.recent {
        map.insert(entry.id.clone(), entry);
    }
    for entry in &cascade.bridges {
        map.insert(entry.id.clone(), entry);
    }

    map
}

/// Get next bloom prompt and current progress
fn get_next_and_progress(
    session: &WakeSession,
    all_blooms: &HashMap<String, KnowledgeEntry>,
) -> Result<(Option<BloomPrompt>, Progress, Option<Summary>)> {
    let current = session.current_position();
    let total = session.total();

    let progress = Progress {
        current,
        total,
        remembered: Some(session.remembered_count),
        needed_help: Some(session.needed_help_count),
        skipped: Some(session.skipped_count),
    };

    if session.is_complete() {
        // Ritual complete
        let summary = Summary {
            total,
            remembered: session.remembered_count,
            needed_help: session.needed_help_count,
            skipped: session.skipped_count,
        };
        Ok((None, progress, Some(summary)))
    } else {
        // Get next bloom
        let next_id = session
            .current_bloom_id()
            .ok_or_else(|| anyhow::anyhow!("Failed to get next bloom"))?;
        let next_bloom = all_blooms
            .get(next_id)
            .ok_or_else(|| anyhow::anyhow!("Next bloom not found: {}", next_id))?;

        Ok((Some(BloomPrompt::from(next_bloom)), progress, None))
    }
}

/// Generate progressive hints
fn generate_hint(phrase: &str, attempt: u8) -> String {
    match attempt {
        1 => {
            // Hint 1: starts with...
            let words: Vec<&str> = phrase.split_whitespace().collect();
            if let Some(first_word) = words.first() {
                format!("starts with \"{}...\"", first_word)
            } else {
                "think carefully...".to_string()
            }
        }
        2 => {
            // Hint 2: blank out middle word
            let words: Vec<&str> = phrase.split_whitespace().collect();
            if words.len() >= 3 {
                let middle_idx = words.len() / 2;
                let hint_words: Vec<String> = words
                    .iter()
                    .enumerate()
                    .map(|(i, w)| {
                        if i == middle_idx {
                            "___".to_string()
                        } else {
                            w.to_string()
                        }
                    })
                    .collect();
                format!("\"{}\"", hint_words.join(" "))
            } else if words.len() == 2 {
                format!("\"{} ___\"", words[0])
            } else if !words.is_empty() {
                let first_word = words[0];
                if first_word.chars().count() > 3 {
                    let prefix: String = first_word.chars().take(3).collect();
                    format!("\"{}...\"", prefix)
                } else {
                    phrase.to_string()
                }
            } else {
                "almost there...".to_string()
            }
        }
        _ => "one more try...".to_string(),
    }
}

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

    // =====================================================================
    // Regression tests for unicode boundary panic fix (PR #162)
    //
    // generate_hint() previously used `&first_word[..3]` (byte-index slicing)
    // on single-word wake phrases. Multi-byte UTF-8 characters at the start
    // of the word would cause a panic when byte index 3 landed inside a
    // character. The fix uses `.chars().take(3).collect()` instead.
    // =====================================================================

    #[test]
    fn test_generate_hint_single_emoji_word_would_panic() {
        // Single-word wake phrase made of emoji (4 bytes each).
        // Old code: `&first_word[..3]` slices at byte 3, which is inside
        // the first emoji (bytes 0..3). PANIC!
        let phrase = "\u{1F41F}\u{1F41F}\u{1F41F}\u{1F41F}\u{1F41F}";
        assert_eq!(phrase.chars().count(), 5);
        // Verify byte 3 is NOT a char boundary (the actual panic trigger)
        assert!(!phrase.is_char_boundary(3));

        // attempt=2 triggers the single-word prefix path
        let result = generate_hint(phrase, 2);
        // Should contain first 3 characters (emoji), not panic
        let expected_prefix: String = phrase.chars().take(3).collect();
        assert!(result.contains(&expected_prefix));
        assert!(result.contains("..."));
    }

    #[test]
    fn test_generate_hint_single_cjk_word_would_panic() {
        // Single CJK word (no spaces). CJK chars are 3 bytes each.
        // Old code: `&first_word[..3]` = first 3 bytes = exactly 1 CJK char.
        // This actually happens to NOT panic for pure CJK (3 divides evenly),
        // but it only takes 1 character instead of 3. The fix correctly
        // takes 3 characters.
        let phrase = "\u{4E16}\u{754C}\u{4F60}\u{597D}\u{5417}"; // 5 CJK chars
        assert_eq!(phrase.chars().count(), 5);

        let result = generate_hint(phrase, 2);
        let expected_prefix: String = phrase.chars().take(3).collect();
        assert!(result.contains(&expected_prefix));
    }

    #[test]
    fn test_generate_hint_single_mixed_multibyte_word_would_panic() {
        // A word starting with a 2-byte char (e.g., U+00E9 'e with acute').
        // "\u{00E9}" is 2 bytes. "\u{00E9}abc" = "eabc", 4 chars, 5 bytes.
        // Old code: &word[..3] = bytes 0..3, byte 2 is inside 'a' which is
        // fine here. But "\u{00E9}\u{00E9}\u{00E9}\u{00E9}" = 4 chars, 8 bytes.
        // &word[..3] = byte 3, inside the 2nd char (bytes 2..3). PANIC!
        let phrase = "\u{00E9}\u{00E9}\u{00E9}\u{00E9}";
        assert_eq!(phrase.chars().count(), 4);
        assert_eq!(phrase.len(), 8);
        // Byte 3 is NOT a char boundary
        assert!(!phrase.is_char_boundary(3));

        let result = generate_hint(phrase, 2);
        let expected_prefix: String = phrase.chars().take(3).collect();
        assert!(result.contains(&expected_prefix));
    }

    #[test]
    fn test_generate_hint_attempt_1_first_word_with_emoji() {
        // attempt=1 shows "starts with <first_word>..."
        // This path was safe (uses the whole first word), but verify it
        // still works with multi-byte characters.
        let phrase = "\u{1F41F}\u{1F41F} hello world";
        let result = generate_hint(phrase, 1);
        assert!(result.contains("\u{1F41F}\u{1F41F}"));
        assert!(result.starts_with("starts with"));
    }

    #[test]
    fn test_generate_hint_attempt_2_multiword_with_emoji() {
        // attempt=2 with 3+ words blanks the middle word.
        // Should work fine with emoji words.
        let phrase = "\u{1F41F}\u{1F41F} middle \u{4E16}\u{754C}";
        let result = generate_hint(phrase, 2);
        assert!(result.contains("___"));
        // First and last words should be preserved
        assert!(result.contains("\u{1F41F}\u{1F41F}"));
        assert!(result.contains("\u{4E16}\u{754C}"));
    }

    #[test]
    fn test_generate_hint_attempt_2_two_emoji_words() {
        // attempt=2 with exactly 2 words: shows "first ___"
        let phrase = "\u{1F41F}\u{1F41F} \u{4E16}\u{754C}";
        let result = generate_hint(phrase, 2);
        assert!(result.contains("\u{1F41F}\u{1F41F}"));
        assert!(result.contains("___"));
    }

    #[test]
    fn test_generate_hint_short_single_emoji_word() {
        // Single word with <= 3 chars: returns the phrase as-is (no prefix).
        let phrase = "\u{1F41F}\u{1F41F}"; // 2 chars
        assert_eq!(phrase.chars().count(), 2);

        let result = generate_hint(phrase, 2);
        // chars().count() <= 3, so it returns phrase.to_string()
        assert_eq!(result, phrase);
    }
}