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
537/// #576 already fixed this exact hardcoded-`true` anti-pattern for
538/// `daemon::is_daemon_running` by delegating to `ipc::process::is_alive`
539/// (which has a real Windows `OpenProcess` check); this duplicate copy was
540/// missed, so on non-unix targets `cleanup_stale` could never flip a dead
541/// MCP session's entry to `Finished`, leaving `registry.json` accumulating
542/// stale `Active` entries forever — the root cause of the "N active agents"
543/// dashboard bug on Windows.
544pub fn is_process_alive(pid: u32) -> bool {
545    crate::ipc::process::is_alive(pid)
546}
547
548pub(crate) struct FileLock {
549    path: PathBuf,
550}
551
552impl FileLock {
553    pub(crate) fn acquire(path: &std::path::Path) -> Result<Self, String> {
554        for _ in 0..50 {
555            if std::fs::OpenOptions::new()
556                .write(true)
557                .create_new(true)
558                .open(path)
559                .is_ok()
560            {
561                return Ok(Self {
562                    path: path.to_path_buf(),
563                });
564            }
565            if let Ok(metadata) = std::fs::metadata(path)
566                && let Ok(modified) = metadata.modified()
567                && modified.elapsed().unwrap_or_default().as_secs() > 5
568            {
569                let _ = std::fs::remove_file(path);
570                continue;
571            }
572            std::thread::sleep(std::time::Duration::from_millis(100));
573        }
574        Err("Could not acquire lock after 5 seconds".to_string())
575    }
576}
577
578impl Drop for FileLock {
579    fn drop(&mut self) {
580        let _ = std::fs::remove_file(&self.path);
581    }
582}
583
584#[derive(Debug, Clone, Serialize, Deserialize)]
585pub struct SharedFact {
586    pub from_agent: String,
587    pub category: String,
588    pub key: String,
589    pub value: String,
590    pub timestamp: DateTime<Utc>,
591    #[serde(default)]
592    pub received_by: Vec<String>,
593}
594
595impl AgentRegistry {
596    pub fn share_knowledge(&mut self, from: &str, category: &str, facts: &[(String, String)]) {
597        for (key, value) in facts {
598            self.scratchpad.push(ScratchpadEntry {
599                id: format!("knowledge-{}", chrono::Utc::now().timestamp_millis()),
600                from_agent: from.to_string(),
601                to_agent: None,
602                task_id: None,
603                category: category.to_string(),
604                priority: MessagePriority::default(),
605                privacy: PrivacyLevel::Team,
606                message: format!("[knowledge] {key}={value}"),
607                metadata: HashMap::new(),
608                project_root: None,
609                timestamp: Utc::now(),
610                read_by: Vec::new(),
611                expires_at: None,
612            });
613        }
614        let shared_path = Self::shared_knowledge_path();
615        let mut existing: Vec<SharedFact> = std::fs::read_to_string(&shared_path)
616            .ok()
617            .and_then(|s| serde_json::from_str(&s).ok())
618            .unwrap_or_default();
619
620        for (key, value) in facts {
621            existing.push(SharedFact {
622                from_agent: from.to_string(),
623                category: category.to_string(),
624                key: key.clone(),
625                value: value.clone(),
626                timestamp: Utc::now(),
627                received_by: Vec::new(),
628            });
629        }
630
631        if existing.len() > 500 {
632            existing.drain(..existing.len() - 500);
633        }
634        if let Ok(json) = serde_json::to_string_pretty(&existing) {
635            let _ = std::fs::write(&shared_path, json);
636        }
637    }
638
639    pub fn receive_shared_knowledge(&mut self, agent_id: &str) -> Vec<SharedFact> {
640        let shared_path = Self::shared_knowledge_path();
641        let mut all: Vec<SharedFact> = std::fs::read_to_string(&shared_path)
642            .ok()
643            .and_then(|s| serde_json::from_str(&s).ok())
644            .unwrap_or_default();
645
646        let mut new_facts = Vec::new();
647        for fact in &mut all {
648            if fact.from_agent != agent_id && !fact.received_by.contains(&agent_id.to_string()) {
649                fact.received_by.push(agent_id.to_string());
650                new_facts.push(fact.clone());
651            }
652        }
653
654        if !new_facts.is_empty()
655            && let Ok(json) = serde_json::to_string_pretty(&all)
656        {
657            let _ = std::fs::write(&shared_path, json);
658        }
659        new_facts
660    }
661
662    fn shared_knowledge_path() -> PathBuf {
663        // GH #439: route through the typed data resolver so a post-migration
664        // split install writes to $XDG_DATA_HOME, not a re-created ~/.lean-ctx.
665        crate::core::paths::data_dir()
666            .unwrap_or_else(|_| PathBuf::from("."))
667            .join("shared_knowledge.json")
668    }
669}
670
671#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
672#[serde(rename_all = "snake_case")]
673pub enum AgentRole {
674    Coder,
675    Reviewer,
676    Planner,
677    Explorer,
678    Debugger,
679    Tester,
680    Orchestrator,
681}
682
683impl AgentRole {
684    pub fn from_str_loose(s: &str) -> Self {
685        match s.to_lowercase().as_str() {
686            "review" | "reviewer" | "code_review" => Self::Reviewer,
687            "plan" | "planner" | "architect" => Self::Planner,
688            "explore" | "explorer" | "research" => Self::Explorer,
689            "debug" | "debugger" => Self::Debugger,
690            "test" | "tester" | "qa" => Self::Tester,
691            "orchestrator" | "coordinator" | "manager" => Self::Orchestrator,
692            _ => Self::Coder,
693        }
694    }
695}
696
697#[derive(Debug, Clone)]
698pub struct ContextDepthConfig {
699    pub max_files_full: usize,
700    pub max_files_signatures: usize,
701    pub preferred_mode: &'static str,
702    pub include_graph: bool,
703    pub include_knowledge: bool,
704    pub include_gotchas: bool,
705    pub context_budget_ratio: f64,
706}
707
708impl ContextDepthConfig {
709    pub fn for_role(role: AgentRole) -> Self {
710        match role {
711            AgentRole::Coder => Self {
712                max_files_full: 5,
713                max_files_signatures: 15,
714                preferred_mode: "full",
715                include_graph: true,
716                include_knowledge: true,
717                include_gotchas: true,
718                context_budget_ratio: 0.7,
719            },
720            AgentRole::Reviewer => Self {
721                max_files_full: 3,
722                max_files_signatures: 20,
723                preferred_mode: "signatures",
724                include_graph: true,
725                include_knowledge: true,
726                include_gotchas: true,
727                context_budget_ratio: 0.5,
728            },
729            AgentRole::Planner => Self {
730                max_files_full: 1,
731                max_files_signatures: 10,
732                preferred_mode: "map",
733                include_graph: true,
734                include_knowledge: true,
735                include_gotchas: false,
736                context_budget_ratio: 0.3,
737            },
738            AgentRole::Explorer => Self {
739                max_files_full: 2,
740                max_files_signatures: 8,
741                preferred_mode: "map",
742                include_graph: true,
743                include_knowledge: false,
744                include_gotchas: false,
745                context_budget_ratio: 0.4,
746            },
747            AgentRole::Debugger => Self {
748                max_files_full: 8,
749                max_files_signatures: 5,
750                preferred_mode: "full",
751                include_graph: false,
752                include_knowledge: true,
753                include_gotchas: true,
754                context_budget_ratio: 0.8,
755            },
756            AgentRole::Tester => Self {
757                max_files_full: 4,
758                max_files_signatures: 10,
759                preferred_mode: "full",
760                include_graph: false,
761                include_knowledge: false,
762                include_gotchas: true,
763                context_budget_ratio: 0.6,
764            },
765            AgentRole::Orchestrator => Self {
766                max_files_full: 0,
767                max_files_signatures: 5,
768                preferred_mode: "map",
769                include_graph: true,
770                include_knowledge: true,
771                include_gotchas: false,
772                context_budget_ratio: 0.2,
773            },
774        }
775    }
776
777    pub fn mode_for_rank(&self, rank: usize) -> &'static str {
778        if rank < self.max_files_full {
779            "full"
780        } else if rank < self.max_files_full + self.max_files_signatures {
781            "signatures"
782        } else {
783            "map"
784        }
785    }
786}
787
788impl From<ScratchpadEntry> for A2AMessage {
789    fn from(entry: ScratchpadEntry) -> Self {
790        Self {
791            id: entry.id,
792            from_agent: entry.from_agent,
793            to_agent: entry.to_agent,
794            task_id: entry.task_id,
795            category: MessageCategory::parse_str(&entry.category),
796            priority: entry.priority,
797            privacy: entry.privacy,
798            content: entry.message,
799            metadata: entry.metadata,
800            project_root: entry.project_root,
801            timestamp: entry.timestamp,
802            read_by: entry.read_by,
803            expires_at: entry.expires_at,
804        }
805    }
806}
807
808impl From<A2AMessage> for ScratchpadEntry {
809    fn from(msg: A2AMessage) -> Self {
810        Self {
811            id: msg.id,
812            from_agent: msg.from_agent,
813            to_agent: msg.to_agent,
814            task_id: msg.task_id,
815            category: msg.category.to_string(),
816            priority: msg.priority,
817            privacy: msg.privacy,
818            message: msg.content,
819            metadata: msg.metadata,
820            project_root: msg.project_root,
821            timestamp: msg.timestamp,
822            read_by: msg.read_by,
823            expires_at: msg.expires_at,
824        }
825    }
826}
827
828#[cfg(test)]
829mod tests {
830    use super::*;
831
832    #[test]
833    fn register_and_list() {
834        let mut reg = AgentRegistry::new();
835        let id = reg.register("cursor", Some("dev"), "/tmp/project");
836        assert!(!id.is_empty());
837        assert_eq!(reg.list_active(None).len(), 1);
838        assert_eq!(reg.list_active(None)[0].agent_type, "cursor");
839    }
840
841    #[test]
842    fn reregister_same_pid() {
843        let mut reg = AgentRegistry::new();
844        let id1 = reg.register("cursor", Some("dev"), "/tmp/project");
845        let id2 = reg.register("cursor", Some("review"), "/tmp/project");
846        assert_eq!(id1, id2);
847        assert_eq!(reg.agents.len(), 1);
848        assert_eq!(reg.agents[0].role, Some("review".to_string()));
849    }
850
851    #[test]
852    fn post_and_read_messages() {
853        let mut reg = AgentRegistry::new();
854        reg.post_message("agent-a", None, "finding", "Found a bug in auth.rs");
855        reg.post_message("agent-b", Some("agent-a"), "request", "Please review");
856
857        let msgs = reg.read_unread("agent-a");
858        assert_eq!(msgs.len(), 1);
859        assert_eq!(msgs[0].category, "request");
860    }
861
862    #[test]
863    fn set_status() {
864        let mut reg = AgentRegistry::new();
865        let id = reg.register("claude", None, "/tmp/project");
866        reg.set_status(&id, AgentStatus::Idle, Some("waiting for review"));
867        assert_eq!(reg.agents[0].status, AgentStatus::Idle);
868        assert_eq!(
869            reg.agents[0].status_message,
870            Some("waiting for review".to_string())
871        );
872    }
873
874    #[test]
875    fn broadcast_message() {
876        let mut reg = AgentRegistry::new();
877        reg.post_message("agent-a", None, "status", "Starting refactor");
878
879        let msgs_b = reg.read_unread("agent-b");
880        assert_eq!(msgs_b.len(), 1);
881        assert_eq!(msgs_b[0].message, "Starting refactor");
882
883        let msgs_a = reg.read_unread("agent-a");
884        assert!(msgs_a.is_empty());
885    }
886
887    #[test]
888    fn diary_add_and_format() {
889        let mut diary = AgentDiary::new("test-agent-001", "cursor", "/tmp/project");
890        diary.add_entry(
891            DiaryEntryType::Discovery,
892            "Found auth module at src/auth.rs",
893            Some("auth"),
894        );
895        diary.add_entry(
896            DiaryEntryType::Decision,
897            "Use JWT RS256 for token signing",
898            None,
899        );
900        diary.add_entry(
901            DiaryEntryType::Progress,
902            "Implemented login endpoint",
903            Some("auth"),
904        );
905
906        assert_eq!(diary.entries.len(), 3);
907
908        let summary = diary.format_summary();
909        assert!(summary.contains("test-agent-001"));
910        assert!(summary.contains("FOUND"));
911        assert!(summary.contains("DECIDED"));
912        assert!(summary.contains("DONE"));
913    }
914
915    #[test]
916    fn diary_compact_format() {
917        let mut diary = AgentDiary::new("test-agent-002", "claude", "/tmp/project");
918        diary.add_entry(DiaryEntryType::Insight, "DB queries are N+1", None);
919        diary.add_entry(
920            DiaryEntryType::Blocker,
921            "Missing API credentials",
922            Some("deploy"),
923        );
924
925        let compact = diary.format_compact();
926        assert!(compact.contains("diary:test-agent-002"));
927        assert!(compact.contains("B:Missing API credentials"));
928        assert!(compact.contains("I:DB queries are N+1"));
929    }
930
931    #[test]
932    fn diary_entry_types() {
933        let types = vec![
934            DiaryEntryType::Discovery,
935            DiaryEntryType::Decision,
936            DiaryEntryType::Blocker,
937            DiaryEntryType::Progress,
938            DiaryEntryType::Insight,
939        ];
940        for t in types {
941            assert!(!format!("{t}").is_empty());
942        }
943    }
944
945    #[test]
946    fn diary_truncation() {
947        let mut diary = AgentDiary::new("test-agent", "cursor", "/tmp");
948        for i in 0..150 {
949            diary.add_entry(DiaryEntryType::Progress, &format!("Step {i}"), None);
950        }
951        assert!(diary.entries.len() <= 100);
952    }
953
954    #[test]
955    fn truncate_utf8_emoji_no_panic() {
956        let result = truncate("Agent 🤖 Name ist lang genug", 15);
957        assert!(result.ends_with("..."));
958    }
959
960    #[test]
961    fn truncate_utf8_cyrillic_no_panic() {
962        let result = truncate("агент выполняет длинную задачу", 15);
963        assert!(result.ends_with("..."));
964    }
965
966    #[test]
967    fn truncate_short_utf8_unchanged() {
968        assert_eq!(truncate("短い", 20), "短い");
969    }
970
971    fn test_entry(agent_id: &str, project_root: &str, pid: u32) -> AgentEntry {
972        let now = Utc::now();
973        AgentEntry {
974            agent_id: agent_id.to_string(),
975            agent_type: "cursor".to_string(),
976            role: Some("dev".to_string()),
977            project_root: project_root.to_string(),
978            started_at: now,
979            last_active: now,
980            pid,
981            status: AgentStatus::Active,
982            status_message: None,
983        }
984    }
985
986    /// #419: the wake-up briefing scopes agents to the current project via
987    /// `list_active(Some(root))`. Peers working on *other* projects must never
988    /// leak into the briefing.
989    #[test]
990    fn list_active_scopes_to_project_root() {
991        let mut reg = AgentRegistry::new();
992        reg.agents
993            .push(test_entry("a-1", "/proj/a", std::process::id()));
994        reg.agents
995            .push(test_entry("b-1", "/proj/b", std::process::id()));
996
997        let active_a = reg.list_active(Some("/proj/a"));
998        assert_eq!(active_a.len(), 1);
999        assert_eq!(active_a[0].agent_id, "a-1");
1000
1001        // Unscoped still sees both.
1002        assert_eq!(reg.list_active(None).len(), 2);
1003    }
1004
1005    /// #419: a crashed/exited MCP process leaves an `Active` entry behind.
1006    /// `cleanup_stale` must flip it to `Finished` (regardless of age) so
1007    /// `list_active` no longer surfaces it as a live peer — the ghost the
1008    /// briefing used to show. Previously `#[cfg(unix)]`-only, which is why
1009    /// the non-unix `is_process_alive` hardcoded-`true` regression (see its
1010    /// doc comment) shipped unnoticed: this exact test never ran on Windows.
1011    #[test]
1012    fn cleanup_stale_prunes_dead_pid_from_active_list() {
1013        // Reap a child so its PID is guaranteed dead at assertion time.
1014        let reaped = {
1015            let mut cmd = if cfg!(windows) {
1016                let mut c = std::process::Command::new("cmd");
1017                c.args(["/C", "exit"]);
1018                c
1019            } else {
1020                std::process::Command::new("true")
1021            };
1022            let mut child = cmd.spawn().expect("spawn short-lived helper process");
1023            let pid = child.id();
1024            child.wait().expect("reap helper process");
1025            pid
1026        };
1027
1028        let mut reg = AgentRegistry::new();
1029        reg.agents.push(test_entry("ghost", "/proj/a", reaped));
1030        reg.agents
1031            .push(test_entry("live", "/proj/a", std::process::id()));
1032
1033        reg.cleanup_stale(24);
1034
1035        let ids: Vec<&str> = reg
1036            .list_active(Some("/proj/a"))
1037            .iter()
1038            .map(|a| a.agent_id.as_str())
1039            .collect();
1040        assert!(ids.contains(&"live"), "live same-project agent must remain");
1041        assert!(
1042            !ids.contains(&"ghost"),
1043            "dead-pid agent must be pruned from the active list (#419)"
1044        );
1045    }
1046}