1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
use super::super::*;
impl CliRunner {
pub(crate) async fn handle_search_cmd(&self, action: &SearchAction) -> Result<()> {
match action {
SearchAction::Docs { query, limit } => {
let docs_dir = self.repo_path.join("docs");
if !docs_dir.exists() {
anyhow::bail!("docs/ directory not found at {}", docs_dir.display());
}
let query_lower = query.to_lowercase();
let mut results: Vec<(String, usize, String)> = Vec::new();
Self::search_dir_recursive(&docs_dir, &query_lower, &mut results).await?;
results.truncate(*limit);
if self.json_output {
let data: Vec<serde_json::Value> = results
.iter()
.map(|(file, line, text)| {
serde_json::json!({
"file": file,
"line": line,
"text": text.trim(),
})
})
.collect();
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"status": "success",
"query": query,
"data": data,
}))?
);
} else if results.is_empty() {
println!("No matches for \"{}\" in docs/", query);
} else {
println!(
"{} \"{}\" ({} matches)",
"Search results:".bright_cyan().bold(),
query.bright_yellow(),
results.len()
);
for (file, line, text) in &results {
println!(" {}:{} {}", file.bright_green(), line, text.trim());
}
}
}
SearchAction::Code { query, glob, limit } => {
let query_lower = query.to_lowercase();
let mut results: Vec<(String, usize, String)> = Vec::new();
Self::search_dir_recursive(&self.repo_path, &query_lower, &mut results).await?;
// Apply glob filter if provided
if let Some(glob_pattern) = glob {
let matcher = glob::Pattern::new(glob_pattern)
.map_err(|e| anyhow!("Invalid glob pattern: {}", e))?;
results.retain(|(file, _, _)| {
Path::new(file)
.file_name()
.and_then(|n| n.to_str())
.is_some_and(|name| matcher.matches(name))
});
}
results.truncate(*limit);
if self.json_output {
let data: Vec<serde_json::Value> = results
.iter()
.map(|(file, line, text)| {
serde_json::json!({
"file": file,
"line": line,
"text": text.trim(),
})
})
.collect();
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"status": "success",
"query": query,
"glob": glob,
"data": data,
}))?
);
} else if results.is_empty() {
println!("No matches for \"{}\" in source code", query);
} else {
println!(
"{} \"{}\" ({} matches)",
"Code search:".bright_cyan().bold(),
query.bright_yellow(),
results.len()
);
for (file, line, text) in &results {
println!(" {}:{} {}", file.bright_green(), line, text.trim());
}
}
}
}
Ok(())
}
/// Recursively search directory for query matches in text files
async fn search_dir_recursive(
dir: &Path,
query: &str,
results: &mut Vec<(String, usize, String)>,
) -> Result<()> {
let mut entries = tokio::fs::read_dir(dir).await?;
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
// Skip hidden dirs and common non-text dirs
if let Some(name) = path.file_name().and_then(|n| n.to_str())
&& (name.starts_with('.') || name == "target" || name == "node_modules")
{
continue;
}
if path.is_dir() {
// Use Box::pin to handle recursive async
Box::pin(Self::search_dir_recursive(&path, query, results)).await?;
} else if path.is_file() {
// Only search text-like files
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
if !matches!(
ext,
"rs" | "md"
| "toml"
| "yaml"
| "yml"
| "json"
| "ts"
| "js"
| "py"
| "go"
| "sh"
| "txt"
| "html"
| "css"
) {
continue;
}
if let Ok(content) = tokio::fs::read_to_string(&path).await {
for (i, line) in content.lines().enumerate() {
if line.to_lowercase().contains(query) {
results.push((path.display().to_string(), i + 1, line.to_string()));
}
}
}
}
}
Ok(())
}
pub(crate) async fn handle_evolution(&self, action: &EvolutionAction) -> Result<()> {
match action {
EvolutionAction::Metrics { agent, format } => {
let status_dir = PathBuf::from("coordination/agent-status");
let mut metrics: Vec<serde_json::Value> = Vec::new();
if status_dir.exists() {
let mut entries = tokio::fs::read_dir(&status_dir).await?;
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
if path.extension().is_some_and(|e| e == "json")
&& let Ok(content) = tokio::fs::read_to_string(&path).await
&& let Ok(status) = serde_json::from_str::<serde_json::Value>(&content)
{
if let Some(filter) = agent {
if status
.get("agent_id")
.and_then(|s| s.as_str())
.is_some_and(|s| s == filter)
{
metrics.push(status);
}
} else {
metrics.push(status);
}
}
}
}
if format == "json" || self.json_output {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"status": "success",
"data": metrics,
}))?
);
} else if metrics.is_empty() {
println!("No agent metrics found in coordination/agent-status/");
} else {
println!("{}", "Agent Metrics".bright_cyan().bold());
println!("{}", "=============".bright_cyan());
for m in &metrics {
let agent_id = m.get("agent_id").and_then(|v| v.as_str()).unwrap_or("?");
let st = m.get("status").and_then(|v| v.as_str()).unwrap_or("?");
let ts = m.get("timestamp").and_then(|v| v.as_str()).unwrap_or("?");
println!(
" {} [{}] last updated: {}",
agent_id.bright_yellow(),
st.bright_white(),
ts.bright_black()
);
}
println!("\nTotal: {} agents", metrics.len());
}
}
EvolutionAction::Patterns { agent, limit } => {
let task_dir = PathBuf::from("coordination/task-queue");
let mut tasks: Vec<serde_json::Value> = Vec::new();
if task_dir.exists() {
let mut entries = tokio::fs::read_dir(&task_dir).await?;
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
if path.extension().is_some_and(|e| e == "json")
&& let Ok(content) = tokio::fs::read_to_string(&path).await
&& let Ok(task) = serde_json::from_str::<serde_json::Value>(&content)
{
if let Some(filter) = agent {
if task
.get("assigned_agent")
.and_then(|s| s.as_str())
.is_some_and(|s| s == filter)
{
tasks.push(task);
}
} else {
tasks.push(task);
}
}
}
}
tasks.truncate(*limit);
// Count by status
let mut status_counts: std::collections::HashMap<String, usize> =
std::collections::HashMap::new();
for task in &tasks {
let st = task
.get("status")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string();
*status_counts.entry(st).or_default() += 1;
}
if self.json_output {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"status": "success",
"data": {
"tasks": tasks,
"status_counts": status_counts,
},
}))?
);
} else {
println!("{}", "Task Patterns".bright_cyan().bold());
println!("{}", "=============".bright_cyan());
if status_counts.is_empty() {
println!("No tasks found in coordination/task-queue/");
} else {
println!(" Status breakdown:");
for (status, count) in &status_counts {
println!(
" {}: {}",
status.bright_white(),
count.to_string().bright_yellow()
);
}
println!("\n Total: {} tasks analyzed", tasks.len());
}
}
}
EvolutionAction::Report { format } => {
// Combine metrics + patterns
let status_dir = PathBuf::from("coordination/agent-status");
let task_dir = PathBuf::from("coordination/task-queue");
let agent_count = if status_dir.exists() {
let mut count = 0usize;
let mut entries = tokio::fs::read_dir(&status_dir).await?;
while let Some(entry) = entries.next_entry().await? {
if entry.path().extension().is_some_and(|e| e == "json") {
count += 1;
}
}
count
} else {
0
};
let task_count = if task_dir.exists() {
let mut count = 0usize;
let mut entries = tokio::fs::read_dir(&task_dir).await?;
while let Some(entry) = entries.next_entry().await? {
if entry.path().extension().is_some_and(|e| e == "json") {
count += 1;
}
}
count
} else {
0
};
let report = serde_json::json!({
"agent_count": agent_count,
"task_count": task_count,
"generated_at": chrono::Utc::now().to_rfc3339(),
});
match format.as_str() {
"json" => {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"status": "success",
"data": report,
}))?
);
}
"markdown" => {
println!("# Evolution Report\n");
println!("- **Agents tracked**: {}", agent_count);
println!("- **Tasks in queue**: {}", task_count);
println!(
"- **Generated**: {}",
report
.get("generated_at")
.and_then(|v| v.as_str())
.unwrap_or("?")
);
}
_ => {
println!("{}", "Evolution Report".bright_cyan().bold());
println!("{}", "================".bright_cyan());
println!(" Agents tracked: {}", agent_count);
println!(" Tasks in queue: {}", task_count);
}
}
}
}
Ok(())
}
}