agent-team-mail 1.3.1

CLI for local agent team mail workflows.
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
use crate::output_contract::{HelpResult, HelpResultKind};
use anyhow::Result;
use atm_core::ack::AckOutcome;
use atm_core::clear::ClearOutcome;
use atm_core::doctor::{
    BootstrapAutoStartOutcome, BootstrapConnectOutcome, BootstrapLaunchGateOutcome,
    BootstrapTraceReport, DoctorReport, DoctorSeverity, DoctorStatus,
};
use atm_core::list::ListOutcome;
use atm_core::observability::{AtmLogRecord, AtmLogSnapshot};
use atm_core::protocol::{RuntimeLivenessState, RuntimeReadinessState, RuntimeStatusSnapshot};
use atm_core::read::ReadOutcome;
use atm_core::send::SendOutcome;
use atm_core::team_admin::{
    AddMemberOutcome, BackupOutcome, ClearNudgeTemplateOverrideOutcome,
    DisableNudgeTemplateOverrideOutcome, MembersList, RestoreOutcome, RestorePlan,
    SetNudgeTemplateOverrideOutcome, TeamsList, UpdateMemberOutcome,
};

/// Print one send result in human-readable or JSON form.
pub fn print_send_result(outcome: &SendOutcome, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(outcome)?);
    } else {
        println!(
            "Sent to {}@{} [message_id: {}]",
            outcome.agent, outcome.team, outcome.message_id
        );
    }

    for warning in &outcome.warnings {
        eprintln!("{}", warning.render());
    }

    Ok(())
}

/// Print one help result in human-readable or JSON form.
pub fn print_help_result(result: &HelpResult, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(result)?);
        return Ok(());
    }

    match result.kind {
        HelpResultKind::CommandHelp => {
            print!("{}", result.body);
            if !result.body.ends_with('\n') {
                println!();
            }
        }
        _ => println!("{}", result.body),
    }

    Ok(())
}

/// Print one list result in human-readable or JSON form.
pub fn print_list_result(outcome: &ListOutcome, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(outcome)?);
        return Ok(());
    }

    println!("Queue: {}@{}", outcome.agent, outcome.team);
    println!(
        "Unread: {} | Pending-Ack: {} | History: {}",
        outcome.bucket_counts.unread,
        outcome.bucket_counts.pending_ack,
        outcome.bucket_counts.history
    );

    for row in &outcome.rows {
        println!(
            "- {} {}: {}",
            row.timestamp.into_inner().to_rfc3339(),
            row.from,
            row.summary
        );
        println!(
            "  message_id: {}",
            row.message_id
                .map(|message_id| message_id.to_string())
                .unwrap_or_else(|| "<none>".to_string())
        );
        if let Some(task_id) = &row.task_id {
            println!("  task_id: {task_id}");
        }
        println!(
            "  state: {}{}",
            if row.read { "read" } else { "unread" },
            if row.pending_ack { " pending-ack" } else { "" }
        );
    }

    if outcome.history_collapsed && outcome.bucket_counts.history > 0 {
        println!();
        println!(
            "History: {} older messages hidden. Use --all to show them.",
            outcome.bucket_counts.history
        );
    }

    Ok(())
}

/// Print one read result in human-readable or JSON form.
pub fn print_read_result(outcome: &ReadOutcome, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(outcome)?);
        return Ok(());
    }

    println!("Queue: {}@{}", outcome.agent, outcome.team);
    println!(
        "Unread: {} | Pending-Ack: {} | History: {}",
        outcome.bucket_counts.unread,
        outcome.bucket_counts.pending_ack,
        outcome.bucket_counts.history
    );
    println!(
        "Selected: {} | Matches: {} | Additional: {}",
        outcome
            .selected_message_id
            .map(|message_id| message_id.to_string())
            .unwrap_or_else(|| "<none>".to_string()),
        outcome.match_count,
        outcome.additional_match_count
    );
    if let Some(message) = &outcome.message {
        println!();
        println!("From: {}", message.envelope.from);
        println!(
            "At: {}",
            message.envelope.timestamp.into_inner().to_rfc3339()
        );
        if let Some(task_id) = &message.envelope.task_id {
            println!("Task: {task_id}");
        }
        if let Some(summary) = message.envelope.summary.as_deref() {
            println!("Summary: {summary}");
        }
        println!("Body:");
        println!("{}", message.envelope.text);
    } else {
        println!();
        println!("No matching message.");
    }

    if outcome.additional_match_count > 0 {
        println!();
        println!(
            "Additional matches remain. Use `atm list` with the same filters to inspect them."
        );
    }

    Ok(())
}

