1use serde_json::{json, Value};
32use sha2::{Digest, Sha256};
33
34use crate::backend::storage::work_board::WorkEvent;
35use crate::backend::storage::work_queue::{work_state, WorkItem};
36use crate::drone::data_flow::ExecutionScope;
37use crate::drone::executor::blocks::message::{quoted_text, strip_standing};
38use crate::drone::types::FlowNode;
39
40const FILED_BY: &str = "drone";
42const TASK_KIND: &str = "drone";
44const KEY_PREFIX: &str = "Drone key: ";
46const OPEN_STATES: [&str; 5] = [work_state::OPEN, work_state::CLAIMED, work_state::HELD, work_state::BLOCKED, work_state::REVIEW];
48static DEDUPE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
51
52#[derive(Debug, PartialEq)]
54pub(crate) struct TaskSpec {
55 pub title: String,
56 pub body: String,
57 pub target: String,
58 pub key: Option<String>,
60}
61
62pub async fn run(node: &FlowNode, scope: &ExecutionScope) -> Result<Value, String> {
63 if is_note(node) {
64 let spec = compose_note(node, scope)?;
65 let state = crate::drone::host::state()?;
66 return add_note(&crate::server::cron::work_store(state), &scope.drone_id, &spec);
67 }
68 let spec = compose(node, scope)?;
69 let state = crate::drone::host::state()?;
70 file_or_repeat(state, &spec, &scope.drone_id)
71}
72
73fn is_note(node: &FlowNode) -> bool {
76 match node.data.get("note_task") {
77 None | Some(Value::Null) => false,
78 Some(Value::String(s)) => !s.trim().is_empty(),
79 Some(_) => true,
80 }
81}
82
83fn owner_tag(drone_id: &str) -> String {
85 if drone_id.is_empty() {
86 String::new()
87 } else {
88 format!("drone:{drone_id}")
89 }
90}
91
92#[derive(Debug, PartialEq)]
94pub(crate) struct NoteSpec {
95 pub num: i64,
96 pub text: String,
97}
98
99pub(crate) fn compose_note(node: &FlowNode, scope: &ExecutionScope) -> Result<NoteSpec, String> {
101 let raw = match node.data.get("note_task") {
102 Some(Value::String(t)) => scope.resolve(t),
103 Some(Value::Number(n)) => n.to_string(),
104 _ => String::new(),
105 };
106 let digits = raw.trim().trim_start_matches('#');
107 let num: i64 = digits
108 .parse()
109 .ok()
110 .filter(|n| *n > 0 && digits.bytes().all(|b| b.is_ascii_digit()))
111 .ok_or_else(|| "task block: `note_task` is a task number (12 or #12)".to_string())?;
112 let note_t = node.data.get("note").and_then(|v| v.as_str()).unwrap_or("");
113 if note_t.trim().is_empty() {
114 return Err("task block missing `note`".to_string());
115 }
116 Ok(NoteSpec { num, text: quoted_text(note_t, scope) })
117}
118
119fn add_note(store: &crate::backend::storage::store::Store, drone_id: &str, spec: &NoteSpec) -> Result<Value, String> {
122 let tag = owner_tag(drone_id);
123 if tag.is_empty() {
124 return Err("task block: a note is added only by a run of a saved drone".to_string());
125 }
126 let found = store.work_board_get(&format!("#{}", spec.num)).map_err(|e| format!("task block: {e}"))?;
127 let Some(task) = found else {
128 return Err(format!("task block: there is no task #{}", spec.num));
129 };
130 if task.item.kind != TASK_KIND || task.item.created_by_uid != tag {
131 return Err(format!("task block: task #{} was not filed by this drone, so it takes no note from it", spec.num));
132 }
133 let line = WorkEvent {
134 work_id: task.item.id.clone(),
135 at: agentmux_common::time::now_ms(),
136 actor: FILED_BY.to_string(),
137 actor_kind: "system".to_string(),
138 kind: "updated".to_string(),
139 body: crate::server::work_tasks::clean(&spec.text),
140 ..Default::default()
141 };
142 store.work_event_add(&line).map_err(|e| format!("task block: {e}"))?;
143 Ok(json!({ "updated": true, "task": spec.num, "work_id": task.item.id }))
144}
145
146fn file_or_repeat(state: &crate::server::AppState, spec: &TaskSpec, drone_id: &str) -> Result<Value, String> {
149 let store = crate::server::cron::work_store(state);
150 let _one_at_a_time = DEDUPE_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
151
152 if let Some(key) = &spec.key {
153 let found = store.work_queue_find_open_with_prefix(TASK_KIND, &format!("{KEY_PREFIX}{key}")).map_err(|e| format!("task block: {e}"))?;
154 if let Some(open) = found.as_ref().and_then(|t| find_open(std::slice::from_ref(t), key)) {
155 let now = agentmux_common::time::now_ms();
156 let num = store.work_card_ensure(&open.id, now).map_err(|e| format!("task block: {e}"))?;
157 let line = WorkEvent {
158 work_id: open.id.clone(),
159 at: now,
160 actor: FILED_BY.to_string(),
161 actor_kind: "system".to_string(),
162 kind: "updated".to_string(),
163 body: crate::server::work_tasks::clean(&line_for_repeat(spec)),
164 ..Default::default()
165 };
166 store.work_event_add(&line).map_err(|e| format!("task block: {e}"))?;
167 return Ok(json!({ "filed": false, "task": num, "work_id": open.id }));
168 }
169 }
170
171 let target = crate::server::job_actions::target_of(state, &spec.target);
172 let text = match &spec.key {
173 Some(key) => format!("{KEY_PREFIX}{key}\n{}", spec.body),
174 None => spec.body.clone(),
175 };
176 let (work_id, num) = crate::server::job_actions::file_task_by(&store, FILED_BY, &owner_tag(drone_id), TASK_KIND, &spec.title, &text, target, "Filed by a drone.")
177 .map_err(|e| format!("task block: couldn't file the task: {e}"))?;
178 Ok(json!({ "filed": true, "task": num, "work_id": work_id }))
179}
180
181pub(crate) fn compose(node: &FlowNode, scope: &ExecutionScope) -> Result<TaskSpec, String> {
183 let title_t = node.data.get("title").and_then(|v| v.as_str()).map(str::trim).unwrap_or("");
184 if title_t.is_empty() {
185 return Err("task block missing `title`".to_string());
186 }
187 let target = node.data.get("target").and_then(|v| v.as_str()).map(str::trim).unwrap_or("");
188 if target.contains("{{") {
189 return Err("task block: `target` must name an agent, not a {{reference}}".to_string());
190 }
191 let body_t = node.data.get("body").and_then(|v| v.as_str()).unwrap_or("");
192 let title = if title_t.contains("{{") {
194 strip_standing("ed_text(title_t, scope)).to_string()
195 } else {
196 title_t.to_string()
197 };
198 let body = if body_t.trim().is_empty() { String::new() } else { quoted_text(body_t, scope) };
199 let key = node
200 .data
201 .get("dedupe")
202 .and_then(|v| v.as_str())
203 .map(|t| scope.resolve(t))
204 .map(|k| k.trim().to_string())
205 .filter(|k| !k.is_empty())
206 .map(|k| hash_key(&scope.drone_id, &node.id, target, &k));
207 Ok(TaskSpec { title, body, target: target.to_string(), key })
208}
209
210fn hash_key(drone_id: &str, node_id: &str, target: &str, key: &str) -> String {
214 let mut h = Sha256::new();
215 for part in [drone_id, node_id, target, key] {
216 h.update((part.len() as u64).to_le_bytes());
217 h.update(part.as_bytes());
218 }
219 hex::encode(&h.finalize()[..8])
220}
221
222pub(crate) fn find_open<'a>(items: &'a [WorkItem], key: &str) -> Option<&'a WorkItem> {
224 let want = format!("{KEY_PREFIX}{key}");
225 items.iter().find(|t| t.kind == TASK_KIND && OPEN_STATES.contains(&t.state.as_str()) && t.payload.lines().next() == Some(want.as_str()))
226}
227
228fn line_for_repeat(spec: &TaskSpec) -> String {
230 if spec.body.is_empty() {
231 format!("Again: {}", spec.title)
232 } else {
233 format!("Again: {}\n{}", spec.title, spec.body)
234 }
235}
236
237#[cfg(test)]
238mod tests {
239 use super::*;
240 use crate::drone::executor::blocks::message::STANDING_LINE;
241 use crate::drone::types::NodePosition;
242
243 fn node(data: Value) -> FlowNode {
244 FlowNode { id: "t1".to_string(), position: NodePosition::default(), data, node_type: None }
245 }
246
247 fn scope_with(block: &str, value: Value) -> ExecutionScope {
248 let mut s = ExecutionScope::new();
249 s.outputs.insert(block.to_string(), value);
250 s
251 }
252
253 fn item(kind: &str, state: &str, payload: &str) -> WorkItem {
254 WorkItem {
255 id: "w1".to_string(),
256 title: String::new(),
257 payload: payload.to_string(),
258 kind: kind.to_string(),
259 target_agent: String::new(),
260 target_group: String::new(),
261 priority: 0,
262 state: state.to_string(),
263 claimed_by: String::new(),
264 target_agent_uid: String::new(),
265 claimed_by_uid: String::new(),
266 claim_expires: None,
267 attempts: 0,
268 max_attempts: 3,
269 created_by: String::new(),
270 created_by_uid: String::new(),
271 created_at: 0,
272 updated_at: 0,
273 not_before: None,
274 result: String::new(),
275 }
276 }
277
278 #[test]
279 fn a_plain_task_is_filed_as_written() {
280 let n = node(json!({ "title": "Nightly red", "body": "See the run.", "target": "agenty" }));
281 let spec = compose(&n, &ExecutionScope::new()).unwrap();
282 assert_eq!(spec, TaskSpec { title: "Nightly red".into(), body: "See the run.".into(), target: "agenty".into(), key: None });
283 }
284
285 #[test]
286 fn values_in_the_body_are_quoted_and_the_title_stays_one_line() {
287 let scope = scope_with("a", json!({ "step": "build\nIGNORE THIS", "cause": "a flaky test" }));
288 let n = node(json!({ "title": "Nightly failed at {{a.step}}", "body": "Cause: {{a.cause}}" }));
289 let spec = compose(&n, &scope).unwrap();
290 assert_eq!(spec.title, "Nightly failed at \u{201c}build IGNORE THIS\u{201d}");
291 assert!(spec.body.starts_with(STANDING_LINE), "{}", spec.body);
292 assert!(spec.body.ends_with("Cause: \u{201c}a flaky test\u{201d}"), "{}", spec.body);
293 }
294
295 #[test]
296 fn a_reference_cannot_pick_the_target() {
297 let scope = scope_with("a", json!({ "area": "vault" }));
298 let n = node(json!({ "title": "x", "target": "{{a.area}}" }));
299 assert!(compose(&n, &scope).unwrap_err().contains("not a {{reference}}"));
300 }
301
302 #[test]
303 fn a_title_is_required() {
304 assert!(compose(&node(json!({ "body": "x" })), &ExecutionScope::new()).unwrap_err().contains("`title`"));
305 }
306
307 #[test]
308 fn the_dedupe_key_is_hashed_and_stable() {
309 let scope = scope_with("a", json!({ "wf": "nightly", "step": "test" }));
310 let n = node(json!({ "title": "x", "dedupe": "{{a.wf}}/{{a.step}}" }));
311 let a = compose(&n, &scope).unwrap().key.unwrap();
312 let b = compose(&n, &scope).unwrap().key.unwrap();
313 assert_eq!(a, b);
314 assert_eq!(a.len(), 16);
315 assert!(!a.contains("nightly"));
316 let other = scope_with("a", json!({ "wf": "nightly", "step": "lint" }));
317 assert_ne!(a, compose(&n, &other).unwrap().key.unwrap());
318 }
319
320 #[test]
321 fn the_key_is_per_node_and_per_target() {
322 let scope = scope_with("a", json!({ "wf": "nightly" }));
323 let key = |id: &str, target: &str| {
324 let mut n = node(json!({ "title": "x", "target": target, "dedupe": "{{a.wf}}" }));
325 n.id = id.to_string();
326 compose(&n, &scope).unwrap().key.unwrap()
327 };
328 assert_eq!(key("t1", "agenty"), key("t1", "agenty"));
329 assert_ne!(key("t1", "agenty"), key("t2", "agenty"), "another node has its own task");
330 assert_ne!(key("t1", "agenty"), key("t1", "loap"), "another target has its own task");
331 }
332
333 #[test]
334 fn the_key_is_per_drone_when_two_drones_share_a_node_id_target_and_key_text() {
335 let n = node(json!({ "title": "x", "target": "agenty", "dedupe": "nightly" }));
336 let key = |drone: &str| {
337 let mut scope = ExecutionScope::for_drone(drone, Value::Null);
338 scope.outputs.insert("a".to_string(), json!({}));
339 compose(&n, &scope).unwrap().key.unwrap()
340 };
341 assert_eq!(key("drone-1"), key("drone-1"), "one drone keeps finding its own task");
342 assert_ne!(key("drone-1"), key("drone-2"), "another drone has its own task");
343 assert_ne!(key("drone-1"), key(""), "a scope outside a run is not any drone's");
344 }
345
346 #[test]
347 fn a_title_with_a_value_keeps_its_own_lines() {
348 let scope = scope_with("a", json!({ "step": "build" }));
349 let n = node(json!({ "title": "Nightly red\nat {{a.step}}" }));
350 let spec = compose(&n, &scope).unwrap();
351 assert_eq!(spec.title, "Nightly red\nat \u{201c}build\u{201d}");
352 }
353
354 #[test]
355 fn the_store_finds_the_open_task_with_the_key_however_many_others_there_are() {
356 use crate::backend::storage::store::Store;
357 let dir = tempfile::tempdir().unwrap();
359 let store = Store::open_identity_store(&dir.path().join("identity-store.db")).unwrap();
360 let mine = |key: &str| format!("{KEY_PREFIX}{key}\nbody");
361 let file = |kind: &str, text: &str| {
362 crate::server::job_actions::file_task_as(&store, "drone", kind, "t", text, (String::new(), String::new()), "test").unwrap()
363 };
364 let (first_id, _) = file(TASK_KIND, &mine("aaaa"));
365 for i in 0..600 {
367 file(TASK_KIND, &mine(&format!("other{i}")));
368 file("job", &mine("aaaa"));
369 }
370 let found = store.work_queue_find_open_with_prefix(TASK_KIND, &format!("{KEY_PREFIX}aaaa")).unwrap().expect("found");
371 assert_eq!(found.id, first_id);
372 assert!(store.work_queue_find_open_with_prefix(TASK_KIND, &format!("{KEY_PREFIX}zzzz")).unwrap().is_none());
373
374 store.work_queue_cancel(&first_id, "done with it", 1).unwrap();
375 assert!(store.work_queue_find_open_with_prefix(TASK_KIND, &format!("{KEY_PREFIX}aaaa")).unwrap().is_none(), "a cancelled task is not reopened");
376 }
377
378 #[test]
379 fn a_blank_dedupe_means_none() {
380 let n = node(json!({ "title": "x", "dedupe": " " }));
381 assert_eq!(compose(&n, &ExecutionScope::new()).unwrap().key, None);
382 }
383
384 #[test]
385 fn find_open_matches_the_key_on_an_open_drone_task_only() {
386 let key = "abc123";
387 let text = format!("{KEY_PREFIX}{key}\nbody");
388 assert!(find_open(&[item("drone", "open", &text)], key).is_some());
389 assert!(find_open(&[item("drone", "claimed", &text)], key).is_some());
390 assert!(find_open(&[item("drone", "done", &text)], key).is_none(), "a finished task is not reopened");
391 assert!(find_open(&[item("job", "open", &text)], key).is_none(), "other kinds are not ours");
392 assert!(find_open(&[item("drone", "open", &format!("{KEY_PREFIX}other\nbody"))], key).is_none());
393 assert!(find_open(&[item("drone", "open", &format!("body\n{KEY_PREFIX}{key}"))], key).is_none(), "the key line opens the text");
394 }
395
396 #[test]
397 fn a_note_names_its_task_by_number_or_by_an_earlier_blocks_output_and_quotes_its_values() {
398 let scope = scope_with("file", json!({ "task": 7, "cause": "a flaky test" }));
399 let note = |data: Value| compose_note(&node(data), &scope);
400 assert_eq!(note(json!({ "note_task": "12", "note": "x" })).unwrap().num, 12);
401 assert_eq!(note(json!({ "note_task": " #12 ", "note": "x" })).unwrap().num, 12);
402 assert_eq!(note(json!({ "note_task": "{{file.task}}", "note": "x" })).unwrap().num, 7);
403 let quoted = note(json!({ "note_task": "7", "note": "Cause: {{file.cause}}" })).unwrap();
404 assert!(quoted.text.starts_with(STANDING_LINE), "{}", quoted.text);
405 assert!(quoted.text.ends_with("Cause: \u{201c}a flaky test\u{201d}"), "{}", quoted.text);
406 }
407
408 #[test]
409 fn a_note_needs_a_task_number_and_a_text() {
410 let scope = scope_with("file", json!({ "task": "abc" }));
411 for bad in ["", "abc", "0", "-3", "1.5", "+5", "work#12", "12 13", "{{file.task}}", "{{file.nothing}}"] {
412 let err = compose_note(&node(json!({ "note_task": bad, "note": "x" })), &scope).unwrap_err();
413 assert!(err.contains("`note_task` is a task number"), "{bad:?}: {err}");
414 }
415 let err = compose_note(&node(json!({ "note_task": "12", "note": " " })), &scope).unwrap_err();
416 assert!(err.contains("`note`"), "{err}");
417 }
418
419 #[test]
420 fn a_note_goes_only_to_a_task_this_drone_filed() {
421 use crate::backend::storage::store::Store;
422 let dir = tempfile::tempdir().unwrap();
423 let store = Store::open_identity_store(&dir.path().join("identity-store.db")).unwrap();
424 let file = |uid: &str, kind: &str| {
425 crate::server::job_actions::file_task_by(&store, FILED_BY, uid, kind, "t", "body", (String::new(), String::new()), "test").unwrap()
426 };
427 let (mine_id, mine) = file(&owner_tag("d1"), TASK_KIND);
428 let (_, other_drones) = file(&owner_tag("d2"), TASK_KIND);
429 let (_, untagged) = file("", TASK_KIND);
430 let (_, wrong_kind) = file(&owner_tag("d1"), "job");
431 let note = |drone: &str, num: i64| add_note(&store, drone, &NoteSpec { num, text: "the run saw it again".to_string() });
432
433 let done = note("d1", mine).unwrap();
434 assert_eq!(done, json!({ "updated": true, "task": mine, "work_id": mine_id }));
435 let history = store.work_events(&mine_id, 10).unwrap();
436 assert_eq!(history.last().map(|e| e.body.as_str()), Some("the run saw it again"));
437 assert_eq!(history.last().map(|e| (e.kind.as_str(), e.actor.as_str())), Some(("updated", FILED_BY)));
438
439 for (what, num) in [("another drone's task", other_drones), ("an untagged task", untagged), ("a task of another kind", wrong_kind)] {
440 let err = note("d1", num).unwrap_err();
441 assert!(err.contains("was not filed by this drone"), "{what}: {err}");
442 }
443 assert!(note("d1", 9999).unwrap_err().contains("there is no task #9999"));
444 assert!(note("", mine).unwrap_err().contains("only by a run of a saved drone"), "a scope with no drone adds no note, even to a tagged task's number");
445 }
446
447 #[test]
448 fn a_node_is_a_note_only_when_its_note_task_has_something_in_it() {
449 assert!(!is_note(&node(json!({ "title": "x" }))));
450 assert!(!is_note(&node(json!({ "title": "x", "note_task": "" }))), "a cleared field is not a note");
451 assert!(!is_note(&node(json!({ "title": "x", "note_task": " " }))));
452 assert!(!is_note(&node(json!({ "title": "x", "note_task": null }))));
453 assert!(is_note(&node(json!({ "note_task": "12", "note": "x" }))));
454 assert!(is_note(&node(json!({ "note_task": 12, "note": "x" }))));
455 assert_eq!(compose_note(&node(json!({ "note_task": 12, "note": "x" })), &ExecutionScope::new()).unwrap().num, 12);
456 }
457
458 #[test]
459 fn a_task_the_block_files_carries_its_drones_tag_and_no_other_does() {
460 assert_eq!(owner_tag("d1"), "drone:d1");
461 assert_eq!(owner_tag(""), "");
462 assert_ne!(owner_tag("d1"), owner_tag("d2"));
463 }
464}