1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use std::path::PathBuf;
4
5const MAX_SCRATCHPAD_ENTRIES: usize = 200;
6const MAX_DIARY_ENTRIES: usize = 100;
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct AgentRegistry {
10 pub agents: Vec<AgentEntry>,
11 pub scratchpad: Vec<ScratchpadEntry>,
12 pub updated_at: DateTime<Utc>,
13}
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct AgentDiary {
17 pub agent_id: String,
18 pub agent_type: String,
19 pub project_root: String,
20 pub entries: Vec<DiaryEntry>,
21 pub created_at: DateTime<Utc>,
22 pub updated_at: DateTime<Utc>,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize)]
26pub struct DiaryEntry {
27 pub entry_type: DiaryEntryType,
28 pub content: String,
29 pub context: Option<String>,
30 pub timestamp: DateTime<Utc>,
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
34pub enum DiaryEntryType {
35 Discovery,
36 Decision,
37 Blocker,
38 Progress,
39 Insight,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct AgentEntry {
44 pub agent_id: String,
45 pub agent_type: String,
46 pub role: Option<String>,
47 pub project_root: String,
48 pub started_at: DateTime<Utc>,
49 pub last_active: DateTime<Utc>,
50 pub pid: u32,
51 pub status: AgentStatus,
52 pub status_message: Option<String>,
53}
54
55#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
56pub enum AgentStatus {
57 Active,
58 Idle,
59 Finished,
60}
61
62impl std::fmt::Display for AgentStatus {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 match self {
65 AgentStatus::Active => write!(f, "active"),
66 AgentStatus::Idle => write!(f, "idle"),
67 AgentStatus::Finished => write!(f, "finished"),
68 }
69 }
70}
71
72#[derive(Debug, Clone, Serialize, Deserialize)]
73pub struct ScratchpadEntry {
74 pub id: String,
75 pub from_agent: String,
76 pub to_agent: Option<String>,
77 pub category: String,
78 pub message: String,
79 pub timestamp: DateTime<Utc>,
80 pub read_by: Vec<String>,
81}
82
83impl AgentRegistry {
84 pub fn new() -> Self {
85 Self {
86 agents: Vec::new(),
87 scratchpad: Vec::new(),
88 updated_at: Utc::now(),
89 }
90 }
91
92 pub fn register(&mut self, agent_type: &str, role: Option<&str>, project_root: &str) -> String {
93 let pid = std::process::id();
94 let agent_id = format!("{}-{}-{}", agent_type, pid, &generate_short_id());
95
96 if let Some(existing) = self.agents.iter_mut().find(|a| a.pid == pid) {
97 existing.last_active = Utc::now();
98 existing.status = AgentStatus::Active;
99 if let Some(r) = role {
100 existing.role = Some(r.to_string());
101 }
102 return existing.agent_id.clone();
103 }
104
105 self.agents.push(AgentEntry {
106 agent_id: agent_id.clone(),
107 agent_type: agent_type.to_string(),
108 role: role.map(std::string::ToString::to_string),
109 project_root: project_root.to_string(),
110 started_at: Utc::now(),
111 last_active: Utc::now(),
112 pid,
113 status: AgentStatus::Active,
114 status_message: None,
115 });
116
117 self.updated_at = Utc::now();
118 crate::core::events::emit_agent_action(&agent_id, "register", None);
119 agent_id
120 }
121
122 pub fn update_heartbeat(&mut self, agent_id: &str) {
123 if let Some(agent) = self.agents.iter_mut().find(|a| a.agent_id == agent_id) {
124 agent.last_active = Utc::now();
125 }
126 }
127
128 pub fn set_status(&mut self, agent_id: &str, status: AgentStatus, message: Option<&str>) {
129 if let Some(agent) = self.agents.iter_mut().find(|a| a.agent_id == agent_id) {
130 agent.status = status;
131 agent.status_message = message.map(std::string::ToString::to_string);
132 agent.last_active = Utc::now();
133 }
134 self.updated_at = Utc::now();
135 }
136
137 pub fn list_active(&self, project_root: Option<&str>) -> Vec<&AgentEntry> {
138 self.agents
139 .iter()
140 .filter(|a| {
141 if let Some(root) = project_root {
142 a.project_root == root && a.status != AgentStatus::Finished
143 } else {
144 a.status != AgentStatus::Finished
145 }
146 })
147 .collect()
148 }
149
150 pub fn list_all(&self) -> &[AgentEntry] {
151 &self.agents
152 }
153
154 pub fn post_message(
155 &mut self,
156 from_agent: &str,
157 to_agent: Option<&str>,
158 category: &str,
159 message: &str,
160 ) -> String {
161 let id = generate_short_id();
162 self.scratchpad.push(ScratchpadEntry {
163 id: id.clone(),
164 from_agent: from_agent.to_string(),
165 to_agent: to_agent.map(std::string::ToString::to_string),
166 category: category.to_string(),
167 message: message.to_string(),
168 timestamp: Utc::now(),
169 read_by: vec![from_agent.to_string()],
170 });
171
172 if self.scratchpad.len() > MAX_SCRATCHPAD_ENTRIES {
173 self.scratchpad
174 .drain(0..self.scratchpad.len() - MAX_SCRATCHPAD_ENTRIES);
175 }
176
177 self.updated_at = Utc::now();
178 id
179 }
180
181 pub fn read_messages(&mut self, agent_id: &str) -> Vec<&ScratchpadEntry> {
182 let unread: Vec<usize> = self
183 .scratchpad
184 .iter()
185 .enumerate()
186 .filter(|(_, e)| {
187 !e.read_by.contains(&agent_id.to_string())
188 && (e.to_agent.is_none() || e.to_agent.as_deref() == Some(agent_id))
189 })
190 .map(|(i, _)| i)
191 .collect();
192
193 for i in &unread {
194 self.scratchpad[*i].read_by.push(agent_id.to_string());
195 }
196
197 self.scratchpad
198 .iter()
199 .filter(|e| e.to_agent.is_none() || e.to_agent.as_deref() == Some(agent_id))
200 .filter(|e| e.from_agent != agent_id)
201 .collect()
202 }
203
204 pub fn read_unread(&mut self, agent_id: &str) -> Vec<&ScratchpadEntry> {
205 let unread_indices: Vec<usize> = self
206 .scratchpad
207 .iter()
208 .enumerate()
209 .filter(|(_, e)| {
210 !e.read_by.contains(&agent_id.to_string())
211 && e.from_agent != agent_id
212 && (e.to_agent.is_none() || e.to_agent.as_deref() == Some(agent_id))
213 })
214 .map(|(i, _)| i)
215 .collect();
216
217 for i in &unread_indices {
218 self.scratchpad[*i].read_by.push(agent_id.to_string());
219 }
220
221 self.updated_at = Utc::now();
222
223 self.scratchpad
224 .iter()
225 .filter(|e| {
226 e.from_agent != agent_id
227 && (e.to_agent.is_none() || e.to_agent.as_deref() == Some(agent_id))
228 && e.read_by.contains(&agent_id.to_string())
229 && e.read_by.iter().filter(|r| *r == agent_id).count() == 1
230 })
231 .collect()
232 }
233
234 pub fn cleanup_stale(&mut self, max_age_hours: u64) {
235 let cutoff = Utc::now() - chrono::Duration::hours(max_age_hours as i64);
236
237 for agent in &mut self.agents {
238 if agent.last_active < cutoff
239 && agent.status != AgentStatus::Finished
240 && !is_process_alive(agent.pid)
241 {
242 agent.status = AgentStatus::Finished;
243 }
244 }
245
246 self.agents
247 .retain(|a| !(a.status == AgentStatus::Finished && a.last_active < cutoff));
248
249 self.updated_at = Utc::now();
250 }
251
252 pub fn save(&self) -> Result<(), String> {
253 let dir = agents_dir()?;
254 std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
255
256 let path = dir.join("registry.json");
257 let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
258
259 let lock_path = dir.join("registry.lock");
260 let _lock = FileLock::acquire(&lock_path)?;
261
262 std::fs::write(&path, json).map_err(|e| e.to_string())
263 }
264
265 pub fn load() -> Option<Self> {
266 let dir = agents_dir().ok()?;
267 let path = dir.join("registry.json");
268 let content = std::fs::read_to_string(&path).ok()?;
269 serde_json::from_str(&content).ok()
270 }
271
272 pub fn load_or_create() -> Self {
273 Self::load().unwrap_or_default()
274 }
275}
276
277impl Default for AgentRegistry {
278 fn default() -> Self {
279 Self::new()
280 }
281}
282
283impl AgentDiary {
284 pub fn new(agent_id: &str, agent_type: &str, project_root: &str) -> Self {
285 let now = Utc::now();
286 Self {
287 agent_id: agent_id.to_string(),
288 agent_type: agent_type.to_string(),
289 project_root: project_root.to_string(),
290 entries: Vec::new(),
291 created_at: now,
292 updated_at: now,
293 }
294 }
295
296 pub fn add_entry(&mut self, entry_type: DiaryEntryType, content: &str, context: Option<&str>) {
297 self.entries.push(DiaryEntry {
298 entry_type,
299 content: content.to_string(),
300 context: context.map(std::string::ToString::to_string),
301 timestamp: Utc::now(),
302 });
303 if self.entries.len() > MAX_DIARY_ENTRIES {
304 self.entries
305 .drain(0..self.entries.len() - MAX_DIARY_ENTRIES);
306 }
307 self.updated_at = Utc::now();
308 }
309
310 pub fn format_summary(&self) -> String {
311 if self.entries.is_empty() {
312 return format!("Diary [{}]: empty", self.agent_id);
313 }
314 let mut out = format!(
315 "Diary [{}] ({} entries):\n",
316 self.agent_id,
317 self.entries.len()
318 );
319 for e in self.entries.iter().rev().take(10) {
320 let age = (Utc::now() - e.timestamp).num_minutes();
321 let prefix = match e.entry_type {
322 DiaryEntryType::Discovery => "FOUND",
323 DiaryEntryType::Decision => "DECIDED",
324 DiaryEntryType::Blocker => "BLOCKED",
325 DiaryEntryType::Progress => "DONE",
326 DiaryEntryType::Insight => "INSIGHT",
327 };
328 let ctx = e
329 .context
330 .as_deref()
331 .map(|c| format!(" [{c}]"))
332 .unwrap_or_default();
333 out.push_str(&format!(" [{prefix}] {}{ctx} ({age}m ago)\n", e.content));
334 }
335 out
336 }
337
338 pub fn format_compact(&self) -> String {
339 if self.entries.is_empty() {
340 return String::new();
341 }
342 let items: Vec<String> = self
343 .entries
344 .iter()
345 .rev()
346 .take(5)
347 .map(|e| {
348 let prefix = match e.entry_type {
349 DiaryEntryType::Discovery => "F",
350 DiaryEntryType::Decision => "D",
351 DiaryEntryType::Blocker => "B",
352 DiaryEntryType::Progress => "P",
353 DiaryEntryType::Insight => "I",
354 };
355 format!("{prefix}:{}", truncate(&e.content, 50))
356 })
357 .collect();
358 format!("diary:{}|{}", self.agent_id, items.join("|"))
359 }
360
361 pub fn save(&self) -> Result<(), String> {
362 let dir = diary_dir()?;
363 std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
364 let path = dir.join(format!("{}.json", sanitize_filename(&self.agent_id)));
365 let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
366 std::fs::write(&path, json).map_err(|e| e.to_string())
367 }
368
369 pub fn load(agent_id: &str) -> Option<Self> {
370 let dir = diary_dir().ok()?;
371 let path = dir.join(format!("{}.json", sanitize_filename(agent_id)));
372 let content = std::fs::read_to_string(&path).ok()?;
373 serde_json::from_str(&content).ok()
374 }
375
376 pub fn load_or_create(agent_id: &str, agent_type: &str, project_root: &str) -> Self {
377 Self::load(agent_id).unwrap_or_else(|| Self::new(agent_id, agent_type, project_root))
378 }
379
380 pub fn list_all() -> Vec<(String, usize, DateTime<Utc>)> {
381 let Ok(dir) = diary_dir() else {
382 return Vec::new();
383 };
384 if !dir.exists() {
385 return Vec::new();
386 }
387 let mut results = Vec::new();
388 if let Ok(entries) = std::fs::read_dir(&dir) {
389 for entry in entries.flatten() {
390 if entry.path().extension().and_then(|e| e.to_str()) == Some("json") {
391 if let Ok(content) = std::fs::read_to_string(entry.path()) {
392 if let Ok(diary) = serde_json::from_str::<AgentDiary>(&content) {
393 results.push((diary.agent_id, diary.entries.len(), diary.updated_at));
394 }
395 }
396 }
397 }
398 }
399 results.sort_by_key(|x| std::cmp::Reverse(x.2));
400 results
401 }
402}
403
404impl std::fmt::Display for DiaryEntryType {
405 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
406 match self {
407 DiaryEntryType::Discovery => write!(f, "discovery"),
408 DiaryEntryType::Decision => write!(f, "decision"),
409 DiaryEntryType::Blocker => write!(f, "blocker"),
410 DiaryEntryType::Progress => write!(f, "progress"),
411 DiaryEntryType::Insight => write!(f, "insight"),
412 }
413 }
414}
415
416fn diary_dir() -> Result<PathBuf, String> {
417 let dir = crate::core::data_dir::lean_ctx_data_dir()?;
418 Ok(dir.join("agents").join("diaries"))
419}
420
421fn sanitize_filename(name: &str) -> String {
422 name.chars()
423 .map(|c| {
424 if c.is_alphanumeric() || c == '-' || c == '_' {
425 c
426 } else {
427 '_'
428 }
429 })
430 .collect()
431}
432
433fn truncate(s: &str, max: usize) -> String {
434 if s.len() <= max {
435 s.to_string()
436 } else {
437 format!("{}...", &s[..max.saturating_sub(3)])
438 }
439}
440
441fn agents_dir() -> Result<PathBuf, String> {
442 let dir = crate::core::data_dir::lean_ctx_data_dir()?;
443 Ok(dir.join("agents"))
444}
445
446fn generate_short_id() -> String {
447 use std::collections::hash_map::DefaultHasher;
448 use std::hash::{Hash, Hasher};
449 use std::time::SystemTime;
450
451 let mut hasher = DefaultHasher::new();
452 SystemTime::now().hash(&mut hasher);
453 std::process::id().hash(&mut hasher);
454 format!("{:08x}", hasher.finish() as u32)
455}
456
457fn is_process_alive(pid: u32) -> bool {
458 #[cfg(unix)]
459 {
460 std::process::Command::new("kill")
461 .args(["-0", &pid.to_string()])
462 .output()
463 .is_ok_and(|o| o.status.success())
464 }
465 #[cfg(not(unix))]
466 {
467 let _ = pid;
468 true
469 }
470}
471
472struct FileLock {
473 path: PathBuf,
474}
475
476impl FileLock {
477 fn acquire(path: &std::path::Path) -> Result<Self, String> {
478 for _ in 0..50 {
479 if std::fs::OpenOptions::new()
480 .write(true)
481 .create_new(true)
482 .open(path)
483 .is_ok()
484 {
485 return Ok(Self {
486 path: path.to_path_buf(),
487 });
488 }
489 if let Ok(metadata) = std::fs::metadata(path) {
490 if let Ok(modified) = metadata.modified() {
491 if modified.elapsed().unwrap_or_default().as_secs() > 5 {
492 let _ = std::fs::remove_file(path);
493 continue;
494 }
495 }
496 }
497 std::thread::sleep(std::time::Duration::from_millis(100));
498 }
499 Err("Could not acquire lock after 5 seconds".to_string())
500 }
501}
502
503impl Drop for FileLock {
504 fn drop(&mut self) {
505 let _ = std::fs::remove_file(&self.path);
506 }
507}
508
509#[derive(Debug, Clone, Serialize, Deserialize)]
510pub struct SharedFact {
511 pub from_agent: String,
512 pub category: String,
513 pub key: String,
514 pub value: String,
515 pub timestamp: DateTime<Utc>,
516 #[serde(default)]
517 pub received_by: Vec<String>,
518}
519
520impl AgentRegistry {
521 pub fn share_knowledge(&mut self, from: &str, category: &str, facts: &[(String, String)]) {
522 for (key, value) in facts {
523 self.scratchpad.push(ScratchpadEntry {
524 id: format!("knowledge-{}", chrono::Utc::now().timestamp_millis()),
525 from_agent: from.to_string(),
526 to_agent: None,
527 category: category.to_string(),
528 message: format!("[knowledge] {key}={value}"),
529 timestamp: Utc::now(),
530 read_by: Vec::new(),
531 });
532 }
533 let shared_path = Self::shared_knowledge_path();
534 let mut existing: Vec<SharedFact> = std::fs::read_to_string(&shared_path)
535 .ok()
536 .and_then(|s| serde_json::from_str(&s).ok())
537 .unwrap_or_default();
538
539 for (key, value) in facts {
540 existing.push(SharedFact {
541 from_agent: from.to_string(),
542 category: category.to_string(),
543 key: key.clone(),
544 value: value.clone(),
545 timestamp: Utc::now(),
546 received_by: Vec::new(),
547 });
548 }
549
550 if existing.len() > 500 {
551 existing.drain(..existing.len() - 500);
552 }
553 if let Ok(json) = serde_json::to_string_pretty(&existing) {
554 let _ = std::fs::write(&shared_path, json);
555 }
556 }
557
558 pub fn receive_shared_knowledge(&mut self, agent_id: &str) -> Vec<SharedFact> {
559 let shared_path = Self::shared_knowledge_path();
560 let mut all: Vec<SharedFact> = std::fs::read_to_string(&shared_path)
561 .ok()
562 .and_then(|s| serde_json::from_str(&s).ok())
563 .unwrap_or_default();
564
565 let mut new_facts = Vec::new();
566 for fact in &mut all {
567 if fact.from_agent != agent_id && !fact.received_by.contains(&agent_id.to_string()) {
568 fact.received_by.push(agent_id.to_string());
569 new_facts.push(fact.clone());
570 }
571 }
572
573 if !new_facts.is_empty() {
574 if let Ok(json) = serde_json::to_string_pretty(&all) {
575 let _ = std::fs::write(&shared_path, json);
576 }
577 }
578 new_facts
579 }
580
581 fn shared_knowledge_path() -> PathBuf {
582 dirs::home_dir()
583 .unwrap_or_else(|| PathBuf::from("."))
584 .join(".lean-ctx")
585 .join("shared_knowledge.json")
586 }
587}
588
589#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
590#[serde(rename_all = "snake_case")]
591pub enum AgentRole {
592 Coder,
593 Reviewer,
594 Planner,
595 Explorer,
596 Debugger,
597 Tester,
598 Orchestrator,
599}
600
601impl AgentRole {
602 pub fn from_str_loose(s: &str) -> Self {
603 match s.to_lowercase().as_str() {
604 "review" | "reviewer" | "code_review" => Self::Reviewer,
605 "plan" | "planner" | "architect" => Self::Planner,
606 "explore" | "explorer" | "research" => Self::Explorer,
607 "debug" | "debugger" => Self::Debugger,
608 "test" | "tester" | "qa" => Self::Tester,
609 "orchestrator" | "coordinator" | "manager" => Self::Orchestrator,
610 _ => Self::Coder,
611 }
612 }
613}
614
615#[derive(Debug, Clone)]
616pub struct ContextDepthConfig {
617 pub max_files_full: usize,
618 pub max_files_signatures: usize,
619 pub preferred_mode: &'static str,
620 pub include_graph: bool,
621 pub include_knowledge: bool,
622 pub include_gotchas: bool,
623 pub context_budget_ratio: f64,
624}
625
626impl ContextDepthConfig {
627 pub fn for_role(role: AgentRole) -> Self {
628 match role {
629 AgentRole::Coder => Self {
630 max_files_full: 5,
631 max_files_signatures: 15,
632 preferred_mode: "full",
633 include_graph: true,
634 include_knowledge: true,
635 include_gotchas: true,
636 context_budget_ratio: 0.7,
637 },
638 AgentRole::Reviewer => Self {
639 max_files_full: 3,
640 max_files_signatures: 20,
641 preferred_mode: "signatures",
642 include_graph: true,
643 include_knowledge: true,
644 include_gotchas: true,
645 context_budget_ratio: 0.5,
646 },
647 AgentRole::Planner => Self {
648 max_files_full: 1,
649 max_files_signatures: 10,
650 preferred_mode: "map",
651 include_graph: true,
652 include_knowledge: true,
653 include_gotchas: false,
654 context_budget_ratio: 0.3,
655 },
656 AgentRole::Explorer => Self {
657 max_files_full: 2,
658 max_files_signatures: 8,
659 preferred_mode: "map",
660 include_graph: true,
661 include_knowledge: false,
662 include_gotchas: false,
663 context_budget_ratio: 0.4,
664 },
665 AgentRole::Debugger => Self {
666 max_files_full: 8,
667 max_files_signatures: 5,
668 preferred_mode: "full",
669 include_graph: false,
670 include_knowledge: true,
671 include_gotchas: true,
672 context_budget_ratio: 0.8,
673 },
674 AgentRole::Tester => Self {
675 max_files_full: 4,
676 max_files_signatures: 10,
677 preferred_mode: "full",
678 include_graph: false,
679 include_knowledge: false,
680 include_gotchas: true,
681 context_budget_ratio: 0.6,
682 },
683 AgentRole::Orchestrator => Self {
684 max_files_full: 0,
685 max_files_signatures: 5,
686 preferred_mode: "map",
687 include_graph: true,
688 include_knowledge: true,
689 include_gotchas: false,
690 context_budget_ratio: 0.2,
691 },
692 }
693 }
694
695 pub fn mode_for_rank(&self, rank: usize) -> &'static str {
696 if rank < self.max_files_full {
697 "full"
698 } else if rank < self.max_files_full + self.max_files_signatures {
699 "signatures"
700 } else {
701 "map"
702 }
703 }
704}
705
706#[cfg(test)]
707mod tests {
708 use super::*;
709
710 #[test]
711 fn register_and_list() {
712 let mut reg = AgentRegistry::new();
713 let id = reg.register("cursor", Some("dev"), "/tmp/project");
714 assert!(!id.is_empty());
715 assert_eq!(reg.list_active(None).len(), 1);
716 assert_eq!(reg.list_active(None)[0].agent_type, "cursor");
717 }
718
719 #[test]
720 fn reregister_same_pid() {
721 let mut reg = AgentRegistry::new();
722 let id1 = reg.register("cursor", Some("dev"), "/tmp/project");
723 let id2 = reg.register("cursor", Some("review"), "/tmp/project");
724 assert_eq!(id1, id2);
725 assert_eq!(reg.agents.len(), 1);
726 assert_eq!(reg.agents[0].role, Some("review".to_string()));
727 }
728
729 #[test]
730 fn post_and_read_messages() {
731 let mut reg = AgentRegistry::new();
732 reg.post_message("agent-a", None, "finding", "Found a bug in auth.rs");
733 reg.post_message("agent-b", Some("agent-a"), "request", "Please review");
734
735 let msgs = reg.read_unread("agent-a");
736 assert_eq!(msgs.len(), 1);
737 assert_eq!(msgs[0].category, "request");
738 }
739
740 #[test]
741 fn set_status() {
742 let mut reg = AgentRegistry::new();
743 let id = reg.register("claude", None, "/tmp/project");
744 reg.set_status(&id, AgentStatus::Idle, Some("waiting for review"));
745 assert_eq!(reg.agents[0].status, AgentStatus::Idle);
746 assert_eq!(
747 reg.agents[0].status_message,
748 Some("waiting for review".to_string())
749 );
750 }
751
752 #[test]
753 fn broadcast_message() {
754 let mut reg = AgentRegistry::new();
755 reg.post_message("agent-a", None, "status", "Starting refactor");
756
757 let msgs_b = reg.read_unread("agent-b");
758 assert_eq!(msgs_b.len(), 1);
759 assert_eq!(msgs_b[0].message, "Starting refactor");
760
761 let msgs_a = reg.read_unread("agent-a");
762 assert!(msgs_a.is_empty());
763 }
764
765 #[test]
766 fn diary_add_and_format() {
767 let mut diary = AgentDiary::new("test-agent-001", "cursor", "/tmp/project");
768 diary.add_entry(
769 DiaryEntryType::Discovery,
770 "Found auth module at src/auth.rs",
771 Some("auth"),
772 );
773 diary.add_entry(
774 DiaryEntryType::Decision,
775 "Use JWT RS256 for token signing",
776 None,
777 );
778 diary.add_entry(
779 DiaryEntryType::Progress,
780 "Implemented login endpoint",
781 Some("auth"),
782 );
783
784 assert_eq!(diary.entries.len(), 3);
785
786 let summary = diary.format_summary();
787 assert!(summary.contains("test-agent-001"));
788 assert!(summary.contains("FOUND"));
789 assert!(summary.contains("DECIDED"));
790 assert!(summary.contains("DONE"));
791 }
792
793 #[test]
794 fn diary_compact_format() {
795 let mut diary = AgentDiary::new("test-agent-002", "claude", "/tmp/project");
796 diary.add_entry(DiaryEntryType::Insight, "DB queries are N+1", None);
797 diary.add_entry(
798 DiaryEntryType::Blocker,
799 "Missing API credentials",
800 Some("deploy"),
801 );
802
803 let compact = diary.format_compact();
804 assert!(compact.contains("diary:test-agent-002"));
805 assert!(compact.contains("B:Missing API credentials"));
806 assert!(compact.contains("I:DB queries are N+1"));
807 }
808
809 #[test]
810 fn diary_entry_types() {
811 let types = vec![
812 DiaryEntryType::Discovery,
813 DiaryEntryType::Decision,
814 DiaryEntryType::Blocker,
815 DiaryEntryType::Progress,
816 DiaryEntryType::Insight,
817 ];
818 for t in types {
819 assert!(!format!("{t}").is_empty());
820 }
821 }
822
823 #[test]
824 fn diary_truncation() {
825 let mut diary = AgentDiary::new("test-agent", "cursor", "/tmp");
826 for i in 0..150 {
827 diary.add_entry(DiaryEntryType::Progress, &format!("Step {i}"), None);
828 }
829 assert!(diary.entries.len() <= 100);
830 }
831}