/// Print one acknowledgement result in human-readable or JSON form.
pub fn print_ack_result(outcome: &AckOutcome, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(outcome)?);
    } else {
        println!("{}", render_ack_result_line(outcome));
        if outcome.reply_disposition.is_suppressed_self_ack() {
            println!("Suppressed reply text:");
            println!("{}", outcome.reply_text);
        }
    }

    for warning in &outcome.warnings {
        eprintln!("{}", warning.render());
    }

    Ok(())
}

fn render_ack_result_line(outcome: &AckOutcome) -> String {
    match &outcome.reply_disposition {
        atm_core::ack::AckReplyDisposition::SuppressedSelfAck => format!(
            "Acknowledged {} for {}@{} and suppressed the self-ack reply",
            outcome.message_id, outcome.agent, outcome.team
        ),
        atm_core::ack::AckReplyDisposition::Sent {
            reply_message_id,
            reply_target,
        } => format!(
            "Acknowledged {} for {}@{} and sent reply {} to {}",
            outcome.message_id, outcome.agent, outcome.team, reply_message_id, reply_target
        ),
    }
}

/// Print one clear result in human-readable or JSON form.
pub fn print_clear_result(outcome: &ClearOutcome, dry_run: bool, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(outcome)?);
        return Ok(());
    }

    if dry_run {
        println!(
            "Dry run: would remove {} message(s) from {}@{}",
            outcome.removed_total, outcome.agent, outcome.team
        );
    } else {
        println!(
            "Cleared {} message(s) from {}@{}",
            outcome.removed_total, outcome.agent, outcome.team
        );
    }

    println!(
        "Acknowledged: {} | Read: {} | Remaining: {}",
        outcome.removed_by_class.acknowledged,
        outcome.removed_by_class.read,
        outcome.remaining_total
    );

    Ok(())
}

/// Print one retained log snapshot in human-readable or JSON form.
pub fn print_log_snapshot(snapshot: &AtmLogSnapshot, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(snapshot)?);
        return Ok(());
    }

    for record in &snapshot.records {
        print_log_record_line(record);
    }

    Ok(())
}

/// Print one stream of retained log records in human-readable or JSON form.
pub fn print_log_records<I>(records: I, json: bool) -> Result<()>
where
    I: IntoIterator<Item = AtmLogRecord>,
{
    for record in records {
        if json {
            println!("{}", serde_json::to_string(&record)?);
        } else {
            print_log_record_line(&record);
        }
    }

    Ok(())
}

/// Print one doctor report in human-readable or JSON form.
pub fn print_doctor_result(report: &DoctorReport, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(report)?);
        return Ok(());
    }

    print_doctor_summary(report);
    print_doctor_observability(report);
    print_doctor_post_send(report);
    println!(
        "Logging health: {} | Query readiness: {}",
        render_doctor_state(report.observability.logging_state),
        report
            .observability
            .query_state
            .map(render_doctor_state)
            .unwrap_or("unknown")
    );
    if let Some(runtime_status) = &report.runtime_status {
        print_runtime_status(runtime_status);
    }
    if let Some(bootstrap_trace) = &report.bootstrap_trace {
        print_bootstrap_trace(bootstrap_trace);
    }
    print_doctor_environment(report);
    print_doctor_findings(report);
    print_doctor_roster(report);
    print_doctor_recommendations(report);

    Ok(())
}

fn print_doctor_post_send(report: &DoctorReport) {
    let post_send = &report.post_send;
    if post_send.config_root.as_os_str().is_empty()
        && post_send.external_rules.is_empty()
        && post_send.recipient_paths.is_empty()
    {
        return;
    }
    println!(
        "Post-send configuration: {}",
        post_send.config_root.display()
    );
    for rule in &post_send.external_rules {
        println!(
            "  override recipient={} executable={} argv={:?}",
            rule.recipient_matcher,
            rule.executable.display(),
            rule.argv
        );
    }
    for recipient in &post_send.recipient_paths {
        println!(
            "  recipient={} path={:?}",
            recipient.recipient, recipient.path
        );
    }
}

