clawgarden-agent 0.4.0

Agent runtime with persona/memory loader, judge, and pi RPC for ClawGarden
Documentation
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
//! speak_or_not judge - decides if agent should respond to a message
//!
//! v1 uses a rule-based heuristic judge. The judge evaluates whether an agent
//! should respond based on:
//!   1. Role-keyword relevance (content matches agent's expertise area)
//!   2. Engagement signals (questions, direct mentions, imperatives)
//!   3. Conversation context (recent messages, reply threading)
//!
//! All decision fields (speak, confidence, reason) are returned synchronously.
//! For Phase 2+, an LLM-based judge can be added via a `JudgeStrategy` trait.

use std::time::Duration;
use tokio::time::timeout;

/// Input for the judge
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct JudgeInput {
    /// Conversation identifier
    pub conversation_id: String,
    /// Correlation ID for tracing
    pub correlation_id: String,
    /// Message content to evaluate
    pub content: String,
    /// Agent persona (role, expertise, behavioral notes)
    pub persona: String,
    /// Agent memory (project context, recent decisions)
    pub memory: String,
    /// Recent messages in the conversation (context thread)
    pub recent_messages: Vec<String>,
}

/// Output from the judge
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct JudgeOutput {
    /// Whether the agent should speak
    pub speak: bool,
    /// Confidence score (0.0 to 1.0)
    pub confidence: f32,
    /// Optional reason for the decision
    pub reason: Option<String>,
}

/// Decision timeout in milliseconds
const DECISION_TIMEOUT_MS: u64 = 400;

// ── Engagement signal patterns ───────────────────────────────────────────────

/// Patterns that indicate a direct request or question (high engagement signals)
const QUESTION_PATTERNS: &[&str] = &[
    // English
    "how do",
    "how can",
    "how should",
    "how would",
    "what is",
    "what are",
    "what's",
    "whats",
    "why is",
    "why are",
    "why did",
    "why does",
    "who is",
    "who are",
    "who did",
    "when is",
    "when did",
    "when will",
    "where is",
    "where did",
    "can you",
    "could you",
    "would you",
    "should i",
    "should we",
    "is there",
    "are there",
    "do you",
    "does this",
    "tell me",
    "explain",
    "help me",
    "please",
    "give me",
    "need to",
    "need help",
    "looking for",
    // Korean
    "어떻게",
    "",
    "뭐야",
    "뭐예요",
    "뭔가",
    "누가",
    "언제",
    "어디",
    "해줘",
    "해줘요",
    "해주세요",
    "대답해",
    "말해줘",
    "알려줘",
    "도와줘",
    "설명해",
    "좀 해",
    "부탁해",
    "도움",
    "질문",
    "대답",
    "응답",
    "안녕",
];

/// Patterns that indicate low engagement (should defer)
const LOW_ENGAGEMENT_PATTERNS: &[&str] = &[
    "lol",
    "lmao",
    "haha",
    "🤣",
    "😂", // pure reactions
    "brb",
    "afk",
    "be right back",
    "sent",
    "delivered",
    "typing", // typing indicator
];

/// Sentiment/complexity markers
const POSITIVE_PATTERNS: &[&str] = &[
    "great",
    "awesome",
    "love it",
    "perfect",
    "thanks",
    "nice work",
    "well done",
    "sounds good",
];

const COMPLEX_PATTERNS: &[&str] = &[
    "however",
    "although",
    "but",
    "alternatively",
    "decision",
    "recommend",
    "strategy",
    "architecture",
    "refactor",
    "migration",
    "deployment",
    "deploy",
    "security",
    "performance",
    "optimization",
    "error",
    "bug",
    "issue",
    "fail",
    "crash",
    "api",
    "endpoint",
    "database",
    "service",
    "test",
    "review",
    "approve",
    "reject",
    "kubernetes",
    "k8s",
    "docker",
    "container",
    "helm",
    "rust",
    "golang",
    "nodejs",
    "python",
    "java",
    "microservice",
    "serverless",
    "ci/cd",
    "pipeline",
];

