Skip to main content

batty_cli/team/
session.rs

1//! Session lifecycle: pause/resume, nudge management, stop/attach/status/validate.
2//!
3//! Extracted from `lifecycle.rs` — pure refactor, zero logic changes.
4
5use std::path::Path;
6use std::path::PathBuf;
7
8use anyhow::{Context, Result, bail};
9use tracing::{info, warn};
10
11use super::daemon_mgmt::{
12    DAEMON_SHUTDOWN_GRACE_PERIOD, force_kill_daemon, request_graceful_daemon_shutdown,
13    resume_marker_path,
14};
15use super::{
16    config, estimation, events, hierarchy, now_unix, status, team_config_path, team_events_path,
17};
18use crate::tmux;
19
20/// Path to the pause marker file. Presence pauses nudges and standups.
21pub fn pause_marker_path(project_root: &Path) -> PathBuf {
22    project_root.join(".batty").join("paused")
23}
24
25/// Create the pause marker file, pausing nudges and standups.
26pub fn pause_team(project_root: &Path) -> Result<()> {
27    let marker = pause_marker_path(project_root);
28    if marker.exists() {
29        bail!("Team is already paused.");
30    }
31    if let Some(parent) = marker.parent() {
32        std::fs::create_dir_all(parent).ok();
33    }
34    std::fs::write(&marker, "").context("failed to write pause marker")?;
35    info!("paused nudges and standups");
36    Ok(())
37}
38
39/// Remove the pause marker file, resuming nudges and standups.
40pub fn resume_team(project_root: &Path) -> Result<()> {
41    let marker = pause_marker_path(project_root);
42    if !marker.exists() {
43        bail!("Team is not paused.");
44    }
45    std::fs::remove_file(&marker).context("failed to remove pause marker")?;
46    info!("resumed nudges and standups");
47    Ok(())
48}
49
50/// Path to the nudge-disabled marker for a given intervention.
51pub fn nudge_disabled_marker_path(project_root: &Path, intervention: &str) -> PathBuf {
52    project_root
53        .join(".batty")
54        .join(format!("nudge_{intervention}_disabled"))
55}
56
57/// Create a nudge-disabled marker file, disabling the intervention at runtime.
58pub fn disable_nudge(project_root: &Path, intervention: &str) -> Result<()> {
59    let marker = nudge_disabled_marker_path(project_root, intervention);
60    if marker.exists() {
61        bail!("Intervention '{intervention}' is already disabled.");
62    }
63    if let Some(parent) = marker.parent() {
64        std::fs::create_dir_all(parent).ok();
65    }
66    std::fs::write(&marker, "").context("failed to write nudge disabled marker")?;
67    info!(intervention, "disabled intervention");
68    Ok(())
69}
70
71/// Remove a nudge-disabled marker file, re-enabling the intervention.
72pub fn enable_nudge(project_root: &Path, intervention: &str) -> Result<()> {
73    let marker = nudge_disabled_marker_path(project_root, intervention);
74    if !marker.exists() {
75        bail!("Intervention '{intervention}' is not disabled.");
76    }
77    std::fs::remove_file(&marker).context("failed to remove nudge disabled marker")?;
78    info!(intervention, "enabled intervention");
79    Ok(())
80}
81
82/// Print a table showing config, runtime, and effective state for each intervention.
83pub fn nudge_status(project_root: &Path) -> Result<()> {
84    use crate::cli::NudgeIntervention;
85
86    let config_path = team_config_path(project_root);
87    let automation = if config_path.exists() {
88        let team_config = config::TeamConfig::load(&config_path)?;
89        Some(team_config.automation)
90    } else {
91        None
92    };
93
94    println!(
95        "{:<16} {:<10} {:<10} {:<10}",
96        "INTERVENTION", "CONFIG", "RUNTIME", "EFFECTIVE"
97    );
98
99    for intervention in NudgeIntervention::ALL {
100        let name = intervention.marker_name();
101        let config_enabled = automation
102            .as_ref()
103            .map(|a| match intervention {
104                NudgeIntervention::Replenish => true, // no dedicated config flag
105                NudgeIntervention::Triage => a.triage_interventions,
106                NudgeIntervention::Review => a.review_interventions,
107                NudgeIntervention::Dispatch => a.manager_dispatch_interventions,
108                NudgeIntervention::Utilization => a.architect_utilization_interventions,
109                NudgeIntervention::OwnedTask => a.owned_task_interventions,
110            })
111            .unwrap_or(true);
112
113        let runtime_disabled = nudge_disabled_marker_path(project_root, name).exists();
114        let runtime_str = if runtime_disabled {
115            "disabled"
116        } else {
117            "enabled"
118        };
119        let config_str = if config_enabled {
120            "enabled"
121        } else {
122            "disabled"
123        };
124        let effective = config_enabled && !runtime_disabled;
125        let effective_str = if effective { "enabled" } else { "DISABLED" };
126
127        println!(
128            "{:<16} {:<10} {:<10} {:<10}",
129            name, config_str, runtime_str, effective_str
130        );
131    }
132
133    Ok(())
134}
135
136/// Stop a running team session and clean up any orphaned `batty-` sessions.
137/// Summary statistics for a completed session.
138#[derive(Debug, Clone, PartialEq, Eq)]
139pub(crate) struct SessionSummary {
140    pub tasks_completed: u32,
141    pub tasks_merged: u32,
142    pub runtime_secs: u64,
143}
144
145impl SessionSummary {
146    pub fn display(&self) -> String {
147        format!(
148            "Session summary: {} tasks completed, {} merged, runtime {}",
149            self.tasks_completed,
150            self.tasks_merged,
151            format_runtime(self.runtime_secs),
152        )
153    }
154}
155
156fn format_runtime(secs: u64) -> String {
157    if secs < 60 {
158        format!("{secs}s")
159    } else if secs < 3600 {
160        format!("{}m", secs / 60)
161    } else {
162        let hours = secs / 3600;
163        let mins = (secs % 3600) / 60;
164        if mins == 0 {
165            format!("{hours}h")
166        } else {
167            format!("{hours}h {mins}m")
168        }
169    }
170}
171
172/// Compute session summary from the event log.
173///
174/// Finds the most recent `daemon_started` event and counts completions and
175/// merges that occurred after it. Runtime is calculated from the daemon start
176/// timestamp to now.
177pub(crate) fn compute_session_summary(project_root: &Path) -> Option<SessionSummary> {
178    let events_path = team_events_path(project_root);
179    let all_events = events::read_events(&events_path).ok()?;
180
181    // Find the most recent daemon_started event.
182    let session_start = all_events
183        .iter()
184        .rev()
185        .find(|e| e.event == "daemon_started")?;
186    let start_ts = session_start.ts;
187    let now_ts = now_unix();
188
189    let session_events: Vec<_> = all_events.iter().filter(|e| e.ts >= start_ts).collect();
190
191    let tasks_completed = session_events
192        .iter()
193        .filter(|e| e.event == "task_completed")
194        .count() as u32;
195
196    let tasks_merged = session_events
197        .iter()
198        .filter(|e| e.event == "task_auto_merged" || e.event == "task_manual_merged")
199        .count() as u32;
200
201    let runtime_secs = now_ts.saturating_sub(start_ts);
202
203    Some(SessionSummary {
204        tasks_completed,
205        tasks_merged,
206        runtime_secs,
207    })
208}
209
210pub fn stop_team(project_root: &Path) -> Result<()> {
211    // Compute session summary before shutting down (events log is still available).
212    let summary = compute_session_summary(project_root);
213
214    // Write resume marker before tearing down — agents have sessions to continue
215    let marker = resume_marker_path(project_root);
216    if let Some(parent) = marker.parent() {
217        std::fs::create_dir_all(parent).ok();
218    }
219    std::fs::write(&marker, "").ok();
220
221    // Ask the daemon to persist a final clean snapshot before the tmux session is torn down.
222    if !request_graceful_daemon_shutdown(project_root, DAEMON_SHUTDOWN_GRACE_PERIOD) {
223        warn!("daemon did not stop gracefully; forcing shutdown");
224        force_kill_daemon(project_root);
225    }
226
227    let config_path = team_config_path(project_root);
228    let primary_session = if config_path.exists() {
229        let team_config = config::TeamConfig::load(&config_path)?;
230        Some(format!("batty-{}", team_config.name))
231    } else {
232        None
233    };
234
235    // Kill only the session belonging to this project
236    match &primary_session {
237        Some(session) if tmux::session_exists(session) => {
238            tmux::kill_session(session)?;
239            info!(session = %session, "team session stopped");
240        }
241        Some(session) => {
242            info!(session = %session, "no running session to stop");
243        }
244        None => {
245            bail!("no team config found at {}", config_path.display());
246        }
247    }
248
249    // Print session summary after teardown.
250    if let Some(summary) = summary {
251        println!();
252        println!("{}", summary.display());
253    }
254
255    Ok(())
256}
257
258/// Attach to a running team session.
259///
260/// First tries the team config in the project root. If not found, looks for
261/// any running `batty-*` tmux session and attaches to it.
262pub fn attach_team(project_root: &Path) -> Result<()> {
263    let config_path = team_config_path(project_root);
264
265    let session = if config_path.exists() {
266        let team_config = config::TeamConfig::load(&config_path)?;
267        format!("batty-{}", team_config.name)
268    } else {
269        // No local config — find any running batty session
270        let mut sessions = tmux::list_sessions_with_prefix("batty-");
271        match sessions.len() {
272            0 => bail!("no team config found and no batty sessions running"),
273            1 => sessions.swap_remove(0),
274            _ => {
275                let list = sessions.join(", ");
276                bail!(
277                    "no team config found and multiple batty sessions running: {list}\n\
278                     Run from the project directory, or use: tmux attach -t <session>"
279                );
280            }
281        }
282    };
283
284    if !tmux::session_exists(&session) {
285        bail!("no running session '{session}'; run `batty start` first");
286    }
287
288    tmux::attach(&session)
289}
290
291/// Show team status.
292pub fn team_status(project_root: &Path, json: bool) -> Result<()> {
293    let config_path = team_config_path(project_root);
294    if !config_path.exists() {
295        bail!("no team config found at {}", config_path.display());
296    }
297
298    let team_config = config::TeamConfig::load(&config_path)?;
299    let members = hierarchy::resolve_hierarchy(&team_config)?;
300    let session = format!("batty-{}", team_config.name);
301    let session_running = tmux::session_exists(&session);
302    let runtime_statuses = if session_running {
303        match status::list_runtime_member_statuses(&session) {
304            Ok(statuses) => statuses,
305            Err(error) => {
306                warn!(session = %session, error = %error, "failed to read live runtime statuses");
307                std::collections::HashMap::new()
308            }
309        }
310    } else {
311        std::collections::HashMap::new()
312    };
313    let pending_inbox_counts = status::pending_inbox_counts(project_root, &members);
314    let triage_backlog_counts = status::triage_backlog_counts(project_root, &members);
315    let owned_task_buckets = status::owned_task_buckets(project_root, &members);
316    let agent_health = status::agent_health_by_member(project_root, &members);
317    let paused = pause_marker_path(project_root).exists();
318    let mut rows = status::build_team_status_rows(
319        &members,
320        session_running,
321        &runtime_statuses,
322        &pending_inbox_counts,
323        &triage_backlog_counts,
324        &owned_task_buckets,
325        &agent_health,
326    );
327
328    // Populate ETA estimates for members with active tasks.
329    let active_task_elapsed: Vec<(u32, u64)> = rows
330        .iter()
331        .filter(|row| !row.active_owned_tasks.is_empty())
332        .flat_map(|row| {
333            let elapsed = row.health.task_elapsed_secs.unwrap_or(0);
334            row.active_owned_tasks
335                .iter()
336                .map(move |&task_id| (task_id, elapsed))
337        })
338        .collect();
339    let etas = estimation::compute_etas(project_root, &active_task_elapsed);
340    for row in &mut rows {
341        if let Some(&task_id) = row.active_owned_tasks.first() {
342            if let Some(eta) = etas.get(&task_id) {
343                row.eta = eta.clone();
344            }
345        }
346    }
347
348    let workflow_metrics = status::workflow_metrics_section(project_root, &members);
349    let (active_tasks, review_queue) = match status::board_status_task_queues(project_root) {
350        Ok(queues) => queues,
351        Err(error) => {
352            warn!(error = %error, "failed to load board task queues for status json");
353            (Vec::new(), Vec::new())
354        }
355    };
356
357    if json {
358        let report = status::build_team_status_json_report(status::TeamStatusJsonReportInput {
359            team: team_config.name.clone(),
360            session: session.clone(),
361            session_running,
362            paused,
363            workflow_metrics: workflow_metrics
364                .as_ref()
365                .map(|(_, metrics)| metrics.clone()),
366            active_tasks,
367            review_queue,
368            members: rows,
369        });
370        println!("{}", serde_json::to_string_pretty(&report)?);
371    } else {
372        println!("Team: {}", team_config.name);
373        println!(
374            "Session: {} ({})",
375            session,
376            if session_running {
377                "running"
378            } else {
379                "stopped"
380            }
381        );
382        println!();
383        println!(
384            "{:<20} {:<12} {:<10} {:<12} {:>5} {:>6} {:<14} {:<14} {:<16} {:<18} {:<24} {:<20}",
385            "MEMBER",
386            "ROLE",
387            "AGENT",
388            "STATE",
389            "INBOX",
390            "TRIAGE",
391            "ACTIVE",
392            "REVIEW",
393            "ETA",
394            "HEALTH",
395            "SIGNAL",
396            "REPORTS TO"
397        );
398        println!("{}", "-".repeat(195));
399        for row in &rows {
400            println!(
401                "{:<20} {:<12} {:<10} {:<12} {:>5} {:>6} {:<14} {:<14} {:<16} {:<18} {:<24} {:<20}",
402                row.name,
403                row.role,
404                row.agent.as_deref().unwrap_or("-"),
405                row.state,
406                row.pending_inbox,
407                row.triage_backlog,
408                status::format_owned_tasks_summary(&row.active_owned_tasks),
409                status::format_owned_tasks_summary(&row.review_owned_tasks),
410                row.eta,
411                row.health_summary,
412                row.signal.as_deref().unwrap_or("-"),
413                row.reports_to.as_deref().unwrap_or("-"),
414            );
415        }
416        if let Some((formatted, _)) = workflow_metrics {
417            println!();
418            println!("{formatted}");
419        }
420    }
421
422    Ok(())
423}
424
425fn workflow_mode_declared(config_path: &Path) -> Result<bool> {
426    let content = std::fs::read_to_string(config_path)
427        .with_context(|| format!("failed to read {}", config_path.display()))?;
428    let value: serde_yaml::Value = serde_yaml::from_str(&content)
429        .with_context(|| format!("failed to parse {}", config_path.display()))?;
430    let Some(mapping) = value.as_mapping() else {
431        return Ok(false);
432    };
433
434    Ok(mapping.contains_key(serde_yaml::Value::String("workflow_mode".to_string())))
435}
436
437fn migration_validation_notes(
438    team_config: &config::TeamConfig,
439    workflow_mode_is_explicit: bool,
440) -> Vec<String> {
441    if !workflow_mode_is_explicit {
442        return vec![
443            "Migration: workflow_mode omitted; defaulting to legacy so existing teams and boards run unchanged.".to_string(),
444        ];
445    }
446
447    match team_config.workflow_mode {
448        config::WorkflowMode::Legacy => vec![
449            "Migration: legacy mode selected; Batty keeps current runtime behavior and treats workflow metadata as optional.".to_string(),
450        ],
451        config::WorkflowMode::Hybrid => vec![
452            "Migration: hybrid mode selected; workflow adoption is incremental and legacy runtime behavior remains available.".to_string(),
453        ],
454        config::WorkflowMode::WorkflowFirst => vec![
455            "Migration: workflow_first mode selected; complete board metadata and orchestrator rollout before treating workflow state as primary truth.".to_string(),
456        ],
457    }
458}
459
460/// Validate team config without launching.
461pub fn validate_team(project_root: &Path, verbose: bool) -> Result<()> {
462    let config_path = team_config_path(project_root);
463    if !config_path.exists() {
464        bail!("no team config found at {}", config_path.display());
465    }
466
467    let team_config = config::TeamConfig::load(&config_path)?;
468
469    if verbose {
470        let checks = team_config.validate_verbose();
471        let mut any_failed = false;
472        for check in &checks {
473            let status = if check.passed { "PASS" } else { "FAIL" };
474            println!("[{status}] {}: {}", check.name, check.detail);
475            if !check.passed {
476                any_failed = true;
477            }
478        }
479        if any_failed {
480            bail!("validation failed — see FAIL checks above");
481        }
482    } else {
483        team_config.validate()?;
484    }
485
486    let workflow_mode_is_explicit = workflow_mode_declared(&config_path)?;
487
488    let members = hierarchy::resolve_hierarchy(&team_config)?;
489
490    println!("Config: {}", config_path.display());
491    println!("Team: {}", team_config.name);
492    println!(
493        "Workflow mode: {}",
494        match team_config.workflow_mode {
495            config::WorkflowMode::Legacy => "legacy",
496            config::WorkflowMode::Hybrid => "hybrid",
497            config::WorkflowMode::WorkflowFirst => "workflow_first",
498        }
499    );
500    println!("Roles: {}", team_config.roles.len());
501    println!("Total members: {}", members.len());
502
503    // Backend health checks — warn about missing binaries but don't fail validation.
504    let backend_warnings = team_config.check_backend_health();
505    for warning in &backend_warnings {
506        println!("[WARN] {warning}");
507    }
508
509    for note in migration_validation_notes(&team_config, workflow_mode_is_explicit) {
510        println!("{note}");
511    }
512    println!("Valid.");
513    Ok(())
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519    use crate::team::TRIAGE_RESULT_FRESHNESS_SECONDS;
520    use crate::team::config::RoleType;
521    use crate::team::hierarchy;
522    use crate::team::inbox;
523    use crate::team::status;
524    use crate::team::team_config_dir;
525    use crate::team::team_config_path;
526    use serial_test::serial;
527
528    #[test]
529    fn nudge_disable_creates_marker_and_enable_removes_it() {
530        let tmp = tempfile::tempdir().unwrap();
531        std::fs::create_dir_all(tmp.path().join(".batty")).unwrap();
532
533        let marker = nudge_disabled_marker_path(tmp.path(), "triage");
534        assert!(!marker.exists());
535
536        disable_nudge(tmp.path(), "triage").unwrap();
537        assert!(marker.exists());
538
539        // Double-disable should fail
540        assert!(disable_nudge(tmp.path(), "triage").is_err());
541
542        enable_nudge(tmp.path(), "triage").unwrap();
543        assert!(!marker.exists());
544
545        // Double-enable should fail
546        assert!(enable_nudge(tmp.path(), "triage").is_err());
547    }
548
549    #[test]
550    fn nudge_marker_path_uses_intervention_name() {
551        let root = std::path::Path::new("/tmp/test-project");
552        assert_eq!(
553            nudge_disabled_marker_path(root, "replenish"),
554            root.join(".batty").join("nudge_replenish_disabled")
555        );
556        assert_eq!(
557            nudge_disabled_marker_path(root, "owned-task"),
558            root.join(".batty").join("nudge_owned-task_disabled")
559        );
560    }
561
562    #[test]
563    fn nudge_multiple_interventions_independent() {
564        let tmp = tempfile::tempdir().unwrap();
565        std::fs::create_dir_all(tmp.path().join(".batty")).unwrap();
566
567        disable_nudge(tmp.path(), "triage").unwrap();
568        disable_nudge(tmp.path(), "review").unwrap();
569
570        assert!(nudge_disabled_marker_path(tmp.path(), "triage").exists());
571        assert!(nudge_disabled_marker_path(tmp.path(), "review").exists());
572        assert!(!nudge_disabled_marker_path(tmp.path(), "dispatch").exists());
573
574        enable_nudge(tmp.path(), "triage").unwrap();
575        assert!(!nudge_disabled_marker_path(tmp.path(), "triage").exists());
576        assert!(nudge_disabled_marker_path(tmp.path(), "review").exists());
577    }
578
579    #[test]
580    fn pause_creates_marker_and_resume_removes_it() {
581        let tmp = tempfile::tempdir().unwrap();
582        std::fs::create_dir_all(tmp.path().join(".batty")).unwrap();
583
584        assert!(!pause_marker_path(tmp.path()).exists());
585        pause_team(tmp.path()).unwrap();
586        assert!(pause_marker_path(tmp.path()).exists());
587
588        // Double-pause should fail
589        assert!(pause_team(tmp.path()).is_err());
590
591        resume_team(tmp.path()).unwrap();
592        assert!(!pause_marker_path(tmp.path()).exists());
593
594        // Double-resume should fail
595        assert!(resume_team(tmp.path()).is_err());
596    }
597
598    fn write_team_config(project_root: &std::path::Path, yaml: &str) {
599        std::fs::create_dir_all(team_config_dir(project_root)).unwrap();
600        std::fs::write(team_config_path(project_root), yaml).unwrap();
601    }
602
603    #[test]
604    fn workflow_mode_declared_detects_absent_field() {
605        let tmp = tempfile::tempdir().unwrap();
606        write_team_config(
607            tmp.path(),
608            r#"
609name: test
610roles:
611  - name: engineer
612    role_type: engineer
613    agent: codex
614"#,
615        );
616
617        assert!(!workflow_mode_declared(&team_config_path(tmp.path())).unwrap());
618    }
619
620    #[test]
621    fn workflow_mode_declared_detects_present_field() {
622        let tmp = tempfile::tempdir().unwrap();
623        write_team_config(
624            tmp.path(),
625            r#"
626name: test
627workflow_mode: hybrid
628roles:
629  - name: engineer
630    role_type: engineer
631    agent: codex
632"#,
633        );
634
635        assert!(workflow_mode_declared(&team_config_path(tmp.path())).unwrap());
636    }
637
638    #[test]
639    fn migration_validation_notes_explain_legacy_default_for_older_configs() {
640        let config =
641            config::TeamConfig::load(std::path::Path::new("src/team/templates/team_pair.yaml"))
642                .unwrap();
643        let notes = migration_validation_notes(&config, false);
644
645        assert_eq!(notes.len(), 1);
646        assert!(notes[0].contains("workflow_mode omitted"));
647        assert!(notes[0].contains("run unchanged"));
648    }
649
650    #[test]
651    fn migration_validation_notes_warn_about_workflow_first_partial_rollout() {
652        let config: config::TeamConfig = serde_yaml::from_str(
653            r#"
654name: test
655workflow_mode: workflow_first
656roles:
657  - name: engineer
658    role_type: engineer
659    agent: codex
660"#,
661        )
662        .unwrap();
663        let notes = migration_validation_notes(&config, true);
664
665        assert_eq!(notes.len(), 1);
666        assert!(notes[0].contains("workflow_first mode selected"));
667        assert!(notes[0].contains("primary truth"));
668    }
669
670    fn make_member(name: &str, role_name: &str, role_type: RoleType) -> hierarchy::MemberInstance {
671        hierarchy::MemberInstance {
672            name: name.to_string(),
673            role_name: role_name.to_string(),
674            role_type,
675            agent: Some("codex".to_string()),
676            prompt: None,
677            reports_to: None,
678            use_worktrees: false,
679        }
680    }
681
682    #[test]
683    fn strip_tmux_style_removes_formatting_sequences() {
684        let raw = "#[fg=yellow]idle#[default] #[fg=magenta]nudge 1:05#[default]";
685        assert_eq!(status::strip_tmux_style(raw), "idle nudge 1:05");
686    }
687
688    #[test]
689    fn summarize_runtime_member_status_extracts_state_and_signal() {
690        let summary = status::summarize_runtime_member_status(
691            "#[fg=cyan]working#[default] #[fg=blue]standup 4:12#[default]",
692            false,
693        );
694
695        assert_eq!(summary.state, "working");
696        assert_eq!(summary.signal.as_deref(), Some("standup"));
697        assert_eq!(summary.label.as_deref(), Some("working standup 4:12"));
698    }
699
700    #[test]
701    fn summarize_runtime_member_status_marks_nudge_and_standup_together() {
702        let summary = status::summarize_runtime_member_status(
703            "#[fg=yellow]idle#[default] #[fg=magenta]nudge now#[default] #[fg=blue]standup 0:10#[default]",
704            false,
705        );
706
707        assert_eq!(summary.state, "idle");
708        assert_eq!(
709            summary.signal.as_deref(),
710            Some("waiting for nudge, standup")
711        );
712    }
713
714    #[test]
715    fn summarize_runtime_member_status_distinguishes_sent_nudge() {
716        let summary = status::summarize_runtime_member_status(
717            "#[fg=yellow]idle#[default] #[fg=magenta]nudge sent#[default]",
718            false,
719        );
720
721        assert_eq!(summary.state, "idle");
722        assert_eq!(summary.signal.as_deref(), Some("nudged"));
723        assert_eq!(summary.label.as_deref(), Some("idle nudge sent"));
724    }
725
726    #[test]
727    fn summarize_runtime_member_status_tracks_paused_automation() {
728        let summary = status::summarize_runtime_member_status(
729            "#[fg=cyan]working#[default] #[fg=244]nudge paused#[default] #[fg=244]standup paused#[default]",
730            false,
731        );
732
733        assert_eq!(summary.state, "working");
734        assert_eq!(
735            summary.signal.as_deref(),
736            Some("nudge paused, standup paused")
737        );
738        assert_eq!(
739            summary.label.as_deref(),
740            Some("working nudge paused standup paused")
741        );
742    }
743
744    #[test]
745    fn build_team_status_rows_defaults_by_session_state() {
746        let architect = make_member("architect", "architect", RoleType::Architect);
747        let human = hierarchy::MemberInstance {
748            name: "human".to_string(),
749            role_name: "human".to_string(),
750            role_type: RoleType::User,
751            agent: None,
752            prompt: None,
753            reports_to: None,
754            use_worktrees: false,
755        };
756
757        let pending = std::collections::HashMap::from([
758            (architect.name.clone(), 3usize),
759            (human.name.clone(), 1usize),
760        ]);
761        let triage = std::collections::HashMap::from([(architect.name.clone(), 2usize)]);
762        let owned = std::collections::HashMap::from([(
763            architect.name.clone(),
764            status::OwnedTaskBuckets {
765                active: vec![191u32],
766                review: vec![193u32],
767            },
768        )]);
769        let rows = status::build_team_status_rows(
770            &[architect.clone(), human.clone()],
771            false,
772            &Default::default(),
773            &pending,
774            &triage,
775            &owned,
776            &Default::default(),
777        );
778        assert_eq!(rows[0].state, "stopped");
779        assert_eq!(rows[0].pending_inbox, 3);
780        assert_eq!(rows[0].triage_backlog, 2);
781        assert_eq!(rows[0].active_owned_tasks, vec![191]);
782        assert_eq!(rows[0].review_owned_tasks, vec![193]);
783        assert_eq!(rows[0].health_summary, "-");
784        assert_eq!(rows[1].state, "user");
785        assert_eq!(rows[1].pending_inbox, 1);
786        assert_eq!(rows[1].triage_backlog, 0);
787        assert!(rows[1].active_owned_tasks.is_empty());
788        assert!(rows[1].review_owned_tasks.is_empty());
789
790        let runtime = std::collections::HashMap::from([(
791            architect.name.clone(),
792            status::RuntimeMemberStatus {
793                state: "idle".to_string(),
794                signal: Some("standup".to_string()),
795                label: Some("idle standup 2:00".to_string()),
796            },
797        )]);
798        let rows = status::build_team_status_rows(
799            &[architect],
800            true,
801            &runtime,
802            &pending,
803            &triage,
804            &owned,
805            &Default::default(),
806        );
807        assert_eq!(rows[0].state, "reviewing");
808        assert_eq!(rows[0].pending_inbox, 3);
809        assert_eq!(rows[0].triage_backlog, 2);
810        assert_eq!(rows[0].active_owned_tasks, vec![191]);
811        assert_eq!(rows[0].review_owned_tasks, vec![193]);
812        assert_eq!(
813            rows[0].signal.as_deref(),
814            Some("standup, needs triage (2), needs review (1)")
815        );
816        assert_eq!(rows[0].runtime_label.as_deref(), Some("idle standup 2:00"));
817    }
818
819    #[test]
820    fn delivered_direct_report_triage_count_only_counts_results_newer_than_lead_response() {
821        let tmp = tempfile::tempdir().unwrap();
822        let root = inbox::inboxes_root(tmp.path());
823        inbox::init_inbox(&root, "lead").unwrap();
824        inbox::init_inbox(&root, "eng-1").unwrap();
825        inbox::init_inbox(&root, "eng-2").unwrap();
826
827        let mut old_result = inbox::InboxMessage::new_send("eng-1", "lead", "old result");
828        old_result.timestamp = 10;
829        let old_result_id = inbox::deliver_to_inbox(&root, &old_result).unwrap();
830        inbox::mark_delivered(&root, "lead", &old_result_id).unwrap();
831
832        let mut lead_reply = inbox::InboxMessage::new_send("lead", "eng-1", "next task");
833        lead_reply.timestamp = 20;
834        let lead_reply_id = inbox::deliver_to_inbox(&root, &lead_reply).unwrap();
835        inbox::mark_delivered(&root, "eng-1", &lead_reply_id).unwrap();
836
837        let mut new_result = inbox::InboxMessage::new_send("eng-1", "lead", "new result");
838        new_result.timestamp = 30;
839        let new_result_id = inbox::deliver_to_inbox(&root, &new_result).unwrap();
840        inbox::mark_delivered(&root, "lead", &new_result_id).unwrap();
841
842        let mut other_result = inbox::InboxMessage::new_send("eng-2", "lead", "parallel result");
843        other_result.timestamp = 40;
844        let other_result_id = inbox::deliver_to_inbox(&root, &other_result).unwrap();
845        inbox::mark_delivered(&root, "lead", &other_result_id).unwrap();
846
847        let triage_state = status::delivered_direct_report_triage_state_at(
848            &root,
849            "lead",
850            &["eng-1".to_string(), "eng-2".to_string()],
851            100,
852        )
853        .unwrap();
854        assert_eq!(triage_state.count, 2);
855        assert_eq!(triage_state.newest_result_ts, 40);
856    }
857
858    #[test]
859    fn delivered_direct_report_triage_count_excludes_stale_delivered_results() {
860        let tmp = tempfile::tempdir().unwrap();
861        let root = inbox::inboxes_root(tmp.path());
862        inbox::init_inbox(&root, "lead").unwrap();
863        inbox::init_inbox(&root, "eng-1").unwrap();
864
865        let mut stale_result = inbox::InboxMessage::new_send("eng-1", "lead", "stale result");
866        stale_result.timestamp = 10;
867        let stale_result_id = inbox::deliver_to_inbox(&root, &stale_result).unwrap();
868        inbox::mark_delivered(&root, "lead", &stale_result_id).unwrap();
869
870        let triage_state = status::delivered_direct_report_triage_state_at(
871            &root,
872            "lead",
873            &["eng-1".to_string()],
874            10 + TRIAGE_RESULT_FRESHNESS_SECONDS + 1,
875        )
876        .unwrap();
877
878        assert_eq!(triage_state.count, 0);
879        assert_eq!(triage_state.newest_result_ts, 0);
880    }
881
882    #[test]
883    fn delivered_direct_report_triage_count_keeps_fresh_delivered_results() {
884        let tmp = tempfile::tempdir().unwrap();
885        let root = inbox::inboxes_root(tmp.path());
886        inbox::init_inbox(&root, "lead").unwrap();
887        inbox::init_inbox(&root, "eng-1").unwrap();
888
889        let mut fresh_result = inbox::InboxMessage::new_send("eng-1", "lead", "fresh result");
890        fresh_result.timestamp = 100;
891        let fresh_result_id = inbox::deliver_to_inbox(&root, &fresh_result).unwrap();
892        inbox::mark_delivered(&root, "lead", &fresh_result_id).unwrap();
893
894        let triage_state = status::delivered_direct_report_triage_state_at(
895            &root,
896            "lead",
897            &["eng-1".to_string()],
898            150,
899        )
900        .unwrap();
901
902        assert_eq!(triage_state.count, 1);
903        assert_eq!(triage_state.newest_result_ts, 100);
904    }
905
906    #[test]
907    fn delivered_direct_report_triage_count_excludes_acked_results() {
908        let tmp = tempfile::tempdir().unwrap();
909        let root = inbox::inboxes_root(tmp.path());
910        inbox::init_inbox(&root, "lead").unwrap();
911        inbox::init_inbox(&root, "eng-1").unwrap();
912
913        let mut result = inbox::InboxMessage::new_send("eng-1", "lead", "task complete");
914        result.timestamp = 100;
915        let result_id = inbox::deliver_to_inbox(&root, &result).unwrap();
916        inbox::mark_delivered(&root, "lead", &result_id).unwrap();
917
918        let mut lead_reply = inbox::InboxMessage::new_send("lead", "eng-1", "acknowledged");
919        lead_reply.timestamp = 110;
920        let lead_reply_id = inbox::deliver_to_inbox(&root, &lead_reply).unwrap();
921        inbox::mark_delivered(&root, "eng-1", &lead_reply_id).unwrap();
922
923        let triage_state = status::delivered_direct_report_triage_state_at(
924            &root,
925            "lead",
926            &["eng-1".to_string()],
927            150,
928        )
929        .unwrap();
930
931        assert_eq!(triage_state.count, 0);
932        assert_eq!(triage_state.newest_result_ts, 0);
933    }
934
935    #[test]
936    fn format_owned_tasks_summary_compacts_multiple_ids() {
937        assert_eq!(status::format_owned_tasks_summary(&[]), "-");
938        assert_eq!(status::format_owned_tasks_summary(&[191]), "#191");
939        assert_eq!(status::format_owned_tasks_summary(&[191, 192]), "#191,#192");
940        assert_eq!(
941            status::format_owned_tasks_summary(&[191, 192, 193]),
942            "#191,#192,+1"
943        );
944    }
945
946    #[test]
947    fn owned_task_buckets_split_active_and_review_claims() {
948        let tmp = tempfile::tempdir().unwrap();
949        let members = vec![
950            make_member("lead", "lead", RoleType::Manager),
951            hierarchy::MemberInstance {
952                name: "eng-1".to_string(),
953                role_name: "eng".to_string(),
954                role_type: RoleType::Engineer,
955                agent: Some("codex".to_string()),
956                prompt: None,
957                reports_to: Some("lead".to_string()),
958                use_worktrees: false,
959            },
960        ];
961        std::fs::create_dir_all(
962            tmp.path()
963                .join(".batty")
964                .join("team_config")
965                .join("board")
966                .join("tasks"),
967        )
968        .unwrap();
969        std::fs::write(
970            tmp.path()
971                .join(".batty")
972                .join("team_config")
973                .join("board")
974                .join("tasks")
975                .join("191-active.md"),
976            "---\nid: 191\ntitle: Active\nstatus: in-progress\npriority: high\nclaimed_by: eng-1\nclass: standard\n---\n",
977        )
978        .unwrap();
979        std::fs::write(
980            tmp.path()
981                .join(".batty")
982                .join("team_config")
983                .join("board")
984                .join("tasks")
985                .join("193-review.md"),
986            "---\nid: 193\ntitle: Review\nstatus: review\npriority: high\nclaimed_by: eng-1\nclass: standard\n---\n",
987        )
988        .unwrap();
989
990        let owned = status::owned_task_buckets(tmp.path(), &members);
991        let buckets = owned.get("eng-1").unwrap();
992        assert_eq!(buckets.active, vec![191]);
993        assert!(buckets.review.is_empty());
994        let review_buckets = owned.get("lead").unwrap();
995        assert!(review_buckets.active.is_empty());
996        assert_eq!(review_buckets.review, vec![193]);
997    }
998
999    #[test]
1000    fn workflow_metrics_enabled_detects_supported_modes() {
1001        let tmp = tempfile::tempdir().unwrap();
1002        let config_path = tmp.path().join("team.yaml");
1003
1004        std::fs::write(
1005            &config_path,
1006            "name: test\nworkflow_mode: hybrid\nroles: []\n",
1007        )
1008        .unwrap();
1009        assert!(status::workflow_metrics_enabled(&config_path));
1010
1011        std::fs::write(
1012            &config_path,
1013            "name: test\nworkflow_mode: workflow_first\nroles: []\n",
1014        )
1015        .unwrap();
1016        assert!(status::workflow_metrics_enabled(&config_path));
1017
1018        std::fs::write(&config_path, "name: test\nroles: []\n").unwrap();
1019        assert!(!status::workflow_metrics_enabled(&config_path));
1020    }
1021
1022    #[test]
1023    fn team_status_metrics_section_renders_when_workflow_mode_enabled() {
1024        let tmp = tempfile::tempdir().unwrap();
1025        let team_dir = tmp.path().join(".batty").join("team_config");
1026        let board_dir = team_dir.join("board");
1027        let tasks_dir = board_dir.join("tasks");
1028        std::fs::create_dir_all(&tasks_dir).unwrap();
1029        std::fs::write(
1030            team_dir.join("team.yaml"),
1031            "name: test\nworkflow_mode: hybrid\nroles:\n  - name: engineer\n    role_type: engineer\n    agent: codex\n",
1032        )
1033        .unwrap();
1034        std::fs::write(
1035            tasks_dir.join("031-runnable.md"),
1036            "---\nid: 31\ntitle: Runnable\nstatus: todo\npriority: medium\nclass: standard\n---\n\nTask body.\n",
1037        )
1038        .unwrap();
1039
1040        let members = vec![make_member("eng-1-1", "engineer", RoleType::Engineer)];
1041        let section = status::workflow_metrics_section(tmp.path(), &members).unwrap();
1042
1043        assert!(section.0.contains("Workflow Metrics"));
1044        assert_eq!(section.1.runnable_count, 1);
1045        assert_eq!(section.1.idle_with_runnable, vec!["eng-1-1"]);
1046    }
1047
1048    #[test]
1049    #[serial]
1050    #[cfg_attr(not(feature = "integration"), ignore)]
1051    fn list_runtime_member_statuses_reads_tmux_role_and_status_options() {
1052        let session = "batty-test-team-status-runtime";
1053        let _ = crate::tmux::kill_session(session);
1054
1055        crate::tmux::create_session(session, "sleep", &["20".to_string()], "/tmp").unwrap();
1056        let pane_id = crate::tmux::pane_id(session).unwrap();
1057
1058        let role_output = std::process::Command::new("tmux")
1059            .args(["set-option", "-p", "-t", &pane_id, "@batty_role", "eng-1"])
1060            .output()
1061            .unwrap();
1062        assert!(role_output.status.success());
1063
1064        let status_output = std::process::Command::new("tmux")
1065            .args([
1066                "set-option",
1067                "-p",
1068                "-t",
1069                &pane_id,
1070                "@batty_status",
1071                "#[fg=yellow]idle#[default] #[fg=magenta]nudge 0:30#[default]",
1072            ])
1073            .output()
1074            .unwrap();
1075        assert!(status_output.status.success());
1076
1077        let statuses = status::list_runtime_member_statuses(session).unwrap();
1078        let eng = statuses.get("eng-1").unwrap();
1079        assert_eq!(eng.state, "idle");
1080        assert_eq!(eng.signal.as_deref(), Some("waiting for nudge"));
1081        assert_eq!(eng.label.as_deref(), Some("idle nudge 0:30"));
1082
1083        crate::tmux::kill_session(session).unwrap();
1084    }
1085
1086    // --- Session summary tests ---
1087
1088    #[test]
1089    fn session_summary_counts_completions_correctly() {
1090        let tmp = tempfile::tempdir().unwrap();
1091        let events_dir = tmp.path().join(".batty").join("team_config");
1092        std::fs::create_dir_all(&events_dir).unwrap();
1093
1094        let now = crate::team::now_unix();
1095        let events = [
1096            format!(r#"{{"event":"daemon_started","ts":{}}}"#, now - 3600),
1097            format!(
1098                r#"{{"event":"task_completed","role":"eng-1","task":"10","ts":{}}}"#,
1099                now - 3000
1100            ),
1101            format!(
1102                r#"{{"event":"task_completed","role":"eng-2","task":"11","ts":{}}}"#,
1103                now - 2000
1104            ),
1105            format!(
1106                r#"{{"event":"task_auto_merged","role":"eng-1","task":"10","ts":{}}}"#,
1107                now - 2900
1108            ),
1109            format!(
1110                r#"{{"event":"task_manual_merged","role":"eng-2","task":"11","ts":{}}}"#,
1111                now - 1900
1112            ),
1113            format!(
1114                r#"{{"event":"task_completed","role":"eng-1","task":"12","ts":{}}}"#,
1115                now - 1000
1116            ),
1117        ];
1118        std::fs::write(events_dir.join("events.jsonl"), events.join("\n")).unwrap();
1119
1120        let summary = compute_session_summary(tmp.path()).unwrap();
1121        assert_eq!(summary.tasks_completed, 3);
1122        assert_eq!(summary.tasks_merged, 2);
1123        assert!(summary.runtime_secs >= 3599 && summary.runtime_secs <= 3601);
1124    }
1125
1126    #[test]
1127    fn session_summary_calculates_runtime() {
1128        let tmp = tempfile::tempdir().unwrap();
1129        let events_dir = tmp.path().join(".batty").join("team_config");
1130        std::fs::create_dir_all(&events_dir).unwrap();
1131
1132        let now = crate::team::now_unix();
1133        let events = [format!(
1134            r#"{{"event":"daemon_started","ts":{}}}"#,
1135            now - 7200
1136        )];
1137        std::fs::write(events_dir.join("events.jsonl"), events.join("\n")).unwrap();
1138
1139        let summary = compute_session_summary(tmp.path()).unwrap();
1140        assert_eq!(summary.tasks_completed, 0);
1141        assert_eq!(summary.tasks_merged, 0);
1142        assert!(summary.runtime_secs >= 7199 && summary.runtime_secs <= 7201);
1143    }
1144
1145    #[test]
1146    fn session_summary_handles_empty_session() {
1147        let tmp = tempfile::tempdir().unwrap();
1148        let events_dir = tmp.path().join(".batty").join("team_config");
1149        std::fs::create_dir_all(&events_dir).unwrap();
1150
1151        // No daemon_started event — summary returns None.
1152        std::fs::write(events_dir.join("events.jsonl"), "").unwrap();
1153        assert!(compute_session_summary(tmp.path()).is_none());
1154    }
1155
1156    #[test]
1157    fn session_summary_handles_missing_events_file() {
1158        let tmp = tempfile::tempdir().unwrap();
1159        // No events.jsonl at all.
1160        assert!(compute_session_summary(tmp.path()).is_none());
1161    }
1162
1163    #[test]
1164    fn session_summary_display_format() {
1165        let summary = SessionSummary {
1166            tasks_completed: 5,
1167            tasks_merged: 4,
1168            runtime_secs: 8100, // 2h 15m
1169        };
1170        assert_eq!(
1171            summary.display(),
1172            "Session summary: 5 tasks completed, 4 merged, runtime 2h 15m"
1173        );
1174    }
1175
1176    #[test]
1177    fn format_runtime_seconds() {
1178        assert_eq!(format_runtime(45), "45s");
1179    }
1180
1181    #[test]
1182    fn format_runtime_minutes() {
1183        assert_eq!(format_runtime(300), "5m");
1184    }
1185
1186    #[test]
1187    fn format_runtime_hours_and_minutes() {
1188        assert_eq!(format_runtime(5400), "1h 30m");
1189    }
1190
1191    #[test]
1192    fn format_runtime_exact_hours() {
1193        assert_eq!(format_runtime(7200), "2h");
1194    }
1195
1196    #[test]
1197    fn session_summary_uses_latest_daemon_started() {
1198        let tmp = tempfile::tempdir().unwrap();
1199        let events_dir = tmp.path().join(".batty").join("team_config");
1200        std::fs::create_dir_all(&events_dir).unwrap();
1201
1202        let now = crate::team::now_unix();
1203        // First session had 2 completions, second session has 1.
1204        let events = [
1205            format!(r#"{{"event":"daemon_started","ts":{}}}"#, now - 7200),
1206            format!(
1207                r#"{{"event":"task_completed","role":"eng-1","task":"1","ts":{}}}"#,
1208                now - 6000
1209            ),
1210            format!(
1211                r#"{{"event":"task_completed","role":"eng-1","task":"2","ts":{}}}"#,
1212                now - 5000
1213            ),
1214            format!(r#"{{"event":"daemon_started","ts":{}}}"#, now - 1800),
1215            format!(
1216                r#"{{"event":"task_completed","role":"eng-1","task":"3","ts":{}}}"#,
1217                now - 1000
1218            ),
1219        ];
1220        std::fs::write(events_dir.join("events.jsonl"), events.join("\n")).unwrap();
1221
1222        let summary = compute_session_summary(tmp.path()).unwrap();
1223        // Should only count events from the latest daemon_started.
1224        assert_eq!(summary.tasks_completed, 1);
1225        assert!(summary.runtime_secs >= 1799 && summary.runtime_secs <= 1801);
1226    }
1227
1228    /// Count unwrap()/expect() calls in production code (before `#[cfg(test)] mod tests`).
1229    fn production_unwrap_expect_count(source: &str) -> usize {
1230        // Split at the test module boundary, not individual #[cfg(test)] items
1231        let prod = if let Some(pos) = source.find("\n#[cfg(test)]\nmod tests") {
1232            &source[..pos]
1233        } else {
1234            source
1235        };
1236        prod.lines()
1237            .filter(|line| {
1238                let trimmed = line.trim();
1239                // Skip lines that are themselves cfg(test)-gated items
1240                !trimmed.starts_with("#[cfg(test)]")
1241                    && (trimmed.contains(".unwrap(") || trimmed.contains(".expect("))
1242            })
1243            .count()
1244    }
1245
1246    #[test]
1247    fn production_daemon_mgmt_has_limited_unwrap_or_expect_calls() {
1248        let src = include_str!("daemon_mgmt.rs");
1249        // spawn_daemon uses unwrap_or_else for canonicalize — this is acceptable
1250        assert!(
1251            production_unwrap_expect_count(src) <= 1,
1252            "daemon_mgmt.rs should minimize unwrap/expect in production code"
1253        );
1254    }
1255
1256    #[test]
1257    fn production_session_has_no_unwrap_or_expect_calls() {
1258        let src = include_str!("session.rs");
1259        assert_eq!(
1260            production_unwrap_expect_count(src),
1261            0,
1262            "session.rs should avoid unwrap/expect"
1263        );
1264    }
1265}