agentmux_srv/server/prep/
decide.rs1use crate::backend::agent_state::AgentState;
8use crate::server::AppState;
9
10use super::Prep;
11
12#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum Decision {
15 Ask,
16 Skip(&'static str),
18}
19
20struct Inputs {
22 states: Vec<Option<AgentState>>,
24 api_offline: bool,
26 lost: Option<&'static str>,
28}
29
30fn can_take_a_turn(s: Option<AgentState>) -> bool {
31 matches!(s, Some(AgentState::Working | AgentState::Waiting | AgentState::Idle))
32}
33
34fn in_a_turn(s: Option<AgentState>) -> bool {
35 matches!(s, Some(AgentState::Working | AgentState::Waiting))
36}
37
38fn decide_from(i: &Inputs) -> Decision {
39 if !i.states.iter().any(|s| can_take_a_turn(*s)) {
40 return Decision::Skip("cannot_take_a_turn");
42 }
43 if i.api_offline {
44 return Decision::Skip("api_offline");
45 }
46 if i.states.iter().any(|s| in_a_turn(*s)) || i.lost.is_some() {
47 return Decision::Ask;
48 }
49 Decision::Skip("nothing_to_lose")
50}
51
52fn lost_of(state: &AppState, block: &str) -> Option<&'static str> {
55 crate::backend::continuity_facts::something_to_lose(&state.mstore, Some(&state.work_store), block)
56}
57
58pub fn decide(state: &AppState, prep: &Prep) -> Decision {
60 let states: Vec<Option<AgentState>> = prep.blocks.iter().map(|b| crate::backend::agent_state::current_state(&state.mstore, b)).collect();
61 let Some(asked) = prep.blocks.iter().zip(&states).find(|(_, s)| can_take_a_turn(**s)).map(|(b, _)| b) else {
62 return decide_from(&Inputs { states, api_offline: false, lost: None });
63 };
64 let api_offline = crate::server::jekt_hold::api_is_offline_for(&state.mstore, asked, &crate::connectivity::status(), agentmux_common::time::now_ms_u64());
65 let lost = lost_of(state, asked);
66 let decision = decide_from(&Inputs { states, api_offline, lost });
67 tracing::debug!(agent = %prep.agent_name, ?decision, lost = ?lost, "prep: decided");
68 decision
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74
75 fn inputs(states: &[Option<AgentState>], api_offline: bool, lost: Option<&'static str>) -> Inputs {
76 Inputs { states: states.to_vec(), api_offline, lost }
77 }
78
79 #[test]
80 fn an_agent_in_a_turn_is_asked() {
81 for s in [AgentState::Working, AgentState::Waiting] {
82 assert_eq!(decide_from(&inputs(&[Some(s)], false, None)), Decision::Ask, "{s:?}");
83 }
84 }
85
86 #[test]
87 fn an_idle_agent_is_asked_only_when_it_holds_something() {
88 assert_eq!(decide_from(&inputs(&[Some(AgentState::Idle)], false, Some("holds a claimed task"))), Decision::Ask);
89 assert_eq!(decide_from(&inputs(&[Some(AgentState::Idle)], false, None)), Decision::Skip("nothing_to_lose"));
90 }
91
92 #[test]
93 fn an_agent_that_cannot_take_a_turn_is_never_asked() {
94 for s in [Some(AgentState::Limited), Some(AgentState::SignedOut), Some(AgentState::Stopped), Some(AgentState::Error), None] {
95 assert_eq!(decide_from(&inputs(&[s], false, Some("holds a claimed task"))), Decision::Skip("cannot_take_a_turn"), "{s:?}");
96 }
97 assert_eq!(decide_from(&inputs(&[], false, Some("x"))), Decision::Skip("cannot_take_a_turn"), "no pane");
98 }
99
100 #[test]
101 fn a_pane_that_can_answer_is_enough_when_another_cannot() {
102 assert_eq!(decide_from(&inputs(&[Some(AgentState::Limited), Some(AgentState::Working)], false, None)), Decision::Ask);
103 }
104
105 #[tokio::test]
106 async fn a_task_claimed_on_the_work_store_counts_when_the_identity_store_holds_none() {
107 use crate::backend::obj::Block;
108 use crate::backend::storage::store::Store;
109 use crate::backend::storage::work_queue::{ClaimFilter, WorkItem};
110 let mut state = crate::server::tests::test_state();
111 let own = Store::open_in_memory().unwrap();
113 own.apply_identity_schema_for_tests().unwrap();
114 state.work_store = std::sync::Arc::new(own);
115 let mut block = Block { oid: uuid::Uuid::new_v4().to_string(), ..Default::default() };
116 block.meta.insert("agentId".into(), serde_json::json!("Held-p47796"));
117 state.mstore.insert(&mut block).unwrap();
118 let item = WorkItem {
119 id: "w-p47796".into(),
120 title: "Hold something".into(),
121 payload: String::new(),
122 kind: String::new(),
123 target_agent: String::new(),
124 target_group: String::new(),
125 priority: 0,
126 state: String::new(),
127 claimed_by: String::new(),
128 target_agent_uid: String::new(),
129 claimed_by_uid: String::new(),
130 claim_expires: None,
131 attempts: 0,
132 max_attempts: 3,
133 created_by: "tester".into(),
134 created_by_uid: String::new(),
135 created_at: 1000,
136 updated_at: 1000,
137 not_before: None,
138 result: String::new(),
139 };
140 state.work_store.work_queue_enqueue(&item).unwrap();
141 let claim = ClaimFilter { kind: None, agent_id: "Held-p47796".into(), agent_uid: String::new(), groups: vec![] };
142 state.work_store.work_queue_claim(&claim, 2000, 600_000).unwrap().expect("the task is claimed");
143 assert_eq!(lost_of(&state, &block.oid), Some("holds a claimed task"));
144 }
145
146 #[test]
147 fn an_offline_api_is_not_asked() {
148 assert_eq!(decide_from(&inputs(&[Some(AgentState::Working)], true, None)), Decision::Skip("api_offline"));
149 }
150}