/// Default role keywords to check when persona is empty or unreadable
const DEFAULT_ROLE_KEYWORDS: &[(&str, &[&str])] = &[
    (
        "pm",
        &[
            "plan",
            "sprint",
            "task",
            "deadline",
            "priority",
            "roadmap",
            "stakeholder",
            "requirement",
        ],
    ),
    (
        "dev",
        &[
            "code",
            "implement",
            "bug",
            "api",
            "function",
            "refactor",
            "test",
            "deploy",
            "git",
        ],
    ),
    (
        "engineer",
        &[
            "code",
            "implement",
            "architecture",
            "system",
            "api",
            "database",
            "deploy",
        ],
    ),
    (
        "reviewer",
        &[
            "review",
            "code review",
            "feedback",
            "approve",
            "reject",
            "improve",
            "quality",
        ],
    ),
    (
        "critic",
        &[
            "concern",
            "issue",
            "risk",
            "problem",
            "think twice",
            "reconsider",
            "downside",
        ],
    ),
    (
        "designer",
        &[
            "design",
            "ui",
            "ux",
            "interface",
            "layout",
            "visual",
            "prototype",
            "figma",
        ],
    ),
    (
        "researcher",
        &[
            "research",
            "investigate",
            "find",
            "analyze",
            "data",
            "study",
            "explore",
        ],
    ),
    (
        "tester",
        &[
            "test",
            "bug",
            "edge case",
            "qa",
            "coverage",
            "failing",
            "assertion",
            "spec",
        ],
    ),
    (
        "ops",
        &[
            "deploy",
            "infrastructure",
            "docker",
            "kubernetes",
            "ci/cd",
            "pipeline",
            "monitor",
        ],
    ),
    (
        "analyst",
        &[
            "analyze",
            "metric",
            "data",
            "insight",
            "report",
            "trend",
            "query",
            "dashboard",
        ],
    ),
];

// ── Main judge entry point ───────────────────────────────────────────────────

/// Run the judge with a timeout guard.
/// Returns `JudgeOutput { speak: false, confidence: 0.0 }` on timeout or panic.
pub async fn judge(input: JudgeInput) -> JudgeOutput {
    let result = timeout(Duration::from_millis(DECISION_TIMEOUT_MS), async {
        Ok::<JudgeOutput, ()>(heuristic_judge(&input))
    })
    .await;

    match result {
        Ok(Ok(output)) => output,
        Ok(Err(())) => {
            log::warn!("Judge panicked, returning conservative default");
            JudgeOutput {
                speak: false,
                confidence: 0.0,
                reason: Some("Judge panicked — conservative no-speak".to_string()),
            }
        }
        Err(_) => {
            log::warn!("Judge timed out after {}ms", DECISION_TIMEOUT_MS);
            JudgeOutput {
                speak: false,
                confidence: 0.0,
                reason: Some("Decision timeout".to_string()),
            }
        }
    }
}

// ── Core heuristic implementation ────────────────────────────────────────────

/// Core heuristic judge — synchronous, no external calls
fn heuristic_judge(input: &JudgeInput) -> JudgeOutput {
    let content_lower = input.content.to_lowercase();
    let content = input.content.trim();

    // Reject obviously noise content early
    if is_noise(&content_lower, content) {
        return JudgeOutput {
            speak: false,
            confidence: 0.05,
            reason: Some("Low-engagement content (noise)".to_string()),
        };
    }

    // Extract role keywords from persona
    let role_keywords = extract_role_keywords(&input.persona);

    // Extract expertise phrases (multi-word)
    let expertise_phrases = extract_expertise_phrases(&input.persona);

    // Score each dimension
    let role_score = score_role_relevance(&content_lower, &role_keywords, &expertise_phrases);
    let engagement_score = score_engagement_signals(&content_lower, content);
    let context_score = score_conversation_context(&input.recent_messages);

    // Weighted combination: role (40%) + engagement (40%) + context (20%)
    let combined = (role_score * 0.4) + (engagement_score * 0.4) + (context_score * 0.2);

    // Threshold-based decision: combined score >= 0.05 triggers speak.
    // Explicit question patterns or any matching keyword is enough to speak.
    // Even low-confidence matches are worth speaking (false positives are
    // handled by the 10-agent voting system in the bus aggregation layer).
    let speak = combined > 0.05;
    let confidence = combined.min(1.0);

    let reason = build_reason(role_score, engagement_score, context_score, &role_keywords);

    JudgeOutput {
        speak,
        confidence,
        reason,
    }
}