fn print_doctor_summary(report: &DoctorReport) {
    println!(
        "Doctor status: {}",
        render_doctor_status(report.summary.status)
    );
    println!("{}", report.summary.message);
}

fn print_doctor_observability(report: &DoctorReport) {
    println!(
        "Active log path: {}",
        report
            .observability
            .active_log_path
            .as_ref()
            .map(|path| path.display().to_string())
            .unwrap_or_else(|| "<unavailable>".to_string())
    );
    if let Some(maintenance) = &report.observability.maintenance {
        println!(
            "Maintenance: {} | Rotated: {} | Pruned: {} | Last pass: {}",
            render_maintenance_state(maintenance.state),
            maintenance.rotated_files_total,
            maintenance.pruned_files_total,
            maintenance
                .last_pass_at
                .map(|timestamp| timestamp.into_inner().to_string())
                .unwrap_or_else(|| "never".to_string())
        );
    }
}

fn print_doctor_environment(report: &DoctorReport) {
    if report.environment.atm_home.is_none()
        && report.environment.atm_team.is_none()
        && report.environment.atm_identity.is_none()
        && report.environment.team_override.is_none()
        && report.client_context.team.is_none()
        && report.client_context.identity.is_none()
        && report.client_context.version.is_none()
        && report.daemon_context.as_ref().is_none_or(|context| {
            context.team.is_none() && context.identity.is_none() && context.version.is_none()
        })
    {
        return;
    }

    println!();
    println!("Environment:");
    if let Some(path) = &report.environment.atm_home {
        println!("  ATM_HOME={}", path.display());
    }
    if let Some(team) = &report.environment.atm_team {
        println!("  ATM_TEAM={team}");
    }
    if let Some(identity) = &report.environment.atm_identity {
        println!("  ATM_IDENTITY={identity}");
    }
    if let Some(team_override) = &report.environment.team_override {
        println!("  --team={team_override}");
    }
    if report.client_context.team.is_some()
        || report.client_context.identity.is_some()
        || report.client_context.version.is_some()
    {
        println!("  client_context:");
        if let Some(team) = &report.client_context.team {
            println!("    team={team}");
        }
        if let Some(identity) = &report.client_context.identity {
            println!("    identity={identity}");
        }
        if let Some(version) = &report.client_context.version {
            println!("    version={version}");
        }
    }
    if let Some(daemon_context) = &report.daemon_context
        && (daemon_context.team.is_some()
            || daemon_context.identity.is_some()
            || daemon_context.version.is_some())
    {
        println!("  daemon_context:");
        if let Some(team) = &daemon_context.team {
            println!("    team={team}");
        }
        if let Some(identity) = &daemon_context.identity {
            println!("    identity={identity}");
        }
        if let Some(version) = &daemon_context.version {
            println!("    version={version}");
        }
    }
}

fn print_doctor_findings(report: &DoctorReport) {
    if report.findings.is_empty() {
        return;
    }

    println!();
    println!("Findings:");
    for finding in &report.findings {
        println!(
            "  [{}] {} {}",
            render_finding_severity(finding.severity),
            finding.code,
            finding.message
        );
        if let Some(remediation) = &finding.remediation {
            println!("    remediation: {remediation}");
        }
    }
}

fn print_doctor_roster(report: &DoctorReport) {
    let Some(roster) = &report.member_roster else {
        return;
    };
    println!();
    println!("Members: {}", roster.team);
    for member in &roster.members {
        let home_dir = member.home_dir.as_path().display().to_string();
        println!(
            "  {} | type={} model={} home_dir={} live_cwd={} pane={}",
            member.name,
            empty_dash(&member.agent_type),
            empty_dash(&member.model),
            empty_dash(&home_dir),
            empty_dash_opt(member.live_cwd.as_deref()),
            empty_dash_opt(member.tmux_pane_id.as_deref())
        );
    }
}

fn print_doctor_recommendations(report: &DoctorReport) {
    if report.recommendations.is_empty() {
        return;
    }

    println!();
    println!("Recommendations:");
    for recommendation in &report.recommendations {
        println!("  - {recommendation}");
    }
}

