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//! Heartbeat monitor โ detects unresponsive agents for 24/7 autonomous operation.
//!
//! The heartbeat monitor runs as a background tokio task, periodically checking
//! each running agent's `last_active` timestamp. If an agent hasn't been active
//! for longer than 2x its heartbeat interval, a `HealthCheckFailed` event is
//! published to the event bus.
use crate::registry::AgentRegistry;
use chrono::Utc;
use openfang_types::agent::{AgentId, AgentState};
use tracing::{debug, warn};
/// Default heartbeat check interval (seconds).
const DEFAULT_CHECK_INTERVAL_SECS: u64 = 30;
/// Multiplier: agent is considered unresponsive if inactive for this many
/// multiples of its heartbeat interval.
const UNRESPONSIVE_MULTIPLIER: u64 = 2;
/// Result of a heartbeat check.
#[derive(Debug, Clone)]
pub struct HeartbeatStatus {
/// Agent ID.
pub agent_id: AgentId,
/// Agent name.
pub name: String,
/// Seconds since last activity.
pub inactive_secs: i64,
/// Whether the agent is considered unresponsive.
pub unresponsive: bool,
}
/// Heartbeat monitor configuration.
#[derive(Debug, Clone)]
pub struct HeartbeatConfig {
/// How often to run the heartbeat check (seconds).
pub check_interval_secs: u64,
/// Default threshold for unresponsiveness (seconds).
/// Overridden per-agent by AutonomousConfig.heartbeat_interval_secs.
pub default_timeout_secs: u64,
}
impl Default for HeartbeatConfig {
fn default() -> Self {
Self {
check_interval_secs: DEFAULT_CHECK_INTERVAL_SECS,
default_timeout_secs: DEFAULT_CHECK_INTERVAL_SECS * UNRESPONSIVE_MULTIPLIER,
}
}
}
/// Check all running agents and return their heartbeat status.
///
/// This is a pure function โ it doesn't start a background task.
/// The caller (kernel) can run this periodically or in a background task.
pub fn check_agents(registry: &AgentRegistry, config: &HeartbeatConfig) -> Vec<HeartbeatStatus> {
let now = Utc::now();
let mut statuses = Vec::new();
for entry_ref in registry.list() {
// Only check running agents
if entry_ref.state != AgentState::Running {
continue;
}
let inactive_secs = (now - entry_ref.last_active).num_seconds();
// Determine timeout: use agent's autonomous config if set, else default
let timeout_secs = entry_ref
.manifest
.autonomous
.as_ref()
.map(|a| a.heartbeat_interval_secs * UNRESPONSIVE_MULTIPLIER)
.unwrap_or(config.default_timeout_secs) as i64;
let unresponsive = inactive_secs > timeout_secs;
if unresponsive {
warn!(
agent = %entry_ref.name,
inactive_secs,
timeout_secs,
"Agent is unresponsive"
);
} else {
debug!(
agent = %entry_ref.name,
inactive_secs,
"Agent heartbeat OK"
);
}
statuses.push(HeartbeatStatus {
agent_id: entry_ref.id,
name: entry_ref.name.clone(),
inactive_secs,
unresponsive,
});
}
statuses
}
/// Check if an agent is currently within its quiet hours.
///
/// Quiet hours format: "HH:MM-HH:MM" (24-hour format, UTC).
/// Returns true if the current time falls within the quiet period.
pub fn is_quiet_hours(quiet_hours: &str) -> bool {
let parts: Vec<&str> = quiet_hours.split('-').collect();
if parts.len() != 2 {
return false;
}
let now = Utc::now();
let current_minutes = now.format("%H").to_string().parse::<u32>().unwrap_or(0) * 60
+ now.format("%M").to_string().parse::<u32>().unwrap_or(0);
let parse_time = |s: &str| -> Option<u32> {
let hm: Vec<&str> = s.trim().split(':').collect();
if hm.len() != 2 {
return None;
}
let h = hm[0].parse::<u32>().ok()?;
let m = hm[1].parse::<u32>().ok()?;
if h > 23 || m > 59 {
return None;
}
Some(h * 60 + m)
};
let start = match parse_time(parts[0]) {
Some(v) => v,
None => return false,
};
let end = match parse_time(parts[1]) {
Some(v) => v,
None => return false,
};
if start <= end {
// Same-day range: e.g., 22:00-06:00 would be cross-midnight
// This is start <= current < end
current_minutes >= start && current_minutes < end
} else {
// Cross-midnight: e.g., 22:00-06:00
current_minutes >= start || current_minutes < end
}
}
/// Aggregate heartbeat summary.
#[derive(Debug, Clone, Default)]
pub struct HeartbeatSummary {
/// Total agents checked.
pub total_checked: usize,
/// Number of responsive agents.
pub responsive: usize,
/// Number of unresponsive agents.
pub unresponsive: usize,
/// Details of unresponsive agents.
pub unresponsive_agents: Vec<HeartbeatStatus>,
}
/// Produce a summary from heartbeat statuses.
pub fn summarize(statuses: &[HeartbeatStatus]) -> HeartbeatSummary {
let unresponsive_agents: Vec<HeartbeatStatus> = statuses
.iter()
.filter(|s| s.unresponsive)
.cloned()
.collect();
HeartbeatSummary {
total_checked: statuses.len(),
responsive: statuses.len() - unresponsive_agents.len(),
unresponsive: unresponsive_agents.len(),
unresponsive_agents,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_quiet_hours_parsing() {
// We can't easily test time-dependent logic, but we can test format parsing
assert!(!is_quiet_hours("invalid"));
assert!(!is_quiet_hours(""));
assert!(!is_quiet_hours("25:00-06:00")); // Invalid hours handled gracefully
}
#[test]
fn test_quiet_hours_format_valid() {
// The function returns true/false based on current time
// We just verify it doesn't panic on valid input
let _ = is_quiet_hours("22:00-06:00");
let _ = is_quiet_hours("00:00-23:59");
let _ = is_quiet_hours("09:00-17:00");
}
#[test]
fn test_heartbeat_config_default() {
let config = HeartbeatConfig::default();
assert_eq!(config.check_interval_secs, 30);
assert_eq!(config.default_timeout_secs, 60);
}
#[test]
fn test_summarize_empty() {
let summary = summarize(&[]);
assert_eq!(summary.total_checked, 0);
assert_eq!(summary.responsive, 0);
assert_eq!(summary.unresponsive, 0);
}
#[test]
fn test_summarize_mixed() {
let statuses = vec![
HeartbeatStatus {
agent_id: AgentId::new(),
name: "agent-1".to_string(),
inactive_secs: 10,
unresponsive: false,
},
HeartbeatStatus {
agent_id: AgentId::new(),
name: "agent-2".to_string(),
inactive_secs: 120,
unresponsive: true,
},
HeartbeatStatus {
agent_id: AgentId::new(),
name: "agent-3".to_string(),
inactive_secs: 5,
unresponsive: false,
},
];
let summary = summarize(&statuses);
assert_eq!(summary.total_checked, 3);
assert_eq!(summary.responsive, 2);
assert_eq!(summary.unresponsive, 1);
assert_eq!(summary.unresponsive_agents.len(), 1);
assert_eq!(summary.unresponsive_agents[0].name, "agent-2");
}
}