/// Check if content is pure noise (should never warrant a response)
fn is_noise(content_lower: &str, content: &str) -> bool {
    // Empty or whitespace-only
    if content.is_empty() || content.trim().is_empty() {
        return true;
    }

    // Single emoji or very short reaction (< 5 chars, all emoji/symbols)
    if content.len() < 5 && !content.chars().any(|c| c.is_alphabetic()) {
        return true;
    }

    // Check against low-engagement patterns
    for pattern in LOW_ENGAGEMENT_PATTERNS {
        if content_lower.contains(pattern) {
            return true;
        }
    }

    false
}

/// Extract role keywords from persona text
fn extract_role_keywords(persona: &str) -> Vec<String> {
    let mut keywords = Vec::new();
    let mut seen = std::collections::HashSet::new();

    for line in persona.lines() {
        let line_lower = line.to_lowercase();

        // Role indicators: "role:", "i am", "i'm", "my job is", "my focus is"
        if line_lower.starts_with("role:")
            || line_lower.starts_with("i am ")
            || line_lower.starts_with("i'm ")
            || line_lower.contains("my job is")
            || line_lower.contains("my focus is")
            || line_lower.starts_with("- role:")
        {
            let cleaned = line
                .trim_start_matches(|c: char| c == '-' || c == ' ' || c == ':')
                .trim_start_matches("role:")
                .trim_start_matches("i am ")
                .trim_start_matches("i'm ")
                .trim_start_matches("my job is ")
                .trim_start_matches("my focus is ");

            for word in cleaned.split(|c: char| !c.is_alphanumeric() && c != '-' && c != '_') {
                let word = word.trim();
                if word.len() > 2 && seen.insert(word.to_string()) {
                    keywords.push(word.to_string());
                }
            }
        }

        // Expertise sections: "expertise:", "I specialize in", "I know about"
        if line_lower.starts_with("expertise:")
            || line_lower.starts_with("skills:")
            || line_lower.starts_with("specialize")
            || line_lower.starts_with("knowledge")
        {
            for word in line.split(|c: char| !c.is_alphanumeric() && c != '-' && c != '/') {
                let word = word.trim();
                if word.len() > 2 && seen.insert(word.to_string()) {
                    keywords.push(word.to_string());
                }
            }
        }
    }

    // De-duplicate
    keywords
}

/// Extract multi-word expertise phrases (2-3 word phrases)
fn extract_expertise_phrases(persona: &str) -> Vec<String> {
    let mut phrases = Vec::new();
    let mut seen = std::collections::HashSet::new();

    let lines: Vec<&str> = persona.lines().collect();

    for line in &lines {
        let line_lower = line.to_lowercase();

        if line_lower.starts_with("expertise:")
            || line_lower.starts_with("skills:")
            || line_lower.starts_with("expertiese:")
        // typo in some personas
        {
            // Try to extract 2-word phrases
            let content =
                line.trim_start_matches(|c: char| !c.is_alphabetic() && c != '-' && c != '/');
            let words: Vec<&str> = content.split_whitespace().collect();

            for window in words.windows(2) {
                let phrase = window.join(" ");
                if seen.insert(phrase.clone()) {
                    phrases.push(phrase);
                }
            }
            for window in words.windows(3) {
                let phrase = window.join(" ");
                if seen.insert(phrase.clone()) {
                    phrases.push(phrase);
                }
            }
        }
    }

    phrases
}