/// Print one teams listing in human-readable or JSON form.
pub fn print_teams_result(outcome: &TeamsList, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(outcome)?);
        return Ok(());
    }

    if outcome.teams.is_empty() {
        println!("No teams found");
        return Ok(());
    }

    println!("Teams:");
    for team in &outcome.teams {
        println!("  {} ({})", team.name, team.member_count);
    }
    Ok(())
}

/// Print one members listing in human-readable or JSON form.
pub fn print_members_result(outcome: &MembersList, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(outcome)?);
        return Ok(());
    }

    println!("Team: {}", outcome.team);
    if outcome.members.is_empty() {
        println!("  No members");
        return Ok(());
    }

    for member in &outcome.members {
        let home_dir = member.home_dir.as_path().display().to_string();
        println!(
            "  {} | type={} model={} home_dir={} live_cwd={} pane={}",
            member.name,
            empty_dash(&member.agent_type),
            empty_dash(&member.model),
            empty_dash(&home_dir),
            empty_dash_opt(member.live_cwd.as_deref()),
            empty_dash_opt(member.tmux_pane_id.as_deref())
        );
    }
    Ok(())
}

/// Print one add-member result in human-readable or JSON form.
pub fn print_add_member_result(outcome: &AddMemberOutcome, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(outcome)?);
    } else {
        println!(
            "Added member {} to {} (created_inbox: {})",
            outcome.member, outcome.team, outcome.created_inbox
        );
    }
    Ok(())
}

/// Print one update-member result in human-readable or JSON form.
pub fn print_update_member_result(outcome: &UpdateMemberOutcome, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(outcome)?);
    } else {
        println!("Updated member {} in {}", outcome.member, outcome.team);
    }
    Ok(())
}

/// Print one set-nudge-template result in human-readable or JSON form.
pub fn print_set_nudge_template_override_result(
    outcome: &SetNudgeTemplateOverrideOutcome,
    json: bool,
) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(outcome)?);
    } else {
        println!(
            "Set nudge template override {} for {} at {}",
            outcome.kind, outcome.team, outcome.updated_at
        );
    }
    Ok(())
}

/// Print one disable-nudge-template result in human-readable or JSON form.
pub fn print_disable_nudge_template_override_result(
    outcome: &DisableNudgeTemplateOverrideOutcome,
    json: bool,
) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(outcome)?);
    } else {
        println!(
            "Disabled nudge template override {} for {} at {}",
            outcome.kind, outcome.team, outcome.updated_at
        );
    }
    Ok(())
}

/// Print one clear-nudge-template result in human-readable or JSON form.
pub fn print_clear_nudge_template_override_result(
    outcome: &ClearNudgeTemplateOverrideOutcome,
    json: bool,
) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(outcome)?);
    } else {
        let status = if outcome.cleared {
            "cleared"
        } else {
            "already at product default"
        };
        println!(
            "Clear nudge template override {} for {}: {}",
            outcome.kind, outcome.team, status
        );
    }
    Ok(())
}

/// Print one backup result in human-readable or JSON form.
pub fn print_backup_result(outcome: &BackupOutcome, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(outcome)?);
    } else {
        println!("Backup created: {}", outcome.backup_path.display());
    }
    Ok(())
}

/// Print one restore dry-run plan in human-readable or JSON form.
pub fn print_restore_plan(plan: &RestorePlan, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(plan)?);
        return Ok(());
    }

    println!(
        "Dry run — would restore from: {}",
        plan.backup_path.display()
    );
    println!(
        "  Members: {}",
        plan.would_restore_members
            .iter()
            .map(|member| member.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    );
    println!("  Inboxes: {}", plan.would_restore_inboxes.join(", "));
    println!("  Tasks: {}", plan.would_restore_tasks);
    Ok(())
}

/// Print one applied restore result in human-readable or JSON form.
pub fn print_restore_result(outcome: &RestoreOutcome, json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(outcome)?);
    } else {
        println!("Restored from: {}", outcome.backup_path.display());
        println!(
            "  members={} inboxes={} tasks={}",
            outcome.members_restored, outcome.inboxes_restored, outcome.tasks_restored
        );
    }
    Ok(())
}

fn empty_dash(value: &str) -> &str {
    if value.is_empty() { "-" } else { value }
}

fn empty_dash_opt(value: Option<&str>) -> &str {
    value.filter(|value| !value.is_empty()).unwrap_or("-")
}

