Skip to main content

lean_ctx/core/
agents.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4use std::path::PathBuf;
5
6use crate::core::a2a::message::{A2AMessage, MessageCategory, MessagePriority, PrivacyLevel};
7
8const MAX_SCRATCHPAD_ENTRIES: usize = 200;
9const MAX_DIARY_ENTRIES: usize = 100;
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct AgentRegistry {
13    pub agents: Vec<AgentEntry>,
14    pub scratchpad: Vec<ScratchpadEntry>,
15    pub updated_at: DateTime<Utc>,
16}
17
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct AgentDiary {
20    pub agent_id: String,
21    pub agent_type: String,
22    pub project_root: String,
23    pub entries: Vec<DiaryEntry>,
24    pub created_at: DateTime<Utc>,
25    pub updated_at: DateTime<Utc>,
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct DiaryEntry {
30    pub entry_type: DiaryEntryType,
31    pub content: String,
32    pub context: Option<String>,
33    pub timestamp: DateTime<Utc>,
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
37pub enum DiaryEntryType {
38    Discovery,
39    Decision,
40    Blocker,
41    Progress,
42    Insight,
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct AgentEntry {
47    pub agent_id: String,
48    pub agent_type: String,
49    pub role: Option<String>,
50    pub project_root: String,
51    pub started_at: DateTime<Utc>,
52    pub last_active: DateTime<Utc>,
53    pub pid: u32,
54    pub status: AgentStatus,
55    pub status_message: Option<String>,
56}
57
58#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
59pub enum AgentStatus {
60    Active,
61    Idle,
62    Finished,
63}
64
65impl std::fmt::Display for AgentStatus {
66    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        match self {
68            AgentStatus::Active => write!(f, "active"),
69            AgentStatus::Idle => write!(f, "idle"),
70            AgentStatus::Finished => write!(f, "finished"),
71        }
72    }
73}
74
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct ScratchpadEntry {
77    pub id: String,
78    pub from_agent: String,
79    pub to_agent: Option<String>,
80    #[serde(default)]
81    pub task_id: Option<String>,
82    pub category: String,
83    #[serde(default)]
84    pub priority: MessagePriority,
85    #[serde(default)]
86    pub privacy: PrivacyLevel,
87    pub message: String,
88    #[serde(default)]
89    pub metadata: HashMap<String, String>,
90    #[serde(default)]
91    pub project_root: Option<String>,
92    pub timestamp: DateTime<Utc>,
93    pub read_by: Vec<String>,
94    #[serde(default)]
95    pub expires_at: Option<DateTime<Utc>>,
96}
97
98impl AgentRegistry {
99    pub fn new() -> Self {
100        Self {
101            agents: Vec::new(),
102            scratchpad: Vec::new(),
103            updated_at: Utc::now(),
104        }
105    }
106
107    pub fn register(&mut self, agent_type: &str, role: Option<&str>, project_root: &str) -> String {
108        let pid = std::process::id();
109        let agent_id = format!("{}-{}-{}", agent_type, pid, generate_short_id());
110
111        if let Some(existing) = self.agents.iter_mut().find(|a| a.pid == pid) {
112            existing.last_active = Utc::now();
113            existing.status = AgentStatus::Active;
114            if let Some(r) = role {
115                existing.role = Some(r.to_string());
116            }
117            return existing.agent_id.clone();
118        }
119
120        self.agents.push(AgentEntry {
121            agent_id: agent_id.clone(),
122            agent_type: agent_type.to_string(),
123            role: role.map(std::string::ToString::to_string),
124            project_root: project_root.to_string(),
125            started_at: Utc::now(),
126            last_active: Utc::now(),
127            pid,
128            status: AgentStatus::Active,
129            status_message: None,
130        });
131
132        self.updated_at = Utc::now();
133        crate::core::events::emit_agent_action(&agent_id, "register", None);
134        agent_id
135    }
136
137    pub fn update_heartbeat(&mut self, agent_id: &str) {
138        if let Some(agent) = self.agents.iter_mut().find(|a| a.agent_id == agent_id) {
139            agent.last_active = Utc::now();
140        }
141    }
142
143    pub fn set_status(&mut self, agent_id: &str, status: AgentStatus, message: Option<&str>) {
144        if let Some(agent) = self.agents.iter_mut().find(|a| a.agent_id == agent_id) {
145            agent.status = status;
146            agent.status_message = message.map(std::string::ToString::to_string);
147            agent.last_active = Utc::now();
148        }
149        self.updated_at = Utc::now();
150    }
151
152    pub fn list_active(&self, project_root: Option<&str>) -> Vec<&AgentEntry> {
153        self.agents
154            .iter()
155            .filter(|a| {
156                if let Some(root) = project_root {
157                    a.project_root == root && a.status != AgentStatus::Finished
158                } else {
159                    a.status != AgentStatus::Finished
160                }
161            })
162            .collect()
163    }
164
165    pub fn list_all(&self) -> &[AgentEntry] {
166        &self.agents
167    }
168
169    pub fn post_message(
170        &mut self,
171        from_agent: &str,
172        to_agent: Option<&str>,
173        category: &str,
174        message: &str,
175    ) -> String {
176        self.post_message_full(
177            from_agent,
178            to_agent,
179            category,
180            message,
181            PrivacyLevel::default(),
182            MessagePriority::default(),
183            None,
184        )
185    }
186
187    pub fn post_message_full(
188        &mut self,
189        from_agent: &str,
190        to_agent: Option<&str>,
191        category: &str,
192        message: &str,
193        privacy: PrivacyLevel,
194        priority: MessagePriority,
195        ttl_hours: Option<u64>,
196    ) -> String {
197        let id = generate_short_id();
198        let expires_at = ttl_hours.map(|h| Utc::now() + chrono::Duration::hours(h as i64));
199        self.scratchpad.push(ScratchpadEntry {
200            id: id.clone(),
201            from_agent: from_agent.to_string(),
202            to_agent: to_agent.map(std::string::ToString::to_string),
203            task_id: None,
204            category: category.to_string(),
205            priority,
206            privacy,
207            message: message.to_string(),
208            metadata: HashMap::new(),
209            project_root: None,
210            timestamp: Utc::now(),
211            read_by: vec![from_agent.to_string()],
212            expires_at,
213        });
214
215        if self.scratchpad.len() > MAX_SCRATCHPAD_ENTRIES {
216            self.scratchpad
217                .drain(0..self.scratchpad.len() - MAX_SCRATCHPAD_ENTRIES);
218        }
219
220        self.updated_at = Utc::now();
221        id
222    }
223
224    pub fn read_messages(&mut self, agent_id: &str) -> Vec<&ScratchpadEntry> {
225        let unread: Vec<usize> = self
226            .scratchpad
227            .iter()
228            .enumerate()
229            .filter(|(_, e)| {
230                !e.read_by.contains(&agent_id.to_string())
231                    && (e.to_agent.is_none() || e.to_agent.as_deref() == Some(agent_id))
232            })
233            .map(|(i, _)| i)
234            .collect();
235
236        for i in &unread {
237            self.scratchpad[*i].read_by.push(agent_id.to_string());
238        }
239
240        self.scratchpad
241            .iter()
242            .filter(|e| e.to_agent.is_none() || e.to_agent.as_deref() == Some(agent_id))
243            .filter(|e| e.from_agent != agent_id)
244            .collect()
245    }
246
247    pub fn read_unread(&mut self, agent_id: &str) -> Vec<&ScratchpadEntry> {
248        let unread_indices: Vec<usize> = self
249            .scratchpad
250            .iter()
251            .enumerate()
252            .filter(|(_, e)| {
253                !e.read_by.contains(&agent_id.to_string())
254                    && e.from_agent != agent_id
255                    && (e.to_agent.is_none() || e.to_agent.as_deref() == Some(agent_id))
256            })
257            .map(|(i, _)| i)
258            .collect();
259
260        for i in &unread_indices {
261            self.scratchpad[*i].read_by.push(agent_id.to_string());
262        }
263
264        self.updated_at = Utc::now();
265
266        self.scratchpad
267            .iter()
268            .filter(|e| {
269                e.from_agent != agent_id
270                    && (e.to_agent.is_none() || e.to_agent.as_deref() == Some(agent_id))
271                    && e.read_by.contains(&agent_id.to_string())
272                    && e.read_by.iter().filter(|r| *r == agent_id).count() == 1
273            })
274            .collect()
275    }
276
277    pub fn cleanup_stale(&mut self, max_age_hours: u64) {
278        let cutoff = Utc::now() - chrono::Duration::hours(max_age_hours as i64);
279
280        for agent in &mut self.agents {
281            if agent.status == AgentStatus::Finished {
282                continue;
283            }
284            if !is_process_alive(agent.pid) {
285                agent.status = AgentStatus::Finished;
286            }
287        }
288
289        // Remove finished agents older than the cutoff to keep recent history visible.
290        // Drop each retired agent's budget entry too — a finished/dead agent can't read
291        // again, so removing its budget loses no live enforcement and bounds BUDGETS.
292        self.agents.retain(|a| {
293            let retire = a.status == AgentStatus::Finished && a.last_active < cutoff;
294            if retire {
295                crate::core::agent_budget::remove(&a.agent_id);
296            }
297            !retire
298        });
299
300        self.updated_at = Utc::now();
301    }
302
303    pub fn save(&self) -> Result<(), String> {
304        let dir = agents_dir()?;
305        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
306
307        let path = dir.join("registry.json");
308        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
309
310        let lock_path = dir.join("registry.lock");
311        let _lock = FileLock::acquire(&lock_path)?;
312
313        std::fs::write(&path, json).map_err(|e| e.to_string())
314    }
315
316    pub fn load() -> Option<Self> {
317        let dir = agents_dir().ok()?;
318        let path = dir.join("registry.json");
319        let content = std::fs::read_to_string(&path).ok()?;
320        serde_json::from_str(&content).ok()
321    }
322
323    pub fn load_or_create() -> Self {
324        Self::load().unwrap_or_default()
325    }
326}
327
328impl Default for AgentRegistry {
329    fn default() -> Self {
330        Self::new()
331    }
332}
333
334impl AgentDiary {
335    pub fn new(agent_id: &str, agent_type: &str, project_root: &str) -> Self {
336        let now = Utc::now();
337        Self {
338            agent_id: agent_id.to_string(),
339            agent_type: agent_type.to_string(),
340            project_root: project_root.to_string(),
341            entries: Vec::new(),
342            created_at: now,
343            updated_at: now,
344        }
345    }
346
347    pub fn add_entry(&mut self, entry_type: DiaryEntryType, content: &str, context: Option<&str>) {
348        self.entries.push(DiaryEntry {
349            entry_type,
350            content: content.to_string(),
351            context: context.map(std::string::ToString::to_string),
352            timestamp: Utc::now(),
353        });
354        if self.entries.len() > MAX_DIARY_ENTRIES {
355            self.entries
356                .drain(0..self.entries.len() - MAX_DIARY_ENTRIES);
357        }
358        self.updated_at = Utc::now();
359    }
360
361    pub fn format_summary(&self) -> String {
362        if self.entries.is_empty() {
363            return format!("Diary [{}]: empty", self.agent_id);
364        }
365        let mut out = format!(
366            "Diary [{}] ({} entries):\n",
367            self.agent_id,
368            self.entries.len()
369        );
370        let now = Utc::now();
371        for e in self.entries.iter().rev().take(10) {
372            let age = (now - e.timestamp).num_minutes();
373            let prefix = match e.entry_type {
374                DiaryEntryType::Discovery => "FOUND",
375                DiaryEntryType::Decision => "DECIDED",
376                DiaryEntryType::Blocker => "BLOCKED",
377                DiaryEntryType::Progress => "DONE",
378                DiaryEntryType::Insight => "INSIGHT",
379            };
380            let ctx = e
381                .context
382                .as_deref()
383                .map(|c| format!(" [{c}]"))
384                .unwrap_or_default();
385            out.push_str(&format!("  [{prefix}] {}{ctx} ({age}m ago)\n", e.content));
386        }
387        out
388    }
389
390    pub fn format_compact(&self) -> String {
391        if self.entries.is_empty() {
392            return String::new();
393        }
394        let items: Vec<String> = self
395            .entries
396            .iter()
397            .rev()
398            .take(5)
399            .map(|e| {
400                let prefix = match e.entry_type {
401                    DiaryEntryType::Discovery => "F",
402                    DiaryEntryType::Decision => "D",
403                    DiaryEntryType::Blocker => "B",
404                    DiaryEntryType::Progress => "P",
405                    DiaryEntryType::Insight => "I",
406                };
407                format!("{prefix}:{}", truncate(&e.content, 50))
408            })
409            .collect();
410        format!("diary:{}|{}", self.agent_id, items.join("|"))
411    }
412
413    pub fn save(&self) -> Result<(), String> {
414        let dir = diary_dir()?;
415        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
416        let path = dir.join(format!("{}.json", sanitize_filename(&self.agent_id)));
417        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
418        std::fs::write(&path, json).map_err(|e| e.to_string())
419    }
420
421    pub fn load(agent_id: &str) -> Option<Self> {
422        let dir = diary_dir().ok()?;
423        let path = dir.join(format!("{}.json", sanitize_filename(agent_id)));
424        let content = std::fs::read_to_string(&path).ok()?;
425        serde_json::from_str(&content).ok()
426    }
427
428    pub fn load_or_create(agent_id: &str, agent_type: &str, project_root: &str) -> Self {
429        Self::load(agent_id).unwrap_or_else(|| Self::new(agent_id, agent_type, project_root))
430    }
431
432    pub fn list_all() -> Vec<(String, usize, DateTime<Utc>)> {
433        let Ok(dir) = diary_dir() else {
434            return Vec::new();
435        };
436        if !dir.exists() {
437            return Vec::new();
438        }
439        let mut results = Vec::new();
440        if let Ok(entries) = std::fs::read_dir(&dir) {
441            for entry in entries.flatten() {
442                if entry.path().extension().and_then(|e| e.to_str()) == Some("json")
443                    && let Ok(content) = std::fs::read_to_string(entry.path())
444                    && let Ok(diary) = serde_json::from_str::<AgentDiary>(&content)
445                {
446                    results.push((diary.agent_id, diary.entries.len(), diary.updated_at));
447                }
448            }
449        }
450        results.sort_by_key(|x| std::cmp::Reverse(x.2));
451        results
452    }
453
454    /// Load every diary whose `project_root` matches `project_root`, most
455    /// recently updated first. Used by skillify to mine a project's decisions
456    /// and insights across all its agents (#290).
457    pub fn load_all_for_project(project_root: &str) -> Vec<AgentDiary> {
458        let Ok(dir) = diary_dir() else {
459            return Vec::new();
460        };
461        if !dir.exists() {
462            return Vec::new();
463        }
464        let want = project_root.trim_end_matches('/');
465        let mut diaries: Vec<AgentDiary> = Vec::new();
466        if let Ok(entries) = std::fs::read_dir(&dir) {
467            for entry in entries.flatten() {
468                if entry.path().extension().and_then(|e| e.to_str()) != Some("json") {
469                    continue;
470                }
471                if let Ok(content) = std::fs::read_to_string(entry.path())
472                    && let Ok(diary) = serde_json::from_str::<AgentDiary>(&content)
473                    && diary.project_root.trim_end_matches('/') == want
474                {
475                    diaries.push(diary);
476                }
477            }
478        }
479        diaries.sort_by_key(|d| std::cmp::Reverse(d.updated_at));
480        diaries
481    }
482}
483
484impl std::fmt::Display for DiaryEntryType {
485    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
486        match self {
487            DiaryEntryType::Discovery => write!(f, "discovery"),
488            DiaryEntryType::Decision => write!(f, "decision"),
489            DiaryEntryType::Blocker => write!(f, "blocker"),
490            DiaryEntryType::Progress => write!(f, "progress"),
491            DiaryEntryType::Insight => write!(f, "insight"),
492        }
493    }
494}
495
496fn diary_dir() -> Result<PathBuf, String> {
497    let dir = crate::core::data_dir::lean_ctx_data_dir()?;
498    Ok(dir.join("agents").join("diaries"))
499}
500
501fn sanitize_filename(name: &str) -> String {
502    name.chars()
503        .map(|c| {
504            if c.is_alphanumeric() || c == '-' || c == '_' {
505                c
506            } else {
507                '_'
508            }
509        })
510        .collect()
511}
512
513fn truncate(s: &str, max: usize) -> String {
514    if s.len() <= max {
515        s.to_string()
516    } else {
517        format!("{}...", &s[..s.floor_char_boundary(max.saturating_sub(3))])
518    }
519}
520
521fn agents_dir() -> Result<PathBuf, String> {
522    let dir = crate::core::data_dir::lean_ctx_data_dir()?;
523    Ok(dir.join("agents"))
524}
525
526fn generate_short_id() -> String {
527    use std::collections::hash_map::DefaultHasher;
528    use std::hash::{Hash, Hasher};
529    use std::time::SystemTime;
530
531    let mut hasher = DefaultHasher::new();
532    SystemTime::now().hash(&mut hasher);
533    std::process::id().hash(&mut hasher);
534    format!("{:08x}", hasher.finish() as u32)
535}
536
537pub fn is_process_alive(pid: u32) -> bool {
538    #[cfg(unix)]
539    {
540        std::process::Command::new("kill")
541            .args(["-0", &pid.to_string()])
542            .output()
543            .is_ok_and(|o| o.status.success())
544    }
545    #[cfg(not(unix))]
546    {
547        let _ = pid;
548        true
549    }
550}
551
552pub(crate) struct FileLock {
553    path: PathBuf,
554}
555
556impl FileLock {
557    pub(crate) fn acquire(path: &std::path::Path) -> Result<Self, String> {
558        for _ in 0..50 {
559            if std::fs::OpenOptions::new()
560                .write(true)
561                .create_new(true)
562                .open(path)
563                .is_ok()
564            {
565                return Ok(Self {
566                    path: path.to_path_buf(),
567                });
568            }
569            if let Ok(metadata) = std::fs::metadata(path)
570                && let Ok(modified) = metadata.modified()
571                && modified.elapsed().unwrap_or_default().as_secs() > 5
572            {
573                let _ = std::fs::remove_file(path);
574                continue;
575            }
576            std::thread::sleep(std::time::Duration::from_millis(100));
577        }
578        Err("Could not acquire lock after 5 seconds".to_string())
579    }
580}
581
582impl Drop for FileLock {
583    fn drop(&mut self) {
584        let _ = std::fs::remove_file(&self.path);
585    }
586}
587
588#[derive(Debug, Clone, Serialize, Deserialize)]
589pub struct SharedFact {
590    pub from_agent: String,
591    pub category: String,
592    pub key: String,
593    pub value: String,
594    pub timestamp: DateTime<Utc>,
595    #[serde(default)]
596    pub received_by: Vec<String>,
597}
598
599impl AgentRegistry {
600    pub fn share_knowledge(&mut self, from: &str, category: &str, facts: &[(String, String)]) {
601        for (key, value) in facts {
602            self.scratchpad.push(ScratchpadEntry {
603                id: format!("knowledge-{}", chrono::Utc::now().timestamp_millis()),
604                from_agent: from.to_string(),
605                to_agent: None,
606                task_id: None,
607                category: category.to_string(),
608                priority: MessagePriority::default(),
609                privacy: PrivacyLevel::Team,
610                message: format!("[knowledge] {key}={value}"),
611                metadata: HashMap::new(),
612                project_root: None,
613                timestamp: Utc::now(),
614                read_by: Vec::new(),
615                expires_at: None,
616            });
617        }
618        let shared_path = Self::shared_knowledge_path();
619        let mut existing: Vec<SharedFact> = std::fs::read_to_string(&shared_path)
620            .ok()
621            .and_then(|s| serde_json::from_str(&s).ok())
622            .unwrap_or_default();
623
624        for (key, value) in facts {
625            existing.push(SharedFact {
626                from_agent: from.to_string(),
627                category: category.to_string(),
628                key: key.clone(),
629                value: value.clone(),
630                timestamp: Utc::now(),
631                received_by: Vec::new(),
632            });
633        }
634
635        if existing.len() > 500 {
636            existing.drain(..existing.len() - 500);
637        }
638        if let Ok(json) = serde_json::to_string_pretty(&existing) {
639            let _ = std::fs::write(&shared_path, json);
640        }
641    }
642
643    pub fn receive_shared_knowledge(&mut self, agent_id: &str) -> Vec<SharedFact> {
644        let shared_path = Self::shared_knowledge_path();
645        let mut all: Vec<SharedFact> = std::fs::read_to_string(&shared_path)
646            .ok()
647            .and_then(|s| serde_json::from_str(&s).ok())
648            .unwrap_or_default();
649
650        let mut new_facts = Vec::new();
651        for fact in &mut all {
652            if fact.from_agent != agent_id && !fact.received_by.contains(&agent_id.to_string()) {
653                fact.received_by.push(agent_id.to_string());
654                new_facts.push(fact.clone());
655            }
656        }
657
658        if !new_facts.is_empty()
659            && let Ok(json) = serde_json::to_string_pretty(&all)
660        {
661            let _ = std::fs::write(&shared_path, json);
662        }
663        new_facts
664    }
665
666    fn shared_knowledge_path() -> PathBuf {
667        // GH #439: route through the typed data resolver so a post-migration
668        // split install writes to $XDG_DATA_HOME, not a re-created ~/.lean-ctx.
669        crate::core::paths::data_dir()
670            .unwrap_or_else(|_| PathBuf::from("."))
671            .join("shared_knowledge.json")
672    }
673}
674
675#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
676#[serde(rename_all = "snake_case")]
677pub enum AgentRole {
678    Coder,
679    Reviewer,
680    Planner,
681    Explorer,
682    Debugger,
683    Tester,
684    Orchestrator,
685}
686
687impl AgentRole {
688    pub fn from_str_loose(s: &str) -> Self {
689        match s.to_lowercase().as_str() {
690            "review" | "reviewer" | "code_review" => Self::Reviewer,
691            "plan" | "planner" | "architect" => Self::Planner,
692            "explore" | "explorer" | "research" => Self::Explorer,
693            "debug" | "debugger" => Self::Debugger,
694            "test" | "tester" | "qa" => Self::Tester,
695            "orchestrator" | "coordinator" | "manager" => Self::Orchestrator,
696            _ => Self::Coder,
697        }
698    }
699}
700
701#[derive(Debug, Clone)]
702pub struct ContextDepthConfig {
703    pub max_files_full: usize,
704    pub max_files_signatures: usize,
705    pub preferred_mode: &'static str,
706    pub include_graph: bool,
707    pub include_knowledge: bool,
708    pub include_gotchas: bool,
709    pub context_budget_ratio: f64,
710}
711
712impl ContextDepthConfig {
713    pub fn for_role(role: AgentRole) -> Self {
714        match role {
715            AgentRole::Coder => Self {
716                max_files_full: 5,
717                max_files_signatures: 15,
718                preferred_mode: "full",
719                include_graph: true,
720                include_knowledge: true,
721                include_gotchas: true,
722                context_budget_ratio: 0.7,
723            },
724            AgentRole::Reviewer => Self {
725                max_files_full: 3,
726                max_files_signatures: 20,
727                preferred_mode: "signatures",
728                include_graph: true,
729                include_knowledge: true,
730                include_gotchas: true,
731                context_budget_ratio: 0.5,
732            },
733            AgentRole::Planner => Self {
734                max_files_full: 1,
735                max_files_signatures: 10,
736                preferred_mode: "map",
737                include_graph: true,
738                include_knowledge: true,
739                include_gotchas: false,
740                context_budget_ratio: 0.3,
741            },
742            AgentRole::Explorer => Self {
743                max_files_full: 2,
744                max_files_signatures: 8,
745                preferred_mode: "map",
746                include_graph: true,
747                include_knowledge: false,
748                include_gotchas: false,
749                context_budget_ratio: 0.4,
750            },
751            AgentRole::Debugger => Self {
752                max_files_full: 8,
753                max_files_signatures: 5,
754                preferred_mode: "full",
755                include_graph: false,
756                include_knowledge: true,
757                include_gotchas: true,
758                context_budget_ratio: 0.8,
759            },
760            AgentRole::Tester => Self {
761                max_files_full: 4,
762                max_files_signatures: 10,
763                preferred_mode: "full",
764                include_graph: false,
765                include_knowledge: false,
766                include_gotchas: true,
767                context_budget_ratio: 0.6,
768            },
769            AgentRole::Orchestrator => Self {
770                max_files_full: 0,
771                max_files_signatures: 5,
772                preferred_mode: "map",
773                include_graph: true,
774                include_knowledge: true,
775                include_gotchas: false,
776                context_budget_ratio: 0.2,
777            },
778        }
779    }
780
781    pub fn mode_for_rank(&self, rank: usize) -> &'static str {
782        if rank < self.max_files_full {
783            "full"
784        } else if rank < self.max_files_full + self.max_files_signatures {
785            "signatures"
786        } else {
787            "map"
788        }
789    }
790}
791
792impl From<ScratchpadEntry> for A2AMessage {
793    fn from(entry: ScratchpadEntry) -> Self {
794        Self {
795            id: entry.id,
796            from_agent: entry.from_agent,
797            to_agent: entry.to_agent,
798            task_id: entry.task_id,
799            category: MessageCategory::parse_str(&entry.category),
800            priority: entry.priority,
801            privacy: entry.privacy,
802            content: entry.message,
803            metadata: entry.metadata,
804            project_root: entry.project_root,
805            timestamp: entry.timestamp,
806            read_by: entry.read_by,
807            expires_at: entry.expires_at,
808        }
809    }
810}
811
812impl From<A2AMessage> for ScratchpadEntry {
813    fn from(msg: A2AMessage) -> Self {
814        Self {
815            id: msg.id,
816            from_agent: msg.from_agent,
817            to_agent: msg.to_agent,
818            task_id: msg.task_id,
819            category: msg.category.to_string(),
820            priority: msg.priority,
821            privacy: msg.privacy,
822            message: msg.content,
823            metadata: msg.metadata,
824            project_root: msg.project_root,
825            timestamp: msg.timestamp,
826            read_by: msg.read_by,
827            expires_at: msg.expires_at,
828        }
829    }
830}
831
832#[cfg(test)]
833mod tests {
834    use super::*;
835
836    #[test]
837    fn register_and_list() {
838        let mut reg = AgentRegistry::new();
839        let id = reg.register("cursor", Some("dev"), "/tmp/project");
840        assert!(!id.is_empty());
841        assert_eq!(reg.list_active(None).len(), 1);
842        assert_eq!(reg.list_active(None)[0].agent_type, "cursor");
843    }
844
845    #[test]
846    fn reregister_same_pid() {
847        let mut reg = AgentRegistry::new();
848        let id1 = reg.register("cursor", Some("dev"), "/tmp/project");
849        let id2 = reg.register("cursor", Some("review"), "/tmp/project");
850        assert_eq!(id1, id2);
851        assert_eq!(reg.agents.len(), 1);
852        assert_eq!(reg.agents[0].role, Some("review".to_string()));
853    }
854
855    #[test]
856    fn post_and_read_messages() {
857        let mut reg = AgentRegistry::new();
858        reg.post_message("agent-a", None, "finding", "Found a bug in auth.rs");
859        reg.post_message("agent-b", Some("agent-a"), "request", "Please review");
860
861        let msgs = reg.read_unread("agent-a");
862        assert_eq!(msgs.len(), 1);
863        assert_eq!(msgs[0].category, "request");
864    }
865
866    #[test]
867    fn set_status() {
868        let mut reg = AgentRegistry::new();
869        let id = reg.register("claude", None, "/tmp/project");
870        reg.set_status(&id, AgentStatus::Idle, Some("waiting for review"));
871        assert_eq!(reg.agents[0].status, AgentStatus::Idle);
872        assert_eq!(
873            reg.agents[0].status_message,
874            Some("waiting for review".to_string())
875        );
876    }
877
878    #[test]
879    fn broadcast_message() {
880        let mut reg = AgentRegistry::new();
881        reg.post_message("agent-a", None, "status", "Starting refactor");
882
883        let msgs_b = reg.read_unread("agent-b");
884        assert_eq!(msgs_b.len(), 1);
885        assert_eq!(msgs_b[0].message, "Starting refactor");
886
887        let msgs_a = reg.read_unread("agent-a");
888        assert!(msgs_a.is_empty());
889    }
890
891    #[test]
892    fn diary_add_and_format() {
893        let mut diary = AgentDiary::new("test-agent-001", "cursor", "/tmp/project");
894        diary.add_entry(
895            DiaryEntryType::Discovery,
896            "Found auth module at src/auth.rs",
897            Some("auth"),
898        );
899        diary.add_entry(
900            DiaryEntryType::Decision,
901            "Use JWT RS256 for token signing",
902            None,
903        );
904        diary.add_entry(
905            DiaryEntryType::Progress,
906            "Implemented login endpoint",
907            Some("auth"),
908        );
909
910        assert_eq!(diary.entries.len(), 3);
911
912        let summary = diary.format_summary();
913        assert!(summary.contains("test-agent-001"));
914        assert!(summary.contains("FOUND"));
915        assert!(summary.contains("DECIDED"));
916        assert!(summary.contains("DONE"));
917    }
918
919    #[test]
920    fn diary_compact_format() {
921        let mut diary = AgentDiary::new("test-agent-002", "claude", "/tmp/project");
922        diary.add_entry(DiaryEntryType::Insight, "DB queries are N+1", None);
923        diary.add_entry(
924            DiaryEntryType::Blocker,
925            "Missing API credentials",
926            Some("deploy"),
927        );
928
929        let compact = diary.format_compact();
930        assert!(compact.contains("diary:test-agent-002"));
931        assert!(compact.contains("B:Missing API credentials"));
932        assert!(compact.contains("I:DB queries are N+1"));
933    }
934
935    #[test]
936    fn diary_entry_types() {
937        let types = vec![
938            DiaryEntryType::Discovery,
939            DiaryEntryType::Decision,
940            DiaryEntryType::Blocker,
941            DiaryEntryType::Progress,
942            DiaryEntryType::Insight,
943        ];
944        for t in types {
945            assert!(!format!("{t}").is_empty());
946        }
947    }
948
949    #[test]
950    fn diary_truncation() {
951        let mut diary = AgentDiary::new("test-agent", "cursor", "/tmp");
952        for i in 0..150 {
953            diary.add_entry(DiaryEntryType::Progress, &format!("Step {i}"), None);
954        }
955        assert!(diary.entries.len() <= 100);
956    }
957
958    #[test]
959    fn truncate_utf8_emoji_no_panic() {
960        let result = truncate("Agent 🤖 Name ist lang genug", 15);
961        assert!(result.ends_with("..."));
962    }
963
964    #[test]
965    fn truncate_utf8_cyrillic_no_panic() {
966        let result = truncate("агент выполняет длинную задачу", 15);
967        assert!(result.ends_with("..."));
968    }
969
970    #[test]
971    fn truncate_short_utf8_unchanged() {
972        assert_eq!(truncate("短い", 20), "短い");
973    }
974
975    fn test_entry(agent_id: &str, project_root: &str, pid: u32) -> AgentEntry {
976        let now = Utc::now();
977        AgentEntry {
978            agent_id: agent_id.to_string(),
979            agent_type: "cursor".to_string(),
980            role: Some("dev".to_string()),
981            project_root: project_root.to_string(),
982            started_at: now,
983            last_active: now,
984            pid,
985            status: AgentStatus::Active,
986            status_message: None,
987        }
988    }
989
990    /// #419: the wake-up briefing scopes agents to the current project via
991    /// `list_active(Some(root))`. Peers working on *other* projects must never
992    /// leak into the briefing.
993    #[test]
994    fn list_active_scopes_to_project_root() {
995        let mut reg = AgentRegistry::new();
996        reg.agents
997            .push(test_entry("a-1", "/proj/a", std::process::id()));
998        reg.agents
999            .push(test_entry("b-1", "/proj/b", std::process::id()));
1000
1001        let active_a = reg.list_active(Some("/proj/a"));
1002        assert_eq!(active_a.len(), 1);
1003        assert_eq!(active_a[0].agent_id, "a-1");
1004
1005        // Unscoped still sees both.
1006        assert_eq!(reg.list_active(None).len(), 2);
1007    }
1008
1009    /// #419: a crashed/exited MCP process leaves an `Active` entry behind.
1010    /// `cleanup_stale` must flip it to `Finished` (regardless of age) so
1011    /// `list_active` no longer surfaces it as a live peer — the ghost the
1012    /// briefing used to show.
1013    #[cfg(unix)]
1014    #[test]
1015    fn cleanup_stale_prunes_dead_pid_from_active_list() {
1016        // Reap a child so its PID is guaranteed dead at assertion time.
1017        let reaped = {
1018            let mut child = std::process::Command::new("true")
1019                .spawn()
1020                .expect("spawn true");
1021            let pid = child.id();
1022            child.wait().expect("reap true");
1023            pid
1024        };
1025
1026        let mut reg = AgentRegistry::new();
1027        reg.agents.push(test_entry("ghost", "/proj/a", reaped));
1028        reg.agents
1029            .push(test_entry("live", "/proj/a", std::process::id()));
1030
1031        reg.cleanup_stale(24);
1032
1033        let ids: Vec<&str> = reg
1034            .list_active(Some("/proj/a"))
1035            .iter()
1036            .map(|a| a.agent_id.as_str())
1037            .collect();
1038        assert!(ids.contains(&"live"), "live same-project agent must remain");
1039        assert!(
1040            !ids.contains(&"ghost"),
1041            "dead-pid agent must be pruned from the active list (#419)"
1042        );
1043    }
1044}