/// Score how well content matches the agent's role/expertise
fn score_role_relevance(
    content_lower: &str,
    role_keywords: &[String],
    _expertise_phrases: &[String],
) -> f32 {
    if role_keywords.is_empty() {
        // Fallback: use default role keyword table
        return score_with_default_keywords(content_lower);
    }

    let mut match_count = 0;
    let _phrase_matches = 0;

    for keyword in role_keywords {
        if content_lower.contains(&keyword.to_lowercase()) {
            match_count += 1;
        }
    }

    // Score: 0-0.7 based on keyword density
    let keyword_ratio = (match_count as f32 / (role_keywords.len() as f32).max(1.0)).min(1.0);
    keyword_ratio * 0.7
}

/// Fallback scoring using built-in role keyword table
fn score_with_default_keywords(content_lower: &str) -> f32 {
    let mut best_score = 0.0_f32;

    for (_role, keywords) in DEFAULT_ROLE_KEYWORDS {
        let matches: usize = keywords
            .iter()
            .filter(|kw| content_lower.contains(&kw.to_lowercase()))
            .count();

        let ratio = (matches as f32 / (keywords.len() as f32).max(1.0)).min(1.0);
        let score = ratio * 0.5; // cap at 0.5 for fallback mode
        best_score = best_score.max(score);
    }

    best_score
}

/// Score engagement signals (questions, imperatives, direct mentions)
fn score_engagement_signals(content_lower: &str, content: &str) -> f32 {
    let mut score = 0.0_f32;

    // Question detection — explicit question phrases are a strong engagement signal
    for pattern in QUESTION_PATTERNS {
        if content_lower.contains(pattern) {
            score += 0.35; // 0.35 base + other signals can push total to 0.2+ confidence
        }
    }

    // Direct question mark fallback (even without known pattern)
    if content.contains('?') && score == 0.0 {
        score += 0.25;
    }

    // Imperative commands
    if content_lower.starts_with("please ")
        || content_lower.starts_with("can you ")
        || content_lower.starts_with("could you ")
        || content_lower.starts_with("would you ")
        || content_lower.starts_with("tell ")
        || content_lower.starts_with("show ")
        || content_lower.starts_with("give ")
    {
        score += 0.2;
    }

    // Positive/complex content signals
    for pattern in POSITIVE_PATTERNS {
        if content_lower.contains(pattern) {
            score += 0.1;
        }
    }

    for pattern in COMPLEX_PATTERNS {
        if content_lower.contains(pattern) {
            score += 0.05;
        }
    }

    // Content length bonus (longer substantive content is more likely relevant)
    let word_count = content.split_whitespace().count();
    if word_count >= 10 {
        score += 0.05;
    }
    if word_count >= 30 {
        score += 0.05;
    }

    score.min(1.0)
}

/// Score conversation context — does the thread suggest the agent should respond?
fn score_conversation_context(recent_messages: &[String]) -> f32 {
    if recent_messages.is_empty() {
        return 0.0;
    }

    let mut score = 0.0_f32;

    // If recent messages show active discussion, slightly boost
    let avg_len: usize =
        recent_messages.iter().map(|m| m.len()).sum::<usize>() / recent_messages.len().max(1);

    if avg_len > 20 {
        score += 0.1;
    }

    // Recent message mentions "we should", "let's", "what about" (collaborative signals)
    for msg in recent_messages.iter().take(3) {
        let msg_lower = msg.to_lowercase();
        if msg_lower.contains("what about")
            || msg_lower.contains("let's ")
            || msg_lower.contains("we should")
            || msg_lower.contains("agree")
        {
            score += 0.05;
        }
    }

    score.min(1.0)
}