fn print_log_record_line(record: &AtmLogRecord) {
    let target = record.target.as_deref().unwrap_or("-");
    let action = record.action.as_deref().unwrap_or("-");
    let message = record.message.as_deref().unwrap_or("");

    println!(
        "{} {:?} {} {} {}",
        record.timestamp.into_inner().to_rfc3339(),
        record.level,
        record.service,
        target,
        action
    );

    if !message.is_empty() {
        println!("  {message}");
    }

    if !record.fields.is_empty() {
        println!(
            "  fields: {}",
            serde_json::to_string(&record.fields).unwrap_or_else(|_| "{}".to_string())
        );
    }
}

fn render_doctor_state(
    state: atm_core::observability::AtmObservabilityHealthState,
) -> &'static str {
    match state {
        atm_core::observability::AtmObservabilityHealthState::Healthy => "healthy",
        atm_core::observability::AtmObservabilityHealthState::Degraded => "degraded",
        atm_core::observability::AtmObservabilityHealthState::Unavailable => "unavailable",
    }
}

fn render_doctor_status(status: DoctorStatus) -> &'static str {
    match status {
        DoctorStatus::Healthy => "healthy",
        DoctorStatus::Warning => "warning",
        DoctorStatus::Error => "error",
    }
}

fn render_maintenance_state(
    state: atm_core::observability::AtmMaintenanceWorkerState,
) -> &'static str {
    match state {
        atm_core::observability::AtmMaintenanceWorkerState::Running => "running",
        atm_core::observability::AtmMaintenanceWorkerState::Degraded => "degraded",
        atm_core::observability::AtmMaintenanceWorkerState::Stopped => "stopped",
    }
}

fn render_finding_severity(severity: DoctorSeverity) -> &'static str {
    match severity {
        DoctorSeverity::Info => "info",
        DoctorSeverity::Warning => "warning",
        DoctorSeverity::Error => "error",
    }
}

fn print_runtime_status(runtime_status: &RuntimeStatusSnapshot) {
    println!();
    println!("Runtime status:");
    println!(
        "  Liveness: {} | Readiness: {}",
        render_runtime_liveness(runtime_status.liveness),
        render_runtime_readiness(runtime_status.readiness)
    );
    println!(
        "  Members: active={} idle={} offline={} unknown={}",
        runtime_status.member_counts.active_members,
        runtime_status.member_counts.idle_members,
        runtime_status.member_counts.offline_members,
        runtime_status.member_counts.unknown_members
    );
    println!(
        "  Degraded ingest: {}",
        render_bool(runtime_status.degraded_ingest)
    );
    if let Some(owner_pid) = runtime_status.singleton_owner_pid {
        println!("  Singleton owner pid: {owner_pid}");
    }
    if let Some(detail) = &runtime_status.detail {
        println!("  Detail: {detail}");
    }
}

fn print_bootstrap_trace(trace: &BootstrapTraceReport) {
    print!("{}", render_bootstrap_trace_section(trace));
}

fn render_runtime_liveness(state: RuntimeLivenessState) -> &'static str {
    match state {
        RuntimeLivenessState::Running => "running",
        RuntimeLivenessState::Unavailable => "unavailable",
    }
}

fn render_runtime_readiness(state: RuntimeReadinessState) -> &'static str {
    match state {
        RuntimeReadinessState::Ready => "ready",
        RuntimeReadinessState::Degraded => "degraded",
        RuntimeReadinessState::Unavailable => "unavailable",
    }
}

fn render_bootstrap_connect(state: BootstrapConnectOutcome) -> &'static str {
    match state {
        BootstrapConnectOutcome::Connected => "connected",
        BootstrapConnectOutcome::NotFound => "not_found",
        BootstrapConnectOutcome::Timeout => "timeout",
        BootstrapConnectOutcome::Failed => "failed",
    }
}

fn render_bootstrap_launch_gate(state: BootstrapLaunchGateOutcome) -> &'static str {
    match state {
        BootstrapLaunchGateOutcome::Launched => "launched",
        BootstrapLaunchGateOutcome::Failed => "failed",
        BootstrapLaunchGateOutcome::Skipped => "skipped",
    }
}

