Repository navigation
Expand file tree
/
Copy pathlist.rs
More file actions
1263 lines (1160 loc) · 43.2 KB
/
Copy pathlist.rs
File metadata and controls
1263 lines (1160 loc) · 43.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! `hcom list` command — list active instances.
//!
//!
//! Supports: human-readable, --json, --names, --format, -v,
//! single instance query (self/named), full listing with unread counts.
use std::collections::HashMap;
use crate::db::{HcomDb, InstanceRow};
use crate::identity;
use crate::identity::{get_full_name, resolve_display_name};
use crate::instance_lifecycle::{
RECENTLY_STOPPED_WINDOW, cleanup_stale_instances, cleanup_stale_placeholders, format_age,
get_instance_status,
};
use crate::instances::{is_remote_instance, is_subagent_instance};
use crate::shared::{
CommandContext, SENDER, ST_LISTENING, shorten_path, shorten_path_max, status_icon,
};
/// Tool label shown in `hcom list`, e.g. `CLAUDE` or `CODEX*`.
///
/// A star means an agent whose delivery depends on local bindings has a
/// missing one: its hooks haven't bound yet (or never will), or its hcom
/// process is gone. Subagents use their parent's session and relay mirrors are
/// bound on their own device, so neither gets a star.
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
struct Bindings {
session: bool,
process: bool,
}
impl Bindings {
fn for_instance(db: &HcomDb, name: &str) -> Self {
Self {
session: db.has_session_binding(name),
process: db.has_process_binding_for_instance(name),
}
}
}
fn get_bindings_batch(db: &HcomDb) -> HashMap<String, Bindings> {
let Ok(mut stmt) = db.conn().prepare(
"SELECT name,
EXISTS(SELECT 1 FROM session_bindings WHERE instance_name = instances.name),
EXISTS(SELECT 1 FROM process_bindings WHERE instance_name = instances.name)
FROM instances",
) else {
return HashMap::new();
};
stmt.query_map([], |row| {
Ok((
row.get(0)?,
Bindings {
session: row.get(1)?,
process: row.get(2)?,
},
))
})
.ok()
.into_iter()
.flatten()
.filter_map(Result::ok)
.collect()
}
fn tool_label(bindings: Bindings, data: &InstanceRow) -> String {
if data.tool == "adhoc" {
return "AD-HOC".to_string();
}
let tool = data.tool.to_uppercase();
if is_remote_instance(data) || is_subagent_instance(data) {
return tool;
}
if bindings.session && bindings.process {
tool
} else {
format!("{tool}*")
}
}
/// Binding summary for verbose/detail views: "hooks, process", "hooks", ...
/// An ad-hoc row's session binding only keys its identity (no hooks run).
fn bindings_display(bindings: Bindings, data: &InstanceRow) -> &'static str {
let session = bindings.session;
if data.tool == "adhoc" {
return if session { "session" } else { "none" };
}
match (session, bindings.process) {
(true, true) => "hooks, process",
(true, false) => "hooks",
(false, true) => "process",
(false, false) => "none",
}
}
/// Parsed arguments for `hcom list`.
#[derive(clap::Parser, Debug)]
#[command(name = "list", about = "List active agents")]
pub struct ListArgs {
/// Agent name or "self"
pub name: Option<String>,
/// Field to extract (used with name)
pub field: Option<String>,
/// Show recently stopped agents
#[arg(long)]
pub stopped: bool,
/// JSON output
#[arg(long)]
pub json: bool,
/// Verbose output
#[arg(short = 'v', long)]
pub verbose: bool,
/// Names-only output
#[arg(long)]
pub names: bool,
/// Shell export format
#[arg(long)]
pub sh: bool,
/// Custom format template with {field} placeholders
#[arg(long)]
pub format: Option<String>,
/// Show all (with --stopped)
#[arg(long)]
pub all: bool,
/// Limit results (with --stopped)
#[arg(long)]
pub last: Option<usize>,
}
/// Get unread message count for a single instance.
fn get_unread_count(db: &HcomDb, name: &str, last_event_id: i64) -> i64 {
db.conn()
.query_row(
"SELECT COUNT(*) FROM events WHERE id > ? AND type = 'message'
AND EXISTS (SELECT 1 FROM json_each(json_extract(data, '$.delivered_to')) WHERE value = ?)",
rusqlite::params![last_event_id, name],
|row| row.get(0),
)
.unwrap_or(0)
}
/// Get unread counts for all instances in batch.
fn get_unread_counts_batch(db: &HcomDb, instances: &[InstanceRow]) -> HashMap<String, i64> {
let recipients: HashMap<&str, i64> = instances
.iter()
.filter(|inst| !is_remote_instance(inst))
.map(|inst| (inst.name.as_str(), inst.last_event_id))
.collect();
let Some(min_cursor) = recipients.values().min() else {
return HashMap::new();
};
let Ok(mut stmt) = db
.conn()
.prepare("SELECT id, json_extract(data, '$.delivered_to') FROM events WHERE type = 'message' AND id > ? ORDER BY id")
else {
return HashMap::new();
};
let Ok(rows) = stmt.query_map([min_cursor], |row| {
Ok((row.get::<_, i64>(0)?, row.get::<_, Option<String>>(1)?))
}) else {
return HashMap::new();
};
let mut counts = HashMap::new();
// Scan the unread tail once. Joining json_each recipients in SQL otherwise
// makes SQLite re-scan messages per agent, even inside a single statement.
for row in rows {
let Ok((id, Some(data))) = row else {
continue;
};
let Ok(data) = serde_json::from_str::<serde_json::Value>(&data) else {
continue;
};
let Some(delivered_to) = data.as_array() else {
continue;
};
let mut seen = std::collections::HashSet::new();
for name in delivered_to.iter().filter_map(serde_json::Value::as_str) {
if let Some(cursor) = recipients.get(name)
&& id > *cursor
&& seen.insert(name)
{
*counts.entry(name.to_owned()).or_insert(0) += 1;
}
}
}
counts
}
/// Main entry point for `hcom list` command.
///
/// Returns exit code (0 = success, 1 = error).
pub fn cmd_list(db: &HcomDb, args: &ListArgs, ctx: Option<&CommandContext>) -> i32 {
// Clean up stale placeholders and instances
cleanup_stale_placeholders(db);
let _ = cleanup_stale_instances(db, 3600, 3600);
let explicit_name = ctx.and_then(|c| c.explicit_name.as_deref());
// --stopped: show recently stopped instances from life events
if args.stopped {
return cmd_list_stopped(db, args);
}
let json_output = args.json;
let verbose_output = args.verbose;
let names_output = args.names;
let sh_output = args.sh;
let format_template = args.format.clone();
let target_name = args.name.as_deref();
let field_name = args.field.as_deref();
// Resolve current instance identity
let (sender_identity, current_name) = if let Some(id) = ctx.and_then(|c| c.identity.as_ref()) {
(Some(id.clone()), Some(id.name.clone()))
} else if let Some(name) = explicit_name {
match identity::resolve_identity(db, Some(name), None, None, None, None) {
Ok(id) => {
let n = id.name.clone();
(Some(id), Some(n))
}
Err(e) => {
eprintln!("Error: Cannot resolve '{name}': {e}");
return 1;
}
}
} else {
identity::resolve_identity(db, None, None, None, None, None)
.map(|id| {
let n = id.name.clone();
(Some(id), Some(n))
})
.unwrap_or((None, None))
};
// Single instance query: hcom list <name|self> [field] [--json]
if let Some(target) = target_name {
let is_self = target == "self";
if is_self && sender_identity.is_none() {
eprintln!("Error: Cannot use 'self' without identity. Run 'hcom start' first.");
return 1;
}
let lookup_name = if is_self {
current_name.clone().unwrap_or_default()
} else {
let resolved = resolve_display_name(db, target);
resolved.unwrap_or_else(|| target.to_string())
};
if lookup_name.is_empty() {
eprintln!("Error: No name to look up.");
return 1;
}
match db.get_instance_full(&lookup_name) {
Ok(Some(data)) => {
let mut payload = serde_json::json!({
"name": lookup_name,
"session_id": data.session_id,
"status": data.status,
"directory": data.directory,
"transcript_path": data.transcript_path,
"parent_name": data.parent_name,
"agent_id": data.agent_id,
"tool": data.tool,
});
if is_self
&& let Some(id) = &sender_identity
&& let Some(sid) = &id.session_id
{
payload["session_id"] = serde_json::json!(sid);
}
if let Some(field) = field_name {
println!("{}", extract_field_value(&payload, field));
} else if sh_output {
print_sh_exports(&payload);
} else if json_output {
println!("{}", serde_json::to_string(&payload).unwrap_or_default());
} else {
print_instance_details(db, &data, &lookup_name);
}
return 0;
}
_ => {
if is_self {
let payload = serde_json::json!({
"name": lookup_name,
"session_id": sender_identity.as_ref().and_then(|id| id.session_id.as_deref()).unwrap_or(""),
});
if let Some(field) = field_name {
println!("{}", extract_field_value(&payload, field));
} else if sh_output {
print_sh_exports(&payload);
} else if json_output {
println!("{}", serde_json::to_string(&payload).unwrap_or_default());
} else {
println!("{lookup_name}");
}
return 0;
} else {
eprintln!("Error: {}", identity::describe_missing_agent(db, target));
return 1;
}
}
}
}
// Full listing mode
let sorted_instances = match db.iter_instances_full() {
Ok(rows) => rows,
Err(e) => {
eprintln!("Error: {e}");
return 1;
}
};
if names_output {
for data in &sorted_instances {
println!("{}", get_full_name(data));
}
return 0;
}
let unread_counts = get_unread_counts_batch(db, &sorted_instances);
let binding_counts = get_bindings_batch(db);
if json_output || format_template.is_some() {
let mut result_list: Vec<serde_json::Value> = Vec::new();
for data in &sorted_instances {
let full_name = get_full_name(data);
let cs = get_instance_status(data, db);
let (status, description, age_seconds) = (cs.status, cs.description, cs.age_seconds);
// Get binding status
let bindings = binding_counts.get(&data.name).copied().unwrap_or_default();
let hooks_bound = bindings.session;
let process_bound = bindings.process;
// Parse launch_context JSON
let launch_context: serde_json::Value = data
.launch_context
.as_deref()
.filter(|s| !s.is_empty())
.and_then(|s| serde_json::from_str(s).ok())
.unwrap_or(serde_json::json!({}));
let payload = serde_json::json!({
"name": full_name,
"status": status,
"status_context": data.status_context,
"status_detail": data.status_detail,
"status_age_seconds": age_seconds,
"description": description,
"unread_count": unread_counts.get(&data.name).copied().unwrap_or(0),
"headless": data.background != 0,
"session_id": data.session_id.as_deref().unwrap_or(""),
"directory": data.directory,
"parent_name": data.parent_name,
"agent_id": data.agent_id,
"background_log_file": if data.background_log_file.is_empty() { None } else { Some(&data.background_log_file) },
"transcript_path": if data.transcript_path.is_empty() { None } else { Some(&data.transcript_path) },
"created_at": data.created_at,
"tag": data.tag,
"tool": data.tool,
"base_name": data.name,
"hooks_bound": hooks_bound,
"process_bound": process_bound,
"launch_context": launch_context,
});
result_list.push(payload);
}
if let Some(ref template) = format_template {
// Validate template keys against first payload (error on unknown fields)
if let Some(first) = result_list.first()
&& let Some(obj) = first.as_object()
{
// Find all {key} placeholders in template
let mut i = 0;
let bytes = template.as_bytes();
while i < bytes.len() {
if bytes[i] == b'{'
&& let Some(end) = template[i + 1..].find('}')
{
let key = &template[i + 1..i + 1 + end];
if !key.is_empty() && !obj.contains_key(key) {
eprintln!("Error: unknown field '{{{}}}' in --format template", key);
return 1;
}
i += end + 2;
continue;
}
i += 1;
}
}
for payload in &result_list {
let obj = payload.as_object().unwrap();
let mut line = template.clone();
for (key, val) in obj {
let replacement = match val {
serde_json::Value::String(s) => s.clone(),
serde_json::Value::Null => String::new(),
other => other.to_string(),
};
line = line.replace(&format!("{{{key}}}"), &replacement);
}
println!("{line}");
}
} else {
println!(
"{}",
serde_json::to_string(&result_list).unwrap_or_default()
);
}
return 0;
}
// Human-readable output
let display_name = if let Some(ref name) = current_name {
if name != SENDER {
if let Ok(Some(data)) = db.get_instance_full(name) {
get_full_name(&data)
} else {
name.clone()
}
} else {
name.clone()
}
} else {
String::new()
};
if !display_name.is_empty() {
println!("Your name: {display_name}");
} else {
println!("Your name: (not participating)");
}
println!();
// Check if multiple tool types exist
let mut tool_types = std::collections::HashSet::new();
for data in &sorted_instances {
tool_types.insert(data.tool.clone());
}
let show_tool = tool_types.len() > 1;
// Check if multiple directories
let mut directories = std::collections::HashSet::new();
for data in &sorted_instances {
if !data.directory.is_empty() {
directories.insert(data.directory.clone());
}
}
// Compute name column width
let mut max_name_len = 0;
for data in &sorted_instances {
let mut n = get_full_name(data).len();
if data.background != 0 {
n += 11; // " [headless]"
}
if is_remote_instance(data) {
n += 9; // " [remote]"
}
let uc = unread_counts.get(&data.name).copied().unwrap_or(0);
if uc > 0 {
n += format!(" +{uc}").len();
}
max_name_len = max_name_len.max(n);
}
let name_col_width = (max_name_len + 2).max(14);
for data in &sorted_instances {
let name = get_full_name(data);
let cs = get_instance_status(data, db);
let (status, age_str, description) = (cs.status, cs.age_string, cs.description);
let icon = status_icon(&status);
let age_display = if age_str == "now" {
age_str.clone()
} else if !age_str.is_empty() {
format!("{age_str} ago")
} else {
String::new()
};
let desc_sep = if !description.is_empty() { ": " } else { "" };
let tool_prefix = if show_tool {
let padded = format!(
"[{}]",
tool_label(
binding_counts.get(&data.name).copied().unwrap_or_default(),
data
)
);
format!("{padded:<10}")
} else {
String::new()
};
// Badges
let headless_badge = if data.background != 0 {
" [headless]"
} else {
""
};
let remote_badge = if is_remote_instance(data) {
" [remote]"
} else {
""
};
// Unread
let unread = unread_counts.get(&data.name).copied().unwrap_or(0);
let unread_str = if unread > 0 {
format!(" +{unread}")
} else {
String::new()
};
// Listening-since suffix: show idle duration for listening agents idle >= 60s
let listening_since = if status == ST_LISTENING && cs.age_seconds >= 60 {
format!(" since {}", format_age(cs.age_seconds))
} else {
String::new()
};
// Subagent timeout marker: show countdown when < 10s remaining
let timeout_marker = if status == ST_LISTENING && data.parent_session_id.is_some() {
let timeout = if let Some(ref parent_name) = data.parent_name {
db.get_instance_full(parent_name)
.ok()
.flatten()
.and_then(|p| p.subagent_timeout)
} else {
None
}
.unwrap_or_else(|| crate::config::load_config_snapshot().core.subagent_timeout);
let remaining = timeout.saturating_sub(cs.age_seconds);
if remaining > 0 && remaining < 10 {
format!(" \u{23f1} {remaining}s")
} else {
String::new()
}
} else {
String::new()
};
let name_part = format!("{name}{headless_badge}{remote_badge}{unread_str}");
let status_text =
format!("{age_display}{desc_sep}{description}{listening_since}{timeout_marker}");
println!(
"{tool_prefix}{icon} {name_part:<width$}{status_text}",
width = name_col_width
);
if verbose_output {
let session_id = data.session_id.as_deref().unwrap_or("(none)");
let directory_display = if data.directory.is_empty() {
"(none)".to_string()
} else {
shorten_path_max(&data.directory, 60)
};
let parent = data.parent_name.as_deref().unwrap_or("(none)");
let tool_display = if data.tool == "adhoc" {
"ad-hoc"
} else {
&data.tool
};
let created_str = if data.created_at > 0.0 {
let now = crate::shared::time::now_epoch_f64();
let age_f = now - data.created_at;
// format_age takes i64 where 0 → "now". Use f64 threshold
// so sub-second ages display as "0s" instead of "now".
let age_str = if age_f <= 0.0 {
"now".to_string()
} else {
let secs = age_f as i64;
if secs < 60 {
format!("{secs}s")
} else {
format_age(secs)
}
};
format!("{age_str} ago")
} else {
"(unknown)".to_string()
};
println!(" session_id: {session_id}");
println!(" tool: {tool_display}");
println!(" created: {created_str}");
println!(" directory: {directory_display}");
if parent != "(none)" {
println!(" parent: {parent}");
let agent_id = data.agent_id.as_deref().unwrap_or("(none)");
println!(" agent_id: {agent_id}");
}
// Binding status
println!(
" bindings: {}",
bindings_display(
binding_counts.get(&data.name).copied().unwrap_or_default(),
data
)
);
let transcript = if data.transcript_path.is_empty() {
"(none)".to_string()
} else {
shorten_path_max(&data.transcript_path, 60)
};
if data.background != 0 && !data.background_log_file.is_empty() {
println!(
" headless log: {}",
shorten_path_max(&data.background_log_file, 60)
);
}
println!(" transcript: {transcript}");
if !data.status_detail.is_empty() {
let detail = if data.status_detail.len() > 60 {
let end = (0..=60)
.rev()
.find(|&i| data.status_detail.is_char_boundary(i))
.unwrap_or(0);
format!("{}...", &data.status_detail[..end])
} else {
data.status_detail.clone()
};
println!(" detail: {detail}");
}
println!();
}
}
if sorted_instances.is_empty() {
println!("No active agents. Launch one with: hcom claude");
}
// Recently stopped summary
let active_names: std::collections::HashSet<String> =
sorted_instances.iter().map(|d| d.name.clone()).collect();
let recently_stopped = get_recently_stopped(db, &active_names);
if !recently_stopped.is_empty() {
let names = if recently_stopped.len() <= 5 {
recently_stopped.join(", ")
} else {
format!(
"{} +{}",
recently_stopped[..5].join(", "),
recently_stopped.len() - 5
)
};
println!("\nRecently stopped (10m): {names}");
println!(" -> hcom list --stopped [name]");
}
// Hint about archives if no instances
if sorted_instances.is_empty() {
let archive_dir = crate::paths::hcom_dir().join("archive");
if archive_dir.exists()
&& let Ok(entries) = std::fs::read_dir(&archive_dir)
{
let archive_count = entries
.filter_map(|e| e.ok())
.filter(|e| {
e.file_name()
.to_str()
.map(|s| s.starts_with("session-"))
.unwrap_or(false)
})
.count();
if archive_count > 0 {
let plural = if archive_count != 1 { "s" } else { "" };
println!("({archive_count} archived session{plural} - run: hcom archive)");
}
}
}
0
}
fn print_instance_details(db: &HcomDb, data: &InstanceRow, display_name: &str) {
let cs = get_instance_status(data, db);
let status = cs.status;
// Status line construction
let status_line = if data.status_context.is_empty() {
status.clone()
} else {
format!("{status} ({})", data.status_context)
};
println!("{display_name}:");
// Core Identity
let headless_str = if data.background != 0 {
" (Headless)"
} else {
""
};
let tool_display = if data.tool == "adhoc" {
"ad-hoc"
} else {
&data.tool
};
println!(" Tool: {tool_display}{headless_str}");
if let Some(ref term) = data
.terminal_preset_effective
.as_ref()
.or(data.terminal_preset_requested.as_ref())
&& !term.is_empty()
{
println!(" Terminal: {term}");
}
let session_id = data.session_id.as_deref().unwrap_or("(none)");
println!(" Session: {session_id}");
if let Some(ref tag) = data.tag
&& !tag.is_empty()
{
println!(" Tag: {tag}");
}
// Status & Connection
println!(" Status: {status_line}");
if !data.status_detail.is_empty() {
println!(" Detail: {}", data.status_detail);
}
// Uptime and Age
let now = crate::shared::time::now_epoch_f64();
if data.status_time > 0 {
let state_age = now - (data.status_time as f64);
if state_age > 0.0 {
println!(" State Age: {}", format_age(state_age as i64));
}
}
if data.created_at > 0.0 {
let uptime = now - data.created_at;
if uptime > 0.0 {
println!(" Uptime: {}", format_age(uptime as i64));
}
}
// Unread Count
let unread = get_unread_count(db, &data.name, data.last_event_id);
if unread > 0 {
let s = if unread == 1 { "" } else { "s" };
println!(" Unread: {unread} message{s}");
}
// Bindings
println!(
" Bindings: {}",
bindings_display(Bindings::for_instance(db, &data.name), data)
);
if let Some(pid) = data.pid {
println!(" PID: {pid}");
}
// Hierarchy
if let Some(ref parent) = data.parent_name
&& !parent.is_empty()
{
println!(" Parent: {parent}");
if let Some(ref agent_id) = data.agent_id
&& !agent_id.is_empty()
{
println!(" Agent ID: {agent_id}");
}
// Subagent Timeout
let timeout = data
.subagent_timeout
.unwrap_or_else(|| crate::config::load_config_snapshot().core.subagent_timeout);
let remaining = timeout.saturating_sub(cs.age_seconds);
if status == ST_LISTENING && remaining > 0 {
println!(" Timeout: {}s remaining", remaining);
}
}
// Paths
println!(" Directory: {}", shorten_path_max(&data.directory, 80));
if !data.transcript_path.is_empty() {
println!(" Transcript: {}", shorten_path(&data.transcript_path));
}
if data.background != 0 && !data.background_log_file.is_empty() {
println!(" Log File: {}", shorten_path(&data.background_log_file));
}
}
/// Extract a field value from a JSON payload, normalizing booleans to "1"/"0".
fn extract_field_value(payload: &serde_json::Value, field: &str) -> String {
match payload.get(field) {
Some(serde_json::Value::Bool(b)) => if *b { "1" } else { "0" }.to_string(),
Some(serde_json::Value::String(s)) => s.clone(),
Some(serde_json::Value::Null) => String::new(),
Some(other) => other.to_string(),
None => String::new(),
}
}
/// Print shell-export format for `hcom list --sh`.
fn print_sh_exports(payload: &serde_json::Value) {
let name = payload.get("name").and_then(|v| v.as_str()).unwrap_or("");
let session_id = payload
.get("session_id")
.and_then(|v| v.as_str())
.unwrap_or("");
let status = payload
.get("status")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
let directory = payload
.get("directory")
.and_then(|v| v.as_str())
.unwrap_or("");
println!("export HCOM_INSTANCE_NAME={}", shell_quote(name));
println!("export HCOM_SID={}", shell_quote(session_id));
println!("export HCOM_STATUS={}", shell_quote(status));
println!("export HCOM_DIRECTORY={}", shell_quote(directory));
}
use crate::tools::args_common::shell_quote;
/// `hcom list --stopped [name] [--all] [--last N]` — show stopped instances from life events.
/// Without a name: shows recent stopped (default last 20, use --all for unlimited).
/// With a name: shows details for that specific stopped instance.
/// Uses human-friendly formatting rather than raw JSON for readability.
fn cmd_list_stopped(db: &HcomDb, args: &ListArgs) -> i32 {
use rusqlite::params;
let show_all = args.all;
let last_n: usize = args.last.unwrap_or(20);
let filter_name = args.name.as_deref();
let now = crate::shared::time::now_epoch_f64();
let limit = if show_all { 10000 } else { last_n };
let (query, param) = if let Some(name) = filter_name {
let name = crate::identity::resolve_display_name_or_stopped(db, name)
.unwrap_or_else(|| name.to_string());
// Fix: fetch up to 10000 events for named instance (was LIMIT 1)
(
"SELECT instance, timestamp, data FROM events
WHERE type = 'life' AND json_extract(data, '$.action') = 'stopped'
AND instance = ?
ORDER BY id DESC LIMIT 10000"
.to_string(),
name,
)
} else {
(
format!(
"SELECT instance, timestamp, data FROM events
WHERE type = 'life' AND json_extract(data, '$.action') = 'stopped'
ORDER BY id DESC LIMIT {limit}"
),
String::new(),
)
};
let Ok(mut stmt) = db.conn().prepare(&query) else {
eprintln!("Error: failed to query stopped events");
return 1;
};
struct StoppedEntry {
instance: String,
timestamp: String,
data: String,
}
let row_mapper = |row: &rusqlite::Row| -> rusqlite::Result<StoppedEntry> {
Ok(StoppedEntry {
instance: row.get(0)?,
timestamp: row.get(1)?,
data: row.get(2)?,
})
};
let entries: Vec<StoppedEntry> = if filter_name.is_some() {
stmt.query_map(params![param], row_mapper)
} else {
stmt.query_map([], row_mapper)
}
.ok()
.into_iter()
.flatten()
.filter_map(|r| r.ok())
.collect();
if entries.is_empty() {
if let Some(name) = filter_name {
println!("No stopped events found for '{name}'");
} else {
println!("No recently stopped agents (last 60m)");
}
return 0;
}
if filter_name.is_some() {
// Detailed view for a single instance (show all stop events, not just 1)
let entry = &entries[0];
let data: serde_json::Value = serde_json::from_str(&entry.data).unwrap_or_default();
let snapshot = &data["snapshot"];
println!("Stopped: {}", entry.instance);
println!(" Time: {}", entry.timestamp);
if let Some(by) = data["by"].as_str() {
println!(" By: {by}");
}
if let Some(reason) = data["reason"].as_str() {
println!(" Reason: {reason}");
}
if let Some(tool) = snapshot["tool"].as_str() {
println!(" Tool: {tool}");
}
if let Some(tag) = snapshot["tag"].as_str()
&& !tag.is_empty()
{
println!(" Tag: {tag}");
}
if let Some(dir) = snapshot["directory"].as_str() {
println!(" Directory: {dir}");
}
if let Some(sid) = snapshot["session_id"].as_str()
&& !sid.is_empty()
{
println!(" Session: {sid}");
}
if let Some(tp) = snapshot["transcript_path"].as_str()
&& !tp.is_empty()
{
println!(" Transcript: {tp}");
}
println!("\n Resume: hcom r {}", entry.instance);
// Show history if multiple stop events
if entries.len() > 1 {
println!("\n Stop history ({} events):", entries.len());
for (i, e) in entries.iter().enumerate() {
let d: serde_json::Value = serde_json::from_str(&e.data).unwrap_or_default();
let reason = d["reason"].as_str().unwrap_or("");
let by = d["by"].as_str().unwrap_or("");
let age = if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&e.timestamp) {
let event_epoch = dt.timestamp() as f64;
format_age((now - event_epoch) as i64)
} else {
e.timestamp.clone()
};
let by_part = if by.is_empty() {
String::new()
} else {
format!(" by:{by}")
};
let marker = if i == 0 { " (latest)" } else { "" };
println!(" {age} ago [{reason}{by_part}]{marker}");
}
}
} else {
// Summary table
let header = if show_all {
format!("Stopped agents (all, showing {}):", entries.len())
} else {
format!("Stopped agents (last {last_n}):")
};
println!("{header}\n");
for entry in &entries {
let data: serde_json::Value = serde_json::from_str(&entry.data).unwrap_or_default();
let snapshot = &data["snapshot"];
let tool = snapshot["tool"].as_str().unwrap_or("?");
let tag = snapshot["tag"].as_str().unwrap_or("");
let reason = data["reason"].as_str().unwrap_or("");
let by = data["by"].as_str().unwrap_or("");
// Parse timestamp for age
let age = if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&entry.timestamp) {
let event_epoch = dt.timestamp() as f64;
format_age((now - event_epoch) as i64)
} else {
entry.timestamp.clone()
};