/// Build a human-readable reason string
fn build_reason(
    role_score: f32,
    engagement_score: f32,
    context_score: f32,
    _role_keywords: &[String],
) -> Option<String> {
    let mut parts = Vec::new();

    if role_score > 0.1 {
        parts.push(format!(
            "role_match={:.2}",
            (role_score * 10.0).round() / 10.0
        ));
    }
    if engagement_score > 0.1 {
        parts.push(format!(
            "engagement={:.2}",
            (engagement_score * 10.0).round() / 10.0
        ));
    }
    if context_score > 0.05 {
        parts.push(format!(
            "context={:.2}",
            (context_score * 10.0).round() / 10.0
        ));
    }

    if parts.is_empty() {
        None
    } else {
        Some(format!("scores[{}]", parts.join("|")))
    }
}

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

    fn make_input(content: &str, persona: &str) -> JudgeInput {
        JudgeInput {
            conversation_id: "conv_1".to_string(),
            correlation_id: "req_1".to_string(),
            content: content.to_string(),
            persona: persona.to_string(),
            memory: String::new(),
            recent_messages: vec![],
        }
    }

    #[test]
    fn test_noise_rejection() {
        // Single emoji
        assert!(!heuristic_judge(&make_input("😂", "")).speak);

        // Short reaction
        assert!(!heuristic_judge(&make_input("lol", "")).speak);

        // "brb"
        assert!(!heuristic_judge(&make_input("brb", "")).speak);
    }

    #[test]
    fn test_question_detection() {
        let input = make_input(
            "How do I deploy a Rust service to Kubernetes?",
            "Role: ops engineer",
        );
        let output = heuristic_judge(&input);
        assert!(output.speak, "expected speak=true, got false");
        assert!(
            output.confidence > 0.2,
            "expected confidence > 0.2, got {:.3}",
            output.confidence
        );
    }

    #[test]
    fn test_role_keyword_extraction() {
        let persona =
            "Role: garden expert\nI am a plant specialist\nExpertiese: vegetables, herbs, soil";
        let keywords = extract_role_keywords(persona);
        assert!(keywords.iter().any(|k| k.contains("expert")));
        assert!(keywords.iter().any(|k| k.contains("plant")));
        assert!(keywords.iter().any(|k| k.contains("specialist")));
    }

    #[test]
    fn test_role_relevance_garden() {
        let persona = "Role: garden expert\nI am a plant specialist";
        let input = make_input("My tomato plants have yellow leaves", persona);
        let output = heuristic_judge(&input);
        assert!(output.speak);
    }

    #[test]
    fn test_imperative_command() {
        let input = make_input(
            "Please review the PR for the new API endpoint",
            "Role: reviewer",
        );
        let output = heuristic_judge(&input);
        assert!(output.speak);
    }

    #[test]
    fn test_complex_content() {
        let persona = "Role: engineer";
        let input = make_input(
            "We need to refactor the database migration script before the security audit",
            persona,
        );
        let output = heuristic_judge(&input);
        assert!(output.confidence > 0.0);
    }

    #[tokio::test]
    async fn test_judge_timeout() {
        let input = make_input("Hello world", "Role: pm");
        let output = judge(input).await;
        // Should complete without hanging
        assert!(output.confidence >= 0.0);
    }

    #[test]
    fn test_multi_word_expertise_phrases() {
        let persona = "Expertiese: code review, database design, system architecture";
        let phrases = extract_expertise_phrases(persona);
        assert!(phrases.iter().any(|p| p.contains("code review")));
        assert!(phrases.iter().any(|p| p.contains("database design")));
    }

    #[test]
    fn test_conservative_default_on_empty_persona() {
        let input = make_input("What's for lunch?", "");
        let output = heuristic_judge(&input);
        // Without persona keywords, question detection should still work
        assert!(output.confidence >= 0.0);
    }

    #[test]
    fn test_engagement_score_imperative() {
        // Imperative commands should get higher engagement score
        let input_please = make_input("Please check the build logs", "Role: dev");
        let input_plain = make_input("Build logs show an error", "Role: dev");

        let score_please =
            score_engagement_signals(&input_please.content.to_lowercase(), &input_please.content);
        let score_plain =
            score_engagement_signals(&input_plain.content.to_lowercase(), &input_plain.content);

        assert!(score_please > score_plain);
    }
}