fn render_bootstrap_auto_start(state: BootstrapAutoStartOutcome) -> &'static str {
    match state {
        BootstrapAutoStartOutcome::AutoStarted => "auto_started",
        BootstrapAutoStartOutcome::Failed => "failed",
        BootstrapAutoStartOutcome::Skipped => "skipped",
    }
}

fn render_bool(value: bool) -> &'static str {
    if value { "yes" } else { "no" }
}

fn render_bootstrap_trace_section(trace: &BootstrapTraceReport) -> String {
    let mut output = String::from("\nBootstrap trace:\n");
    output.push_str(&format!(
        "  Daemon connect: {}\n",
        render_bootstrap_connect(trace.daemon_connect)
    ));
    output.push_str(&format!(
        "  Launch gate: {}\n",
        render_bootstrap_launch_gate(trace.daemon_launch_gate)
    ));
    output.push_str(&format!(
        "  Auto-start: {}\n",
        render_bootstrap_auto_start(trace.daemon_auto_start)
    ));
    if let Some(detail) = &trace.connect_detail {
        output.push_str(&format!("  Connect detail: {detail}\n"));
    }
    if let Some(detail) = &trace.launch_gate_detail {
        output.push_str(&format!("  Launch-gate detail: {detail}\n"));
    }
    if let Some(detail) = &trace.auto_start_detail {
        output.push_str(&format!("  Auto-start detail: {detail}\n"));
    }
    output
}

#[cfg(test)]
mod tests {
    use atm_core::ack::AckOutcome;
    use atm_core::doctor::{
        BootstrapAutoStartOutcome, BootstrapConnectOutcome, BootstrapLaunchGateOutcome,
        BootstrapTraceReport,
    };
    use serde_json::json;

    use super::{render_ack_result_line, render_bootstrap_trace_section};

    #[test]
    fn bootstrap_trace_section_renders_doctor_output_block() {
        let rendered = render_bootstrap_trace_section(&BootstrapTraceReport {
            daemon_connect: BootstrapConnectOutcome::Connected,
            daemon_launch_gate: BootstrapLaunchGateOutcome::Launched,
            daemon_auto_start: BootstrapAutoStartOutcome::AutoStarted,
            connect_detail: Some("connect detail".to_string()),
            launch_gate_detail: None,
            auto_start_detail: Some("auto-start detail".to_string()),
        });

        assert!(rendered.contains("Bootstrap trace:"));
        assert!(rendered.contains("Daemon connect: connected"));
        assert!(rendered.contains("Launch gate: launched"));
        assert!(rendered.contains("Auto-start: auto_started"));
        assert!(rendered.contains("Connect detail: connect detail"));
        assert!(rendered.contains("Auto-start detail: auto-start detail"));
    }

    #[test]
    fn ack_output_renders_suppressed_self_ack_human_line() {
        let outcome: AckOutcome = serde_json::from_value(json!({
            "action": "ack",
            "team": "test-team",
            "agent": "sender-a",
            "message_id": "01KX5TEST00000000000000001",
            "task_id": null,
            "reply_disposition": {
                "kind": "suppressed_self_ack"
            },
            "reply_text": "already on it",
            "warnings": []
        }))
        .expect("ack outcome");

        let rendered = render_ack_result_line(&outcome);
        assert!(rendered.contains("suppressed the self-ack reply"));
        assert!(rendered.contains("01KX5TEST00000000000000001"));
    }

    #[test]
    fn ack_output_json_shape_preserves_sent_reply_disposition() {
        let outcome: AckOutcome = serde_json::from_value(json!({
            "action": "ack",
            "team": "test-team",
            "agent": "sender-a",
            "message_id": "01KX5TEST00000000000000002",
            "task_id": null,
            "reply_disposition": {
                "kind": "sent",
                "reply_target": "team-lead@test-team",
                "reply_message_id": "01KX5TEST00000000000000003"
            },
            "reply_text": "received",
            "warnings": []
        }))
        .expect("ack outcome");

        let rendered = serde_json::to_value(&outcome).expect("json outcome");
        assert_eq!(rendered["reply_disposition"]["kind"], "sent");
        assert_eq!(
            rendered["reply_disposition"]["reply_target"],
            "team-lead@test-team"
        );
        assert_eq!(
            rendered["reply_disposition"]["reply_message_id"],
            "01KX5TEST00000000000000003"
        );
    }
}